﻿///<reference path="GMAPJSHelper_Release.js"/>

//search could only two mode types - sellpoints and acceptances
/*A.Kostyuk: Async call to google map api                     */
/* loadGoogleScript   - by url and special param(LoadGoogleMap)get script      */
/* LoadGoogleMap      - function, which automatically calls from google script 
it load additional scripts and google map general object*/
/* MapIsLoaded        - method,function which will eb call when Gmap2 object is loaded*/
/* EnsureGoogleMap    - function, -wait until Gmap2 is loaded. then execute code-delegate*/
var zoomLevel = 9;
var firstZoomLevel = 6;
var isMapLoaded = false;
var PaggingObject = null; //to check that script has been loaded
var SearchResult = null; //to check that script has been loaded
var LabeledMarker = null; //to check that script has been loaded
var showeditshopbutton = false;
function loadGoogleScript(ScriptSrc) {
    RegisterScript(ScriptSrc + "&callback=LoadGoogleMap", "google_com_jsapi");
}
function LoadGoogleMap() {
    //function will be called by google script automatically
    google.load("maps", "2.x", { "callback": MapIsLoaded });
    ShowLog('google.load("maps", "2.x", { "callback": MapIsLoaded });');
}

function MapIsLoaded() {
    //here we sure that "maps" with GMAP2 object
    RegisterScript("/sites/vvvirischeque/js/maps/labeledmarker.js", "labeledmarker_js");
    RegisterScript("/sites/vvvirischeque/js/maps/mappagging.js", "mappagging_js");
    RegisterScript("/sites/vvvirischeque/js/maps/searchresult.js", "searchresult_js");
    ShowLog('isMapLoaded = true;');
    isMapLoaded = true;
}
function EnsureGoogleMap(delegateToCall) {
    if (isMapLoaded && LabeledMarker && PaggingObject && SearchResult) {
        ShowLog('EnsureGoogleMap:delegateToCall();');
        delegateToCall();
    } else
        setTimeout(function() {
            EnsureGoogleMap(delegateToCall);
        }, 100);
}
/*A.kostyuk: End async load scripts */
/*---------------------------------------------------------------------------------------*/

function LoadAcceptancesShops(postcode, radius, branche,  isfirsttime, lblTitleText, hfTitleText) {
    glLblTitle = lblTitleText;
    glHFTitle = hfTitleText;
    postcode = postcode.replace("%27", "'");

    if (!isfirsttime)
        jQuery("#tbPostcode").val(postcode);
    
    var input = jQuery(".brancesInput").siblings("input:hidden[value=" + branche + "]")[0];
    jQuery(input).siblings(".brancesInput").children("input:checkbox").attr('checked', true);

    var _radius = document.getElementById(ddlDistanceID).value;
    if (!isfirsttime) {
        var postcode = document.getElementById("tbPostcode").value;
        radius = document.getElementById(ddlDistanceID).value + getRadiusesToShops(document.getElementById(ddlDistanceID)).replace(document.getElementById(ddlDistanceID).value, "");
    }
    EnsureGoogleMap(function() {
        PageMode.initilize("acceptances");
        MapInstance.initialize();
        if (postcode.IsNullOrEmpty()) {
            //postcode = defaultCenterPoint;
            postcode = MapInstance.defaulLocation;
        }
        MapInstance.isfirsttime = isfirsttime;
        //SearchResult.initialize();
        if (branche != "") SearchResult.checkedBranches.push(branche);

        doLoad(postcode, radius, PageMode.mode, 0);
    });
}

function LoadSellPointsShops(postcode, radius,  isfirsttime, lblTitleText, hfTitleText) {

    glLblTitle = lblTitleText;
    glHFTitle = hfTitleText;
    postcode = postcode.replace("%27", "'");

    if (!isfirsttime)
        jQuery("#tbPostcode").val(postcode);
    
    var _radius = document.getElementById(ddlDistanceID).value;
    if (!isfirsttime) {
        var postcode = document.getElementById("tbPostcode").value;
        radius = document.getElementById(ddlDistanceID).value + getRadiusesToShops(document.getElementById(ddlDistanceID)).replace(document.getElementById(ddlDistanceID).value, "");
    }
    if (postcode.IsNullOrEmpty()) {
        //postcode = defaultCenterPoint;
        postcode = MapInstance.defaulLocation;
    }
    EnsureGoogleMap(function() {
        PageMode.initilize("sellpoints");
        MapInstance.initialize();
    
        MapInstance.isfirsttime = isfirsttime;
        doLoad(postcode, radius, PageMode.mode, 0);
    });
}

var MapInstance = {
    map: null,
    geocoder: null,
    defaulLocation: null, //the latlong for the dfefault center
    searchPrefix: null, //the search prefix, which automatically will be added to all queries 
    mapCenterMarker: null,
    entityCoordinates: null,
    coordinatesInfo: null,
    isfirsttime: false,

    initialize: function() {
        var mapNode = document.getElementById("map");
        if (!mapNode) return;
        MapInstance.map = new GMap2(mapNode);
        MapInstance.map.setUIToDefault();
        MapInstance.geocoder = new GClientGeocoder();

        MapInstance.defaulLocation = jQuery("#hfDefaultCenterPoint").val();
        MapInstance.defaulLocation = String(MapInstance.defaulLocation).length < 1 ? "52.132633, 5.291266" : MapInstance.defaulLocation;
        MapInstance.searchPrefix = jQuery("#hfDefaultSearchPrefix").val();
        MapInstance.searchPrefix == String(MapInstance.searchPrefix).length < 1 ? "The Netherlands, NL" : MapInstance.searchPrefix;
        MapInstance.entityCoordinates = document.getElementById('coordinates_hidden');

        if (MapInstance.entityCoordinates.value.IsNullOrEmpty())
            MapInstance.setCenterByLocation(MapInstance.defaulLocation, 7);
        else
            MapInstance.setCenterByPoint(MapInstance.entityCoordinates.value);

        if (PageMode.mode == null || typeof (PageMode.mode) == 'undefined') {
            MapInstance.mapCenterMarker = new CenterMarker();
            MapInstance.map.addOverlay(MapInstance.mapCenterMarker);
        }
    },

    setCenterByLocation: function(_location) {
    MapInstance.geocoder.getLatLng(_location, function(latlng) {
            MapInstance.setCenterByPoint(latlng);
        });
    },

    setCenterByPoint: function(latlng, scaleTo) {
        var urlvalues = latlng ? String(latlng).replace(")", "").replace("(", "") : "";
        var newPnt;
        if (jQuery.trim(urlvalues) == "") {
            latlng = MapInstance.defaulLocation; //url is empty -center of the hollands
            newPnt = GLatLng.fromUrlValue(latlng); // center
        } else
            newPnt = GLatLng.fromUrlValue(urlvalues); // center by url
        var scalemode = scaleTo ? scaleTo : firstZoomLevel; //default zoom to some avarage value
        MapInstance.map.setCenter(newPnt, scalemode, G_NORMAL_MAP);

        var blueIcon = new GIcon(G_DEFAULT_ICON);
        blueIcon.iconSize = new GSize(39, 34);
        blueIcon.image = "http://www.google.com/mapfiles/arrow.png";

        var mtitle = (PaggingObject) ? PaggingObject.searchLocation + "," + PaggingObject.searchRadius : "";
        markerOptions = { icon: blueIcon, title: mtitle };
        MapInstance.map.addOverlay(new GMarker(newPnt, markerOptions));

        MapInstance.entityCoordinates.value = String(latlng);
        return latlng;
    },

    Search: function() {
        MapInstance.setCenterByLocation(document.getElementById("address").value);
        MapInstance.mapCenterMarker.setLatLng(MapInstance.map.getCenter());
    },

    GetLocation: function() {
        ClearFilter();
        var location = document.getElementById("tbPostcode").value;

        if (IsPostalCodeValidated(location)) {
            MapInstance.isfirsttime = false;
            LoadShops();
        }
        else {
            showdocelement("pcodereqMessage", true);
        }
    }
}

function CenterMarker() {
    var gMarker = new GMarker(MapInstance.map.getCenter(), { draggable: true });
    gMarker.enableDragging();

    GEvent.addListener(gMarker, "dragend", function(latlng) {
        MapInstance.setCenterByPoint(latlng);
    });

    return gMarker;
}

function LoadShops() {
    //var _radius = document.getElementById(ddlDistanceID).value;
    var _radiuses = getRadiusesToShops(document.getElementById(ddlDistanceID));

    var postcode = document.getElementById("tbPostcode").value;
    branchDataShouldBeUpdatet = true;
    doLoad(postcode, _radiuses, PageMode.mode, "0");
}

function ClearFilter() {
    var inputs = jQuery("table[id=brancesTable] input[type='checkbox']");
    var spans = jQuery("table[id=brancesTable]").find("span[id=styleSpan]");
    for (var i = 0; i < inputs.length; i++) {
        var currentInput = inputs[i];
        var currentSpan = spans[i];
        currentSpan.className = "brancesSpan";
        currentInput.checked = false;
    }

    var searchFilter = jQuery("#searchFilter option:first").attr("selected", "yes");

    SearchResult.checkedBranches = new Array();
    //SortBy();
}

function DisplaySearchResultTitle(foundQ) {
    var textHF = document.getElementById(glHFTitle).value;

    var tempTextHF = "";
    var defAmount = PageMode.mode == "acceptances" ? "23000" : "830";
    tempTextHF = MapInstance.isfirsttime ? textHF.replace('[FoundQuantity]', defAmount)
                                              : textHF.replace('[FoundQuantity]', foundQ);

    document.getElementById(glLblTitle).innerHTML = tempTextHF;
}

function getRadiusesToShops(ddElemnt) {
    var afterSelected = false;
    var radiuses = [];
    jQuery(ddElemnt).find("option").each(function(i, option) {
        if (option.selected || afterSelected) {
            radiuses.push(option.text);
            afterSelected = true;
        }
    });
    return radiuses.join();
}
function setSearchingRadiuse(strRad) {
    var ranges = document.getElementById(ddlDistanceID);
    if (strRad == "Netherlands") {
        if (ranges.options[0].text != strRad) {
            var nOpt = document.createElement("<option value='Netherlands' selected='true' disabled>");
            nOpt.text = strRad;
            ranges.options.add(nOpt, 0);
            //jQuery("<option value='Netherlands' selected='true'>Netherlands</option>").insertBefore(radOptions.eq(0));
        }
        else ranges.options[0].selected = true;
    }
    else {
        if (ranges.options[0].text == "Netherlands") ranges.options.remove(0);
        jQuery(ranges).find("option").each(function(i, option) {
            if (strRad != null)
                if (jQuery.trim(option.text.toLowerCase()) == jQuery.trim(strRad.toLowerCase())) {
                option.selected = true;
            }
        });
    }
}

function doLoad(postcode, _radius, _mode) {
    doLoad(postcode, _radius, _mode, 0);
}

function doLoad(postcode, _radius, _mode, page) {

    showdocelement("pNoResults", false);
    var showError = true;
    ShowLog("postcode=" + postcode + "; _radius=" + _radius + "; _mode=" + _mode + "; page=" + page);
    if (MapInstance.isfirsttime && page == "0") {
        var latlng = MapInstance.defaulLocation; //default point
        jQuery.post("~/search/search.ashx", { isfirstSearch: MapInstance.isfirsttime,
            isfirst: MapInstance.isfirsttime,
            mode: _mode,
            radius: _radius,
            branchegroups: GetBrancheGroups(),
            sortby: GetSortedBy(),
            point: String(latlng),
            page: page
        },
                        function(data) {
                            if (!(data)) return;
                            
                            MapInstance.map.clearOverlays();
                            PaggingObject.initialize(data.Shops, data.TotalFound, data.CurrentSet, "0", latlng, "pagging", "searchPagging", MapInstance.isfirsttime);
                            PaggingObject.searchLocation = postcode;
                            PaggingObject.searchRadius = _radius;
                            PaggingObject.renderButtons();
                            PaggingObject.setPointsInRange();

                            DisplaySearchResultTitle(data.TotalFound);

                            MapInstance.setCenterByPoint(latlng, zoomLevel);
                            //showdocelement("pNoResults", data.length == 0);
                            if (SearchResult.searchResultItems != null) {
                                showError = SearchResult.searchResultItems == 0;
                            }
                            showdocelement("pNoResults", showError);
                        }
                        , "json");
    } else {
    
        if (MapInstance.isfirsttime || jQuery.trim(postcode) != "") {// && PageMode.isInitialized -error when page is empty
            if (String(postcode).indexOf(MapInstance.searchPrefix) < 0)
                postcode = MapInstance.searchPrefix + ', ' + postcode;

            reqshouldbeshown = false;

            MapInstance.geocoder.getLatLng(postcode, function(latlng) {
                latlng = latlng ? latlng : MapInstance.defaulLocation; //get default position if google didn't return it
                var txtpostcode = document.getElementById("tbPostcode").value;
                
                    MapInstance.setCenterByPoint(latlng);
                    jQuery.blockUI({
                        message: '<span class="shopsSearchWait">Een moment geduld</span>',
                        fadeIn: 1000,
                        timeout: 3000,
                        css: {
                            width: "auto",
                            border: "2px solid #00AEEF"
                        },
                        onBlock: function() {
                            //get data items
                        jQuery.post("~/search/search.ashx", { isfirstSearch: MapInstance.isfirsttime,
                                isfirst: MapInstance.isfirsttime,
                                mode: _mode,
                                radius: _radius,
                                branchegroups: GetBrancheGroups(),
                                sortby: GetSortedBy(),
                                point: latlng.toString().replace(")", "").replace("(", ""),
                                page: page
                            },
                                                function(data) {
                                                    if (!(data)) return;
                                                    
                                                    MapInstance.map.clearOverlays();
                                                    PaggingObject.initialize(data.Shops, data.TotalFound, data.CurrentSet, data.CurrentPage, latlng, "pagging", "searchPagging", MapInstance.isfirsttime);
                                                    PaggingObject.searchLocation = postcode;
                                                    PaggingObject.searchRadius;// = _radius;
                                                    PaggingObject.searchRadius = data.Radius == "Netherlands" ? document.getElementById(ddlDistanceID).options[1].value : data.Radius;
                                                    PaggingObject.renderButtons();
                                                    PaggingObject.setPointsInRange();
                                                    setSearchingRadiuse(data.Radius);
                                                    DisplaySearchResultTitle(data.TotalFound);
                                                    //}
                                                    MapInstance.setCenterByPoint(latlng, zoomLevel);
                                                    if (SearchResult.searchResultItems != null) {
                                                        showError = SearchResult.searchResultItems == 0;
                                                    }
                                                    showdocelement("pNoResults", showError);

                                                    if (_mode == PageModeTypes.acceptances) {
                                                        if (showError && data.TotalFound == 0) clearBranchesData();
                                                        else {
                                                            var branches = jQuery.parseJSON(data.BranchesData);
                                                            if (branches != null)
                                                                updateBranchesData(branches);
                                                        }
                                                    }
                                                    jQuery.unblockUI();
                                                }
                                                , "json");
                        } //onblock function
                    }); //end block ui
            });
        }
    }

    showdocelement("pPageModeDoesntSpecified", !PageMode.isInitialized);
    showdocelement("pcodereqMessage", jQuery.trim(postcode) == "");
}

function IsPostalCodeValidated(testString) {
    var exp = /^(([a-zA-Z,\-\x27]{1,25})|([ ]{1,25}))*([0-9]{4})?(([a-zA-Z,\-\x27]{0,25})|([ ]{0,25}))+$/; 
    var value = exp.test(testString);
    return value;
}

function showdocelement(elid, visibleflag) {
    var el = document.getElementById(elid);
    if (el) {
        if (visibleflag) el.style.display = "block";
        else el.style.display = "none";
    }
}

function AddShopMarkersToMap(center, shops) {

    MapInstance.setCenterByPoint(center);

    for (var i = 0; i < shops.length; i++) {
        var shopMarker = new GMarker(GLatLng.fromUrlValue(shops[i].location));
        MapInstance.map.addOverlay(shopMarker);
    }
}

function GetBrancheGroups() {
    var brancheGroups = "";
    jQuery("table#brancesTable input:checked").each(
        function() {
            if (brancheGroups == "")
                brancheGroups += jQuery(this).parent().next().next().val();
            else
                brancheGroups += "," + jQuery(this).parent().next().next().val();
        });

    return brancheGroups;
}

function GetSortedBy() {
    if (jQuery("#searchFilter option:selected").val() != jQuery("#searchFilter option:selected").text())
        return jQuery("#searchFilter option:selected").val();
    else
        return "";
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function RegisterScript(ScriptSrc, ScriptId) {
    var el = jQuery("#" + ScriptId);
    if (el.length < 1) {
        ShowLog("script doesn't exist:" + ScriptId);
        el = document.createElement("script");
        el.type = "text/javascript";
        //script.attributes["id"] = ScriptId;
        el.id = ScriptId;
        el.src = ScriptSrc;
        document.body.appendChild(el);
    } else ShowLog("script exists:" + ScriptId);
}

function ShowLog(s) {
//    var script = document.createElement("div");
//    script.style.display = 'none';
//    var d = new Date();
//    script.innerHTML = d.getMinutes() + ":" + d.getSeconds() + ":" + d.getMilliseconds() + "   -" + s;
//    document.body.appendChild(script);
}

String.prototype.IsNullOrEmpty = function() {
    if (this == null || this == undefined || this == "")
        return true;
    else
        return false;
};

var PageModeTypes =
{
    sellpoints: "sellpoints",
    acceptances: "acceptances"
}

var glHFTitle;
var glLblTitle;

var PageMode = {
    mode: null,
    isInitialized: false,

    initilize: function(_mode) {
        PageMode.mode = _mode;
        PageMode.isInitialized = true;
    }
}