	var notactiveday = new Array();
	var delaybeforebooking ;
	var heurref ;
	var notactivedayshop="";
	var languageinfo = "";
	var infoshop =new Array();
	var map;
	var markers;
    var gmarkers = [];
    var htmls = [];
	var bounds;

	function selectthisshop(id){
		$('#shops').val(id);
		$.fn.fancybox.close();
	}


	$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
	  while(x<c.length){var m=r.exec(c.substr(x));
	    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
	    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
	    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
	URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
	  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
	  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
	});






	function createMarker(i, SkisetIcon) {
		var lat = markers[i].getAttribute("lat");
		var long = markers[i].getAttribute("long");
		var point = new GLatLng(lat,long);
 	    bounds.extend(point);
		map.setCenter(point, 17);
		var marker = new GMarker(point, {icon:SkisetIcon});
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml('<table><tr><td><img src="'+$.URLDecode(markers[i].getAttribute("photo"))+'" style="width:110px;height:74xp;" /></td><td><table><tr><td>'+$.URLDecode(markers[i].getAttribute("name"))+'</td></tr><tr><td>'+$.URLDecode(markers[i].getAttribute("address"))+'</td></tr></table></td></tr><tr><td colspan=2 style="text-align:center;"><input type="button" name="chooseit" value="choose this shop" id="shop_'+markers[i].getAttribute("id")+'" onClick="selectthisshop('+markers[i].getAttribute("id")+')"/></td></tr></table>');
          });
		gmarkers[markers[i].getAttribute("id")] = marker;
		return marker;
	}


function mapavailable(){
		if($('#resorts').val() != 0)
			$('.showmaplink').show();
		$("#openmaplink").unbind("click");
		$("#openmaplink").fancybox({
			'params':{
				id:$('#resorts :selected').val(),
				country:$('#countries :selected').val()
				},
			'overlayShow':	true,
			'overlayOpacity':0.7,
			'frameWidth': 975,
			'frameHeight':505,
			'sizefix':true,
			closeCallback:function(){
				$('select').show();
			},
			loadedCallback:function(){
				$('select').hide();				
				$("#carousellistcontent").jCarouselLite({
					btnNext: "#cartocontentflecheD",
					btnPrev: "#cartocontentflecheG",
					circular: true,
					vertical: false,
					visible:4
				});
				
					if($('#isgmap').html() == "1"){
					if (GBrowserIsCompatible()) {
					bounds = new GLatLngBounds();
				    map = new GMap2(document.getElementById("map_canvas"));
					map.addControl(new GSmallMapControl());
					map.addControl(new GMapTypeControl());
					map.setMapType(G_SATELLITE_MAP);
					var tmp = $('#resorts').val().split('_');
 			       GDownloadUrl("/ajaxdata/shoplistgmap/id/"+tmp[1], function(data) {
				        var xml = GXml.parse(data);
				        markers = xml.documentElement.getElementsByTagName("marker");
						var baseIcon = new GIcon(G_DEFAULT_ICON);
						baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
						baseIcon.iconSize = new GSize(20, 34);
						baseIcon.shadowSize = new GSize(37, 34);
						baseIcon.iconAnchor = new GPoint(9, 34);
						baseIcon.infoWindowAnchor = new GPoint(9, 2);
						var SkisetIcon = new GIcon(baseIcon);
						SkisetIcon.image = "http://static0.skiset.com/images/iconeSKmap.gif";
						for (var i = 0; i < markers.length; i++) {
							map.addOverlay(createMarker(i,SkisetIcon));
						}
						//maintenant on va regarder si un magasin est selectionne
						if($('#shops').val() != 0){
							GEvent.trigger(gmarkers[$('#shops').val()], "click");
						}else{
							map.setZoom(map.getBoundsZoomLevel(bounds));
						    map.setCenter(bounds.getCenter());							
						}
				   });
				  }
				}else{
				  if ($('#count').html() <= 4)
                {
					$("#cartocontentflecheG").hide();
                    $("#cartocontentflecheD").hide();
                }
				$('.selecthebergeur').click(function(){
					$.each($('.hebergeur'), function(i,item){
						$(item).attr('class','selecthebergeur hebergeur');
					});
					$('#mapimg').attr('src', "http://staticch.skiset.com/plans/"+$(this).attr('id')+".jpg");
					$(this).attr('class','selecthebergeurselected hebergeur');
				});

				$(".shopdetailspointer").click(function(){
					$('#shops').val($(this).attr('id'));
					$.fn.fancybox.close();
				})
				$(".shopdetailspointer").jHelperTip({
				 trigger: "hover", 
				 source: "ajax", 
				 attrName: "alt", 
				 opacity: 1,
				 url:'/index/magdetails',
				 loadingText: 'Loading...',
				 autoClose:true
				});
			}
		}
		});
}

function skisetcalendar(date){
		if (new Date(date.valueOf()+heurref) <= (new Date().valueOf()+delaybeforebooking))
			return [false,"ui-datepicker-disabled","Magasin fermé "];
		else
			return [true, ""];
	}
	
function datepickerskiset()
{	
	startdateskiset =$('#startdate').html().split("-");
	enddyteskiset =$('#enddatesaison').html().split("-");
	var today =$('#alternate').val().split("-");
	
	$.datepicker.setDefaults($.extend( $.datepicker.regional[''+languageinfo+'']));
	$("#datepicker").datepicker({
		beforeShowDay: skisetcalendar, 
		minDate:new Date(startdateskiset[2], startdateskiset[1]-1, startdateskiset[0]),
		firstDay:0,
		numberOfMonths:2,
		dateFormat:'DD d MM yy',
		altField: '#alternate', 
		altFormat: 'dd-mm-yy',
		showOn: 'both',
		defaultDate: new Date(today[2], today[1]-1, today[0]),
		gotoCurrent: true,
		navigationAsDateFormat: true,
		buttonImage: 'http://staticfr.skiset.com/calendaricon.gif',
		buttonImageOnly: true,
		maxDate: new Date(enddyteskiset[2], enddyteskiset[1]-1, enddyteskiset[0])
	});
}
	//mise à jour de la date
function updatedate(){
	var s = $('#alternate').val().split("-");
	var today = new Date(s[2],s[1]-1,s[0]).getTime();
	var sec = (1000 * 60 * 60 * 24 * ($('#days').val()-1));
	var newdate = new Date(today+sec);
	languageinfo = $('#domaine').html();
	if( languageinfo=='en' || languageinfo == 'dk'|| languageinfo == 'us')
		languageinfo = '';
	$("#enddate").html(
		$.datepicker.formatDate( 
		'DD d MM yy',
		newdate,
		{
			dayNames: $.datepicker.regional[''+languageinfo+''].dayNames, 
			monthNames: $.datepicker.regional[''+languageinfo+''].monthNames,
			yearNames: $.datepicker.regional[''+languageinfo+''].yearNames
		})
	);   
}


function getpromo()
{
	if($('#alternate').val()){
		$.getJSON('/ajaxdata/getpromo/format/json/countries/'+$('#countries').val()+'/shops/'+$('#shops').val()+'/datepicker/'+$('#alternate').val()+'/codepromo/'+$('#promo').val(), function(data){
			$('#zonepromo').html(data.promo);
			$('#divpourcentpromo').show();
			$('#reductionsentence').hide();
		});
	}else{
		$('#zonepromo').html('0');
		$('#reductionsentence').hide();
		$('#divpourcentpromo').show();
	}
}
	
	
function msg6egal7(days)
{
	var countries= $('#countries').val();
	if (days.val() == 6 && countries != 12 && countries != 28){
		//$('#info6egal7surdemande').show();
        $('#info6egal7').css("visibility","visible");
        $('#info6egal7').html($('#txtinfo6egal7').html());
		//$('#info6egal7').hide();
       // $('#info6egal7').css("visibility","hidden");
	}else if(days.val() == 7 && countries != 12 && countries != 28){
		//$('#info6egal7').show();
        $('#info6egal7').css("visibility","visible");
        $('#info6egal7').html($('#txtinfo6egal7surdemande').html());

		//$('#info6egal7surdemande').hide();
       // $('#info6egal7surdemande').css("visibility","hidden");
	}else{
		//$('#info6egal7').hide();
        $('#info6egal7').css("visibility","hidden");
		//$('#info6egal7surdemande').hide();
        $('#info6egal7surdemande').css("visibility","hidden");
	}
}


function getshopsettings(){
	$.getJSON('/ajaxdata/getminimumdurationforshop/format/json/id/'+$('#shops').val()+'/date/'+$('#alternate').val(), function(json){

		var select = "";
		var selected = $('#days').val();
		$.each(json.result, function(i,item){
			select += '<option label="'+item+'" value="'+i+'">'+item+'</option>';
		});
		$('#days').html(select);
		$('#days').val(selected);
	});
	
}

$(document).ready(function(){
	
	
	$('#loaderpage').show();
/*	
	$('#promo').keyup(function(){
	    if($(this).val().length > 3){
	        $('#checkcodemotor').show();
	    }
	    else{
	        $('#checkcodemotor').hide();
	    }
	});

	$('#checkcodemotor').click(function(){
	    getpromo();
	    return false;
	});
	
*/	
	
	//ici on verifie si on a des erreurs ou pas
	if($('#dialogerror').html() != null){
		$("#dialogerror").dialog({
					bgiframe: true,
					modal: true,
					width:450,
					height:250,
					dialogClass: 'alerterrorbox',
					buttons: {
						Ok: function() {
							$(this).dialog('close');
						}
					}
				});
	}
	
	$("#logopartenaire").jCarouselLite({
		circular: true,
		vertical: false,
		visible:5,
		auto:1500
	});
	
	$('#divplusinfo').click(function(){
		//$('#repeatplusdinfos').toggle();
		//$('#flechemenuderoulmagD').toggle();
		//$('#flechemenuderoulmagB').toggle();
	});
	
	$('#menuiteminfoski').hover(
		function(){
			$('.menu2txt').slideDown();
		},function(){
			$('.menu2txt').slideUp();
		}
	);
		
	$('#menuitemlang').hover(
		function(){
			$('.menu2img').slideDown();
		},function(){
			$('.menu2img').slideUp();
		}
	);
	
	//TICK&GO
	$('#tickandgocheck').click(function(){
		$('#tickandgomsg').html('<img src="http://static0.skiset.com/images/ajax-loader.gif" />');
		$.getJSON('ajaxdata/checktickandgocardnumber/format/json/cardnumber/'+$('#promotickandgo').val(), function(json){
			$('#tickandgomsg').html(json.result.message);
		});
	});
	
	
	if($('#alternate').val()){
		$('#divpourcentpromo').hide();
		msg6egal7($('#days'));
		delaybeforebooking =$("#delaybeforebooking").html()*3600000;
		heurref =$("#heurref").html()*3600000;
		languageinfo = $("#domaine").html();
	 	if(languageinfo=='en' || languageinfo == 'dk' || languageinfo == 'us')
	 		languageinfo='';
		//default datepicker
		datepickerskiset();
		//load resorts
		mapavailable();

        if($("#resorts").val() == 0)
             $('#divpourcentpromo').hide();
        else
           getpromo();

	
		$('#submitimage').click(function(){
			$("#resamotorform").submit();
		});
	
		$('#imginfo').jHelperTip({
		 	trigger: "hover", 
		 	source: "container",
		 	topOff: 20,
            leftOff: -125,
            dC:"#infobulle",
		 	opacity: 1,
		 	autoClose:true
		});
		
	var evt = $.browser.msie ? "click" : "change"	;
		
	$("#countries").bind(evt,function(){
/*	
		if ($(this).val() >= 1000)
		{
			//country america
			alert("Bookings for American's ski resorts will be available in October");
			// on force sur la france
			$(this).val(1);
		}
*/
		// country europa
		$.getJSON('/ajaxdata/getallresortsbycountry/format/json/id/'+$(this).val(), function(data){
			var option = "";
			var nb = 0;
			$('#resorts').empty();
			$('#shops').empty();
			$('#resorts').html('<option>Loading...</option>');
			$('#shops').html('<option>Loading...</option>');
			$('#divpourcentpromo').hide();
			$.each(data.resorts, function(i,resort){
				if(resort.web_nearresort_id != null)
					option += '<option value="'+resort.name+'_'+resort.id+'_'+resort.web_nearresort_id+'" label="'+resort.name+'">'+resort.name+'</option>';
				else
					option += '<option value="'+resort.name+'_'+resort.id+'_0" label="'+resort.name+'">'+resort.name+'</option>';
				nb++;
			});
			if(nb > 1){
				option = '<option value="0" label="">'+data.msg+'</option>'+option;
			}
			$('#resorts').html(option);

            if($('#resorts :selected').val()!= 0){
                $('#resorts').change(); // ici on force le change et on évite de répéter le code
			}
            else{
                $('#shops').html('<option>Loading...</option>');
			}
            
           
            var s = data.resorts[0].id.split("_");
			
		});
		$.getJSON('/ajaxdata/getlistofdaysavailable/format/json/id/'+$(this).val(), function(json){
			var select = "";
			var selected = $('#days').val();
			$.each(json.result, function(i,item){
				select += '<option label="'+item+'" value="'+i+'">'+item+'</option>';
			});
			$('#days').html(select);
			$('#days').val(selected);
		});
		mapavailable();
	});
	//load shops
	$("#resorts").bind(evt,function(){
		mapavailable();
		var s = $(this).val().split("_");
		if(s[2] != 0){
			//on envoi une requete ajax pour recuperer le message et verifier si il existe
			$.getJSON('/ajaxdata/getmessagefornearresort/format/json/id/'+s[2], function(data){
				if(data.messages)
					alert(data.messages);
			});
		}
        // on calcul la promo à la sélection de la station
        if($(this).val() == 0)
           $('#divpourcentpromo').hide();
        else
           getpromo();

		var option = "";
		$.getJSON('/ajaxdata/getallshopsbyresort/format/json/id/'+s[1], function(data){
		$('#shops').empty();
			$('#shops').html('<option>Loading...</option>');
			var nb = 0;
			var i=0;
			var notactiveday="0";
			var shopid = null;
			$.each(data.shops, function(i,shop){
				option += '<option value="'+shop.id+'" label="'+shop.name+'">'+shop.name+'</option>';
				shopid = shop.id;
				infoshop[i] = shop;
				nb++;
			});
            if(nb > 1)
                option = '<option value="0" label="">'+data.msg+'</option>'+option;
			else{
				$.get('/ajaxdata/getshopinfos/shopid/'+shopid, function(response){$('.categorybox1').html(response);});
			}
				//mettre un truc
			$("#infoshop").html($.toJSON(infoshop));
			$('#shops').html(option);

            getpromo();
			getshopsettings();

		});
		
	//	 TODO : La meteo est desactiver tant que le flux meteo n'est pas traiter
//		$.get('/ajaxdata/getweatherhome/resortid/'+s[1], function(response){$('.categorybox2').html(response);});
	});
	$("#shops").bind(evt,function()
	{ 
        getpromo();
		//recherche les informations magasins
		$.get('/ajaxdata/getshopinfos/shopid/'+$(this).val(), function(response){
			$('.categorybox1').html(response);
		});
		//recherche les settings magasin
		getshopsettings();
	});
	
	$("#days").click(function(){
		var s = $('#alternate').val().split("/");
		var today = new Date(s[2],s[0]-1,s[1]).getTime();
		var sec = (1000 * 60 * 60 * 24 * ($('#days').val()-1));
		var newdate = new Date(today+sec);
		
		$("#enddate").html(	$.datepicker.formatDate( 
			'DD d MM', 
			newdate,
			{
			dayNamesShort: $.datepicker.regional[''+languageinfo+''].dayNamesShort, 
			dayNames: $.datepicker.regional[''+languageinfo+''].dayNames, 
			monthNamesShort: $.datepicker.regional[''+languageinfo+''].monthNamesShort,
			monthNames: $.datepicker.regional[''+languageinfo+''].monthNames
			}
		));	
		msg6egal7($(this));
		updatedate();
	});
	
	$("#datepicker").change(function(){
		updatedate();
         if($("#resorts").val() == 0)
             $('#divpourcentpromo').hide();
        else
           getpromo();
		getshopsettings();
	});
	
	
	$('#headerplusdinfos').click(function(){
		$('#repeatplusdinfos').toggle();
	});
	
	$('#errorindex').click(function(){
		$(this).fadeOut('slow');
	});
	$('#errorindexalert').click(function(){
		$('#errorindex').fadeIn('slow');
	});
	}
	
	$('#loaderpage').hide();
});