/**
 * Global variables storing results of the 
 * directions AHs/HLs. 
 */
var latStart;
var lonStart;
var latEnd;
var lonEnd;
var addressStart;
var addressEnd;


/**
 * This function is executed when the document
 * finished loading. 
 * 
 */
$(document).ready(function (){
    /* Fix for IE6: fixing $ ref for JQuery */
    window.$ = window.jQuery;



    /******************************\
    |      JQuery TABS             |
    \******************************/
    $("#tabs").tabs({
        load: function(event, ui) {
        $(".vertical_openads").openads({adServerURL: adServerURL,zoneId: adZone32, width:"120", height: "240"});
        $(".side_openads").openads({adServerURL: adServerURL,zoneId: adZone37, width:"300", height: "250"});
        $(".bottom_openads").openads({adServerURL: adServerURL,zoneId: adZone33, width:"728", height: "90"});
    }
    });

    $("#footer-tabs").tabs({
        select: function(event, ui) {
        $("#footerDiv").hide();
        $("#tabs").show().tabs('select', ui.index);
        return false;
    }
    });

    $("#backhome-link").click(function() {
        $("#footerDiv").hide();
        $("#tabs").show().tabs('select', 0);
        return false;
    });


    $("#homeLink").click(function() {
        $("#footerDiv").hide();
        $("#tabs").show().tabs('select', 0);
        return false;
    });

    $("#aboutUsLink").click(function() {
        $("#footerDiv").hide();
        $("#tabs").show().tabs('select', 2);
        return false;
    });

    $("#help_nav").click(function() {
        $("#helpLink").trigger('click');
    });


    $(".footer-link").click(function() {
        $("#tabs").hide();
        $("#footerDiv").show();
        $("#footerDiv > #footerContainer").load(this.href, function(){
            $(".vertical_openads").openads({adServerURL: adServerURL,zoneId: adZone34, width:"120", height: "240"});
            $(".side_openads").openads({adServerURL: adServerURL,zoneId: adZone62, width:"300", height: "250"});
            $(".bottom_openads").openads({adServerURL: adServerURL,zoneId: adZone33, width:"728", height: "90"});
        });
        //$('html,body').animate({scrollTop: targetOffset}, 1000);
        $(window).scrollTop();
        return false;
    });


    /******************************\
    |      JQuery OpenAds          |
    \******************************/
    $(".vertical_openads").openads({adServerURL: adServerURL,zoneId: adZone32, width:"120", height: "240"});
    $(".side_openads").openads({adServerURL: adServerURL,zoneId: adZone37, width:"300", height: "250"});
    $(".bottom_openads").openads({adServerURL: adServerURL,zoneId: adZone33, width:"728", height: "90"});
    $(".free_HL_ad").openads({adServerURL: adServerURL,zoneId: adZoneHL, width:"90", height: "70"});
    /******************************\
    |      OPEN LAYERS SETUP       |
    \******************************/

    map = init_map();
    rssMetadata.setMetaData();
    /******************************\
    |      HOT LOCALITY SETUP      |
    \******************************/
    hotLocality = new AddressHelper({delay: 1000, geocode: true, geocodeResult: getMap,maxReturnValues: 100,autoSearch: true,scroll: true,excludeUngeocoded:true});
    if (hotLocality.sanityCheck()) {hotLocality.create();}
    /******************************\
    |          DIRECTIONS          |
    \******************************/
    init_directions();
    /******************************\
    |            MARKERS           |
    \******************************/
    init_markers();
	
    /******************************\
    |       Center and zoom        |
    \******************************/
    var lon = getUrlParameter("lon");
    var lat = getUrlParameter("lat");
    var zoom = getUrlParameter("zoom");
	
    if((!lon || !lat) && startLat && startLon && endLat && endLon) //if no coordinates and have a bounds...use the bounds
    {   
	    
		
		function clickLabel2() {
                            return function() {
								map.zoomToExtent(markers.getDataExtent());
                            };
                        };

        setMaplabel(getUrlParameter("label"), clickLabel2());	

        
        zoomToExtent = true;
    }
    else
    {
        useGetIPCoord = false;
        //if no coordinates set the default
        if(!lon || !lat)
        {
            lon = 138.088;
            lat = -28.246;
            useGetIPCoord = true;
        }
        else
        {
            lon = parseFloat(lon);
            lat = parseFloat(lat);
        }
        //if no zoom set the default
        if(!zoom) {
            zoom = 3;
        } else {
            zoom = parseInt(zoom);
        }
            
        map.setCenter(new OpenLayers.LonLat(lon,lat).transform(proj_4326, map.getProjectionObject()),zoom);

        if(useGetIPCoord) {
            getIPCoord();
        }
		
		function clickLabel(lat, lon) {
                            var point = new OpenLayers.LonLat(lon, lat).transform(proj_4326, map.getProjectionObject());
                            return function() {
                                map.panTo(point);
                            }
                        };

        setMaplabel(getUrlParameter("label"), clickLabel(lat, lon));
    }

    initHLsAndAHs();

});

/**
 * Function to initialise all HL/AH instances. 
 * 
 */
function initHLsAndAHs(){

    var addressHelper_start = new AddressHelper({prefix: 'start',minChars:0, type: 'addresshelper', geocode: true, geocodeResult: startGeocodeFound,excludeUngeocoded:true,maxReturnValues: 100,autoSearch: true,scroll: true});

    if (addressHelper_start.sanityCheck()) {
        addressHelper_start.create();
    }

    var addressHelper_end = new AddressHelper({prefix: 'end',minChars:0, type: 'addresshelper', geocode: true, geocodeResult: endGeocodeFound,excludeUngeocoded:true,maxReturnValues: 100,autoSearch: true,scroll: true});

    if (addressHelper_end.sanityCheck()) {
        addressHelper_end.create();
    }

    var hotLocality_start = new AddressHelper({ prefix: 'start', id:'address', geocode: true,  geocodeResult: startGeocodeFound,excludeUngeocoded:true,maxReturnValues: 100,autoSearch: true,scroll: true});

    if (hotLocality_start.sanityCheck()) {
        hotLocality_start.create();
    }

    var hotLocality_end = new AddressHelper({ prefix: 'end', id:'address', geocode: true,  geocodeResult: endGeocodeFound,excludeUngeocoded:true,maxReturnValues: 100,autoSearch: true,scroll: true});

    if (hotLocality_end.sanityCheck()) {
        hotLocality_end.create();
    }

    /*var directoryHL = new AddressHelper({ id:'directoryHLInput', geocode: true,  geocodeResult: directoryHLCallback,excludeUngeocoded:true,maxReturnValues: 100,autoSearch: true,scroll: true});
    directoryHL.get('fields').freeFormAddress.set({elementId: 'directoryHLId'});

    if (directoryHL.sanityCheck()){
        directoryHL.create();
    }*/
}


/**
 * Function to clear all fields of an
 * AH instance.
 * 
 * @param addressHelper
 * @return
 */
function clearAHFields(addressHelper)
{
    var prefix = "#" + addressHelper.get("prefix");
    var fields = $(prefix+"_stateField")
    .add(prefix+"_suburbField")
    .add(prefix+"_streetNameField")
    .add(prefix+"_streetTypeField")
    .add(prefix+"_streetNumberField")
    .add(prefix+"_flatNumberField");
    fields.val("");
}


/**
 * Executed when AH/HL found 
 * start coordinates of the route.
 * 
 * @param lon
 * @param lat
 * @return
 */
function startGeocodeFound(lon,lat)
{
    latStart = lat;
    lonStart = lon;
    addressStart = this.current;
    $("#start_matchInfo")
    .html("Address Located")
    .animate({
        color:"lime"
    },750)
    .animate({
        color:"#0B3E9B"
    },750);
}


/**
 * Executed when AH/HL found 
 * end coordinates of the route. 
 *
 * @param lon
 * @param lat
 * @return
 */
function endGeocodeFound(lon,lat)
{
    latEnd = lat;
    lonEnd = lon;
    addressEnd = this.current;
    $("#end_matchInfo")
    .html("Address Located")
    .animate({
        color:"lime"
    },750)
    .animate({
        color:"#0B3E9B"
    },750);
}


/**
 * Switches from HL to AH for the
 * start address.
 * 
 * @return
 */
function show_start_advanced()
{
    $("#addressHelper_start_frame").animate({
        height:"240px"
    },{queue:true, duration: 1000});

    $("#hotLocality_start").animate({opacity:0},
            {
        complete:function(){
        $("#hotLocality_start").css({height:"0px"});
        $("#addressHelper_start").css({height:""}).animate({opacity:1},500);
    },duration:500
            });


}


/**
 * Switches from HL to AH for the
 * end address.
 * 
 * @return
 */
function show_end_advanced()
{
    $("#addressHelper_end_frame").animate({
        height:"240px"
    },{queue:true, duration: 1000});

    $("#hotLocality_end").animate({opacity:0},
            {
        complete:function(){
        $("#hotLocality_end").css({height:"0px"});
        $("#addressHelper_end").css({height:""}).animate({opacity:1},500);
    },duration:500
            });


}


/**
 * Switches from AH to HL for the
 * start address.
 * 
 * @return
 */
function show_start_simple()
{
    $("#addressHelper_start_frame").animate({
        height:"80px"
    },{queue:true, duration: 1000});

    $("#addressHelper_start").animate({opacity:0},
            {
        complete:function(){
        $("#addressHelper_start").css({height:"0px"});
        $("#hotLocality_start").css({height:""}).animate({opacity:1},500);
    },duration:500
            });


}


/**
 * Switches from AH to HL for the
 * end address.
 * 
 * @return
 */
function show_end_simple()
{
    $("#addressHelper_end_frame").animate({
        height:"130px"
    },{queue:true, duration: 1000});

    $("#addressHelper_end").animate({opacity:0},
            {
        complete:function(){
        $("#addressHelper_end").css({height:"0px"});
        $("#hotLocality_end").css({height:""}).animate({opacity:1},500);
    },duration:500
            });
}
 
 /**
  * Sets up the URL parameters to send to the index.jsp page
  */
 function passDirections(){

     //do we have lat lons for the starting and ending addresses?
     if (latStart == null || latStart == '' || lonStart == null || lonStart == '') {
         alert("Please enter a starting address");
         return;
     // Check that the coordinate fields contain numbers and not 0 or text
     } else if (!validCoords(latStart, lonStart)) {
         alert("Sorry, but we could not get coordinates for the starting location you entered." + "\n" + "Please enter more information into the starting address fields");
         return;
     } else if (latEnd == null || latEnd == '' || lonEnd == null || lonEnd == '') {
         alert("Please enter a destination address");
         return;
     } else if (!validCoords(latEnd, lonEnd)) {
         alert("Sorry, but we could not get coordinates for the destination you entered." + "\n" + "Please enter more information into the destination address fields");
         return;
     }

     // Check that the distance between the start and end points is less than 2000Kms - distance specified by TC 31/10/2007 - see Jira issue FREEMAPS-35
     var distance;
     var d, dr;
     with (Math) {
         dr = 0.017453292519943295; // 2.0 * PI / 360.0; or, radians per degree
         d = cos(parseFloat(lonEnd) * dr - parseFloat(lonStart) * dr) * cos(parseFloat(latEnd) * dr - parseFloat(latStart) * dr);
         distance = acos(d) * 6378.137; // equatorial radius
     }

     if (distance > 2000 ) {
         alert("Please choose 2 locations that are less then 2000 kilometers apart");
         return;
     }
     parent.document.location = "index.jsp?startLat=" + latStart + "&startLon=" + lonStart + "&endLat=" + latEnd + "&endLon=" + lonEnd + "&label=" + addressStart + " to " + addressEnd;
 }
