
// General routines
function showloading(where) {
	container = document.getElementById(where);
	if (container) {
		positioning = 'top: '+container.offsetTop+'px; width: '+container.offsetWidth+'px; height: '+container.offsetHeight+'px; ';
		$('div#' + where).append('<div id="requestwaiting" style="position: absolute; ' + positioning + '"/>');
	}
}
function postform(whatform,destination,callerobj) {
	if (callerobj) {
		destination= $('#' + callerobj.id).parent('div').attr("id");	
	}
	showloading(destination);
	$.ajax({
	  url: "/cfpages/functions/ajaxcontroller.cfc?method=execute",
	  cache: false,
	  data: $('#' + whatform).serialize(),
	  type: "POST",
	  success: function(data) {
		$('div#' + destination).hide();
		$('div#' + destination).html(data);
		$('div#' + destination).fadeIn();				  
		}
	});		
	return false;
}	


function topscroll() {
	$('html').animate({scrollTop:0}, 'slow');//IE, FF
	$('body').animate({scrollTop:0}, 'slow');//chrome, don't know if safary works
}

function loadSection(panel,what,extra) {
	
	if (!extra) {
		extra='';	
	}	
	
	if (panel == 'new') {
		window.open("/cfpages/functions/ajaxcontroller.cfc?method=execute&actionmethod=" + what + "&extraparams=" + extra,what);
		$('#requestwaiting').hide();
	} else {
		showloading(panel);
		$.ajax({
		  url: "/cfpages/functions/ajaxcontroller.cfc",
		  dataType: "html",
		  cache: false,
		  data: {actionmethod:what, method:"execute", extraparams:extra },
		  success: function(data) {		
				$('div#' + panel).hide();
				$('div#' + panel).html(data);
				$('div#' + panel).fadeIn();
			},
			error:function(xhr,err){
				alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
				alert("responseText: "+xhr.responseText);
				$('#requestwaiting').hide();
			}
		});	
	}
}		

function setOffers() {
$('a.offerlink').each(function()
   {
	  $(this).qtip(
	  {
		 content: {
			// Set the text to an image HTML string with the correct src URL to the loading image you want to use
			text: '<img src="/images/extras/ajax-loader.gif" alt="Loading..." />',
			url: '/cfpages/xml/iglusummary.cfm?id=' + $(this).attr('rel'), // Use the rel attribute of each element for the url to load
			title: {
			   text: 'IGLU Offer - ' + $(this).text(), // Give the tooltip a title using each elements text
			   button: 'Close' // Show a close link in the title
			}
		 },
		 position: {
			corner: {
			   target: 'bottomMiddle', // Position the tooltip above the link
			   tooltip: 'topMiddle'
			},
			adjust: {
			   screen: true // Keep the tooltip on-screen at all times
			}
		 },
		 show: { 
			when: 'click', 
			solo: true // Only show one tooltip at a time
		 },
		 hide: 'unfocus',
		 style: {
			tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
			border: {
			   width: 0,
			   radius: 4
			},
			name: 'light', // Use the default light style
			width: 415 // Set the tooltip width
		 }
	  })
   });	
	$('a.resortname').each(function()
	   {
		  $(this).qtip(
		  {
			 content: {
				// Set the text to an image HTML string with the correct src URL to the loading image you want to use
				text: '<img src="/images/extras/ajax-loader.gif" alt="Loading..." />',
				url: '/cfpages/xml/resortsummary.cfm?id=' + $(this).attr('rel'), // Use the rel attribute of each element for the url to load
				title: {
				   text: 'WSG Review - ' + $(this).text(), // Give the tooltip a title using each elements text
				   button: 'Close' // Show a close link in the title
				}
			 },
			 position: {
				corner: {
				   target: 'bottomMiddle', // Position the tooltip above the link
				   tooltip: 'topMiddle'
				},
				adjust: {
				   screen: true // Keep the tooltip on-screen at all times
				}
			 },
			 show: { 
				when: 'click', 
				solo: true // Only show one tooltip at a time
			 },
			 hide: 'unfocus',
			 style: {
				tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
				border: {
				   width: 0,
				   radius: 4
				},
				name: 'light', // Use the default light style
				width: 350 // Set the tooltip width
			 }
		  })
	   });
}




// for the sub menu shown on resort links
function show() {
	var menu = $(this);
	menu.children(".actions").slideDown('fast');
}

function hide() { 
	var menu = $(this);
	menu.children(".actions").slideUp('fast');
}






function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
} 
function setText(thefield){
if (thefield.value=="")
thefield.value = thefield.defaultValue
} 


function popItUp(newURL) {
	newWindow=window.open(newURL,"sendMail","statusbar=false, titlebar=false, resizable=false, menubar=false,HEIGHT=480, WIDTH=500")
	newWindow.focus()
}		


function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "block";
}
function ReverseContentDisplay(d) {
if(d.length < 1) { return; }
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}


// jDiv - a jQuery plugin
// (c) Skyrocket Labs
// http://www.skyrocketlabs.com
// fred@skyrocketlabs.com
// Created: 10.24.2009
// Last updated: 02.06.2010

// DISPLAYS HIDDEN DIVS AS SUBMENUS ON HOVER

$(document).ready(function() {

	$('#mainnavigation').append( $('div.dropdown') );
						   
        var hide01 = false;
		$("#nav-resorts").hover(function(){          
		   if (hide01) clearTimeout(hide01);
            $("#dropdown-resorts").slideDown();
			$(this).addClass("active");
        }, function() {
			hide01 = setTimeout(function() {$("#dropdown-resorts").hide();});
			$("#nav-resorts").removeClass("active");
        });
        $("#dropdown-resorts").hover(function(){
            if (hide01) clearTimeout(hide01);
            $("#nav-resorts").addClass("active");
        }, function() {
			hide01 = setTimeout(function() {$("#dropdown-resorts").hide();});
			$("#dropdown-resorts").slideDown();
			$("#nav-resorts").removeClass("active");
        });
		
		
        var hide03 = false;
		$("#nav-travel").hover(function(){          
		   if (hide03) clearTimeout(hide03);
            $("#dropdown-travel").slideDown();
			$(this).addClass("active");
        }, function() {
			hide03 = setTimeout(function() {$("#dropdown-travel").hide()});
			$("#nav-travel").removeClass("active");
        });
        $("#dropdown-travel").hover(function(){
            if (hide03) clearTimeout(hide03);
            $("#nav-travel").addClass("active");
        }, function() {
			hide03 = setTimeout(function() {$("#dropdown-travel").hide();});
			$("#dropdown-travel").slideDown();
			$("#nav-travel").removeClass("active");
        });
		
        var hide04 = false;
		$("#nav-news").hover(function(){          
		   if (hide04) clearTimeout(hide04);
            $("#dropdown-news").slideDown();
			$(this).addClass("active");
        }, function() {
			hide04 = setTimeout(function() {$("#dropdown-news").hide()});
			$("#nav-news").removeClass("active");
        });
        $("#dropdown-news").hover(function(){
            if (hide04) clearTimeout(hide04);
            $("#nav-news").addClass("active");
        }, function() {
			hide04 = setTimeout(function() {$("#dropdown-news").hide();});
			$("#dropdown-news").slideDown();
			$("#nav-news").removeClass("active");
        });
		
		
        var hide05 = false;
		$("#nav-shop").hover(function(){          
		   if (hide05) clearTimeout(hide05);
            $("#dropdown-shop").slideDown();
			$(this).addClass("active");
        }, function() {
			hide05 = setTimeout(function() {$("#dropdown-shop").hide()});
			$("#nav-shop").removeClass("active");
        });
        $("#dropdown-shop").hover(function(){
            if (hide05) clearTimeout(hide05);
            $("#nav-shop").addClass("active");
        }, function() {
			hide05 = setTimeout(function() {$("#dropdown-shop").hide();});
			$("#dropdown-shop").slideDown();
			$("#nav-shop").removeClass("active");
        });
				
        var hide06 = false;
		$("#nav-knowledge").hover(function(){          
		   if (hide06) clearTimeout(hide06);
            $("#dropdown-knowledge").slideDown();
			$(this).addClass("active");
        }, function() {
			hide06 = setTimeout(function() {$("#dropdown-knowledge").hide()});
			$("#nav-knowledge").removeClass("active");
        });
        $("#dropdown-knowledge").hover(function(){
            if (hide06) clearTimeout(hide06);
            $("#nav-knowledge").addClass("active");
        }, function() {
			hide06 = setTimeout(function() {$("#dropdown-knowledge").hide();});
			$("#dropdown-knowledge").slideDown();
			$("#nav-knowledge").removeClass("active");
        });
		

	if ( $('a.popimg').length!=0) {
		$("a.popimg").fancybox({
			'overlayShow'			: false,
			'zoomSpeedIn'			: 600,
			'zoomSpeedOut'			: 500,
			'easingIn'				: 'easeOutBack',
			'easingOut'				: 'easeInBack'
		});	
	 };
	if(typeof(resorts) != "undefined"){ 
		$("#suggestresort").autocomplete(resorts, {
			minChars: 0,
			width: 310,
			matchContains: "word",
			autoFill: false,
			formatItem: function(row, i, max) {
				return i + "/" + max + ": " + row.name + ", " + row.country;
			},
			formatMatch: function(row, i, max) {
				return row.name + " " + row.country;
			},
			formatResult: function(row) {
				return row.name;
			}
		});
		$('#suggestresort').result(function(event, data, formatted) {
			if (data) {
				window.location.href=data.theurl;
			}
		});
	}
	
	if ( $('#shopincontextdiv').length!=0) {	
		loadSection('shopincontextdiv','shop.incontext','PageID=' + globalPageID);
	}
	
	
	













	
	});


	
	var map = null;
	//var markerCluster = new MarkerClusterer(map);
	var markerCluster =  null;
	var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' + 'chco=FFFFFF,008CFF,000000&ext=.png';
	var markers = [];
	var glookup = [];	
	var runningcounter=0;
	var eventClick=0;
	var totalMarkers=0;	
	var bounds=null;	  
	var mapzoomlevel=6;	 
	var bShowDirections=false;
	var gMapType="";
	
  function initMap(themap,thetype,theid) {
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 2,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
	gMapType=thetype;
    map = new google.maps.Map(document.getElementById(themap), myOptions);
	if (thetype=='world') {
		refreshMap(theid);
	} else if (thetype=='travel') {
		bShowDirections=true;
		initializeDirections(theid);
		
	} else if (thetype=='user') {	
		markerClusterer = null;
		$.ajax({
		  url: "/cfpages/xml/member_data.cfm?User=" + theid,
		  cache: false,
		  success: function(data) {	
				placemarkers(data);
			   }			
		 });	
		
	} else if (thetype=='linked') {	
		markerClusterer = null;
		$.ajax({
		  url: "/cfpages/resorts/google_data.cfm?Type=L&ID=" + theid,
		  cache: false,
		  success: function(data) {	
				placemarkers(data);
			   }			
		 });	
	} else if (thetype=='webcam') {	
		markerClusterer = null;
		$.ajax({
		  url: "/cfpages/resorts/google_data.cfm?Type=W&ID=" + theid,
		  cache: false,
		  success: function(data) {	
				placemarkers(data);
			   }			
		 });	
	} else if (thetype=='local') {
		markerClusterer = null;
		$.ajax({
		 url: "/cfpages/resorts/google_data.cfm?Type=L&ResortID=" + theid,
		  cache: false,
	      dataType:"xml",
		  success: function(data) {
				try
				  {
					placemarkers(data);	
					var newmarkers =XML2JS(data,"markers");
					// Remove current set of movie template items
					$("#locallist").empty();
					// Render the template items for each movie
					if (newmarkers.length > 0) {
						$("#movieTemplate" ).tmpl(newmarkers).appendTo("#locallist");
					}
					$('#requestwaiting').remove();
						
				  }
				catch(err)
				  {
					$('#requestwaiting').remove();
					alert(err);
				  }
			},
			error:function(xhr,err){
				$('#requestwaiting').remove();
				alert(err);
			}		
		});		

	}
  }

  function refreshMap(thecountry) {
	markerClusterer = null;
	$.ajax({
	  url: "/cfpages/resorts/google_data.cfm?ID=" + thecountry,
	  cache: false,
	  success: function(data) {	
			placemarkers(data);
		   }			
	 });	
  }


  var directionDisplay;
  var directionsService;
  //var directionsService = new google.maps.DirectionsService();
  var map;
 
  function initializeDirections(thelocation) {
	 directionsService = new google.maps.DirectionsService();
	 var rendererOptions = {
		draggable: true
	  };	  
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directions"));
	markerClusterer = null;
	$.ajax({
	  url: "/cfpages/resorts/google_data.cfm?Type=T&ResortID=" + thelocation,
	  cache: false,
	  success: function(data) {	
			placemarkers(data);
		   }			
	 });	
	
  }

	function setDirections(fromAddress, toAddress) {
		var request = {
			origin:fromAddress, 
			destination:toAddress,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		directionsService.route(request, function(response, status) {
		  if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
		  }
		});
	  fAddress=document.getElementById("fromAddress");
	  fAddress.value=fromAddress;			  
	}

	function getCoords(marker) {
		var loc = marker.getPoint();
		var matchll = /\(([-.\d]*), ([-.\d]*)/.exec( loc );
		if ( matchll ) { 
				var lat = parseFloat( matchll[1] );
				var lon = parseFloat( matchll[2] );
		lat = lat.toFixed(6);
		lon = lon.toFixed(6);

			var message = "geotagged geo:lat=" + lat + " geo:lon=" + lon + " "; 
			var messageRoboGEO = lat + ";" + lon + ""; 
		} else { 
			var message = "<b>Error extracting info from</b>:" + point + ""; 
			var messagRoboGEO = message;
		}
		window.alert("Check the route below");
		toAddress = document.getElementById("toAddress");
		setDirections(lat + ',' + lon, toAddress.value);				
	}	
	function printOption() {
	  fAddress=document.getElementById("fromAddress").value;		
	  tAddress=document.getElementById("toAddress").value;		
	  window.open ('http://maps.google.com/maps?f=d&saddr=' + fAddress + '&daddr=' + tAddress + '&t=h&z=8&pw=2',"mywindow");
	}

	
	
	function placemarkers(data) {
		
		if (markerCluster) {
			markerCluster.clearMarkers();
		}

        markers = [];
		glookup = [];	
		runningcounter=0;
		eventClick=0;
		totalMarkers=0;	
        var markerImage = new google.maps.MarkerImage(imageUrl, new google.maps.Size(24, 32));
		bounds = new google.maps.LatLngBounds();
		var infowindow = new google.maps.InfoWindow({content: "", size: new google.maps.Size(50,50)});
		

		$(data).find("marker").each(function() {
			var marker = $(this);
			var markertitle=marker.attr("itemname");			
			var itemtype=marker.attr("itemtype");
			var subtype=marker.attr("subtype");
			var id=marker.attr("id");
			var imageUrl="";
			var highlight=marker.attr("highlight");
			var latlng = new google.maps.LatLng(parseFloat(marker.attr("lat")),
											parseFloat(marker.attr("lng")));	
			var htmldata=$("htmldata", marker).text();
			if (itemtype == "R") {					
				if (highlight == "true") {
					extra="green";
				} else {
					extra="";
				}
				if (subtype == "1") {
					imageUrl =  "/images/mapicons/resortartificial" + extra + ".png"; 
				} else if (subtype == "2") {	
					imageUrl =  "/images/mapicons/resortindoor" + extra + ".png"; 
				} else {
					imageUrl =  "/images/mapicons/resortmtn" + extra + ".png"; 
				}														  
			  } else if (itemtype == "A") {
				imageUrl =  "/images/mapicons/smallairport.png"; 	
			} else if (itemtype == "B") {
				imageUrl =  "/images/mapicons/bar.png"; 	
			} else if (itemtype == "C") {
				imageUrl =  "/images/mapicons/coffee.png";			
			} else if (itemtype == "F") {
				imageUrl =  "/images/mapicons/restaurant"; 	
			} else if (itemtype == "H") {
				if (subtype == "S") {
					imageUrl =  "/images/mapicons/hostel.png"; 
				} else if (subtype == "A") {	
					imageUrl =  "/images/mapicons/apartment.png"; 
				} else if (subtype == "C") {	
					imageUrl =  "/images/mapicons/campingsite.png"; 
				} else {	
					imageUrl =  "/images/mapicons/hotel.png"; 					
				};					
			} else if (itemtype == "I") {
				imageUrl =  "/images/mapicons/info.png"; 					
			} else if (itemtype == "K") {
				imageUrl =  "/images/mapicons/fastfood.png"; 	
			} else if (itemtype == "N") {
				imageUrl =  "/images/mapicons/bank.png"; 					
			} else if (itemtype == "O") {
				imageUrl =  "/images/mapicons/hostel.png";			
			} else if (itemtype == "P") {
				imageUrl =  "/images/mapicons/supermarket.png";							
			} else if (itemtype == "T") {
				imageUrl =  "/images/mapicons/train.png"; 	
			} else if (itemtype == "L") {
				imageUrl =  "/images/mapicons/skilift.png"; 	
			} else if (itemtype == "U") {
				imageUrl =  "/images/mapicons/bus.png"; 	
			} else if (itemtype == "W") {
				imageUrl =  subtype; 
				//imageUrl =  "/images/mapicons/photo.png"; 				
			}
		
			var markerImage = new google.maps.MarkerImage(imageUrl, new google.maps.Size(24, 32));
	
			var tmarker = new google.maps.Marker({position: latlng, map: map, icon: markerImage, title: markertitle });
			if (highlight == "false") {
				markers.push(tmarker);
			}
			glookup[runningcounter]= id;
			runningcounter++;						
			google.maps.event.addListener(tmarker, 'click', function() {

					if (bShowDirections) {
						toAddress = document.getElementById("toAddress");
						setDirections(latlng.lat() + ',' + latlng.lng(), toAddress.value);
					};

					if (htmldata.length > 0) {
						infowindow.setContent(htmldata);
						infowindow.open(map,tmarker);						
					} else {
					
						$.ajax({
						  url: "/cfpages/xml/objectpopup.cfm?ID=" + id + "&type=" + itemtype,
						  cache: true,
						  success: function(data) {	
									infowindow.setContent(data);	
									infowindow.open(map,tmarker);															
								}			  
						 });									
					};
			  });					
			bounds.extend(latlng);		  
		 });
		
		if (gMapType=="local") {
			var iSize=1;
		} else {
			var iSize=20;
		}
		markerCluster = new MarkerClusterer(map, markers, {gridSize:iSize});
		map.fitBounds(bounds);
	}



      function clearClusters(e) {
        e.preventDefault();
        e.stopPropagation();
        markerClusterer.clearMarkers();
      }

	function getID(resortid) {			
		for (var x = 0; x < runningcounter; x++) {
			if (glookup[x] == resortid) {								
				return (x);
				break;
			}
		}					
	}	
	function loadResort(resortid) {					
		var x=getID(resortid);
		eventClick=1;				
		google.maps.event.trigger(markers[x], 'click');
		eventClick=0;
	}
	function zoomOut(resortid) {
		loadResort(resortid);
		map.fitBounds(bounds);		
	}
	function zoomIn(resortid) {
		loadResort(resortid);
		map.setZoom(13);	
	}	
	
	
	
	


// Resort finder

function resortfinderpost(whatform,destination) {
	
	showloading(destination);
	$.ajax({
	  url: "/cfpages/functions/ajaxcontroller.cfc?method=execute",
	  cache: false,
	  data: $('#' + whatform).serialize(),
	  success: function(data) {
			try
			  {
				placemarkers(data);	
				
				var newmarkers =XML2JS(data,"markers");
				
				//var xmlobject = (new DOMParser()).parseFromString(data, "text/xml");		
				//var newmarkers =XML2JS(xmlobject,"markers");
				// Remove current set of movie template items
				$("#resortlist").empty();
				// Render the template items for each movie
				if (newmarkers.length > 0) {
					$("#movieTemplate" ).tmpl(newmarkers).appendTo("#resortlist");
				}
				$('#requestwaiting').remove();
					
			  }
			catch(err)
			  {
			  	$('#requestwaiting').remove();
				alert(err);
			  }
		},
		error:function(xhr,err){
			$('#requestwaiting').remove();
			alert(err);
		}		
	});		
	return false;
}	

 // convert XML data into JavaScript array of JavaScript objects
function XML2JS(xmlDoc, containerTag) {
    var output = new Array();
    var rawData = xmlDoc.getElementsByTagName(containerTag)[0];
	
	//var rawData = xmlDoc.getElementsByTagName(containerTag);
	
    //var rawData = xmlDoc;
	var i, j, oneRecord, oneObject;
    for (i = 0; i < rawData.childNodes.length; i++) {
        if (rawData.childNodes[i].nodeType == 1) {
            oneRecord = rawData.childNodes[i];
            oneObject = output[output.length] = new Object();
            for (j = 0; j < oneRecord.childNodes.length; j++) {
                if (oneRecord.childNodes[j].nodeType == 1) {
                    try
			  		{
					oneObject[oneRecord.childNodes[j].tagName] = 
                        oneRecord.childNodes[j].firstChild.nodeValue;   
				}
				catch(err)
				  {
					
				  }						
                }
            }
        }
    }
    return output;
}

// user tools - add location to myplaces
function addtoplace(objecttype,objectid,statustype,callingdiv) {
		loadSection(callingdiv,"user.addplace","objecttype="+objecttype+"&objectid="+objectid+"&statustype="+statustype);
		//DWREngine._execute(_cfscriptLocation, null, 'addtoplace', objecttype,objectid,statustype, addtoplaceResult);	
}

