var ns4 = document.layers;
var op5 = (navigator.userAgent.indexOf("Opera 5")!=-1)||(navigator.userAgent.indexOf("Opera/5")!=-1);
var op6 = (navigator.userAgent.indexOf("Opera 6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1);
var agt=navigator.userAgent.toLowerCase();
var mac = (agt.indexOf("mac")!=-1);
var ie = (agt.indexOf("msie") != -1); 
var mac_ie = mac && ie;

var imageWin = null;

function getRealLeft(el) {
    xPos = el.offsetLeft;
    tempEl = el.offsetParent;
    while (tempEl != null) {
        xPos += tempEl.offsetLeft;
        tempEl = tempEl.offsetParent;
    }
    return xPos;
}

function getRealTop(el) {
    yPos = el.offsetTop;
    tempEl = el.offsetParent;
    while(tempEl != null){
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}

function showHideMenuNode(node_id, image_id){
	n = document.getElementById(node_id);
	i = document.getElementById(image_id);
	if(n){
		n.style.display = n.style.display == "none" ? "block" : "none";
		if(i){
			i.src = n.style.display == "none" ? skin_images + "/menu_tree_plus.gif" : skin_images + "/menu_tree_minus.gif";
		}
	}
}


function getElementHeight(Elem) {
	if(ns4){
		var elem = document.getElementById(Elem);
		return elem.clip.height;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) { 
			xPos = elem.style.pixelHeight;
		} else {
			xPos = elem.offsetHeight;
		}
		return xPos;
	} 
}

function getElementWidth(Elem) {
	if (ns4) {
		var elem = document.getElementById(Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}


if(document.layers){
	_browser = "nn";
}
if(document.all){
	_browser = "ie";
}
if(navigator.userAgent.toLowerCase().match("gecko")){
	_browser= "gecko";
}
function isEmail(entry){
	var rex= /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/	
	return rex.test(entry);
}

function delay(gap){ /* gap is in millisecs */
	var then, now; 
	then = new Date().getTime();
	now = then;
	while((now-then) < gap){
		now=new Date().getTime();
	}
}

function showImage(image_url, image_width, image_height){
	image_width = image_width == "" ? 400 : image_width;
	image_height = image_height == "" ? 380 : image_height;

	var w = screen.width;
	var h = screen.height;
	var ww = image_width * 1 + 30;
	var wh = image_height * 1 + 45;
	var wx = (w - ww)/2;
	var wy = (h - wh)/2;
	
	if(imageWin != null){
		imageWin.close();
	}
	imageWin = null;
	imageWin = window.open(
		"", 
		"ProductImageWindow", 
		"titlebar=yes, toolbar=no, menubar=no, status=no, directories=no, resizable=yes, scrollbars=yes, top=" + wy.toString() + ", left=" + wx.toString() + ", width=" + ww.toString() + ", height=" + wh.toString() + ""
	);
	while(imageWin==null);
	imageWin.focus();
	
	imageWin.document.body.innerHTML = "";
	imageWin.document.write('<body style="padding:5px;margin:0px">');
	imageWin.document.write('<div align="center"><img hspace="0" vspace="0" src="' + image_url + '"></div><br/>');
	imageWin.document.write('<div align="center" style="font-family:arial;font-color:black;font-size:11px;"><a href="javascript:window.close();" style="color:#0000AA;">Close Window</a></div>');
	imageWin.document.write('</body>');
	imageWin.width = ww;
	imageWin.height = wh;
}

function showPrinterPage(url){
	var prWin = null;
	prWin = window.open(
		url,
		"PrintVer", 
		"titlebar=yes, toolbar=no, menubar=yes, status=yes, directories=no, resizable=yes, scrollbars=yes, top=20, left=20, width=810, height=600"
	);
	while(prWin==null);
	prWin.focus();
}

function OnButton(bt){
	document.images[bt].src = skin_images + bt + "_on.gif";
	
}
function OffButton(bt){
	document.images[bt].src = skin_images + bt + "_off.gif";
}

function OnMenu(cid){
	document.images["menul_" + cid].src = skin_images + "catl_bg_on.gif";
	document.all["menur_" + cid].background = skin_images + "catr_bg_on.gif";
}
function OffMenu(cid){
	document.images["menul_" + cid].src = skin_images + "catl_bg_off.gif";
	document.all["menur_" + cid].background = skin_images + "catr_bg_off.gif";
}

function OnMenu(img){
	document.images[img].src = skin_images + "menu_arrow_on.gif";
}
function OffMenu(img){
	document.images[img].src = skin_images + "menu_arrow.gif";
}

function ShowPopup(src){
	var bWin = null;
	bWin = window.open(
		src, 
		"PopupWind", 
		"titlebar=no, toolbar=no, menubar=no, status=no, directories=no, resizable=no, scrollbars=no, top=20, left=20, width=320, height=240"
	);
	while(bWin==null);
	bWin.focus();
}

function PopUpImage(image_source, image_width, image_height){
	var bWin = null;
	bWin = window.open(
		image_source, 
		"ImageWind", 
		"titlebar=no, toolbar=no, menubar=no, status=no, directories=no, resizable=no, scrollbars=no, top=20, left=20, width=" + (image_width + 20) + ", height=" + (image_height + 20)
	);
	while(bWin==null);
	bWin.focus();
}

function ConfirmLogout(){
	if(orderItemsCount > 0){
		if(confirm("You have items in your cart. Logging out will empty your cart\nAre you sure want to continue?")){
			document.location = urlLogout;
		}
	}
	else{
		if(confirm("Do you really want to logout?")){
			document.location = urlLogout;
		}
	}
}

function CartConfirmDeleteItem(ocid){
	if(confirm(msg_confirm_delete_item)){
		document.location = CartDeleteItemUrl + '&ocid=' + ocid;
	}
}
function CartConfirmEmpty(){
	if(confirm(msg_confirm_empty_cart)){
		document.location = CartEmptyUrl;
	}
}

function LuhnCheck(str){
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++){
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;
    
  return result;
}


function validateCCNum(cardNum){
	var result = false;
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first2digs = cardNum.substring(0,2);
	var first3digs = cardNum.substring(0,3);
	var first4digs = cardNum.substring(0,4);
	var first5digs = cardNum.substring(0,5);
	var first6digs = cardNum.substring(0,6);
	
	
	//cascade validation
	//source: http://en.wikipedia.org/wiki/Credit_card_number
	for(i=0; i<11; i++){
		switch(i){
			case 0: //American Express 34 and 37 15 
				result = (cardLen == 15) && ((first2digs == "34") || (first2digs == "37"));
				break;
			case 1: //Bankcard 560–561 16 
				result = (cardLen == 16) && ((first3digs == "560") || (first3digs == "561"));
				break;
			case 2: //Diners Club International[1] 36 15 
				result = (cardLen == 15) && (first2digs == "36");
				break;
			case 3: //Diners Club US & Canada[1] 55 16 
				result = (cardLen == 16) && (first2digs == "55");
				break;
			
			//As of October 1st, 2005, Discover Bank will include a new BIN in the range of 650000–650999.
			case 4: //Discover Card 6011 and 650* 16 
				result = (cardLen == 16) && ((first3digs == "650") || (first4digs == "6011"));
				break;
			case 5: //JCB 3 16 
				result = (cardLen == 16) && (firstdig == "3");
				break;
			case 6: //JCB 1800 and 2131 15 
				result = (cardLen == 15) && ((first4digs == "1800") || (first4digs == "2131"));
				break;
				
			//As of November 8, 2004, MasterCard purchased the domestic (US) Diner's Club BIN range.
			//Diner's club international's website makes no reference to old 38 prefix numbers,
			//and they can be presumed reissued under the 55 or 36 BIN prefix
			case 7: //MasterCard* 51–55, 36 14 or 16 
				result = ((cardLen == 14) || (cardLen == 16)) && ((first2digs == "36") || (first2digs == "51") || (first2digs == "52") || (first2digs == "53") || (first2digs == "54") || (first2digs == "55") || (first2digs == "56") || (first2digs == "57")||(first2digs == "58") || (first2digs == "38"));
				break;
			case 8: //Visa 4 13 or 16 	
				result = ((cardLen == 13) || (cardLen == 16)) && (firstdig == "4");
				break;
			case 9: //Solo (debit card)
				result = ((cardLen == 16) || (cardLen == 18) || (cardLen == 19)) && (first4digs == "6334" || first4digs == "6767");
				break;
			case 10: //Switch (debit card)
				result = ((cardLen == 16) || (cardLen == 18) || (cardLen == 19)) && (first4digs == "4903" || first4digs == "4905" || first4digs == "4911" || first4digs == "4936" || first4digs == "6333" || first4digs == "6759" || first6digs == "564182" || first6digs == "633110");
				break;
		}
		if(result) return true;
	}
	return false;
}

// checks if the card is expired
function isCardExpired (expMonth, expYear) {
	var expDate = new Date();
	expDate.setFullYear(expYear,expMonth - 1,1);
	var today = new Date();
	today.setFullYear(today.getFullYear(),today.getMonth(),1);
	if (expDate < today)
	{
		return true;
	}
	return false;
}

function validateExpDate(expDate){
	//valid are  mmyy, mm/yy, mm20yy, mm/20yy
	var rex = /^(([0]\d{1})|([1]([012])))(\/?)(([2][0])?)(\d{2})$/;
	return rex.test(expDate);
}

function validateExpMonth(expDate){
	//valid are  01-12
	var rex = /^(([0]?\d{1})|([1]([012])))$/;
	return rex.test(expDate);
}

function validateExpYear(expDate){
	//valid are  mmyy, mm/yy, mm20yy, mm/20yy
	var rex = /^(([2][0])?)(\d{2})$/;
	return rex.test(expDate);
}

function validateCVC2(cvc2){
	//valid are ddd or dddd
	var rex = /^(\d{3,4})$/;
	return cvc2==""?true:rex.test(cvc2);
}

function validateName(name){
	var rex = /^[a-zA-Z \-\']+$/;
	return rex.test(name);
}

function validateText(txt){
	var d = "";
	for(i=0; i < txt.length; i++){
		if(txt.charAt(i) != " "){
			d = d + txt.charAt(i);
		}
	}
	if(d == ""){
		return false;
	}
	else{
		return true;
	}
}

function CheckField(frm, fname, ftitle){
	var s = frm.elements[fname].value;
	var d = "";
	
	for(i=0; i < s.length; i++){
		if(s.charAt(i) != " "){
			d = d + s.charAt(i);
		}
	}
	if(d == ""){
		alert(msg_please_enter + ' ' + ftitle);
		frm.elements[fname].focus();
		return false;
	}
	else{
		return true;
	}
}

function CheckCustomFields(frm, place){
	var irex = /^custom_field\[(\d{1,})\]$/;
	for(i=0; i<frm.elements.length; i++){
		if(irex.test(frm.elements[i].name)){
		//	alert(frm.elements[i].name);
			var s = frm.elements[i].name;
			var id = s.substring(13, s.length-1);
			if(frm.elements['custom_field_place[' + id + ']'].value == place){
				if(frm.elements['custom_field_required[' + id + ']'].value == 'yes'){
					//alert(frm.elements[i].type);
					if(frm.elements[i].type == "checkbox" && !frm.elements[i].checked){
						alert(msg_to_continue_please_check + ' ' + frm.elements['custom_field_name[' + id + ']'].value);
						frm.elements[i].focus();
						return false;
					}
					else if(frm.elements[i].value == ""){
						alert(msg_please_enter + ' ' + frm.elements['custom_field_name[' + id + ']'].value);
						frm.elements[i].focus();
						return false;
					}
				}
			}
		}
	}
	return true;
}

function CheckAddProduct(frm, min_order, max_order, allowed_max){
	if(product_may_be_added){
		var rex = /^(\d{1,})$/
		if(!rex.test(frm.elements["oa_quantity"].value)){
			alert(msg_enter_numeric_product_quantity);
			frm.elements["oa_quantity"].focus();
			return false;
		}
		if((frm.elements["oa_quantity"].value *1) < min_order){
			alert(msg_number_of_items_exceeded_min);
			frm.elements["oa_quantity"].focus();
			return false;
		}
		if((max_order != "-") && (frm.elements["oa_quantity"].value * 1 > max_order)){
			alert(msg_number_of_items_exceeded_max);
			frm.elements["oa_quantity"].focus();
			return false;
		}
		if((allowed_max != "-") && (frm.elements["oa_quantity"].value * 1 > allowed_max)){
			alert(msg_number_of_items_exceed_inventory);
			frm.elements["oa_quantity"].focus();
			return false;
		}
		return true;
	}
	return false;
}

function CheckResetPassword(frm){
	if(!CheckField(frm, "login", "username")) return false;
	if(!isEmail(frm.elements["email"].value)){
		alert(msg_enter_valid_email);
		frm.elements["email"].focus();
		return false;
	}
	return true;
}

function CheckCartForm(frm){
	var irex = /^oa_quantity\[(\d{1,})\]$/;
	var prex = /^oa_pid_to_ocid\[(\d{1,})\]$/;
	var drex = /^(\d{1,})$/
	
	var products = new Array();
	
	for(i=0; i<frm.elements.length; i++){
		
		if(irex.test(frm.elements[i].name)){
			if(!drex.test(frm.elements[i].value)){
				alert(msg_enter_numeric_product_quantity);
				frm.elements[i].focus();
				return false;	
			}
			if(frm.elements[i].value * 1 < (frm.elements["min_" + frm.elements[i].name].value) * 1){
				alert(msg_number_of_items_exceeded_min);
				frm.elements[i].focus();
				return false;
			}
			if(
				(frm.elements["max_" + frm.elements[i].name].value != "-") && 
				(frm.elements[i].value * 1 > frm.elements["max_" + frm.elements[i].name].value * 1)
			){
				alert(msg_number_of_items_exceeded_max);
				frm.elements[i].focus();
				return false;
			}
			if(
				(frm.elements["allowed_" + frm.elements[i].name].value != "-") && 
				(frm.elements[i].value * 1 > frm.elements["allowed_" + frm.elements[i].name].value * 1)
			){
				alert(msg_number_of_items_exceed_inventory);
				frm.elements[i].focus();
				return false;
			}
		}
		
		if(prex.test(frm.elements[i].name)){
			var ocid = frm.elements[i].value;
			var pid = frm.elements["oa_ocid_to_pid[" + ocid + "]"].value;
			if(products[pid]){
				products[pid] = products[pid] + frm.elements["oa_quantity[" + ocid + "]"].value * 1;
			}
			else{
				products[pid] = frm.elements["oa_quantity[" + ocid + "]"].value * 1;
			}
			
			if(frm.elements["oa_inventory_control[" + ocid + "]"].value == "Yes"){
				if(frm.elements["allowed_oa_quantity[" + ocid + "]"].value < products[pid]){
					alert(msg_number_of_items_exceed_inventory);
					frm.elements["oa_quantity[" + ocid + "]"].focus();
					return false;
				}
			}
		}
	}
	return true;
}

function CheckNewsletters(frm){
	if(!isEmail(frm.elements["email"].value)){
		alert(msg_enter_valid_email);
		frm.elements["email"].focus();
		return false;
	}
	return true;
}

function CheckUnsubscribe(frm){
	if(!isEmail(frm.elements["cancel_email"].value)){
		alert(msg_enter_valid_email);
		frm.elements["cancel_email"].focus();
		return false;
	}
	if(confirm(msg_want_cancel_subscription)){
		return true;
	}
	return false;
}

function CheckLoginForm(frm){
	if(!CheckField(frm, "login", msg_your_username)) return false;
	if(!CheckField(frm, "password", msg_your_password)) return false;
	return true;
}

/////////////////////////////
// CHECK SIGNUP FORM
function CheckSignupForm(frm, fm_company, fm_address2, fm_phone, ship2all, ship2countries){
	if(!CheckField(frm, "form[fname]", msg_first_name)) return false;
	if(!CheckField(frm, "form[lname]", msg_last_name)) return false;
	if(fm_company == "Required" && (!CheckField(frm, "form[company]", msg_company_name))) return false;
	if(!CheckField(frm, "form[address1]", msg_address_line1)) return false;
	if(fm_address2 == "Required" && (!CheckField(frm, "form[address2]", msg_address_line2))) return false;
	if(!CheckField(frm, "form[city]", msg_city_name)) return false;
	
	if(!CheckField(frm, "form[country]", msg_country)) return false;
	if(frm.elements["form[state]"].options.length > 1){
		if(frm.elements["form[state]"].value == "" || frm.elements["form[state]"].value == "0"){
			alert(msg_select_province_state);
			frm.elements["form[state]"].focus();
			return false;
		}
	}
	else{
		if(!CheckField(frm, "form[province]", msg_custom_province_state)) return false;
	}
	
	if(!CheckField(frm, "form[zip]", msg_zip_postal_code)) return false;
	if(fm_phone == "Required" && (!CheckField(frm, "form[phone]", msg_phone_number))) return false;
	
	if(!CheckCustomFields(frm, 'billing')){
		return false;	
	}
	
	if(!ship2all && frm.elements["form[thesame]"].checked){
		//check shipping country
		c = frm.elements["form[country]"].value;
		is_country = false;
		for(i=1; i<= ship2countries.length; i++){
			if(ship2countries[i] == c){
				is_country = true;
			}
		}
		if(!is_country){
			alert(msg_incorrect_shipping_address);
			return false;
		}
	}
	
	if(!CheckField(frm, "form[email]", msg_email_address)) return false;
	if(!isEmail(frm.elements["form[email]"].value)){
		alert(msg_enter_valid_email);
		frm.elements["form[email]"].focus();
		return false;
	}
	if(!CheckField(frm, "form[login]", msg_username)) return false;
	if(!CheckField(frm, "form[password]", msg_password)) return false;
	if(!CheckField(frm, "form[password2]", msg_password_confirmation)) return false;
	
	if(!CheckCustomFields(frm, 'account')){
		return false;	
	}
	
	if(!CheckCustomFields(frm, 'signup')){
		return false;	
	}
	
	if(frm.elements["form[agree]"]){
		if(frm.elements["form[agree]"].checked == false){
			alert(msg_read_terms_before_registration);
			return false;
		}
	}
	return true;
}

function CheckShippingAddress(frm, fm_company, fm_address2){
	if(!CheckField(frm, "form[name]", msg_name)) return false;
	if(fm_company == "Required" && (!CheckField(frm, "form[company]", msg_company_name))) return false;
	if(!CheckField(frm, "form[address1]", msg_address_line1)) return false;
	if(fm_address2 == "Required" && (!CheckField(frm, "form[address2]", msg_address_line2))) return false;
	if(!CheckField(frm, "form[city]", msg_city_name)) return false;
	
	
	//check is state/province select OR custom state/province
	sd = document.getElementById('div_shipping_address_state');

	if(sd.style.display == "block"){
		//check province/state from select
		if(frm.elements["form[state]"].value == "" || frm.elements["form[state]"].value == "0"){
			alert(msg_select_province_state);
			frm.elements["form[state]"].focus();
			return false;
		}
	}
	else{
		//check custom province/state
		if(!CheckField(frm, "form[province]", msg_custom_province_state)) return false;
	}
	
	if(!CheckField(frm, "form[zip]", msg_zip_postal_code)) return false;
	
	if(!CheckCustomFields(frm, 'shipping')){
		return false;	
	}
	
	return true;
}

///////////////////////////////
// CHECK PROFILE FORM
function CheckProfileForm(frm, fm_company, fm_address2, fm_phone){
	if(!CheckField(frm, "form[fname]", msg_first_name)) return false;
	if(!CheckField(frm, "form[lname]", msg_last_name)) return false;
	if(fm_company == "Required" && (!CheckField(frm, "form[company]", msg_company_name))) return false;
	if(!CheckField(frm, "form[address1]", msg_address_line1)) return false;
	if(fm_address2 == "Required" && (!CheckField(frm, "form[address2]", msg_address_line2))) return false;
	if(!CheckField(frm, "form[city]", msg_city_name)) return false;
	if(!CheckField(frm, "form[country]", msg_country)) return false;
	if(!CheckField(frm, "form[country]", msg_country)) return false;
	if(frm.elements["form[state]"].options.length > 1){
		if(frm.elements["form[state]"].value == "" || frm.elements["form[state]"].value == "0"){
			alert(msg_select_province_state);
			frm.elements["form[state]"].focus();
			return false;
		}
	}
	else{
		if(!CheckField(frm, "form[province]", msg_custom_province_state)) return false;
	}
	
	if(!CheckField(frm, "form[zip]", msg_zip_postal_code)) return false;
	if(fm_phone == "Required" && (!CheckField(frm, "form[phone]", msg_phone_number))) return false;
	if(!CheckField(frm, "form[email]", msg_email_address)) return false;
	if(!isEmail(frm.elements["form[email]"].value)){
		alert(msg_enter_valid_email);
		frm.elements["form[email]"].focus();
		return false;
	}
	
	if(!CheckCustomFields(frm, 'billing')){
		return false;	
	}
	
	if(frm.elements["form[password]"].value != ""){
		if(frm.elements["form[password]"].value != frm.elements["form[password2]"].value){
			alert(msg_different_password_and_comfirmation);
			frm.elements["form[password]"].focus();
			return false;
		}
	}
	
	if(!CheckCustomFields(frm, 'account')){
		return false;	
	}
	
	return true;
}

function CheckEmail2FriendForm(frm){
	if(!CheckField(frm, "yname", msg_your_name)) return false;
	if(!CheckField(frm, "yemail", msg_your_email_address)) return false;
	if(!isEmail(frm.elements["yemail"].value)){
		alert(msg_enter_valid_email);
		frm.elements["yemail"].focus();
		return false;
	}
	if(!CheckField(frm, "fname", msg_your_friend_name)) return false;
	if(!CheckField(frm, "femail", msg_your_friend_email_address)) return false;
	if(!isEmail(frm.elements["femail"].value)){
		alert(msg_enter_valid_email);
		frm.elements["femail"].focus();
		return false;
	}
	return true;
}

function ConfirmDeleteShippingAddress(address_id){
	if(confirm(msg_confirm_delete_shipping_address)){
		document.location = site_dinamic_url + 'ua=' + USER_DELETE_ADDRESS + '&address_id=' + address_id;
	}
}

function CheckWishlistName(frm){
	if(!CheckField(frm, "wishlist_name", msg_enterWishlistName)) return false;	
	return true;
}
function CheckWishlistEmailFrm(frm){
	if(!CheckField(frm, "mail_subject", "subject")) return false;	
	if(!isEmail(frm.elements["your_email"].value)){
		alert(msg_enter_valid_email);
		frm.elements["your_email"].focus();
		return false;
	}
	return true;
}
function ConfirmDeleteWishlist(wl_id){
	if(confirm(msg_confirm_delete_wishlist)){		
		document.location = site_dinamic_url + 'p=manage_wishlist&wl_action=delete_wishlist&wlid=' + wl_id;
	}
}

function ConfirmDeleteWishlistProduct(wlp_id){
	if(confirm(msg_confirm_delete_wishlist_product)){		
		document.location = site_dinamic_url + 'p=manage_wishlist&wl_action=delete_product&wlpid=' + wlp_id;
	}
}
