//Form validation
function checkform(of)
		{
		// Test if DOM is available and there is an element called required
			if(!document.getElementById || !document.createTextNode){return;}
			if(!document.getElementById('required')){return;}

		// Define error messages and split the required fields
			var errorID='errormsg';
			var errorClass='error'
			/* changes for linked list */
			var errorMsg='Please enter or change the following fields:';
			/* end changes for linked list */
			var errorAlt='Error';
			var errorTitle='This field has an error!';
			var reqfields=document.getElementById('required').value.split(',');

		// Cleanup old mess
			// if there is an old errormessage field, delete it
			if(document.getElementById(errorID))
			{
				var em=document.getElementById(errorID);
				em.parentNode.removeChild(em);
				
			}
			// remove old images and classes from the required fields
			for(var i=0;i<reqfields.length;i++)
			{
				var f=document.getElementById(reqfields[i]);
				if(!f){continue;}
				if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
				{
					f.parentNode.removeChild(f.previousSibling);
					f.style.backgroundColor = "#fff";
				}
				else{
				}
				//f.className='';
			}
		// loop over required fields
			for(var i=0;i<reqfields.length;i++)
			{
		// check if required field is there
				var f=document.getElementById(reqfields[i]);
				var fc=document.getElementById('email1');
				if(!f){continue;}
		// test if the required field has an error, 
		// according to its type
				switch(f.type.toLowerCase())
				{
					case 'text':
						if(f.value=='' && f.id!='email1' && f.id!='email1_confirm' && f.id!='ccnum'){cf_adderr(f)}							
		// email is a special field and needs checking
						if(f.id=='email1' && !cf_isEmailAddr(f.value)) {cf_adderr(f)}
						if(f.id=='email1_confirm')
							{
							if (f.value=='' || f.value != fc.value || !cf_isEmailAddr(f.value))
								{cf_adderr(f)}
						   }
						  if(f.id=='ccnum'){
						 	 if(checkcc(f.value))
						  	{cf_adderr(f)}
						  }
					break;
					case 'textarea':
						if(f.value==''){cf_adderr(f)}							
					break;
					case 'file':
						if(f.value==''){cf_adderr(f)}							
					break;
					case 'checkbox':
						if(!f.checked){cf_adderr(f)}							
					break;
					case 'select-one':
					
					//alert(f.value);
					if(f.value=='' && f.id!='exp_year' && f.id!='exp_month'){cf_adderr(f)}
					if(f.id=='exp_month' || f.id=='exp_year')
						{
					 	 if(f.value==''){cf_adderr(f)}
						 else  if(checkexp())	{cf_adderr(f)}
						}
						//if(!f.selectedIndex && f.selectedIndex==0 && f.value!=''){cf_adderr(f)}							
					break;
				}
			}
			return !document.getElementById(errorID);

			/* Tool methods */
			function cf_adderr(o)
			{
				// create image, add to and colourise the error fields
				var errorIndicator=document.createElement('img');
				errorIndicator.alt=errorAlt;
				errorIndicator.src=errorImg;
				errorIndicator.title=errorTitle;
				o.className=errorClass;
				o.parentNode.insertBefore(errorIndicator,o);

			// Check if there is no error message
				if(!document.getElementById(errorID))
				{
				// create errormessage and insert before submit button
					var em=document.createElement('div');
					em.id=errorID;
					var newp=document.createElement('p');
					// clone and insert the error image
					newp.appendChild(errorIndicator.cloneNode(true));
					newp.appendChild(document.createTextNode(errorMsg))
					
					em.appendChild(newp);
					/* added for linked list */
					var newul=document.createElement('ul');		
					em.appendChild(newul);
					/* end added for linked list */
					// find the submit button 
					for(var i=0;i<of.getElementsByTagName('input').length;i++)
					{
						if(/submit/i.test(of.getElementsByTagName('input')[i].type))
						{
							var sb=of.getElementsByTagName('input')[i];
							break;
						}
					}
					if(sb)
					{
						sb.parentNode.insertBefore(em,sb);
					}	
				} 
				/* added for linked list */
				var em=document.getElementById(errorID).getElementsByTagName('ul')[0];
				var newli=document.createElement('li');
				var newa=document.createElement('a');
				for(var i=0;i<of.getElementsByTagName('label').length;i++)
				{
					if(of.getElementsByTagName('label')[i].htmlFor==o.id)
					{
						var txt=of.getElementsByTagName('label')[i].firstChild.nodeValue;
						break;
					}
				}
	
				newa.appendChild(document.createTextNode(txt));
				newa.href='#'+f.id;
				newa.onclick=function()
				{
					var loc=this.href.match(/#(\w.+)/)[1];
					document.getElementById(loc).focus();
					return false;
				}
				newli.appendChild(newa);
				em.appendChild(newli);
				/* end added for linked list */
			}
			function cf_isEmailAddr(str) 
			{
			    return str.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/);
			}
		}
window.onload = function()
/* - this tells the browser to load the new table class from the CSS, namely “.hover” - */
{
  var table = document.getElementsByTagName("table");
  for(var t = 0; t < table.length; t++){
   table[t].onmouseover = function(){
    this.className += " hover";
   }
   table[t].onmouseout = function(){
    this.className = this.className.replace("hover", "");
   }
  }
/* - same as above, except this gets the class, of the same name, assigned to tr or table row  - */
{
  var tr = document.getElementsByTagName("tr");
  for(var r = 0; r < tr.length; r++){
   tr[r].onmouseover = function(){
    this.className += " hover";
   }
   tr[r].onmouseout = function(){
    this.className = this.className.replace("hover", "");
   }
  }
}
/* - same as above, for Input Buttons - */
 var zinput = document.getElementsByTagName("input");
  for(var t = 0; t < zinput.length; t++){
   zinput[t].onmouseover = function(){
    this.className += " hover";
   }
   zinput[t].onmouseout = function(){
    this.className = this.className.replace("hover", "");
   }
  }
}
function popUp(strURL,strType,strHeight,strWidth) {
var strOptions="";
var winl = (screen.width - strWidth) / 2;
var wint = (screen.height - strHeight) / 2;
if (strType=="console") strOptions="resizable,height="+strHeight+",width="+strWidth+",top="+wint+",left="+winl;
if (strType=="semiconsole") strOptions="resizable,scrollbars,height="+strHeight+",width="+strWidth+",top="+wint+",left="+winl;
//if (strType=="fixed") strOptions="status,height="+strHeight+",width="+strWidth;
if (strType=="fixed") strOptions="status,height="+strHeight+",width="+strWidth+",top="+wint+",left="+winl;
if (strType=="elastic") strOptions="toolbar,menubar,scrollbars,resizable,location,height="+strHeight+",width="+strWidth+",top="+wint+",left="+winl;
window.open(strURL, 'newWin', strOptions);
}
function showopt(id,cla){
	if (document.getElementById){
		document.getElementById(id).className=cla;
		var tab='t_'+id;
		document.getElementById(tab).className='tab_s';
	}
}
function hideopt(id,cla){
	if (document.getElementById){
		document.getElementById(id).className=cla;
		var tab='t_'+id;
		document.getElementById(tab).className='tab';

	}
}
function showi(id){
	if (document.getElementById){

		document.getElementsByTagName('div')[id].className='showme'
	}
}
function hidei(id){
	if (document.getElementById && document.createTextNode){
		document.getElementsByTagName('div')[id].className='hideme'
	}
}

function checkcc(cc) {
//LUN check
var number = cc;
var cc_error=document.getElementById('cc_error');

	var i, sum, weight;
	sum=0;
	for (i = 0; i < number.length - 1; i++) {
		weight = number.substr(number.length - (i + 2), 1) * (2 - (i % 2));
		sum += ((weight < 10) ? weight : (weight - 9));
	}

	if (parseInt(number.substr(number.length-1)) != ((10 - sum % 10) % 10)) {
		//alert(number);
		write_it('Invalid card number','cc_error');
		return true;
	}
	else {write_it('Card number','cc_error');}
  }
function checkexp(){
//Expiry

var expiry_error=document.getElementById('expiry_error');
var expiresMonth=document.getElementById('exp_month').value;
var expiresYear=document.getElementById('exp_year').value;
if (expiresMonth !='' && expiresYear !='')
{
var nowDate = new Date();
  if (expiresMonth < (nowDate.getMonth() + 1) && 
      expiresYear == nowDate.getFullYear())
  {
  	write_it('The card is expired','expiry_error');
	return true;
  }
  else if (expiresYear < nowDate.getFullYear())
  {
  	write_it('The card is expired','expiry_error');
	return true;
  }
  	else {write_it('','expiry_error');}
}
}
// write in layer
function write_it(text,id)
{
	if (document.getElementById)
	{
		x = document.getElementById(id);
		x.innerHTML = '';
		x.innerHTML = text;
	}
	else if (document.all)
	{
		x = document.all[id];
		x.innerHTML = text;
	}
	else if (document.layers)
	{
		x = document.layers[id];
		text2 = '<p>' + text + '</p>';
		x.document.open();
		x.document.write(text2);
		x.document.close();
	}
}
function returnObjById( id ) 
{ 
    if (document.getElementById) 
        var returnVar = document.getElementById(id); 
    else if (document.all) 
        var returnVar = document.all[id]; 
    else if (document.layers) 
        var returnVar = document.layers[id]; 
    return returnVar; 
}
function swapclass(id,ws_class){
var layer_swap=document.getElementById(id);
layer_swap.className = ws_class;
//var tab='t_'+id;
}
function quantityok(valuein){
   valuein+="";
   if(valuein.length==0){return false};
   for(var i=0;i<valuein.length;i++){
      if(valuein.charAt(i)<"0" || valuein.charAt(i)>"9"){return false;}
   }
   return true;
}
function quantitypositive(valuein){
   if(quantityok(valuein)){
      if(valuein>0){return true;}
   }
   return false;
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function

function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
} // Ends the "getSelectedRadioValue" function


isMoneyFormatAmount = 0.00;
isMoneyFormatString = "0.00";

function isMoneyFormat(str,eur) {
   isMoneyFormatAmount = 0.00;
   isMoneyFormatString = "0.00";
   if(!str) return false;
   str = "" + str; // force string
   for (var i=0; i<str.length;i++) {
      var ch = str.charAt(i);
      if (!isNum(ch) && ch!='.' && ch != ',' && ch !='-') return false
   }

   var sign = 1;
   var signChar = '';
   isMoneyFormatAmount = 0.00;
   isMoneyFormatString = "0.00";

   if (str.length > 1) {
      signChar = str.substring(0,1);
      if (signChar == '-' || signChar == '+' ) {
         if (signChar == '-') sign = -1;         
         str = str.substring(1);
      }
      else signChar = '';
   }
   var decimalPoint = '.';
   var thDelim = ',';
   if (eur) { 
      decimalPoint = ','
      thDelim = '.';
   }
   test1 = str.split(decimalPoint);
   if (test1.length == 2) { // Decimals found
      if (test1[1].length > 2) return false; // more than 2 decimals
      if (isNum(test1[1])) {
         if (test1[1] < 9 && test1[1].charAt(0) > 0) test1[1] = new String(test1[1]+"0");
      }
      else return false; 
   }
   else test1[1] = "00"; // force decimals
   if (test1[0] == '') test1[0] = 0;
   if (test1[0] && test1[0].indexOf(thDelim) != -1) {
      test2 = test1[0].split(thDelim);  
      if (test2.length >= 2) { // thousands found
         var thError = false;
         for (var i=0;i<test2.length;i++) {
            if (test2[i].length < 3 && i != 0) { thError = true; break; } // all thousands exept the first.
            if (!isNum(test2[i])) { thError = true; break; } // all numbers
         }
         if (thError) return false;
         test1[0] = test2.join('')
      }
   }
   isMoneyFormatAmount = (parseInt(test1[0]) + parseFloat('.'+test1[1]))*sign;
   isMoneyFormatString = new String(""+signChar+""+parseInt(test1[0])) +'.'+test1[1];
   return true;
} 

function isNum(str) {
  if(!str) return false;
  for(var i=0; i<str.length; i++){
    var ch=str.charAt(i);
    if ("0123456789".indexOf(ch) ==-1) return false;
  }
  return true;
} 
