var theCarousel = new Carousel();

$(document).ready(function() {
	buildFormToolTips();
	firstAndLast();
	topNav = new TopNav();
	topNav.init();
	$("#panel3 label").inFieldLabels({ fadeOpacity: 0.3 });

	theCarousel.init();

	theCalculator = new Calculator();
	theCalculator.init();
	if ($(document).getUrlParam("freeReview") !== null || $(document).getUrlParam("freeReview") === undefined) {
		theCarousel.goToPanel("#panel3");
	}

});

function ShowConfirmationView() {
	theCarousel.goToPanel("#panel3");
}

function firstAndLast() {
	$("#nav ul li:last-child, #crumb ul li:last-child, #infoSections .section:last, #subContent .article:last").addClass("last");
	$("#nav ul li:first-child, #crumb ul li:first-child").addClass("first");
}

function TopNav() {
	
	this.hoveredEl = false;
	this.subNavTimer = false;
	
	this.init = function() {
		var that = this;
		$("#nav ul li, #nav ul li ul").mouseenter(function() { that.hoverIn(this); });
		$("#nav ul li, #nav ul li ul").mouseleave(function() { that.hoverOut(this); });
		$("#header #nav ul li.active").prev().addClass('activePrev');
		$("#header #nav ul li:last-child").prev().addClass('noDivider');
	}
	this.hoverIn = function (el) {
		$(el).addClass("hovered");
		$(el).prev().addClass('hoveredPrev');
		subNavTimer = $.timer(350, function() {
			if (hoveredEl == el) {
				$(el).find("ul").fadeIn('fast');
			}
		});
		hoveredEl=el;
	}
	this.hoverOut = function(el) {
		$(el).find("ul").fadeOut('fast');
		$(el).removeClass("hovered");
		$(el).prev().removeClass('hoveredPrev');
		$.clearTimer(subNavTimer);
		hoveredEl=false;
	}

}

function Carousel() {
	this.s = {
		main:"#featCarousel",
		panel:".panel"
	}

	this.init = function() {
		t = this;

		$("#arrangeReviewPanel").click(function() {
			t.goToPanel("#panel3");
		});
		$("#viewCalculatorPanelFromLarge, #btnTryItNow, #viewCalculatorPanelFromSmall").click(function() {
			t.goToPanel("#panel2");
		});
		$("#savingsTotal, .savingsSection input, #fraudAmount").focus(function() { $(this).blur(); });
	};
	
	this.goToPanel = function(thePanelSelector) {
		$currentPanel = $(this.s.main).find(".active");
		$nextPanel = $(thePanelSelector,this.s.main);
		$currentPanel.animate({width:"0px"}, 500,'easeInQuad').removeClass('active');
		$nextPanel.animate({width:"979px"}, 700,'easeOutQuad').addClass('active');
	}
}

function Calculator() {
	this.s = {
		main: "#calculator",
		sliders: ".slider"
	};
	this.defaultFraudAmount = 0.06;
	this.init = function() {
		if (!$(this.s.main).is(this.s.main)) { return false; }
		this._createSliders();
		return true;
	}

	this._createSliders = function() {
		var that = this;
		$(".slider #sliderDebtors").slider({ min: 20000, max: 6000000, value: 600000, step: 10000,
			slide: function(event, ui) {
				that.updateValue(this, ui.value);
				that.updateSavingValue(this, ui.value);
			}
		});
		$(".slider #sliderDebtorsPercent").slider({ min: 1, max: 100, value: 10, step: 1,
			slide: function(event, ui) {
				that.updateValue(this, ui.value);
				that.updateSavingValue(this);
			}
		});
		$(".slider #sliderStock").slider({ min: 20000, max: 6000000, value: 600000, step: 10000,
			slide: function(event, ui) {
				that.updateValue(this, ui.value);
				that.updateSavingValue(this, ui.value);
			}
		});
		$(".slider #sliderStockPercent").slider({ min: 1, max: 100, value: 10, step: 1,
			slide: function(event, ui) {
				that.updateValue(this, ui.value);
				that.updateSavingValue(this);
			}
		});
		$(".slider #sliderExpenses").slider({ min: 100000, max: 12000000, value: 1000000, step: 10000,
			slide: function(event, ui) {
				that.updateValue(this, ui.value);
				that.updateSavingValue(this, ui.value);
			}
		});
		$(".slider #sliderExpensesPercent").slider({ min: 1, max: 100, value: 5, step: 1,
			slide: function(event, ui) {
				that.updateValue(this, ui.value);
				that.updateSavingValue(this);
			}
		});
		$(".slider #sliderSales").slider({ min: 500000, max: 20000000, value: 4000000, step: 10000,
			slide: function(event, ui) {
				that.updateValue(this, ui.value);
				that.updateSalesValue(this, ui.value);
			}
		});
		$(".slider #sliderSalesPercent").slider({ min: 1, max: 100, value: 5, step: 1,
			slide: function(event, ui) {
				that.updateValue(this, ui.value);
				that.updateSalesValue(this);
			}
		});
		$(".slider #sliderSalesProfitPercent").slider({ min: 1, max: 100, value: 60, step: 1,
			slide: function(event, ui) {
				that.updateValue(this, ui.value);
				that.updateSalesValue(this);
			}
		});
		$(".slider #sliderFraudPercent").slider({ min: 0, max: 6, value: 3, step: 1,
			slide: function(event, ui) {
				var max = $(this).slider('option', 'max');
				that.updateValue(this, ui.value);
				that.updateSavingValue(this);
				that.updateFraudValue(this, max, 3);
			}
		});

		$inputs = $("#calculator div.valueSection input");
		
		$("#calculator div.valueSection.percent input").each(function(k,v){
			$t = $(this);
			$s = $t.closest("div.valueSection").find(".ui-slider");
			if ($s.attr("id") !== undefined) {
				$t.attr("min",$s.slider("option","min"));
				$t.attr("max",$s.slider("option","max"));
			}
		});
		$inputs.keydown(function(event) {
			if (that.enterKeyPressed(event)) {
				if (event.cancelBubble) { event.cancelBubble(); }
				event.stopPropagation();
				event.preventDefault();
			}
		});
		$inputs.keypress(function(event) {
			if (that.enterKeyPressed(event)) {
				if (event.cancelBubble) { event.cancelBubble(); }
				event.stopPropagation();
				event.preventDefault();
			}
		});

		$inputs.keyup(function() {
			that.fieldUpdated(this);
			$t = $(this);
			if ($t.closest(".valueSection").hasClass("percent")) {
				that.checkFieldBounds(this);
			}
			if ($t.closest("li").attr("id") == "calculatorSalesPanel") {
				that.updateSalesValue(this);
				return;
			}
			if ($t.closest("li").attr("id") == "calculatorFraudPanel") {
				that.updateFraudValue(this);
				return;
			}
			that.updateSavingValue(this);

		});
		$inputs.blur(function() {
			if ($t.closest(".valueSection").hasClass("percent")) {
				that.checkFieldBounds(this, false);				
			}
			if (this.id == "salesPercent" || this.id == "salesProfitPercent" || this.id == "salesAmount") {
				that.updateSalesValue(this);
				return;
			}
			if (this.id == "fraudReducePercent" || this.id == "fraudAmount") {
				that.updateFraudValue(this);
				return;
			}
			that.updateSavingValue(this);
		});
		this._setDefaults();
	}
	
	this.enterKeyPressed = function(e) {
		if (e.keyCode == 13) {
			return true;
		}
		return false;

	};
	this.fieldUpdated = function(el) {
		//get the value, update the nearest slider.
		$e = $(el)
		//if value is "", undefined, etc - set to 0
		var v = this.stripNumberFormatting($e.val());
		if (v===undefined || isNaN(v) || v === "") {
			$e.val(0);
			v = 0;
		}
		$vs = $e.closest(".valueSection").find(".ui-slider");
		if ($vs.hasClass(".ui-slider")) {
			$vs.slider("value", v);
		}
	}
	this.checkFieldBounds = function(el, setValue) {
		//that = this;
		$e = $(el)
		var v = this.stripNumberFormatting($e.val());
		v = (v == undefined || isNaN(v)) ? 0 : parseInt(v);
		vMin = $e.attr("min");
		vMax = $e.attr("max");
		if (vMin !== undefined && vMax !== undefined) {
			v = (v < vMin) ? vMin : v;
			v = (v > vMax) ? vMax : v;
		}
		if (setValue === true) {
			$e.val(this.numberFormat(v));
		}
		$vs = $e.closest(".valueSection").find(".ui-slider");
		if ($vs.hasClass(".ui-slider")) {
			$vs.slider("value", v);
		}
	}
	this.updateValue = function(el, value) {
		$(el).closest(".valueSection").find("input").val(this.numberFormat(value));
	}
	this.updateSavingValue = function(el) {
		//$el = $(el);
		$li = $(el).closest("li");
		amount = parseInt(this.stripNumberFormatting($li.find(".valueSection.amount input").val()));
		percent = this.stripNumberFormatting($li.find(".valueSection.percent input").val());
		if (percent == 0) {
			savingsVal = 0;
		} else {
			savingsVal = parseInt(amount * (percent / 100));
		}
		$li.find(".savingsSection input").val(this.numberFormat(savingsVal))
		this.updateTotal();
	}
	this.updateSalesValue = function(el, value) {
		$el = $(el).closest("li");
		var salesPercentValue = $el.find("#salesPercent").val();
		var salesProfitPercentValue = $el.find("#salesProfitPercent").val();
		salesIncreasePercent = 0;
		theSalesProfitPercent = 0;

		if (!isNaN(salesPercentValue)) {
			salesIncreasePercent = this.stripNumberFormatting($el.find("#salesPercent").val());
		}

		if (!isNaN(salesProfitPercentValue)) {
			theSalesProfitPercent = this.stripNumberFormatting($el.find("#salesProfitPercent").val());
		}
		amount = parseInt(this.stripNumberFormatting($el.find(".valueSection.amount input").val()));
		if (salesIncreasePercent == 0 || theSalesProfitPercent == 0) {
			savingsVal = 0;
		} else {
			savingsVal = parseInt((amount * (salesIncreasePercent / 100)) * (theSalesProfitPercent / 100));
		}
		$el.find(".savingsSection input").val(this.numberFormat(savingsVal))
		this.updateFraudSavings();
		this.updateTotal();
	}
	this.updateFraudValue = function(el, max, defaultVal) {
		$el = $(el).closest("li");
		$input = $el.find(".valueSection.percent input");
		amount = parseInt(this.stripNumberFormatting($("#calculatorSalesPanel").find(".valueSection.amount input").val()));
		percent = this.stripNumberFormatting($input.val());
		var defVal = 0;
		if (!max) {
			max = $input.attr("max");
		}
		percent = (max - percent) || defVal;
		if (percent == 0) {
			savingsVal = 0;
		} else {
			savingsVal = parseInt(amount * (percent / 100));
		}
		$el.find(".savingsSection input").val(this.numberFormat(savingsVal))
		this.updateTotal();
	}

	this.updateTotal = function() {
		var total = 0;
		var that = this;
		$("#calculator .savingsSection input").each(function(k, v) {
			value = parseInt(that.stripNumberFormatting($(v).val()));
			total = total + value
		});
		$("#savingsTotal").val("$ " + this.numberFormat(total));
	}
	this.updateFraudSavings = function() {
		amount = parseInt(this.stripNumberFormatting($("#calculatorSalesPanel").find(".valueSection.amount input").val()));
		var fv = parseInt(amount * this.defaultFraudAmount);
		$("#fraudAmount").val(this.numberFormat(fv));
		$el = $("#calculatorFraudPanel");
		amount = parseInt(this.stripNumberFormatting($("#calculatorSalesPanel").find(".valueSection.amount input").val()));
		percent = this.stripNumberFormatting($el.find(".valueSection.percent input").val());

		var max = 6;
		var defVal = 0;
		if (!max) {
			max = $input.attr("max");
		}
		percent = (max - percent) || defVal;

		if (percent == 0) {
			savingsVal = 0;
		} else {
			savingsVal = parseInt(amount * (percent / 100));
		}
		$el.find(".savingsSection input").val(this.numberFormat(savingsVal))
	}
	//get the values of the sliders and assign these values to the text boxes
	this._setDefaults = function() {
		var that = this;
		$(".slider .ui-slider").each(function(k, v) {
			value = $(v).slider("value");
			$in = $(v).closest("div.valueSection").find("input");
			$in.val(that.numberFormat(value));
			$in.trigger("keyup");
		});
		this.updateFraudValue();

	}

	this.numberFormat = function(number) {
		//if the string has commas in then, remove:
		str = "";
		nStr = number + "";
		nStr = nStr.replace(",", "");
		//console.log(nStr);
		x = nStr.split(".");
		x1 = x[0];
		x2 = x.length > 1 ? "." + x[1] : "";
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, "$1" + "," + "$2");
		}
		str += x1 + x2;
		return str
	}
	this.stripNumberFormatting = function(strNum) {
		nStr = strNum + "";
		while (nStr.match(",")) {
			nStr = nStr.replace(",", "");
		}
		nStr = parseFloat(nStr)==NaN?0:parseFloat(nStr);
		return nStr;
	}

}

// Registration form functions

function buildFormToolTips() {
	$('span.message').hide();
	$("div.form input, div.form select, div.form textarea").focus(function() {
		if ($(this).parents("div").hasClass('error')) {
			$(this).closest('div.error').find('span.message').show();
			$(this).closest('div.error').find('span.arrow').addClass('arrowActive');
			$(this).blur(function() {
				$(this).closest('div.error').find('span.message').hide();
				$(this).closest('div.error').find('span.arrow').removeClass('arrowActive');
			});
		}
	});
}

/* Copyright (c) 2006-2007 Mathias Bank (http://www.mathias-bank.de)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* Version 2.1
*/
jQuery.fn.extend({ getUrlParam: function(strParamName) { strParamName = escape(unescape(strParamName)); var returnVal = new Array(); var qString = null; if ($(this).attr("nodeName") == "#document") { if (window.location.search.search(strParamName) > -1) { qString = window.location.search.substr(1, window.location.search.length).split("&"); } } else if ($(this).attr("src") != "undefined") { var strHref = $(this).attr("src"); if (strHref.indexOf("?") > -1) { var strQueryString = strHref.substr(strHref.indexOf("?") + 1); qString = strQueryString.split("&"); } } else if ($(this).attr("href") != "undefined") { var strHref = $(this).attr("href"); if (strHref.indexOf("?") > -1) { var strQueryString = strHref.substr(strHref.indexOf("?") + 1); qString = strQueryString.split("&"); } } else { return null; } if (qString == null) return null; for (var i = 0; i < qString.length; i++) { if (escape(unescape(qString[i].split("=")[0])) == strParamName) { returnVal.push(qString[i].split("=")[1]); } } if (returnVal.length == 0) return null; else if (returnVal.length == 1) return returnVal[0]; else return returnVal; } }); 
