function ccn(fieldindex)
{
	var ccns = document.getElementsByName( "cardnumber[]" );
	var ccn = ccns[fieldindex];
	if (fieldindex == 0) {
		var firstdigit = ccn.value.substring(0,1);
		if (firstdigit == 3) { //AmEx
			ccns[1].maxLength = 6;
			ccns[1].size = 6;
			ccns[2].maxLength = 5;
			ccns[2].size = 5;
			ccns[3].style.visibility = 'hidden';
			ccns[3].value = '';
			ccn.form.cvv2.maxLength = 4;
			ccn.form.cvv2.size = 4;
		} else {
			ccns[1].maxLength = 4;
			ccns[1].size = 4;
			ccns[2].maxLength = 4;
			ccns[2].size = 4;
			ccns[3].maxLength = 4;
			ccns[3].size = 4;
			ccns[3].style.visibility = 'visible';
			ccn.form.cvv2.maxLength = 3;
			ccn.form.cvv2.size = 3;
		}
	}

	//alert(ccn.value);
	if (ccn.value.length > 0) {
		if (ccn.form.cc_type) {
			//var idx = ccn.form.cc_type.length - 1;
			//ccn.form.cc_type[idx].checked= true;
			ccn.form.cc_type2.checked= true;
		}
	}

	if ( ccn.value.length == ccn.maxLength )
	{
		if ( fieldindex < 3 )
		{
			var nf = ccns[fieldindex+1];
			if (nf.style.visibility!='hidden') nf.focus();
		}
		else
		{
			ccn.form.cvv2.focus();
		}
	}
}

function clearcard () {
	var ccns = document.getElementsByName( "cardnumber[]" );
	for (var i=0;i<ccns.length;i++) {
		if (ccns[i]) ccns[i].value = '';
	}

	var cvv = document.getElementById( "cvv2" );
	if (cvv) cvv.value='';

	var expmon = document.getElementById( "expmon" );
	if (expmon) expmon.selectedIndex=0;

	var expyear = document.getElementById( "expyear" );
	if (expyear) expyear.selectedIndex=0;
}

function validatefield(field,alerttxt)
{
	var res = false;
	with (field)
	{
		if ( ( value==null ) || ( value=="") )
		{
			if ( alerttxt != "" )
			{
				alert(alerttxt);
			}
		}
		else 
		{
			res = true;
		}
	}
	return res;
}

function validateform(thisform)
{
	var res;
	var field;

	var x=document.getElementById(thisform.id);
	for (var i=0;i<x.length;i++)
	{
		field = x.elements[i];
		if ( ( field.alt != null ) && ( field.alt != "" ) )
		{
			res = validatefield(field, field.alt + " must be filled out!");
			if ( !res )
			{
				field.focus();
				return false;
			}
		}
	}

	return true;
}

function validatereg(thisform)
{
	var result = false;
	result = validateform(thisform);
	if (result) {
		if (thisform.psw1.value.length < 8) {
			alert("Passwords should be at least 8 characters long");
			result= false;
		} else {
			if (thisform.psw1.value != thisform.psw2.value) {
				thisform.psw1.value = thisform.psw2.value = '';
				alert("Password mismatch");
				result= false;
			}
			if (result) result = ValidateEmail(thisform.email.value);
			if (result) {
				if (thisform.email.value != thisform.email2.value) {
					alert("E-mail mismatch");
					result= false;
				}
			}
			if (result) result = ValidatePhone(thisform.homephone.value);
			if (result) result = ValidatePhone(thisform.dayphone.value);
		}
	}
	return result;
}

function validateshipping(thisform)
{
	var result = false;

	var isPhoneFileds = thisform.maker;
	if (typeof(isPhoneFileds)=="object") {
		var ex_model=true;
		var new_model=true;
		if (!thisform.maker.selectedIndex || !thisform.model.selectedIndex) ex_model=false;
		var reg = /([A-Za-z0-9])+$/;
		if(reg.test(thisform.cust_phone.value) == false) new_model=false;
		//if (NoChars(thisform.cust_phone.value)) new_model=false;
		if (!ex_model && !new_model) {
			alert("Please enter valid phone model");
			return false;
		}
	}

	var fields=[ "address1", "city", "zip" ];

	for ( var i=0; i<fields.length; i++ )
	{
		var field = document.getElementsByName( fields[i] );
		res = validatefield(field[0], field[0].alt + " must be filled out!");
		if ( !res )
		{
			field[0].focus();
			return false;
		}
	}

	var CouponNumber = thisform.coupon.value;
	if (CouponNumber.length > 0) {
		if ((CouponNumber.length != 6) && (CouponNumber.length != 10)) {
			alert("Promo code is invalid");
			return false;
		}
	}

	var BadAddress = NoChars(thisform.address1.value);
	if (BadAddress) {
		alert("Please enter valid address");
		return false;
	}
	var BadCity = NoChars(thisform.city.value);
	if (BadCity) {
		alert("Please enter valid city name");
		return false;
	}
		
	//if( result )
	var iscountry = validatefield( thisform.country, "Select country !");
	if ( iscountry )
	{
	 	var isstate = true;
		if ( 840 == thisform.country.value )	// USA code
		{
			isstate = validatefield( thisform.state, "Select state !");
			if (!isstate) return false;
		}
	}
	
	var issameaddress = false;
	if ((thisform.country.value==thisform.sh_country.value) && (thisform.sh_address1.value=='') && (thisform.sh_address2.value=='') && (thisform.sh_city.value=='') && (thisform.sh_zip.value=='')) {
		issameaddress = true;
	}

	if (issameaddress) {
		if (( 840 != thisform.country.value ) && (124 != thisform.country.value )) {
			//alert("Please enter shipping address in USA or Canada");
			//return false;
		}
	}

	if ( !issameaddress )
	{
		var fields=[ "sh_address1", "sh_city", "sh_zip" ];

		for ( var i=0; i<fields.length; i++ )
		{
		 		var field = document.getElementsByName( fields[i] );
				res = validatefield(field[0], field[0].alt + " must be filled out!");
				if ( !res )
				{
					if (thisform.sameaddress.checked == false) {
						field[0].focus()
					};
					return false;
				}
		}

		var BadAddress = NoChars(thisform.sh_address1.value);
		if (BadAddress) {
			alert("Please enter valid address");
			return false;
		}
		var BadCity = NoChars(thisform.sh_city.value);
		if (BadCity) {
			alert("Please enter valid city name");
			return false;
		}
		
		//if( result )
		var iscountry = validatefield( thisform.sh_country, "Select country !");
		if ( iscountry )
		{
		 	var isstate = true;
			if ( 840 == thisform.sh_country.value )	// USA code
			{
			 	isstate = validatefield( thisform.sh_state, "Select state !");
				if (!isstate) return false;
			}
		}
	}

	// check / invoice 
	if (document.forms[thisform.id].check) {
		var fcheck = document.getElementsByName( "check" );
		var finv = document.getElementsByName( "invoice" );
		var ischeck = validatefield( fcheck[0], "" ) && validatefield( finv[0], "" );
	}

	var isfund = false
	if (!document.forms[thisform.id].expmon) {
		isfund = true;
	} else if (document.forms[thisform.id].cc_type) {
		if (document.forms[thisform.id].cc_type[1].checked) isfund = true;
	}

	if (( !ischeck ) && (!isfund))
	{
		// CHECK CC DATA
		var fields=[ "cvv2", "expmon", "expyear" ];

		for ( var i=0; i<fields.length; i++ )
		{
		 		var field = document.getElementsByName( fields[i] );
				res = validatefield(field[0], field[0].alt + " must be filled out!");
				if ( !res )
				{
					field[0].focus();
					return false;
				}
		}	
		
		var cardnumber="";
		var ccns = document.getElementsByName( "cardnumber[]" );
		for( var k = 0; k < 4; k++)
		{
			cardnumber = cardnumber + "" + ccns[k].value;
		}

		var fc = cardnumber;
		
		if ( fc.charAt(0) != '4' && fc.charAt(0) != '5' && fc.charAt(0) != '3' && fc.charAt(0) != '6')
		{
			alert("Unknown card type !");
			//thisform.cardnumber.focus();
			ccns[0].focus();
			return false;
		}

		if ((fc.charAt(0) == '3') && ( fc.length != 15 ))
		{
			alert("Wrong number length !");
			//thisform.cardnumber.focus();
			ccns[0].focus();
			return false;		
		}

		if ((fc.charAt(0) != '3') && ( fc.length != 16 ))
		{
			alert("Wrong number length !");
			//thisform.cardnumber.focus();
			ccns[0].focus();
			return false;		
		}

		var fc = thisform.cvv2.value;
		if ( fc.length < 3 )
		{
			alert("Bad cvv length !");
			thisform.cvv2.focus();
			return false;		
		}
		
		var d = new Date();
		var expmon = parseInt(thisform.expmon.value);
		var expyear = parseInt(thisform.expyear.value);
		var curmon = d.getMonth()+1;
		var curyear = d.getFullYear() % 100;
		
		if ( ( expyear > curyear ) || ( ( expyear == curyear ) && ( expmon >= curmon ) ) )
		{
			result = true;
		}
		else
		{
			alert("Bad expiration date !");
			return false;
		}	
		// END CHECK CC DATA
	}
	else
	{
		result = true;
	}
	return result;
}

function validatedelivery(thisform)
{
	var selindex = thisform.postalid.selectedIndex;
	var result = ( selindex > 0 );
	if ( !result )
	{
		alert("Select delivery type!");	
	}
	return result;
}

function hidescrollbars()
{
	if ( window.scrollbars )
		window.scrollbars.visible = false;
	//alert(window.scrollbars.visible);
}

function formSubmit(sFormName)
{
	var sendform = document.getElementsByName(sFormName)[0];
	sendform.submit();
}

function tsimSubmit(sFormName, iOp)
{
	var sendform = document.getElementsByName(sFormName)[0];
	sendform.elements["TSIM_OPS"].value = iOp;
	sendform.submit();
}

function faqSubmit(sFormName, idfaq, faqid)
{
	var sendform = document.getElementsByName(sFormName)[0];
	sendform.elements["idfaq"].value = idfaq;
	sendform.elements["faqid"].value = faqid;
	sendform.submit();
}

function itemMoreSubmit(sFormName, iditem)
{
	var sendform = document.getElementsByName(sFormName)[0];
	sendform.elements["iditem"].value = iditem;
	sendform.submit();
}

function packageAdd(sFormName, idgroup, idgood, comboboxname, id, operation )
{
	var combobox = document.getElementsByName(comboboxname)[0];
	var selindex=combobox.selectedIndex;
	var goodid = combobox.options[selindex].value;
	var sendform = document.getElementsByName(sFormName)[0];
	sendform.elements["idgroup"].value = idgroup;
	sendform.elements["idgood"].value = idgood;
	sendform.elements["goodid"].value = goodid;
	sendform.elements[id].value = operation;
	sendform.submit();
}


function packageSubmit(sFormName, idgroup, idgood, goodid, id, operation )
{
	var sendform = document.getElementsByName(sFormName)[0];
	sendform.elements["idgroup"].value = idgroup;
	sendform.elements["idgood"].value = idgood;
	sendform.elements["goodid"].value = goodid;
	sendform.elements[id].value = operation;
	sendform.submit();
}

function imginsert( objname )
{
	var myTitle = "Select picture";
	var myText = showModalDialog(_editor_url + "imginsert.php?name=true",
									myTitle, // str or obj specified here can be read from dialog as "window.dialogArguments"
									"resizable: yes; help: no; status: no; scroll: yes; ");
	if ( myText ) 
	{ 
		document.all[objname].value = myText;
	}
}

function checkcharlimit(sf2check, sf2show, limit)
{
	var f2check = document.getElementsByName(sf2check)[0];
	var f2show = document.getElementsByName(sf2show)[0];
	var flength = f2check.value.length;
	f2show.value = flength; 
	if ( flength > limit )
	{
		f2show.style.fontWeight = "bold";
		f2show.style.color = "#FF0000";
		f2show.value = flength + " (" + limit + ")";
	}
	else
	{
		f2show.style.fontWeight = "normal";
		f2show.style.color = "#000000";
	}	
}

function OpenDetailsWindow( link )
{
	window.open(link,'o1','scrollbars=yes, status=no, toolbar=no, location=no, width=800, height=500, left=50, top=50');
}

function ValidatePhone(phn) {
	var re = new RegExp(" ","g");
	phn = phn.replace(re, "");
	var allValid = NoChars(phn);
	if (!allValid) {
		alert("Please enter only digit characters in the \"Phone Number\" field.");
		return false;
	} else {
		if ((phn.length > 0) && (phn.length < 10)) {
			alert("Phone number should be at least 10 digits long");
			return false;
		} else {
			return true;
		}
	}
}

function NoChars(str) {
	var checkOK = "0123456789+-";
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	for (i = 0; i < str.length; i++) {
		ch = str.charAt(i);
		for (j = 0; j < checkOK.length; j++)
			if (ch == checkOK.charAt(j))
				break;
		if (j == checkOK.length) {
			allValid = false;
			break;
		}
		allNum += ch;
	}
	return allValid;
}

function ValidateEmail(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false) {
		alert("Please enter valid e-mail address.");
		return false;
	} else return true;
}

function SMSLength() {
	var maxlength = 160;
	var smslength = smsform.smstext.value.length;
	var charsleft = maxlength - smslength;
	if (charsleft < 0) {
		text = smsform.smstext.value.substr(0, maxlength);
		smsform.smstext.value = text;
		charsleft = 0;
	}
	smsform.left.value = charsleft;
}


function ValidateCoupon() {
	var CouponEmail = entercard.email.value;
	var CouponNumber = entercard.coupon.value;
	if ((CouponNumber.length == 6) || (CouponNumber.length == 10)){
		WriteToLayer('CouponHint', '<small>validation...</small>');
		var ResponseText = '';
		var xmlHttpReq = false;
		var self = this;
		// Mozilla/Safari
		if (window.XMLHttpRequest) {
			self.xmlHttpReq = new XMLHttpRequest();
		}
		// IE
		else if (window.ActiveXObject) {
			self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			WriteToLayer('CouponHint', '<small>Can\'t validate promo code</small>');
			entercard.submitbutton.disabled=false;
			return false;
		}

		URL = '/validate_coupon.php?coupon=' + CouponNumber+'&email='+CouponEmail;

		self.xmlHttpReq.open('GET', URL, true);
		self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		self.xmlHttpReq.onreadystatechange = function() {
			entercard.submitbutton.disabled=false;
			if (self.xmlHttpReq.readyState == 4) {
				ResponseText = self.xmlHttpReq.responseText;
				if (ResponseText == 'invalid') {
					var MsgText = 'Promo code is invalid! Leave the box blank if you do not know the code';
					if (CouponNumber.length == 10) alert(MsgText);
					WriteToLayer('CouponHint', '<font color=red>' + MsgText + '</font>');
				} else if (ResponseText != '') { 
					entercard.submitbutton.disabled=false;
					WriteToLayer('CouponHint', ResponseText);
				} else {
					WriteToLayer('CouponHint', '');
				}
			}
		}
		self.xmlHttpReq.send(URL);
	}
}

function WriteToLayer(id, text) {
	if (document.layers) {
		document.layers[id].document.close();
		document.layers[id].document.write(text);
		document.layers[id].document.close();
	} else {
		if (document.all) {
			document.all[id].innerHTML = text;
		} else {
			document.getElementById(id).innerHTML = text;
		}
	}
}

function RentalsAgreementCheck() {
	if (confirmform.agreement.checked == false) {
		alert("If you agree to the terms of this sale, please click on  'I read Terms and Conditions' box");
		document.all.agreementrow.style.backgroundColor='#dddddd';
		confirmform.agreement.focus();
		return false;
	}
}

document.write('<div class="help" id="maphelpdiv" style="position:absolute; z-index: 30; border: 1px solid Gray; width:200px; padding: 5px; display:none; background-color: White; filter: alpha(opacity=95); font-size: 10px;"></div>');
maphelps=new Array();
var mapview=true;
function maphelpwin(txt,e){
	hd = document.getElementById('maphelpdiv');
	if(mapview){
		hd.innerHTML=txt;
		hd.style.visibility='visible';
		mapview=false;
	}
	if(navigator.appName=="Netscape"){
		var _x=e.pageX-245;
		var _y=e.pageY+5;
	}else{
		var _x=window.event.clientX-245;
		var _y=window.event.clientY+5;
	}

	r=false;
	b=false;
	if(_x<2){_x=2;r=true;}
	//if(_y+hd.clientHeight+2>document.body.clientHeight){_y=document.body.clientHeight-hd.clientHeight-2;b=true;}
	if(r&&b){
		if(navigator.appName=="Netscape"){
			var _x=e.pageX-5;
			var _y=e.pageY-5;
		}else{
			var _x=window.event.clientX-5;
			var _y=window.event.clientY-5;
		}
		if(navigator.appName=="Netscape"){
			hd.style.left=_x;
			hd.style.top=_y;
		}else{
			hd.style.left=_x-hd.clientWidth+document.body.scrollLeft;
			hd.style.top=_y-hd.clientHeight+document.body.scrollTop;
		}
	}else{
		if(navigator.appName=="Netscape"){
			hd.style.left=_x;
			hd.style.top=_y;
		}else{
			hd.style.left=_x+document.body.scrollLeft;
			hd.style.top=_y+document.body.scrollTop;
		}
	}
	hd.style.display='block';
}

function mapclosehelpwin(){
	hd = document.getElementById('maphelpdiv');
	hd.style.visibility='hidden';
	hd.style.left='0';
	hd.style.top='0';
	mapview=true;
}

document.write('<div class="help" id="helpdiv" style="position:absolute; z-index: 31; border: 1px solid Gray; width:200px; padding: 5px; display:none; background-color: White; filter: alpha(opacity=95); font-size: 10px;"></div>');
helps=new Array();
var view=true;
function helpwin(txt,e){
	hd = document.getElementById('helpdiv');
	if(view){
		hd.innerHTML=txt;
		hd.style.visibility='visible';
		view=false;
	}
	if(navigator.appName=="Netscape"){
		var _x=e.pageX+5;
		var _y=e.pageY+5;
	}else{
		var _x=window.event.clientX+5;
		var _y=window.event.clientY+5;
	}

	r=false;
	b=false;
	if(_x+hd.clientWidth+2>document.body.clientWidth){_x=document.body.clientWidth-hd.clientWidth-2;r=true;}
	if(_y+hd.clientHeight+2>document.body.clientHeight){_y=document.body.clientHeight-hd.clientHeight-2;b=true;}
	if(r&&b){
		if(navigator.appName=="Netscape"){
			var _x=e.pageX-5;
			var _y=e.pageY-5;
		}else{
			var _x=window.event.clientX-5;
			var _y=window.event.clientY-5;
		}
		if(navigator.appName=="Netscape"){
			hd.style.left=_x+"px";
			hd.style.top=_y+"px";
		}else{
			hd.style.left=_x-hd.clientWidth+document.body.scrollLeft;
			hd.style.top=_y-hd.clientHeight+document.body.scrollTop;
		}
	}else{
		if(navigator.appName=="Netscape"){
			var _x=e.pageX-5;
			var _y=e.pageY-5;
			hd.style.left=_x+"px";
			hd.style.top=_y+"px";
		}else{
			hd.style.left=_x+document.body.scrollLeft;
			hd.style.top=_y+document.body.scrollTop;
		}
	}
	hd.style.display='block';
}

function closehelpwin(){
	hd = document.getElementById('helpdiv');
	hd.style.visibility='hidden';
	hd.style.left='0';
	hd.style.top='0';
	view=true;
}

function ShowWaitMessage(target)
{
	try {
		if (!target)
			target = this;

		var WDiv =target.document.getElementById("WaitMessage");
		WDiv.style.display = "block";
		WDiv.style.pixelLeft = document.body.clientWidth / 2 - (WDiv.clientWidth/2);
		WDiv.style.pixelTop = document.body.clientHeight / 2 - (WDiv.clientHeight/2);
		WDiv.style.left = document.body.clientWidth / 2 - (WDiv.clientWidth/2);
		WDiv.style.top = document.body.clientHeight / 2 - (WDiv.clientHeight/2);
	} catch (e) {
		return false;
	}
	return true;
}

function HideWaitMessage(target)
{
	try {
		if (!target)
			target = this;

		target.document.getElementById("WaitMessage").style.display = "none";
	} catch (e) {
		return false;
	}
	return true;
}

function CenterWaitMessage(target)
{
	try {
		if (!target)
			target = this;

		var WDiv =target.document.getElementById("WaitMessage");
		WDiv.style.pixelLeft = (document.body.clientWidth/2) - 90;
		WDiv.style.pixelTop = (document.body.clientHeight/2) - 30;
		WDiv.style.left = (document.body.clientWidth/2) - 90;
		WDiv.style.top = (document.body.clientHeight/2) - 30;
	} catch (e) {
		return false;
	}
	return true;
}
function OpenPopupWindow(winname, w, h) {
	popupwin = window.open("", winname,"height=" + h + ",width=" + w + ",toolbar=no,scrollbars=yes,directories=no,status=no,menubar=no,resizable=yes");
	popupwin.window.focus();
}

