/*jslint strict:true, evil: true, onevar: true, nomen: false  */ /*global $, jQuery, console, hbx, window, ndm, document, GBrowserIsCompatible, GUnload, alert, GEvent, GSize, GIcon, GLargeMapControl, GLatLng, GMap2, GMapTypeControl, GPoint, LabeledMarker, clearTimeout, setTimeout, setInterval, clearInterval, tb_remove */

"use strict";

/**
 * Motormouth services used by CG_petrol prices:
 * v1 setup
 * called in getAverage()
 * NationalSummary => natSum
 * NationalDailyPriceAverages => natDaily
 * deprecated -> CityPricingSummary => citySum
 * good -> CityWeeklyPriceHistory => cityWklHist & cityWklHistLcl
 *
 * called in CG_performPriceQuery
 * PostcodeSearchGeocodeMultiFuel
 *
 * v2 setup:
 * CityWeeklyPriceHistory
 * NationalSummary
 * NationalDailyPriceAverages
 * PostcodeSearchGeocodeMultiFuel
 *
 * CityPricingSummary doesn't appear to exist anymore.
 * CitySummary is probably the alternative.
 *
 * CPS v1 response
 *
 jQuery.fn.CG_useAverageData({"ResultData":{"ResultCode":"0","ResultMsg":"Successful","Data":[{"MinPrice":"1269","MaxPrice":"1497","AvgPrice":"1434","CheapestDay":"Saturday"}]}});
 */

/* GLOBAL VARIABLES */
var curURL = document.location.toString(),
    curQuery = document.location.search,
    stationPopInfo = "",
    curPostcode,
    mouseOverMapPin = false,
    mouseX,
    mouseY,
    locationFieldID = "location",
    userBrowser = "",
    buildNational = true,
    postCodesLoaded = false,
    openVcard,
    lookupJSON,
    extraPostcode,
    addPostcodeNum,
    listHTML = "",
    CG_showMap = true,
    CG_mapIcon,
    CG_mapBuilt = false,
    map,
    allData = [],
    cleanData = [],
    cheepestFuel,
    dataReady = false,
    stations = [],
    stationsVal = "",
    stationsString = "",
    addresses = [],
    setAvgType = "",
    avgFuelTime,
    setAvgFuelType = 2,
    natSummary = [],
    chartData = [],
    postCodeMatches = [],
    chartNum = 0,
    timedAnim,
    curHoverAnim = 0,
    prevHoverAnim = 0,
    activeCity = "",
    initCity = "Sydney",
    setCity = "",
    setPostCode = "",
    cities = ["Adelaide","Brisbane","Gold Coast","Hobart","Melbourne","Perth","Sunshine Coast","Sydney"],
    noCities = 8,
    CG_postcodes = [],
    allStatesChart = true,
    pauseBuild,
    searchExpanded = false,
    bugWin,
    petrolFound = false,
    ieAlertShown = false,
    cookieAttFound = false,
    cookieAttValue = "",
    ieAlertInit = false,
    alertMode = false
;

/* Load the postcodes script */
$.ajax({
    url:"/javascript/screenspecific/CG_postcodes.js",
    dataType: "script",
    success: function(){ postCodesLoaded = true; },
    cache: true
});

/* Use the following function for debugging */
jQuery.fn.CG_alert = function(msg){
    if(alertMode){
//        console.info(msg);
    }
};

function checkIndependentStation(pStat){
    var indStation = false,
        indStations = ["Mobil","7 Eleven","Budget","Gogas","Liberty","Metro Fuel","Prime Petroleum","Speedway","United","Volume Plus","Freedom Fuels","IFS","Matilda","Neumann","Apco","Better Choice","Foodies","Fuel Zone","Fueline","SAFF","Gull","Peak","Wesco Fuels","On the Run","Southern Cross","Uptown Fuel","Energy Fuels"];

    jQuery.each(indStations,function(index){
        if(pStat.indexOf(indStations[index])!== -1){
            indStation = true;
        }
    });
    return indStation;
}

/* VCARD FUNCTIONS */
function getVCardExtraClass(pStat){
    var vCardExtraClass = "";

        if(stationsString.indexOf(pStat) !== -1){
            vCardExtraClass = "vcard_refined";
        }

        if(stationsString.indexOf("Independent") !== -1 && checkIndependentStation(pStat)){
            vCardExtraClass = "vcard_refined";
        }

    return vCardExtraClass;
}

function refineVCards(){
    var siteName, refineFound = false, refineClass = "";
    $(document).CG_formStationValue();

    $("#CG_search_summary_refine").html("<strong>Stations:</strong><span>"+stationsString+"</span>");

    /* Loop through all the vcards and add the extra class if required */
    $("li.vcard").removeClass("vcard_refined");

    $("li.vcard").each(function(){
        siteName = $(this).find(".fn span:eq(0)").text().split("/").join(" ");

        refineClass = getVCardExtraClass(siteName);
        $(this).addClass(refineClass);
        if(refineClass === "vcard_refined"){
            refineFound = true;
        }
    });

    if(!refineFound && stationsString !== "All stations"){
        $("#CG_search_summary_refine").html("<strong>Stations:</strong><span>"+stationsString+"</span><br/><p class='CG_no_refine_msg'>No results for "+stationsString+" were found</p>");
    }
}

function CG_closeStationPop(){
    $("#CG_map_popup").css("display","none");
}

function toggleVCard(cardNum,fromMap,e){
    var cardID = "vcard"+cardNum,
        iconID = "CG_map_icon_"+cardNum,
        iconTop,
        iconLeft,
        mapTop,
        mapHeight,
        mapWidth,
        mapPan,
        mapPanX,
        mapPanY,
        maxLeft = 880,
        minLeft = 390,
        panX,
        panY;

    if(cardID !== openVcard && openVcard !== ""){
        //Close the open vcard first
        $("#"+openVcard).removeClass("vcard_hover");
        if(userBrowser === "ie6.0"){
           $("#"+openVcard).children("p.adr").css("display","none");
        }else{
           $("#"+openVcard).children("p.adr").slideUp("slow");
        }
    }

    if($("#"+cardID).children("p.adr").css("display") === "block" && !fromMap){
        $("#"+cardID).removeClass("vcard_hover");
        if(userBrowser === "ie6.0"){
           $("#"+cardID).children("p.adr").css("display","none");
        }else{
           $("#"+cardID).children("p.adr").slideUp("slow");
        }
        openVcard = "";
        CG_closeStationPop();
    }else{
        $("#"+cardID).addClass("vcard_hover");
        if(userBrowser === "ie6.0"){
           $("#"+cardID).children("p.adr").css("display","block");
        }else{
           $("#"+cardID).children("p.adr").slideDown("slow");
        }
        openVcard = cardID;

        stationPopInfo = $("#"+ cardID + " h4").html();
        stationPopInfo = stationPopInfo + "<p>" + $("#"+ cardID + " p.adr").text() + "</p>";
        stationPopInfo = stationPopInfo + '<a href="javascript:CG_closeStationPop()">close X</a>';

        // Get the screen position of the icon
        iconTop = $("#"+iconID).offset().top;
        iconLeft = $("#"+iconID).offset().left;
        mapTop = $("#CG_price_results_map").offset().top;
        mapHeight = $("#CG_price_results_map").height();
        mapWidth = $("#CG_price_results_map").width();

        // Check the popup is within the boundary of the map
        if(iconTop < mapTop || iconTop > (mapTop + mapHeight) || iconLeft < minLeft || iconLeft > maxLeft){
            // The map needs to be panned
            panX = 0;
            if(iconLeft < minLeft){ panX = "+1"; }
            if(iconLeft > maxLeft){ panX = "-1"; }

            panY = 0;
            if(iconTop < mapTop){ panY = "+1"; }
            if(iconTop > (mapTop + mapHeight)){ panY = "-1"; }

            mapPanX = parseInt(panX,10)*(mapWidth/4);
            mapPanY = parseInt(panY,10)*(mapHeight/4);
            mapPan = new GSize(mapPanX,mapPanY);

            map.panBy(mapPan);

            $("#CG_map_popup").css({
                display:"block",
                left:iconLeft + (mapPanX+20)+"px",
                top:iconTop + mapPanY+"px"
            });
        }else{
            $("#CG_map_popup").css({
                display:"block",
                left:(iconLeft+20)+"px",
                top:iconTop+"px"
            });
        }

        $("#CG_map_popup").html(stationPopInfo);
        if(openVcard === "vcard0"){
            $("#CG_map_popup").addClass("CG_popup_cheapest");
        }else{
            $("#CG_map_popup").removeClass("CG_popup_cheapest");
        }
    }
}

jQuery.fn.CG_buildVcard = function(pData,cardNum,vcardClass){
    var vCard = "",
        vCardExtraClass = getVCardExtraClass(pData.Name),mOver,mOut;

    mOver = "$(this).addClass('vcard_mover')";
    mOut = "$(this).removeClass('vcard_mover')";

    vCard = ['<li class="vcard '+vcardClass+' '+vCardExtraClass+'" onmouseover="'+mOver+'" onmouseout="'+mOut+'" onclick="javascript:toggleVCard(\''+cardNum+'\')" id="vcard'+cardNum+'">',
            '<h4 class="fn org" title="click to view the address and map location"><span>'+pData.Name+'</span> <em class="note">'+$(document).CG_formatPriceMap(pData)+'</em></h4>',
            '<p class="adr">',
            '<span class="street-address">'+pData.Address+' </span>',
            '<span class="locality">'+pData.Suburb+' </span>',
            '<span class="postal-code">'+pData.Postcode+'</span>',
            '</p>',
            '</li>'].join('');
    return vCard;
};


/* START BUILDING NATIONAL CHARTS */
function CG_startBuild(){
    $(document).CG_checkCookie('defaultCity');
    $(document).CG_buildAvgTables();
}

function CG_waitToBuild(){
    try { clearTimeout(pauseBuild);}catch(exception){}
    if(!allStatesChart){
        pauseBuild = setTimeout("CG_waitToBuild()",1000);
    }else{
        CG_startBuild();
    }
}

jQuery.fn.CG_getURLParam = function(pName, qString){
    var fullParamDefs, p = 0, thisParamDef, pLoc, pValue = "";

    fullParamDefs = qString.substring(1).split("&");
    for(p=0;p<fullParamDefs.length;p++){
        thisParamDef = fullParamDefs[p];
        pLoc = thisParamDef.indexOf(pName);
        if(pLoc !== -1){
            pValue = thisParamDef.substring(pLoc+pName.length+1);
        }
    }
    return pValue;
};

function CG_selectPostcode(pCde){
    var curFtype = $("input[name='fuelType']:checked").val(), urlQuery, urlLocation;

    curPostcode = pCde;

    $(document).CG_formStationValue();
    urlQuery = "?stations="+stationsVal+"&fuelType="+curFtype+"&suburb="+$("#"+locationFieldID).val().toString()+"&postcode="+pCde;

    if(curQuery.length > 0){
        urlLocation = curURL.substring(0,curURL.indexOf("?"));
    }else{
        urlLocation = curURL;
    }
    document.location.href = urlLocation + urlQuery;
}

/* This function is used to find a postcode if the user enters a suburb name */
lookupJSON = function(args){
    var text = "",
        pcodeSearch,
        i=0;

    switch(args.ResultData.ResultCode){
        case "0":
            alert("Location not found. Please try another suburb or postcode.");
            break;
        case "1":
            curPostcode = jQuery.trim(args.ResultData.Data[0].postcode);
            $(document).CG_getPetrolPrices(true);
            break;
        case "2":
            text = "Did you mean: <br />";
            for (i=0 ; i<args.ResultData.Data.length ; i++){
                pcodeSearch = "CG_selectPostcode('"+args.ResultData.Data[i].postcode+"')";
                text = text + '<a href="javascript:'+pcodeSearch+'">';
                text = text + args.ResultData.Data[i].name + " " + args.ResultData.Data[i].state + " " + args.ResultData.Data[i].postcode;
                text = text + "</a>";
            }
            $("#did_you_mean").html(text);
            $("#did_you_mean").css("display","block");
            break;
    }
};


jQuery.fn.CG_getCurrentPostcode = function(formPost){
    var curPCodeInt,
        curLocation = $("#"+locationFieldID).val().toString(),
        validShortPostcode = false;

    curPostcode = "";
    $("#"+locationFieldID).removeClass("CG_postcode_error");

    if(curLocation === ""){
        // The field is blank
        alert("Please supply a postcode to search for petrol.");
        $("#"+locationFieldID).addClass("CG_postcode_error");
        $("#CG_postcode").val();
    }else{
        if(curLocation.length === 3 && curLocation.substring(0,1) === "8"){
            validShortPostcode = true;
        }

        if(curLocation.length < 4 && !validShortPostcode){
            alert("Please enter a valid postcode.");
            $("#"+locationFieldID).addClass("CG_postcode_error");
            $("#CG_postcode").val();
        }else{
            curPCodeInt = parseInt(curLocation,10);
            // If the current location is an number set it as the current postcode
            if(curPCodeInt.toString() !== "NaN"){
                if(curLocation.length > 4){
                    alert("Location not found. Please try another suburb or postcode.");
                }else{
                    curPostcode = curLocation;
                    $(document).CG_getPetrolPrices(true);
                }
            }else{
                // They have typed in a suburb name. Do a postcode lookup and then perform the query
                $.getScript("tools-and-advice/petrol-prices-lookup/"+curLocation.toLowerCase());
            }
        }
    }
};

jQuery.fn.CG_performPriceQuery = function(pCode,fType,pStat,expandSearch,addPostCode,expandComplete){
		  //var APIUrl = "http://motormouth.net.au/services/fuelpricingservices.ashx?",
		  var APIUrl = "/api/rp/index.php?",
        APIFormat = "&format=json",
//        APIPartnerID = "&partner=18",
//        APICallBack = "&callback=jQuery.fn.CG_petrolPriceData&jsoncallback=?",
        APIOpVal = "&op=PostcodeSearchGeocodeMultiFuel",
        APILocation = "&Postcode=" + pCode,
        APIStations = "stations="+pStat,
        APIFuelType = "&FuelTypes=" + fType,
        APIEndQuery = "&surrounding=true",
        APIQuery = APIUrl +
            APIStations +
            APIOpVal +
            APIFormat +
//            APIPartnerID +
//            APICallBack +
            APILocation +
            APIFuelType +
            APIEndQuery;

    /* Make sure all stations is checked if no specific one is chosen */
    if(pStat.substring(0,1) === "1"){
        $("#CG_station_all").attr("checked","checked");
    }

    /* Show the results block */
    $("#CG_price_results").css("display","block");

    /* Hide the map */
    $("#map_canvas").css("display","none");
    $("#CG_map_popup").css("display","none");

    /* Show the loader */
    $("#CG_petrolloader").css("display","block");
    $("#CG_petrolstations").html("");


    /* Hide the national information */
    $("#CG_price_national").css("display","none");
    $("#panel-middle").css("display","none");

    if(expandSearch){
        /* Use the addPostCode if it is different from pCode */
        if(addPostCode !== curPostcode){
            APILocation = "&Postcode=" + addPostCode;
//            APICallBack = "&callback=jQuery.fn.CG_morePetrolPriceData&jsoncallback=?";
            APIQuery = APIUrl +
                APIOpVal +
                APIFormat +
//                APIPartnerID +
//                APICallBack +
                APILocation +
                APIFuelType +
                APIEndQuery;

            if(expandComplete){ dataReady = true; }
            $.getJSON(APIQuery,jQuery.fn.CG_morePetrolPriceData);
        }
    }else{
        $.getJSON(APIQuery,jQuery.fn.CG_petrolPriceData);
    }
    $(document).CG_alert(APIQuery);
};

jQuery.fn.CG_setSummaryValues = function(curStat,curFtype){
    $(document).CG_formStationValue();
    $("#CG_search_summary_postcode").html("<strong>Suburb/Postcode:</strong><span>"+$("#"+locationFieldID).val()+"</span>");
    $("#CG_search_summary_fueltype").html("<strong>Fuel Type:</strong><span>"+$(document).CG_formFuelTypeValue(false,curFtype)+"</span>");
    $("#CG_search_summary_refine").html("<strong>Stations:</strong><span>"+curStat+"</span>");
};

/* This is the main function that gets the petrol data */
jQuery.fn.CG_getPetrolPrices = function (formPost, expandSearch, addPostCode, expandComplete) {
    var
        fuelTypeFieldName = "fuelType",
        curFuelType = $("input[name='"+fuelTypeFieldName+"']:checked").val(),
        urlQuery = "", urlLocation;

        /* Get the formatted stations values */
        $(document).CG_formStationValue();

    if(formPost){
        urlQuery = "?stations="+stationsVal+"&fuelType="+curFuelType+"&postcode="+curPostcode;

        if(curQuery.length > 0){
            urlLocation = curURL.substring(0,curURL.indexOf("?"));
        }else{
            urlLocation = curURL;
        }
        document.location.href = urlLocation + urlQuery;
    }else{
        /* Clear the national map animation */
        clearInterval(timedAnim);

        /* Clear the map popup */
        stationPopInfo = "";
        $("#CG_map_popup").html("");
        $("#CG_map_popup").css("display","none");
        $("#CG_price_results_map").css("display","none");

        /* Hide the did you mean */
        $("#did_you_mean").css("display","none");

        /* Clear the all data array */
        if(!expandSearch){
            allData.length = 0;
        }

        $("#CG_sorryMessage").css("display","none");

        if(!curPostcode || curPostcode === ""){
            // It has returned as either blank or multi-suburb
        }else{
            // Set the summary values
            $(document).CG_setSummaryValues(stationsString,curFuelType);

            // Perform the JSON query
            $(document).CG_performPriceQuery(curPostcode, curFuelType, stationsVal, expandSearch, addPostCode, expandComplete);
        }
    }
};

/* JSON DATA || Retrieving and using the data from the JSON query */
jQuery.fn.CG_petrolPriceData = function(jsonData){
    /* Initial data return */
    dataReady = false;
    allData.length = 0;
    cheepestFuel = 10000;
    stations.length = 0;
    addresses.length = 0;

    $("#CG_petrolstations").html("");

    switch(jsonData.ResultCode){
        case 0:
            /* Data found */
            petrolFound = true;
            dataReady = true;
            $(document).CG_extractData(jsonData.Data);
            $("#CG_petrolloader").css("display","none");
            searchExpanded = false;
            break;
        case 1:
            petrolFound = false;
            /* No data was found - expand the radius and search again */
            /* Show loader and please wait message */
            $("#CG_petrolloader").css("display","block");
            $("#CG_petrolstations").html("");

            /* Find other postcodes in the delivery area */
            if(!postCodesLoaded){
                $.ajax({
                    url:"/javascript/screenspecific/CG_postcodes.js",
                    dataType: "script",
                    success: function(){
                        $(document).CG_expandSearch(curPostcode);
                        postCodesLoaded = true; },
                    cache: true
                });
            }else{
                $(document).CG_expandSearch(curPostcode);
            }
            searchExpanded = true;
            break;
    }
};

jQuery.fn.CG_morePetrolPriceData = function(jsonData){
    var expandComplete = false;

    if(jsonData.ResultCode === "0"){
        petrolFound = true;
        $(document).CG_extractData(jsonData.Data,true);
        $("#CG_petrolloader").css("display","none");
    }else{
        /* Check if it is the last search */
        if(dataReady){
            /* If no petrol is found after the expanded search */
            if(!petrolFound){
                $("#CG_petrolloader").css("display","none");
                $("#CG_sorryMessage").css("display","block");
            }else{
                listHTML = "";
                if(allData.length > 0){
                    allData.sort(
                        function(a,b){
                            return parseFloat(a.Price) - parseFloat(b.Price);
                        }
                    );
                }
                $("#CG_petrolloader").css("display","none");
                $(document).CG_buildPetrolMap();
                searchExpanded = false;
            }
        }
    }

    /* Continue expanding the search */
    addPostcodeNum = addPostcodeNum+1;
    if(addPostcodeNum < postCodeMatches.length){
        if(addPostcodeNum === postCodeMatches.length-1){
            expandComplete = true;
        }
        $(document).CG_getPetrolPrices(false,true,postCodeMatches[addPostcodeNum],expandComplete);
    }
};


jQuery.fn.CG_expandSearch = function(curPostcode){
    var regionDef, pcd;
    postCodeMatches.length = 0;
    addPostcodeNum = 0;

    /* Find the matching postcode definition */
    regionDef = CG_postcodes[curPostcode].deliveryArea;

    /* Loop through the array and find other postcodes that match the delivery area */
    for(pcd=0;pcd<CG_postcodes.length;pcd++){
        if(CG_postcodes[pcd] && CG_postcodes[pcd].deliveryArea === regionDef){
            if(pcd !== curPostcode){
                postCodeMatches[postCodeMatches.length] = pcd;
            }
        }
    }

    //For each postcode match do another json query
    if(postCodeMatches.length > 1){
        $(document).CG_getPetrolPrices(false,true,postCodeMatches[addPostcodeNum],false);
    }else{
        $("#CG_petrolloader").css("display","none");
        $("#CG_sorryMessage").css("display","block");
    }
};

jQuery.fn.CG_extractData = function(pData,concat){
    var thisStation, thisAddress;

    $.each(pData, function(i, val) {
        /* Add to allData array */
        /* Check if it is a duplicate listing */
        thisStation = pData[i].Brand;
        thisAddress = pData[i].Address;

        if(jQuery.inArray(thisStation,stations) === -1 || jQuery.inArray(thisAddress,addresses) === -1){
            allData[allData.length] = pData[i];
            stations[stations.length] = thisStation;
            addresses[addresses.length] = thisAddress;
        }

        //Set the cheapest fuel
        if(parseFloat(pData[i].Price) < cheepestFuel){
            cheepestFuel = parseFloat(pData[i].Price);
        }
    });

    if(dataReady){
        /* Sort the data by price */
        listHTML = "";
        if(allData.length > 0){
            allData.sort(
                function(a,b){
                    return parseFloat(a.Price) - parseFloat(b.Price);
                }
            );
            $(document).CG_buildPetrolMap();
        }else{
            $("#CG_petrolloader").css("display","none");
            $("#CG_sorryMessage").css("display","block");
        }
        searchExpanded = false;
    }
};

/* FUEL TYPES || Controls for the fields and formatting of the fuel types */
jQuery.fn.CG_formFuelTypeValue = function(toNum, pVal){
    var fuelVal,ft=0, fuelTypes = [];

    fuelTypes[2] = "Unleaded";
    fuelTypes[3] = "Diesel";
    fuelTypes[4] = "LPG";
    fuelTypes[5] = "Premium";
    fuelTypes[6] = "E10";

    $("input[name=fuelType]").each(function(i){
        if(!toNum){
            //Make it into a string
            fuelVal = fuelTypes[pVal];
        }else{
            for(ft = 0; ft < fuelTypes.length; ft++){
                if(fuelTypes[ft] === pVal){
                    fuelVal = ft;
                }
            }
        }
    });
    return fuelVal;
};


/* STATIONS || Controls for the fields and formatting of the stations */
/* Independent = 7 Eleven, Budget, Gogas, Liberty, Metro Fuel, Prime Petroleum, Speedway, United, Volume Plus, Freedom Fuels, IFS, Matilda, Neumann, Apco, Better Choice, Foodies, Fuel Zone, Fueline, SAFF, Gull, Peak, Wesco Fuels, On the Run, Southern Cross, Uptown Fuel, Energy Fuels */

jQuery.fn.CG_formStationValue = function(){
    var allStations = false;
    stationsVal = "";
    stationsString = "";

    $("#search-refine input").each(function(i){
        if($(this).attr("checked")){
            if(i===0){ allStations = true; }
            stationsVal = stationsVal + "1";
            stationsString = stationsString + $(this).val() + ", ";
        }else{
           stationsVal = stationsVal + "0";
        }
    });

    if(stationsVal === "000000"){
        stationsVal = "100000";
        allStations = true;
    }

    stationsString = stationsString.substring(0,stationsString.length-2);

    if(allStations){  stationsString = "All stations"; }
};

jQuery.fn.CG_controlAllStations = function(){
    $(this).each(function(){
        var checkState, controlChecks;

        checkState = $(this).prop("checked");

        controlChecks = function(){
            if(checkState){
                $("#search-refine input").prop("checked","checked");
                $("#search-refine label").not(":first").css("color","#aaa");
                $("#search-refine input").not(":first").prop("disabled","disabled");
            }else{
                $("#search-refine input").removeProp("checked");
                $("#search-refine label").not(":first").css("color","");
                $("#search-refine input").not(":first").removeProp("disabled");
            }
        };
        controlChecks();

        $(this).click(function(){
            checkState = $(this).prop("checked");
            controlChecks();
        });
    });

};


/* MAP FUNCTIONS */
jQuery.fn.CG_formatPriceMap = function(pData){
    var price;
    price = (parseFloat(pData.Price)/10).toString();
    if(price.indexOf(".") === -1){
        price = price + ".0";
    }
    return price;
};

/* Draw a base map of Australia */
jQuery.fn.CG_buildPetrolMap = function(options){
    var
        icnOpts = jQuery.extend({
            icnImage : "/img/icons/marker.gif",
            icnWidth : "42",
            icnHeight : "40",
            icnOffsetX : "5",
            icnOffsetY : "38",
            icnShadow : "/img/icons/marker-shadow.png",
            icnShadowWidth : "65",
            icnShadowHeight : "32",
            icnLabelOffsetX : 1,
            icnLabelOffsetY : -33,
            icnClickable : true,
            icnCheapest : "/img/icons/marker-cheapest.gif"
        },options||{}),
        mapMarker,
        mapMarkerOpts,
        markerClass = "",
        vcardClass = "",
        mapCoords,
        mapCenterLat = 0,
        mapCenterLong = 0,
        numberOfStations = allData.length,
        thisData,
        zoomControl
        ;

    if(CG_showMap){
        $("#map_canvas").css("display","block");
        $("#CG_price_results_map").css("display","block");
    }else{
        $("#CG_price_results_map").css("display","block");
        $("#CG_no_map").css("display","block");
    }

    if(numberOfStations > 0){

        if(CG_showMap && GBrowserIsCompatible){
            /* Work out center of map */
            jQuery.each(allData,function(lnum){
                mapCenterLat = mapCenterLat + parseFloat(allData[lnum].Lat);
                mapCenterLong = mapCenterLong + parseFloat(allData[lnum].Long);
            });
            mapCenterLat = mapCenterLat/numberOfStations;
            mapCenterLong = mapCenterLong/numberOfStations;


            /* Draw the map */
            map = new GMap2(document.getElementById("map_canvas"));

            zoomControl = new GLargeMapControl();

            map.addControl(zoomControl); //Adds the map zoom tool to the map
            map.addControl(new GMapTypeControl()); //Adds the map type toolbar to the map
            map.setCenter(new GLatLng(mapCenterLat, mapCenterLong), 11);
            map.setUIToDefault();
            map.disableScrollWheelZoom();

            //mapPane = map.getPane(G_MAP_MARKER_PANE);
            CG_mapBuilt = true;

            /* Add the markers */
            CG_mapIcon = new GIcon();
            CG_mapIcon.iconSize = new GSize(icnOpts.icnWidth, icnOpts.icnHeight);
            CG_mapIcon.iconAnchor = new GPoint(icnOpts.icnOffsetX, icnOpts.icnOffsetY);

            /* If it is not IE6 add a shadow*/
            if(userBrowser !== "ie6.0"){
                CG_mapIcon.shadow = icnOpts.icnShadow;
                CG_mapIcon.shadowSize = new GSize(icnOpts.icnShadowWidth, icnOpts.icnShadowHeight);
            }
        }

        /* Available attributes
            SiteID,SiteName,SiteAddress,Price,SiteBrand,SiteSuburb,SitePostcode,Latitude,Longitude,FuelTypeID,FuelTypeName,
         */
        listHTML = '<ul class="CG_list_accordion">';

        jQuery.each(allData,function(index){
            /* Build the listing details */
            thisData = allData[index];

            if(parseFloat(thisData.Price) === cheepestFuel){
                if(CG_showMap && GBrowserIsCompatible){
                    CG_mapIcon.image = icnOpts.icnCheapest;
                }
                markerClass = "CG_marker_cheapest";
                vcardClass = "CG_vcard_cheapest";
            }else{
                if(CG_showMap && GBrowserIsCompatible){
                    CG_mapIcon.image = icnOpts.icnImage;
                }
                markerClass = "";
                vcardClass = "";
            }

            listHTML = listHTML + $(document).CG_buildVcard(thisData,index,vcardClass);

            if(CG_showMap && GBrowserIsCompatible){
                mapMarkerOpts = {
                    "icon": CG_mapIcon,
                    "clickable": icnOpts.icnClickable,
                    "labelID": "CG_map_icon_"+index,
                    "labelText": $(document).CG_formatPriceMap(thisData),
                    "labelOffset": new GSize(icnOpts.icnLabelOffsetX, icnOpts.icnLabelOffsetY)
                };
                mapCoords = new GLatLng(thisData.Lat,thisData.Long);

                mapMarker = new LabeledMarker(mapCoords, mapMarkerOpts);
                mapMarker.SiteAddress = thisData.Address;
                mapMarker.SiteName = thisData.Name;
                mapMarker.Price = $(document).CG_formatPriceMap(thisData);

                GEvent.addListener(mapMarker, "mouseover", function() {
                    mouseOverMapPin = true;
                    toggleVCard(index,true);
                });

                GEvent.addListener(mapMarker, "mouseout", function() {
                    mouseOverMapPin = false;
                });

                GEvent.addListener(map,"zoomend",function(){
                    if(!mouseOverMapPin){
                        CG_closeStationPop();
                    }
                });

                map.addOverlay(mapMarker);
            }
        });

        listHTML = listHTML + '</ul>';
        $("#CG_search_summary").html();
        $("#CG_petrolstations").html(listHTML);

        /* Open up first list item */
        $("#vcard0").click();

    }else{
        /* No data found for entire region */
    }

};

/* AVERAGE TABLES AND GRAPHS */
jQuery.fn.getAverage = function(avgType,city,fuelType){
	 var APIUrlPrefix = "/api/rp/index.php?service=fps&",
        stdParams = "format=json",
        xtraParams = "";

    switch(avgType){
        case "natSum": /* Full national summary */
            xtraParams = "&op=NationalSummary&region=ALL&fuelTypes=2,3,4,5,6";
            break;
        case "natDaily": /* Has to be run for each fuel type and gives average for each city */
            setAvgFuelType = fuelType;
            xtraParams = "&op=NationalDailyPriceAverages&fuelType=" + setAvgFuelType;
            break;
        case "citySum": /* Used to get cheapest day */
            xtraParams = "&op=CitySummary&fuelType=6&cityName=" + city;
            break;
        case "cityWklHist": /* Used for the google chart */
        case "cityWklHistLcl": /* Used for the google chart */
            xtraParams = "&op=CityWeeklyPriceHistory&fuelType=2&cityName=" + city;
            break;
    }

    setAvgType = avgType;

    $.getJSON(APIUrlPrefix+stdParams+xtraParams,jQuery.fn.CG_useAverageData);
    $(document).CG_alert(APIUrlPrefix+stdParams+xtraParams);
};

jQuery.fn.CG_useAverageData = function(jsonData){
    switch(jsonData.ResultCode){
        case "0": //Where a string 0 is returned - deprecated
		  case 0: //Where a real 0 is returned
			  /* Data was found */
           $(document).CG_extractAvgData(jsonData,true);
           break;
        case "1": //where a string 1 is returned - deprecated
		  case 1: //Where a real 1 is returned
           /* No data was found */
           $(document).CG_extractAvgData();
           break;
		  default:
			  console.error("Unexected resultcode");
    }
};

jQuery.fn.CG_getNextFuelAverage = function(){
    clearTimeout(avgFuelTime);
    $(document).getAverage('natDaily','',setAvgFuelType+1);
};

jQuery.fn.CG_extractAvgData = function(resultData,concat){
    var pData = "",
        avgPrice = 0,
        noCities = 0,
        relHeight = 2000,
        pxlHeight,
        grphPrice = 0,
        grphPriceLbl = "",
        fuelTypeAsString
        ;

    if(resultData){
        pData = resultData.Data;
    }

    switch(setAvgType){
        case "natSum":
            natSummary = pData;
            //Build the sydney table first
            $(document).CG_showAvgTable(initCity);
            break;
        case "natDaily":
            fuelTypeAsString = $(document).CG_formFuelTypeValue(false, setAvgFuelType);
            $.each(pData,
                function(i, val) {
                    avgPrice = avgPrice + parseFloat(pData[i].Price);
                    noCities = noCities + 1;
                }
            );
            grphPrice = avgPrice/noCities;
            pxlHeight = grphPrice/relHeight * 50;
            grphPriceLbl = $(document).CG_formatPrice(grphPrice);

            $("#CG_NA_"+fuelTypeAsString).html('<span>'+fuelTypeAsString+'</span>'+grphPriceLbl);
            $("#CG_NA_"+fuelTypeAsString).css("height",pxlHeight);
            if(setAvgFuelType < 6){
                //Wait a few seconds to be sure the data has come back and been used
                avgFuelTime = setTimeout("jQuery.fn.CG_getNextFuelAverage()",500);
            }else{
                $(document).getAverage('natSum');
            }
            break;
        case "citySum":

            if(!pData){
                $("#cheapestDay").html("Not available");
            }else{
                $("#cheapestDay").html(pData[0].CheapestDay);
            }
            //Build the chart
            $(document).getAverage('cityWklHistLcl',activeCity);
            break;
        case "cityWklHist":
            /* Use all the days and prices to make a chart */
            chartData[chartNum] = resultData;
            if(chartNum < cities.length-1){
                chartNum = chartNum + 1;
                $(document).getAverage('cityWklHist',cities[chartNum]);
            }else{
                $(document).CG_buildAvgChart(true);
            }
            break;
        case "cityWklHistLcl": /* Used for the google chart */
            chartData.length = 0;
            chartData[0] = resultData;
            $(document).CG_buildAvgChart(false,activeCity);
            break;

    }
};

jQuery.fn.CG_buildAvgTables = function(){
    /* Start building the graph */
    $(document).getAverage('natDaily','',2);
};

jQuery.fn.CG_showAvgTable = function(cityName){
    //Loop through natSummary and extract table data
    var minPrice,
        avgPrice,
        maxPrice,
        fuelType;

    if(setCity === "" || setCity === cityName){

        $("#cityName").html(cityName+" averages*");
        /* Clear the table first for instances where no data is available */
        $(".petrol-map-data table td").html("&nbsp;");

        $.each(natSummary,
            function(ns) {
                if(jQuery.trim(natSummary[ns].Region) === jQuery.trim(cityName)){
                    fuelType = natSummary[ns].Fuel.toLowerCase();
                    minPrice = parseFloat(natSummary[ns].MinPrice)/10;
                    maxPrice = parseFloat(natSummary[ns].MaxPrice)/10;
                    avgPrice = parseFloat(natSummary[ns].AvgPrice)/10;

                    $("#low_"+fuelType).text(minPrice);
                    $("#av_"+fuelType).text(avgPrice);
                    $("#high_"+fuelType).text(maxPrice);
                }
            }
        );

        //Get the cheapest day data
        activeCity = cityName;
        $(document).getAverage('citySum',cityName);
    }
};

jQuery.fn.CG_formatPrice = function(pPrice){
    var adjPrice = pPrice/10,
        priceString = adjPrice.toString(),
        posDec = priceString.indexOf("."),
        decString,
        intString,
        adjDecString
        ;

    if(posDec === -1){
        intString = priceString;
        adjDecString = ".0";
    }else{
        decString = priceString.substring(posDec+1,posDec+2)+"."+priceString.substring(posDec+2);
        adjDecString = parseInt(decString,10);
        intString = priceString.substring(0,posDec);
    }
    return intString + "." + adjDecString;
};

jQuery.fn.CG_buildAvgChart = function(allStates,city){
    var max_val,
        min_val,
        chart_url = "http://chart.apis.google.com/chart?",
        chart_type = "cht=lc",
        chart_values = "chd=t:",
        sunAvg = 0,
        monAvg = 0,
        tuesAvg = 0,
        wedAvg = 0,
        thurAvg = 0,
        friAvg = 0,
        satAvg = 0,
        noDataSets = chartData.length,
        avgArray,
        sortedAvgArray,
        graphIndex,
        diff,
        chart_size = "chs=320x141",
        chart_line_color = "chco=ff0000",
        chart_axis = "chxt=x,y",
        chart_grid = "chg=0,11",
        chart_points = "chm=s,ff0000,0,-1,6.0",
        chart_y_values = "chxl=0:|sun|mon|tue|wed|thu|fri|sat|",
        chart_x_values,
        ar=0
        ;

    $.each(chartData,
        function(cd) {
            try {
                sunAvg = sunAvg + parseInt(chartData[cd].Data[0].price,10);
                monAvg = monAvg + parseInt(chartData[cd].Data[1].price,10);
                tuesAvg = tuesAvg + parseInt(chartData[cd].Data[2].price,10);
                wedAvg = wedAvg + parseInt(chartData[cd].Data[3].price,10);
                thurAvg = thurAvg + parseInt(chartData[cd].Data[4].price,10);
                friAvg = friAvg + parseInt(chartData[cd].Data[5].price,10);
                satAvg = satAvg + parseInt(chartData[cd].Data[6].price,10);
            }catch(exception){}
        }
    );

    sunAvg = sunAvg/noDataSets;
    monAvg = monAvg/noDataSets;
    tuesAvg = tuesAvg/noDataSets;
    wedAvg = wedAvg/noDataSets;
    thurAvg = thurAvg/noDataSets;
    friAvg = friAvg/noDataSets;
    satAvg = satAvg/noDataSets;

    avgArray = [sunAvg,monAvg,tuesAvg,wedAvg,thurAvg,friAvg,satAvg];

    sortedAvgArray = [sunAvg,monAvg,tuesAvg,wedAvg,thurAvg,friAvg,satAvg];
    sortedAvgArray.sort();

    min_val = sortedAvgArray[0];
    max_val = sortedAvgArray[sortedAvgArray.length-1];

    graphIndex = (100) / (max_val-min_val);

    for(ar=0; ar<avgArray.length; ar++){
        chart_values = chart_values + Math.floor((avgArray[ar]-min_val) * graphIndex);
        if(ar < avgArray.length-1){
            chart_values = chart_values + ",";
        }
    }

    diff = Math.floor((max_val - min_val)/5);
    chart_x_values = "1:||" + parseInt(min_val/10,10) + "||" + parseInt(Math.floor(min_val+diff)/10,10) + "||"  + parseInt(Math.floor(min_val+diff*2)/10,10) + "||"+ parseInt(Math.floor(min_val+diff*3)/10,10) + "||"+ parseInt(Math.floor(min_val+diff*4)/10,10) + "||" + parseInt(Math.floor(min_val+diff*5)/10,10);

    if(allStates){
        $("#CG_petrol_chart").html('<img src="'+chart_url+chart_type+'&'+chart_values+'&'+chart_size+'&'+chart_line_color+'&'+ chart_points + '&' +chart_axis+'&'+chart_grid+'&'+chart_y_values+chart_x_values+'"/>');
        allStatesChart = true;
    }else{
        $("#CG_petrol_chart_state").html(city);

        if(chart_x_values.indexOf("NaN")!== -1){
            $("#CG_petrol_chart_local").html("<span>Sorry. No data was available for "+city+"</span>");
        }else{
            $("#CG_petrol_chart_local").html('<img src="'+chart_url+chart_type+'&amp;'+chart_values+'&amp;'+chart_size+'&amp;'+chart_line_color+'&amp;'+ chart_points + '&amp;' +chart_axis+'&amp;'+chart_grid+'&amp;'+chart_y_values+chart_x_values+'"/>');
        }
    }
};

jQuery.fn.CG_saveToCookie = function(cityName){
    $("#"+setCity+"_map").removeClass("active");
    $(document).CG_writeCookie('defaultCity',cityName);
    clearInterval(timedAnim);
    $("#cities_map li a").eq(prevHoverAnim).removeClass("hover");
    setCity = cityName;
    $(document).CG_showAvgTable(setCity);
    $("#"+cityName+"_map").addClass("active");
};

jQuery.fn.CG_writeCookie = function(dataName,dataVal){
    var expDate = new Date(),
        expTime,
        cookieExpire,
        cookieDomain = "carsguide.com.au",
        cookiePath = "/";

    expTime = expDate.getTime() + (365*24*60*60*1000);
    expDate.setTime(expTime);
    cookieExpire = expDate.toGMTString();
    document.cookie = dataName+"="+dataVal+";expires="+cookieExpire+";domain="+cookieDomain+";path="+cookiePath;
};

jQuery.fn.CG_checkCookie = function(ckAttr){
    var cookieData = document.cookie,
        cookieDataArray,
        ckAttrDef,
        cookieDataDef,
        cd=0;

    cookieAttFound = false;
    cookieAttValue = "";

    cookieDataArray = cookieData.split(";");
    for(cd=0;cd<cookieDataArray.length;cd++){
        cookieDataDef = cookieDataArray[cd];
        if(cookieDataDef.indexOf(ckAttr) !== -1){
            ckAttrDef = cookieDataDef.split("=");
            cookieAttValue = ckAttrDef[1];

            if(ckAttr === "defaultCity"){
                setCity = cookieAttValue;
                initCity = cookieAttValue;
                clearInterval(timedAnim);
                $("#cities_map li a").eq(prevHoverAnim).removeClass("hover");
                $("#"+setCity+"_map").addClass("active");
            }
            cookieAttFound = true;
        }
    }
};

function CG_checkIEAlert(){
    $(document).CG_checkCookie('ieAlertShown');
    if(!cookieAttFound){
        $(document).CG_writeCookie('ieAlertShown','true');
        $("#CG_ie_mapshelp").click();
        ieAlertInit = true;
    }
}

function CG_setIENoMap(){
    tb_remove();
    $(document).CG_writeCookie('CG_showMap','false');
    $("#CG_no_map").css("display","block");
    CG_showMap = false;
}

function CG_allowMapIE(){
    $(document).CG_writeCookie('CG_showMap','true');
    $("#CG_no_map").css("display","none");
    CG_showMap=true;
    $(document).CG_buildPetrolMap();
}

function CG_continueBuild(){
    var curFuelTypeFieldID,fType,pStat,urlSuburb,labelClick = false;
    $("#CG_petrol_search_form").submit(
        function(){
            $(this).CG_getCurrentPostcode();
            return false;
        }
    );

    $(".CG_petrol_search_station").click(function(){ refineVCards();});

    $("body").append('<div id="CG_map_popup"></div>');

    $(document).mousemove(function(e){
        mouseX = e.pageX;
        mouseY = e.pageY;
        if(mouseOverMapPin){
            $("#CG_map_popup").css({
                left:mouseX+"px",
                top:mouseY+"px"
            });
        }
    });

    /* FUEL TYPE SELECTOR */
    $("#CG_petrol_search_type").click(function(){
        if($(this).attr("open") === "open"){
            $(this).attr("open","closed");
            $(this).removeClass("CG_petrol_search_type_open");
        }else{
            if(!labelClick){
                $(this).attr("open","open");
                $(this).addClass("CG_petrol_search_type_open");
            }
            labelClick = false;
        }
    });

    $("#CG_petrol_search_type label").click(function(){
        $("#CG_petrol_search_type label").removeClass("active");
        $(this).addClass("active");
        $("#CG_setFuelType").text($(this).text());
        labelClick = true;
        $(this).find("input").attr("checked","checked");
    });

    $("fieldset.CG_petrol_search_type label").hover(
        function(){
            $(this).addClass("hover");
        },
        function(){
            $(this).removeClass("hover");
        }
    );

    /* CHECK URL QUERY */
    if(curQuery.length > 0){
        buildNational = false;

        curPostcode = $(document).CG_getURLParam('postcode',curQuery);
        fType = $(document).CG_getURLParam('fuelType',curQuery);
        pStat = $(document).CG_getURLParam('stations',curQuery);
        urlSuburb = $(document).CG_getURLParam('suburb',curQuery);

        if(urlSuburb !== ""){
            $("#location").val(urlSuburb);
        }else{
            $("#location").val(curPostcode);
        }

        curFuelTypeFieldID = $(document).CG_formFuelTypeValue(false,fType);
        $("#"+curFuelTypeFieldID).attr("checked","checked");
        $("#CG_setFuelType").text(curFuelTypeFieldID);
        $(document).CG_performPriceQuery(curPostcode,fType,pStat);
        $(document).CG_formStationValue();
        $(document).CG_setSummaryValues(stationsString,fType);
    }else{
        $(".CG_fueltypes_explain h4").CG_invokeAccordion();
        $(".CG_fueltypes_explain h4").not(":eq(0)").click();
        $(document).getAverage('cityWklHist',cities[chartNum]);
        $("#cities_map li").hover(
            function(){
                $(document).CG_showAvgTable($(this).text());
            },
            function(){}
        );
    }
}

/* DOCUMENT READY FUNCTIONS  */
$(document).ready(function(){
    userBrowser = $(document).CG_getBrowser();
    if(userBrowser === "ie6.0"){
        CG_checkIEAlert();
        $(document).CG_checkCookie('CG_showMap');
        if(cookieAttValue === "false"){
            CG_showMap = false;
            $("#CG_no_map").css("display","block");
        }
    }
    CG_continueBuild();
});

function CG_animateNationalMap(){
    var noCities = $("#cities_map li").length;

    $("#cities_map li a").eq(prevHoverAnim).removeClass("hover");
    $("#cities_map li a").eq(curHoverAnim).trigger("mouseover").addClass("hover");

    prevHoverAnim = curHoverAnim;
    if(curHoverAnim < noCities-1){
        curHoverAnim = curHoverAnim + 1;
    }else{
        curHoverAnim = 0;
    }
}

$(window).load(function(){
    $("#CG_station_all").CG_controlAllStations();
    $(".CG_petrol_finder form").removeClass("CG_form_disabled");

    if(buildNational){
        if(allStatesChart){
            CG_startBuild();
        }else{
            CG_waitToBuild();
        }
        if(setCity === "" && userBrowser !== "ie6.0"){
            timedAnim = setInterval(CG_animateNationalMap,4000);
        }
    }
});

$(window).unload(function(){
    try { GUnload(); }catch(exception){}
});

