//////////////
// Settings //
//////////////

var AJAXdomain = window.location.protocol + '//' + window.location.hostname + '/';
var AJAXSSLDOMAIN = window.location.protocol + '//' + location.hostname + '/';

var thisElement = '';
var errClr = "textError";
var error = '';

// This function can be used to add / remove default text for any input field.
// For this to work, use the following format on the input field:
// <input type="text" name="myname" id="myid" deftext="mydefault" value="mydefault" onfocus="DefaultText('myid')" onblur="DefaultText('myid')" />
// You can also add an onsubmit="DefaultText('myid')" to the form if you don't want to submit the default text to the form processing.
function DefaultText(id) {

	tmp = $('#'+id).attr('deftext');

	if (jQuery.trim($('#'+id).val()) == '')
	{
		$('#'+id).val(tmp);
	}
	else if (jQuery.trim($('#'+id).val()) == tmp)
	{
		$('#'+id).val('');
	}
}


// setup Share to work as tabs for each div directly under div.share_container
// $(function() {

// $("#share").tabs("#share div.share_container", {tabs: 'p', effect: 'slide', initialIndex: null});
// });

// This is throwing an error every time - disabled to see if it's missed. - SP 
//$(document).ready(function() {
//	$("p[rel]").overlay();
//});


// 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 CreditSearch(tmp)
{
	$('#creditlist').load("/include/sbx/checkout/AJAX_credit_list.inc.php", {credit_code: tmp});
}

function CheckDiscountCode(code)
{
	if (code.length > 0)
	{
		$('#code_error').load("/include/sbx/checkout/check_discount_code.ajax.php", {discount_code: code}, function(){LoadShippingOptions();});
	}
}

function LoadShippingOptions()
{
	$('#shipping_container').load("/include/sbx/checkout/make_shipping_select_ajax.php", {shipping: $('#f_shipvia').val()});
}

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() {
	$('.required').removeClass('required');
	error = 0;
	errormsg = "";

	if ($('#fname').val() == '') {
		error = 1;
		$('#fname').addClass('required');
	}
	if ($('#lname').val() == '') {
		error = 1;
		$('#lname').addClass('required');
	}
	if ($('#address1').val() == '') {
		error = 1;
		$('#address1').addClass('required');
	}
	if ($('#city').val() == '') {
		error = 1;
		$('#city').addClass('required');
	}
	if ($('#state').val() == '') {
		error = 1;
		$('#state').addClass('required');
	}
	if ($('#zip').val() == '') {
		error = 1;
		$('#zip').addClass('required');
	}
	if ($('#country').val() == '') {
		error = 1;
		$('#country').addClass('required');
	}
	if ($('#phone').val() == '') {
		error = 1;
		$('#phone').addClass('required');
	}
	if ($('#email').val() == '') {
		error = 1;
		$('#email').addClass('required');
	}
	if ( !verifyEmailFormat($('#email').val())) {
		errormsg += '<p class=\"error\">Your email address is not in a valid format. Please enter a proper email address.</p>';
		error = 1;
		$('#email').addClass('required');
	}
	if ($('#invoiceNum').val() == '') {
		error = 1;
		$('#invoiceNum').addClass('required');
	}
/*
	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 = 1;
		errormsg += '<p class="error">You must agree to our terms.</p>';
	}

	var myitems = "";
	sep = "";
	//$("select[name*='return_type_']").each(
	$("input[name*='item_ID_']").each(
		function(item) {
			if ($(this).attr('checked'))
			{
				str = $(this).attr('item_ID');
				if(jQuery.trim($("#reason_"+str).val()) == "")
				{
					error = 1;
					$("#reason_"+str).addClass('required');
				}
				if(jQuery.trim($("#qty_"+str).val()) == "" || $("#qty_"+str).val() == "0" || $("#qty_"+str).val() > $("#maxqty_"+str).val())
				{
					error = 1;
					$("#qty_"+str).addClass('required');
					errormsg += '<p class="error">Return quantites must be between 1 and max.</p>';
				}
/*
				if (jQuery.trim($("#exchange_"+str).val()) == "" && $("#return_type_"+str).val() == "Exchange")
				{
					error = 1;
					$("#exchange_"+str).addClass('required');
					errormsg += '<p class="error">For exchanges, what did you want instead?</p>';
				}
*/
				if(jQuery.trim($("#exchange_"+str).val()) == "")
				{
					error = 1;
					$("#exchange_"+str).addClass('required');
				}
				if (error == 0)
				{
					myitems += sep + str + "||Return||" + $("#qty_"+str).val() + "||" + $("#reason_"+str).val() + "||" + $("#exchange_"+str).val();
					sep = "::";
				}
			}
		}
	);
	if (myitems == "")
	{
		error = 1;
		errormsg += '<p class="error">Please check, and fill out each item you wish to return.</p>';
	}


	if (error == 0 && myitems != "") {
		$('#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(),
			country: $('#country').val(),
			phone: $('#phone').val(),
			email: $('#email').val(),
			invoiceNum: $('#invoiceNum').val(),
			items: myitems
		});

	} else {
		$('#errorContainer').html("<p class=\"error\">Please complete all required fields.</p>"+errormsg);
	}
}


// 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) {

		$('.required').removeClass('required');
		$('#apply_error').html('');

	// 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>';
			}

			bad_credit = 0;
			$("input[name*='f_exist_value_']").each(
				function(item)
				{
						if(Math.abs($(this).val()) > Math.abs($(this).attr('max')))
						{
								$('#apply_error').html("The amount to apply for each code cannot exceed its value.");
								$('#f_exist_value_'+$(this).attr('credit_ID')).addClass('required');
								bad_credit = 1;
						}
				}
			)
			if(bad_credit == 1)
			{
				error += '<li>Too much shop credit is being applied.</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).className = errClr;
}
function deHighlightErrorField(field) {
	$(field).className = 'text';
}


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;
}


/********** NEW AND IMPROVED **********/
function PromoSearch(tmp, size)
{
	$('#grid-container').load('/include/sbx/promo/_promo_grid.inc.php', {action: "search", lookup: tmp, size: size}, function(){
		$('#lookup').val("");
		$('#search_size').val("");
		$('#lookup').focus();
	});
}

// Lookbook

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 DataCheck()
	{
		$('#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(jQuery.trim($(this).val()) == "")
					{
						$(this).addClass('required');
						res = 0;
					}
				}
			}
		);

		if (jQuery.trim($('#email').val()) != "")
		{
			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 true;
		}
		else
		{
			$('#errMsg').addClass('alert').html(errmsg);
			return false;
		}
	}

