//=============================================================================================================
//============ Set IE / FF ====================================================================================
var IE;
if(window.innerHeight) {
	IE = false;
}else{
	IE = true;	
}
// Just a quick test
//=============================================================================================================
//============ Get Window Dimensions ==========================================================================
var height;
var width;
function getWidth() {
	if(IE) {
		width = document.body.clientWidth;
	}else{
		width = window.innerWidth;
	}
}

function getHeight() {
	if(IE) {
		height = document.body.clientHeight;
	}else{
		height = window.innerHeight;
	}
}

//=============================================================================================================
//============ Login ==========================================================================================
function fieldFoBlo (ID, VALUE, EX) {
	var obj = document.getElementById(ID);
	if (VALUE == EX) {
		obj.value = '';	
	}
	if (VALUE == '') {
		obj.value = EX;	
	}
}

function subLogin() {
	ua = document.getElementById('login_username').value;
	ub = document.getElementById('login_password').value;
	ajaxFunc('proc_Login');
}

function finishLogin(RSP) {
	if(RSP == 'error') {
		alert('Invalid Username/Password Combination!');
	}else{
		document.getElementById('login_block').style.display = 'none';
		document.getElementById('loggedin_block').style.display = 'block';
		document.getElementById('loginWelcomeName').innerHTML = 'Welcome ' + RSP;
	}
}

function subLogout() {
	ua = 0;
	ub = 0;
	ajaxFunc('proc_Logout');
}

function finishLogout() {
	window.location = HPath;	
}
//=============================================================================================================
//============ AJAX Function ==================================================================================
var xmlHttp;
var ua;
var ub;
var AP;
var bf_waitLoader = false;

function ajaxFunc(A) {
	if ((A != 'proc_DuplicateEmail') && (A != 'proc_T4Var')) {
		beginWaitLoader();
		bf_waitLoader = true;
	}
	AP = A;
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert("Your browser does not support AJAX!");
		return;
	}
	//Create the post string
	var url = HPath + "ajax/";
	url += A + '.php';
	var params = 'ua='+ua+'&ub='+ub;

	xmlHttp.onreadystatechange=stateChanged;
	xmlHttp.open("POST", url, true);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(params);
}

function stateChanged() {
	if (xmlHttp.readyState == 4) {
		// Get the response text
			var RSP = xmlHttp.responseText;
		//If the waitLoader was opened, close it
		if (bf_waitLoader) {
			bf_waitLoader = false;
			if(t_waitLoader) {
				cancelWaitTimer();
			}
			if(document.getElementById('pageShroud').style.display == 'block') {
				pageShroud();
			}
		}
		// Route the response to the correct function
		fRouter(RSP);
	}
}

function GetXmlHttpObject() {
	var xmlHttp = null;
	try {
		//Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch (e) {
		// IE
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");	
		}
		catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");	
		}
	}
	return xmlHttp;
}
//=============================================================================================================
//============ AJAX Router ====================================================================================
function fRouter(RSP) {
	if(AP == 'getDistributors') {
		showDistributors(RSP);	
	}
	if(AP == 'proc_Contact') {
		showContactResult(RSP);	
	}
	if(AP == 'register') {
		showRegister(RSP);	
	}
	if(AP == 'proc_DuplicateEmail') {
		reg_showDupEmail(RSP);	
	}
	if(AP == 'proc_Register') {
		registrationComplete(RSP);	
	}
	if(AP == 'forgotPW') {
		showAJ(RSP);	
	}
	if(AP == 'proc_ForgotPW') {
		finishForgotPW(RSP);	
	}
	if(AP == 'proc_Login') {
		finishLogin(RSP);	
	}
	if(AP == 'proc_Logout') {
		finishLogout();	
	}
	if(AP == 'proc_Invoice') {
		showInvoice(RSP);	
	}
	if(AP == 'proc_PrintableInvoice') {
		displayPrintableInvoice(RSP);	
	}
	if(AP == 'updateRegister') {
		showAJ(RSP);	
	}
	if(AP == 'proc_UpdateRegister') {
		finishUpdateRegister(RSP);	
	}
	if(AP == 'proc_DateCodes') {
		showDateCodes(RSP);	
	}
	if(AP == 'proc_SetSyspro') {
		showSysproNumber(RSP);	
	}
	if(AP == 'proc_SetLanguage') {
		finishLanguage(RSP);
	}
	if(AP == 'proc_SearchDetails') {
		showAJ(RSP);
	}
	if(AP == 'proc_WafdieDetails') {
		showAJ(RSP);
	}
	if(AP == 'proc_UserSearch') {
		showSearchResults(RSP);
	}
	if(AP == 'proc_OpenUser') {
		showAJ(RSP);
		unFixAJ();
	}
	if(AP == 'proc_DelUser') {
		openResearch();
	}
	if(AP == 'proc_UpdateUser') {
		//pageShroud();	
	}
	if(AP == 'proc_AddCart') {
		showAJ(RSP);
	}
	if(AP == 'proc_EmptyCart') {
		showAJ(RSP);
	}
	if(AP == 'proc_ViewCart') {
		showAJ(RSP);
	}
	if(AP == 'proc_DeleteCart') {
		showAJ(RSP);
	}
	if(AP == 'proc_UpdateCart') {
		showAJ(RSP);
	}
	if(AP == 'proc_SetDisty') {
		showDisty(RSP);
	}
}
//=============================================================================================================
//============ Show AJAX Container ============================================================================
function showAJ(V) {
	getWidth();
	var d = document.getElementById('ajaxContent');
	var c = document.getElementById('ajContent');
	c.innerHTML = V;
	pageShroud();
	d.style.left = ((((width/2)-(d.offsetWidth/2))/width)*100) + '%';
	d.style.top = '100px';
	d.style.position = 'absolute';
}

function unFixAJ() {
	var d = document.getElementById('ajaxContent');	
	d.style.position = 'absolute';
}
//=============================================================================================================
//============ Wait Loader ====================================================================================
var waitLoader_timeout = 500;
var t_waitLoader = 0;

function waitLoader() {
	var wL = '<img src="' + GPath + 'waitLoader.gif" />';
	showAJ(wL);
}

function beginWaitLoader() {
	t_waitLoader = window.setTimeout("waitLoader()", waitLoader_timeout);
}
function cancelWaitTimer () {
	if (t_waitLoader) {
		window.clearTimeout(t_waitLoader);
	}
}
//=============================================================================================================
//=============Page Shroud ====================================================================================
function pageShroud() {
	var d = document.getElementById('pageShroud');
	var c = document.getElementById('ajaxContent');
	if(d.style.display == 'block') {
		c.style.position = 'absolute';
		d.style.display = 'none';
		c.style.display = 'none';
		c.style.left = '-9999px';
		c.style.top = '-9999px';
	}else{
		d.style.display = 'block';
		c.style.display = 'block';
	}
}
//=============================================================================================================
//============ Regex ==========================================================================================
function alphaSpaces(V) {
	var regex = /^[a-zA-Z ]+$/;
	if(regex.test(V)) {
		return true;	
	}
	return false;
}
function alphaNumSpaces(V) {
	var regex = /^[a-zA-Z0-9 \'\.]+$/;
	if(regex.test(V)) {
		return true;	
	}
	return false;
}
function NumOnly(V) {
	var regex = /^[0-9]+$/;
	if(regex.test(V)) {
		return true;	
	}
	return false;
}
function NumSpace(V) {
	var regex = /^[0-9 ]+$/;
	if(regex.test(V)) {
		return true;	
	}
	return false;
}
function NumDash(V) {
	var regex = /^[0-9\-]+$/;
	if(regex.test(V)) {
		return true;	
	}
	return false;
}
function AlphaNumChar(V) {
	var regex = /^[a-zA-Z0-9 \'\.]+$/;
	if(regex.test(V)) {
		return true;	
	}
	return false;
}
function valEmail(V) {
	var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
	if(regex.test(V)) {
		return true;	
	}
	return false;
}
//=============================================================================================================
//============ Correct Form ===================================================================================
function formError(R, ID) {
	document.getElementById(ID).innerHTML = '<table><tr><td><img src="' + GPath + 'iconError.png"></td><td valign="middle">' + R + '</td></tr></table>';
}
function formCorrect(ID) {
	document.getElementById(ID).innerHTML = '<img src="' + GPath + 'iconCorrect.png">';
}
//=============================================================================================================
//============ Registration ===================================================================================
	//Required Fields
	var reg_name = false;
	var reg_title = false;
	var reg_email = false;
	var reg_phone = false;
	var reg_company = false;
	var reg_address = false;
	var reg_city = false;
	var reg_state = false;
	var reg_zipcode = false;
	var reg_industry = false;
	
function beginRegister() {
	ua = 0;
	ub = 0;
	ajaxFunc('register');
}

function showRegister(RSP) {
	showAJ(RSP);
}

function subRegistration() {
	if((reg_name) && (reg_title) && (reg_email) && (reg_phone) && (reg_company) && (reg_address) && (reg_city) && (reg_state) && (reg_zipcode) && (reg_industry)) {
		document.getElementById('regSubmit').disabled = '';	
	}else{
		document.getElementById('regSubmit').disabled = 'disabled';		
	}
}

function submitRegistrationForm() {
	var values = new String;
	var data = document.userForm.elements;
	for (var i=0; i<data.length; i++) {
		if(data[i].id == 'regEmail') {
			var a = encodeURI(data[i].value);
		}
		values += encodeURI(data[i].value) + '|';
	}
	values = values.substr(0, (values.length - 1));
	ua = escape(values);
	ub = escape(a);
	ajaxFunc('proc_Register');	
}

function registrationComplete(RSP) {
	if(RSP == 'error') {
		alert('There was an issue with your registration!\n\nPlease try again.');
	}else{
		if(RSP == 'mailerror') {
			alert('The email containing your password failed to send!\n\nPlease contact the webmaster.');
		}else{
			alert('An email has been sent to you containing your automatically generated password.');
		}
	}
}

function reg_checkName(V) {
	var a = 'errorName';
	if(V.length < 3) {
		reg_name = false;
		formError('Too Short', a);	
	}else{
		if(alphaSpaces(V)) {
			reg_name = true;
			formCorrect(a);
		}else{
			reg_name = false;
			formError('Invalid Characters', a);	
		}
	}
	subRegistration();
}

function reg_checkTitle(V) {
	var a = 'errorTitle';
	if(V == 'none') {
		reg_title = false;
		formError('Title Needed', a);	
	}else{
		reg_title = true;
		formCorrect(a);	
	}
	subRegistration();
}

function reg_checkEmail(V) {
	var a = 'errorEmail';
	if(valEmail(V)) {
		reg_email = true;
		formCorrect(a);
	}else{
		reg_email = false;
		formError('Invalid Email', a);	
	}	
	subRegistration();
}

function reg_checkDuplicateEmail(V) {
	ua = V;
	ub = 0;
	ajaxFunc('proc_DuplicateEmail');
}

function reg_showDupEmail(RSP) {
	var a = 'errorEmail';
	if(RSP == 'fine') {
		reg_email = true;
		formCorrect(a);	
	}else{
		reg_email = false;
		formError('Duplicate Email', a);
	}
}

function reg_checkPhone(V) {
	var a = 'errorPhone';
	if(V.length < 10) {
		reg_phone = false;
		formError('Too Short', a);	
	}else{
		if(NumDash(V)) {
			reg_phone = true;
			formCorrect(a);
		}else{
			reg_phone = false;
			formError('Invalid Characters', a);	
		}
	}
	subRegistration();
}

function reg_checkCompany(V) {
	var a = 'errorCompany';
	if(V.length < 3) {
		reg_company = false;
		formError('Too Short', a);	
	}else{
		if(AlphaNumChar(V)) {
			reg_company = true;
			formCorrect(a);
		}else{
			reg_company = false;
			formError('Invalid Characters', a);	
		}
	}
	subRegistration();
}

function reg_checkAddress(V) {
	var a = 'errorAddress';
	if(V.length < 3) {
		reg_address = false;
		formError('Too Short', a);	
	}else{
		reg_address = true;
		formCorrect(a);
	}
	subRegistration();
}

function reg_checkCity(V) {
	var a = 'errorCity';
	if(V.length < 3) {
		reg_city = false;
		formError('Too Short', a);	
	}else{
		reg_city = true;
		formCorrect(a);
	}
	subRegistration();
}

function reg_checkState(V) {
	var a = 'errorState';
	if(V.length < 2) {
		reg_state = false;
		formError('Too Short', a);	
	}else{
		reg_state = true;
		formCorrect(a);
	}
	subRegistration();
}

function reg_checkZip(V) {
	var a = 'errorPostal';
	if(V.length < 3) {
		reg_zipcode = false;
		formError('Too Short', a);	
	}else{
		reg_zipcode = true;
		formCorrect(a);
	}
	subRegistration();
}

function reg_checkIndustry(V) {
	var a = 'errorIndustry';
	if(V == 'none') {
		reg_industry = false;
		formError('Industry Needed', a);	
	}else{
		reg_industry = true;
		formCorrect(a);	
	}
	subRegistration();
}
//=============================================================================================================
//============ Forgot PW ======================================================================================
function forgotPassword() {
	ua = 0;
	ub = 0;
	ajaxFunc('forgotPW');	
}

function proc_ForgotPW(V) {
	ua = V;
	ub = 0;
	ajaxFunc('proc_ForgotPW');
}

function finishForgotPW(RSP) {
	if(RSP == 'error') {
		alert('There was a problem retrieving your information!\n\nPlease try again.');	
	}else{
		alert('Your username/password have been emailed to you.');	
	}
}
//=============================================================================================================
//============ Update User Info ===============================================================================
function updateRegister() {
	ua = 0;
	ub = 0;
	ajaxFunc('updateRegister');
	reg_name = true;
	reg_title = true;
	reg_email = true;
	reg_phone = true;
	reg_company = true;
	reg_address = true;
	reg_city = true;
	reg_state = true;
	reg_zipcode = true;
	reg_industry = true;
}

function submitUpdateRegistrationForm() {
	var values = new String;
	var data = document.userForm.elements;
	for (var i=0; i<data.length; i++) {
		values += encodeURI(data[i].value) + '|';
	}
	values = values.substr(0, (values.length - 1));
	ua = escape(values);
	ub = 0;
	ajaxFunc('proc_UpdateRegister');	
}

function finishUpdateRegister(RSP) {
	if(RSP == 'error') {
		alert('There was an issue during the update process!\n\nPlease try again.');
	}else{
		alert('Your settings have been updated!');	
	}
}
//=============================================================================================================
//============ Languages ======================================================================================
function setLanguage(V) {
	ua = V;
	ub = 0;
	ajaxFunc('proc_SetLanguage');
}
function finishLanguage(RSP) {
	window.location	= HPath;
}

$(document).ready(function(){
	//this makes pressing enter run the login script
	 $("input").keypress(function (e) { if((e.which == 13) && $('#login_username') && ($('#login_username').val() != 'username') && $('#login_password') && ($('#login_password').val() != 'password') ) { subLogin(); } });
});