var global_valfield;
var now = new Date();
var emptyString = /^\s*$/ ;
var pwInput, pwvInput;
var gender = "";
// FormValidation.js
function writeErrorbox(mes)
{
	eraseErrorBox();
	
	var tables = document.getElementsByTagName("table");
	for(i = 0; i < tables.length; i++)
	{	
		if(document.getElementsByTagName("table")[i].className == "varjostus")
		{
			myAttribute = document.getElementsByTagName("table")[i];
		}
		else if(document.getElementById("logo_bar"))
		{
			myAttribute = document.getElementById("logo_bar");
		}
	}
	var errorbox = document.createElement("div");
	
	if(myAttribute.id == "logo_bar")
	{
		var tr = document.createElement("tr");
		var td = document.createElement("td");
		tr.align = "left";
		td.colSpan= "3";
		errorbox.id = "errorbox";
		errorbox.className = "errorbox";
		errorbox.innerHTML = mes + errorArray.join(", ");
		td.appendChild(errorbox);
		tr.appendChild(td);
		insertAfter(myAttribute.parentNode, tr, myAttribute);
	}
	else
	{
		errorbox.id = "errorbox";
		errorbox.className = "errorbox";
		errorbox.innerHTML = mes + errorArray.join(", ");
		insertAfter(myAttribute.parentNode, errorbox, myAttribute);
	}

	//myAttribute.parentNode.insertBefore(errorbox, myAttribute);

}
// Trim leading/trailing whitespace off string
function trim(str)
{
	return str.replace(/^\s+|\s+$/g, '');
}
//Trim all white spaces and dash
function trimWhiteSpaces(str)
{
	return str.replace(/\s/g, '');
}
//Erase useless characters
function eraseUselessCharacters(str)
{
	return str.replace(/[\(\)\,\.\-\ \s]/g, '');
}
//StringWithout...?
function isStringWithout(str, exp)
{
	if (exp.test(str)) return false;
	return true;
}
//Right length?
function isRightLength(elem, min, max)
{
	if(elem.value.length < min || elem.value.length > max) return false;
	return true;
}
//Split date
function splitDate(day, month, year)
{
	this.day = day;
	this.month = month;
	this.year = year;
}
//InsertAfter-function
function insertAfter(parent, node, referenceNode) 
{
	parent.insertBefore(node, referenceNode.nextSibling);
}
//   msg
// Display error message in SPAN element.
function msg(valfield, message, index)
{
	var dispmessage;
	var myParent = valfield.parentNode;
	if (emptyString.test(message)) 
	dispmessage = String.fromCharCode(nbsp);    //IE demands a non-breaking space
	else  
	dispmessage = message;

	if(document.getElementById("error_" + valfield.name + index)) 
	{
		myParent.removeChild(document.getElementById("error_" + valfield.name + index));
	}
	
	if(valfield.className.toLowerCase().indexOf("error") > -1)
	{
		valfield.className = valfield.className.replace("error", "");
	}
	
	if(message != " ")
	{
		var errSpan = document.createElement("span");
		var errMessage = document.createTextNode(dispmessage);
		errSpan.id = "error_" + valfield.name +index;
		errSpan.appendChild(errMessage);
		errSpan.className = "errortext";
		myParent.appendChild(errSpan);
		if(valfield.className.toLowerCase().indexOf("error") == -1)
		{
			valfield.className += "error"; 
		}
	}
}
//   msg2
// Display error message in SPAN element.
function msg2(valfield, message, index)
{
	var dispmessage;
	var myParent = valfield.parentNode;
	if (emptyString.test(message)) 
	dispmessage = String.fromCharCode(nbsp);    //IE demands a non-breaking space
	else  
	dispmessage = message;

	if(document.getElementById("error_" + valfield.name + index)) 
	{
		myParent.removeChild(document.getElementById("error_" + valfield.name + index));
	}
	
	if(valfield.className.toLowerCase().indexOf("error") > -1)
	{
		valfield.className = valfield.className.replace("error", "");
	}
		
	if(message != " ")
	{
		var errSpan = document.createElement("span");
		var errMessage = document.createTextNode(dispmessage);
		errSpan.id = "error_" + valfield.name +index;
		errSpan.appendChild(errMessage);
		errSpan.className = "errortext";
		myParent.appendChild(errSpan);
		myParent.insertBefore(errSpan, valfield.nextSibling);
		if(valfield.className.toLowerCase().indexOf("error") == -1)
		{
			valfield.className += "error"; 
		}
	}
}
function msg3(valfield, message, index)
{
	var dispmessage;
	var myParent = valfield.parentNode.parentNode;
	if (emptyString.test(message)) 
	dispmessage = String.fromCharCode(nbsp);    //IE demands a non-breaking space
	else  
	dispmessage = message;

	if(document.getElementById("error_" + valfield.name + index)) 
	{
		myParent.removeChild(document.getElementById("error_" + valfield.name + index));
	}
	
	if(valfield.className.toLowerCase().indexOf("error") > -1)
	{
		valfield.className = valfield.className.replace("error", "");
	}
		
	if(message != " ")
	{
		var newtd = document.createElement("td");
		var errSpan = document.createElement("span");
		var errMessage = document.createTextNode(dispmessage);
		newtd.id = "error_" + valfield.name +index;
		//errSpan.id = "error_" + valfield.name +index;
		errSpan.appendChild(errMessage);
		errSpan.className = "errortext";
		newtd.appendChild(errSpan);
		myParent.appendChild(newtd);
		//myParent.insertBefore(errSpan, valfield.nextSibling);
		if(valfield.className.toLowerCase().indexOf("error") == -1)
		{
			valfield.className += "error"; 
		}
	}
}
//check If Required Field Is Empty
function checkIfRequiredFieldIsEmpty(valfield, required)
{
	if (!document.getElementById) return true;  // not available on this browser - leave validation to the server

	if (emptyString.test(valfield.value)) 
	{
		if (required) 
		{
		  return false;
		}
		else {
		  return true;  
		}
	}
}
//search Label Text
//try to find labeltext in previous td
function searchLabelText(field)
{
	var tr = field.parentNode.parentNode;
	var td = tr.firstChild;
	if(td.id == "")
	{
		return "";
	}
	while(td.nodeName.toLowerCase() != "td")
	{
		td = td.nextSibling;
	}
	var label = td.innerHTML;
	return label.replace(/\s\*/g, '');
}
//check If Required 
//try to find "*"-char in labeltext
function searchRequire(field)
{
	var tr = field.parentNode.parentNode;

	if(tr.innerHTML.indexOf(field.name) != -1){
		if(tr.innerHTML.indexOf("*") != "-1")
		{
			return true;
		}
	}
	return false;
}
//validate SelectBox
function validateSelectBox(valfield)   // element to be validated
{
	if(required == true && valfield.value < 1)
	{
		return false;
	}
	return true;
}
//validate Alpha With dash
function validateAlpha(valfield)   // element to be validated
{
	var trimmedField = trimWhiteSpaces(valfield.value);  // value of field with whitespace trimmed off
	// x41-x5A: Letters(UPPERCASE) 
	// x61-x7A: Letters(lowercase) 
	// \xC0-\xD6 \xD8-\xF6 \xF8-\xFF \x152 \x153 \x160 \x161 \x178 \x192: Latin capitals 
	// \u0401 \u0451 \u0410-\u044F: Cyrillic characters (unicode) 
	// \u0100-\u017E: Some other letters (unicode)	
	// \x2D: "-" character
	var alphaExp = new RegExp(/^[\x41-\x5A \x61-\x7A \xC0-\xD6 \xD8-\xF6 \xF8-\xFF \x152 \x153 \x160 \x161 \x178 \x192 \u0401 \u0451 \u0410-\u044F \x2D]+$/);
	if (!alphaExp.test(trimmedField))
	{
	    return false;
	}
	return true;
}
//validate Alpha Numeric With dash
function validateAlphaNumeric(valfield)   // element to be validated
{
	var trimmedField = trimWhiteSpaces(valfield.value);  // value of field with whitespace trimmed off
	// x30-x39: Numbers
	// x41-x5A: Letters(UPPERCASE) 
	// x61-x7A: Letters(lowercase) 
	// \xC0-\xD6 \xD8-\xF6 \xF8-\xFF \x152 \x153 \x160 \x161 \x178 \x192: Latin capitals 
	// \u0401 \u0451 \u0410-\u044F: Cyrillic characters (unicode) 
	// \u0100-\u017E: Some other letters (unicode)
	// \x2D: "-" character
	var alphanumExp = new RegExp(/^[\x30-\x39 \x41-\x5A \x61-\x7A \xC0-\xD6 \xD8-\xF6 \xF8-\xFF \x152 \x153 \x160 \x161 \x178 \x192 \u0401 \u0451 \u0410-\u044F \u0100-\u017E \x2D]+$/);
	
	if (!alphanumExp.test(trimmedField)) 
	{
	    return false;
	}
	return true;
}
//validate Alpha Numeric With Control Chars
function validateAlphaNumericWithControlChars(valfield)   // element to be validated
{
	var trimmedField = eraseUselessCharacters(valfield.value);  // value of field with whitespace and some characters trimmed off
	// x30-x39: Numbers
	// x41-x5A: Letters(UPPERCASE) 
	// x61-x7A: Letters(lowercase) 
	// \xC0-\xD6 \xD8-\xF6 \xF8-\xFF \x152 \x153 \x160 \x161 \x178 \x192: Latin capitals 
	// \u0401 \u0451 \u0410-\u044F: Cyrillic characters (unicode) 
	// \u0100-\u017E: Some other letters (unicode)
	var alphanumExp = new RegExp(/^[\x30-\x39 \x41-\x5A \x61-\x7A \xC0-\xD6 \xD8-\xF6 \xF8-\xFF \x152 \x153 \x160 \x161 \x178 \x192 \u0401 \u0451 \u0410-\u044F \u0100-\u017E]+$/);
	
	if (!alphanumExp.test(trimmedField)) 
	{
	    return false;
	}
	return true;
}
//validate Numeric
function validateNumeric(valfield)   // element to be validated
{
	var trimmedField = trimWhiteSpaces(valfield.value);  // value of field with whitespace trimmed off
	var numericExpression = new RegExp(/^[\d]+$/);
		
	if (!numericExpression.test(trimmedField))
	{
	    return false;
	}
	return true;
}
//validate Numeric With Some Control Chars 
function validateNumericWithControlChars(valfield)   // element to be validated
{
	var trimmedField = eraseUselessCharacters(valfield.value);  // value of field with whitespace trimmed off
	var numericExpression = new RegExp(/^[\+]{0,1}[\d]+$/);

	if (!numericExpression.test(trimmedField))
	{
	    return false;
	}
	return true;
}
//validate Date
function validateCardValidity(valfield)   // element to be validated
{
	var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
	var dateRE = new RegExp(/^(\d{4})$/);
	
	if (!dateRE.test(tfld)) 
	{
		return false;
	}
	
	if(tfld.substr(0,2) > 12 || tfld.substr(0,2) < 1)
	{
		return false;
	}
	var newYear = nowYear.toString().substr(2,2); 

	if(tfld.substr(2,2) < newYear)
	{
		return false;
	}
	else if(tfld.substr(2,2) == newYear)
	{
		if(tfld.substr(0,2) < (now.getMonth()+1))
		{
			return false;
		}
	}
	return true;
}
//validate Date default
function validateDate(valfield)   // element to be validated
{
	// Use the same date format with Finnish store
	if(countryVar == 'FI' || countryVar == 'RU')
	{
		if(!validateDateFI(valfield))
		{
			return false;
		}
		return true;
	}else return true;
}

//Validate date of birth (Russia)
function validateDateRU(valfield)   // element to be validated
{	
	// Use the same date format with Finnish store
	if(!validateDateFI(valfield))
	{
		return false;
	}
	return true;
}

//validate Date (Finland)
function validateDateFI(valfield)   // element to be validated
{
	var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
	var splitted = tfld.split('.');
	var validateDay = new splitDate(splitted[0], splitted[1], splitted[2]);
	var dateRE = new RegExp(/^(\d{2})(\.)(\d{2})(\.)(\d{4})$/);
	
	if (!dateRE.test(tfld)) 
	{
		return false;
	}

	if(validateDay.year.substr(0,2) != "19" && validateDay.year.substr(0,2) != "20")
	{
		return false;
	}
	
	ddmmyy = validateDay.day.concat(validateDay.month.concat(validateDay.year.substr(2,2)));
	
	if (validateDay.year%400 == 0) monthLength[1] = 29;
	else if(validateDay.year%100 == 0) monthLength[1] = 28;
	else if(validateDay.year%4 == 0) monthLength[1] = 29;
	else monthLength[1] = 28;

	if(validateDay.year > (nowYear - minAge) || (validateDay.month > (now.getMonth()+1) && validateDay.year == nowYear))
	{
		return false;
	}
	if(validateDay.year == nowYear && validateDay.month == (now.getMonth()+1))
	{
		if(validateDay.day >= now.getDate())
		{
			return false;
		}
	}
	if (validateDay.day < 1 || validateDay.day > monthLength[validateDay.month-1])
	{
		return false;
	}
	if(validateDay.month < 1 || validateDay.month > monthLength.length)
	{
		return false;
	}

    return true;
}
//validate Date (Finland)
function validateDate2FI(valfield, mark)   // element to be validated
{
	var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
	var validateDay;
	var dateRE = new RegExp(/^(\d{6})$/);

	if (!dateRE.test(tfld)) 
	{
		return false;
	}
	ddmmyy = tfld;
	if(mark == "A"){
		validateDay = new splitDate(tfld.substring(0, 2), tfld.substring(2, 4), "20" + tfld.substring(4, 6));
	}
	else if(mark == "-"){
		validateDay = new splitDate(tfld.substring(0, 2), tfld.substring(2, 4), "19" + tfld.substring(4, 6));
	}
	else if(mark == "+"){
		validateDay = new splitDate(tfld.substring(0, 2), tfld.substring(2, 4), "18" + tfld.substring(4, 6));
	}
	else{
		return false;
	}
	
	if (validateDay.year%400 == 0) monthLength[1] = 29;
	else if(validateDay.year%100 == 0) monthLength[1] = 28;
	else if(validateDay.year%4 == 0) monthLength[1] = 29;
	else monthLength[1] = 28;

	if(validateDay.year > (nowYear - minAge) || (validateDay.month > (now.getMonth()+1) && validateDay.year == nowYear))
	{
		return false;
	}
	if(validateDay.year == nowYear && validateDay.month == (now.getMonth()+1))
	{
		if(validateDay.day >= now.getDate())
		{
			return false;
		}
	}
	if (validateDay.day < 1 || validateDay.day > monthLength[validateDay.month-1])
	{
		return false;
	}
	if(validateDay.month < 1 || validateDay.month > monthLength.length)
	{
		return false;
	}
    return true;
}
//validate Password
function validatePassword  (valfield)   // element to be validated
{
	var tfld = trim(valfield.value);// value of field with useless characters trimmed off
	//var passwd = new RegExp(/^.*(?=.{8,40})(?=.*\d)(?=.*[a-zåäö]|[A-ZÅÄÖ])([\x20-\x7E]).*$/);
	var passwd = new RegExp(/^.*(?=.{8,40})(?=.*\d)([\x20-\x7E]).*$/);

	if (!passwd.test(tfld)) 
	{
		return false;
	}
	return true;
}
//validate Email
function validateEmail(valfield)   // element to be validated
{
	var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
	var email = new RegExp(/^[\w\-\.\+]+[\@]{1}[^\x20-\x2C \x2F \x3A-\x40 \x5B-\x60 \x7B-\xBF]+[\.]{1}[^\x20-\x40 \x5B-\x60 \x7B-\xBF]{2,4}$/);
	if (!email.test(tfld)) 
	{
		return false;
	}
	return true;
}
//Validate Personal identity number default
function validatePersonalIdNumber(valfield)   // element to be validated
{
	if(countryVar == 'FI')
	{
		if(!validatePersonalIdNumberFI(valfield)){
			return false;
		}
		return true;
	}else if(countryVar == 'LT'){
		if(!validatePersonalIdNumberLT(valfield)){
			return false;
		}
		return true;
	}else if(countryVar == 'LV'){
		if(!validatePersonalIdNumberLV(valfield)){
			return false;
		}
		return true;
	}else if(countryVar == 'EE'){
		if(!validatePersonalIdNumberEE(valfield)){
			return false;
		}
		return true;
	}else return true;
}
//Validate Personal identity number Finland
function validatePersonalIdNumberFI(valfield)   // element to be validated
{
	var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
	var pinRE = new RegExp(/^\d{3}[0-9abcdefhjklmnprstuvwxyABCDEFHJKLMNPRSTUVWXY]$/);

	if (!pinRE.test(tfld)) 
	{
		return false;
	}
	var parsed = ddmmyy.concat(tfld.substr(0,3));
	var result = parseInt(parsed, 10)%31;
	var checkGender = parseInt(tfld.substr(2,1), 10)%2;
	if(checkChar[result] != tfld.substr(3,1).toUpperCase())
	{
		return false;
	}
	if(checkGender == 0){
		gender = 'F';
	}else{
		gender = 'M';
	}
	return true;
}

//Validate date of birth and personal identity number (Latvia)
function validatePersonalIdNumberLV(valfield)   // element to be validated
{
	var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
//	var pinRE = new RegExp(/^(\d{6})(\-)(\d{5})$/);
	var pinRE2 = new RegExp(/^(\d{11})$/);
	var yyyy;
	var validateDay;
	var pin = tfld.substr(7,5);

	ddmmyy = tfld.substr(0,6);
	
	if (/*!pinRE.test(tfld) && */!pinRE2.test(tfld)) 
	{
		return false;
	}

	yyyy = nowYear.toString().substr(0,2) + tfld.substr(4,2);
	if(nowYear <= yyyy)
	{
		yyyy = (nowYear - 100).toString().substr(0,2) + tfld.substr(4,2);	
	}

	validateDay = new splitDate(tfld.substr(0,2), tfld.substr(2,2), yyyy);
	
	if (validateDay.year%400 == 0) monthLength[1] = 29;
	else if(validateDay.year%100 == 0) monthLength[1] = 28;
	else if(validateDay.year%4 == 0) monthLength[1] = 29;
	else monthLength[1] = 28;

	if(validateDay.year > (nowYear - minAge) || (validateDay.month > (now.getMonth()+1) && validateDay.year == nowYear))
	{
		return false;
	}
	if(validateDay.year == nowYear && validateDay.month == (now.getMonth()+1))
	{
		if(validateDay.day >= now.getDate())
		{
			return false;
		}
	}
	if (validateDay.day > monthLength[validateDay.month-1])
	{
		return false;
	}
	if(validateDay.month < 1 || validateDay.month > monthLength.length)
	{
		return false;
	}

	return true;
}
//Validate date of birth and personal identity number (Lithuania)
function validatePersonalIdNumberLT(valfield)   // element to be validated
{
	if(!validatePin_LT_EE(valfield)){
		return false;
	}
	return true;
}

//Validate date of birth and personal identity number (Estonia)
function validatePersonalIdNumberEE(valfield)   // element to be validated
{
	if(!validatePin_LT_EE(valfield)){
		return false;
	}
	return true;
}

function validatePin_LT_EE(valfield){
	var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
	var pinRE = new RegExp(/^(\d{11})$/);
	var check = new Array(1,2,3,4,5,6,7,8,9,1);
	var check2 = new Array(3,4,5,6,7,8,9,1,2,3);
	var preResult = 0;
	var result = 0;

	if (!pinRE.test(tfld)) 
	{
		return false;
	}
	
	for(var i=0;i<tfld.length-1;i++)
	{
		preResult += tfld.substr(i,1)*check[i];
	}
	result = preResult%11;

	if(result < 10)
	{
		if(tfld.substr(tfld.length-1,1) == result)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if(result == 10)
	{
		preResult = 0;
		for(var i=0;i<tfld.length-1;i++)
		{
			preResult += tfld.substr(i,1)*check2[i];
		}
		result = preResult%11;

		if(result < 10)
		{
			if(tfld.substr(tfld.length-1,1) == result)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
}

//Remove all options of valfield(selectbox)
function removeAllOptions(valfield)
{
	for(var i=valfield.options.length-1;i>=0;i--)
	{
		valfield.remove(i);
	}
}
//Set focus
function setFocusDelayed()
{
  global_valfield.focus();
  if(global_valfield.type == 'text' || global_valfield.type == 'password' || global_valfield.type == 'textarea')
  {
  	global_valfield.select();
  }
}
function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}

//Open new window
function newwindow(URL) 
{ 
	var newin = window.open(URL,'newWin','width=550,height=500,left=0,top=100,screenX=0,screenY=100,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1'); 
	newin.focus();
}

//Open new window
function newImageWindow(URL) 
{ 
	var newin = window.open(URL,'newImgWin','scrollbars=no,location=no,menubar=no,toolbar=no,width=528,height=598, top=10,left=10'); 
	newin.focus();
}

function eraseErrorSpans()
{
	var spans = document.getElementsByTagName("span");
	for(i = 0; i < spans.length; i++)
	{
		if(document.getElementsByTagName("span")[i].className == "errortext")
		{ 
			document.getElementsByTagName("span")[i].parentNode.removeChild(document.getElementsByTagName("span")[i]);
		}		
	}
}

function eraseErrorBox()
{
	var divs = document.getElementsByTagName("div");
	for(i = 0; i < divs.length; i++)
	{
		if(document.getElementsByTagName("div")[i].className == "errorbox")
		{ 
			document.getElementsByTagName("div")[i].parentNode.removeChild(document.getElementsByTagName("div")[i]);
		}		
	}
}

function nowYear(){
	var nowYearVar = now.getYear();
	
	if(nowYearVar < 2000)
	{
		nowYearVar = nowYearVar + 1900;
	}
	return nowYearVar;
}

function showErrors(field, eMessage, errorspanStyle, index)
{
	if(errorspanStyle == 'msg')
	{
 		msg(field, eMessage, index);
	}
	else if(errorspanStyle == 'msg2')
	{
 		msg2(field, eMessage, index);
	}
	else
	{
 		msg3(field, eMessage, index);
	}
	if(errorArray.join('').indexOf(errField) != -1 && field.type != 'text'){
 		return;
 	}
 	errorArray.push(errField);
 	return;
}
//Validate name inputs
function validate_name(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
 	if(!validateAlpha(field) || !isRightLength(field, 0, field.maxLength))
 	{
 		showErrors(field, errMes, errorspanStyle, index);
 		return;
 	}
}
//Validate firstName
function validate_firstName(field, required, errorspanStyle, index)
{
	validate_name(field, required, errorspanStyle, index);
}
//Validate middleName
function validate_middleName(field, required, errorspanStyle, index)
{
	validate_name(field, required, errorspanStyle, index);
}
//Validate lastName
function validate_lastName(field, required, errorspanStyle, index)
{
	validate_name(field, required, errorspanStyle, index);
}
//Validate nickName
function validate_nickName(field, alternateIds, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(field.value.toLowerCase() == alternateIds[0].text.toLowerCase() || !isRightLength(field, 0, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
		
	for(var e=1;e<alternateIds.length-1;e++)
	{
		if(!alternateIds[e].selected)
		{
			if(field.value.toLowerCase() == alternateIds[e].text.toLowerCase())
			{
				showErrors(field, errMesSame, errorspanStyle, index);
				return;
			}
		}
	}
}
//Validate auctionNickName
function validate_auctionNickname(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(!isRightLength(field, 0, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}
//Validate address inputs
function validate_address(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(!validateAlphaNumericWithControlChars(field) || !isRightLength(field, 0, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}
//Validate address1
function validate_address1(field, required, errorspanStyle, index)
{
	validate_address(field, required, errorspanStyle, index);
}
//Validate address2
function validate_address2(field, required, errorspanStyle, index)
{
	validate_address(field, required, errorspanStyle, index);
}
//Validate address3
function validate_address3(field, required, errorspanStyle, index)
{
	validate_address(field, required, errorspanStyle, index);
}
//Validate addressField1
function validate_addressField1(field, required, errorspanStyle, index)
{
	validate_address(field, required, errorspanStyle, index);
}
//Validate addressField2
function validate_addressField2(field, required, errorspanStyle, index)
{
	validate_address(field, required, errorspanStyle, index);
}
//Validate state (region)
function validate_state(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(!validateAlphaNumericWithControlChars(field) || !isRightLength(field, 0, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}
//Validate zipCode
function validate_zipCode(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
 	if(!validateNumeric(field))					
 	{
 		if(field.value.substr(0,3).toLowerCase() == "lv-")
 		{
 			if(/^[\d]+$/.test(field.value.substr(3,4)))
 			{
 				if(field.value.length == 7)
 				{
 					return;
 				}
 			}	
 			showErrors(field, errMes, errorspanStyle, index);
 			return;
 		}
 		showErrors(field, errMesSame, errorspanStyle, index);
 		return;
 	}
 	if(!isRightLength(field, field.maxLength, field.maxLength))
 	{
 		showErrors(field, errMes, errorspanStyle, index);
 		return;
 	}
}
//Validate city
function validate_city(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(!validateAlphaNumericWithControlChars(field) || !isRightLength(field, 0, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}
//Validate email
function validate_email(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(!validateEmail(field) || !isRightLength(field, 0, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}
//Validate dateOfBirth
function validate_dateofbirth(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(!validateDate(field) || !isRightLength(field, 0, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}
//Validate personalIdNumber
function validate_pin(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value) && dateOfBirthFieldAvailable == true)
	{	
		if(required && countryVar != 'FI'){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}				
	if(!validatePersonalIdNumber(field) || !isRightLength(field, 0, field.maxLength))					
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}
//Validate alternateId
function validate_alternateId(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(!validateNumeric(field) || !isRightLength(field, field.maxLength, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}
//validate logonId
function validate_logonId(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(!validateAlphaNumericWithControlChars(field) || !isRightLength(field, 6, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}
//Validate password
function validate_password(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
 	if(field.value == "************" && pwvInput.value == "************")
 	{
 		return;
 	}
 	else if(field.value == "************" && pwvInput.value != "************")
 	{
 		showErrors(field, errMesDontMatch, errorspanStyle, index);
		return;
 	}
 	if(!isRightLength(field, 8, field.maxLength))
 	{
 		showErrors(field, errMesShort, errorspanStyle, index);
		return;
 	}
 	if(!validatePassword(field))
 	{
 		showErrors(field, errMes, errorspanStyle, index);
		return;
 	}
 	if(field.value != "" && field.value == username)
 	{
 		showErrors(field, errMesSame, errorspanStyle, index);
		return;
 	}
}
//Validate passwordVerify
function validate_passwordVerify(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
 	if(field.value == "************" && pwInput.value == "************")
 	{
 		return;
 	}
 	else if(field.value == "************" && pwInput.value != "************")
 	{
 		showErrors(field, errMesDontMatch, errorspanStyle, index);
		return;
 	}
 	if(field.value != pwInput.value)
 	{
 		showErrors(field, errMesDontMatch, errorspanStyle, index);
		return;
 	}
 	if(!isRightLength(field, 8, field.maxLength))
 	{
 		showErrors(field, errMesShort, errorspanStyle, index);
		return;
 	}
 	if(!validatePassword(field))
 	{
 		showErrors(field, errMes, errorspanStyle, index);
		return;
 	}
}
//Validate stockmannCard
function validate_stockmanncard(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if(!isRightLength(field, 16, field.maxLength))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
	if(!luhnCheck(field.value))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
	
}

    function luhnCheck(cardNumber) {
        if (isLuhnNum(cardNumber)) {
            var no_digit = cardNumber.length;
            var oddoeven = no_digit & 1;
            var sum = 0;
            for (var count = 0; count < no_digit; count++) {
                var digit = parseInt(cardNumber.charAt(count));
                if (!((count & 1) ^ oddoeven)) {
                    digit *= 2;
                    if (digit > 9) digit -= 9;
                };
                sum += digit;
            };
            if (sum == 0) return false;
            if (sum % 10 == 0) return true;
        };
        return false;
    }
    
   function isLuhnNum(argvalue) {
        argvalue = argvalue.toString();
        if (argvalue.length == 0) {
            return false;
        }
        for (var n = 0; n < argvalue.length; n++) {
            if ((argvalue.substring(n, n+1) < "0") ||
                (argvalue.substring(n,n+1) > "9")) {
                return false;
            }
        }
        return true;
    }

//Validate phone
function validate_phone(field, required, errorspanStyle, index)
{
	if(emptyString.test(field.value))
	{	
		if(required){
			var phones = document.getElementsByName("phone1");

	 		if(phones.length > 1){
		 		for(var a=0;a<phones.length;a++){
		 			if(phones[a].value != field.value && !emptyString.test(phones[a].value)){
		 				return;
		 			}
		 		}
	 		}
			showErrors(field, errMesReq, errorspanStyle, index);
			return;
		}else return;
	}
	if((!validateNumericWithControlChars(field) || !isRightLength(field, 0, field.maxLength)) && !emptyString.test(field.value))
	{
		showErrors(field, errMes, errorspanStyle, index);
		return;
	}
}

function checkCookies(){
	var cookieEnabled=(navigator.cookieEnabled)? true : false;
	
	//if not IE4+ nor NS6+
	if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){ 
		document.cookie="testcookie";
		cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false;
	}
	return cookieEnabled;
}