/**
 * Index JavaScript Document
 * Copyright Jumpeye Creative Media 2007-2008
 * www.jumpeye.com
 */


/*****************************  Prototypes  *****************************/
// Prototypes
String.prototype.capitalize = function(){
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};


/**************************  Generic functions  *************************/
// Display an element by id
function show(elem) {
	if(document.getElementById(elem)) {
		document.getElementById(elem).style.display = '';
	}
}

// Hide an element by id
function hide(elem) {
	if(document.getElementById(elem)) {
		document.getElementById(elem).style.display = 'none';
	}
}

// Go to
function goTo(link) {
	document.location.href = link;
}

// Check that the string is alpha-numeric
function isAlphaNumeric(string) {
	var regex=/^[0-9A-Za-z]+$/;
	if (regex.test(string)) {
		return true;
	} else {
		return false;
	}
}

// Check that the string is numeric
function isNumeric(string) {
	var regex = /^[0-9]+$/;
	if (regex.exec(string)) {
		return true;
	} else {
		return false;
	}
}

// Count character occurrences in a string
function charOccurences(argString, argChar) {
	var occ = 0;
	for ( var i = 0; i < argString.length; i++ ) {
		if (argString.charAt(i) == argChar) {
			occ++;
		}
	}
	return occ;
}

// Validating email addresses
function isProperEmail(argEmail) {
	if (charOccurences(argEmail, '@') + charOccurences(argEmail, '.') < 2) {
		return false
	}
	var atPos = argEmail.indexOf('@')
	var dotPos = argEmail.indexOf('.')

	if((atPos == 0) || (atPos == (argEmail.length - 1))) {
		return false
	}
	if((dotPos == 0) || (dotPos == (argEmail.length - 1))) {
		return false
	}

	var emailPat = /^(.+)@(.+)$/;
	var quotedUser = "(\"[^\"]*\")";
	var atom = '\[^\\s\\(\\)><@,;:\\\\\\\"\\.\\[\\]\]+';
	var word = "(" + atom + "|" + quotedUser + ")";
	var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");

	var matchArray = argEmail.match(emailPat);
	if (matchArray == null) {
 		return false;
	}
	var user = matchArray[1];
	var domain = matchArray[2];
	for (i = 0; i < user.length; i++) {
		if (user.charCodeAt(i) > 127) {
			return false;
		}
	}
	for (i = 0; i < domain.length; i++) {
		if (domain.charCodeAt(i) > 127) {
			return false;
		}
	}
	if (user.match(userPat)==null || domain.match(domainPat)==null) {
		return false;
	}
	return true;
}


/*************************  Specific functions  *************************/
// Bookmarks function
function addToFavorites() {
	var title = window.document.title;
	var url = top.location;

	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url, "");

	} else if(window.opera){ //Opera
		var a = document.createElement("A");
		a.rel = "sidebar";
		a.target = "_search";
		a.title = title;
		a.href = url;
		a.click();

	} else if (window.external) { // IE Favorite
		window.external.AddFavorite(url, title);
	}
}

// Generic Form Validator by Zuzu
function validateForm(theForm, prevItem, borderError, borderOk, passMinLenght, alternateFunction){
	// init main vars
	if(!borderError) {
		var borderError = "#ff0000";
	}
	if(!borderOk) {
		var borderOk = "#000000";
	}
	if(!passMinLenght) {
		var passMinLenght = 4;
	}
	var passwordTemp = false;
	var parseFilter = false;
	var errorAt = false;
	var errorReg = false;
	var errorMessages = new Array();
	{
		errorMessages[1] = "Please complete all required fields.";
		errorMessages[2] = "Please enter a valid email address.";
		errorMessages[3] = " must contain only letters or digit.";
		errorMessages[4] = "Please enter at least " + passMinLenght + " characters for your password.";
		errorMessages[5] = "Your passwords do not match, please make sure your password is re-entered properly.";
	}

	// parse entire form
	for (var i=0; i < theForm.elements.length; i++) {
		if (theForm.elements[i].alt) {
			parseFilter = theForm.elements[i].alt;
		} else if (theForm.elements[i].title) {
			parseFilter = theForm.elements[i].title;
		} else {
			parseFilter = '';
		}

		// skip element with parse filter "optional"
		if((parseFilter != '' && parseFilter.indexOf("optional") >= 0) || theForm.elements[i].style.display == "none") {
			if (!errorAt) {
				prevItem = theForm.elements[i].name;
			}
			continue;
		}
		
		// parsing text, password and textarea elements
		if (theForm.elements[i].type == "text" || theForm.elements[i].type == "password" || theForm.elements[i].type == "textarea" ) {

			// check for empty fields
			if (theForm.elements[i].value == "") {
				if (!errorAt) {
					errorAt = theForm.elements[i];
					errorReg = errorMessages[1];
				}
				theForm.elements[i].style.borderColor = borderError;

			// check for valid email
			} else if (parseFilter.indexOf("email") >= 0 && !isProperEmail(theForm.elements[i].value)) {
				if (!errorAt) {
					errorAt = theForm.elements[i];
					errorReg = errorMessages[2];
				}
				theForm.elements[i].style.borderColor = borderError;

			// check for alphanumeric value
			} else if (parseFilter.indexOf("alphanumeric") >= 0 && !isAlphaNumeric(theForm.elements[i].value)) {
				if (!errorAt) {
					errorAt = theForm.elements[i];
					errorReg = errorAt.name.capitalize() + errorMessages[3];
				}
				theForm.elements[i].style.borderColor = borderError;

			// check for valid password
			} else if (parseFilter.indexOf("password") >= 0) {
				// check for correct password lenght
				if (theForm.elements[i].value.length < passMinLenght) {
					if (!errorAt) {
						errorAt = theForm.elements[i];
						errorReg = errorMessages[4];
					}
					theForm.elements[i].style.borderColor = borderError;
					theForm.elements[i].value = '';
				
				// check for indentical password fields value
				} else {
					if(!passwordTemp) {
						passwordTemp = theForm.elements[i];
						
					} else if(passwordTemp.value != theForm.elements[i].value) {
						if (!errorAt) {
							errorAt = passwordTemp;
							errorReg = errorMessages[5];
						}
						passwordTemp.style.borderColor = borderError;
						passwordTemp.value = '';
						theForm.elements[i].style.borderColor = borderError;
						theForm.elements[i].value = '';
						
					} else {
						passwordTemp.style.borderColor = borderOk;
						theForm.elements[i].style.borderColor = borderOk;
					}
				}

			// no error found
			} else {
				theForm.elements[i].style.borderColor = borderOk;
				if (!errorAt) {
					prevItem = theForm.elements[i].name;
				}
			}

		// parsing select-one elements
		} else if(theForm.elements[i].type == "select-one") {
			if (theForm.elements[i].selectedIndex == 0) {
				if (!errorAt) {
					errorAt = theForm.elements[i];
					errorReg = errorMessages[1];
				}
				theForm.elements[i].style.borderColor = borderError;
				
			} else {
				theForm.elements[i].style.borderColor = borderOk;
			}
		}
	}

	// alert and go to error
	if(errorAt != '') {
		document.location.href	 = '#' + prevItem;
		alert(errorReg);
		errorAt.focus();
		if(alternateFunction) {
			alternateFunction(0);
		}
		return false
		
	} else if(alternateFunction) {
		return alternateFunction(1);
	}
	return true;
}

// Credit Card Validator
function validateCreditCardInfo(flag) {
	if (!document.getElementById('method_buy1') || !document.getElementById('method_buy1').checked) {
		if(flag) {
			document.location.href = '#';
			hide('shopping_cart_process');
			show('shopping_cart_load');
		}
		return true;
	}
	var borderError = "#CD0292";
	var borderOk = "#CCCCCC";
	var error = false;
	var errorAt = false;
	
	var cci_no = document.getElementById("cci_no");
	var cci_expdate = document.getElementById("cci_expdate");
	var cci_csc = document.getElementById("cci_csc");
	
	//card no
	if (cci_no.value == "" || !isNumeric(cci_no.value.replace (/\s/g, ""))) {
		error = "You must enter a valid Card Number.";
		errorAt = cci_no;
		cci_no.style.borderColor = borderError;
	} else {
		cci_no.style.borderColor = borderOk;
	}
	// expdate
    var month = cci_expdate.value.substring(0,2);
    var year = cci_expdate.value.substring(2,4);
    if (cci_expdate.value == "" || cci_expdate.value.length != 4 || !(isNumeric(month) && month>=1 && month<=12) || !isNumeric(year)) {
    	if(!error) {
    		error = "You must enter the expiration date of the credit card.";
    		errorAt = cci_expdate;
    	}
		cci_expdate.style.borderColor = borderError;
	} else {
		cci_expdate.style.borderColor = borderOk;
	}
	// csc
    if (cci_csc.value.length < 3 || !isNumeric(cci_csc.value)) {
    	if(!error) {
    		error = "You must enter a valid Card Security Code.";
    		errorAt = cci_csc;
    	}
		cci_csc.style.borderColor = borderError;
    } else {
		cci_csc.style.borderColor = borderOk;
	}
    
    if(error && flag) {
    	document.location.href	 = '#' + errorAt.name;
    	errorAt.focus();
    	alert(error);
    	return false;
    }
    if(flag) {
	    document.location.href = '#';
		hide('shopping_cart_process');
		show('shopping_cart_load');
	}
	return true;
}

// Check if US is selected
function checkForUs() {
	var current = document.getElementById('countries').selectedIndex;
	current = document.getElementById('countries').options[current].value;
	if (current == '840'){
		hide('state');
		show('us_states');
	} else {
		show('state');
		hide('us_states');
	}
}

// Tab emulator function
function jcShowTab(group, id) {
	var i=1;
	while(document.getElementById(group + '_' + i)) {
		if(i == id) {
			document.getElementById(group + '_' + i).className = 'show';
			document.getElementById(group + '_a_' + i).className = 'jc_tab_selected';
			document.getElementById(group + '_a_' + i).blur();
		} else {
			document.getElementById(group + '_' + i).className = 'hidden';
			document.getElementById(group + '_a_' + i).className = 'jc_tab1';
		}
		i++;
	}
}

// Popin Controller
function popinControl(action, link) {
	mySrc = '';
	switch(action) {
		case 'take':
			mySrc = '/popin.htm?action=1';
			window.open(link);
			break;
		case 'close':
			if(document.getElementById('popin_never_ask').checked) {
				mySrc = '/popin.htm?action=2';
			}
			break;
	}
	document.getElementById('popinmessenger').src = mySrc;
	document.getElementById('popin').style.display = 'none';
}

// Validate Tell a friend form
function validateTellFormEmail() {
	if (isProperEmail(document.tell_a_friend.email_address.value) != true) {
		alert("Please enter a valid email address.");
		document.tell_a_friend.email_address.focus();
		return false;
	} else {
		document.tell_a_friend.submit();
	}
}

// Google Translate Links
function toUrl(lang) {
	if(lang == 'en') {
		url = 'http://www.jumpeyecomponents.com/';
	} else {
		url = 'http://translate.google.com/translate?u=http://www.jumpeyecomponents.com/&langpair=en|' + lang;
	}
	top.location.href = url;
}
