﻿var intPaginationCurrent = 1;
var selectedItemsList = $('');

function onSelectionChange(propertyName) {
    $('#activity').show("fast", function () {
        $('#activity').fadeIn("fast", function () {
            updateCriteriaInfo(propertyName);
            displayProductList();
            setSliderRanges();
        }).fadeOut();
    });
}

function displayProductList() {
    var displayItems = $(''); // Selection for holding items that match criteria
    $('#productSearchResultContent').children().each(function (index) {
        if (isDisplayProduct($(this)) == true)
            displayItems = $(displayItems).add($(this));

    });
    $('#productSearchResultContent').children().hide();
    selectedItemsList = displayItems;

    paginationDisplayPage(intPaginationCurrent);

}


/**
 * getIntervalValueFromSliderPosition
 * @param parameterName - for identifying slider
 * @param positionIndex - index in the interval-array
 * @return value - item value in the interval-array
 **/
function getIntervalValueFromSliderPosition(parameterName, positionIndex) {
    var arrInterval = $("#interval_" + parameterName).val().split(',');
    var value = arrInterval[parseInt(positionIndex)];
    arrInterval = null;
    return value;
}


/**
* isDisplayProduct
* @param node productNode
* @param [optional] int specificationParameterIgnore - ignore this parameter for determining if product is diaplayable - used for calculating selector options
* @return bool
*/
function isDisplayProduct(productNode, specificationParameterIdIgnore) {

    var isDisplayed = true;
    // Check regular sliders (two handles)
    for (var i = 1; i < productFilters.sliders.length; i++) {
        var propertyName = productFilters.sliders[i];
        var propertyValue = productNode.data('att_' + propertyName);
        if (typeof specificationParameterIdIgnore == 'undefined' || specificationParameterIdIgnore != propertyName) {
            if ($('#amount_' + propertyName + '_1').val() == $('#amount_' + propertyName + '_min').val() && $('#amount_' + propertyName + '_2').val() == $('#amount_' + propertyName + '_max').val()) {
                // Both slider-handles are in extreme positions (min and max) - in this case we ignore the parameter so that products with no value specified are displayed
            }
            else if ("" != $('#interval_' + propertyName).val() && $('#amount_' + propertyName + '_1').val() == getIntervalValueFromSliderPosition(propertyName, $('#amount_' + propertyName + '_min').val()) && $('#amount_' + propertyName + '_2').val() == getIntervalValueFromSliderPosition(propertyName, $('#amount_' + propertyName + '_max').val())) {
                // Stepped slider
                // Both slider-handles are in extreme positions (min and max) - in this case we ignore the parameter so that products with no value specified are displayed
            }
            else {
                var valueMin = $('#amount_' + propertyName + '_1').val();
                var valueMax = $('#amount_' + propertyName + '_2').val();
                if (propertyValue < valueMin || propertyValue > valueMax) {
                    isDisplayed = false;
                }
            }
        }
    }

    // Checkboxes
    for (var i = 0; i < productFilters.selectingItems.length; i++) {
        var propertyName = productFilters.selectingItems[i];
        var propertyValue = productNode.data('att_'+propertyName);
        var valuesChecked = getCookie('searchCriteria_' + propertyName);
        if (null == valuesChecked)
            valuesChecked = '';
        valuesChecked = valuesChecked.replace(/^\s+|\s+$/g, '') //trimmed for whitespace
        if ('' != valuesChecked) {
            var valuesCheckedList = valuesChecked.split("#");
            if (typeof specificationParameterIdIgnore == 'undefined' || specificationParameterIdIgnore != propertyName) {
                if (false == in_array(propertyValue, valuesCheckedList)) {
                    isDisplayed = false;
                }
            }
        }
    }

    // boolean-sliders
    for (var i = 0; i < productFilters.boolSliders.length; i++) {
        var propertyName = productFilters.boolSliders[i];
        var propertyValue = productNode.data('att_' + propertyName);
        var selectedValue = $('#booleanSliderValue_' + propertyName).val();
        if (selectedValue != "") {
            if (typeof specificationParameterIdIgnore == 'undefined' || specificationParameterIdIgnore != propertyName) {
                if (selectedValue.toString() != propertyValue.toString()) {
                    isDisplayed = false;
                }
            }
        }
    }

    return isDisplayed;
}


function paginationPrevious() {
    if (intPaginationCurrent > 1) {
        return paginationDisplayPage(intPaginationCurrent - 1);
    }
}

function paginationNext() {
    return paginationDisplayPage(intPaginationCurrent + 1);
}

function paginationDisplayPage(pageNumber) {
    if (typeof intPaginationItemsPerPage != 'undefined') {
        var itemsPerPage = intPaginationItemsPerPage;
        if ('all' == intPaginationItemsPerPage)
            itemsPerPage = parseInt($(selectedItemsList).length);

        // Update pagination links
        var intAmountPages = Math.ceil(parseInt($(selectedItemsList).length) / itemsPerPage);

        if (pageNumber > intAmountPages) // If a selection
            pageNumber = intAmountPages;
        else if (pageNumber == 0 && intAmountPages > 0)
            pageNumber = 1;

        var displayItems = selectedItemsList;
        var firstItemPosition = ((pageNumber - 1) * itemsPerPage);

        $('#productSearchResultContent').children().hide();
        displayItems = $(displayItems).slice(firstItemPosition, firstItemPosition + itemsPerPage);
        $(displayItems).show();

        intPaginationCurrent = pageNumber;

        var strPaginationLinks = "";
        for (j = 0; j < intAmountPages; j++) {
            var intPageNumber = j + 1;
            var selected = "";
            if (intPageNumber == pageNumber)
                selected = "text-decoration:underline;";
            strPaginationLinks = strPaginationLinks + "<a onclick=\"javascript:paginationDisplayPage('" + intPageNumber + "')\" style=\"cursor:pointer; " + selected + "\">" + intPageNumber + "</a> ";
        }

        $('.paginationLinks').html(strPaginationLinks);

        $('.paginationItemCount').html($(selectedItemsList).length + " stk.");
        //$('.paginationItemCount').effect('highlight', {}, 2500);
    }
}

function setPaginationItemsPerPage(intAmount) {
    intPaginationItemsPerPage = intAmount;
    paginationDisplayPage(1);
}

/**
 * Sort listed products based on selected parameter
 * @param node - select-element object
 */
function productListSort(objSelect) {
    var sortParameter = $(objSelect).find(':selected').val();
    if ("" == sortParameter) {
        return;
    }

    var productList = $('#productSearchResultContent');
    sortNodeList(productList, sortParameter);
    displayProductList();
}

function sortNodeList(objNodeList, sortParameter) {
    var listItems = objNodeList.children().get();

    listItems.sort(function (a, b) {
        var compA = $(a).data('att_' + sortParameter);
        var compB = $(b).data('att_' + sortParameter);
        return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    });

    $.each(listItems, function (idx, itm) { objNodeList.append(itm); });
}


function toggleParameterButton(specificationParameterId, intParameterValueNumber)
{
    if ($('#inputButton' + specificationParameterId + '_' + intParameterValueNumber).attr('checked')) {
        $('#inputButton' + specificationParameterId + '_' + intParameterValueNumber).removeAttr('checked');
        $('#btnParam' + specificationParameterId + '_' + intParameterValueNumber).removeClass('slider-range-btn-active');
    }
    else {
        $('#inputButton' + specificationParameterId + '_' + intParameterValueNumber).attr('checked', 'checked');
        $('#btnParam' + specificationParameterId + '_' + intParameterValueNumber).addClass('slider-range-btn-active');
    }

    onSelectionChange(specificationParameterId);
    //updateCriteriaInfo(specificationParameterId);
    //displayProductList();
    //setSliderRanges();
}


/**
 * Toggle whether productId to list for product-comparison
 * @param int intProductId
 */
function toggleCompare(intProductId) {
    var currentCompareProductIds = getCookie("productCompare");
    if (null == currentCompareProductIds)
        currentCompareProductIds = '';

    var arrProductIds = currentCompareProductIds.split("#");

    var index = null;
    for (var i = 0; i < arrProductIds.length; i++) {
        if (arrProductIds[i] == intProductId) {
            index = i;
        }
    }

    if (document.getElementById('productCompare_' + intProductId) && document.getElementById('productCompare_' + intProductId).checked == true) {
        if (arrProductIds.length <= 4) {
            // Add to comparison list if not already there
            if (null == index)
                arrProductIds.push(parseInt(intProductId));
        }
        else {
            //alert("Du kan maksimalt sammenligne 4 produkter ad gangen. Fjern evt. et af de valgte produkter for at vælge nye til sammenligning");
            $("#dialog-modal").dialog({
                height: 160,
                modal: true,
                show: "blind",
                hide: "fold"
            });
            $('#productCompare_' + intProductId).removeAttr("checked");
        }
    }
    else {
        // Remove from comparison list
        if (null != index)
            arrProductIds.splice(index, 1);
    }

    var strProductIds = arrProductIds.join("#");
    setCookie("productCompare", strProductIds, 3);
}



//expires = hours
function setCookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct
    expires time
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
	((expires) ? ";expires=" + expires_date.toGMTString() : "") +
	((path) ? ";path=" + path : "") +
	((domain) ? ";domain=" + domain : "") +
	((secure) ? ";secure" : "");
}



// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function getCookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (var i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}



// this deletes the cookie when called
function deleteCookie(name, path, domain) {
    if (getCookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}



function checkboxItemAll(argVarName, argAllNone) {
    if (argAllNone == "all") {
        var blnChecked = true
    }
    else if (argAllNone == "none") {
        var blnChecked = false
    }
    var arrInputs = document.getElementById("list_" + argVarName).getElementsByTagName('input')
    for (var i = 0; i < arrInputs.length; i++) {
        arrInputs[i].checked = blnChecked;
    }
    updateCriteriaInfo(argVarName)
}

function updateCriteriaInfo(argVarName, argValue) {
    if (document.getElementById("list_" + argVarName))//checkbox eller radio
    {
        var arrInputs = document.getElementById("list_" + argVarName).getElementsByTagName('input');
        var strCookie = "";
        var intCount = 0;
        for (var i = 0; i < arrInputs.length; i++) {
            if (arrInputs[i].checked == true) {
                strPrefix = "";
                if (intCount > 0)
                    strPrefix = "#";
                strCookie += strPrefix + arrInputs[i].value;
                intCount++;
            }

        }
    }
    else//select
    {
        strCookie = argValue
    }
    setCookie("searchCriteria_" + argVarName, strCookie, 3);
}

function goToWebsiteProductPage(strEAN) {
    var strDestinationPage = "http://www.punkt1.dk/products/details/" + strEAN + ".aspx";
    window.top.location.href = strDestinationPage;
}

function parseNumber(stringValue) {
    var arrValue = stringValue.toString().split(",");
    return parsedValue = arrValue.join(".");
}

function in_array(needle, haystack) {
    var key = ''
    for (key in haystack) {
        if (haystack[key] == needle) {
            return true;
        }
    }
    return false;
}

function isset(varname) {
    if (typeof (window[varname]) != "undefined") return true;
    else return false;
}

function cleanArray(actual) {
    var newArray = new Array();
    for (var i = 0; i < actual.length; i++) {
        if (actual[i]) {
            newArray.push(actual[i]);
        }
    }
    return newArray;
}


function pageCookie() {
    var tempPageCookie = getCookie("searchCriteria_pagetype");
    if (isset("strSearchPageType")) {
        if (!tempPageCookie || tempPageCookie != strSearchPageType) {
            deletePageCookies()
            setCookie("searchCriteria_pagetype", strSearchPageType, 3);
        }
    }
    else {
        if (tempPageCookie)
            deletePageCookies()
    }
}
function deletePageCookies() {
    var a_all_cookies = document.cookie.split(';');
    for (var i = 0; i < a_all_cookies.length; i++) {
        a_temp_cookie = a_all_cookies[i].split('=');
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        if (cookie_name.substring(0, 15) == "searchCriteria_") {
            deleteCookie(cookie_name)
        }
    }


}

function resetSelections() {
    deletePageCookies();
    document.location = document.location;
}

window.onload = pageCookie;


