//////////////
// Settings //
//////////////

var AJAXdomain = window.location.protocol + '//' + window.location.hostname + '/';
var AJAXSSLDOMAIN = window.location.protocol + '//' + location.hostname + '/';

var thisElement = '';
var errClr = "textError";
var error = '';

// Added by scotty to set the session variables for view mode when shopping.
//  Requires the below php pages since JavaScript cannot directly affect Session Vars.
function ChangeViewMode(v)
{
		// Generate Post Request
		$.post("/include/sbx/shop/set_view_mode.ajax.php", { 
				view: v
			}, 
			function(){
				window.location="";
			});
}

function CheckDiscountCode(code)
{
	if (code.length > 0)
	{
		$('#code_error').load("/include/sbx/checkout/check_discount_code.ajax.php", {discount_code: code});
	}
}		
		
function helpPost() {
	error = '';

	if ($('#questionType').val() == '') {
		error += '<p class="error">Please select a department.</p>';
	}
	if ($('#first_name').val() == '') {
		error += '<p class="error">Please enter your first name.</p>';
	}
	if ($('#last_name').val() == '') {
		error += '<p class="error">Please enter your last name.</p>';
	}
	if ($('#email').val() == '') {
		error += '<p class="error">Please enter an email address.</p>';
	}
	if ( !verifyEmailFormat($('#email').val())) {
		error += '<p class="error">Your email address is not in a valid format. Please enter a proper email address.</p>';
	}


	if (error == '') {
		$('#errorContainer').html("");

		var myval = 0;
		if ($('#f_mailinglist:checked').length == 1)
		{
			myval = 1;
		}

		var url = AJAXdomain + 'help/ajaxhelp/';
		$('#resultContainer').load(url, {
			questionType: $('#questionType').val(),
			first_name: $('#first_name').val(),
			last_name: $('#last_name').val(),
			email: $('#email').val(),
			ordernumber: $('#ordernumber').val(),
			phone: $('#phone').val(),
			comments: $('#comments').val(),
			mailinglist: myval
		});
	} else {
		$('#errorContainer').html(error);
		scroll(0,0);
	}
}

function submitRMA() {
	error = '';

	if ($('#fname').val() == '') {
		error += '<p class="error">Please enter your first name.</p>';
	}
	if ($('#lname').val() == '') {
		error += '<p class="error">Please enter your last name.</p>';
	}
	if ($('#address1').val() == '') {
		error += '<p class="error">Please enter your address.</p>';
	}
	if ($('#city').val() == '') {
		error += '<p class="error">Please enter your city.</p>';
	}
	if ($('#state').val() == '') {
		error += '<p class="error">Please select your state.</p>';
	}
	if ($('#zip').val() == '') {
		error += '<p class="error">Please enter your zip/postal code.</p>';
	}
	if ($('#country').val() == '') {
		error += '<p class="error">Please select your country.</p>';
	}
	if ($('#phone').val() == '') {
		error += '<p class="error">Please enter your phone number.</p>';
	}
	if ($('#email').val() == '') {
		error += '<p class="error">Please enter an email address.</p>';
	}
	if ( !verifyEmailFormat($('#email').val())) {
		error += '<p class=\"alert\">Your email address is not in a valid format. Please enter a proper email address.</p>';
	}
	if ($('#invoiceNum').val() == '') {
		error += '<p class="error">Please enter your order number.</p>';
	}
	if ($('#prodReturn').val() == '') {
		error += '<p class="error">Please enter a product to return.</p>';
	}
	if ($('#reason').val() == '') {
		error += '<p class="error">Please select a reason.</p>';
	}
	// This works too: if ($('#terms').attr('checked') == '') {
	if (!$('#terms').attr('checked')) {
		error += '<p class="error">You must agree to our terms.</p>';
	}

	if (error == '') {
		$('#errorContainer').html("");

		var url = AJAXdomain + 'help/ajax-ra/';
		$('#resultContainer').load(url, {
			fname: $('#fname').val(),
			lname: $('#lname').val(),
			address1: $('#address1').val(),
			address2: $('#address2').val(),
			city: $('#city').val(),
			state: $('#state').val(),
			zip: $('#zip').val(),
			email: $('#email').val(),
			phone: $('#phone').val(),
			invoiceNum: $('#invoiceNum').val(),
			prodReturn: $('#prodReturn').val(),
			reason: $('#reason').val(),		
			reasonOther: $('#reasonOther').val()
		});
	} else {
		$('#errorContainer').html(error);
	}
}


// Load A Page W/ Ajax
function getPage(url, pars, div) {
	  	$('#'+div).load(url+"?"+pars);
}

// Check Username
function verifyUsername(returnFunc) {

	if (returnFunc == "checkout") {
		var myAjax = new Ajax.Request( AJAXdomain + "register/verify/", { method: 'post', parameters: "returnNumeric=1&checkUser=" + $F('f_username'), onComplete: verifyEmail });
	} else {
		var myAjax = new Ajax.Updater( 'checkContainer' , AJAXdomain + "register/verify/", { method: 'post', parameters: "checkUser=" + $F('f_username') });
	}
}
function verifyEmail(v) {

	if (v.responseText == 0 && $F('f_username') != '') {
		error = "<li>Your username is taken. Please try another.</li>";
	}

	var myAjax = new Ajax.Request( AJAXdomain + "register/verify/", { method: 'post', parameters: "returnNumeric=1&checkEmail=" + $F('f_email'), onComplete: verifyUsernameCheckout });
}

function verifyUsernameCheckout(v) {


	if (v.responseText == 0 && $F('f_email') != '') {
		error = "<li>Your email address is already in use. Please try another or use <a href=\"/account/password-recover/\">recover password</a> link.</li>";
	}

		checkField('f_username', '', '<li>Please enter a username.</li>');
		checkField('f_email', '', '<li>Please enter your email address.</li>');
	if ( !verifyEmailFormat($F('f_email'))) {
		error += '<p>Your email address is not in a valid format. Please enter a proper email address.</p>';
		highlightErrorField('f_email');
	}

		checkField('f_password', '', '<li>Please enter a password.</li>');
		if ($F('f_password') != $F('f_verify')) {
			error += '<li>Your passwords do not match.</li>';
			highlightErrorField('f_password');
			highlightErrorField('f_verify');
		} else {
			deHighlightErrorField('f_password');
			deHighlightErrorField('f_verify');
		}

		if (error == '') {
			$('fm-checkout').submit();
		} else {
			error = "<ul class=\"error\">" + error + "</ul>";
			$('errorContainer').innerHTML = error;
			new Effect.Highlight('errorContainer');
			error = '';

		}

}

//   Depricated from use.  10/06/2008  -SP
//function updateCartQty() {
//	var pars = generatePostString('cartForm');
//	var myAjax = new Ajax.Updater('cartContainer', AJAXdomain + "shop/cart-ajax/", { method: 'post', parameters: pars, onComplete: function(request) { new Effect.Highlight('cartContainer',{}); } });
//}

function storeCheckOutStep(step, errorcheck) {

	// Run Error Check
	if (errorcheck) {

		error = "";

		// Regular Shipping
		if (step == 'shippingForm' || step == 'billingForm') {
			if ($('#f_fname').val() == '') {
				error += '<li>Please enter your first name.</li>';
			}
			if ($('#f_lname').val() == '') {
				error += '<li>Please enter your last name.</li>';
			}
			if ($('#f_address1').val() == '') {
				error += '<li>Please enter an address.</li>';
			}
			if ($('#f_city').val() == '') {
				error += '<li>Please enter a city.</li>';
			}
			if ($('#f_state').val() == '') {
				error += '<li>Please select a state.</li>';
			}
			if ($('#f_phone').val() == '') {
				error += '<li>Please enter a phone number.</li>';
			}
			if ($('#f_country').val() == '') {
				error += '<li>Please select a country.</li>';
			}
			else if ($('#f_country').val() == 'US' 
					&& $('#f_zip').val().length < 5) 
			{
				error += '<li>Please enter a valid zip code.</li>';
			}
			else if ($('#f_country').val() != 'US' 
					&& $('#f_country').val() != '' 
					&& $('#f_zip').val().length < 4) 
			{
				error += '<li>Please enter a valid zip code.</li>';
			}
		}

		if (step == 'shippingForm') {
			var address = new String($('#f_address1').val())
			if ( address.toUpperCase().indexOf("PO BOX") != -1 
				|| address.toUpperCase().indexOf("P.O. BOX") != -1
				|| address.toUpperCase().indexOf("APO ") != -1
				|| address.toUpperCase().indexOf("APO-") != -1
				|| address.toUpperCase().indexOf("APO,") != -1) 
			{
				error += "<li>We can not ship to PO Boxes or APO's. Please try another address.</li>";
				highlightErrorField('f_address1');		
			}
		}

		if (step == 'billingForm') {
			
			if ($('#f_email').val() == '') {
				error += '<li>Please enter an email address.</li>';
			}
			if ( !verifyEmailFormat($('#f_email').val())) {
				error += '<p class=\"alert\">Your email address is not in a valid format. Please enter a proper email address.</p>';
			}
			if ($('#f_ccnum').val() == '') {
				error += '<li>Please enter a credit card number.</li>';
			}
			if ($('#f_ccexp_mo').val() == '') {
				error += '<li>Please enter a valid credit card expiration month.</li>';
			}
			if ($('#f_ccexp_yr').val() == '') {
				error += '<li>Please enter a valid credit card expiration year.</li>';
			}
			if ($('#f_cccvv').val() == '') {
				error += '<li>Please enter a credit card security code.</li>';
			}
			if (!$('#terms').attr('checked')) {
				error += '<li>You have to agree to our terms and conditions.</li>';
			}
		}

		//if (step == 'reviewForm') {
		//	if ($('#f_referral').val() == '') {
		//		error += '<li>Please let us know how you heard about FACTORY 413.</li>';
		//	}
		//}

		if (error == '') {
			$('#checkoutForm').submit();
		} else {
			// Write Error To Div
			$('#errorContainer').html("<p class=\"alert\">Please fill out the required fields:</p><ul class=\"error\">" + error + "</ul>");
		}
	}
}



// Error Check Secondary Scripts
function checkField(field, value, errorMessage) {
	if (field == value) {
		error += errorMessage;
		highlightErrorField(field);
	} else deHighlightErrorField(field);

}

//function highlightErrorField(field) {
	//$('#field').attr({class: 'errClr'});
//}
//function deHighlightErrorField(field) {
	//$('#field').attr({class: 'text'});
//}

// Scotty, the old cold used in this file does not work in Safari. The new code above does. Everything seems to work fine with the code below activated.
function highlightErrorField(field) {
	$(field).className = errClr;	
}
function deHighlightErrorField(field) {
	$(field).className = 'text';	
}

// Deprecated.  -SP 10/21/2008
//function generatePostString(form) {
//	var pointer;
//	var postString = '';
//
//	try {
//		// Input Fields
//		var pointer = getElementsByTagNames('input', $(form));
//		for ( var i in pointer ) {
//			if (pointer[i].name != '') {
//				if (pointer[i].type == 'hidden')
//					postString +=  pointer[i].name + '=' + escape(pointer[i].value) + '&';
//				else {
//					if (pointer[i].checked)
//						postString +=  pointer[i].name + '=' + escape(pointer[i].value) + '&';
//				}
//			}
//		}
//	} catch (e) {}
//	try {
//		// Input Fields
//		var pointer = getElementsByTagNames('input', $(form));
//		for ( var i in pointer ) {
//			if (pointer[i].name != '') {
//				if (pointer[i].type == 'text')
//					postString +=  pointer[i].name + '=' + escape(pointer[i].value) + '&';
//				else {
//					if (pointer[i].checked)
//						postString +=  pointer[i].name + '=' + escape(pointer[i].value) + '&';
//				}
//			}
//		}
//	} catch (e) {}
//	try {
//		// Selects
//		var pointer = getElementsByTagNames('select', $(form));
//		for ( var i in pointer ) {
//			if (pointer[i].name != '') {
//				postString +=  pointer[i].name + '=' + escape(pointer[i].value) + '&';
//			}
//		}
//	} catch(e) {}
//	try {
//		// Textareas
//		var pointer = getElementsByTagNames('textarea', $(form));
//		for ( var i in pointer ) {
//			if (pointer[i].name != '') {
//				postString +=  pointer[i].name + '=' + escape(pointer[i].value) + '&';
//			}
//		}
//	} catch (e) {}
//
//	return postString;
//}
//
//function getElementsByTagNames(list,obj)
//{
//	if (!obj) var obj = document;
//	var tagNames = list.split(',');
//	var resultArray = new Array();
//	for (var i=0;i<tagNames.length;i++)
//	{
//		var tags = obj.getElementsByTagName(tagNames[i]);
//		for (var j=0;j<tags.length;j++)
//		{
//			resultArray.push(tags[j]);
//		}
//	}
//	var testNode = resultArray[0];
//	if (testNode.sourceIndex)
//	{
//		resultArray.sort(function (a,b) {
//				return a.sourceIndex - b.sourceIndex;
//		});
//	}
//	else if (testNode.compareDocumentPosition)
//	{
//		resultArray.sort(function (a,b) {
//				return 3 - (a.compareDocumentPosition(b) & 6);
//		});
//	}
//	return resultArray;
//}

function isValidEmail(str) {
  verifyEmailFormat(str);
}

function verifyEmailFormat(str) {
	if (str == '') return true;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str))
		return true;
	else
		return false;
}

/********** RETAIL FUNCTIONS **********/
/*
	function ToggleForm(tmp)
	{
		if (tmp == 'walkin')
		{
			$('.phone').hide();
			$('.promo').hide();
		}
		else if (tmp == 'phone')
		{
			$('.walkin').hide();
			$('.cash').hide();
			$('.cc').show();
			$('#pay_type').val("cc");
			$('.promo').hide();
		}
		else if (tmp == 'promo')
		{
			$('.phone').hide();
			$('.walkin').hide();
			$('#pay_type').val("promo");
		}
		$('.'+tmp).show();
		$('#sale_type').val(tmp);
	}
*/

	function TogglePayForm(tmp)
	{
		if (tmp == 'cash')
		{
			$('.cc').hide();
		}
		else if (tmp == 'cc')
		{
			$('.cash').hide();
		}
		$('.'+tmp).show();
		$('#pay_type').val(tmp);
	}
	
	function PushShipping()
	{
		$('*[id^=s_]').each(
			function (x)
			{
				$('#'+this.name.substring(2)).val(this.value);
			}
		);
	}
	
	function RecalcTax()
	{
		// Generate Post Request
		$('#tax_holder').load("/include/sbx/retail/AJAX_actions.php", { 
				state: $('#s_state').val(), 
				zip: $('#s_zip').val(),
				sale_type: $('#sale_type').val(),
				action: "calc_tax"
			}, function() {
				$('.grand_total_holder').load("/include/sbx/retail/AJAX_actions.php", { 
						action: "calc_total"
					});
			});
	}
	
	function PullShipOptions()
	{
		$('#shipping_options').load("/include/sbx/retail/AJAX_actions.php", { 
						action: "shipping_list"
					});
	}
	
	function CalcShipping()
	{
		// Generate Post Request
		$('#ship_price').load("/include/sbx/retail/AJAX_actions.php", { 
				shipvia: $('#t_shipvia').val(), 
				sale_type: $('#sale_type').val(),
				action: "calc_shipping"
			}, function() {
				$('.grand_total_holder').load("/include/sbx/retail/AJAX_actions.php", { 
						action: "calc_total"
					});
			});
	}

	function CalcDiscount()
	{
		// Generate Post Request
		$('#discount_price').load("/include/sbx/retail/AJAX_actions.php", { 
				discountCode: $('#t_discountCode').val(), 
				action: "calc_discount"
			}, function() {
				$('.grand_total_holder').load("/include/sbx/retail/AJAX_actions.php", { 
						action: "calc_total"
					});
			});
	}
	
	function CalcChange()
	{
		var myNum=new Number($('#p_amt_collected').val() - $('#calc_grand_total').html().substr(1)).toFixed(2); 
		$('#change').html('$ ' + myNum);
	}


	function ClearCustomer()
	{
		var addtoreplace = "";
		if($('#sale_type').val() !== undefined)
		{
			addtoreplace = $('#sale_type').val();
		}

		// Generate Post Request
		$.post("/include/sbx/retail/AJAX_actions.php", { 
				action: "clear_user"
			}, function() {
				window.location.replace("/retail/"+addtoreplace);
			});
	}


	function LookupEmail()
	{
		var ret = 0;
		var email = $('#email').val().trim();
		if (email == "")
		{
			return true;
		}
		else
		{
			$.post("/include/sbx/retail/AJAX_actions.php", { 
					action: "lookup_email",
					email: email
				}, function(output) {
					if (output == "create_new_account" || output == "use_currently_selected" || output == "changing_your_email")
					{
						$('#checkout').removeAttr('onsubmit').submit();
					}
					else if (output == "found_your_account" || output == "someone_elses_email")
					{
						tb_show("EMAIL ALREADY IN SYSTEM","/include/sbx/retail/_ajax_email_exceptions.inc.php?height=500&width=600&action="+output);
					}
				});
		}
		return false;
	}
	
	
/********** NEW AND IMPROVED **********/
	function DoSearch(tmp)
	{
		$('#cart-container').load('/include/sbx/retail/_retail_search_results.inc.php', {action: "add", lookup: tmp}, function(){
			$('#lookup').val("");
			$('#lookup').focus();
		});
	}
	
	function LoadForm(frm)
	{
		$('#errMsg').removeClass("alert success").html("");
		$('#form-container').html('<div class="alert">Loading...</div>');
		$('#form-container').load('/include/sbx/retail/_ajax_load_form.inc.php', {form_type: frm});
	}
	
	function LoadCart()
	{
		$('#cart-container').load('/include/sbx/retail/_retail_cart_container.inc.php');
	}

	/* FOUND HERE */
	/* http://ninetynine.be/blog/2009/03/thickbox-reinitialize-thickbox-after-change-by-ajax/ */
	function tb_reinit(domChunk) 
	{
		$(domChunk).unbind("click");
		tb_init(domChunk);
	}
	
	function SessionCache(use_ID)
	{
		$('#'+use_ID).val().trim();
		$.post("/include/sbx/retail/AJAX_actions.php", { 
				action: 'session_cache',
				id: use_ID,
				value: $('#'+use_ID).val()
			}, function(output) {
				$('#'+use_ID).addClass(output);
			});
	}

	function RetailDataCheck()
	{
		$('#errMsg').removeClass('alert success').html("");
		$('.required').removeClass('required');
		
		var res = 1;
		var errmsg = "Please complete all required data.";
		
		$('.req').each(
			function(item) {
				if ($(this).attr('type') == "select")
				{
					if($(this).selectedIndex == 0)
					{
						$(this).addClass('required');
						res = 0;
					}
				}
				else
				{
					if($(this).val().trim() == "")
					{
						$(this).addClass('required');
						res = 0;
					}
				}
			}
		);
		
		if ($('#saveaccount').attr('type') == "checkbox")
		{
			if ($('#saveaccount').attr('checked') == true && $('#email').val().trim() == "")
			{
				$('#email').addClass('required');
				res = 0;
			}
		}
		
		if ($('#email').val().trim() != "")
		{
			if ( !verifyEmailFormat($('#email').val()))
			{
				errmsg += '<br />Your email address is not in a valid format. Please enter a proper email address.';
				$('#email').addClass('required');
				res = 0;
			}
		}


		if (res == 1)
		{
			return LookupEmail();
		}
		else
		{
			$('#errMsg').addClass('alert').html(errmsg);
			return false;
		}
	}
	
	function FinishProcess(tmp) 
	{
		$('#use_user_ID').val(tmp);
		SessionCache('use_user_ID'); 
		$('#checkout').removeAttr('onsubmit').submit();
		parent.tb_remove();
	}
	
	function RevertEmail(tmp)
	{
		$('#email').val(tmp);
		SessionCache('email'); 
		$('#checkout').removeAttr('onsubmit').submit();
		parent.tb_remove();
	}
	
	
	
