/// <reference path="ThirdParty/jquery-1.2.6-vsdoc.js" />
/// <reference path="ThirdParty/jquery.domec-0.3.1.js" />
/// <reference path="ThirdParty/jquery.plugin-0810.02.js" />
/// <reference path="ThirdParty/jquery.cssload.js" />
/// <reference path="jquery.locator.js" />


// Get the value of the param passed to the script using the format .js?key=blah
var scripts = document.getElementsByTagName('script');
var myScript = scripts[scripts.length - 1];
// Set Script Id so we can locate it later
myScript.id = "LocatorScript";
var queryString = myScript.src.replace(/^[^\?]+\??/, '');
var params = parseQuery(queryString);
var locatorBaseUrl = myScript.src.match(/^(?:\w+:)?\/\/([^\/?#]+)/) ? myScript.src.match(/^(?:\w+:)?\/\/([^\/?#]+)/)[0] : "";

// Configuration settings set by server
var googleAPIKey = null;
var companyName = null;
var baseCountry = null;
var countries = null;
var foundLocation = false;
var getLocationTimeout = 0;

function parseQuery(query) {
    ///	<summary>
    ///		parseQuery returns an array of key value pairs from the querystring of the js file
    ///	</summary>
    ///	<returns type="Array of Key Value Pairs" />
    ///	<param name="query" type="String">
    ///		String to parse
    ///	</param>
    var Params = {};
    if (!query) {
        return Params; // return empty object
    }
    var Pairs = query.split(/[;&]/);
    for (var i = 0; i < Pairs.length; i++) {
        var KeyVal = Pairs[i].split('=');
        if (!KeyVal || KeyVal.length != 2) { continue; }
        var key = unescape(KeyVal[0]);
        var val = unescape(KeyVal[1]);
        val = val.replace(/\+/g, ' ');
        Params[key] = val;
    }
    return Params;
}
function scriptURL(file) {
    return locatorBaseUrl + "/ScriptManager.aspx?" + (params.favourites !== undefined ? "favourites=" + params.favourites + "&" : "") + "js=" + file;
}
function cssURL(file) {
    return locatorBaseUrl + "/Style.aspx?key=" + params.key + "&base=" + locatorBaseUrl + "&css=" + file;
}
function pluginManagerLoaded() {

    ///	<summary>
    ///		Once the plugin manager and the css loader is loaded define and load all relevant scripts and CSS assets
    ///     The loading is chained together to ensure all assets are loaded.
    ///	</summary>
    $.plugin("MouseWheel", {
        files: [scriptURL("/Scripts/ThirdParty/jquery.mousewheel.js"), scriptURL("/Scripts/jquery.locator.js")],
        selectors: ['body'],
        cache: false,
        callback: function () {// Trendmicro css cascade - note, only cascades in IE
            $.cssload({ url: cssURL("/" + companyName + "/Css/Style.css"), success: function () {
                if ($.browser.msie) {
                    $.cssload({ url: cssURL("/" + companyName + "/Css/Ie.css"), success: function () {
                        if ($.browser.msie && $.browser.version < 7) {
                            $.cssload({ url: cssURL("/" + companyName + "/Css/Ie6/Ie6.css") });
                        }
                    }
                    });
                }
            }
            });
            $.getJSON(locatorBaseUrl + "/Template.aspx?key=" + params.key + "&jsoncallback=?", null, elementsLoaded);
        }
    });

    // Define the Google API and maps
    $.plugin("googleMaps", {
        files: ["http://www.google.com/jsapi?key=" + googleAPIKey + "&f=.js"],
        selectors: ['body'],
        cache: false,
        callback: function () {
            $.plugin("googleMapsV3").get();
        }
    });
    $.plugin("googleMapsV3", {
        files: ["http://maps.googleapis.com/maps/api/js?sensor=true&callback=gmap_draw&f=.js"],
        selectors: ['body'],
        cache: false,
        callback: function () {

        }
    });
    $.plugin("googleUtilities", {
        files: [scriptURL("/Scripts/ThirdParty/infobox.js"), scriptURL("/Scripts/ThirdParty/jquery.pngFix.js")],
        selectors: ['body'],
        cache: false,
        callback: function () { mapLoaded(); }
    });
    window.gmap_draw = function () {
        $.plugin("googleUtilities").get();
    };

    $.plugin("MouseWheel").get();

}
function elementsLoaded(data) {
    ///	<summary>
    ///		Elements have been loaded from template, we need to apply behaviours and functionalty
    ///     to them, then load in the default map.
    ///	</summary>
    ///	<param name="data" type="JsonObject">
    ///		Json object containing template html
    ///	</param>

    $("#LocatorScript").parent(":first").html(data.template.replace("{baseurl}", locatorBaseUrl));
    $("a").click(function (e) {
        genericClick(e);
    });
    $.plugin("googleMaps").get();

}
function genericClick(e) {
    e.target.blur();
}
function mapLoaded() {
    default_map();
    // Try W3C Geolocation (Preferred)
    if (navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function (position) {
            show_map(position, "au");
        }, function (error) {
            //default_map();
        });
        // Try Google Gears Geolocation
    } else if (google.gears) {
        browserSupportFlag = true;
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function (position) {
            show_map(position, "au");
        }, function (error) {
            //default_map();
        });
        // Browser doesn't support Geolocation
    }
    function default_map() {
        var position = { "coords": { "latitude": -1, "longitude": -1} };
        show_map(position, "au");
    }
}
function default_map() {
    clearTimeout(getLocationTimeout);
    foundLocation = true;
    var position = { "coords": { "latitude": -1, "longitude": -1} };
    show_map(position, "au");
}
function show_map(position, country) {
    var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var myOptions = {
        zoom: 14,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    $.locator({
        searchUrl: locatorBaseUrl + "/LocationSearch.aspx?key=" + params.key,
        map: new google.maps.Map($("#LocatorHolder").get(0), myOptions),
        geocoder: new google.maps.Geocoder(),
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        baseCountry: baseCountry === null ? country : baseCountry,
        countries: countries,
        resellerListId: "ResellerList",
        failure: function () { $(document.getElementById("ResellerList")).html("<div style=\"color:Red;padding:13px;\">Sorry, we couldn't find any resellers within the search parameters.</div>"); },
        addressSearchFailure: function () { $(document.getElementById("ResellerList")).html("<div style=\"color:Red;padding:13px;\">Sorry, we can't locate that address. Please check that you have not made a typo and that you have entered at least the Postcode, Country, City and State.</div>"); },
        icon: {
            image: locatorBaseUrl + "/" + companyName + "/Images/Marker.png",
            iconSize: new google.maps.Size(46, 53),
            shadowSize: new google.maps.Size(0, 0),
            iconAnchor: new google.maps.Point(23, 53),
            infoWindowAnchor: new google.maps.Point(158, 99)
        }
    });
}
function loadScript(sScriptSrc, callbackfunction) {
    ///	<summary>
    ///		loadScript is defined to load an external js file using pure javascript
    ///	</summary>
    ///	<param name="sScriptSrc" type="String">
    ///		Uri to script
    ///	</param>
    ///	<param name="callbackfunction" type="Function">
    ///		A function to execute
    ///	</param>
    var oHead = document.getElementsByTagName('head')[0];
    if (oHead) {
        var oScript = document.createElement('script');
        oScript.setAttribute('src', sScriptSrc);
        oScript.setAttribute('type', 'text/javascript');
        var loadFunction = function () {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                callbackfunction();
            }
        };
        oScript.onreadystatechange = loadFunction;
        oScript.onload = callbackfunction;
        oHead.appendChild(oScript);
    }
}

// Load core javascript files, jQuery from Google and jQuery plugin manager
loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js", function () {
    //loadScript(locatorBaseUrl + "/Scripts/ThirdParty/jquery-1.2.6-vsdoc.js", function() {
    $(document).ready(function () {
        $("#LocatorScript").parent(":first").append("Loading locator, please wait");
        $.ajax({
            type: "GET",
            cache: true,
            url: locatorBaseUrl + "/Scripts/ThirdParty/jquery.plugin-0810.02-min.js",
            dataType: "script",
            success: function () {
                $.ajax({
                    type: "GET",
                    cache: true,
                    url: locatorBaseUrl + "/Configuration.aspx?key=" + params.key + "&domain=" + params.domain,
                    dataType: "script",
                    success: function () {
                        $.ajax({
                            type: "GET",
                            cache: true,
                            url: scriptURL("/Scripts/jquery.cssload.js"),
                            dataType: "script",
                            success: pluginManagerLoaded
                        });
                    }
                });
            }
        });
    });
});

