﻿if (initCaller != null)
    initCaller.push("initMarketByPostCode()");

var MarketByPostCodeProgress = true;

function initMarketByPostCode() {
	$("a.searchPostCode").click(function() {
		searchPostCode($(this));
		return false;
	});
	$("a.fancybox_searchPostCode").click(function() {
		fancybox_searchPostCode($(this));
		return false;
	});

    $(".postalCode").keypress(function(e) {
        var mailPanel = $(this).parents(".findShopDummyClass").get(0);
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            searchPostCode($('.searchPostCode', mailPanel));
            return false;
        } else {
            return true;
        }
    });

    if ($("#localshop_postnumber").length > 0) {
        if (NG.Portal.Mix.Web.CommonMethods.ShowAjax("GetAllMarkets")) {
            $.ajax({
                type: "POST",
                url: AjaxServiceUrl + "/GetMarkets",
                contentType: "application/json; charset=utf-8",
                data: "{}",
                success: function(response) {
                    NG.Portal.Mix.Web.CommonMethods.HideAjax("GetAllMarkets");
                    Markets = ($.evalJSON(response)).d;
                    initMainMap();
                },
                error: function(response) {
                    NG.Portal.Mix.Web.CommonMethods.HideAjax("GetAllMarkets");
                }
            });
        }
    }
    else {
        initMainMap();
    }

    $(".menuPC").keyup(function(e) {
        var mailPanel = $(this).parents(".findShopDummyClass").get(0);

        if (Markets != null) {
            var ar = new Array();
            var postCode = $(".inputText", mailPanel).val();
            if (postCode != $(".inputText", mailPanel).attr('title')) {
                var code = Number(postCode)
                if (code != 'NaN' && postCode.length == 4) {
                    for (var j = 0; j < Markets.length; j++) {
                        if (Markets[j].PostalCode.toString().indexOf(postCode) == 0) {
                            ar.push(Markets[j]);
                        }
                    }
                }
            }
            showMenu(ar);
        }
        return true;

    });
}

function searchPostCode(element) {
    if (MarketByPostCodeProgress) {
        var mailPanel = $(element).parents(".findShopDummyClass");
        var useCustomerPaper = mailPanel.hasClass("region");
        var selectStoreIfFound = mailPanel.hasClass("saveStore");
        var validatePostalCodeForm = new NG.Portal.Mix.Web.ValidationClass(mailPanel);
        if (validatePostalCodeForm.Validate() && NG.Portal.Mix.Web.CommonMethods.ShowAjax("MarketByPostCode")) {
            var postCode = $(".inputText", mailPanel).val();
            if (postCode != $(".inputText", mailPanel).attr('title')) {
                MarketByPostCodeProgress = false;
                //default handling is get /GetMarketsByPostCode, looks up ALL markets with
                //given postcode. async ajax callback is onSuccessStoreByPostCode (look further down in this file)
                var webMethod = AjaxServiceUrl + "/GetMarketsByPostCode";
                var successCallback = onSuccessStoreByPostCode;
                
                //change handling to search for customer paper (only if mailPanel has css class "region")
                if (useCustomerPaper) {
                    webMethod = AjaxServiceUrl + "/GetCustomerPaperUrlByMarketPostCode";
                    var successCallback = onSuccessPostCode;
                }

                //not else
                if(selectStoreIfFound)
                {
                    webMethod = AjaxServiceUrl + "/GetMarketIdByPostCode";
                    successCallback = onSuccessMarketByPostCode;
                }
                
                //excecute async post to backend
                $.ajax({
                    type: "POST",
                    url: webMethod,
                    data: "{PostCode:'" + postCode + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: successCallback,
                    error: onFailPostCode
                });
            }
        }
    }
}

function showMenu(ar) {
    var postalDiv = $('#localshop_postnumber');
    var claerDiv = $(".clearfloat", postalDiv);
    $("#postalMenu", postalDiv).remove();
    if (ar.length > 0) {
        var str = "<ul id='postalMenu'>";
        for (var j = 0; j < ar.length; j++) {
            str = str + "<li><a href='javascript:SetStoreAsCurrent(" + ar[j].MarketId + ");'>" + ar[j].PostalCode + ' ' + ar[j].Name + "</a></li>";
        }
        
        str = str + "</ul>";
        claerDiv.after(str);
    }

    
}

function onSuccessPostCode(link) {
    NG.Portal.Mix.Web.CommonMethods.HideAjax("MarketByPostCode");
    if (link.d != null) {
        //simple check to see if the string is "empty" (space is considered empty space)
        if (link.d.replace(/\s/g, "") === "") {
            //if link.d is empty we are missing link to customer paper, post an error message
            $.modal("Vi finner ikke kundeavisen til postnummeret du ber om. Forsøk å gå inn på din nærmeste butikk og se på tilbudene her.",
                {
                    containerCss: {
                        width: "400px",
                        height: "300px"
                    }
                });
        }
        else {
            //creates a simple modal as a lightbox for customer paper
            showCustomerPaperInSimpleModal(link.d);
        }
        //document.location.href = link.d;
    }
    else
    {
        alert(getAlertMessage("PostCode"));
    }
    
    MarketByPostCodeProgress = true;
}

function onSuccessStoreByPostCode(link) {
    NG.Portal.Mix.Web.CommonMethods.HideAjax("MarketByPostCode");
    if (link.d != null) {
        //handles search for markets by postcode
        var count = link.d[0]; //number of markets found
        var url = link.d[1]; //link to first market
        var longitude = link.d[2]; //longitude of _first_ market with longitude
        var latitude = link.d[3]; //latitude of _first_ market with longitude
        var zoomLevel = parseInt(link.d[4]);

        //alert(zoomLevel);
        
        //if more than one market, zoom in on the position of the first market (zoom level = 11)
        if (count > 1) {
            if (GoogleMapInstance) {
                GoogleMapInstance.SetCenterAndScale(latitude, longitude, zoomLevel);
            }
        }
        else {
            //if only one market, redirect to the shop page for that market :)
            document.location.href = url;
        }
    }
    else {
        alert(getAlertMessage("PostCode"));
    }

    MarketByPostCodeProgress = true;
}

function onSuccessMarketByPostCode(pageId)
{
    NG.Portal.Mix.Web.CommonMethods.HideAjax("MarketByPostCode");
    if (pageId.d != null) {
        //alert(pageId.d);
        //this code is in ShopChooser.js
        //SetStoreAsCurrent(pageId.d);
    	RedirectToStorePage(pageId);
        //document.location.href = link.d;
        
    }
    else
    {
        alert(getAlertMessage("PostCode"));
    }
        
    MarketByPostCodeProgress = true;
}

function onFailPostCode(error) {
    NG.Portal.Mix.Web.CommonMethods.HideAjax("MarketByPostCode");
    alert(getAlertMessage("PostCodeRequestError"));
    MarketByPostCodeProgress = true;
}

function showCustomerPaperInSimpleModal(url) {
    //track customerpaper in google
    trackGaEvent('Kundeavis', 'Klikk på kundeavis');
    
    spaceForRightHandSide = 86;  //86px is needed to show the "close" button properly
    paperRatio = 1.4; //width/height ratio of the customer paper
    heightMargin = 15; //adjustment for bottom margin in "lightbox" (modal popup)

    pSize = 0.90;
    
    ieLeftMarginAdjustment = 35;

    //fetch height and calulate max horizontal and vertical sizes for the customer paper

    wHeight = $(window).height();
    wWidth = $(window).width();

    widthNinty = wWidth * pSize;
    heightNinty = wHeight * pSize;

    maxWidth = widthNinty - spaceForRightHandSide;
    maxHeight = heightNinty - heightMargin;

    //need the ratio of the maxWidth/maxHeight to be enable to shrinkwrap the boxes around the
    //customer paper, and to set the correct size of the customerpaper for "best view" in current window size
    ratio = (maxWidth / maxHeight)

    wPx = hPx = iHeight = iWidth = leftmargin = 0;

    //shrink wrapping and defining all sizes for "lightbox"
    if (ratio > paperRatio) {
        twpx = parseInt(heightNinty * paperRatio);
        wPx = twpx + "px";
        hPx = parseInt(heightNinty) + "px";
        iWidth = (twpx - spaceForRightHandSide) + "px";
        iHeight = parseInt((twpx - spaceForRightHandSide) / paperRatio) + "px";
        
        leftmargin = getLeftMarginForIE(-(twpx - spaceForRightHandSide), -ieLeftMarginAdjustment);

    }
    else {
        twpx = parseInt(widthNinty);
        wPx = twpx + "px";
        hPx = parseInt(widthNinty / paperRatio) + "px";
        iWidth = (twpx - spaceForRightHandSide) + "px";
        iHeight = parseInt((twpx - spaceForRightHandSide) / paperRatio) + "px";
        
        leftmargin = getLeftMarginForIE(-(twpx - spaceForRightHandSide), -ieLeftMarginAdjustment);

    }

    //Set width and height of iframe that shows the customerpaper
    $("#cpIframe").css("width", iWidth);
    $("#cpIframe").css("height", iHeight);
  
    ver = getInternetExplorerVersion();

    //Set the url of the customerpaper
    $("#cpIframe").attr("src", url);
//        var iframe = $("#cpIframe")[0];
//        iframe.contentWindow.location.reload(true);
    
    if(ver > -1 && ver < 8.0) {
        //apply IEfix fo iframe..
        $("#cpIframe").css("margin-left", leftmargin);
    }
    
    if(ver > -1) {
        //iframe src does not work properly with IE, if IE try location.href then reload
        var iframe = $("#cpIframe")[0];
        
        try {
            iframe.contentWindow.location.href = url;
        }
        catch(err) {
            //ignore exception, and show lightbox
        }
    }
   
    //open the "lightbox" and set the size of the container (that big white background div)
    $("#cpForModal").modal({
                containerCss: {
                    width: wPx,
                    height: hPx
                }
            }
        );
}

function getInternetExplorerVersion() {

    var rv = -1; // Return value assumes failure.

    if (navigator.appName == 'Microsoft Internet Explorer') {

        var ua = navigator.userAgent;

        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");

        if (re.exec(ua) != null)

            rv = parseFloat(RegExp.$1);

    }

    return rv;

}

function getLeftMarginForIE(width, extraAdjustment) {
    var unadjustedMargin = parseInt(width/2);
    var adjustedMargin = unadjustedMargin + extraAdjustment;

    return adjustedMargin + "px";
}
