var MAXINPUTFIELDS=4;
var mX=0;
var mY=0;
var svg=new Object();
String.prototype.trim=function(){
     var
         r=/^\s+|\s+$/,
         a=this.split(/\n/g),
         i=a.length;
     while(i-->0)
         a[i]=a[i].replace(r,'');
     return a.join('\n');
}
function trim(value) {
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   var obj = /  /g;
   while (temp.match(obj)) { temp = temp.replace(obj, " "); }
   return temp;
}
function checkMail(fld)
{
	// Provides a field object 
	var x = fld.value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)) {
		return true;
	} else {
		return false;
	}
}
function validate() {
	// Validates story input
	document.all.edit_area.value = document.frames[0].window.document.body.innerHTML;
	var msg="";
	var aryFld=new Array("name","email","storytitle","edit_area");
	var aryName=new Array("Name","Email Address", "Title", "Story Detail");
	var cnt=0;
	
	for (i=0; i < aryFld.length; i++) {
		if (document.getElementById(aryFld[i])) {
			if (document.getElementById(aryFld[i]).value =="") {
				cnt++;
				msg+="\n"+aryName[i];
			}	
		}
	}
	
	//document.story.submit();
	if (msg !="") {
		msg= "Please fill in the following required fields before submission: \n\n"+msg;
	}
	if (msg=="") { 
		// Check valid email address
		if (checkMail(document.getElementById("email"))) {
			// Valid email address
		} else {
			msg="The email address is invalid, please re-specify";
			
			return msg;
		}
	}
	return msg;
}
function acceptUpload(index) {
	// Refers to a specific file upload, validates and returns true or false
	// depending on whether a file has actually been added
	var oldindex=index;
	var fld="upload"+index;
	
	// Hide all other fields greater than this unless it is the last one
	
	
	try { 
	
	
	var content=document.getElementById(fld).value;
		
		if (content!="") {
			index++;	// Ensures that the current field is hidden too
		}
			
		if (index < MAXINPUTFIELDS) {
			for (i=1; i < index; i++) {
				var fldHide="uploadArea"+i;
				if (document.getElementById(fldHide)) {
					document.getElementById(fldHide).style.visibility="hidden";
				}
			}
		}
			
		if (content!="" && index <= MAXINPUTFIELDS) {
			
			// Unhide next one in the queue
			fldAppear="uploadArea"+oldindex;
			
			if (document.getElementById(fldAppear)) {	// Hide current complete field
					document.getElementById(fldAppear).style.visibility="hidden";
			}
			fldAppear="tick"+(oldindex);	
			if (document.getElementById(fldAppear)) {	// Hide green accept
					document.getElementById(fldAppear).style.visibility="hidden";
			} else {
				window.status="Cannot find "+fldAppear;
			}
			fldAppear="uploadArea"+(oldindex+1);	
			if (document.getElementById(fldAppear)) {	// Make next field visible
					//document.getElementById(fldAppear).style.visibility="visible";
					// Transfer content to Uploads
					document.getElementById("uploads").innerHTML=document.getElementById(fldAppear).innerHTML;
					
			}
			if (document.getElementById("attachDisp")) {
				if (oldindex >1) {document.getElementById("attachDisp").innerText=oldindex+ " uploads."} else {document.getElementById("attachDisp").innerText=oldindex+ " upload."}
				
			}
		} else {
			if (content=="") {
				content="Please supply a file path";
			}
		}
	} catch (error) {
		alert("Error uploading file: "+error);
	}
	return content ;	 
}
function printEvent(e) {
   if (navigator.appName == "Microsoft Internet Explorer"){
    mX = event.clientX;
    mY = event.clientY;
  }
  else {
    mX = e.pageX;
    mY = e.pageY;
  }
  alert("Click at x = " + mX + " and y = " + mY);
}
function dispMenu(e) {
  if (navigator.appName == "Microsoft Internet Explorer"){
    	mX = event.clientX;
    	mY = event.clientY;
  }
  else {
    mX = e.pageX;
    mY = e.pageY;
  }
  var menu=document.getElementById("statusmenu");
  if (menu) {
  	menu.style.visibility= menu.style.visibility=="hidden" ? "visible" : "hidden";
  	menu.style.posLeft=mX;
  	menu.style.posTop=mY;
  }
}
function publish() {
	// Publish document
	var find="?opendocument";
	var status="published";
	var loc=document.location.href.toLowerCase();
	var index=loc.indexOf(find);
	if (index !=-1) {
	
		loc=loc.substring(0,index+find.length)+"&"+status;
	} else {
		loc=loc+"&"+status;
	}
	document.location.href=loc;
}
function reject() {
	// Reject document
	var find="?opendocument";
	var status="rejected";
	var loc=document.location.href.toLowerCase();
	var index=loc.indexOf(find);
	if (index !=-1) {
		loc=loc.substring(0,index+find.length)+"&"+status;
	} else {
		loc=loc+"&"+status;
	}
	
	document.location.href=loc;
}
function submitStoryAdmin() {
	// Validates then submits the StoryAdmin form
	
	setKeyword(document.getElementById("keywordAdd"));
	var tur=document.getElementById("thankyouresponse");
	var hemail=document.getElementById("heritageEmail");
	
	if (tur ==null || hemail==null) {
			alert("One of the required fields is missing. Unable to submit this form");
	} else {
		document.forms[0].submit();
	}
}
function addAdminKeyword(selObj, addValue) {
	// For a given select object, appends the value if it does
	// not already exist
	var blFound=false;
	if (addValue!="") {
		if (selObj) {
			for (i=0; i < selObj.length; i++) {
		
					if (selObj.options[i].value.toLowerCase()==addValue.toLowerCase()) {
						i=selObj.length;blFound=true;
					}
			}
			if (!blFound) {
					option =new Option (addValue, addValue);
					selObj.options[selObj.length] = option;		
			}
		}
	}
	
}
function removeAdminKeyword(selObj) {
	
	if (selObj.selectedIndex==-1) {
		alert("Please select a keyword first");
	} else {
		for (i=0; i < selObj.length; i++) {
			if (selObj.options[i].selected==true) {
				selObj.options[i]=null;
			}
		}
		
	}
}	
function setKeyword(selObj) {
	// Select All
	
	for (i=0; i < selObj.length; i++) {
		selObj.options[i].selected=true;
	}
}
function logoff(obj, url) {
	// Implements logoff for a particular screen
	// obj is the document object, url is the url string
	
	url=url.toLowerCase();
	nsfindex=url.indexOf(".nsf");
	if (nsfindex != -1) {
	
		if (document.getElementById("ThisDB")) {
			var thisdb=document.getElementById("ThisDB").value;
			obj.location.href=url.substring(0,nsfindex+4)+"?logout&redirectto="+thisdb+"/(webstories)?openview%26restricttocategory=Published";			
		} else {
			alert("Unable to Logout at this time.");
		}
	}	
}	
function validatePassword(pword) {
	var re = /^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$/
	if (!re.test(pword)) { return false } else {return true}
}
function validateZIP(code) {
	var valid = "0123456789-";
	var hyphencount = 0;
	if (code.length!=5 && code.length!=10) {
	//	alert("Please enter your 5 digit or 5 digit+4 zip code.");
		return false;
	}
	for (var i=0; i < code.length; i++) {
		temp = "" + code.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
		//	alert("Invalid characters in your zip code.  Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((code.length==10) && ""+code.charAt(5)!="-")) {
			//alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
			return false;
		}
	}
	return true;
}
function validatePC(code){ //check postcode format is valid
test = code; size = test.length
 test = test.toUpperCase(); //Change to uppercase
 while (test.slice(0,1) == " ") //Strip leading spaces
  {test = test.substr(1,size-1);size = test.length
  }
 while(test.slice(size-1,size)== " ") //Strip trailing spaces
  {test = test.substr(0,size-1);size = test.length
  }
  
 if (size < 6 || size > 8){ //Code length rule  
  return false;
  }
 if (!(isNaN(test.charAt(0)))){ //leftmost character must be alpha character rule  
   return false;
  }
 if (isNaN(test.charAt(size-3))){ //first character of inward code must be numeric rule  
   return false;
  }
 if (!(isNaN(test.charAt(size-2)))){ //second character of inward code must be alpha rule
   return false;
  }
 if (!(isNaN(test.charAt(size-1)))){ //third character of inward code must be alpha rule
   return false;
  }
 if (!(test.charAt(size-4) == " ")){//space in position length-3 rule
   return false;
   }
 count1 = test.indexOf(" ");count2 = test.lastIndexOf(" ");
 if (count1 != count2){//only one space rule
   return false;
  }
return true;
}
function postCodeZipSearch(code, typ) {
	/**
		typ = 0 for postcode, 1 for zip
	*/
	var loc=document.location.href;
	var dbName="usw/www_usw_socal.nsf";
	var user="Anonymous";
	var append='';
	var pos=loc.indexOf(".nsf")+4;
	if (loc.indexOf("-txt") !=-1) {
			append='txt';
	}
	if (loc.indexOf("-stc") !=-1) {
			append='src';		
	}
	var prefix='';
	if (loc.indexOf(".nsf")!=-1) {
		prefix=loc.substring(0,pos);
	} else {
		prefix="/"+dbName;
		window.status=prefix;
	}
	
	switch (typ) {
		case 0:
			if (validatePC(code)==true) {
				document.location.href=prefix+"/fm-WebPostCode"+append+"?openform&postcode="+code;
			} else {
				alert("Please enter a valid postal code");
			}
			break;
		case 1:
			if (validateZIP(code)==true) {
				window.location.href=prefix+"/fm-ndos-search?OpenForm&go=1&zip="+code;
			} else {
				alert("Please enter a valid zipcode!");
			}
			break;
	}
	return;
}	
function postCodeSearch() {
	// SUPERCEDED BY POSTCODEZIPSEARCH
	var pc=document.getElementById("postcode");
	if (pc==null) {
		pc=document.all.postcode;
	}
	if (pc!=null) {
		pc.value=pc.value.toUpperCase();
		if ( validatePostCode())  {
			var loc=document.location.href.toLowerCase();
			var pos=loc.indexOf(".nsf")+4;
			buildPC(pc.value);
			//document.location.href=loc.substring(0,pos)+"/fm-WebPostCode?openform&postcode="+pc.value;
		}
	}
	
}
function zipSearch() {
	// SUPERCEDED BY POSTCODEZIPSEARCH
	var zc='';
	if (document.getElementById("zipcode")) {
		zc=document.getElementById("zipcode");	
	}
	if (zc!=null) {
		if (zc!="") {
			zc=document.all.zipcode;
			var loc=document.location.href.toLowerCase();
			var pos=loc.indexOf(".nsf")+4;
			window.location.href=loc.substring(0,pos)+"/fm-ndos-search?OpenForm&zip=90210"+zc.value;
		} else {
			alert("Please make sure you add a valid zip code first !");
		}
	}
}
		function validatePostCode() {
		
			if (document.getElementById) {
				var postcode=document.getElementById("postcode").value;	
			} else {
				var postcode=document.all.postcode.value;
			}
			postcode=Trim(postcode);		
			var pos=postcode.indexOf(" ");
			if (pos==-1) {
				// There is no space, so format with one
				if (postcode.length==7) {
					postcode=postcode.substring(0,4)+" "+postcode.substring(4,7);
				} else {
					if (postcode.length==8) {
						postcode=postcode.substring(0,4)+" "+postcode.substring(5,8);				
					} else {
						if (postcode.length==6) {
							postcode=postcode.substring(0,3)+" "+postcode.substring(3,6);				
						}
					}
				}
				if (document.getElementById) {
					document.getElementById("postcode").value=postcode;	
				} else {
					document.all.postcode.value=postcode;
				}
			}
			 pos=postcode.indexOf(" ");
			 
			var suffix=postcode.substring(pos+1, postcode.length);
			var prefix=postcode.substring(0, pos);
			prefix=Trim(prefix);
			// Format is LD DLL, LLD DLL, LDD DLL, LLDD DLL
			if (postcode.length > 8) {
				alert("Postcode length should not exceed 8 characters.");				
				return false;
			}
			
			
			if (suffix.length==3 || suffix.length==4)  {
				if (prefix.length>=2 && prefix.length<=4)  {
					return true;
				} else {					
					alert("The Postcode prefix should be alphanumeric between two and four in length");
					return;
				}
				
			} else {
				alert("Postcodes should have a suffix with either three or four alpha numerics (Length: "+suffix.length+")");
				return false;
			}
			
		}
	
function voteOLD(voteName,choices) {
			
		var pv=parseVote(choices); 
			
		if (checkCookie(voteName)==null) {
		
			if (!pv) {
				alert('Please make a choice when voting !')} 
			else {
				var append='&id='+voteName+'&vote'+pv;
				var loc=document.location.href.toLowerCase();
				nsfindex=loc.indexOf(".nsf");
				if (nsfindex != -1) {
					document.location.href=loc.substring(0,nsfindex+4)+'/fm-Vote?openform'+append;					
				} else {
					document.location.href=loc+'/fm-Vote?openform'+append;									
				}				
			}			
		}
}
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 checkCookie(id) {
	
	var path="";
	d=new Date();
	
	if (!document.getElementById("compath")) {
		if (document.forms[0].compath) {
			path=document.forms[0].compath.value;
		}
	
	} else {
		path=document.getElementById("compath").value;		
	}
	
	
	if (path=="") {
		return;
	}
	voteCookie=path+"voting/"+id; 
	
	window.status="Reading "+voteCookie+"....>";
	var ret=readCookie(voteCookie);
	
	if (ret !=null) {
		alert("Sorry, you have voted already !");
		return ret;
	} else {		
		createCookie(voteCookie,d,"999");
		return ret;
	};
}
function checkEnter(e){ //e is event object passed from function invocation
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		document.forms[0].submit() //submit the form
		return false 
	}
		else{
		return true 
	}
} 
function checkEnterSearch(e,obj){ //e is event object passed from function invocation
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		buildurl(obj.value);
		return true 
	}
		else{
		return false
	}
}
function checkEnterPostcode(e,obj){ //e is event object passed from function invocation
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		postCodeSearch();
		return true 
	}
		else{
		return false
	}
}
function sort(fldVal, sOrder) {
	//var newVal=fldVal.toString().split(",");
	//newVal=newVal.toString().split(";");
	
	fldVal=fldVal.toString();
	
	/**  Sorts a field list delimited by commas or semi-colons**/
	if (fldVal.toString().indexOf(",")!=-1) {		
		arRet=fldVal.split(",");
	} else {
		arRet=fldVal.split(";");
	}	
	
	if (sOrder=='D') {
		return arRet.sort(sortDes);
	} else {
		return arRet.sort(sortAsc);	
	}
	
}
function sortAsc(a,b)
{
	if (a < b) {return -1}
 else if (a > b) {return 1}
 else {return 0}
}
function sortDes(a,b)
{
	if (b < a) {return -1}
 else if (b > a) {return 1}
 else {return 0}
}
function addToList(objW, objH, dwNm, dwVal, dhNm, dhVal, doWidth, doHeight) {	
	// Don't go past the boundaries
	// ty = 0 for increase, 1 for decrease
	var maxh=parseInt(document.all.setupimgMaxHeight.value);
	var maxw=parseInt(document.all.setupimgMaxWidth.value);
	var minh=parseInt(document.all.setupimgMinHeight.value);
	var minw=parseInt(document.all.setupimgMinWidth.value);
	
	
	var blFound=false;
	
	if (doWidth==true) {
		var len = objW.length++; // Increase the size of list and return the size
		for (i=0; i < len; i++) {
			if (objW.options[i].value==dwVal || objW.options[i].value==dwNm && dwVal!='') {
				blFound=true;
			}
		}
	}
	if (blFound==false && doWidth==true) {
		if ((dwVal+"").trim()!='' && (dwNm+"").trim() !='') {		
		     objW.options[len].value = dwVal;
			objW.options[len].text = dwNm;
		     objW.selectedIndex = len; 		
		}
     }     
     
     if (doHeight==true) {
       	len = objH.length++; // Increase the size of list and return the size
	    	blFound=false;
		for (i=0; i < len; i++) {
			if (objH.options[i].value==dhVal || objH.options[i].value==dhNm && (dhVal+"").trim()!='') {
				blFound=true;
			}
		}
		if (blFound==false) {
			if ((dhVal+"").trim()!='' && (dhNm+"").trim() !='') {
			     objH.options[len].value = dhVal;
				objH.options[len].text = dhNm;
			     objH.selectedIndex = len; 
			    }
		}
     }
}
function detectSVG() {
	
	
	// Set some base values
	svg.installed=false;
	svg.version='0.0';
	
	if (window.ActiveXObject)
	{
		for (x=2; x<10; x++)
		{
			try
			{
				oSVG=eval("new ActiveXObject('Adobe.SVGCtl."+x+"');");
				if (oSVG)
				{
						svg.installed=true;
					svg.version=x+'.0';
				}
			}
			catch(e) {}
		}
	}
	svg.ver2=(svg.installed && parseInt(svg.version) >= 2) ? true:false;
	svg.ver3=(svg.installed && parseInt(svg.version) >= 3) ? true:false;
	svg.ver4=(svg.installed && parseInt(svg.version) >= 4) ? true:false;
	svg.ver5=(svg.installed && parseInt(svg.version) >= 5) ? true:false;
	svg.ver6=(svg.installed && parseInt(svg.version) >= 6) ? true:false;
	svg.ver7=(svg.installed && parseInt(svg.version) >= 7) ? true:false;
	svg.ver8=(svg.installed && parseInt(svg.version) >= 8) ? true:false;
	svg.ver9=(svg.installed && parseInt(svg.version) >= 9) ? true:false;
}
function doRecurring() {
	alert("here");
}
