﻿var NUMBER_OF_NEAREST_STORES = 5;
var DETAIL_MAP_PAGE_URL = "/Pages/OpeningHours.aspx";

var userCurrentPosition = null;
var defaultZipCode = 82;
var sharedOpeningHours = null;
var DATE_FORMAT = 'yyyy-MM-dd';
var NEARESET_STORE_COOKIE_NAME = 'NearestStore';
var pageType = null;    //possible types are Main & Detail.

var storesTemplate = '<div class="dsg_sp_FindFotex_StoreResults" id="storeResultsInner[ID]" onmouseover="onMouseOverDiv(this);" onmouseout="onMouseOutDiv(this);"  onclick="showOpeningHours([STORE_ID],null)">[STORE_NAME]<br/>[ADDRESS]<br/>[POSTAL_CODE], [CITY]<br/>Tlf.nr.: [PHONE_NUMBER]<br/><a href="#" >Åbningstider</a><br/><a target="_blank" href="http://www.findsmiley.dk/da-DK/Searching/TableSearch.htm?virk=[VIRK]"><img border="0" src="/Style Library/Customer Core Styles/Styles/Images/FindSmiley.gif" alt="Se smiley-rapport her" /></a></div>';
var openingHoursStoreInfoTemplate = '[STORE_NAME]<br/>[ADDRESS]<br/>[POSTAL_CODE], [CITY]<br/><a target="_blank" href="http://www.findsmiley.dk/da-DK/Searching/TableSearch.htm?virk=[VIRK]"><img border="0" src="/Style Library/Customer Core Styles/Styles/Images/FindSmiley.gif" alt="Se smiley-rapport her" /></a>';
var openingHoursHeadingTemplate = '<tr class="dsg_sp_FindFotex_FullWidth"><td id="[DEPTID]" colspan="2" class="dsg_sp_FindFotex_OpeningHoursDepartmentHeading"><div class="dsg_sp_FindFotex_OpeningHoursDepartmentHeading"> [HEADING] ([Week]) [Year]</div></td></tr>';
var openingHoursTemplate = '<tr style="width:100%"><td class="dsg_sp_FindFotex_StoreHourdayName">[WEEKDAY][DEPTID]</td><td class="dsg_sp_FindFotex_StoreHour">[OPENING_HOURS]</td></tr>';

function loadGoogleAPIs(callBackForInitialize) {

    //Initialize google map apis in a lazy fashion to get better page load time.
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=" + callBackForInitialize;
    document.body.appendChild(script);

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://code.google.com/apis/gears/gears_init.js";
    document.body.appendChild(script);
}

function persistStoresInCookie(stores) {
    if (stores == null) {
        return;
    }

    var s = JSON.stringify(stores);
    setCookie(NEARESET_STORE_COOKIE_NAME, s, null);
}

function searchStore() {

    var searchText = document.getElementById('txtSearch').value;
    if ($.trim(searchText).length > 0) {

        if (typeof ShowProgress == 'function' && pageType == "Detail") {
            ShowProgress();
        }        
        loadStores(searchText);
    }
    else {

        alert(window.StringResources.Store_Search_Empty_Search);
        return;
    }
}

function searchNearestStores(number) {

    if (userCurrentPosition != null) {

        var searchTextbox = document.getElementById('txtSearch');
        if (searchTextbox != null) {
            searchTextbox.value = '';
        }

        storesJSon = getCookie(NEARESET_STORE_COOKIE_NAME);    
        if (storesJSon != null) {
            var stores = eval(storesJSon);
            if (stores != null) {

                if (number != undefined && number != null) {
                    var topResults = new Array();
                    for (var index = 0; index < number; index++) {
                        if (index < stores.length) {
                            topResults[index] = stores[index];
                        }
                        else {
                            break;
                        }
                    }

                    AddStoreMarkers(topResults,true);
                    displayResultsAsHtml(topResults);
                }
                else {
                    AddStoreMarkers(stores,true);
                    displayResultsAsHtml(stores);
                }
            }
        }
    }      
}

function loadStores(searchText) {
    //debugger;
    var result = getStoreResults();
    if (result == null || (undefined != searchText && null != searchText)) {

        if (undefined == searchText || null == searchText) {
            searchText = defaultZipCode; //temporary must be changed later, once service implementation is changed.
        }

        var loadAgain = true;
        var txt = getLastSearchText();

        if ((txt != null && $.trim(searchText) == txt) &&
             result != null) {
            loadAgain = false;
        }

        if (loadAgain == true) {            
            searchData = eval("({scope:'FoetexStores', outputtype:'json', searchText:'" + searchText + "'})");
            callGetStores(searchData, displayStores, null);
        }
        else {
            displayStores(result, 'preloaded');
        }

        setLastSearchText(searchText);
    }
}

function getStoreResults() {    
    if (window.opener != null && window.opener.storeResults != undefined) {
        return window.opener.storeResults;
    }
    else if( window.storeResults != undefined ){
        return window.storeResults;
    }

    return null;
}

function setStoreResults(results) {
    if (window.opener != null && window.opener.storeResults != undefined) {
        window.opener.storeResults = results;
    }
    else {
        window.storeResults = results;
    }
}

function getLastSearchText() {
    if (window.opener != null && window.opener.lastSearchText != undefined) {
        return window.opener.lastSearchText;
    }
    else if (window.lastSearchText != undefined) {
        return window.lastSearchText;
    }

    return null;
}

function setLastSearchText(results) {
    if (window.opener != null && window.opener.lastSearchText != undefined) {
        window.opener.lastSearchText = results;
    }
    else {
        window.lastSearchText = results;
    }
}


function displayStores(response, status) {

    try {
        
        if ((status == 'success' || status == 'preloaded')
              && response != null && response != "") {

            var results = null;           
            results = $.parseJSON(response);
            setStoreResults(response);

            if (results.length > 0) {
                // only details map page should show the stores.
                if (undefined != window.displayStoresInfoAsText && null != window.displayStoresInfoAsText) { //details page check. 
                    AddStoreMarkers(results);                   
                    displayResultsAsHtml(results);
                }
                else {
                    // calculate nearest stores.
                    results = calculateDistance(results, NUMBER_OF_NEAREST_STORES);
                    if (results != null && results.length > 0) {
                        //Persists these in Cookie
                        persistStoresInCookie(results);
                        var stores = new Array();
                        stores[0] = results[0];
                        AddStoreMarkers(stores);    // display one nearest store on front page.
                       
                    }                    
                }                
            }
            else {                
                clearStoreResults();
                removeAllMarkers();
            }
        }
        else {
            alert("result not ok, status = " + status);
        }
    }
    catch (error) {
        alert(error);
    }

    if (typeof HideProgress == 'function' && pageType == "Detail") {
        HideProgress();
    }    
}


function clearStoreResults() {
    $("#storeResultsLeft").html('');
    $("#storeResultsRight").html('');
}

function displayResultsAsHtml(stores) {
    
    if (undefined != stores && null != stores) {
        clearStoreResults(); //clear existing results;

        var element = null;
        for (var index = 0; index < stores.length; index++) {

            if ((index + 1) % 2 == 0) {
                element = document.getElementById("storeResultsRight");
            }
            else {
                element = document.getElementById("storeResultsLeft");
            }

            element.innerHTML = element.innerHTML + replaceStoreInfo(storesTemplate, stores[index], index);            
        }
    }
}


function replaceStoreInfo(template, store, index) {
    var result = template.toString().replace('[STORE_NAME]', store.StoreName).replace(
                    '[ADDRESS]', store.Address).replace('[POSTAL_CODE]', store.PostalCode).replace(
                    '[CITY]', store.CityName).replace('[STORE_ID]', store.StoreId).replace('[VIRK]', store.virk).replace(
                    '[PHONE_NUMBER]', store.PhoneNumber);

    if (index != undefined && index != null) {
        result = result.replace('[ID]', index);
    }

    return result;
}



function showOpeningHours(storeId, deptId) {

    try {       
       
        if (deptId == null) {
            deptId = getDepartmentIDs();            
        }

        //danish culture first day of week is monday i.e., 1.
        var startDate = getStartOfWeek(Date.today(), 1);          
        var endDate = startDate.addDays(6);

        var data = eval("({scope:'FoetexStores',storeid:'" + storeId + "',deptIds:'" + deptId + "'})");        
        callGetStoreDetails(data, displayOpeningHours, null);
    }
    catch (error) {
        alert(window.StringResources.Store_Opening_Hours_Error + " " + error.ToString());
    }

}


function getStartOfWeek(startDate, startOfWeek) {

    var diff = startDate.getDay() - startOfWeek;   
    if (diff < 0)
    {
        diff += 7;
    }    
    return startDate.addDays(-1 * diff);
}

function displayOpeningHoursFromMain(storeId, deptId) {

}

function getDepartmentIDs() {

    var depIds = '';
    $('#departments').children().each(
        function () {
            depIds = depIds + $(this).attr("id") + ",";
        }
    );
    return depIds;
}

function getDepartmentHeadings() {

    var depIds = '';
    $('#departments').children().each(
        function () {
            depIds = depIds + $(this).text() + ",";
        }
    );
    return depIds;
}

function displayOpeningHours(response, status) {
    try {

        
        if (status == 'success' && response != null && response != "") {
            var results = $.parseJSON(response);

            var storeNumber;
            $('#shortAddress').html('');
            if (results.Store != null) {
                $(results.Store).each(function (index) {
                    $(replaceStoreInfo(openingHoursStoreInfoTemplate, this)).appendTo($('#shortAddress'));
                });
            }

            $('#openingHours').html('');
            if (results.OpeningHour != null) {

                var depNumbers = "";
                for (i = 0; i < results.OpeningHour.length; i++) {
                    depNumbers = depNumbers + results.OpeningHour[i].DepartmentNumber + ",";
                }
               
                var objExceptionalHour = new ExceptionalHour();
                objExceptionalHour.StoreNumber = results.Store.StoreNumber;
                objExceptionalHour.DepartmentNumbers = depNumbers;


                var startDate = getStartOfWeek(Date.today(), 1);      
                var endDate = getStartOfWeek(Date.today(), 1).addDays(6);  

                objExceptionalHour.StartDate = startDate.toString(DATE_FORMAT) ;
                objExceptionalHour.EndDate = endDate.toString(DATE_FORMAT);              
                sharedOpeningHours = results.OpeningHour;
                objExceptionalHour.post('RequestHandler.ashx', displayResponse);                
               
            }
            else {//set default opening hours
                var date = new Date();
                $('#openingHours').html($('#defaultOpeningHours').html().replace('[Week]', date.getWeekOfYear()).replace('[Year]', date.getFullYear()));
                DisplayOpeningHoursDialog();
            }            
        }
        else {
            alert("result not ok, status = " + status);
        }
    }
    catch (error) {
        alert(error);
    }
}


function displayResponse(response) {

    if (sharedOpeningHours != null) {        
        var exceptionHours = $.parseJSON(response).ExceptionHoursList;
        for (i = 0; i < exceptionHours.length; i++) {
            startDate = Date.parse(exceptionHours[i].StartDate.toString().substring(0, 10));
            endDate = Date.parse(exceptionHours[i].EndDate.toString().substring(0, 10));

            for (j = 0; j < sharedOpeningHours.length; j++) {

                if ( $.trim(exceptionHours[i].DepartmentNumber) == $.trim(sharedOpeningHours[j].DepartmentNumber)) {
                    openingDate = Date.parse(sharedOpeningHours[j].OpeningDate.toString().substring(0, 10));
                    if ( openingDate >= startDate && openingDate <= endDate ) {
                        sharedOpeningHours[j].OpeningFrom = exceptionHours[i].OpeningFrom;
                        sharedOpeningHours[j].OpeningTo = exceptionHours[i].OpeningTo;
                    }
                }
            }
        }

        showGroupedOpeningHoursByDept(sharedOpeningHours);
        DisplayOpeningHoursDialog();
    }
}

function replaceOpeningHoursInfo(template, openingHour) {

    var date = new Date();
    return template.toString().replace('[HEADING]', 'Uge').replace(
            '[Week]', date.getWeekOfYear()).replace('[Year]', date.getFullYear()).replace(
            '[WEEKDAY]', openingHour.CityName).replace('[OPENING_HOURS]', openingHour.OpeningFrom + ' - ' + openingHour.OpeningTo);
}


function showGroupedOpeningHoursByDept(openingHoursNew) {
    //debugger;
    var departmentDIVs = new Array();

    var date = new Date();
    $('#departments').children('div').each(function (index) {
        //alert($(this).attr("id"));
        departmentDIVs[index] = openingHoursHeadingTemplate.toString().replace('[DEPTID]', $(this).attr("id")).replace(
        '[HEADING]', $(this).text()).replace('[Week]', date.getWeekOfYear()).replace('[Year]', date.getFullYear());
    });

    var div;
    var completeDiv;
    var previousOpeningHours;
    //$(departmentDIVs).each(function (index) {
    for (index = 0; index < departmentDIVs.length; index++) {
        div = departmentDIVs[index];
        completeDiv = div;
        previousOpeningHours = null;
        for (innerIndex = 0; innerIndex < openingHoursNew.length; innerIndex++) {

            if (div.indexOf('id="' + openingHoursNew[innerIndex].DepartmentId + '"') > -1) {

                //if (innerIndex > -1) {

                var dayName = getDanishDayName(Date.parse(openingHoursNew[innerIndex].OpeningDate.toString().substring(0, 10)).getDay()); //Date.parse(openingHoursNew[innerIndex].OpeningDate.toString().substring(0, 10)).getDayName(true);
                var previousdayName = null;

                if (previousOpeningHours != undefined && previousOpeningHours != null) {
                    previousdayName = getDanishDayName(Date.parse(previousOpeningHours.OpeningDate.toString().substring(0, 10)).getDay()); //Date.parse(previousOpeningHours.OpeningDate.toString().substring(0, 10)).getDayName(true);
                }


                if (previousdayName != null && previousOpeningHours.OpeningFrom == openingHoursNew[innerIndex].OpeningFrom &&
                            previousOpeningHours.OpeningTo == openingHoursNew[innerIndex].OpeningTo) {

                    var prevAddedGroup = previousdayName + openingHoursNew[innerIndex].DepartmentId;
                    var currentDayGroup = dayName + openingHoursNew[innerIndex].DepartmentId;

                    if (completeDiv.indexOf("-" + prevAddedGroup) > -1) {

                        completeDiv = completeDiv.replace("-" + prevAddedGroup, "-" + currentDayGroup);
                    }
                    else {

                        completeDiv = completeDiv.replace(prevAddedGroup, previousdayName + "-" + currentDayGroup);
                    }
                    previousOpeningHours = openingHoursNew[innerIndex];
                }
                else {

                    var from = GetFormattedHours(openingHoursNew[innerIndex].OpeningFrom);
                    var to = GetFormattedHours(openingHoursNew[innerIndex].OpeningTo);
                    var time = from + ' : ' + to;
                    if (from == openingHoursNew[innerIndex].OpeningFrom || to == openingHoursNew[innerIndex].OpeningTo) {
                        time = 'Lukket';
                    }
                    completeDiv = completeDiv + openingHoursTemplate.toString().replace(
                        '[WEEKDAY]', dayName).replace(
                        '[OPENING_HOURS]', time).replace(
                        '[DEPTID]', openingHoursNew[innerIndex].DepartmentId);
                    previousOpeningHours = openingHoursNew[innerIndex];
                }
                //}                
            }
        }

        if (completeDiv != div) { //Don't add empty department headings
            $('#openingHours').html($('#openingHours').html() + completeDiv.replace(/[DEPTID]-/g, ''));
        }
    }


    //replace all (DEPTID):

    $('#departments').children('div').each(function (index) {
        $('#openingHours').html( replaceAll($('#openingHours').html(),
                                 $(this).attr("id") , '')
                               ) ;        
    });
    
}

function replaceAll(txt, replace, with_this) {
    return txt.replace(new RegExp(replace, 'g'), with_this);
}

function GetFormattedHours(hour) {
    if (hour.length == 4) {
        if (IsNumeric(hour)) {
            return hour.charAt(0) + hour.charAt(1) + "." + hour.charAt(2) + hour.charAt(3);
        }
    }

    return hour;
}


function getUserLocation() {
    if (navigator.geolocation) {    //browser supports location.
        navigator.geolocation.getCurrentPosition(function (position) {

            if (pageType == "Main") {
                initializeGoogleCallback(position);
            }
            else {
                initializeDetailPageGoogleCallback(position);
            }
        }, function () {
            if (pageType == "Main") {
                initializeGoogleCallback(null);
            }
            else {
                initializeDetailPageGoogleCallback(null);
            }
        });
    }
    else {
        if (pageType == "Main") {
            initializeGoogleCallback(null);
        }
        else {
            initializeDetailPageGoogleCallback(null);
        }
    }
}

/*---------------------------  ------------------------ */
//                      FRONT PAGE MAP
/*---------------------------  ------------------------ */
function initializeFindFoetexMain() {

    pageType = "Main";
    if ($('#map_image').length > 0) {
        $('#map_image').hide();
    }

    window.displayStoresInfoAsText = null;  //identify main page.
    $("#txtSearch").keypress(function (event) {
        if (event.which == 13) {
            event.preventDefault();
            onFindClick();
        }
    });

    if ($("#map_canvas").length > 0) {
        $('#map_canvas').show();
        //Initialize google map apis in a lazy fashion to get better page load time.
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=getUserLocation";
        document.body.appendChild(script);

        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://code.google.com/apis/gears/gears_init.js";
        document.body.appendChild(script);
    }
    else if ($('#map_image').length > 0) {
        $('#map_image').show();
    }   
}

function initializeGoogleCallback(userPosition) {
   
    userCurrentPosition = userPosition;    
    if ($("#map_canvas").length > 0) {        
        initializeGoogleMap(56.154459, 10.206777, null, null,true);
    }

    var nearestStoresJSon = getCookie(NEARESET_STORE_COOKIE_NAME);    
    if (nearestStoresJSon != null) {
        searchNearestStores(1);
    }
    else {
        loadStores(""); //loads all stores.   
    } 
}

function calculateDistance(stores,resultCountToReturn) {

    if (userCurrentPosition == null) {
        return null;
    }

    var distance = 6371;
    var nearestLocation = null;
    var lat = userCurrentPosition.coords.latitude;
    var lon = userCurrentPosition.coords.longitude;
   
    var distanceList = new Array();
    var myArray = new Array();    

    for (var index = 0; index < stores.length; index++) {

        if ((stores[index].Latitude != null && stores[index].Latitude != "") &&
            (stores[index].Longitude != null && stores[index].Longitude != "")) {
            var lat2 = stores[index].Latitude;
            var lon2 = stores[index].Longitude;
            distanceList[distanceList.length] = getDistance(lat, lon, lat2, lon2);
            myArray[distanceList[distanceList.length -1]] = stores[index];
        }
    }

    distanceList.sort(function (a, b) { return a - b });

    var nearestStores = new Array();
    for (var counter = 0; counter < resultCountToReturn; counter++) {
        nearestStores[counter] = myArray[distanceList[counter]];
    }

    return nearestStores;
}

function onFindClick() {

    var searchText = $.trim($('#txtSearch').val());

    if (searchText.length > 0) {
        window.FrontMapSearchText = searchText;
        window.open(DETAIL_MAP_PAGE_URL + "?search=" + searchText, "_self");
    }
    else {
        alert(window.StringResources.Store_Search_Empty_Search);
    }
}


/*---------------------------------------------*/
/*          Detail page                        */
/*---------------------------------------------*/

function initializeDetailPageGoogleCallback(userPosition) {

    userCurrentPosition = userPosition;
    window.displayStoresInfoAsText = true;
    initializeGoogleMap(56.154459, 10.206777, null, null, true);

    if (window.location.search.indexOf("?search=") > -1) {
        loadStores(window.location.search.toString().replace("?search=", ""));
    }
    else if (window.location.search.indexOf("?storeId=") > -1) {
        searchNearestStores(1);
        showOpeningHours(window.location.search.toString().replace("?storeId=", ""), null);
    }

    if (navigator.geolocation) {
        $('#findNearestFotexLink').show();
    }
    else {
        $('#findNearestFotexLink').hide();
    }
}


function detailPageOnReady() {

    pageType = "Detail";
    if (isFromMainPage() == false) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "/Style Library/Customer Core Styles/Scripts/Global.js";
        document.body.appendChild(script);
    }

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=getUserLocation";
    document.body.appendChild(script);

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://code.google.com/apis/gears/gears_init.js";
    document.body.appendChild(script);


    window.displayStoresInfoAsText = true;
    $('#txtSearch').focus();

    $("#txtSearch").keypress(function (event) {
        if (event.which == 13) {
            event.preventDefault();
            searchStore();
        }
    });

}

function isFromMainPage() {
    return (window.location.search.indexOf("?search=") > -1 
    || window.location.search.indexOf("?storeId=") > -1);
}

function ShowDialog(TargetElement, title) {
    if (dialog.targetElement != null) {
        dialog.showDialog();
    }
    else {
        var element = TargetElement;
        element.appendTo($('body'));
        dialog.targetElement = element[0];
        dialog.ShowTitleBar = true;
        dialog.title = title;
        dialog.modal = true;
        dialog.draggable = true;
        dialog.resizable = false;
        dialog.position = ['center', 'center'];
        dialog.width = "380px";
        dialog.maxHeight = "400px";
        dialog.showDialog();
        dialog.changeTitlebarClass("");
    }

    //setFoetexTop();
};

function DisplayOpeningHoursDialog() {
    var date = new Date();
    ShowDialog($('#hiddenContainer'), "Butikkens åbningstider uge(" + date.getWeekOfYear() + ")");
}

function onMouseOverDiv(div) {
    $('#' + div.id).css({ 'background-color': '#ddd', 'cursor': 'hand' })
}

function onMouseOutDiv(div) {
    $('#' + div.id).css({ 'background-color': 'Transparent', 'cursor': 'default' })
}

function ShowProgress() {

    if (window.StoresProgressOverlay == undefined || window.StoresProgressOverlay == null) {
        window.StoresProgressOverlay = new dk_dsg_msd_Progress();
        window.StoresProgressOverlay.Container = '#mainDiv';
    }
    window.StoresProgressOverlay.showProgress();
}

function HideProgress() {
    if (window.StoresProgressOverlay != null) {
        window.StoresProgressOverlay.hideProgress();
    }
}


function IsNumeric(strString)
//  check for valid numeric strings	
{
    var strValidChars = "0123456789";
    var strChar;
    var blnResult = true;

    if (strString.length == 0) return false;

    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}
