/******************** Author: Calculated Creativity, IntegraClick, [KRA] ********************/

/******************** VARIABLES ********************/
//editable required variables:
var overIngredientsCount = 0;
var useExitPop=true,projectName="flowingLuxSkinAuraVie";
var exitMessage="*****************************************************\n\nWait!\n\nBefore you leave, please take a look at this limited time offer. Remember, this is an EXCLUSIVE TRIAL OFFER.\n\nWhy miss the chance to erase your wrinkles and look years younger?\n\nClick stay on this page to get your trial order of Auravie Anti-Aging Kit.\n\n*****************************************************";
//do not edit:
var validForm=true,validErr;

/******************** COMMON FUNC ********************/
function fbLike(_address,_theme,_width) {
	"use strict";
	
	if(_theme==0) {
		_theme="light";
	}else {
		_theme="dark";
	}
	if(_width==0) {
		_width="auto";
	}else {
		_width=""+_width+"px";
	}
	$(".fbLike").html('<iframe src="http://www.facebook.com/plugins/like.php?href='+_address+'&amp;colorscheme='+_theme+'" scrolling="no" frameborder="0" style="border:none;width:'+_width+';height:auto;" allowTransparency="true"></iframe>');
}

function geoLoc() {
	/* HTML include: <script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script> */
	//eg. <span class="geoCity"></span>&nbsp;where some text starts here using the "&nbsp;" instead of a space characer " " immediately proceeding the tag because IE has a bug that drops the space after span tags being filled with content from JS
	$('.geoCity').replaceWith(geoip_city());
    $('.geoCityState').replaceWith(geoip_city()+', '+geoip_region());
	$('.geoState').replaceWith(geoip_region_name());
	$('.geoZip').replaceWith(geoip_postal_code());
	$('.geoCountryCode').replaceWith(geoip_country_code());
	$('.geoCountry').replaceWith(geoip_country_name());
}

function setCookie(_name,_value) {
	$.cookie(_name,_value,{expires:10,path:'/'});
}
function setCookie(_name,_value,_time) {
	$.cookie(_name,_value,{expires:_time,path:'/'});
}

function openPopup(linkURL) {
	window.open(linkURL,'popup','width=600,height=600,toolbar=0,location=0,status=0,toolbar=0,scrollbars=1,resizable=1');
}

function popupLinks() {
	if(!document.getElementsByTagName) {return false;}var _popuplinks=document.getElementsByTagName("a");for(var i=0;i<_popuplinks.length;i++) {if(_popuplinks[i].getAttribute("class")=="popup") {_popuplinks[i].onclick=function() {openPopup(this.getAttribute("href"));return false;}}} 
}

//Returns the version of Internet Explorer or a -1 (indicating the use of another browser).
function getInternetExplorerVersion() {
	var rv = -1;if(navigator.appName=='Microsoft Internet Explorer') {var ua=navigator.userAgent;var re=new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");if(re.exec(ua)!=null)rv=parseFloat(RegExp.$1);}return rv;
}

function checkVersion() {
	var ver=getInternetExplorerVersion();
	if(ver>-1) {
		if(ver<8) {
			//do something... usually a js solu to solve an IE browser bug
		}
	}
}

function exitPop() {  
	$('a').bind('click',function() {useExitPop=false;});$('form').submit(function() {useExitPop=false;});window.onbeforeunload=function() {if(useExitPop==true) {return exitMessage;}}
}

/******************** SITE SPECIFIC FUNC ********************/
function carryFormData(_form,_obj) {
	$(document).ready(function() {		
		$(_form).bind('submit',function(e) {
			var cookieName=_obj.replace(".","").replace("#","");
			setCookie(("c"+cookieName+projectName), $(_obj).val(),1);
		});
	});
}

function setFormDataIntoObj(_origObj) {
	var cookieName=_origObj.replace(".","").replace("#","");
	$(".curSet_"+cookieName).html($.cookie("c"+cookieName+projectName));
}

function faceHover(){
    $("#i2,#i1,#i4").hide();
    $('#p1').hover(function(){
        $("#i3").hide();
        $("#containPoints #i1").show();
    },function(){
        $("#containPoints #i1").hide();
    })
    $('#p2').hover(function(){
        $("#i3").hide();
         $("#containPoints #i2").show();
    },function(){
        $("#containPoints #i2").hide();
    })
    $('#p3').hover(function(){
        $("#i3").hide();
         $("#containPoints #i3").show();
    },function(){
        $("#containPoints #i3").hide();
    })
    $('#p4').hover(function(){
        $("#i3").hide();
         $("#containPoints #i4").show();
    },function(){
        $("#containPoints #i4").hide();
    })
}
function overIngredientPoints(_point)
{
	if(_point != 3){
		outIngredientPoints(3);}
	
	overIngredientsCount++;
	$("#containPoints #i" + _point).addClass('i' + _point + 'bg');
}

function outIngredientPoints(_point)
{
	$("#containPoints #i" + _point).removeClass('i' + _point + 'bg');
}

/******************** FORM VALIDATION ********************/

//Form validation for a checkbox. Uses class/id.  
function validCheckbox(_obj,_label) {
	if(!$(_obj).attr('checked')) {
		validForm=false;
		validErr+=('\n'+"*"+_label);
	}
}

//Form validation for required text field. Uses class/id. Precision: field is empty or has content.
function validTxtInput(_obj,_label) {
	if(($(_obj).val()==null) || ($(_obj).val()=="")) {
		validForm=false;
		validErr+=('\n'+"*"+_label);
	}
}

//Form validation for Email field. Uses class/id. Precision: properly written email address.
function validTxtEmail(_obj) {
	if(($(_obj).val()==null) || ($(_obj).val()=="") || ($(_obj).val()=="e.g. abc@test.co")) {
		validForm=false;
		validErr+=('\n'+"*Email");
	}else {
		var _obj=$(_obj).val();
		var atpos=_obj.indexOf("@");
		var dotpos=_obj.lastIndexOf(".");
		if(atpos<1 || dotpos<atpos+2 || dotpos+2>=_obj.length) {
		  	validForm=false;
			validErr+=('\n'+"*Not a valid email address");}
	}
}

//Form validation for Phone field. Uses class/id. Precision: must be 10 digit number
function validTxtPhone(_obj) {
	if(($(_obj).val()==null) || ($(_obj).val()=="") || ($(_obj).val()=="Enter 10 digit #")) {
		validForm=false;
		validErr+=('\n'+"*Phone");
	}else {
		_obj=$(_obj).val();
		_obj=(_obj.replace(/[^\d.]/g, ""));
		if(_obj.length!=10) {
			validForm=false;
			validErr+=('\n'+"*Not a valid Phone Number");
		}
	}
}

//Form validation for Card Number field. Uses class/id. Precision: must be valid credit card number 12-19 digits in length
function validTxtCardNumber(_obj) {
	if(($(_obj).val()==null)||($(_obj).val()=="")) {
		validForm=false;
		validErr+=('\n'+"*Card Number");
	}else {
		_obj=$(_obj).val();
		_obj=(_obj.replace(/[^\d.]/g, ""));
		if((_obj.length!=12)&&(_obj.length!=13)&&(_obj.length!=14)&&(_obj.length!=15)&&(_obj.length!=16)&&(_obj.length!=17)&&(_obj.length!=18)&&(_obj.length!=19)) {
			validForm=false;
			validErr+=('\n'+"*Not a valid Card Number");
		}
	}
}

//Form validation for Card Security Code field. Uses class/id. Precision: must be valid credit card security code 3 or 4 digits in length
function validTxtSecurityCode(_obj) {
	if(($(_obj).val()==null)||($(_obj).val()=="")) {
		validForm=false;
		validErr+=('\n'+"*Security Code");
	}else {
		_obj=$(_obj).val();
		_obj=(_obj.replace(/[^\d.]/g, ""));
		if((_obj.length!=3)&&(_obj.length!=4)) {
			validForm=false;
			validErr+=('\n'+"*Not a valid Security Code");
		}
	}
}

//Form validation for Zip field, United States & Canada only.  Uses class/id. Precision: must be valid zip code structure 5 or 9 digits, or 6 characters in length.
function validTxtZipUSnCA(_obj) {
	if(($(_obj).val()==null)||($(_obj).val()=="")) {
		validForm=false;
		validErr+=('\n'+"*Zip Code");
	}else {
		_obj=$(_obj).val();
		_obj=(_obj.replace(/[^\w.]|[dfioqu]/g, ""));
		if((_obj.length!=5)/*&&(_obj.length!=6)&&(_obj.length!=9)*/) {
			validForm=false;
			validErr+=('\n'+"*Not a valid Zip Code");
		}else {
			if((_obj.length==5)||(_obj.length==9)) { 
				_obj=(_obj.replace(/[^\d.]/g, ""));
				if((_obj.length!=5)&&(_obj.length!=9)) {
					validForm=false;
					validErr+=('\n'+"*Not a valid US Zip Code");
				}
			}/*else { 
				if(_obj.search(/^\s*[a-ceghj-npr-tvxy]\d[a-ceghj-npr-tv-z](\s)?\d[a-ceghj-npr-tv-z]\d\s*$/i)==-1) {
					validForm=false;
					validErr+=('\n'+"*Not a valid Canadian Zip Code");
				}
				
			}*/
		}
	}
}

/*//Form validation for Zip field, United States only.  Uses class/id. Precision: must be valid zip code structure 5 or 9 digits in length.
function validTxtZipUS(_obj) {
	if(($(_obj).val()==null)||($(_obj).val()=="")) {
		validForm=false;
		validErr+=('\n'+"*Zip Code");
	}else {
		_obj=$(_obj).val();
		_obj=(_obj.replace(/[^\d.]/g, ""));
		if((_obj.length!=5)&&(_obj.length!=6)&&(_obj.length!=9)) {
			validForm=false;
			validErr+=('\n'+"*Not a valid US Zip Code");
		}
	}
}*/

//Form validation for required select drop downs. Uses class/id. Precision: anything other than default selected.
function validSelInput(_obj,_label) {
	if($(_obj).val()=="-") {
		validForm=false;
		validErr+=('\n'+"*"+_label);
	}
}

//Validate all required form fields.
function validateForm() {
	validErr=("Please fill out form completely before submitting: "+'\n');
	//go thru and validate each element that needs it
	if($("#pgIndex").length) {
		validTxtInput(".txtFirstName","First Name");
		validTxtInput(".txtLastName","Last Name");
		validTxtInput(".txtAddress","Address");
		validTxtInput(".txtCity","City");
		validSelInput(".selState","State");
		validTxtZipUSnCA(".txtZip");
		validTxtEmail(".txtEmail");
		validTxtPhone(".txtPhone");
	}else if($("#pgOrder").length) {	
		//validTxtInput(".txtNameOnCard","Name on Card");
		validTxtCardNumber(".txtCardNumber");
		validSelInput(".selExpMonth","Card Expiration Month");
		validSelInput(".selExpYear","Card Expiration Year");
		//validTxtSecurityCode(".txtSecurityCode");
		//validCheckbox(".ckAgree","You must agree to the terms and conditions");
	}
	return validForm;
}

function setupFormValidation(_form) {
	//initiate visual form validation
	H5F.listen(window,"load",function() {
		H5F.setup($(_form));
	},false);
	
	//custom form submit process
	$(document).ready(function() {		
		$(_form).bind('submit',function(e) {
			if(validateForm()==false) {
				e.preventDefault();	
				
				alert(validErr);
				//reset variables for the next pass thru when user submits form again
				validErr="";
				validForm=true;
			} else {
			
				if($("#pgIndex").length) {
					return cc_submitIndexPageForm();
				}
				
				else if($("#pgOrder").length) {	
					return cc_submitOrderPageForm();
				}
			}
			
		});
		
		if ($("#pgIndex").length) {
			cc_onloadIndexPageForm();
		
		} else if($("#pgOrder").length) {	
			cc_onloadOrderPageForm();
		}
	});
}

/******************** START POINT: initiate functions ********************/
$(function () {
	"use strict";
	
	if ($("#pgIndex").length) {
		setupFormValidation(".formIndex");
		carryFormData(".formIndex",".txtFirstName");
		
	} else if($("#pgOrder").length) {	
		setupFormValidation(".formOrder");
		setFormDataIntoObj(".txtFirstName");
	}
	
	// Added by CC 
	$('form:not(.filter) :input:visible:first').focus();
	
	// Added by CC
	// exit popup on index 
	exitPop();
	
	popupLinks();
	faceHover();
	if(overIngredientsCount == 0){
		overIngredientPoints(3);
	}	
});


// index page 
function cc_submitIndexPageForm() {
	return true;
}

// order page
function cc_submitOrderPageForm() {
	$("#cc_expires").val($("#fields_expmonth").val() + $("#fields_expyear").val());

		var validData = handleOrderFormSubmit();
//alert('expiry : ' + $("#cc_expires").val() + ' validate : ' + validData + ' overlay : ' + $("#overlay_enable").val());
		if (validData == true) {
			if ($("#overlay_enable").val() == 'y') {
				sendAjaxRequest();
				return false;
			}
			return true;
		}
		return false;
}

function cc_onloadIndexPageForm() {
	$('form:not(.filter) :input:visible:first').focus();
}

function cc_onloadOrderPageForm() {
	$('form:not(.filter) :input:visible:first').focus();
	
	$("#fields_expmonth, #fields_expyear").change(function() {
		$("#cc_expires").val($("#fields_expmonth").val() + $("#fields_expyear").val());
	});


	$("#radioOne").click(function() {
		$("#address_billing").hide();
	});

	$("#radioTwo").click(function() {
		$("#address_billing").show();
	});

	$('#shippingcoupon').keypress(function(e) {
		$("#shippingcoupondiscount").val('n');
		if (e.which == 13) {
			shippingCouponApply();
			return false;
		}
	});

	$('#shippingcouponapply').click(function() {
		shippingCouponApply();
	});

	shippingCouponApply();
}



/* =============  Order Page JS ============================================== */

function shippingCouponApply() {
	if ($('#shippingcoupon').val().length > 2) {
		//alert('Coupon discount applied!!');
		$("#shippingcoupondiscount").val('y');
		$("#shippingcoupongroup").hide();
		$("#div_shippingcouponapplied").show();
		$("#txtShipping").css('color', '#008800');
	} else {
		$("#shippingcoupondiscount").val('n');
		$("#shippingcoupongroup").show();
		$("#div_shippingcouponapplied").hide();
		$("#txtShipping").css('color', '#999');
	}
	calculateProductCost();
}


function calculateProductCost() {

	if ($("#shippingcoupondiscount").val() == 'y') {
		for (var i = 0; i < arySplitProduct.length; i++) {
			if (arySplitProduct[i].coupon == 'y') {
				$("#split_product_id").val(arySplitProduct[i].product_id);
				$("#split_product_price").val(arySplitProduct[i].product_price);
				$("#split_shipping_id").val(arySplitProduct[i].shipping_id);
				$("#split_shipping_initial_price").val(arySplitProduct[i].shipping_initial_price);
				break;
			}
		}
	} else {
		for (var i = 0; i < arySplitProduct.length; i++) {
			if (arySplitProduct[i].coupon == 'n') {
				$("#split_product_id").val(arySplitProduct[i].product_id);
				$("#split_product_price").val(arySplitProduct[i].product_price);
				$("#split_shipping_id").val(arySplitProduct[i].shipping_id);
				$("#split_shipping_initial_price").val(arySplitProduct[i].shipping_initial_price);

				break;
			}
		}
	}

	var product_price = parseFloat($("#product_price").val());
	var split_product_price = parseFloat($("#split_product_price").val());
	var split_shipping_initial_price = parseFloat($("#split_shipping_initial_price").val());
	
	var total = (product_price + split_product_price + split_shipping_initial_price);

	$("#txtShippingAmt").html(total);
	$("#txtTotalAmt").html(total);
	
}

var aryShipping = Array();
var indShipping = 0;

function createShippingObject(id, name, description, recurring_price, initial_price) {
	var shippingType = new Object;
	shippingType.id = id;
	shippingType.name = name;
	shippingType.description = description;
	shippingType.recurring_price = recurring_price;
	shippingType.initial_price = initial_price;
	return shippingType;
}

function setShippingObject(id, name, description, recurring_price, initial_price) {
	aryShipping[indShipping++] = createShippingObject(id, name, description, recurring_price, initial_price);
}


var arySplitProduct = Array();
var indSplitProduct = 0;

function createSplitProductObject(shipping_id, shipping_name, shipping_recurring_price, shipping_initial_price, coupon, product_id, product_name, product_description, product_sku, product_price, product_category_name, product_is_trial, product_is_shippable, product_rebill_product, product_rebill_days) {
	var objType = new Object;

	objType.shipping_id = shipping_id;
	objType.shipping_name = shipping_name;
	objType.shipping_recurring_price = shipping_recurring_price;
	objType.shipping_initial_price = shipping_initial_price;

	objType.coupon = coupon;

	objType.product_id = product_id;
	objType.product_name = product_name;
	objType.product_description = product_description;
	objType.product_sku = product_sku;

	objType.product_price = product_price;
	objType.product_category_name = product_category_name;

	objType.product_is_trial = product_is_trial;
	objType.product_category_name = product_category_name;

	objType.product_is_shippable = product_is_shippable;
	objType.product_category_name = product_rebill_product;
	objType.product_rebill_days = product_rebill_days;

	return objType;
}


function setSplitProductObject(shipping, coupon, product_id, product_name, product_description, product_sku, product_price, product_category_name, product_is_trial, product_is_shippable, product_rebill_product, product_rebill_days) {
	arySplitProduct[indSplitProduct++] = createSplitProductObject(shipping, coupon, product_id, product_name, product_description, product_sku, product_price, product_category_name, product_is_trial, product_is_shippable, product_rebill_product, product_rebill_days);
}


function handleOrderFormSubmit() {

	var address = $("#billing_street_address").val();
	var addresspobox = address.toLowerCase();
	var city = $("#billing_city").val();
	var state = $("#billing_state").val();
	var zip = $("#billing_postcode").val();

	var cc_number = $("#cc_number").val();
	var ccexp = $("#cc_expires").val();
	var cc_cvv = $("#cc_cvv").val();

	var error = Array();
	var err = "";

	var radio2Obj = document.getElementById('radioTwo');

	if (radio2Obj.checked) {
		if (address.length < 4) {
			err += "- Please enter a valid address \r\n";
		}
		if (addresspobox.match('po box') || addresspobox.match('p.o. box') || addresspobox.match('pobox')) {
			err += "- We do not ship to P.O. Boxes \r\n";
		}
		if (city.length < 4) {
			err += "- Please enter a valid city \r\n";
		}
		if (state.length != 2) {
			err += "- Please select a valid state \r\n";
		}
		if (zip.length != 5 || isNaN(zip)) {
			err += "- Please enter a valid zip code \r\n";
		}
	}

	if (cc_number.length < 13 || isNaN(cc_number)) {
		err += "- Please enter a valid card \r\n";
	}
	if (ccexp.length != 4 || isNaN(ccexp)) {
		err += "- Please select a valid card expiration date \r\n";
	}
	if (cc_cvv.length < 3 || isNaN(cc_cvv)) {
		err += "- Please enter a valid card cvv \r\n";
	}


	/*if($('#agree:checked').val() == null) {
	 err += "- Please Agree to Terms and Conditions \r\n";
	 }*/

	if (err.length > 1) {
		alert("Please fix the following errors: \r\n" + err);
		formSubmit = true;
		return false;
	} else {
		formSubmit = true;
		return true;
	}
}

function isValidEmail(str) {
	//return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
	return emailPattern.test(str);
}


function blockUI() {
	$.blockUI({
		css: {
			//backgroundColor: '#fff',
			color: '#fff',
			border: '0px solid #000',
			height: '350px',
			width: '410px',
			border: '0px solid #fff',
			background: 'transparent',
			top:		'8%'
		},
		message : $("#progressMsg").html()
	});
}


function pageUnload() {
	if (formSubmit != true)
		return 'Are you sure you want to leave?';
}
//window.onbeforeunload = pageUnload;


function sendAjaxRequest() {
	blockUI();
	$.ajax({
		type: 'POST',
		url: 'order.php',
		dataType: 'json',
		data: $("#opt_in_form_order").serialize(),
		success: function(data, textStatus, xhr) {
			if (data.state == true && data.filename != '') {
				$.unblockUI();
				var sidstr = '';
				if ($("#div_sidTrack").html() != "")
				{
					sidstr = '&CID='+$("#div_sidTrack").html();
				}
				sidstr = '';
				window.location = "http://"+window.location.hostname+'/thanks.php?data=' + data.filename + sidstr;
			} else {
				$.unblockUI();
				if (data.msg) {
					alert("\r\n\r\nThere has been an error while processing your order through our system. \r\nWe recommend you retry processing your order and \r\nif you should receive the same error message again, \r\nplease contact our customer service department \r\nat (866) 216-9336 for assistance.\r\n\r\n\Error is: " + data.msg + "\r\n");
				} else {
					alert('Please recheck entered values');
				}
				//window.location = 'index.php';
			}

		},
		error:function (xhr, ajaxOptions, thrownError) {
			alert(" Please try again");
		}

	});
}
