function initEnviroment() {
	__baseUri = jQuery("base").attr("href");

	/** Init external links **/
	var a = jQuery("a[rel='external']").get();
	jQuery.each(a, function(a, val) {
		jQuery(val).attr("target", "_blank");
	});
};

function initPayment() {
	var ccMethodCount = jQuery("#app-available-payments-count").val();
	ccMethodCount = parseInt(ccMethodCount);
	switch(ccMethodCount) {
		case 1:
			jQuery(".cc-item").show();
			break;
	}
};

if (!Number.toFixed) {
	Number.prototype.toFixed = function (n){
		return Math.round(this * Math.pow(10, n)) / Math.pow(10, n);
	};
}

if (!Number.toCurrency) {
	Number.prototype.toCurrency = function (){
		var i = parseFloat(this);
		if(isNaN(i)) { i = 0.00; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		i = parseInt((i + .005) * 100);
		i = i / 100;
		s = new String(i);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
		s = minus + s;
		return s;
	};
}

function initForms() {
    var l = $("label[class='required']").get();
    jQuery.each(l, function(a,val){
    	jQuery(val).append($("<span class=\"label-required\">*</span>"));
    });
};

function initOrderForm() {
	jQuery("div.shopping-cart .cart-list li:last-child").css({borderBottom:"none"});

	jQuery("#user-contactinfo-phonenumber").mask("999-999-9999");
	jQuery("#user-contactinfo-zipcode").mask("99999");
	jQuery("#cart-tip-amount").decimalMask({
		separator: ".",
		decSize: 2,
		intSize: 4
	});
	
	jQuery("#user-shippinginfo-phonenumber").mask("999-999-9999");
	jQuery("#user-shippinginfo-zipcode").mask("99999");
	
	var iniShippingEqBilling = function () {
		jQuery("fieldset.shipping-eq-billing #shipping-eq-billing").change(function() {
			if(jQuery(this).attr("checked") == "checked") {
				jQuery("fieldset.shipping-info").slideUp('fast', function() {});
			} else {
				jQuery("fieldset.shipping-info").slideDown('fast', function() {});
			}
		});
	};
	iniShippingEqBilling();

	var elements = jQuery(".price-hidden").get();
	jQuery.each(elements, function (index, value) {
		var hId = jQuery(value).attr("id");
		var vId = hId.replace("item-price-hidden-", "item-price-");
		jQuery("#" + vId).html("$" + jQuery("#" + hId).val());
	});

	var initPaymentGroup = function() {
		var setup = function(groupId) {
			jQuery(".payment-group").slideUp('fast', function() {});
			
			if(jQuery("#" + groupId).is(":hidden")){
				jQuery("#" + groupId).slideDown('slow', function() {});
			}
		};

		var userPaymentId = jQuery("input:radio[name='user[payment]']:checked").attr("id");
		if(typeof(userPaymentId) != "undefined") {
			jQuery("label[for='" + userPaymentId +"']").addClass("active");
			
			setup("group-" + userPaymentId, "");
		}
		
		jQuery(".payment-group-item").change(function() {
			var labelId = jQuery(this).attr("id");
			var groupId = "group-" + labelId;

			jQuery(".in-up").removeClass("active");
			
			var id = jQuery(this).attr("id");
			jQuery("label[for='" + id +"']").addClass("active");
			
			setup(groupId);
		});

		var getCcType = function(ccnumber) {
			var cctype = "";
			if (ccnumber.indexOf("4") == 0) {
				cctype = "visa";
			} else if((ccnumber.indexOf("34") == 0) || (ccnumber.indexOf("37") == 0)) {
				cctype = "amex";
			} else if(ccnumber.indexOf("6011") == 0) {
				cctype = "discover";
			} else if(ccnumber.indexOf("51") == 0 || ccnumber.indexOf("52") == 0 || ccnumber.indexOf("53") == 0 || ccnumber.indexOf("54") == 0 || ccnumber.indexOf("55") == 0) {
				cctype = "mastercard";
			}

			jQuery("#payment-cardtype").val(cctype);

			return cctype;
		};

		jQuery(".credit-card-number").change(function(){
			var inputcid = jQuery(this).attr("id");
			var ccnumber = jQuery(this).val();
			var cctype = getCcType(ccnumber);

			var initIcons = function (cctype) {
				var inputgid = "";
				if(inputcid == "user-paymentgroup-paypal-ccnumber") {
					inputgid = "group-user-payment-paypal";
				}
				if(inputcid == "user-paymentgroup-paypalstandard-ccnumber") {
					inputgid = "group-user-payment-paypalstandard";
				}
				if(inputcid == "user-paymentgroup-authorize-ccnumber") {
					inputgid = "group-user-payment-authorize";
				}
				if(inputcid == "user-paymentgroup-custommethod-ccnumber") {
					inputgid = "group-user-payment-custommethod";
				}
				
				var free = function (inputcid, cctype) {
					var elements = jQuery("#" + inputgid + " .cc-logos img").get();
					jQuery.each(elements, function(index, value) {
						var src = jQuery(value).attr("src");
						jQuery(value).attr("src", src.replace("_default", "_grey"));
					});
				};

				if(!cctype || cctype == "undefined") {
					free(inputcid, cctype);
					return false;
				}

				var setIcons = function (inputcid, cctype) {
					free(inputcid, cctype);

					if(inputgid != "group-user-payment-custommethod") {
						var src = jQuery("#" + inputgid + " .cc-logos img." + cctype + "-logo").attr("src");
						jQuery("#" + inputgid + " .cc-logos img." + cctype + "-logo").attr("src", src.replace("_grey", "_default"));
					}
				};
				
				setIcons(inputcid, cctype);
			};

			initIcons(cctype);
		});
	};
	initPaymentGroup();
	
	/** **/
	var reCalcTotalPrice = function() {
		var cartMode 			= jQuery("#cart-mode").val();
		var cartTax				= jQuery("#cart-tax").val();
		var cartSubTotal		= jQuery("#cart-subtotal-price").val();
		var cartChargeDelivery	= jQuery("#cart-charge-delivery").val();
		var cartChargePickup	= jQuery("#cart-charge-pickup").val();
		
		switch(cartMode) {
			case "checkout":
				var method = jQuery("#cart-delivery-method").val();
				
				var setData = function(value) {
					if(!value || typeof(value) == "undefined" || value == "NaN") {
						value = 0;
					}
					jQuery("#cart-tip").html("$" + value);
				};
				jQuery("#cart-tip-amount").change(function() {
					var tip = jQuery(this).val();
					setData(tip);
				});
				jQuery("#cart-tip-amount").keyup(function() {
					var tip = jQuery(this).val();
					setData(tip);
					
					if(method == "delivery") {
						var tax = ((cartSubTotal * (cartTax / 100)) + (cartChargeDelivery * (cartTax / 100))).toFixed(2);
						jQuery("#cart-subtotal-tax").html("$" + tax);
						
						var cartTotalPrice = parseFloat(cartSubTotal) + parseFloat(cartChargeDelivery)  + parseFloat(tip) + parseFloat(tax);
						jQuery("#cart-total-price").html("$" + cartTotalPrice.toFixed(2));
					}
					
					if(method == "pickup") {
						var tax = (cartSubTotal * (cartTax / 100)).toFixed(2);
						jQuery("#cart-subtotal-tax").html("$" + tax);
						
						var cartTotalPrice = parseFloat(cartSubTotal) + parseFloat(tax) + parseFloat(tip);
						jQuery("#cart-total-price").html("$" + cartTotalPrice.toFixed(2));
					}
					
				});
				
				var tip = jQuery("#cart-tip-amount").val().trim();
				setData(tip);
				
				var setup = function(method) {
					switch(method) {
						case "delivery":
							var tax = ((cartSubTotal * (cartTax / 100)) + (cartChargeDelivery * (cartTax / 100))).toFixed(2);
							jQuery("#cart-subtotal-tax").html("$" + tax);
							
							var cartTotalPrice = parseFloat(cartSubTotal) + parseFloat(cartChargeDelivery)  + parseFloat(tip) + parseFloat(tax);
							jQuery("#cart-total-price").html("$" + cartTotalPrice.toFixed(2));
							
							break;
						case "pickup":
							var tax = (cartSubTotal * (cartTax / 100)).toFixed(2);
							jQuery("#cart-subtotal-tax").html("$" + tax);
							
							var cartTotalPrice = parseFloat(cartSubTotal) + parseFloat(tax) + parseFloat(tip);
							jQuery("#cart-total-price").html("$" + cartTotalPrice.toFixed(2));
							
							break;
					}
				};
				
				setup(method);
				
				break;
			case "menu":
				var setup = function(method) {
					switch(method) {
					//sobol
						case "delivery":
							var tax = ((cartSubTotal * (cartTax / 100)) + (cartChargeDelivery * (cartTax / 100))).toFixed(2);
							jQuery("#cart-subtotal-tax").html("$" + tax.toCurrency());
							
							var cartTotalPrice = parseFloat(cartSubTotal) + parseFloat(cartChargeDelivery) + parseFloat(tax);
							jQuery("#cart-total-price").html("$" + cartTotalPrice.toFixed(2));
							
							jQuery("#finish-order-form #delivery-control-date-label").html("Delivery date");
							jQuery("#finish-order-form #delivery-control-time-label").html("Delivery time");
							break;
						case "pickup":
							var tax = (cartSubTotal * (cartTax / 100)).toFixed(2);
							jQuery("#cart-subtotal-tax").html("$" + tax.toCurrency());
							
							var cartTotalPrice = parseFloat(cartSubTotal) + parseFloat(tax);
							jQuery("#cart-total-price").html("$" + cartTotalPrice.toFixed(2));
							
							jQuery("#finish-order-form #delivery-control-date-label").html("Pickup date");
							jQuery("#finish-order-form #delivery-control-time-label").html("Pickup time");
							break;
					}
				};
				var method = jQuery("input:radio[name='deliveryCharge']:checked").val();
				setup(method);
				jQuery("input:radio[name='deliveryCharge']").unbind().change(function() {
					setup(jQuery(this).val());
				});
				
				break;
		}
	};
	/** **/

	var initTip = function () {
		var cartSubtotal = jQuery("#cart-subtotal-price").val();

		var userTip = jQuery("input:radio[name='user[tip]']:checked").val();
		
		var calcTip = function(tip) {
			var tipAmount = 0;
			if(tip == 0 || !tip || typeof(tip) == "undefined") {
				tipAmount = 0;
			} else {
				tipAmount = tip;
			}
			var tipInCurrency = 0;
			if(typeof(cartSubtotal) != "undefined") {
				tipInCurrency = (cartSubtotal * (tipAmount / 100));
			}

			jQuery("#cart-tip-amount").val(tipInCurrency.toFixed(2));
			
			reCalcTotalPrice();

			var id = jQuery("input:radio[name='user[tip]']:checked").attr("id");
			jQuery(".in-ut").removeClass("active");
			jQuery("label[for='" + id +"']").addClass("active");
		};
		calcTip(userTip);
		
		jQuery(".cart-user-tip").change(function() {
			id = jQuery(this).attr("id");
			jQuery(".in-ut").removeClass("active");
			jQuery("label[for='" + id +"']").addClass("active");
			
			calcTip(jQuery(this).val());
		});
	};
	initTip();
	
	var initButtonDetails = function() {
		jQuery("a.show-details").click(function() {
			var buttonId = jQuery(this).attr("id");
			var paramsId = buttonId.replace("show-details-", "params-");
			if(jQuery("#" + paramsId).is(":visible")){
				jQuery("#" + paramsId).hide();
				jQuery("#" + buttonId).html("Show Details");
			} else {
				jQuery("#" + paramsId).show();
				jQuery("#" + buttonId).html("Hide Details");
			}
		});
	};
	initButtonDetails();
};

jQuery(document).ready(function() {
	initEnviroment();
	initPayment();
	initForms();
	initOrderForm();
});
