/*jslint browser: true */ /*global jQuery: true */

/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

// TODO JsDoc

/**
* Create a cookie with the given key and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String key The key of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given key.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String key The key of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

jQuery.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}


/* Functions */
var urlParams = {};
var urlParams = {};
(function () {
    var e,
    a = /\+/g,  // Regex for replacing addition symbol with a space
    r = /([^&=]+)=?([^&]*)/g,
    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
    q = window.location.search.substring(1);

    while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
})();

function PlacePlutt(){
	var element  = $("#hd ul.lv1 li.branch a.branch:first");
	if(!element.length){element = $("#hd ul.lv1 li.active a.active:first")}
	if(!element.length){
		var path = location.pathname.substring(1);
		if(path)
			element = $('#hd ul.extra:first a[href$="' + path + '"]');
	}
	if(element.length){
		var left = ($(element).position().left + 25 + Math.abs(element.width()/2)-3);
		$("#hd img.plutt").css("left", left + "px").css("visibility","visible");
		$(element.addClass("active").parent().addClass("active"));
	}
} 
 
function PlaceLv3(){ 
//active branch hasChildren 
 	var element = $("#hd ul.lv2 li a.branch:first"); 
	if(element.length){
		//alert(element.html() + " " + element.width())
		var left = Math.abs(element.width()/2)+12;
		$("#hd ul.lv3").css("left", -(left) +"px")
	} 
}

function SetActive(){
	var path = location.pathname.substring(1);
	if(path){
	  var element = $('a[href$="' + path + '"]');
	  if(element.length)
	    $(element).addClass("active");
	}
}

function SetArialForPolish(){
	if((window.location.href.indexOf('oriva.se/pl.aspx') != -1) || (window.location.href.indexOf('oriva.se/pl/') != -1)) {
	$("body").addClass("polish");
	}
}

$(document).ready(function () {

    var addtext = $('#addtext').val();
    var removetext = $('#removetext').val();
    var cName = "Orivafavorites";    

    PlacePlutt();
    PlaceLv3();
    SetActive();
    SetArialForPolish();

    function saveCookie(val) {
        $.cookie(cName, val.join(','), { expires: 36500, path: '/' });
    }

    function saveLangCookie(lang) {
        $.cookie("OrivaLanguage", lang, { expires: 36500, path: '/' });
        window.location = 'http://www.oriva.se';
    }

    function alertAndSessionCookie() {
        var addtext = $('#productAddedText');
        var cookie = $.cookie("OrivaSession");
        if (cookie != "1") {
            $("#modal").center();
            $("#modal").css("visibility", "visible");
            $.cookie("OrivaSession", "1", { path: "/" });
        }
    }

    function set_FavoriteText() {
        var cookie = $.cookie(cName);
        var itemsWithCount = cookie ? cookie.split(/,/) : new Array();
        $(".addToFavorite").each(function () {
            var cnt = $(this).find("input[type=hidden]:first");
            if (cnt.length > 0) {
                var pID = cnt[0].value;
                $(this).find('span.linktext').text(addtext);
                var isNotInCookie = true;
                for (var i = 0; i < itemsWithCount.length; i++) {
                    var id = itemsWithCount[i].split(/;/)[0];
                    isNotInCookie = isNotInCookie && pID != id;
                }

                if (isNotInCookie) {
                    $(this).find('span.linktext').text(addtext);

                }
                else {
                    $(this).removeClass("addToFavorite").addClass("removeFavorite");
                    $(this).find('span.linktext').text(removetext);

                }

            }
        });

        function addToFavorite_Click(element) {
            var pID = $(element).find("input[type=hidden]")[0].value;
            var cookie = $.cookie(cName);
            var itemsWithCount = cookie ? cookie.split(/,/) : new Array();

            var items = new Array();
            for (var i = 0; i < itemsWithCount.length; i++) {
                var id = itemsWithCount[i].split(/;/)[0];
                items.push(id);
            }

            if ($.inArray(pID, items) == -1) {
                itemsWithCount.push(pID + ";1"); // Default to add 1 favorite
            }
            saveCookie(itemsWithCount);
            alertAndSessionCookie();
            $(element).removeClass("addToFavorite").addClass("removeFavorite");
            $(element).find('span.linktext').text(removetext);
            $(element).unbind('click').click(function (event) { removeFavorite_Click(element); });
        }


        function removeFavorite_Click(element) {
            var pID = $(element).find("input[type=hidden]")[0].value;
            var cookie = $.cookie(cName);
            var itemsWithCount = cookie ? cookie.split(/,/) : new Array();

            var items = new Array();
            for (var i = 0; i < itemsWithCount.length; i++) {
                var id = itemsWithCount[i].split(/;/)[0];
                items.push(id);
            }

            var removeIndex = jQuery.inArray(pID, items); //items.indexOf(pID);
            if (removeIndex != -1) itemsWithCount.splice(removeIndex, 1);
            saveCookie(itemsWithCount);
            $(element).removeClass("removeFavorite").addClass("addToFavorite");
            $(element).find('span.linktext').text(addtext);
            $(element).unbind('click').click(function (event) { addToFavorite_Click(element); });
        }

	$("a.imageLink").each(function() {
		var link = $(this).attr("href");
		var node = $('#nodeId').val();
		link = link + "&node=" + node;
		$(this).attr("href", link);
	});

        $("a.imageLink").mouseenter(function () {
            $(this).parent().parent().parent().addClass("active");
        });

        $("li.product").mouseleave(function () {
            $(this).removeClass("active");
        });


        $(".addToFavorite").unbind('click').click(function (event) {
            event.preventDefault();
            addToFavorite_Click(this);
        });

        $(".removeFavorite").unbind('click').click(function (event) {
            removeFavorite_Click(this);
        });
    }



    $("#modal img").click(function (event) {
        event.preventDefault();
        $("#modal").css("visibility", "hidden");
    });


    $(".updateFavorites").click(function (event) {
        event.preventDefault();
        var itemsWithCount = new Array();
        $("ul.products li").each(function () {
            var id = $(this).find(".articleCode").html();
            var amount = $(this).find(".amount").val();
            if (id && amount)
                itemsWithCount.push(id + ";" + amount);
        });
        if ("ids" in urlParams)
            window.location.search = "ids=" + itemsWithCount.join(',');
        else
            saveCookie(itemsWithCount);
    });

    $(".clearFavorites").click(function (event) {

        $.cookie(cName, null, { path: "/" });
        window.location = window.location;
    });

    $("#ctl00_ctl00_ctl00_ContentPlaceHolderDefault_MainContent_listShopingProducts_4_Submit_Button").click(function (event) {
        if (ValidatorOnSubmit()) {
            $("#modal").center();
            $("#modal").css("visibility", "visible");
        }
        else {
            event.preventDefault();
        }
    });



    $(".print").click(function (event) {
        event.preventDefault();
        window.location.search += "&print=1";
    });

    $("#en").click(function (event) {
        event.preventDefault();
        saveLangCookie('en');
    });

    $("#se").click(function (event) {
        event.preventDefault();
        saveLangCookie('se');
    });

    $("#de").click(function (event) {
        event.preventDefault();
        saveLangCookie('de');
    });

    $("#pl").click(function (event) {
        event.preventDefault();
        saveLangCookie('pl');
    });

    $("#hu").click(function (event) {
        event.preventDefault();
        saveLangCookie('hu');
    });

    $("#searchBtn").click(function (event) {
	var lang = $.cookie("OrivaLanguage");
	if($("#searchValue").val() != "" && $("#searchValue").val().length>=2){
		window.location = '/' + lang + '/search.aspx?s='+$("#searchValue").val();
	}
    });

    $('#searchValue').keypress(function(e){
	var c = e.which ? e.which : e.keyCode;
	if(c == 13){
		e.preventDefault();
       		$('#searchBtn').click();
       }
    });

    $("#D1 #thumbListUL img.first").click(function (event) {
        $(this).css("display", "none");
    });

    $("#D1 #thumbListUL img").not('.first').click(function (event) {
        $("#D1 #thumbListUL img.first").css("display", "inline");
    });

    set_FavoriteText();
    if ("print" in urlParams) { window.print(); }

/*
    $("ul.lv2 li").click(function (event) {
	var element = $(this);
	var left = -Math.abs(element.width()/2)-10;
	$(this).find("ul.lv3").css("left", left +"px");
    });
*/

});

  



$(window).load(function(){  
	PlacePlutt();// After embeded fonts are loaded (possible need to replace);
}); 








