//[Arlin] To avoid the IE memory leap when using Jquery with Ajax.net.
(function($) {
$.fn.Disposable = function(cln) 
        {		
            return this.each(function() 
            {			
                var el = this;			
                if (!el.dispose) {				
                    el.dispose = cleanup; // will be called by 	Microsoft for cleanup				
                    $(window).bind("unload", cleanup);
                    }
                    
                function cleanup()
                {				
                    if (!el)					
                        return;				
                    $(el).unbind();				
                    $(window).unbind("unload", cleanup);				
                    el.dispose = null;
                    el = null;			
                 };
             });
         };
})(jQuery);
  
   function loadMapInfo()
            {
                var action; //area search = 1, zip search = 2
		var value; //value being passed in to the server
		
		 $("a").css("cursor", "pointer");

		 $("a.changesearch").click(function() {
			$("#divWhen").toggle();
			$("#divMapPart").toggle();
			$("#divFacility").toggle();
			$("a.changesearch").toggle();
			$("img.whereimage").toggle();
		}).Disposable();
		 
		$("[id$='btnSearch']").click(function() {
		  //alert('hello');
		  var area = $("[id$='_ddlRegion']").val();
		  var zip = '';
		  
		  var basicsearch=true;
		  var searchonzip='';
		  var searchdate=$("[id$='_txtSearchStartDate']").val();
		  var searchtime=$("[id$='_ddlTime']").val();
		  var facilityname = '';
		  
		  searchonzip=false;
		  
		if ($("[id$='divFacility']").is (':visible') && $("[id$='divFacility']").parents (':hidden').length == 0)
		    {basicsearch=false;
			 facilityname=$("[id$='_txtFacilityName']").val();
			 }

		  var count=0;
		  var qs='';
  
		  if (qs=='')
			qs='adv';
		  $.ajax({
		   type: "POST",
		   url: "index.aspx",
		   data: {qs:qs, area: area, zip: zip, baseurl: serverVars.baseurl, basicsearch: basicsearch, searchonzip: searchonzip, searchdate: searchdate, searchtime: searchtime, facilityname: facilityname},  //data: {qs:qs}, 
		   success: function(msg){	//alert(msg);	
			//alert(msg);
			window.location=msg;
			}
		   });
		}).Disposable();
		

		    action='1';
		    value= $("[id$='_ddlRegion']").val();
	        getcourselist(value,action,1);
	        
	        var hfsearchMode=$("[id$='_hfSearchMode']").val();
	        if(hfsearchMode=="basic")
	        {
	            $("#divWhen").toggle();
			    $("#divMapPart").toggle();
			    $("#divFacility").toggle();
			    $("a.changesearch").toggle();
			    $("img.whereimage").toggle();
	        }
            }
            
    $(function(){
        loadMapInfo();
    })

	function getcourselist(value,action,flag){
	$.ajax({
	   type: "POST",
	   url: "index.aspx",
	   data: {action: action, value: value, area: serverVars.area, postalcode: serverVars.postalcode, ip: serverVars.ip, baseurl: serverVars.baseurl, path: serverVars.path, urlpath: serverVars.urlpath},
	   success: function(msg){
	    if(flag==1)
		    loadmap(msg);
		}
	});
	}
	
	function getmapcenter(map){
	//debugger
	var action; //area search = 1, zip search = 2
	var value; //value being passed in to the server
		action='1';
		value= $("[id$='_ddlRegion']").val();
	$.ajax({
	   type: "POST",
	   url: "index.aspx",
	   data: {action: action, value: value, type: '1'},
	   success: function(msg){	//alert(msg);	
	   var myObject = eval( msg);
	   if(mapCenterInfo.latitude==0 && mapCenterInfo.longitude==0)
	   {
	     var valueSelected= $("[id$='_ddlRegion']").val();
	       if (valueSelected=='2')
	        map.setCenter(new GLatLng(38.6,-98), 3); //default to US map
	       else
	        {
	            if (valueSelected=='1')
	              map.setCenter(new GLatLng(60,-95), 3); //default to CA map
	            else  //'select an area/region'
	              map.setCenter(new GLatLng(38.6,-98), 2); //default to USA/Canada map
	        }
	    }
	   else
		    map.setCenter(new GLatLng(mapCenterInfo.latitude,mapCenterInfo.longitude), 9);
		}
	});
	}
	
	function loadmap(msg){
	   var myObject = eval( msg);
	   	   //alert('hi');
	   if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
		var bounds = new GLatLngBounds;
        map.addControl(new GSmallMapControl());
		map.removeMapType(G_SATELLITE_MAP);
        map.addControl(new GMapTypeControl());
		//map.disableDragging();
		map.setCenter(new GLatLng(0,0),0);
        
        // Create a base icon for all of our markers that specifies the
            // shadow, icon dimensions, etc.
            var baseIcon = new GIcon();
            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);
            baseIcon.infoShadowAnchor = new GPoint(18, 25);
			
			var list = $("#courselist").empty();

	        function createCourseList(marker,name,id){
	         // // Create a new list item
			 var item =  $("<li></li>");
			// The checkbox, assign a unique id to it
			var checkbox = $("<input type='checkbox'></input>")
				.attr("name","course")
				.attr("value", id)
				.attr("id", "chkCourses_"+id)
				.attr("checked","checked")
				.click(function() {
				if (marker.isHidden()) {
					marker.show();
				} else {
					marker.hide();
				}
				 }).Disposable();

			// Label that allows us to click on the text also
			label = $("<label>"+name+"</label>")
							.attr("for", "chkCourses_"+id);

			// Append the checkbox and label to the <li>-item
			item.append(checkbox);
			item.append(label);

			list.append(item);
			//Append the <li>-item to the <ul>-list

			}
            
			var markercount = 0;
            function createMarker(point, name, streetaddress, locationaddress, urladdress, photo, locationNumber,id) {
              var icon = new GIcon(baseIcon);  
              icon.image = "images/markers/marker" + ".png";
              var marker = new GMarker(point, icon);
              GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml('<span class="mapBubble_courseTitle">' + name + '</b><br><img src="'+photo+'" align="left" width="60px" height="45px"/>&nbsp;<span class="textNormal">' + streetaddress + '</span><br>&nbsp;<span class="textNormal">' + locationaddress + '</span><br>&nbsp;' + '<a class="textNormal" href="'+urladdress+'">Tee Times & Course Info</a>');
              });
			  bounds.extend(point);  //this is for dynamic centering
			  createCourseList(marker,name,id);  //this hooks up the check box click event with the marker being created
			  markercount++
              return marker;
            }
			
            for (var i = 0; i < mapCourseInfo.locations.length; i++) { //alert(i);
              var point = new GLatLng(mapCourseInfo.locations[i].latitude,mapCourseInfo.locations[i].longitude);
              map.addOverlay(createMarker(point, mapCourseInfo.locations[i].name, mapCourseInfo.locations[i].streetaddress, mapCourseInfo.locations[i].locationaddress, mapCourseInfo.locations[i].urladdress, mapCourseInfo.locations[i].photo, i+1,mapCourseInfo.locations[i].id));
           }
		   
		   //This is added because IE6 does not check the boxes before they are added to the DOM
		  $("input:checkbox").each(
		  function(){
		      this.checked=true;
		  }).Disposable();
		  
		   //if there are markers, the dynamically center and zoom the map, otherwise use the value defined above
		   if (markercount > 0){
		   map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds) - 1); 
		   }   
		   else{
		   getmapcenter(map); //get the center from the db
		   }
      }
	}
	
	function RegionAreaSelectedChanged(ddlID){
		var obj = document.getElementById(ddlID);
		if ("Canada" == obj.options[obj.selectedIndex].text || "United States" == obj.options[obj.selectedIndex].text)
		{
			obj.selectedIndex = obj.selectedIndex + 1;
		}
	    //var hfSearchMode = document.getElementById('<%=hfSearchMode.ClientID.Replace("$","_")%>');
        document.getElementById('divMasterForGoolgMap').style.display = "";
	    if ($("[id$='divFacility']").is (':visible') && $("[id$='divFacility']").parents (':hidden').length == 0)
	    {
	        $("[id$='_hfSearchMode']").val("basic");
	    }
	    else
	    {
	        $("[id$='_hfSearchMode']").val("adv");
	    }
	    return true;
	}
	
window.onunload=GUnload;