﻿var basePrice;
var optionPrice;
var currencySymbol;
var openBuildAndPrice = false;

google.setOnLoadCallback(function () {
    $(document).ready(function () {
        initICEConfigurator();

        if ($("#ConfigurationCode").val() != "" && $("#ConfigurationCode").val() != $("#ConfigurationCode").attr("placeholder")) {
            loadConfigurationCode($("#ConfigurationCode").val());
            openBuildAndPrice = true;
        }
    });
});

function initICEConfigurator() {
	$("#overlay").hide();
	$("ul.optionDescriptions li").hide();

	setConfiguratorBasePrice();

	//Add a change event to disable the options that are precluded by this one
	$("#options select").change(
        function() { updateOptions(this); }
    );

	$("#editionId").change(
		function() { changeBaseEdition(this); }
	);

	$("#GetConfiguration").click(function (e) {
	    e.preventDefault();
	    loadConfigurationCode($("#ConfigurationCode").val());
	});

	if (openBuildAndPrice) {
	    $(".tabs").find("li:eq(3)").find("a").click();
    }

	//Frame colour selector
	$("div[id^='frameColor']").click(function () { selectFrameColour(this); });
	$("div[id^='frameColor'].current").click();

	//Add click events to the option images top open the overlay
	$("li[id^=optionDescription] > a").click(function() { loadOptionImage(this); }).attr("href", "#");
	killAnchors();

	//Print/email buttons
	$("#printSpec").click(function() { captureConfig("print"); });
	$("#emailSpec").click(function () { captureConfig("email"); });
}

function changeBaseEdition(what) {
    var editionUrl = removeConfigurationCodeFromURL(document.location)+"";
	editionUrl = editionUrl.split("#")[0];
	$("#configurator").load(editionUrl + "/" + $(what).val() + "/configure #configurator", function() { initICEConfigurator(); });
	//pageTracker._trackPageview(window.location.pathname + "/configuration/" + $(what).val());
}

function loadConfigurationCode(configurationCode) {
    var editionUrl = removeConfigurationCodeFromURL(document.location)+"";
    editionUrl = editionUrl.split("#")[0];

    $.get(editionUrl + "/loadconfiguration/" + configurationCode, function (theResponse) {
        if (theResponse.indexOf("Fail!") > 0) {
            $(".configurationForm .noConfigMessage").show();
            $("#ConfigurationCode").addClass("input-validation-error");
            $(".tabs").find("li:eq(3)").find("a").click();
        }
        else {
            $("#configurator").html($("#configurator", theResponse).html());
            initICEConfigurator();
            updateOptions();
        }
    });
}

function removeConfigurationCodeFromURL(currentUrl) {
    currentUrl = currentUrl.toString();
    var start = currentUrl.indexOf("/configuration");
    if (start > 0) {
        currentUrl = currentUrl.replace(currentUrl.substring(start, currentUrl.length), "");
    }
    return currentUrl;
}

function updateOptions(what) {
	//Hide all descriptions
	$("ul.optionDescriptions li").hide();
	//Remove all preclusion marks
	$("#options option").removeClass("precludor").removeClass("precluded").removeAttr("disabled");

	var allSelections = $("#options select");
	var optionPriceTotal = 0;
	jQuery.each(allSelections, function(i, val) {
		var chosenId = $(val).val();
		$(".precludedBy_" + chosenId).addClass("precluded").attr("disabled", "disabled");
		$("#optionDescription_" + chosenId).show();
		if (chosenId != "-1") {
			var chosenOptionPrice = eval("optionPrice.option_" + chosenId);
			if (chosenOptionPrice != NaN) {
				optionPriceTotal += chosenOptionPrice;
			}
		}
	}
	);
	
	//var newPrice = formatBigCurrency(basePrice + optionPriceTotal);
	var newPrice = formatCurrency(basePrice + optionPriceTotal);
	if (currencySymbol == "€") {
		newPrice = newPrice.replace(",",".");
	}

	$(".currentPrice").html(currencySymbol + newPrice);
}

function setConfiguratorBasePrice() {
    basePriceString = $("#basePrice").val();
    optionPriceString = $("#optionPrice").val();
    currencySymbol = $("#currencySymbol").val();
    eval("basePrice = " + basePriceString);
    eval("optionPrice = " + optionPriceString);
}

function selectFrameColour(what) {
	$("div[id^='frameColor']").removeClass("current");
	var frameColour = $(what).addClass("current").attr("id");
	frameColour = frameColour.split("_")[1];
	$("#frameColour").val(frameColour);
}

function loadOptionImage(what) {
	var optionId = $(what).closest("li").attr("id").split("_")[1];
	$("#overlay").load("/gallery/option/" + optionId, function() { showOptionImage() });
}

function showOptionImage() {
	$("#overlay .closeButton").click(function() { hideOptionImage(); });
	showOverlay();
}

function hideOptionImage() {
	hideOverlay();
}

//Capture configuration and email

function captureConfig(mode) {
	var allSelectItems = $("#configurator select");
	var colourSelection = $("#frameColour").val();
	var editionId = $(allSelectItems[0]).val();
	var selectedOptions = "";
	$.each(allSelectItems, function(i, val) {
		if (i == 1) {
			selectedOptions += colourSelection + ",";
		}
		var optionValue = $(val).val();
		if (optionValue != "-1") {
			selectedOptions += optionValue + ",";
		}
	});
	var optionData = { options: selectedOptions };
	
	var editionUrl = removeConfigurationCodeFromURL(document.location)+"";
	editionUrl = editionUrl.split("#")[0];
	var configurationUrl = editionUrl + "/" + editionId + "/configuration";

	//Post the config back to the server
	switch (mode)
	{
	    case "print":
	        //pageTracker._trackPageview(window.location.pathname + "/configuration/print/" + editionId);
			$.post(configurationUrl, optionData, function(data) { showConfigurationOverlay(data); });
			break;
		case "email":
		    configurationUrl += "/email";
		    //pageTracker._trackPageview(window.location.pathname + "/configuration/email/" + editionId);
			$.post(configurationUrl, optionData, function(data) { showConfigurationOverlay(data); });
			break;        case "send":
            configurationUrl += "/send";
    
            var forename = $("#Forename").val();
            var surname = $("#Surname").val();
            var address = $("#Address").val();
            var address2 = $("#Address2").val();
            var towncity = $("#TownCity").val();
            var countystate = $("#CountyState").val();
            var postcode = $("#Postcode").val();
            var country = $("#Country").val();
            var email = $("#Email").val();
            var phone = $("#Phone").val();
            var comments = $("#Comments").val();
            var isdealer = $("#IsDealer").is(":checked");
            if ($("#IsDealerAutoTrue").val() == "true") {
                isdealer = true;
            }
            var dealeremail = $("#DealerEmail").val();            var optionData = { options: selectedOptions, Forename: forename, Surname: surname, Address: address, Address2: address2, TownCity: towncity, CountyState: countystate, Postcode: postcode, Country: country, Email: email, Phone: phone, Comments: comments, DealerEmail: dealeremail, IsDealer: isdealer };            $.post(configurationUrl, optionData, function (data) { updateConfigurationOverlay(data); });
            break;
      }
}

function showConfigurationOverlay(html) {
	$("#overlay").html(html);
	$("#overlay .closeButton").click(function() { hideOverlay(); });
	$("#overlay .printButton").click(function() { $("#overlay").css("height", "auto"); window.print(); });
	$("#configSubmit").click(function() { captureConfig("send"); });
	showOverlay();
}

function updateConfigurationOverlay(html) {
	$("#configurationEmailFeedback").html(html);
}
