//window.loadFirebugConsole();

var getJSONFragment = function(json, type) {
	return (typeof json == 'object' && json[type]) ? json[type] : null;
};

var getRandomNumber = function(min, max) {
	return Math.floor(Math.random() * max + min);
};

var makeTemplateLink = function(datas) {
	var tpl = '<a href="' + datas.url + '" target="_top"';
	if (datas.title) {
		tpl += ' title="' + datas.title + '"';
	}
	if (datas.xiti) {
		tpl += ' onclick="xt_med(' + datas.xiti + ');"';
	}
	if (datas.cls) {
		tpl += ' class="' + datas.cls + '"';
	}
	tpl += '>' + datas.content + '</a>';
	return tpl;
};

var makeTemplateImage = function(datas) {
	datas.width = datas.width || 105;
	datas.height = datas.height || 100;
	//var tpl = '<img src="' + datas.src + '" width="' + datas.width + '" height="' + datas.height + '" alt="';
	var tpl = '<img src="' + datas.src + '"  alt="';
	if (datas.alt) {
		tpl += datas.alt;
	}
	tpl += '" />';
	return tpl;
};

var displayExceptionsManager = function(identity) {
	if(identity == "selectGuide") {	
		$("selectAGuide").remove();
	}
	if(identity == "selectTheme") {	
		$("selectATheme").remove();
	}
}


var compileTemplate = function(tplType, datas, tplIdentifier, datasExtra) {
	var tpl, tmpVignette, tmpCountry, tmpCity, tmpCountryCity, tmpDesc, tmpLienFicheDebut, tmpLienFicheFin; 

	if(tplIdentifier == 'carrousselConseilsDest') {
		if(!datas.vignette && !datas.countryname && !datas.cityname && !datas.description){	
			tpl = '';
		} 
		else if(!datas.countryname && !datas.cityname && !datas.vignette){
			tpl = '';
		}		
		else if(!datas.lienfiche){
			tpl = '';
		}		
		else  {
			tmpCountry = datas.countryname;
			if(!datas.countryname){
				tmpCountry ='';
			}
			tmpCity = datas.cityname;
			if(!datas.cityname){
				tmpCity ='';
			}
			tmpCountryCity = '<span class="country">' + tmpCountry + ' - ' + tmpCity + '</span>';		
			if (!datas.countryname) {
				tmpCountryCity = '<span class="country">' + tmpCity + '</span>';
			}
			if (!datas.cityname) {
				tmpCountryCity = '<span class="country">' + tmpCountry + '</span>';
			}
			
			tmpDesc = '<span class="desc">' + datas.description + '</span>';
			if (!datas.description) {
				tmpDesc = '';	
			}
			
			tmpVignette = makeTemplateImage({
							'src': datas.vignette
							});
			if (!datas.vignette) {
				tmpVignette = '';
			}
			
			tmpLienFicheFin = '</a>';

			if (!datas.vignette) {
				tmpLienFicheDebut = '<a class="noImage"  href="' + datas.lienfiche + '">';
			}
			if (datas.vignette) {
				tmpLienFicheDebut = '<a  href="' + datas.lienfiche + '">';
			}
			tpl = '<li>'
			tpl += tmpLienFicheDebut;
			tpl += tmpVignette;
			tpl += tmpCountryCity;
			tpl += tmpDesc;
			tpl += tmpLienFicheFin;
			tpl += '</li>';	
			}
	}
	
	if (tplIdentifier == 'carrousselFormules') {
	
		if (!datas.lienfiche) {
			tpl = '';
		} else if (!datas.name && !datas.vignette) {
			tpl = '';
		} 
		else {
			tmpDesc = datas.name;
			if(!datas.name){
				tmpDesc = '';
			}
			tmpVignette = makeTemplateImage({'src': datas.vignette});
			if(!tmpVignette){
				tmpVignette ='';
			}
			tpl = '<li><a href="' + datas.lienfiche + '">';
			if (datas.vignette) {
				tpl += tmpVignette;
				tpl += '<span class="country">' + tmpDesc + '</span></a></li>';
			} else {
				tpl += '<span class="country noImage2">' + tmpDesc + '</span></a></li>';
			}
			
		}
	}

	if(tplIdentifier == 'selectGuide') {
			if (!datas.lienfiche) {
									tpl = '';
									} else {
									if (!datas.cityname) {
														tpl = '';
														} else {
										tpl = '<option value="' + datas.lienfiche + '">' + datas.cityname + '</option>'; // affichage de la ville par defaut
									}
								}
	}
	
	
	
	if(tplIdentifier == 'selectTheme') {
		if (!datas.lienfiche || !datas.name) {
			tpl = '';
		}
		else {
			tpl = '<option value="' + datas.lienfiche + '">' + datas.name + '</option>';
		}
	}

	if(tplIdentifier == 'carrousselHotelsCoupsDeCoeur') {
	var tmpDestRid, tmpDestHotelname, tmpDestLocalisation, tmpDestDescription, tmpDestVignette, tmpDestLienvisiterStart, tmpDestLienvisiterEnd, tmpDestLienlocaliser,tmpDestLienreserver;
	
	tmpDestLienvisiterStart = '<a href="'+datas.lienvisiter+'">';
	tmpDestLienvisiterEnd = '</a>';
	if(!datas.lienvisiter) {
		tmpDestLienvisiterStart = '';
		tmpDestLienvisiterEnd = '';
	}
	
	tmpDestVignette = '<img src="'+datas.vignette+'" alt="" />';
	if(!datas.vignette) {
		tmpDestVignette = '';
	}
	
	tmpDestHotelname = '<span class="hotelName">'+datas.hotelname+'</span>';
	if(!datas.hotelname) {
		tmpDestHotelname = '';
	}
	
	tmpDestLocalisation = '<span class="HotelPlace">'+datas.localisation+'</span>';
	if(!datas.localisation){
		tmpDestLocalisation = '';
	}
	
	tmpDestDescription = '<span class="description">'+datas.description+'</span>';
	if(!datas.description) {
		tmpDestDescription = '';
	}
	var sLeft = (screen.availWidth-780)/2;
	var sTop = (screen.availHeight-780)/2;
	tmpDestLienlocaliser = '<ul><li><a href="'+datas.lienlocaliser+'" onclick="javascript:window.open(this.href,\'localiser\',\'menubar=no,location=no,resizable=yes,scrollbars=no,status=no,width=780,height=780,top='+sTop+'left='+sLeft+'\'); return false">'+datas.libellelocaliser+'</a></li></ul>';	
	if(!datas.lienlocaliser) {
		tmpDestLienlocaliser = '';
	}
	
	tmpDestLienreserver = '<a class="moreOffers" href="'+datas.lienreserver+'">'+datas.libellereserver+'</a>';
	if(!datas.lienreserver) {
		tmpDestLienreserver = '';
	}
	
	var localEnSavoirPlus = $('knowMore').innerHTML;
	tmpDestEnSavoirPlus = '<span class="knowMore">'+localEnSavoirPlus+'</span>';
	if(!datas.description) {
	tmpDestEnSavoirPlus = '<p class="knowMore">'+localEnSavoirPlus+'</p>';	
	}
	if(!localEnSavoirPlus) {
		tmpDestEnSavoirPlus = ''
	}
	$('lienallhotel').href = datasExtra[0].lien;

		if(!datas.hotelname && !datas.localisation && !datas.description) {
			tpl = '';
		} else if (!datas.rid) {
			tpl = '';
		} else if (!datas.lienvisiter) {
			tpl = '';
		} else 	{

		tpl = '<li class="itemHotel"><div class="liWrapper">';
		tpl += tmpDestLienvisiterStart;
		tpl += tmpDestVignette;
		tpl += tmpDestHotelname;
		tpl += tmpDestLocalisation;
		tpl += tmpDestDescription;
		//tpl += tmpDestEnSavoirPlus;
		tpl += tmpDestLienvisiterEnd;
		tpl += tmpDestLienlocaliser;
		tpl += tmpDestLienreserver;
		tpl += '</div></li>';

		}
	}
	return tpl;
};

var addTemplateToPage = function(options) {
	ACC.tools.addDomReadyListener(function() {
		var dom = $(options.insertTo);
		if (dom) {
			new Ajax.Request(options.url + '?day=' + new Date().getDay(), {
				method: 'get',
				onSuccess: function(request) {
					var json = request.responseText;
					if (typeof json == 'string') {
						json = eval('(' + json + ')');
					} 
					if (typeof json == 'object') {
					
						var fragment, fragmentDest;
						if (options.code_pays) {
							fragment = getJSONFragment(json, options.code_pays);
							if (fragment == null) { // si le code pays n'est pas dans le JSON, on retourne l'affichage par défaut
								fragment = getJSONFragment(json, 'DEF');
							}
							var optionedTypeFragment = getJSONFragment(fragment, options.type);							
							if (optionedTypeFragment.length == 0) {
							fragment = getJSONFragment(json, 'DEF'); 							
							}
						} else {
							if (options.identifier == "carrousselHotelsCoupsDeCoeur") { // gestion de l'exception de la page destination								
								fragment = getJSONFragment(json, 'zoomshotels');
							}
							else {								
								fragment = getJSONFragment(json, 'DEF');
							}
						}
						
						if (options.identifier == "carrousselHotelsCoupsDeCoeur"){ // gestion de l'exception de la page destination
							fragmentDest = getJSONFragment(fragment, "lienallhotel");
							fragment = getJSONFragment(fragment, "hotels");
						} else {
							fragment = getJSONFragment(fragment || json, options.type);
							
						}	
						
						if (fragment.length === 0) {	
							displayExceptionsManager(options.identifier);
						}						
						
						
						if (fragment.length) {
							options.number = options.number || 1;
							if (fragment.length < options.number) {
								options.number = fragment.length;
							}
							for (var i = 0; i < options.number; i++) {
								if (options.randomSort) {
									var n = getRandomNumber(0, fragment.length);
									
									var tpl = compileTemplate(options.type, fragment[n], options.identifier);
									fragment = fragment.without(fragment[n]);
								} 
								else 
								{
									var tpl = compileTemplate(options.type, fragment[i], options.identifier, fragmentDest);
								}
								dom.insert(tpl);
								
							}
						}

						
					}
					if (typeof auto_height_iframe !== undefined) {
						auto_height_iframe();
					}
					
				},
				onComplete: function(){ // lorsque toutes les datas des JSON sont chargées, on lance les carroussels
						
						if ($('scrollZone2')) { // lancement du carroussel Home Conseils Destinations
						setTimeout(function(){var scrollConseilsDestHome02 = new configCycle('scrollZone2', 2, 'li', 'prev2', 'next2', 136, 'left');},0);
						}
						if ($('scrollZone')) { // lancement du carroussel Home Formules & activités 						
						setTimeout(function(){var scrollConseilsDestHome01 = new configCycle('scrollZone', 1, 'li', 'prev', 'next', 265, 'left');},0)
						}
						
						if ($('scrollZoneOrganiserSejour')) { // lancement du carroussel Home Formules & activités 
						setTimeout(function(){var scrollZoneFicheDestination = new configCycle('scrollZoneOrganiserSejour', 2, '.itemHotel', 'prev', 'next', 297, 'left');},0);
						}
						
						// initialisation de la fonction de redirection sur les select box	
						goToSelected.init()
					
				}
			});
		}
	});
};
