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


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

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


function servicePost() {
	error = '';

	if ($('#questionType').val() == '') {
		error += '<p class="error">Please select a department.</p>';
	}
	if ($('#name').val() == '') {
		error += '<p class="error">Please enter your name.</p>';
	}
	if ($('#email').val() == '') {
		error += '<p class="error">Please enter an email address.</p>';
	}
	if ($('#email').val() != $('#confirmemail').val()) {
		error += '<p class="error">Your email address and confirm address do not match. Please try again.</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 + 'service/ajaxservice/';
		$('#resultContainer').load(url, {
			questionType: $('#questionType').val(),
			name: $('#name').val(),
			email: $('#email').val(),
			phone: $('#phone').val(),
			fax: $('#fax').val(),
			company: $('#company').val(),
			address: $('#address').val(),
			city: $('#city').val(),
			state: $('#state').val(),
			zipcode: $('#zipcode').val(),
			country: $('#country').val(),
			comments: $('#comments').val(),
			mailinglist: myval
		});
	} else {
		$('#errorContainer').html(error);
	}
}


// Load A Page W/ Ajax
function getPage(url, pars, div, thisMethod) {
	if (!thisMethod) thisMethod = 'get';
	var myAjax = new Ajax.Updater( div , url, { method: thisMethod, parameters: 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 = '';

		}

}

function updateCartQty() {
	var pars = generatePostString('cartForm');
	var myAjax = new Ajax.Updater('cartContainer', AJAXdomain + "collection/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_zip').val().length < 5) {
				error += '<li>Please enter a valid zip code.</li>';
			}
			if ($('#f_phone').val() == '') {
				error += '<li>Please enter a phone number.</li>';
			}
			if ($('#f_country').val() == '') {
				error += '<li>Please select a country.</li>';
			}
		}

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

		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 (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 code 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';
}


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;
}


function switchFeatureContent(element, featureNum) {
	if (element.hasClassName("detail")) {
		element.innerHTML = $$("dt:nth-of-type(" + featureNum + ")").first().innerHTML;
		element.removeClassName("detail");
	}
	else {
		element.innerHTML = $$("dd:nth-of-type(" + featureNum + ")").first().innerHTML;
		element.addClassName("detail");
	}
}

function featureHover(element, state) {
	if (state == "over") {
		Element.extend(element).addClassName("hover");
	}
	else {
		Element.extend(element).removeClassName("hover");
	}
}

var overlayRules = {
	'#featureimage' : function(element) {
		$$("map area").each(function(s) {
			coords = s.readAttribute("coords").split(",");
			new Insertion.Bottom($("features"), "<div class=\"arrow-wrap\" onmouseover=\"featureHover(this, 'over');\" onmouseout=\"featureHover(this, 'out');\"><div class=\"feature-arrow\" style=\"left: " + coords[0] + "px; bottom: " + coords[1] + "px;\"></div><div class=\"feature\" onmouseover=\"featureHover(this, 'over');\" onmouseout=\"featureHover(this, 'out');\" onclick=\"switchFeatureContent(this, " + s.readAttribute("id").replace(/feature/,"") + ");\" style=\"left: " + (parseInt(coords[0]) + 7) + "px; bottom: " + (parseInt(coords[1]) + 7) + "px;\">" + $$("dt:nth-of-type(" + s.readAttribute("id").replace(/feature/,"") + ")").first().innerHTML + "</div></div>");
			s.remove();
		});
	},

};
