/* Author: antonio@nozebra.dk */

$(document).ready(function () {
    //if not IE7
    if ($.browser.msie == true && parseInt($.browser.version) > 7) {

        /*BG´s MED NOISE PLUGIN*/
        $('body').noisy({
            'intensity': 0.5,
            'size': '200',
            'opacity': 0.05,
            'fallback': '',
            'monochrome': false
        }).css('background-color', '#dfded2');

        $('#mainContainer').noisy({
            'intensity': 0.5,
            'size': '200',
            'opacity': 0.05,
            'fallback': '',
            'monochrome': false
        }).css('background-color', '#e9e9e2');

        $('#mainContainerBottom').noisy({
            'intensity': 0.5,
            'size': '200',
            'opacity': 0.05,
            'fallback': '',
            'monochrome': false
        }).css('background-color', '#e9e9e2');

    } /*If not IE7 ends here*/

	/*http://trevordavis.net/blog/use-jquery-to-open-all-external-links-in-a-new-window*/
	$("a[href^='http']").attr('target','_blank');
	
    /*CSS Tooltip*/
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        $('.tooltip').mouseover(function () {
            $(this).children('span').show();
        }).mouseout(function () {
            $(this).children('span').hide();
        })

        $('.tooltipBlack').mouseover(function () {
            $(this).children('span.tooltipText').show();
        }).mouseout(function () {
            $(this).children('span.tooltipText').hide();
        })
    }

    /*Adding submit filters on change*/
    $('#prodSearchForm :checkbox').change(function () {
        document.getElementById('prodSearchForm').submit();
    });

    /* How many favorite products in da house */
    var favProds = $("#compare tr").length;
    $("#favoriteListNumber").html(favProds);
    $(".totalFavs").text(favProds);

    //Counting how many checked item in the favorite list
    function countChecked() {
        var n = $(".favProductCol1 input[type=checkbox]").filter(":checked").length;

        $(".totalCheckedFavs").text(n);
    }
    countChecked();

    fadeUnchecked();
    $("#rightCol :checkbox").click(function () {

        var o = $(this).parent(".favProductCol1").siblings(".favProductCol2").stop();
        var n = $(".totalCheckedFavs").text(n);

        if ($(this).prop("checked")) {
            o.fadeTo(200, 1);
            n++;
			$(this).parent().parent().removeClass("remove");
        } else {
            o.fadeTo(200, 0.3);
            n--;
			$(this).parent().parent().addClass("remove");
        }


        $(".totalCheckedFavs").text(n);
    });

    $("#rightCol :checkbox").each(fadeUnchecked);

    function fadeUnchecked() {
        var o = $(this).parent(".favProductCol1").siblings(".favProductCol2").stop();

        if (!$(this).prop("checked")) {
            o.addClass("faded");
        }
    }

    //If the fav products boxes are not checked hide them from print
    $("div.favProduct :checked").parent().parent().removeClass('printDisplayNone');

    //Get the content from favoritliste til form mailer
    $(".favoriteProductsList").clone().appendTo('#favListContent');
	
	//Get the content from favoritliste til #pdfList
    //$(".favoriteProductsList").clone().appendTo('#pdfList');
	
	//var mailFavoriteListHref = $("#mailFavoriteList").attr("href");
	//var favoriteListClone = $(".favoriteProductsList").clone();

    //Adding marginRight= 0 to the last item in a row of products
    $('#shopBoxes > div.productBox:nth-child(4n)').css('margin-right', '0px');

    //Zebra skin to tables
    $(".tabCompare tr td:nth-child(2n)").css('background', '#e9e9e2');
    $(".tabCompare tr.tabCompareHeader td").css('background', '#FFF');
    $("#productTabs tr:nth-child(2n)").css('background', '#e9e9e2');

    //Hidding rows in the compare list if they have no attributes
    $(".tabCompare tr td:empty").parent().hide();

    //Making both filter boxes of equal height
    var filterBox2Height = $("#productFilter2").height();
    $("#productFilter1").height(filterBox2Height);


    //Nikki's cool hover effect here
    $('.categoryBox, .productBox, .mainBottomTeaser').hover(function () {
		if($.browser.msie && $.browser.version<="8.0") { 
		} else {
        $(this).find('img').stop(true,true).animate({ "opacity": 0.5 }, 100).animate({ "opacity": 0.75 }, 100)
		}
    }, function () {
		if($.browser.msie && $.browser.version<="8.0") { 
		} else {
        $(this).find('img').stop().animate({ "opacity": 1 }, 250)
		}
    });

    $('#productLeftImage img, #productLeftThumbs img, .relatedProduct img').hover(function () {
        $(this).stop().animate({ "opacity": 0.5 }, 100).animate({ "opacity": 0.75 }, 100)
    }, function () {
        $(this).stop().animate({ "opacity": 1 }, 250)
    });
	
	
	// Clear input fields on focus
	$("input[type=text], input[type=textinput], textarea").each(function ()	{
		var v = this.value;
		
		$(this).blur(function () {
			if (this.value.length == 0) {
				this.value = v;
				//$(this).addClass("unvalid"); 
			}
		}).focus(function () {
			if (this.value == v) {
				this.value = "";
				$(this).removeClass("unvalid");
			}
		}); 
	});
	
	
    //Remove favoriteListNumber if '0'
    if ($("#favoriteListNumber").html() != "0") {
        $("#favoriteListNumber").css("visibility", "visible");
    }
    else {
        $("#favoriteListNumber").css("visibility", "hidden");
    }

});   /***************************document ready ends here****************************/




/* Compare script used for the favorite list*/
var Compare = new Object;
var maxFavoriteCount = 12;
var maxCompareCount = 3;

Compare.add = function (compareid, name, url) {
    for (var i = 0; i < maxFavoriteCount; i++) {
        var key = "p" + i;
        var value = Compare.readCookie(key);
        if (value) {
            if (value.split('|')[0] == compareid) {
                alert("Dette produkt er allerede på din favorit liste...");
                Compare.writecompare();
                return;
            }
			//alert('Dit produkt er i din favoritsliste nu');
        } else {
            Compare.createCookie(key, compareid + '|' + escape(name) + '|' + escape(url), null);
            Compare.writecompare();
			window.location.reload();
            return;
        }
    }
    alert("Du kan ikke tilføje flere produkter. Max er " + maxFavoriteCount);
}

Compare.remove = function (compareid) {
    var value = "";
    for (var i = 0; i < (maxFavoriteCount - 1); i++)
        value += "|";

    //var value = "|||||||||"
    var values = value.split('|')
    for (var i = 0; i < maxFavoriteCount; i++) {
        var key = "p" + i;
        var value = Compare.readCookie(key);
        if (value) {
            if (value.split('|')[0] != compareid) {
                values[i] = value;
            }
        }
    }
    Compare.removeall();
    for (var i = 0; i < values.length; i++) {
        var key = "p" + i;
        if (values[i]) {
            Compare.createCookie(key, values[i], null);
        }
    }
    Compare.writecompare();
	
	/*Need to take the compare product of the url*/
	  docLocationHref = document.location.href;
	  var refPage = "http://www.brandt-hvidevarer.dk/Produkter.aspx";
	  
	  if(docLocationHref.indexOf("PROD")<0){
		  location.href=refPage;
	  }
	  else{
		  docLocationHref = docLocationHref.replace(compareid, '');
		  if(docLocationHref.indexOf("PROD")<0){
				location.href=refPage;
		  }else{
		  		location.href=docLocationHref.replace(compareid, '');
		  }
	  }
}

Compare.removeall = function () {
    for (var i = 0; i < maxFavoriteCount; i++) {
        var key = "p" + i;
        Compare.eraseCookie(key);
    }
    Compare.writecompare();
}

Compare.writecompare = function () {
    var html = "";
    var rows = "";
    for (var i = 0; i < maxFavoriteCount; i++) {
        var key = "p" + i;
        var value = Compare.readCookie(key);
        if (value) {
            rows += Compare.row(value.split('|')[0], value.split('|')[1], value.split('|')[2]);
        }
    }
    if (rows) {
        /*html += "<strong>Compare</strong>";
        html += "<div id=\"smallcart_empty\">";*/
        html += "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"t1\">";
        html += rows;
        html += "</table>";
        html += "<br />";
        html += "<a href=\"javascript:Compare.removeall();\">Remove all</a>&nbsp;&nbsp;&nbsp;";
        html += "<a href=\"javascript:Compare.compare(" + pageID + ");\">Compare</a>";
    }
    if (document.getElementById("compare")) {
        document.getElementById("compare").innerHTML = html;
    }
}

Compare.row = function (compareid, name, url) {
    var html = "";
    html += "<tr>";
    html += "<td><a href=\"" + unescape(url) + "\">" + unescape(name) + "</a></td>";
    html += "<td></td>";
    html += "<td><a href=\"javascript:Compare.remove('" + compareid + "')\">x</a></td>";
    html += "</tr>";
    return html;
}


Compare.createCookie = function (name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

Compare.readCookie = function (name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

Compare.eraseCookie = function (name) {
    Compare.createCookie(name, "", -1);
}

Compare.compare = function (pageid) {
    var ids = "";
    for (var i = 0; i < maxFavoriteCount; i++) {
        var key = "p" + i;
        var value = Compare.readCookie(key);
        if (value) {
            if (ids != "") {
                ids += ",";
            }
            ids += value.split('|')[0];
        }
    }
    if (ids) {
        location = "/Default.aspx?ID=" + pageid + "&Compare=" + ids;
    }
}

/* Similar compare functions used for compare — functions need different cookie, thus the need for duplicate functions // NIS */
Compare.comAdd = function (compareid, name, url) {
    for (var i = 0; i < maxCompareCount; i++) {
        var com = "n" + i;
        var value = Compare.readCookie(com);
        if (value) {
            if (value.split('|')[0] == compareid) {
                alert("Dette produkt er allerede på din favorit liste...");
                Compare.writecompare();
                return;
            }
			//alert('Dit produkt er i din favoritsliste nu');
        } else {
            Compare.comCreateCookie(com, compareid + '|' + escape(name) + '|' + escape(url), null);
            Compare.comWritecompare();
			window.location.reload();
            return;
        }
    }
    alert("Du kan ikke tilføje flere produkter. Max er " + maxCompareCount);
}

Compare.comRemove = function (compareid) {
   var value = "";
    for (var i = 0; i < (maxCompareCount - 1); i++)
        value += "|";
//    console.log(value); Ingen Console.log på live sites — IE8 kan ikke tåle det.
    //var value = "|||||||||"
    var values = value.split('|')
    for (var i = 0; i < maxCompareCount; i++) {
        var com = "n" + i;
        var value = Compare.comReadCookie(com);
        if (value) {
            if (value.split('|')[0] != compareid) {
//     console.log(value); 
	
	            values[i] = value;
            }
        }
    }
	
    Compare.comRemoveall();
    for (var i = 0; i < values.length; i++) {
        var com = "n" + i;
        if (values[i]) {
            Compare.comCreateCookie(com, values[i], null);
        }
    }
    Compare.comWritecompare();
	
	/*Need to take the compare product of the url*/
	  docLocationHref = document.location.href;
	  var refPage = "http://www.brandt-hvidevarer.dk/Produkter.aspx";
	  
	  if(docLocationHref.indexOf("PROD")<0){
		  location.href=refPage;
	  }
	  else{
		  docLocationHref = docLocationHref.replace(compareid, '');
		  if(docLocationHref.indexOf("PROD")<0){
				location.href=refPage;
		  }else{
		  		location.href=docLocationHref.replace(compareid, '');
		  }
	  }
}

Compare.comRemoveall = function () {
    for (var i = 0; i < maxCompareCount; i++) {
        var com = "n" + i;
        Compare.comEraseCookie(com);
    }
    Compare.comWritecompare();
}

Compare.comWritecompare = function () {
    var html = "";
    var rows = "";
    for (var i = 0; i < maxCompareCount; i++) {
        var com = "n" + i;
        var value = Compare.comReadCookie(com);
        if (value) {
            rows += Compare.comRow(value.split('|')[0], value.split('|')[1], value.split('|')[2]);
        }
    }
    if (rows) {
        /*html += "<strong>Compare</strong>";
        html += "<div id=\"smallcart_empty\">";*/
        html += "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"t1\">";
        html += rows;
        html += "</table>";
        html += "<br />";
        html += "<a href=\"javascript:Compare.removeall();\">Remove all</a>&nbsp;&nbsp;&nbsp;";
        html += "<a href=\"javascript:Compare.compare(" + pageID + ");\">Compare</a>";
    }
    if (document.getElementById("compare")) {
        document.getElementById("compare").innerHTML = html;
    }
}

Compare.comRow = function (compareid, name, url) {
    var html = "";
    html += "<tr>";
    html += "<td><a href=\"" + unescape(url) + "\">" + unescape(name) + "</a></td>";
    html += "<td></td>";
    html += "<td><a href=\"javascript:Compare.remove('" + compareid + "')\">x</a></td>";
    html += "</tr>";
    return html;
}


Compare.comCreateCookie = function (name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

Compare.comReadCookie = function (name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

Compare.comEraseCookie = function (name) {
    Compare.createCookie(name, "", -1);
}

Compare.comCompare = function (pageid) {
    var ids = "";
    for (var i = 0; i < maxCompareCount; i++) {
        var com = "n" + i;
        var value = Compare.readCookie(com);
        if (value) {
            if (ids != "") {
                ids += ",";
            }
            ids += value.split('|')[0];
        }
    }
    if (ids) {
        location = "/Default.aspx?ID=" + pageid + "&Compare=" + ids;
    }
}


//BLOCK UI OVERLAY
function openOverlay() { //funktionskald for at launche
	  $.blockUI({
				message: $('#favoriteProductsEmailList'), 
				centerY: false, 
				css: { border: '', top: ($(window).height() - 192) /2 + 'px', left: ($(window).width() - 400) /2 + 'px', width: '400px' },
				overlayCSS: { opacity: '0.2', cursor: 'auto' },
				cursor: 'default'
		  });
	};
	
function closeOverlay() { //kald til at fjerne pop-up
		$.unblockUI();
}
	
