﻿/* Kleenheat Google Map / Store Locator Javascript */

// start Google Maps JS
var map;
var gdir;
var geocoder = null;
var addressMarker;

// Debounce function used for ajax search suggestions
Function.prototype.debounce = function (threshold, execAsap) {
    var func = this, // reference to original function
        timeout; // handle to setTimeout async task (detection period)
    // return the new debounced function which executes the original function only once
    // until the detection period expires
    return function debounced () {
        var obj = this, // reference to original context object
            args = arguments; // arguments at execution time
        // this is the detection function. it will be executed if/when the threshold expires
        function delayed () {
            // if we're executing at the end of the detection period
            if (!execAsap)
                func.apply(obj, args); // execute now
            // clear timeout handle
            timeout = null; 
        };
        // stop any current detection period
        if (timeout)
            clearTimeout(timeout);
        // otherwise, if we're not already waiting and we're executing at the beginning of the detection period
        else if (execAsap)
            func.apply(obj, args); // execute now
        // reset the detection period
        timeout = setTimeout(delayed, threshold || 100); 
    };
}

$(document).ready(function() {
    $("input.slPostcode").attr("autocomplete","off");
    var wcMap = loadMap();	
	
    $("#submitDirections").click(function(){				
	    if( $("#fromAddress").val() == '' ){ alert('Please enter a from address'); return false; };
	    if( $("#toAddress").val() == '' ){ alert('Please enter a to address'); return false; };
		
	    setDirections( $("#fromAddress").val(), $("#toAddress").val(), 'en');
	    return false;
    });
    
    SetStateDisplay($(".SelectedState").val());

    var postcodeText = "Eg: 6000 or Perth";
    var radiusText = "Radius (kms)";
    
    $(".slPostcode").focus(function(){
        if ($(".slPostcode").val() == postcodeText) { $(".slPostcode").val(""); }
        $("#maphover a").removeClass("selected");
        if ($(".SelectedState").val() != "" && $(".SelectedPostcode").val() == "")
        {
            $(".SelectedState").val("");
        }
    });
    
    $(".slPostcode").blur(function(){
        if ($(".slPostcode").val() == "") { $(".slPostcode").val(postcodeText); };
    });
    $(".slRadius").focus(function(){
        if ($(".slRadius").val() == radiusText) { $(".slRadius").val(""); }
        $("#maphover a").removeClass("selected");
        if ($(".SelectedState").val() != "" && $(".SelectedPostcode").val() == "")
        {
            $(".SelectedState").val("");
        }
    });
    $(".slRadius").blur(function(){
        if ($(".slRadius").val() == "") { $(".slRadius").val(radiusText); };
    });
    
    // ajax suggested search 
	$("input.slPostcode").keyup(function(){	
	
	    if ( !/^\d+$/i.test($("input.slPostcode").val()) )
        {
            $("input.SelectedPostcode").val("");
            $("input.SelectedState").val("");
            $("input.SelectedTown").val("");
        }
		if ($("input.slPostcode").val() == "")
        {
            HideSuggestedText();
        }
        				
		var criteria = $("input.slPostcode").val();
		if (criteria != "")
		{
		    $("div#suggested").fadeIn();
		    $.post("/UserControls/Kleenheat/SuggestedLocations.aspx", {criteria:criteria}, function(data) {	
			    $("div#suggestedContent").html(data);
                if ($("div#suggestedContent").find("ul").html() == null)
                {
                    $("div#suggested").hide();
                    $("div#suggestedContent").html("");
                }

		    });
		}
	}.debounce(500)); 
    
});

function loadMap() {
  if (GBrowserIsCompatible()) {      
    map = new GMap2(document.getElementById("maparea"));

    gdir = new GDirections(map, document.getElementById("directions"));
    GEvent.addListener(gdir, "error", handleErrors);  
	
    var icon = new GIcon();
    var markerHTML = "";

    map.setCenter(new GLatLng(-31.889219,115.916061), 15);
	
    map.addControl(new GSmallMapControl());
    //map.addControl(new GScaleControl());
	
    map.checkResize();
	
    return map;
  }
}

function setDirections(fromAddress, toAddress, locale) {
  gdir.load("from: " + fromAddress + " to: " + toAddress,
		    { "locale": locale });
}

function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
   
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	
   else alert("An unknown error occurred.");
   
}

function createMarker(point,icon,html) {
    var marker = new GMarker(point,icon);
    GEvent.addListener(marker, "mouseover", function() {
      marker.openInfoWindowHtml(html);
    });
    return marker;
}

function swapMap(map,mapType) {
    map.checkResize();
    return map.setMapType(mapType);
}

function getMapType(map) {
    return map.getCurrentMapType(map);
}

$(window).unload(function() {
    GUnload();
});

function backToMap() {
    document.getElementById('store_locator_head').style.display = 'none';
}

function SelectState(state)
{
    $("#maphover a").removeClass("selected");
    $(".SelectedState").val(state);
    SetStateDisplay($(".SelectedState").val());
    
    $(".slPostcode").val("Eg: 6000 or Perth");
    $(".slRadius").val("Radius (kms)");
    $("input.SelectedPostcode").val("");
    $("input.SelectedTown").val("");
    HideSuggestedText();
    return false;
}

function SetStateDisplay(state)
{
    $("#maphover a").removeClass("selected");
    if ( $(".SelectedState").val() == "WA" ) {
        $("#maphover a.wa").addClass("selected");
    } else if ( $(".SelectedState").val() == "NT" ) {
        $("#maphover a.nt").addClass("selected");
    } else if ( $(".SelectedState").val() == "VIC" ) {
        $("#maphover a.vic").addClass("selected");
    } else if ( $(".SelectedState").val() == "NSW" ) {
        $("#maphover a.nsw").addClass("selected");
    } else if ( $(".SelectedState").val() == "SA" ) {
        $("#maphover a.sa").addClass("selected");
    } else if ( $(".SelectedState").val() == "QLD" ) {
        $("#maphover a.qld").addClass("selected");
    } else if ( $(".SelectedState").val() == "TAS" ) {
        $("#maphover a.tas").addClass("selected");
    } 
}

// Form Validation
function ValidateStoreSearchForm()
{
    var aErrors = new Array(0);

    // check all fields
    if ( 
        $("input.SelectedState").val() == "" && 
        ( $("input.slPostcode").val() == "" || $("input.slPostcode").val() == "Eg: 6000 or Perth" ) && 
        $("input.SelectedPostcode").val() == ""
        )
    {
        aErrors.push("Please enter some search criteria by either selecting a state or postcode / town");
    }
        
    // if radius, check numeric
    if ( $("input.slRadius").val() != ""  && $("input.slRadius").val() != "Radius (kms)" )
    {
        if ( !/^\d+$/i.test($("input.slRadius").val()) )
            aErrors.push("Please ensure you enter a numeric value for the radius");
    }
    
    // if state, check filter options
    if ( $("input.SelectedState").val() != "" )
    {
        if ( $("input.SelectedState").val() == "WA" || $("input.SelectedState").val() == "NT" )
        {
            if ( $("input.SelectedBusinessUnit").val() == "KleenheatAppliances" || $("span.kleenheatAppliances input").is(":checked") ) // kleenheatappliances
            {
                aErrors.push("Kleenheat Gas Appliance services are not available in WA or NT");
            }     
        }
        if ( $(".SelectedState").val() != "WA" && $("input.SelectedState").val() != "NT" )
        {
            if ( $("input.SelectedBusinessUnit").val() == "GasHouse" || $("span.gashouse input").is(":checked")) // gashouse
            {
                aErrors.push("Gas House services are available in WA and NT only");
            }     
            if ( $("input.SelectedBusinessUnit").val() == "AutoGas" || $("span.autogas input").is(":checked"))  // autogas
            {
                aErrors.push("AutoGas services are available in WA and NT only");
            }
        }
    }
    
    // if postcode, check filter options
    if ( $("input.slPostcode").val() != "" )
    {
        var postcode = $("input.slPostcode").val();
        if (postcode > 5999 && postcode < 7000) {
            if ( $("input.businessUnit").val() == "kleenheatappliances" )
            {
                aErrors.push("Kleenheat Gas Appliance services are not available in WA or NT");
            }
        }
        if (postcode < 1000) {
            if ( $("input.businessUnit").val() == "kleenheatappliances" )
            {
                aErrors.push("Kleenheat Gas Appliance services are not available in WA or NT");
            }
        }
        if (postcode > 1000 && (postcode < 5999 || postcode > 7000)) {
            if ( $("input.businessUnit").val() == "gashouse" )
            {
                aErrors.push("Gas House services are available in WA and NT only");
            }     
            if ( $("input.businessUnit").val() == "autogas" )
            {
                aErrors.push("AutoGas services are available in WA and NT only");
            }
        }
    }
    
    if (aErrors.length) {
	    displayErrorsAlert(aErrors);
	    return false;
	}
	
	return true;
}


function SetSuggestionValues(postcode, suburb, state)
{
    $("input.slPostcode").val(suburb + ", " + state + " " + postcode);
    $("input.SelectedPostcode").val(postcode);
    $("input.SelectedState").val(state);
    $("input.SelectedTown").val(suburb);
    HideSuggestedText();
}

function HideSuggestedText()
{
    $("div#suggested").fadeOut(function(){ $("div#suggestedContent").html(""); });
}

function showAddress(address, city, state, postcode, name) {
    var setAddress = address + ", " + city + " " + state + " " + postcode;
    
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(setAddress,
    function(point) {
        if (!point) {
            
        } else {
            map.setCenter(point, 13);
            markerHTML = "<div class='glocation'>";
            markerHTML += "<b>" + name + "</b>";
            markerHTML += "<div class='gadd'>" + address;
            markerHTML += "<br/>" + city; 
            markerHTML += " " + state + " " + postcode + "<\/div>";
            markerHTML += "<\/div>";

            var marker = new GMarker(point);
            map.addOverlay(marker);
            map.checkResize();
        }
    }
    );
}
// end Google Maps JS
