function resort_finder_init(){

   if (GBrowserIsCompatible()) {
      resortMap = new GMap2(document.getElementById("map"));
      coords = new GLatLng(30, -50);
      resortMap.addMapType(G_PHYSICAL_MAP);
      resortMap.setCenter(coords);
      resortMap.setZoom(2);
      resortMap.addControl(new GLargeMapControl());
      resortMap.addControl(new GMapTypeControl(false));
      resortMap.addControl(new GScaleControl());
   }
}

function resort_finder_search(){
   var controlForm = document.forms['map-control'];
   var url = "/json/resorts/";
   var query_dict = {};
   
   var country_id = controlForm.country_id.value;
   if(country_id != ""){
      query_dict.country_id = country_id;
   }
   
   var resort_altitude = controlForm.resort_altitude.value;
   if (resort_altitude !=""){
      query_dict.resort_altitude = resort_altitude;
   }
   
   var highest_lift = controlForm.highest_lift.value;
   if (highest_lift !=""){
      query_dict.highest_lift = highest_lift;
   }   

   $.getJSON(url, query_dict,function(json){
      addResortsToMap(json);
   });
}

function createMarker(point, text, title, iconID, colour) {
   var cpIcon_iconID = new GIcon(G_DEFAULT_ICON);
   if (colour == 'yellow'){
      cpIcon_iconID.image = "/site_media/img/pin_yellow.png";
      cpIcon_iconID.shadow = "/site_media/img/pin_yellow_shadow.png";
      cpIcon_iconID.iconSize = new GSize(12,20);
      cpIcon_iconID.shadowSize = new GSize(22,20);
   }
   var marker = new GMarker(point,{title:title,icon:cpIcon_iconID});
   GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(text);
   });
   return marker;
   }


function setupResortMap(resort_id, latitude, longitude, zoomLevel, cateringType){
   if (GBrowserIsCompatible()) {
      var query_dict = {"resort_id" : resort_id};
      resortMap = new GMap2(document.getElementById("map"));
      coords = new GLatLng(latitude, longitude);
      resortMap.addMapType(G_PHYSICAL_MAP);
      resortMap.setCenter(coords);
      resortMap.setZoom(zoomLevel);
      resortMap.addControl(new GLargeMapControl());
      resortMap.addControl(new GMapTypeControl(false));
      resortMap.addControl(new GScaleControl());
      
      if (cateringType != null){
         query_dict.catering_type_id = cateringType;
      }
      
      var url = "/json/chalets-for-resorts/";
      $.getJSON(url, query_dict,function(json){
         addChaletsToResortMap(json, zoomLevel);
       });
   }
}


function addResortsToMap(json){
   if (GBrowserIsCompatible()) {
        resortMap.clearOverlays();
        var bounds = new GLatLngBounds();

        for (i = 0; i < json.length; i++){  
           markerHtml = "<div class='map-overlay-title'><a href='" + json[i].url + 
                          "' title='More details for " + json[i].name + "'>" + json[i].name + 
                          "</a></div>";
           point = new GLatLng(json[i].latitude, json[i].longitude);
           marker = createMarker(point, markerHtml, json[i].name, json[i].id, null);
           resortMap.addOverlay(marker);
           bounds.extend(marker.getPoint());
        }
        resortMap.setCenter( bounds.getCenter( ), resortMap.getBoundsZoomLevel(bounds));        
     }
}



function addChaletsToResortMap(json, zoomLevel){
   if (GBrowserIsCompatible()) {
      resortMap.clearOverlays();
      var bounds = new GLatLngBounds();
      
      for (i = 0; i < json.length; i++){  
         markerHtml = "<div class='map-overlay-title'><a href='" + json[i].url + 
                        "' title='More details for " + json[i].name + "'>" + json[i].name + 
                        "</a></div><a href='" + json[i].url + "' title='More details for " + json[i].name + 
                        "'><img src='" + json[i].image_path + 
                        "' id='chalet-thumb-map' name='chalet-thumb-map' width='" + json[i].image_width + 
                        "' height='" + json[i].image_height + 
                        "'></a><div class='map-overlay-text'><ul class='bullet-list'>";
          
         if (json[i].sleeps){
            markerHtml += "<li class='bullet'>Sleeps: " + json[i].sleeps + "</li>";
         }
         for (j = 0; j < json[i].board_types.length; j++){
            markerHtml += "<li class='bullet'>" + json[i].board_types[j] + "</li>";
         }
         
         markerHtml += "</ul>[<a href='#" + json[i].slug + "' title='More details for " +
                        json[i].name + "'>more</a>]</div>";
         
         point = new GLatLng(json[i].latitude, json[i].longitude);
         marker = createMarker(point, markerHtml, json[i].name, json[i].id, null);
         resortMap.addOverlay(marker);
         bounds.extend(marker.getPoint());
      }
      if (json.length < 1 && zoomLevel){
         resortMap.setZoom(zoomLevel);
      }else if (zoomLevel){
         resortMap.setCenter( bounds.getCenter( ), resortMap.getBoundsZoomLevel(bounds));
      }
   }
}

function resortMapSearch(){
   var url = "/json/chalets-for-resorts/";
   var query_dict = {};
   
   var controlForm = document.forms['map-control'];
   var resortId = controlForm.resort_id.value;
   query_dict.resort_id = resortId;
   
   var cateringType = null;
   for (i = 0; i < controlForm.catering_type.length; i++){
      if (controlForm.catering_type[i].checked == true){
         cateringType = controlForm.catering_type[i].value;
         break;
      } 
   }
   if (cateringType != 0){
      query_dict.catering_type_id = cateringType;
   }
   
   var sleeps = controlForm.sleeps.value;
   if(sleeps != ""){
      query_dict.sleeps = sleeps;
   }
   
   var attrs = "";
   for (i = 0; i < controlForm.attribute.length; i++){  
      if (controlForm.attribute[i].checked){
         attrs = controlForm.attribute[i].value + "," + attrs;
      }
   }
   if (attrs.length > 0){
      query_dict.attributes = attrs.substring(0, attrs.length-1);
   }   
   
   $.getJSON(url, query_dict,function(json){
      addChaletsToResortMap(json, null);
    });
   
   if (document.getElementById('mapToggler').checked) {
      addToMap(resortId);
   }
}

function dynamicSelect(){
	this.selects = new Array();
	this.addSelect = function(name){
		this.selects[name] = new selectObj();
	}

	this.updateOptions = function(source, target){
		var form = source.form;
		var target = form.elements[target];
		var value = source.options[source.selectedIndex].value;
		while(target.options.length) target.remove(0);
		if(!this.selects[source.name].options[value]){
			//alert('Invalid selection.'); //For debugging while you set it up
			return;
		}
		var data = this.selects[source.name].options[value].options;
		
		for(var x=0; x<data.length; x++){
			try{
				target.add(data[x]);
			}
			catch(e){
				target.add(data[x], null);
			}
		}	
		target.selectedIndex = 0;
	}
}

function selectObj(){
	this.options = new Array();	
	this.addOption = function(value){
		this.options[value] = new optionObj();
	}
}

function optionObj(){
	this.options = new Array();	
	this.createOption = function(name, value){
		this.options[this.options.length] = new Option(name, value);
	}
}

function setZoom(img, dir, width, height, margin, zIndex, delay) {
   setTimeout(function() {
      if (img.dir==dir) {
         img.style.width=width;
         img.style.height=height;
         img.style.margin=margin;
         img.style.zIndex=zIndex;
         img.parentNode.parentNode.style.zIndex=zIndex;
      }
      }, delay);
}

function larger(img, width, height) {
   img.dir='rtl';
   now=parseInt(img.style.zIndex);
   for (i=now+1; i<=10; i++) {
      w=(width*(10+i))/20+'px';
      h=(height*(10+i))/20+'px';
      m=(-i)+'px 0 0 '+(-width*i/40)+'px';
      setZoom(img, 'rtl', w, h, m, i, 20*(i-now));
   }
}

function smaller(img, width, height) {
   img.dir='ltr';
   now=parseInt(img.style.zIndex);
   for (i=now-1; i>=0; i--) {
      w=(width*(10+i))/20+'px';
      h=(height*(10+i))/20+'px';
      m=(-i)+'px 0 0 '+(-width*i/40)+'px';
      setZoom(img, 'ltr', w, h, m, i, 20*(now-i));
   }
}

function addToMap(resort_id){
	var url = "/json/resort-poi/"
	var poiTypes = new Array();
	$.getJSON(url, {"resort_id" : resort_id },function(json){
	   
	   //build an array of the differt types of POI
	   //we use this as a lookup table when forming the description
	   for (j = 0; j < json.length; j++){
	      if (json[j].model == "chaletpro.poitype"){
	         poiTypes[json[j].pk] = json[j].fields.type;
	      }
      }
	   
		for (i = 0; i < json.length; i++){
		   if (json[i].model == "chaletpro.resortpoi"){
		      poiType = poiTypes[json[i].fields.poi_type];
		      
		      titleText = "";
		      
		      if (json[i].fields.name == ""){
		         titleText = poiType;
	         }else{
	            titleText = json[i].fields.name + " (" + poiType + ")";
            }
		      
			   title = "<div class='map-overlay-title'>"+ titleText + "</div>";  
			   desc = "<div class='map-overlay-text'>" + json[i].fields.description + "</div>";
			   marker = createMarker(new GLatLng(json[i].fields.latitude, json[i].fields.longitude), title + desc,title, json[i].pk, 'yellow');
			   resortMap.addOverlay(marker);
		   }
		}
	});
}

function toggleMapExtras(thing) {
	if (document.getElementById('mapToggler').checked) {
		addToMap(thing);
	} else {
		resetMap();
	}
}

function toggleResortMapExtras(thing) {
	if (document.getElementById('mapToggler').checked) {
		addToMap(thing);
	} else {
		resortMapSearch();
	}
}



function addChaletToShortList(chalet_id, chalet_name) {
   // chalet name should always come in html escaped
   var url = "/json/add-to-favourites/";
   $.getJSON(url, {"chalet_id" : chalet_id },function(json){
      var a_element = $("#chalet_ssi_" + chalet_id).find("a.shortlist-link");
      a_element.html('<div class="icon-shortlist-remove"></div><div class="icon-legend">Remove from shortlist</div>');
      a_element.attr("href", 'javascript:removeChaletFromShortList("' + chalet_id + '","' + chalet_name + '");');
      a_element.attr("title", 'Remove from your shortlist');
   });

   // add to sidebar?
   if ( $('#shortlist ul').length ) {
      $('#shortlist ul').append("<li id='rnav_chalet_" + chalet_id + "'><a href='/ski-chalets/" + chalet_id + "/" + chalet_name.replace(/ /g,'-') + ".html'>" + chalet_name + "</a></li>")
   } else {
      $('#sidebar').prepend("<div class='panel' id='shortlist'><ul><li><a href='/short-list'><div class='icon' id='go-shortlist'></div><div class='icon-legend'>Your shortlist</div></a></li><li><a href='javascript:saveShortList()'><div class='icon' id='save-shortlist'></div><div class='icon-legend'>Save shortlist</div></a></li><li id='rnav_chalet_" + chalet_id + "'><a href='/ski-chalets/" + chalet_id + "/" + chalet_name.replace(/ /g,'-') + ".html'>" + chalet_name + "</a></li></ul></div>")
   }
}

function removeChaletFromShortList(chalet_id, chalet_name){
   // chalet name should always come in html escaped
   var remove_url = "/json/remove-from-favourites/";
   $.getJSON(remove_url, {"chalet_id" : chalet_id },function(json){
      var a_element = $("#chalet_ssi_" + chalet_id).find("a.shortlist-link");
		a_element.html('<div class="icon-shortlist-add"></div><div class="icon-legend">Add to shortlist</div>');
		a_element.attr("href", "javascript:addChaletToShortList('" + chalet_id + "','" + chalet_name + "');");
		a_element.attr("title", 'Add to your shortlist');
		$("#rnav_chalet_" + chalet_id).slideUp("slow");
	});
}

function toggleMap(){
   $('#map').slideToggle("slow");
}

function removeChaletFromShortlistAndHide(chalet_id){
   var remove_url = "/json/remove-from-favourites/";
   $.getJSON(remove_url, {"chalet_id" : chalet_id },function(json){
      $("#chalet_ssi_" + chalet_id).slideUp("slow");
      $("#rnav_chalet_" + chalet_id).slideUp("slow");
   });
}

function saveShortList() {
   var url = "/json/save-shortlist/";
   email = document.getElementById('shortlist-email').value;
   $.getJSON(url, {"email" : email }, function(json){
      if (json[0].model == "chaletpro.jsonerror"){
         $('#shortlist-error').append(json[0].fields.error_text)
      } else {
         $.unblockUI();
      }
   });
}

function saveShortListDialog(msg) {
   var msg = "<div id='overlay'><form name='save-shortlist' id='save-shortlist' action='javascript:saveShortList()'><fieldset class='small-form'> \
   <div class='input-row'> \
      <p class='form-text-title'>Save your shortlist</p> \
      <p class='form-text'>Enter your email address to save your shortlist for next time you visit</p> \
      <label for='email'>Email</label><input type='text' name='shortlist-email' id='shortlist-email'> \
      <p class='form-text'><span class='form-error' id='shortlist-error'></span></p> \
   </div> \
   <div class='submit-row'> \
      <input id='save-shortlist-submit' type='submit' alt='Save' value='Save' class='button'> \
      <input id='cancel' type='reset' class='button' value='Cancel' alt='Cancel' onclick='javascript:$.unblockUI();'> \
   </div> \
   </fieldset></form></div>"
   $.blockUI.defaults.css = {
        padding:        0,
        margin:         0,
        width:          '347px',
        top:            '40%',
        left:           '35%',
        textAlign:      'left',
        color:          '#000',
        border:         '0px solid #aaa',
        backgroundColor:'#fff',
        cursor:         'wait'
    };
    $.blockUI({ message: msg });
}

function unShow(what) {
   $(what).hide()
}

function hideSaveShortList() {
   $.blockUI;
}

function updateResorts(country){
	var country_id = document.forms['simple_search'].country.value;            
	var resort_select_box = document.forms['simple_search'].resort;
	if (original_resort_select_box.length == 0) {
		for (var i=0; i < resort_select_box.options.length; i++) {
			original_resort_select_box[i] = new Array(resort_select_box.options[i].text, resort_select_box.options[i].value);
		}
	}
	//clear old resort dropdown
	resort_select_box.options.length = 0;
	if (country_id == ""){
		//need to add back all the resorts.
		resort_select_box.options.length = original_resort_select_box.length;
		for (var i=0; i<original_resort_select_box.length; i++){
			resort_select_box.options[i] = new Option(original_resort_select_box[i][0], original_resort_select_box[i][1]);
		}
	} else {
		var resort_array = country_array[country_id];
		resort_select_box.options.length = resort_array.length + 1;
		resort_select_box.options[0] = new Option("","");
		for (var i=0; i<resort_array.length; i++){
			resort_select_box.options[i+1] = new Option(resort_array[i][1], resort_array[i][0]);
		}
	}
}

function confirmAction(msg) {
   var r = confirm(msg);
   if (r==true) {
      return true;
   } else {
      return false;
   }
}
