/*
 * @author: Ronny Hartmann-Schmidt
 *
 * This file handles filling the storefront form an visible elements handling afte an option
 * of a variant SKU is selected.
 *
 * Preconditions are:	- included jQuery library
 * 						- Master/Variant - SKU
 * 						- using "model/buildVariantDataModel.inc"
 *
 */
/*
 * Global variable definitions
 */
var variantOption0 = "";
var variantOption1 = "";
var variantOption2 = "";
var variantOption3 = "";
var variantOption4 = "";
var currencySign = "";
var jsonObjLength = 0;
var isOutlet = false;

function getURLParam(strParamName){

	var strReturn = "";
	var strHref = window.location.href;

	if ( strHref.indexOf("?") > -1 ){
		var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
		var aQueryString = strQueryString.split("&");
		
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
			if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return strReturn;
}	

function markSubmittedColor(colorId) {
	if(variantOption0 != "") {
		for (var i = 0; i < variantCombinationsObj.myVariants.length; i++) {
			if(variantCombinationsObj.myVariants[i].cattVal0 == variantOption0 && variantCombinationsObj.myVariants[i].cattVal1 == colorId && variantCombinationsObj.myVariants[i].qty > 0) {
				var optionTwoJS = $("#div\\.color-tooltip-" + colorId).attr("onclick");
				if(optionTwoJS){optionTwoJS();}
				break;
			}
		}
	}
}	

/*
 * overwriting the skuId value from the AddItem form with the first available sku in the
 * variant sku result set
 */
function initiateFirstAvailableVariantSku(skuId){
    $(document).ready(function(){
    	
    	var optionOneIdValue = "";
    	var optionTwoIdValue = "";
    	
        for (var i = 0; i < variantCombinationsObj.myVariants.length; i++) {
        	if (variantCombinationsObj.myVariants[i].siId == skuId){
        		// Get the JS action event
        		optionOneIdValue = variantCombinationsObj.myVariants[i].cattVal0.replace(" ","-");
        		optionTwoIdValue = variantCombinationsObj.myVariants[i].cattVal1.replace(" ","-");
        		var optionOneJS = $("#variant-0-" + optionOneIdValue).attr("onclick");
        		var optionTwoJS = $("#div\\.color-tooltip-" + optionTwoIdValue).attr("onclick");
        	}
        }
        // Fire the JS action event to simulate choose of first available variant item
        if(optionOneJS){optionOneJS();}
       // if(optionTwoJS){optionTwoJS();}

        // Deselect color
        $("#variant-1-" + optionTwoIdValue).removeClass("active");
                
        jQuery('[name=siId]').val(skuId);
		
		var colorId = getURLParam("colorid");
		
		if(colorId != "") {
			markSubmittedColor(colorId);
		}		

    });
}

/*
 * run over the page and search for n/a variants and mark them
 */
function markNotAvailableVariants(){

    if ($(".not-available").length) {
        $(".not-available").each(function(){
            var varianttohandle = $(this).attr("id");
            var variantwidthtohandle = $(this).width() + 8;
            var variantheighttohandle = $(this).height() + 8;
            $("#" + varianttohandle).append('<image src=' + window.location.protocol + '//' + window.location.hostname + '/ctlimg/Wolford/images/backgrounds/not_available.gif class="image-not-available" id="image-not-available-' + varianttohandle + '">');
            $("#image-not-available-" + varianttohandle).css("width", variantwidthtohandle + "px");
            $("#image-not-available-" + varianttohandle).css("height", variantheighttohandle + "px");
            $("#image-not-available-" + varianttohandle).css("display", "block");
        });
    }

}

function setFormData(index) {

	var varaiantSiId = variantCombinationsObj.myVariants[index].siId;
		varaiantSiId = varaiantSiId.toString();

	var varaiantPrice = variantCombinationsObj.myVariants[index].siPrice;
		varaiantPrice = varaiantPrice.toString();
		//varaiantPrice = varaiantPrice.replace(/[.]/,",");

	var varaiantRetailPrice = variantCombinationsObj.myVariants[index].retailPrice;
		varaiantRetailPrice = varaiantRetailPrice.toString();
		//varaiantRetailPrice = varaiantRetailPrice.replace(/[.]/,",");

	var variantImage = variantCombinationsObj.myVariants[index].variantImage;
		variantImage = variantImage.toString();

	var variantQtyOnHold = variantCombinationsObj.myVariants[index].qty;

	// fill the form with the new data
	$('[name=siId]').val(varaiantSiId);
	$('[name=variantQtyOnHold]').val(variantQtyOnHold);
	if (parseInt(varaiantRetailPrice) > 0 && parseFloat(varaiantRetailPrice) > parseFloat(varaiantPrice) ) {
		$("#rrp-price-id").html("<del>" + currencySign + "&nbsp;" + varaiantRetailPrice + "</del>");
		$("#rrp-price-id").show();
		$("#rrp-price-id").removeClass("hide");
		$("#si-price-id").addClass("new-price");
	}
	else {
		$("#rrp-price-id").hide();
		$("#si-price-id").removeClass("new-price");
	}
	$("#si-price-id").html(currencySign + "&nbsp;" + varaiantPrice);

	// set the new variant image if available
	if( $("#si-image-id").attr("src") != variantImage && variantImage != "" ) {
		$("#si-image-id").attr("src",variantImage);
	}

}

function handleOption0(trigger){
	var variantFound = false;

	for (var i = 0; i < variantCombinationsObj.myVariants.length; i++) {

		// looking for all combinations wich don't have quantity and are fitting our selected variant option
		if (parseInt(variantCombinationsObj.myVariants[i].qty) < 1 && variantCombinationsObj.myVariants[i].cattVal0 == variantOption0) {

			// if we got one we have to set those container to not available
			$("#variant-1-" + variantCombinationsObj.myVariants[i].cattVal1).addClass("not-available");

            var varianttohandle = "variant-1-" + variantCombinationsObj.myVariants[i].cattVal1;
            var variantOverlayPercent = "color-tooltip-percent-layer-" + variantCombinationsObj.myVariants[i].cattVal1;
            var variantwidthtohandle = $("#" + varianttohandle).width() + 8;
            var variantheighttohandle = $("#" + varianttohandle).height() + 8;

            if(parseFloat(variantCombinationsObj.myVariants[i].siPrice) < parseFloat(variantCombinationsObj.myVariants[i].retailPrice) && !isOutlet){
            	$("#" + varianttohandle).append('<image src=' + window.location.protocol + '//' + window.location.hostname + '/ctlimg/Wolford/images/backgrounds/sale_strich.png class="image-not-available" id="image-not-available-' + varianttohandle + '">');
            	$("#" + variantOverlayPercent).show();
            }
            else{
            	$("#" + varianttohandle).append('<image src=' + window.location.protocol + '//' + window.location.hostname + '/ctlimg/Wolford/images/backgrounds/not_available.gif class="image-not-available" id="image-not-available-' + varianttohandle + '">');
            	$("#" + variantOverlayPercent).hide();
            }

            $("#image-not-available-" + varianttohandle).css("width", variantwidthtohandle + "px");
            $("#image-not-available-" + varianttohandle).css("height", variantheighttohandle + "px");
            $("#image-not-available-" + varianttohandle).css("display", "block");


			// if a former selected container now becomes n/a we have to deselect this one and clear the former selected option
			if ($("#variant-1-" + variantCombinationsObj.myVariants[i].cattVal1).hasClass("active")) {
				$("#variant-1-" + variantCombinationsObj.myVariants[i].cattVal1).removeClass("active");
				if (trigger) {
					variantOption1 = "";
				}
			}
		}

		// now catch the first available variant item with the seleceted property and set the form data
		// this is for variants which have only one property
		if (variantCombinationsObj.myVariants[i].cattVal0 == variantOption0 && parseInt(variantCombinationsObj.myVariants[i].qty) > 0) {
			setFormData(i);
			variantFound = true;

			var variantOverlayPercent = "color-tooltip-percent-layer-" + variantCombinationsObj.myVariants[i].cattVal1;

			// Look for a available discounted variant item and mark it
			if(parseFloat(variantCombinationsObj.myVariants[i].siPrice) < parseFloat(variantCombinationsObj.myVariants[i].retailPrice) && !isOutlet){
	            var varianttohandle = "variant-1-" + variantCombinationsObj.myVariants[i].cattVal1;
	            var variantwidthtohandle = $("#" + varianttohandle).width() + 8;
	            var variantheighttohandle = $("#" + varianttohandle).height() + 8;
	            $("#" + varianttohandle).append('<image src=' + window.location.protocol + '//' + window.location.hostname + '/ctlimg/Wolford/images/backgrounds/sale_normal.png class="image-available-discounted" id="image-not-available-' + varianttohandle + '">');
	            $("#" + variantOverlayPercent).show();
	            $("#image-not-available-" + varianttohandle).css("width", variantwidthtohandle + "px");
	            $("#image-not-available-" + varianttohandle).css("height", variantheighttohandle + "px");
	            $("#image-not-available-" + varianttohandle).css("display", "block");
			}
			else {
				$("#" + variantOverlayPercent).hide();
			}

		}
	};

	if(!variantFound){
		$('[name=siId]').val("");
	}

}

function handleOption1(trigger){
	var variantFound = false;

	for (var i = 0; i < variantCombinationsObj.myVariants.length; i++) {

		// looking for all combinations wich don't have quantity and are fitting our selected variant option
		if (parseInt(variantCombinationsObj.myVariants[i].qty) < 1 && variantCombinationsObj.myVariants[i].cattVal1 == variantOption1) {

			// if we got one we have to set those container to not available
			$("#variant-0-" + variantCombinationsObj.myVariants[i].cattVal0).addClass("not-available");

			// if a former selected container now becomes n/a we have to deselect this one and clear the former selected option
			if ($("#variant-0-" + variantCombinationsObj.myVariants[i].cattVal1).hasClass("active")) {
				$("#variant-0-" + variantCombinationsObj.myVariants[i].cattVal1).removeClass("active");
				if (trigger) {
					variantOption0 = "";
				}
			}
		}

		// now catch the first available variant item with the seleceted property and set the form data
		// this is for variants which have only one property
		if (variantCombinationsObj.myVariants[i].cattVal1 == variantOption1 && parseInt(variantCombinationsObj.myVariants[i].qty) > 0) {
			setFormData(i);
			variantFound = true;
		}

	}

	if(!variantFound){
		$('[name=siId]').val("");
	}
}

function handleVariantOpionData(){
	for (var i = 0; i < variantCombinationsObj.myVariants.length; i++) {
		if(variantCombinationsObj.myVariants[i].cattVal0 == variantOption0 && variantCombinationsObj.myVariants[i].cattVal1 == variantOption1){
			setFormData(i);
		}
	}
}

/*
 * here we look into JSON
 */
function searchForAvailableVariants(variantIndex){
	// running through the whole JSON object

	// we have to handle both choosen variant but w/o clearing the former choosen opposite variant option
	handleOption0(false);
	handleOption1(false);

	// now get the data of the choosen variant combination and fill the form and manipulate the page
	handleVariantOpionData();

}

/*
 * initial handler for choosing the correct function / doing dependend on the selected variant
 */
function variantChoose(variantIndex, variantValue, variantArrayClass, variantSubmittedId, jsonLength, currSign, isOutletSubmit){

	
    //Do all this stuff only if the submitted variant is available... means do not have the class "not-available"
    if (!$("#" + variantSubmittedId).hasClass("not-available")) {

    	if(isOutletSubmit == "true"){
    		isOutlet = true;
    	}
    	else {
    		isOutlet = false;
    	}
    	
        jsonObjLength = jsonLength;

		// set the curreny sign as we may have multiple choices
		currencySign = currSign;

        // save the value of the submitted variant
        switch (variantIndex) {
            case "0":
                variantOption0 = variantValue;
				var oppositeIdForNARemove = 1;
                break;
            case "1":
                variantOption1 = variantValue;
				var oppositeIdForNARemove = 0;
				
				// remove the select color hint
				jQuery(".first-load").each(function(){
					
					if(jQuery(this).attr("alt")) {
						var onClickEvent = jQuery(this).attr("alt");
						onClickEvent = onClickEvent.replace(/function onclick\(\)/g,"");
						onClickEvent = onClickEvent.replace(/function anonymous\(\)/g,"");
						onClickEvent = onClickEvent.replace("{","");
						onClickEvent = onClickEvent.replace("}","");
						jQuery(this).unbind("click").click(function(){eval(onClickEvent)});
						jQuery(this).attr("alt","");
					}
					
					if(jQuery(this).attr("rel")) {
						var hrefEvent = jQuery(this).attr("rel");
						jQuery(this).attr("href",hrefEvent);
						jQuery(this).attr("rel","");
						jQuery(this).unbind("click");
					}
					
					jQuery(this).removeClass("first-load");
					
				});					
				
                break;
            case "2":
                variantOption2 = variantValue;
                break;
            case "3":
                variantOption3 = variantValue;
                break;
            case "4":
                variantOption4 = variantValue;
                break;
        }

        // reset the view of all item of the submitted variantArrayClass
        $("." + variantArrayClass).each(function(){
            $(this).removeClass("active");
        });

		// reset the not-available classes and images as they have to be built each time new
		// but only for the opposite row
		$("span").each(function(){
			if ($(this).hasClass("not-available") && $(this).attr("id").indexOf("variant-" + oppositeIdForNARemove) != -1) {
				$(this).removeClass("not-available");
			}
        });

		$(".image-not-available").remove();
		$(".image-available-discounted").remove();

        // run through the JSON object and search for available variants
        searchForAvailableVariants(variantIndex);

        // set back the not available variants
        markNotAvailableVariants();

        // change the look for submitted variant
        $("#" + variantSubmittedId).addClass("active");
		
    }
}


