var displayValidationWarnings = true;
var errors = '';

//removes link border
function getLinksToBlur() {
	if (!document.getElementById) return
	links = document.getElementsByTagName("a");
	for(i=0; i<links.length; i++) {
		links[i].onfocus = unblur
	}
}

function unblur() {
this.blur();
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_preloadImages() { //v3.0
getLinksToBlur()
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

//character limit for text areas
function charAlert(textField, number) {
	if(textField.value.length > number){
		/* must be > 300, not == 300 or else the substring statement on the next line
		by pressing the 'enter' key rather than clicking 'OK'. */
		textField.value= textField.value.substring(0,number)
		// set field's value equal to first 300 characters.
		textField.blur()
		/* move cursor out of form element
		to keep it from placing itself at position zero,
		causing an overwrite of the first character */
		alert("No more text can be entered")
	}
}

//validate form code
//Args groups of three: 'Object','','Test Type' 
//Added Image and Doc File type Validation - 15/11/04 Chris Lugg
//Added Password Validation - 24/11/04 Chris Lugg
function MM_validateForm() { //v4.0 ? vYM2.0
	
	var d,i,p,q,nm,test,num,min,max,args=MM_validateForm.arguments;
	var maxlength;

	errors = '';
	for (i=0; i<(args.length-2); i+=3) {
  		test=args[i+2];
		fld = MM_findObj(args[i]);
		if (fld) {
			nm = fld.name;
			nm = sortName(nm);

			if ((val=fld.value)!="") { //checks if variable contains an entry
				if (!validateFieldLength(fld))
				{
					//validation failed - field input too long for database
					errors+='- The '+nm+' is greater length than the maximum allowed.\n';
				}

				if (test.indexOf('isEmail')!=-1) { //checks if type is email
					p=val.indexOf('@');
					d=val.indexOf('.');
					if ((p<1 || p==(val.length-1))||(d<1 || d==(val.length-1))) errors+='- '+nm+' must contain an e-mail address.\n';
				} else if (test.indexOf('duration') != -1) { //checks valid image file
					if (!validateDuration(val)) {
						//validation failed
						errors+='- Please select a duration.\n';
					}
				} else if (test.indexOf('image') != -1) { //checks valid image file
					if (!validateImageFile(val)) {
						//validation failed
						errors+='- The '+nm+' is not a valid image file.\n';
					}
				} else if (test.indexOf('image1') != -1) { //checks valid image file
					if (!validateImageFile(val)) {
						//validation failed
						errors+='- The '+nm+' is not a valid image file.\n';
					}
				} else if (test.indexOf('image2') != -1) { //checks valid image file
					if (!validateImageFile(val)) {
						//validation failed
						errors+='- The '+nm+' is not a valid image file.\n';
					}
				} else if (test.indexOf('doc') != -1) { //checks valid doc file
					if (!validateDocFile(val)) {
						//validation failed
						errors+='- The '+nm+' is not a valid file.\n';
					}
				} else if (test.indexOf('password') != -1) { //checks valid password
					val2=MM_findObj('confirmPassword');
					if ((val2=val2.value)!="") { //checks confirmPassword
						if (val!=val2) { //password match
							errors += '- The passwords do not match.\n';
						} else if (val.length < 6) { //
							errors += '- The password must be 6 or more chars.\n';
						}
					} else {
						errors += '- You must confirm the password.\n';
					}
				} else if (test.indexOf('date') != -1) { //checks date field
					if (!validateDateField(val)) {
						errors+='- '+nm+' is not a valid date.\n';
					}
				} else if (test.indexOf('url') != -1) { //checks date field
					if (!validateURLField(val)) {
						errors+='- '+nm+' field requires http:// ';
					}
				} else if (test!='R') { //checks number validation
					num = parseFloat(val);
        			if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; //checks if type is number
        			if (test.indexOf('inRange') != -1) { //checks range for number
						p=test.indexOf(':');
          				min=test.substring(8,p);
						max=test.substring(p+1);
          				if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    				}
				} 
			} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n';
		}
  	}

	if (displayValidationWarnings == true)
	{
		if (errors) alert('The following error(s) occurred:\n'+errors+'\n');
	}
	document.MM_returnValue = (errors == '');
}

function displayValidationOff()
{
	displayValidationWarnings = false;
}

function displayValidationOn()
{
	displayValidationWarnings = true;
}

function validateDuration(val) {
	if (val == 'Please select')
		validateDuration = false;
	else
		validateDuration = true;
}

function validateUser(userList, usrFld)
{
	var userCount;
	var reply = true;

	for (userCount = 0; userCount < userList.length ; ++userCount )
	{
		if (userList[userCount] == usrFld)
		{
			reply = false;
			break;
		}
	}
	
	return reply;
}

function ShowProgress()
{
  strAppVersion = navigator.appVersion;
  if (document.theform.imageLarge != null || document.theform.imageSmall != null)
  {
	  if (document.theform.imageLarge.value != "" || document.theform.imageSmall.value != "")
	  {
		if (strAppVersion.indexOf('MSIE') != -1 && strAppVersion.substr(strAppVersion.indexOf('MSIE')+5,1) > 4)
		{
		  winstyle = "dialogWidth=385px; dialogHeight:140px; center:yes";
		  window.showModelessDialog('<% = barref %>&b=IE',null,winstyle);
		}
		else
		{
		  window.open('<% = barref %>&b=NN','','width=370,height=115', true);
		}
	  }
  }
  return true;
}

//Validate fails if select box value is 0
function validateSelBox(val) {
	if (val<=0) {
		return false;
	} else {
		return true;
	}
}

function MM_validateDataCaptureForm(args) 
	{ //v4.0 ? vYM2.0

	
	var d,i,p,q,nm,test,num,min,max,errors='',loopMax,x,g;
	for (i=0; i<(args.length); i++) {
		val=MM_findObj(args[i]);
		/*alert("args[i]="+args[i]);
		alert("val.name="+val.name);
		alert("val.value="+val.value);
		alert("val.length="+val.length);*/
		if (val.length>1) {
			//loopMax = val.length;
			loopMax = 1;
		} else {
			loopMax = 1;
		}
		for (x=0;x<loopMax;x++) {
			//Reset Val
			val=MM_findObj(args[i]);
			//if we are an array then get the item.
			if (loopMax>1) {
				//SAFARI FAILS HERE
				try {
					//val = val.item(x);
					//val = document.getElementById(args[i]+'_'+x);
				} catch(e) {
					alert(e);
				}
			}
			if (val) {
				test=val.getAttribute('validation');
				//alert(val.name + "->" + val.value+" : test->"+test);
				nm=val.getAttribute('errorMessage');
//			alert("item = " + val.name);
				if ((val=val.value)!="") { //checks if variable contains an entry
					if (test.indexOf('isEmail')!=-1) { //checks if type is email
						if (validEmail(val)== false)
						{
							 errors+='- '+nm+' must contain a valid e-mail address.\n';
						}
					} else if (test.indexOf('image') != -1) { //checks valid image file
						if (!validateImageFile(val)) {
							//validation failed
							errors+='- The '+nm+' is not a valid image file.\n';
						}
					} else if (test.indexOf('doc') != -1) { //checks valid doc file
						if (!validateDocFile(val)) {
							//validation failed
							errors+='- The '+nm+' is not a valid file.\n';
						}
					} else if (test.indexOf('uniqueUser') != -1) {
						if (!validateUser(val)) {
							//validation failed
							errors+='- The username you have chosen is already in use, please choose again.\n';
						}
					} else if (test.indexOf('isUniqueNumber') != -1) { //checks date field
						if (!validateUniqueNumber(val)) {
							errors+='- The '+nm+' you have chosen is already in use, please choose again.\n';
						}
					} else if (test.indexOf('uniqueEmail') != -1) {
						if (!validateEmail(val)) {
							//validation failed
							errors+='- The Email Address you have chosen is already in use, please choose again.\n';
						} else {
							p=val.indexOf('@');
							d=val.indexOf('.',p);
							if ((p<1 || p==(val.length-1))||(d<1 || d==(val.length-1) || d<p)) errors+='- '+nm+' must contain an e-mail address.\n';
						}
					} else if (test.indexOf('isTel') != -1) {
						if (!validateTel(val)) {
							//validation failed
							errors+='- The '+nm+' is not a valid telephone number.\n';
						}
					} else if (test.indexOf('confirmpassword') != -1) { //checks valid password
						val2=MM_findObj('confirmPassword');
						if (val.length < 6) { //
							errors += '- The password must be 6 or more chars.\n';
						} else {
							if ((val2=val2.value)!="") { //checks confirmPassword
								if (val!=val2) { //password not match
									errors += '- The passwords do not match.\n';
								}
							} else {
								errors += '- You must confirm the password.\n';
							}
						}
					} else if (test.indexOf('password') != -1) { //checks valid password
						if (val.length < 6) { //
							errors += '- The password must be 6 or more chars.\n';
						}
					} else if (test.indexOf('isDate') != -1) { //checks date field
						if (!validateDateField(val)) {
							errors+='- '+nm+' is not a valid date.\n';
						}
					} else if (test.indexOf('url') != -1) { //checks url field
						if (!validateURLField(val)) {
							errors+='- '+nm+' field requires http:// \n';
						}
					} else if (test.indexOf('isSel') != -1) { //checks selection box
						if (!validateSelBox(val)) {
							errors+='- Please select '+nm+'\n';
						}
					} else if (test.indexOf('isNum') != -1) { //checks selection box
						if (isNaN(val)) {
							errors+='- '+nm+' must contain a number.\n'; //checks if type is number
						}
					} else if (test.indexOf('greaterThan') != -1) { //checks gtreaterThan number
						num = parseFloat(val); 
						p=test.indexOf(':');
						q=test.substring(p+1);
						if (num<q) { 
							errors+='- '+nm+' must contain a number greater than '+q+'.\n';
						}
					} else if (test!='R') { //checks number validation
						num = parseFloat(val);        		
						if (test.indexOf('inRange') != -1) { //checks range for number
							p=test.indexOf(':');
							min=test.substring(8,p);
							max=test.substring(p+1);
							if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
						}
					}
				} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n';
			}
		}
  	}
	if (errors) alert('The following error(s) occurred:\n'+errors+'\n');
	document.MM_returnValue = (errors == '');
}


//Rename error messages
function sortName(nm) {
	newNameOfError='';
	switch(nm) {
		case "theTitle" :
			newNameOfError = "Title";
			break;
		case "trackerCode" :
			newNameOfError = "Tracker Code";
			break;
		case "headline" :
			newNameOfError = "Headline";
			break;	
		case "summary" :
			newNameOfError = "Summary";
			break;
		case "briefCopy" :
			newNameOfError = "Brief Copy";
			break;
		case "priority" : 
			newNameOfError = "Priority";
			break;
		case "text" :
			newNameOfError = "Body Text";
			break;
		case "image" :
			newNameOfError = "Image";
			break;
		case "thumbnail" :
			newNameOfError = "Thumbnail";
			break;
		case "photographer" :
			newNameOfError = "Photographer";
			break;
		case "date_from" :
			newNameOfError = "Date";
			break;
		case "date" : 
			newNameOfError = "Date";
			break;
		case "name" :
			newNameOfError = "Name";
			break;
		case "firstName" :
			newNameOfError = "First Name";
			break;
		case "surname" :
			newNameOfError = "Surname";
			break;
		case "username" :
			newNameOfError = "Username";
			break;
		case "email" :
			newNameOfError = "Email";
			break;
		case "password" :
			newNameOfError = "Password";
			break;
		case "link" :
			newNameOfError = "Link";
			break;
		case "priority" :
			newNameOfError = "Priority";
			break;
		case "duration" :
			newNameOfError = "Duration";
			break;
		}

	return newNameOfError;
}

function getFileExtension(filename) {
	return filename.substring(filename.indexOf("."))
}

function validateImageFile(filename) {
	var ext = getFileExtension(filename);
	ext.toLowerCase;
	if (ext==".jpg" || ext==".jpeg" || ext==".gif" || ext==".bmp" || ext==".png" || ext==".tiff") {
		return true;
	} else {
		return false;
	}
}

function validateDocFile(filename) {
	var ext = getFileExtension(filename);
	ext.toLowerCase;
	if (ext==".txt" || ext==".doc" || ext==".pdf" || ext==".xls" || ext==".csv") {
		return true;
	} else {
		return false;
	}
}

//Open new browser window
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

//Adds select options dynamically
function addOption(selBox, optText, optValue)
{
   //alert("Adding to Option = " + optText + ", " + optValue);
   newOption = new Option(optText);
   newOption.value = optValue;
   selBox.options[selBox.length] = newOption;
}

//Fill a select box dynamically based upon a parent value.
//
//selBox - The selection box
//valArray - An array containing the posible values by parent id
//selectedVal - The selected value if there is one
//parentVal - The parent value for which the select will be populated
function fillBox(selBox, valArray, selectedVal, parentVal) {

	//Remove existing options
	while (0 < selBox.options.length) {
		selBox.options[(selBox.options.length - 1)] = null;
	}

	//var addSelect = true;

	//Add in the options for the selected parent industry
	for (var i=0; i < valArray.length; i++) {
		//alert("i = " + i + "\n" + "valArray.length = " + valArray.length + "\n" + "valArray[i][0] = " + valArray[i][0] + "\n" + "valArray[i][1] = " + valArray[i][1] + "\n" +  "valArray[i][2] = " + valArray[i][2] + "\n" + "parentVal = " + parentVal + "\n")
		if ((valArray[i][2] == parentVal)) {
			/*if (addSelect) {
				//Always add the no selection element
				addOption(selBox, valArray[0][0], valArray[0][1]);
				addSelect = false;
			}*/
			addOption(selBox, valArray[i][0], valArray[i][1]);
		}
	}

	//set the selected option
	for (var i=0; i < selBox.options.length; i++) {
		if(selBox.options[i].value == selectedVal) {
			selBox.options[i].selected = true;
		}
	}
}

function validateDateField(fld)
{
	var monthLength = new Array(31,28,31,30,31,30,31,31,30,31,30,31)
	var reply = true;

	if (fld.length !=  10 )
	{
		reply = false;
	}
	else
	{
		var day = fld.substring(0,2);
		var month = fld.substring(3,5);
 		var year = fld.substring(6,10);
    
		if (isNaN(day) ||isNaN(month) || isNaN(year))
		{
			reply = false;
			
		}
		else
		{
			d = parseFloat(day);
			m = parseFloat(month);
			y = parseFloat(year);

			if ( (y % 4) == 0 ) monthLength[1] = 29; // Month 2 is a leap year 
	
			if ( m < 1 || m > 12 )
			{
				reply = false;
			}
			else if ( d < 1 || d > monthLength[m-1])
			{
				reply = false;
			}
		}	
	}
	return reply;
}

function validateURLField(fld)
{
	var reply = true;
	if (fld.length == 0)
	{
		// Do nothing, field may not be required
	}
	else if (fld.length <  8 )
	{
		reply = false;
	}
	else
	{
		var fldBeginsWith = fld.substring(0,7);
		if (fldBeginsWith.search('http://') != 0)
		{
			reply = false;
		}		
	}	
	return reply;
}

function validateFieldLength(fld)
{
	var reply = true;
	var maxlength = fld.getAttribute("maxlength");

	if (maxlength == null || maxlength.length == 0) reply = true; // No field length validation required.
	else
	{
		max = parseFloat(maxlength);			
		cur = parseFloat(val.length);
		if (cur > max)
		{
			reply = false; // the length of the user input is too long
		}
	}
	return reply;
}
function validEmail(mail)
{
	at_pos=mail.indexOf("@");
	dot_pos=mail.indexOf(".");
	if(at_pos<1 || dot_pos<1)
	{
		//alert("Please check position of '@' and '.' in email address.");
		return false;
	}
	else
	{
		condition="yes";
		var at_count=0;
		var dot_count=0;
		var temp=0;
		for(var i=0;i<mail.length;i++)
		{
			if((mail.charCodeAt(i)>0 && mail.charCodeAt(i)<48)||(mail.charCodeAt(i)>57 && mail.charCodeAt(i)<65)||(mail.charCodeAt(i)>91 && mail.charCodeAt(i)<97)||mail.charCodeAt(i)>122)
			{
				if(mail.charAt(i)=="@"||mail.charAt(i)=="."||mail.charAt(i) == "-"||mail.charAt(i) == "_")
				{
						if(mail.charAt(i)=="@"){at_count++}else{dot_count++} // counts the no. of times @ and . appears in email
						if(dot_count>=1)
						{
							dot_pos=i;
							if((dot_pos>at_pos) && temp==0)
							{
								pos=dot_pos-at_pos;
								temp++;
							}								
						}
				}
				else
				{
					condition="no";
					i=mail.length;
				}
			}
		}
		if(condition=="no")
		{
			//alert("Your email contains a blank space or special character.");
			//loginform.elements[0].focus();
			return false;
		}
		else
		{
			if(at_count>1)
			{
				//alert("E-mail contains extra @ ");
				//loginform.elements[0].focus();
				return false;
			}
			else
			{
				if(pos<2)
				{
					//alert("Missing domain name between '@' and '.'");
					//loginform.elements[0].focus();
					i=mail.length;
					return false
				}
				else
				{	
					count=dot_pos+1;
					domain="";
					for(count;count<mail.length;count++)
					{
						domain=domain+mail.charAt(count);		
					}
					dom=new Array("au","com","net","org","edu","in","mil","gov","arpa","biz","aero","name","coop","info","pro","museum");
					error="yes";
					for(var k=0;k<dom.length;k++)
					{
						if(domain==dom[k])
						{
							k=dom.length;
							error="no";
						}
					}
					if((error=="yes" && (domain.length>2)) || (domain.length<2))
					{
						//alert("Domain name must end with well known domains \n or 2-lettered country name. eg com,edu,in etc.");
						//loginform.elements[0].focus();
						return false;
					}
				}
			}
		}
	}
	
	return true;
}

function validateTel(val) {
	//ASCII values used
	//32 = space
	//40-41 = ()
	//43 = +
	//48-57 = numbers 0-9
	var numaric = val;
	for (var j=0; j<numaric.length; j++) {
		var alphaa = numaric.charAt(j);
		var hh = alphaa.charCodeAt(0);
		if ((hh == 32) || (hh > 39 && hh < 42) || (hh == 43) || (hh > 47 && hh < 58)) {
			//all OK continue to next char
		} else {
			return false;
		}
	}
	return true;
}

function validateTimeField(fld)
{
	var reply = true;

	if (fld.length !=  5 )
	{
		reply = false;
	}
	else {
		var hour = fld.substring(0,2);
		var minute = fld.substring(3,5);

		if (hour > 23 || hour < 0)
		{
			reply = false;
		}
		else if (minute > 59 || minute < 0)
		{
			reply = false;
		}
	}
	return reply;
}
