// JavaScript Document
var cartTimer, cartOver, languageTimer, languageOver, myPagesOver, myPagesTimer, activeDrop, dialog, mypagesfocus;
var htmlDummy = false;
var dropTimer = [];
var dropQueue = [];
var dropOpen = [];
var cartIsHovered = false;
var cartIsHoverable = true;


$(function() { initFrameWork(); });

//----------------------------------------------------------
//  initFrameWork     
//  - function for initating framwork (menus etc)
//----------------------------------------------------------
var initFrameWork = function() {


    // Event handlers for mini basket
    $('#cart').hover(openCart, closeCart);
    $('#cart-open').hover(openCart, closeCart);
    $('#cart-open .products-wrapper').mouseover(openCart);
    $('#cart-open .products').mouseover(openCart);
    $('#cart-open .product').mouseover(openCart);
    //$('#cart').load('/Shop/Cart/content/AddToCart.aspx');
    $('#cart-open').hover(function() { cartIsHovered = true; }, function() { cartIsHovered = false; });

    // Event handlers for changing language and country
    $('#change-language').click(openLanguage);
    $('#language-open').hover(openLanguage, closeLanguageSlow);
    $('#language-open input:button').click(closeLanguage);

    // Event handler for "Mina sidor"
    $('#my-pages').click(openMyPages);
    $('#mypages-open').hover(openMyPages, closeMyPages);
    $('#mypages-login .red-button').click(function() {
        loginUser($('#mypages-login input:text').val(), $('#mypages-login input:password').val(), $('#mypages-login input:checkbox').attr("checked"), frameworkLoginResult, $(this));
    });
    $('#mypages-open *').focus(function() { mypagesfocus = true; openMyPages() });
    $('#mypages-open *').blur(function() { mypagesfocus = false; closeMyPages(); });


    //-----------------------------------------------------------------
    // Hide any error messages when clicked on 
    //-----------------------------------------------------------------
    $('.frameworkErrorMessageBox').click(function() {
        $('.frameworkErrorMessageBox').fadeOut();
    });



    initRollOverImageEventHandlers("#header ");
    initRollOverImageEventHandlers("#wrapper ");
    $(".guide-link").hover(rolloverTextOn, rolloverTextOff);

    setZIndex();

    htmlToFlash('.cart-sum');
    htmlToFlash('legend');
    htmlToFlash('h1');
    htmlToFlash('h2');
    htmlToFlash('h3');
    htmlToFlash('h4');
    htmlToFlash('h5');


    // Dropdowns
    $('.link').click(function(e) {
        if (dropOpen[$(this).attr('href')]) {
            startCloseDrop('a', $(this).attr("href"));
        } else {
            openDrop(e, 'click', 'a', $(this).attr("href"), $(this))
        }
        e.preventDefault();
    });

    $('.link').mouseover(
        function(e) { openDrop(e, 'hover', 'a', $(this).attr("href"), $(this)); });
    $('.drop').hover(
        function(e) { openDrop(e, 'hover', 'div', '#' + $(this).attr("id"), $('a[href="#' + $(this).attr("id") + '"]')) },
        function() { startCloseDrop('div', '#' + $(this).attr("id")) });
    $('.nav').hover(
        function(e) { openDrop(e, 'hover', 'a', $(this).children('a:first').attr("href"), $(this).children('a:first')) },
        function() { startCloseDrop('a', $(this).children('a:first').attr("href")) });


    // For IE6 CSS compatability	
    $('input:text').each(function() { $(this).addClass('text'); });
    $('input:password').each(function() { $(this).addClass('password'); });
    $('input:button').each(function() { $(this).addClass('button'); });
    $('input:checkbox').each(function() { $(this).addClass('checkbox'); });



}

//-----------------------------------------------------------------
// Fix to arrange all div-elements in falling z-index
//-----------------------------------------------------------------
var setZIndex = function() {
    var zIndexNumber = 2000;
    $('div').each(function() {
        // Class 'background' is always placed on z-index 0
        if ($(this).hasClass("background")) {
            $(this).css('zIndex', 0);
        }
        else {
            $(this).css('zIndex', zIndexNumber);
            zIndexNumber -= 1;
            // Assure that all elements has positive z-index
            if (zIndexNumber < 1)
                zIndexNumber = 1;
        }

    });

}


//----------------------------------------------------------
//  openDropSizes
//----------------------------------------------------------
var openDrop = function(e, event, tag, dropId, linktag) {

    if (tag == 'div' || (tag == 'a' && dropOpen[dropId] == true) || event == 'click') {

        // Get the drop div
        var drop = $(dropId);

        // close other drops 
        $('.drop:visible').hide();

        // Stop any timers running to close this div       
        clearTimeout(dropTimer[dropId]);

        // Set the arrow to point down
        //$('a[href="' + dropId + '"]').addClass('active');
        linktag.addClass('active');

        var newSrc = linktag.children('img:first').attr("src").replace("arrow-active", "arrow-selected");
        linktag.children('img:first').attr("src", newSrc);

        // Disable the rollover image effekt of the link
        linktag.unbind('mouseleave', rolloverOff);
        linktag.unbind('mouseenter', rolloverOn);
        linktag.unbind('mouseenter', rolloverTextOn);
        linktag.unbind('mouseleave', rolloverTextOff);

        // Show this drop in the correct position
        drop.css("left", linktag.children('img:first').position().left);
        drop.show();


        // if search drop down focus on input field
        $(dropId + ' input:text').focus();

        // Set flag that this drop is open   
        dropOpen[dropId] = true;

    }
    e.preventDefault();
}

//----------------------------------------------------------
//  startCloseDrop
//----------------------------------------------------------
var startCloseDrop = function(tag, dropId) {

    // only initiate closing if showing
    if (dropOpen[dropId]) {
        var thedrop = $(dropId);
        dropTimer[dropId] = setTimeout('closeDrop("' + dropId + '")', 200);
    }
}

//----------------------------------------------------------
//  closeDrop
//----------------------------------------------------------
var closeDrop = function(dropId) {


    var thedrop = $(dropId);

    // Point arrow right instead of down
    var newSrc = $('a[href="' + dropId + '"]').children('img:first').attr("src").replace("arrow-selected", "arrow-active");
    $('a[href="' + dropId + '"]').children('img:first').attr("src", newSrc);

    // Only do this if it not the active menuchoice on the page
    if ($('a[href="' + dropId + '"]').hasClass("rollover") || $('a[href="' + dropId + '"]').hasClass("rollover-text")) {

        // Connect the event handlers for rollovereffect
        $('a[href="' + dropId + '"]').bind('mouseenter', rolloverOn);
        $('a[href="' + dropId + '"]').bind('mouseleave', rolloverOff);
        $('a[href="' + dropId + '"]').bind('mouseenter', rolloverTextOn);
        $('a[href="' + dropId + '"]').bind('mouseleave', rolloverTextOff);

        // Change images from red to black 
        $('a[href="' + dropId + '"]').children('img').each(function(i) {
            var oldSrc = $(this).attr("src").replace("-active.gif", ".gif");
            $(this).attr("src", oldSrc);
        });
        $('a[href="' + dropId + '"]').children('img').each(function(i) {
            var oldSrc = $(this).attr("src").replace("TextColor=ED2931", "TextColor=000000");
            $(this).attr("src", oldSrc);
        });



    }
    // Hide the drop
    thedrop.hide();
    if (badBrowser()) {
        $("select").css({ display: "block" });
    }

    // Set displayflag to false
    dropOpen[dropId] = false;

}



//----------------------------------------------------------
//  initRollOverImageEventHandlers     
//  - function for adding event handlers mouseover images
//----------------------------------------------------------
var initRollOverImageEventHandlers = function(selection) {
    // function for rollover images
    $(selection + ".rollover").hover(rolloverOn, rolloverOff);
    $(selection + ".rollover-text").hover(rolloverTextOn, rolloverTextOff);
}

//----------------------------------------------------------
//  initModalDialogEventHandlers
//  - function for adding event handlers for modal dialogs
//----------------------------------------------------------
var initModalDialogEventHandlers = function(selection) {


    $(selection + '.simplemodal').click(function(e) {

        e.preventDefault();
        var containerId = $(this).attr('rel');

        $('#basicModalContent').load($(this).attr('href'), function() {
            initModalDialogLoaded(containerId);
        });
    });
}

var initModalDialogLoaded = function(containerId) {
    if (containerId) {
        dialog = $('#basicModalContent').modal({ "containerId": containerId });
    } else {
        dialog = $('#basicModalContent').modal();
    }

    htmlToFlash('h3');
    $('input:text').each(function() { $(this).addClass('text'); });
    $('.tipErrorMessageBox').click(function() { $(this).fadeOut() });

}

//----------------------------------------------------------
//  rolloverOn
//----------------------------------------------------------
var rolloverOn = function() {
    $(this).children('img').each(function(i) {
        var newSrc = $(this).attr("src").replace(".gif", "-active.gif");
        $(this).attr("src", newSrc);
    });
}

//----------------------------------------------------------
//  rolloverOff
//----------------------------------------------------------
var rolloverOff = function() {
    $(this).children('img').each(function(i) {
        var oldSrc = $(this).attr("src").replace("-active.gif", ".gif");
        $(this).attr("src", oldSrc);
    });
}
//----------------------------------------------------------
//  rolloverTextOn
//----------------------------------------------------------
var rolloverTextOn = function() {
    $(this).find('img').each(function(i) {
        var newSrc = $(this).attr("src").replace("TextColor=000000", "TextColor=ED2931")
        $(this).attr("src", newSrc);
    });
}

//----------------------------------------------------------
//  rolloverTextOff
//----------------------------------------------------------
var rolloverTextOff = function() {
    $(this).find('img').each(function(i) {
        var oldSrc = $(this).attr("src").replace("TextColor=ED2931", "TextColor=000000");
        $(this).attr("src", oldSrc);
    });
}

//----------------------------------------------------------
//  closeOpenDrop
//----------------------------------------------------------
var closeOpenDrop = function() {
    // see if any visible 
    var visible = $('.drop:visible:first').attr('id') || "";
    if (visible != "") {

        var newSrc = $('.link.active').children('img:last').attr("src").replace("-active.gif", ".gif");
        $('.link.active').children('img:last').attr("src", newSrc);

        newSrc = $('.link.active').children('img:first').attr("src").replace("arrow-selected", "arrow");
        $('.link.active').children('img:first').attr("src", newSrc);

        $('.link.active').bind('mouseenter', rolloverOn);
        $('.link.active').bind('mouseleave', rolloverOff);
        $('.link.active').removeClass('active');

        $('.drop:visible:first').hide();
    }
}


//----------------------------------------------------------
//  openMyPages
//----------------------------------------------------------
var openMyPages = function(e) {
    clearTimeout(myPagesTimer);
    var drop = $('#mypages-open');
    $(drop).css("top", $('#categories').position().top);
    $(drop).show();
    closeOpenDrop();
    return false;
}

//----------------------------------------------------------
//  closeMyPages
//----------------------------------------------------------
var closeMyPages = function() {
    if (!mypagesfocus) {
        myPagesOver = false;
        clearTimeout(myPagesTimer);
        myPagesTimer = setTimeout(function() {
            if (!myPagesOver) $('#mypages-open').hide();
        }, 1000);
    }
    return false;
}


//----------------------------------------------------------
//  closeCart
//----------------------------------------------------------
var closeCart = function() {

    //console('CLOSECART');
    clearTimeout(cartTimer);
    //console('stopping cartTimer for opening');
    //$('#debug').css('background-color','white');

    if (cartOver) {

        //console('starting cartTimer for closing');
        //$('#debug').css('background-color','red');

        cartTimer = setTimeout(function() {
            cartOver = false;
            $('#cart-open').slideUp(100);
            //$('#debug').css('background-color','white');
        }, 200);

    }

    return false;
}

var closeCartNotOnHover = function() {
    if (!cartIsHovered) {
        cartTimer = setTimeout(function() {
            cartOver = false;
            $('#cart-open').slideUp(100);
        }, 1);
    }
}


//----------------------------------------------------------
//  openCart
//----------------------------------------------------------
var openCart = function() {

    //Do not open minicart on international site
    if ($('#cart').html() == '') {
        return;
    }

    //Do not open minicart if it is empty
    if (!cartIsHoverable) {        
        return;
    }

    //console('OPENCART');    
    //console('stopping cartTimer for closing');
    clearTimeout(cartTimer);
    //$('#debug').css('background-color','white');

    if (!cartOver) {


        //console('starting cartTimer for opening');
        //$('#debug').css('background-color','green');
        cartTimer = setTimeout(function() {
            if (htmlDummy) {
                $('#cart-open').load('content/framework/expanded-mini-basket.htm', miniBasketLoaded);
            } else {
                adjustedWidth = Math.max(parseInt($('#cart-open').css('width')), $('#cart .cart-button')[0].clientWidth + $('#cart .cart-sum2')[0].clientWidth + 30);
                $('#cart-open').css('width', adjustedWidth);
                $('#cart-open').load('/shop/Cart/content/minicartexpanded.aspx', miniBasketLoaded);
            }

        }, 800);


    }

}



//----------------------------------------------------------
//  miniBasketLoaded
//----------------------------------------------------------
var miniBasketLoaded = function() {

    if ($('.product').length < 3) {
        $('.products').css("overflow", "hidden");
        $('.product').css("width", 205);
    }
    $('#cart-open').slideDown(200);
    //$('#debug').css('background-color','white');
    cartOver = true;
}

//----------------------------------------------------------
//  closeLanguage
//----------------------------------------------------------
var closeLanguage = function() {
    languageOver = false;
    $('#language-open').hide(100);
    return false;
}
//----------------------------------------------------------
//  closeLanguageSlow
//----------------------------------------------------------
var closeLanguageSlow = function() {
    languageOver = false;
    clearTimeout(languageTimer);
    languageTimer = setTimeout(function() {
        if (!languageOver) $('#language-open').hide(100);
    }, 1000);
    return false;
}
//----------------------------------------------------------
//  openLanguage
//----------------------------------------------------------
var openLanguage = function() {
    languageOver = true;
    //console($('#language-open').css('top'));
    //$('#language-open').css('top',$('#language-open').css('top')-100);
    $('#language-open').show();
    $('#language-open').css('zIndex', 10000);
    closeOpenDrop();
    return false;
}

//----------------------------------------------------------
//  addToCart
//----------------------------------------------------------
var addToCart = function(articleid) {

    cartIsHoverable = true;

    //alert("DEBUG:: Adding product with article id '" + articleid + "' to basket");
    var url = '/Shop/Cart/content/AddToCart.aspx?productid=' + articleid + '&quantity=1&rand=' + Math.random();
    if (htmlDummy) {
        url = 'content/framework/mini-basket.htm?productid=' + articleid;
    }
    //alert('Adding to basket. Loading this url: ' + url);
    $('#cart').load(url);
}

//----------------------------------------------------------
//  htmlToFlash
//----------------------------------------------------------
var htmlToFlash = function(selector, color, swf, vars, wmode) {

    // alert(selector)

    // if (htmlDummy){
    if (color == undefined || color == '') color = '#000000';
    if (htmlDummy) {
        if (swf == undefined || swf == '') swf = "css/sifr/futuraefdemibold.swf";
    }
    else {
        if (swf == undefined || swf == '') swf = "/PageUI/Flash/futuraefdemibold.swf";
    }
    if (vars == undefined || vars == '') vars = "textalign=left";
    if (wmode == undefined || wmode == '') wmode = "transparent"; //"opaque";

    if (typeof sIFR == "function") {
        sIFR.sWmode = wmode;
        sIFR.replaceElement(selector, named({ sFlashSrc: swf, sColor: color, sWmode: wmode, sFlashVars: vars }));
    } else {
    }
    //}
}



//----------------------------------------------------------
//  showLoadingAnimation
//----------------------------------------------------------
var showLoadingAnimation = function(text, containerId) {

    $('<div>')
        .addClass('loadingMessage')
	    .text(text)
	    .append($('<img>').attr('src', 'images/loadingAnimation.gif'))
	    .appendTo('#' + containerId);
}


//----------------------------------------------------------
//  loginUser
//----------------------------------------------------------
var loginUser = function(strEmail, strPassword, strRemember, resultFunction, button) {

    var url = button.parents('form').attr('action');
    if (htmlDummy) {
        var d = new Date();
        var d2 = d.getMilliseconds();
        if (d2 < 500) { url = 'content/login-ok.htm'; }
        else { url = 'content/login-not-ok.htm'; }
    }
    $.get(url, { email: strEmail, password: strPassword, remember: strRemember }, resultFunction);
}

//----------------------------------------------------------
//  Check if valid email
//----------------------------------------------------------
var checkEmail = function(strEmail) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if (strEmail == '')
        return false;
    else
        return emailReg.test(strEmail);
}

/*
var console = function(text){

$('#debug').append(text + '<br>');
}
*/


//-------------------------------------
// Callback function for login result
//-------------------------------------
var frameworkLoginResult = function(data) {

    if (data.length > 0) {

        var resultCode = data.toString().substr(0, 4);
        var resultData = data.toString().substr(4, data.toString().length);

        if (resultCode == "ERR_") {
            $('.frameworkErrorMessageBox').css("top", $('#mypages-login .red-button').position().top - 130);
            $('.frameworkErrorMessageBox').css("left", $('#mypages-login .red-button').position().left - 320);
            $('.frameworkErrorMessageBox').css("z-index", 4000);
            $('.frameworkErrorMessageBox td').text(resultData)
            //$('.frameworkErrorMessageBox').removeClass('rightError');
            $('.frameworkErrorMessageBox').addClass('rightError');
            $('.frameworkErrorMessageBox').fadeIn();
        }
        else if (resultCode == "URL_") {
            $('.frameworkErrorMessageBox').fadeOut();
            location.href = resultData;
        }

    }

}
//-------------------------------------
// Function for validating swedish social numbers
//-------------------------------------
function validateSocialNumber(nr) {

    this.valid = false;
    if (!nr.match(/^(\d{2})(\d{2})(\d{2})\-(\d{4})$/)) { return false; }
    this.now = new Date(); this.nowFullYear = this.now.getFullYear() + ""; this.nowCentury = this.nowFullYear.substring(0, 2); this.nowShortYear = this.nowFullYear.substring(2, 4);
    this.year = RegExp.$1; this.month = RegExp.$2; this.day = RegExp.$3; this.controldigits = RegExp.$4;
    this.fullYear = (this.year * 1 <= this.nowShortYear * 1) ? (this.nowCentury + this.year) * 1 : ((this.nowCentury * 1 - 1) + this.year) * 1;
    var months = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    if (this.fullYear % 400 == 0 || this.fullYear % 4 == 0 && this.fullYear % 100 != 0) { months[1] = 29; }
    if (this.month * 1 < 1 || this.month * 1 > 12 || this.day * 1 < 1 || this.day * 1 > months[this.month * 1 - 1]) { return false; }
    this.alldigits = this.year + this.month + this.day + this.controldigits;
    var nn = "";
    for (var n = 0; n < this.alldigits.length; n++) { nn += ((((n + 1) % 2) + 1) * this.alldigits.substring(n, n + 1)); }
    this.checksum = 0;
    for (var n = 0; n < nn.length; n++) { this.checksum += nn.substring(n, n + 1) * 1; }
    this.valid = (this.checksum % 10 == 0) ? true : false;
    return this.valid;
    this.sex = parseInt(this.controldigits.substring(2, 3)) % 2;
}

function badBrowser() {
    if ($.browser.msie && parseInt($.browser.version) <= 6) { return true; }
    return false;
}


//-------------------------------------
// Function for simulating click events
//-------------------------------------
function simulateClick2(linkID) {
    if (document.getElementById(linkID).dispatchEvent) {
        var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); document.getElementById(linkID).dispatchEvent(e);
    } else { document.getElementById(linkID).click(); } return false;
}

function simulateClick(jPath, btnID) {

    $(jPath).keydown(function(event) {
        if (event.which || event.keyCode) {
            if ((event.which == 13) || (event.keyCode == 13)) {
                if (document.getElementById(btnID).dispatchEvent) {
                    var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); document.getElementById(btnID).dispatchEvent(e);
                } else { document.getElementById(btnID).click(); } return false;
            }
        } else { return true; }
    });
}


function DoTheGATracking(clickedHref) {    
    if (window.pageTracker) {
        pageTracker._trackPageview("/Shop/Campaign/PuffItem/Click_main_" + clickedHref);        
    }
}
