
kk_konfigurator = {
    defPrice: 1000,
    curPrice: 0,
    options: {},
    init : function(price) {
        kk_konfigurator.options = new Object();
        $("div.product-view-configure-single-option").click(kk_konfigurator.click);
        $("div.product-view-configure-single-option").hover(kk_konfigurator.mouseover,kk_konfigurator.mouseout);
        kk_konfigurator.defPrice = price;
        kk_konfigurator.curPrice = price;
		//$("div.product-view-configure-single-option-image").hover(kk_konfigurator.zoomShow, kk_konfigurator.zoomHide);
		$("div.product-view-configure-zoom-image").bind("click",function(event){kk_konfigurator.zoomShowHide(event, $(this))});

		kk_konfigurator.excludeIncompatibilities($(this));
    },
    validateAndSubmit : function() {
    	var ret = kk_konfigurator.validate();

        if(!ret.ok) {
            $("#errorMsg").children("p").text("");
			$("#errorMsg").children("p").append(ret.errors_txt);
            $("#errorMsg").modal({"overlayId":"errorModalOverlay", "containerId":"errorModalContainer", "closeTitle":"Luk", "closeClass":"errorCloseModal"});
        } else {
            $("#conf_form").submit();
        }
    
	},    
    validate : function() {
        var ok = true;
        var errors_txt ="";
        $("div.product-view-configure-options-container").each(
            function() {
                var variant = $(this);//.parents("div.product-view-configure-options-container");
                var variant_id = variant.attr("kk:variant_id");
                var multiple = variant.attr("kk:variant_allow_multiple");
                var optional = variant.attr("kk:variant_optional");
                var cur_val=  $("#variant_"+variant_id).val();

                if((cur_val.length < 1 || cur_val == '0') && optional == 0) {
                    errors_txt = errors_txt + "<br />" + $(this).attr("kk:variant_name") + " skal vælges."
                    ok = false;
                }
            }
        );
		return {'ok':ok, 'errors_txt':errors_txt};

    },
    getCurrentPrice : function () {
		var options = new Array();  	
        $("div.product-view-configure-options-container").each(
            function() {
                var variant = $(this);//.parents("div.product-view-configure-options-container");
                var variant_id = variant.attr("kk:variant_id");
                var multiple = variant.attr("kk:variant_allow_multiple");
                var optional = variant.attr("kk:variant_optional");
                var cur_val=  $("#variant_"+variant_id).val();
				var temp = {"variant_id": variant_id, "option_id":cur_val};
                options.push(temp);
            }
        );
        //console.log(options);
        var param = JSON.stringify(options);
        var prod_id = $("#price-tag-container").attr("kk:product_id");

        $.getJSON("index.php?eID=kk_getprice",{"prod_uid": prod_id,"params": param},function(ret) {
			if(ret.price) {
				//ToDo: Her ville det være fedt hvis prise lige kom frem på skærmen og derefter fadede væk, lidt ligesom på
				// markedsforing når man lægger i kurv.
				kk_konfigurator.showPriceAtTop(number_format(ret.price,2,",",".")+"dkr.");
				$("#price-tag-container").html(number_format(ret.price,2,",",".")+"dkr.");
			} else {
				$("#price-tag-container").html(ret.error);
			}
		});
	},
	showPriceAtTop: function(aPrice){
		$(".tx-kontorkoncept-pi1").before('<div class="tmpPrice">'+aPrice+'</div>');
		$(".tmpPrice").css({'position':'absolute', 'top':($(document).scrollTop()+20)+'px', 'left':($(".tx-kontorkoncept-pi1").position().left+500)+'px'});
		$(".tmpPrice").fadeOut(3500, kk_konfigurator.removePriceAtTop);
	},
	removePriceAtTop: function(){
		$("tmpPrice").remove();
	},
    mouseover: function() {
    	if(!$(this).hasClass("unselectable")){
        	$(this).addClass("product-view-configure-single-option-mouseover");
        	$(this).children(".product-view-configure-single-option-image").children(".product-view-configure-zoom-image").children("img").show();
		}
        //div.product-view-configure-single-option
    },
    mouseout: function() {
        $(this).removeClass("product-view-configure-single-option-mouseover");
        $(this).children(".product-view-configure-single-option-image").children(".product-view-configure-zoom-image").children("img").hide();
    },
    click: function() {
		if(!$(this).hasClass("unselectable")){
	        var variant = $(this).parents("div.product-view-configure-options-container");
	        var variant_id = variant.attr("kk:variant_id");
	        var multiple = variant.attr("kk:variant_allow_multiple");
	        //Here we should check if multiple is allowed, should be attribute on variant...
	        if(multiple=="1") {
	            //console.log("Multiple");
	            var cur_val=  $("#variant_"+variant_id).val();
	            if(cur_val.length>0) {
	                var temp  = cur_val.split(",");
	            } else {
	                var temp = new Array();
	            }
	            //console.log(temp);
	            var new_value= new Array();
	            if($(this).attr("kk:selected") == 1) {
	                $(this).attr("kk:selected","0");
	                $(this).removeClass("product-view-configure-single-option-selected");
	                var option_id = $(this).attr("kk:option_id");
	                 for (var i=0; i < temp.length; i++) {
	                 //   console.log(temp[i]+"::"+option_id);
	                    if(temp[i] == option_id) {

	                    } else {
	                        new_value.push(temp[i]);
	                    }
	                 }
	            } else {
	                $(this).attr("kk:selected","1");
	                $(this).addClass("product-view-configure-single-option-selected");
	                new_value= temp;
	                new_value.push($(this).attr("kk:option_id"));
	            }
	            //console.log(new_value);
	            $("#variant_"+variant_id).val(new_value.join(","));
	        } else {

	            if($(this).attr("kk:selected") == 1) {
	                var new_value = 0;
	                $(this).attr("kk:selected","0");
	                $(this).removeClass("product-view-configure-single-option-selected");

	            } else {


	                //First remove selected status on all currently seleveted item.
	                $(".product-view-configure-single-option-selected",variant).each(
	                    function() {
	                        $(this).attr("kk:selected","0");
	                        $(this).removeClass("product-view-configure-single-option-selected");
	                    }
	                );
	                /**/
	                //var new_price = kk_konfigurator.curPrice + parseFloat($(this).attr("kk:option_price"));
	                var new_value = $(this).attr("kk:option_id");
	                $(this).attr("kk:selected","1");
	                $(this).addClass("product-view-configure-single-option-selected");


	                //console.log(kk_konfigurator.curPrice);

	            }
	            $("#variant_"+variant_id).val(new_value);
	        }
	        //Calcualte price and update
	        //This is not possible anymore
	        /*
	        var new_price = kk_konfigurator.defPrice;
	        $(".product-view-configure-single-option-selected").each(function() {
	                new_price = new_price + parseFloat($(this).attr("kk:option_price"));
	            }
	        );

	        $("#price-tag-container").html(number_format(new_price,2,",",".")+"dkr.");
	        kk_konfigurator.curPrice = new_price;
			/**/
	        kk_konfigurator.excludeIncompatibilities($(this));
	        
	        var ret = kk_konfigurator.validate();
	        if(ret.ok) {
	        	//console.log("Product conf ok");
	        	//ToDo: Load price from Ajax.
	    		kk_konfigurator.getCurrentPrice();    	
			} else {
			
			}
		}
    },
    excludeIncompatibilities: function(sender){
    	kk_konfigurator.incompatabilities = new Array();
    	$(".product-view-configure-single-option-selected").each(
			function(){
				var incompatibleString = $(this).attr("kk:option_incompatible_with");
                var allIncompatible = new Array();
    			if(incompatibleString && incompatibleString.length > 0){
    				allIncompatible = incompatibleString.split(",");
    				//console.log(allIncompatible);
					for(var i = 0; i < allIncompatible.length; i++){
						kk_konfigurator.incompatabilities.push(allIncompatible[i]);
					}
				}
			}
    	);
/*    	console.log(kk_konfigurator.incompatabilities);
    	var incompatibleString = sender.attr("kk:option_incompatible_with");

    	var allIncompatible = new Array();
    	if(incompatibleString && incompatibleString.length > 0){
    		allIncompatible = incompatibleString.split(",");
		}
*/
		$(".product-view-configure-single-option").each(
			function(){
				/*var tmpArr = $(this).attr("kk:option_incompatible_with").split(",");
				for(var i = 0; i < tmpArr.length; i++){

				}
				if($(this).hasClass("product-view-configure-single-option-selected"){

				}*/

				if(jQuery.inArray($(this).attr("kk:option_id"), kk_konfigurator.incompatabilities) > -1){
					$(this).addClass("unselectable");
					$(this).removeClass("product-view-configure-single-option-selected");
				}
				else{
					$(this).removeClass("unselectable");
				}
			}
		)
	},
	zoomShowHide: function(event, sender){
		event.stopPropagation();

		$(".product-view-configure-large-image").removeClass("zoomShow");
		if(!$(sender).hasClass("product-view-configure-zoom-image")){
			$("#zoombox").hide();
		}
		else{
			var zoomcontentbox = $(sender).parents(".product-view-configure-single-option").children(".product-view-configure-large-image");

			$(zoomcontentbox).addClass("zoomShow");

			//var zoomLeft = $("#content-sub").offset().left - $(zoombox).parent("div").offset().left + 50;
			var winWidth = 0;
			var scrTop = 0;
			var winHeight = 0;

			if(document.documentElement.clientHeight){
				scrTop = document.documentElement.scrollTop;
				winHeight = document.documentElement.clientHeight;
				winWidth = document.documentElement.clientWidth;
			}
			else{
				scrTop = window.pageYOffset;
				winHeight = window.innerHeight;
				winWidth = window.innerWidth;
			}

			var zoomTop = Math.round(winHeight/2 - 160 + scrTop);
			if(isNaN(zoomTop)){zoomTop = 289}
			var zoomLeft = Math.round(252 + 333 - 280);
			//var zoomLeft = 310;
			$("#zoombox").show();
			$("#zoombox").html("");

			$("#zoombox").append($(zoomcontentbox).html());

			$("#zoombox").css({"left":zoomLeft+"px", "top":zoomTop+"px"});

			$("#zoombox").children(".large-image-close").bind("click", function(event){kk_konfigurator.zoomShowHide(event, $(this))});
		}
	},
	updateSelections: function(){
		$(".product-view-configure-options-container").each(
			function(){
				kk_konfigurator.selected = new Array();
				$(this).children(".product-view-configure-single-option-selected").each(
					function(){
						kk_konfigurator.selected.push($(this).attr("kk:option_id"));
					}
				);
				$(this).children("input").val(kk_konfigurator.selected.join(","));
			}
		);
		var ret = kk_konfigurator.validate();
		if(ret.ok) {
			kk_konfigurator.getCurrentPrice();
		}
	}
}

kk_konfigureret = {
	init : function(){
		$(".product-view-configured-variant-option").hover(kk_konfigureret.variantOver, kk_konfigureret.variantOut);
		$(".orange-overlay").click(
			function(){followAnchorTag($(".nav-left a"));}
		)
	},
	totalPrice : function(productPrice){
		var total = 0;
		$(".product-view-configured-variant-option").each(function(){
			if(!isNaN($(this).attr("kk:option_price"))){
				total = total + parseFloat($(this).attr("kk:option_price"));
			}
		});
		total = total + parseFloat(productPrice);
		$("#price-tag-container span.price").html(number_format(total,2,",",".")+"dkr.");
		$(".product-view-configured-navigation span.price").html(number_format(total,2,",",".")+"dkr.");
	},
	variantOver : function(){
		$(this).children("div[class!=orange-overlay]").css({"visibility":"hidden"});
		$(this).addClass("variant-over");
		$(this).children(".orange-overlay").show();
	},
	variantOut : function(){
		$(this).children(".orange-overlay").hide();
		$(this).children("div").css({"visibility":"visible"});
		$(this).removeClass("variant-over");
	}
}

function followAnchorTag(anAnchor){
	var theSite = document.location.protocol + "//" + document.location.hostname;
	var theHref = $(anAnchor).attr("href");
	var theLink = theSite + "/" + theHref;
	document.location.replace(theLink);
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57

    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "," : dec_point;
    var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;

    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

