//================= Diverse funktioner der bruges rundt omkring på sitet

//============= Globale variabler sættes
// De første bruges i getProductList() funktionen
var globalBrand = '',
  globalType = '',
  globalColor = '',
  globalSize = '';
quickViewTopMargin = '';
getProduct = true;

var arrSearchCategories = new Array();
arrSearchCategories[0] = "genders";
arrSearchCategories[1] = "brands";
arrSearchCategories[2] = "types";
arrSearchCategories[3] = "colors";
arrSearchCategories[4] = "sizes";

var _seasonNumber = 0;

// arrBrands bruges i toogleBrands() funktionen
var arrBrands = new Array();
var endHereForward,
  startHereForward = 0,
  endHereBack = 0,
  startHereBack,
  theEndIsHere = false,
  theStartIsHere = true,
  countIndicator = 1,
  numOfSteps = 0,
  brandCount = 0;

//quickview
var quickLookOpen = false;
var blockDetail = false;
// Hover funktion på "søge menuen"
function hoverCategory(obj, state) {
    var $object = $(obj);
    state = parseFloat(state);
    if (state === 1) {
        $object.find('span.shadowFirst').addClass('shadowFirstBg');
        $object.find('a').addClass('productSearchHover');
        $object.find('span.shadowLast').addClass('shadowLastBg');
    } else if (state === 2) {
        $object.find('span.shadowFirst').removeClass('shadowFirstBg');
        $object.find('a').removeClass('productSearchHover');
        $object.find('span.shadowLast').removeClass('shadowLastBg');
    }
}

// Slide down funktion - Viser og skjuler søgekriterer. Hvis man eksempelvis trykker 
// type bliver alle typer vist
function slideCategory(obj, slide, productSearch) {
    var $object = $(obj).parent();
    var idToShow = $object.attr('rel');
    var $showThis = $('#' + idToShow);
    var boxIsVisible = $('.searchDropdown').is(':visible');
    var $removeClass,
    isChosen,
    $curShowObject;

    if (boxIsVisible) {
        var $visibleBox = $('.searchDropdown:visible');
        var visibleBoxId = $visibleBox.attr('id');
        if (visibleBoxId != idToShow) {
            $visibleBox.hide();
            $showThis.show();
            $removeClass = $('li[rel="' + visibleBoxId + '"]');
            $removeClass.find('span.shadowFirst').removeClass('shadowFirstBg');
            $removeClass.find('a').removeClass('productSearchHover');
            $removeClass.find('span.shadowLast').removeClass('shadowLastBg');

            isChosen = $removeClass.find('a span').hasClass('chosenCat');
            if (!isChosen) {
                $removeClass.find('a span').removeClass().addClass('slideDownCat');
            }

            $("." + $removeClass.attr('rel') + "_arrow").css("visibility", "hidden");
            $("." + idToShow + "_arrow").css("visibility", "visible");

            $removeClass.bind('mouseenter', function () { hoverCategory(this, 1); });
            $removeClass.bind('mouseleave', function () { hoverCategory(this, 2); });
            $object.unbind('mouseenter, mouseleave');

            isChosen = $object.find('a span').hasClass('chosenCat');
            if (!isChosen) {
                $object.find('a span').removeClass().addClass('slideUpCat');
            }


        } else if (visibleBoxId == idToShow) {
            $removeClass = $('li[rel="' + visibleBoxId + '"]');
            isChosen = $removeClass.find('a span').hasClass('chosenCat');
            if (!isChosen) {
                $removeClass.find('a span').removeClass().addClass('slideDownCat');
            }
            $showThis.slideUp();
            $removeClass.bind('mouseenter', function () { hoverCategory(this, 1); });
            $removeClass.bind('mouseleave', function () { hoverCategory(this, 2); });

            $("." + idToShow + "_arrow").css("visibility", "hidden");
        }
    } else {
        if (slide) {
            $showThis.slideDown();
            isChosen = $object.find('a span').hasClass('chosenCat');
            if (!isChosen) {
                $object.find('a span').removeClass().addClass('slideUpCat');
            }
            $object.unbind('mouseenter, mouseleave');

            $("." + idToShow + "_arrow").css("visibility", "visible");
        }
    }



}

// Denne funktion bruges til at fjerne et søgekritere
function removeProduct(seasonNum, shoeCategory, brand, type, color, size, pageId, catNum, obj) {
    catNum = parseFloat(catNum);

    switch (catNum) {
        case 1:
            globalBrand = '';
            break;
        case 2:
            globalType = '';
            break;
        case 3:
            globalColor = '';
            break;
        case 4:
            globalSize = '';
            break;
    }

    getProductList('', catNum, pageId, seasonNum, shoeCategory, brand, type, color, size, true)
    $(obj).parent().addClass('displayNone');
    $(obj).remove();
    $('#searchBread_productNr').hide();
}

// Denne funktion bruges til at hente produktlister
function getProductList(obj, catNum, pageId, seasonNum, shoeCategory, brand, type, color, size, remove) {
    catNum = parseFloat(catNum);

    var navBreadText = $(obj).html();

    var urlString = '/1094.aspx?seasonNumber='
    urlString += seasonNum;
    urlString += '&pageid=';
    urlString += pageId;
    urlString += '&shoecategory=';
    urlString += shoeCategory;
    if (brand.length > 0) {
        urlString += '&brand=';
        urlString += brand;
        globalBrand = brand;
    } else if (globalBrand > 0) {
        urlString += '&brand=';
        urlString += globalBrand;
    }

    if (type.length > 0) {
        urlString += '&type=';
        urlString += type;
        globalType = type;
    } else if (globalType.length > 0) {
        urlString += '&type=';
        urlString += globalType;
    }

    if (color.length > 0) {
        urlString += '&color=';
        urlString += color;
        globalColor = color;
    } else if (globalColor.length > 0) {
        urlString += '&color=';
        urlString += globalColor;
    }

    if (size.length > 0) {
        urlString += '&size=';
        urlString += size;
        globalSize = size;
    } else if (globalSize.length > 0) {
        urlString += '&size=';
        urlString += globalSize;
    }

    $.ajax({
        type: "GET",
        url: GetEncodedUrl(urlString),
        success: function (data) {
            $('#productList').html(data);

            if (remove) {
                $('li[rel="' + arrSearchCategories[catNum] + '"]').find('a span').removeClass().addClass('slideDownCat');
                $('#' + arrSearchCategories[catNum]).find('a').removeClass();
            } else {
                switch (catNum) {
                    case 1:
                        brand = '';
                        break;
                    case 2:
                        type = '';
                        break;
                    case 3:
                        color = '';
                        break;
                    case 4:
                        size = '';
                        break;
                }

                var newElem = $('<a></a>').html(navBreadText).bind('click', function () {
                    removeProduct(seasonNum, shoeCategory, brand, type, color, size, pageId, catNum, this);
                    return false;
                }).attr('href', '/');

                $('#' + arrSearchCategories[catNum]).find('a').removeClass();
                $(obj).addClass('activeCat');
                $('li[rel=' + arrSearchCategories[catNum] + ']').find('a span').removeClass().addClass('chosenCat');

                var hasClass = $('#searchBread_' + arrSearchCategories[catNum]).hasClass('displayNone');
                if (!hasClass) {
                    $('#searchBread_' + arrSearchCategories[catNum]).find('a').replaceWith(newElem);
                } else {
                    $('#searchBread_' + arrSearchCategories[catNum]).append(newElem).removeClass('displayNone');
                }
            }
        }
    });

    //Vis clearSearch (Ryd) knap, ved sorterings oversigten
    $('div.clearSearchJQ').removeClass('displayNone');
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  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 GetEncodedUrl(urlString)
{
  var msg = "You're not using Internet Explorer.";
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    return Utf8.encode(urlString);
  }
  
  return urlString;
}

var Utf8 = {
 
  // public method for url encoding
  encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";
 
    for (var n = 0; n < string.length; n++) {
 
      var c = string.charCodeAt(n);
 
      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      }
      else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }
 
    }
 
    return utftext;
  },
 
  // public method for url decoding
  decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;
 
    while ( i < utftext.length ) {
 
      c = utftext.charCodeAt(i);
 
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
 
    }
 
    return string;
  }
 
}


function encodeLatin1URIComponent(str) { 
    var bytes= ''; 
    for (var i= 0; i<str.length; i++) 
        bytes+= str.charCodeAt(i)<256? str.charAt(i) : '?'; 
    return escape(bytes).split('+').join('%2B'); 
} 

// Lukker quickview popupen
function closeQuickView(obj) {
    obj.remove();
    quickLookOpen = false; //markerer at der ikke allerede er et vindue åbent
    getShop = false;
    // Søger for at produktet kan blive vist i detaljevisningen igen
    getProduct = true;
}

// Genererer quickview popupen og viser den



//var $currentObj;
function quickView(productId, seasonnumber) {
    // Søger for at produktet ikke bliver loaded bag quickvieweren

    if (!quickLookOpen) {
        quickLookOpen = true;
        getProduct = false;

        var $quickViewWrap = $('<div></div>');
        var $quickViewTop = $('<div></div>');
        var $quickViewMiddle = $('<div></div>');
        var $quickViewBottom = $('<div></div>');
        var $closeQuickview = $('<a href="#"></a>');
        var $closeQuickviewImg = $('<img src="/images/gfx_closeQuickview.png"></img>');

        $closeQuickview.addClass('closeQuickview').append($closeQuickviewImg);

        currentObj = $quickViewWrap;
        $closeQuickview.bind('click', function () {
            closeQuickView($quickViewWrap);
            return false;
        });

        $quickViewTop.addClass('quickViewTop');
        $quickViewMiddle.addClass('quickViewMiddle').append($closeQuickview)
        $quickViewBottom.addClass('quickViewBottom');
        $quickViewWrap.attr('id', 'quickViewWrap').append($quickViewTop).append($quickViewMiddle).append($quickViewBottom);

        var quickviewUrl = '/1135.aspx?productID=';
        quickviewUrl += productId;
        quickviewUrl += '&seasonnumber=';
        quickviewUrl += seasonnumber;

        $.ajax({
            type: "GET",
            url: quickviewUrl,
            success: function (data) {
                $quickViewMiddle.append(data);

                $('body').prepend($quickViewWrap);
                calculateTopMargin();
                $(window).bind('resize', function () {
                    calculateTopMargin();
                }).bind('scroll', function () {
                    scrollCalculate();
                });

            }
        });

    }

    else {

        //closeQuickView(currentObj);
        //quickLookOpen = true;

    }
}

// Beregner quickview margin til toppen af vinduet
function calculateTopMargin() {
    var h = parseFloat($(window).height());
    var w = parseFloat($(window).width());
    var quickViewHeight = 378;

    var browserWindow = $(window);
    var browserTopScroll = browserWindow.scrollTop();


    var dif = h - quickViewHeight;
    quickViewTopMargin = Math.floor(dif / 2);
    var newQuickViewTopMargin;

    if (browserTopScroll > 0) {
        newQuickViewTopMargin = quickViewTopMargin + browserTopScroll;
        newQuickViewTopMargin = newQuickViewTopMargin + 'px';
    } else {
        newQuickViewTopMargin = quickViewTopMargin + 'px';
    }

    $('#quickViewWrap').css('top', newQuickViewTopMargin);
}

// Beregner ny quickview top margin når der scrolles
function scrollCalculate() {
    var $quickWrap = $('#quickViewWrap');

    var currentTopMargin = quickViewTopMargin;
    var theWindow = $(window);
    var topScroll = theWindow.scrollTop();

    currentTopMargin = parseFloat(currentTopMargin);
    topScroll = parseFloat(topScroll);

    var newTopMargin = currentTopMargin + topScroll;
    newTopMargin = newTopMargin + 'px';

    $quickWrap.css('top', newTopMargin);
}

function showShop(obj) {
    var $linkClicked = $(obj);
    var $parent = $linkClicked.parent().parent();
    var currentState = $parent.hasClass('activeShop');
    if (currentState) {
        $parent.removeClass('activeShop');
        $linkClicked.removeClass('activeShopLink');
    } else {
        $parent.addClass('activeShop');
        $linkClicked.addClass('activeShopLink');
    }
}

//================= Indsamling af data til top 10 sko
function logShoe(ProductId) {
    $.get('logging.ashx?productid=' + ProductId);
    //alert("hit");
    //$.GET('/logging.ashx?productid='+ProductId, {data: 'here'}, function(data){ alert("hit");})
}

//bullet
function getProductDetail(prodID, seasonNumber) {
    _seasonNumber = seasonNumber;
    if (getProduct) {
        var productViewUrl = '/1149.aspx?productID=';
        productViewUrl += prodID;
        productViewUrl += '&seasonnumber=';
        productViewUrl += seasonNumber;


        $.ajax({
            type: "GET",
            url: productViewUrl,
            success: function (data) {
                $('#productList').html(data);

                searcbBreadString = 'VARENR. ';
                searcbBreadString += prodID;

                ProductVisit(prodID,
                    function () {
                        VisitedProducts(prodID, visitedProductSuccessCallback, visitedProductErrorCallback);
                    },
                    function (jqXHR, textStatus, errorThrown) { alert(textStatus); }
                );

                $('#searchBread_productNr').html(searcbBreadString).show();

                //var $tabNav = $('#tabNav');
                //if($tabNav[0]){
                $('#tabNav ul').idTabs();
                //}  
            }
        });
    }

    $('div.clearSearchJQ').removeClass('displayNone');
}

function showDetail(obj) {
    var $this = $(obj);
    var $next = $this.next();
    var state = $this.hasClass('activefoldOut');
    if (!state) {
        $this.addClass('activefoldOut');
        $next.show();
    } else {
        $this.removeClass('activefoldOut');
        $next.hide();
    }
}

// Funktionen bruges til at navigere imellem brand logo'erne der ligger i bunden af sitet
function toogleBrands(direction) {
    direction = parseFloat(direction);
    brandCount = arrBrands.length;

    numOfSteps = Math.ceil(brandCount / 12);

    //Go forward      
    if (direction === 2) {

        if (countIndicator < numOfSteps) {
            ++countIndicator;
            //console.log(countIndicator);
            calculateNextStep();
        }
    }


    //Go Back
    if (direction === 1) {

        if (countIndicator > 1) {
            --countIndicator;
            //console.log(countIndicator);      
            calculateNextStep();
        }
    }
}

//Beregn hvilke ikoner der skal vises
function calculateNextStep() {
    $.each(arrBrands, function (index) {
        //hide stuff
        if (arrBrands[index][1] === true) {
            $(arrBrands[index][0]).hide();
            //set false fordi objektet er ikke synligt længere
            arrBrands[index][1] = false;
        }
    });

    //Start tal til vores array for billeder der skal være synlige
    var itemsToShow = 12 * (countIndicator - 1);

    //Rest der ikke skal være synlig
    var itemRest = (12 * countIndicator) + 1;
    if (itemRest > brandCount) {

        var forMegetOver = itemRest - brandCount;
        itemRest = itemRest - forMegetOver + 1;
        //console.log("NY REST: "+ itemRest); 
    }

    //if(itemRest > 27){itemRest = 28}
    //console.log("Rest: "+ itemRest); 
    //console.log("items: "+ itemsToShow); 


    for (var i = itemsToShow; i < arrBrands.length, i < itemRest - 1; i++) {
        //console.log  (arrBrands[i]);

        if (arrBrands[i][1] === false) {
            arrBrands[i][1] = true;
            $(arrBrands[i][0]).show();

        }
    }
}



//SLIDEDOWN UD FRA ID
function runFoldOut() {
    var activeBefore = false;
    var $isThereActives = $('.foldetOut:first').next('div, ul');
    var $foldUpBefore;

    if ($isThereActives[0]) {
        $foldUpBefore = $isThereActives;
        activeBefore = true;
    }


    $('.foldThisNextDivOut').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        var $foldThis = $this.next('div, ul');
        var isInActive = $foldThis.hasClass('displayNone');

        if (isInActive) {


            if (activeBefore) {
                $foldUpBefore.slideUp('fast', function () {
                    $foldUpBefore.prev('h2').removeClass('foldetOut');
                    $foldUpBefore.prev('h2').addClass('foldetIn');
                    $foldUpBefore.addClass('displayNone');
                });
            }

            $foldThis.slideDown('fast', function () {
                // Animation complete.
                $this.removeClass('foldetIn');
                $this.addClass('foldetOut');
                // $this.addClass('activeSundhed');
                $foldThis.removeClass('displayNone');

                $foldUpBefore = $(this);
            });

            activeBefore = true;
        } else {
            $foldThis.slideUp('fast', function () {
                // Animation complete.        
                // $this.removeClass('activeSundhed');
                $this.removeClass('foldetOut');
                $this.addClass('foldetIn');
                $foldThis.addClass('displayNone');
                activeBefore = false;
            });
        }
    });
}

function showTip(obj) {
    var $this = $(obj);
    var $currentActive = $('.activeDescription');
    var idToShow = $this.attr('rel');

    $currentActive.hide().removeClass('activeDescription');
    $('#' + idToShow).show().addClass('activeDescription');

}

var getShop = false;
function getShops() {
    var $selectedSize = $('#findSizes option:selected');
    var selectedVal = $selectedSize.val();

    if (!getShop) {
        getShop = true;

        var $getShopsWrap = $('<div></div>');
        var $getShopsTop = $('<div></div>');
        var $getShopsMiddle = $('<div></div>');
        var $getShopsBottom = $('<div></div>');
        var $closeGetShops = $('<a href="#"></a>');
        var $closeGetShopsImg = $('<img src="/images/gfx_closeQuickview.png"></img>');

        $closeGetShops.addClass('closeQuickview').append($closeGetShopsImg);

        currentObj = $getShopsWrap;
        $closeGetShops.bind('click', function () {
            closeQuickView($getShopsWrap);
            return false;
        });

        $getShopsTop.addClass('quickViewTop');
        $getShopsMiddle.addClass('quickViewMiddle').append($closeGetShops)
        $getShopsBottom.addClass('quickViewBottom');
        $getShopsWrap.attr('id', 'quickViewWrap').append($getShopsTop).append($getShopsMiddle).append($getShopsBottom);

        var getShopsUrl = '/1303.aspx';
        getShopsUrl += selectedVal;

        $.ajax({
            type: "GET",
            url: getShopsUrl,
            success: function (data) {
                $getShopsMiddle.append(data);

                $('body').prepend($getShopsWrap);
                calculateTopMargin();
                $(window).bind('resize', function () {
                    calculateTopMargin();
                }).bind('scroll', function () {
                    scrollCalculate();
                });

            }
        });

    }
}

function editUser(e) {
    $obj = $('#editUser');
    pass = $obj.find('#pass').val()

    if (pass.length < 1) {
        $obj.find('#passError').show();
        return false;
    } else {
        $obj.find('#passError').hide();
        return true;
    }
}

// Denne funktion bruges til at vise Skopleje produkter
function getShoeCareProduct(prodID, pageID, currentPageID, activeCat) {
    //window.console.log(activeCat);
    window.location = '/' + pageID + '.aspx?prodId=' + prodID + '&camefrom=' + currentPageID + '&grouptoshow=' + activeCat;

}

// Denne funktion validerer "Create VIP" formularen
function createVIP(obj, Terms) {
    var errors = 0;
    var $obj = $(obj);

    var emailRegEx = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    var emailInput = $obj.find('#email').val();
    var emailValid = emailRegEx.test(emailInput);

    var pass = $obj.find('#pass').val();
    var name = $obj.find('#name').val();
    var adress = $obj.find('#adress').val();

    var postnrRegEx = /^[0-9]{4}$/;
    var postnrInput = $obj.find('#postnr').val();
    var postnrValid = postnrRegEx.test(postnrInput);

    var mobilRegEx = /^[0-9]{8}$/;
    var mobilInput = $obj.find('#mobilnummer').val();
    var mobilValid = mobilRegEx.test(mobilInput);

    /*var yearDate = new Date();
    var birthYear = $('input#year:').val();
    var birthDate = $('input#day:').val();
    var birthMonth = $('input#month:').val(); */

    var by = $obj.find('#by').val();

    var female = $('input#female:checked').length;
    var male = $('input#male:checked').length;

    //    var kidsU7 = $('#kidsU7').val();
    //    var kidsO12 = $('#kidsO12').val();

    var terms;
    if (Terms == '1') {
        terms = $('input#terms:checked').length;
    } else {
        terms = 1;
    }

    /*if(birthYear > yearDate.getFullYear() || birthYear.length <4){    
    $obj.find('#yearError').show();
    errors++;
    //window.console.log('year error')
    } else{
    $obj.find('#yearError').hide();
    }
  
    if(birthDate > 32 || birthDate.length <1){    
    $obj.find('#yearError').show();
    errors++;
    //window.console.log('day error')
    }else{
    //$obj.find('#yearError').hide();
    }
  
    if(birthMonth > 12 || birthMonth.length <1){    
    $obj.find('#yearError').show();
    errors++;
    //window.console.log('month error')
    }else{
    //$obj.find('#yearError').hide();
    }*/

    if (!emailValid) {
        $obj.find('#emailError').show();
        errors++;
    } else {
        $obj.find('#emailError').hide();
    }

    if (pass.length < 1) {
        $obj.find('#passError').show();
        errors++;
    } else {
        $obj.find('#passError').hide();
    }

    if (name.length < 1) {
        $obj.find('#nameError').show();
        errors++;
    } else {
        $obj.find('#nameError').hide();
    }

    if (adress.length < 1) {
        $obj.find('#adressError').show();
        errors++;
    } else {
        $obj.find('#adressError').hide();
    }

    if (!mobilValid) {
        $obj.find('#mobilnummerError').show();
        errors++;
    } else {
        $obj.find('#mobilnummerError').hide();
    }


    if (!postnrValid) {
        $obj.find('#postnrError').show();
        errors++;
    } else {
        $obj.find('#postnrError').hide();
    }

    if (by.length < 1) {
        $obj.find('#byError').show();
        errors++;
    } else {
        $obj.find('#byError').hide();
    }

    if (male < 1 && female < 1) {
        $obj.find('#sexError').show();
        errors++;
    } else {
        if (male > 0) {
            $obj.find('input[name="male"]').val('1');
        }
        if (female > 0) {
            $obj.find('input[name="female"]').val('1');
        }
        $obj.find('#sexError').hide();
    }

    //if (kidsU7.length < 1) {
    //        $obj.find('#kidsU7Error').show();
    //        errors++;
    //    } else {
    //        $obj.find('#kidsU7Error').hide();
    //    }
    //
    //    if (kidsO12.length < 1) {
    //        $obj.find('#kidsO12Error').show();
    //        errors++;
    //    } else {
    //        $obj.find('#kidsO12Error').hide();
    //    }

    if (terms == 0) {
        $obj.find('#termsError').show();
        errors++;
    } else {
        $obj.find('#termsError').hide();
    }

    if (errors == 0) {
        $obj.submit();
    } else {
        return false;
    }
}

// Her hentes værdien for favorit liste cookien
// er den undefined er den ikke sat før.
var cookieIsSet = $.cookie("favorit");

function setFavoritesCookie(prodID) {
    var produktID;
    if (cookieIsSet == null) {
        produktID = prodID;
        $.cookie("favorit", produktID, { expires: 14, path: '/' });
    } else {
        produktID = cookieIsSet;
        produktID = produktID + '-' + prodID;
        deleteCookie('favorit');
        $.cookie("favorit", produktID, { expires: 14, path: '/' });
    }
}

function deleteCookie(name) {

    document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

}

function saveYourFavorites() {
    $.cookie("favoritesSaved", 'true', { expires: 14, path: '/' });
    deleteCookie('favorit');
    //    $('#saveYourFavorites').submit();
    window.location = '/1528.aspx?favoritliste=1';
}

function logOut() {
    logoutHref = $('#hiddenLogout form a').attr('href');
    $('#logMeOut').attr('href', logoutHref);
}



//================= Alt herunder kører når doskumentet loader
$(document).ready(function () {

    //lyt efter fol
    runFoldOut();
    //============= Forside karrusel 

    jQuery('#mycarousel').jcarousel({
        wrap: 'circular'
    });

    jQuery('#mycarousetxt').jcarousel({
        wrap: 'circular'
    });


    // ============ Footer brand navigation binding
    var $prevBrandbtn = $('#prevBrandbtn');
    var $forwardBrandbtn = $('#forwardBrandbtn');

    // Hvert brand logo ligges ind i et array
    // array'et bruges i toogleBrands() funktionen
    $('#brandLogoWrap img').each(function (i) {
        i = parseInt(i);
        var brandet = new Array();
        arrBrands.push(brandet);
        arrBrands[i][0] = $(this);
        if (i < 13) {
            arrBrands[i][1] = true;
        } else {
            arrBrands[i][1] = false;
        }
    });

    $prevBrandbtn.bind('click', function () { toogleBrands('1'); return false; });
    $forwardBrandbtn.bind('click', function () { toogleBrands('2'); return false; });

    //============= Produktsøgning/oversigts side/quickview visning /Detalje visning
    var $productSearch = $('.productSearchHeader');

    if ($productSearch[0]) {
        $productSearch.find('ul li').bind('mouseenter', function () { hoverCategory(this, 1); });
        $productSearch.find('ul li').bind('mouseleave', function () { hoverCategory(this, 2); });

        $productSearch.find('ul li a').bind('click', function () {
            slideCategory(this, true, $productSearch);
            return false;
        });

        $("td.productItem").live("mouseenter", function () {
            $(this).find(".detailBalloon").stop(true, true).fadeIn("fast");
        }).live("mouseleave", function () {
            $(this).find(".detailBalloon").stop(true, true).fadeOut("fast");
        });

        $("div.productItem").live("mouseenter", function () {
            $(this).find(".detailBalloon").stop(true, true).fadeIn("fast");
        }).live("mouseleave", function () {
            $(this).find(".detailBalloon").stop(true, true).fadeOut("fast");
        });

/*        var $quickViewHover;

        $('div.productItem').live('mouseenter', function () {
            var onclick = $(this).attr('rel');

            $quickViewHover = $('<div onclick="' + onclick + '"></div>');
            $quickViewHover.addClass('productItemHover').html(' ');

            $(this).prepend($quickViewHover);
        }).live('mouseleave', function () {
            $(this).find('.productItemHover').remove();
        });

        $('td.productItem').live('mouseenter', function () {
            var onclick = $(this).attr('rel');
            $quickViewHover = $('<div onclick="' + onclick + '"></div>');
            $quickViewHover.addClass('productItemHoverTable').html(' ');

            $(this).append($quickViewHover);
        }).live('mouseleave', function () {
            $(this).find('.productItemHoverTable').remove();
        });*/

    }

    //============= Find butik
    var $findButik = $('#shopView');
    if ($findButik[0]) {
        $findButik.find('a.colHeader').bind('click', function () {
            showShop(this);
            return false;
        });
    }

    var $tips = $('#sundhed');
    if ($tips[0]) {
        $tips.find('ul.underKategori li').click(function () {
            showTip(this);
        });
    }

    var $createUser = $('#createUser');
    if ($createUser[0]) {
        $createUser.submit(function () {
            createVIP($createUser, '1');
            return false;
        });
    }

    var hiddenLogout = $('#hiddenLogout');
    if (hiddenLogout[0]) {
        logOut();
    }

    var $saveCookieFavs = $('#saveCookieFavs');
    if ($saveCookieFavs[0]) {
        $saveCookieFavs.click(function (event) {
            event.preventDefault();
            $('#saveYourFavorites').submit();
        });
    }

});


// Suggestive selling javascript
function ProductVisit(productId, successCallBack, errorCallBack) {
    $.ajax({
        type: "POST",
        url: getBaseURL() + "SuggestiveSelling/SuggestiveSellingService.asmx/ProductVisit",
        data: "{productId:'" + productId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: successCallBack,
        error: errorCallBack
    });
}

function VisitedProducts(productId, successCallBack, errorCallBack) {
    $.ajax({
        type: "POST",
        dataFilter: function (data) {
            var msg;

            if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') {
                msg = JSON.parse(data);
            }
            else {
                msg = eval('(' + data + ')');
            }

            if (msg.hasOwnProperty('d')) {
                return msg.d;
            }
            else {
                return msg;
            }
        },
        url: getBaseURL() + "SuggestiveSelling/SuggestiveSellingService.asmx/VisitedProducts",
        data: "{productId:'" + productId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: successCallBack,
        error: errorCallBack
    });
}

function getBaseURL() {
    var basehost = $("<a />");
    basehost.attr("href", location.href);

    return basehost.attr("protocol") + "//" + basehost.attr("host") + "/";
}

function visitedProductSuccessCallback(data, textStatus, xhr) {
    var ssshoes = $("#ssshoes")
    var ssshoeCarousel = $("#ssshoeCarousel");

    if (ssshoes != null && ssshoes != undefined && ssshoeCarousel != null && ssshoeCarousel != undefined) {
        $("#ssshoeCarousel").jcarousel({
            scroll: 1,
            itemLoadCallback: function (carousel, state) {
                if (state != "init") {
                    return;
                }

                for (i = 0; i < data.Product.length; i++) {
                    ssslink = $("<a />");
                    sssimage = $("<img onerror=\"ForsideImgError(this)\" />");

                    sssdiscription = $("<div class=\"productItemText\"><span>" + data.Product[i].Name + "</span><br><span class=\"productPrice\">" + data.Product[i].Price + "</span> </div>");


                    sssimage.attr("src", "/product_images/" + _seasonNumber + "/related/" + data.Product[i].ID + ".jpg");
                    sssimage.attr("alt", "product image");

                    ssslink.attr("rel", data.Product[i].ID);
                    ssslink.click(function () {
                        getProductDetail($(this).attr("rel"), _seasonNumber);
                        logShoe($(this).attr("rel"));
                    });

                    ssslink.attr("href", "javascript: return false;");
                    ssslink.append(sssimage);
                    ssslink.append(sssdiscription);

                    carousel.add(i + 1, ssslink);
                }

                carousel.size(data.Product.length);
            }
        });

        $(ssshoes).find("ul").css("width", ((data.Product.length + 2) * 171) + "px");

        if (!ssshoes.is(":visible")) {
            ssshoes.show('fast');
        }
    }
}

function visitedProductErrorCallback(jqXHR, textStatus, errorThrown) {
    var ssshoes = $("#ssshoes");

    if (ssshoes != undefined) {
        if (ssshoes.is(":visible")) {
            ssshoes.hide('fast');
        }
    }
}

function ForsideImgError(source) {
    source.src = "/product_images/Ingenbilledeforside.jpg";
    source.onerror = "";
    return true;
}
