
//set classes for differens browsers and os's
function set_systeminfo() {
    var body_element = $("body");
    try { 
	    body_element.addClass($.client.os.toLowerCase());
	    body_element.addClass($.client.browser.toLowerCase());
	    body_element.addClass("v"+$.browser.version.toLowerCase().substring(0,1));
    } catch (err) { }
}

//sets returned price/month from Klarna
function klarna_monthly(monthly_fee) {
    var container = $("#klarna_monthly_container");
    var img = "<img src='/BluerangeEasy/templates/common/components/klarna_api/product_page_klarna.gif' align='absmiddle' class='klarna_logotype_S' />";
    var str = img + "<span>fr&aring;n " + monthly_fee + " SEK/m&aring;n. <a href='https://online.klarna.com/account_se.yaws?eid=10173' target='_blank'>mer info &#187;</a></span>";

    container.html(str);
}

//check for klarna prechosen AND if freight have been added
function check_delivery() {

    //set klarna as chosen
    document.getElementById('ShopDeliveryProperty_1_1').checked = true;
    document.getElementById('DeliveryMethod').submit();
}
function add_freight_product() {
    
    return false;
}

$(document).ready(function () {

    // active topmenu hover menus
    active_topmenu();

    //activate accordionmenu
    $('#accordionmenu').initMenu();

    //focus functionality on fields
    focus_fields();

    //small cart functionality
    smallcart_functions();

    //show info about bloggnign about product
    blog_about_product();

    //functionality during checkout
    checkout_functionality();

});

function checkout_functionality() {

    //fetch person info from personnr
    fetch_personinformation();

    //create fullname str
    on_order_submit();

    //show deliveryaddress fields
    delivery_address_fields();

    //field to save hostess checkbox
    save_hostess();

    //add zeroproduct when a campaign is used
    check_campaign_product();
}

function check_campaign_product() {
    $("#addcampaignform").submit(function (e) {
        var campaign_product_id = 517981;
        var shopcart = $.cookie("ShopCart");
        if (!shopcart.match(campaign_product_id)) {
            add_freight(campaign_product_id, 1, "zeroproduct");
        }
    });
}
function addFreeProduct(productid, quantity) {
    var shopcart = $.cookie("ShopCart");
    if (!shopcart.match(productid)) {
        add_freight(productid, quantity, "freeproduct");
        window.location.reload;
    }
}
function removeFreeProduct(productid) {
    var shopcart = $.cookie("ShopCart");
    if (shopcart.match(productid)) {
        remove_freight(productid);
        window.location.reload;
    }
}

function save_hostess() {
    $("#chkHostess").change(function () {
        if ($(this).attr("checked")) {
            document.getElementById("DeliveryDescription").value = "true";
        } else {
            document.getElementById("DeliveryDescription").value = "";
        }
    });
}

function delivery_address_fields() {
    $("#DeliveryAddress").change(function () {
        $("#deliveryinformation").toggle();
    });
}

//create fullname str
function on_order_submit() {
    $("#orderform").submit(function () {
        var name = $("#Firstname").attr("value") + " " + $("#Surname").attr("value");
        $("#InvoiceName").attr("value", name);
        $("#DeliveryEmail").val($("#InvoiceEmail").val());
    });
}

//fetch person info from personnr
function fetch_personinformation() {
    $("#Persno").change(function () {
        try {
            //first, empty all fields
            $("#Firstname, #Surname, #InvoiceAddress1, #InvoiceZip ,#InvoiceCity").attr("value", "");
            get_address(2011, $(this).attr("value"), "write_person_info");
        } catch (err) { }
    });
}
function write_person_info(str) {
    var personinfo = str.split("|");

    //fill fields
    $("#Firstname").attr("value", personinfo[0]);
    $("#Surname").attr("value", personinfo[1]);
    $("#InvoiceAddress1").attr("value", personinfo[2]);
    $("#InvoiceZip").attr("value", personinfo[3]);
    $("#InvoiceCity").attr("value", personinfo[4]);
}

//small cart functionality
function smallcart_functions() {
	
	//show/hide the smallcart
	$("#showcart").click(function(e) {
		e.preventDefault();
		e.stopImmediatePropagation();
		$("#shopdetails").toggle();
		var oldtext = $(this).text();
		var newtext = $(this).attr("alt");
		$(this).text(newtext);
		$(this).attr("alt", oldtext);
	});

    $("input#Order").click(function (e) {
        createCookie("JustAddedToCart", "true", 1)
    });
    
    //shop product have been added?
    $(document).ready(function () {
        if ($.cookie("JustAddedToCart")) {
            //ok remove the cookie, and show full cart
            eraseCookie("JustAddedToCart");
            $("#shopdetails").toggle();

            //change text for show/hide
            var oldtext = $("#showcart").text();
            var newtext = $("#showcart").attr("alt");

            $("#showcart").attr("alt", oldtext);
            $("#showcart").text(newtext);
            
            //show information bubble
            just_added_to_cart_info();
        }
    });
}

function just_added_to_cart_info() {
    var container = $("<div id='added-to-cart' class='shadow-block'></div>");
    var innercontainer = $("<div class='inner'></div>").appendTo(container);
    $("<h5></h5>").html("Din varukorg har uppdaterats").appendTo(innercontainer);
    $("<p></p>").html("Handla g&#228;rna vidare, eller klicka p&#229; <b>&quot;KASSAN&quot;</b>-knappen till v&#228;nster f&#246;r att avsluta ditt k&#246;p.").appendTo(innercontainer);
    $("<img src='/BluerangeEasy/templates/2115/images/added-to-cart_leftarrow.png' class='arrow' />").appendTo(innercontainer);
    var parent = $("#smallcart-frame");

    //show the message.. and then fade out and remove adter a few seconds
    parent.addClass("active");
    container.appendTo(parent);
    container.delay(4000).fadeOut(400, function () {
        $(this).remove();
        parent.removeClass("active");
    });
}

// active topmenu hover menus
function active_topmenu() {
	var config = {
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
		 interval: 100, // number = milliseconds for onMouseOver polling interval
		 over: topmenu_over, // function = onMouseOver callback (REQUIRED)
		 timeout: 200, // number = milliseconds delay before onMouseOut
		 out: topmenu_out // function = onMouseOut callback (REQUIRED)
	};
	
	//$("#topnav ul ul").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
	$("#topnav ul li").hoverIntent(config); //Trigger Hover intent with custom configurations
}
function topmenu_over() {
    if ($(this).find("ul").length > 0) {
        //hide flash object?
        if ($("div[rel='hideflash']").length > 0 && !$("img[class='flashreplacement']").length > 0) {
            var flashframe = $("div[rel='hideflash']");
            var flash_sub_url = flashframe.attr("alt");
            var sub_img = $("<img class='flashreplacement' />").attr("src", flash_sub_url);
            flashframe.parent().height(flashframe.parent().outerHeight());

            flashframe.hide();
            sub_img.appendTo(flashframe.parent());
        }
		$(this).children("ul").stop().show();
		$(this).stop().addClass("active");
	}
}
function topmenu_out() {
    if ($(this).children("ul").length > 0) {
        if ($("div[rel='hideflash']").length > 0) {
            $("img[class='flashreplacement']").remove();
            $("div[rel='hideflash']").show();
        }
		$(this).children("ul").stop().hide();
		$(this).stop().removeClass("active");
	}
}

//focus functionality on fields
function focus_fields() {
	$("input.focusfield, textarea.focusfield").each(function(){
		$(this).val($(this).attr("alt"));
	});
	$("input.focusfield, textarea.focusfield").focus(function() {
		if($(this).val()==$(this).attr("alt")) {
			$(this).val("").addClass("active");
		}
	});
	$("input.focusfield, textarea.focusfield").blur(function() {
		if($(this).val()=="") {
			$(this).val($(this).attr("alt")).removeClass("active");
		}
	});
}

function blog_about_product() {
    $("#bloginformationbox").mouseup(function () {
        return false
    });
    $(document).mouseup(function (e) {
        $("#bloginformationbox").hide();
    });
    $(".sharebuttons .blogabout").click(function (e) {
        e.preventDefault();
        $("#bloginformationbox").show();
    });
}
























// -------------  COOKIE FUNCTIONS ------------- //

function add_freight(productid, quantity, data) {

    //DOES COOKIE EXIST?
    if ($.cookie("ShopCart") && !($.cookie("ShopCart").match(productid))) {
        var currentcookiestr = $.cookie("ShopCart");
        var newcookie = "";
        newcookie = currentcookiestr + "|" + productid + "|" + quantity + ",0," + data;
        createCookie("ShopCart", newcookie, 7);
        return true;
    } else {
        return false;
    }

}

function remove_freight(productid) {
    if ($.cookie("ShopCart")) {
        var currentcookie = $.cookie("ShopCart").split("|");
        var newcookie = "";
        for (var i = 0; i < currentcookie.length; i++) {
            if (parseInt(currentcookie[i]) == productid) {
                //this is the product that should be removed = ignore it
            } else {
                newcookie += currentcookie[i] + "|" + currentcookie[i + 1] + "|";
            }
            i = i + 1;
        }
        var newcookielength = newcookie.length;
        newcookie = newcookie.substring(0, newcookielength - 1);
        createCookie("ShopCart", newcookie, 7);
    }
}


function createCookie(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=/";
}

function readCookie(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;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

//check to see if invalid freightproduct is in shopcart
function check_cookie() {
    if ($.cookie("ShopCart")) {
        var shopcartcookie = $.cookie("ShopCart");
        if (shopcartcookie.match("460561")) {
            eraseCookie("ShopCart");
            window.location.reload;
        }
    }
}
