
//All functions written by Fitzroy Nembhard (ceo@fitzwork.com). Do not reuse without
//permission

var errorLog=new Array();//errors in form
var toggles=new Array();
var fileSelected;//used to tell which file for uploading is selected for comments
var iPos=0;//initial position of container
var fPos=0;//final position of container
var Container="";
var Tabbers=new Array('a','input','textarea','iframe','button','select');
var tabIndexes=new Array();
var firstRun=1;

function toggleTabKey(Obj, On)
{
	for(var i=0;i<Tabbers.length;i++)
	{
		var elmntNo=0;
		tbs=Obj.getElementsByTagName(Tabbers[i]);
		for(var j=0;j<tbs.length;j++)
		{
			if(firstRun)
			{
				tabIndexes=new Array();
				tabIndexes[tabIndexes.length]=tbs[j].tabIndex;//store all indexes
			}	
			if(On)
				tbs[j].tabIndex=-1;
			else
			{
				tbs[j].tabIndex=tabIndexes[elmntNo];//return to original status
				elmntNo++;
			}	
		}
	}
	firstRun=0;
}
 
function checkKeyCode(val)
{
	if(window.event)
		if(window.event.keyCode==9)//if tab key pressed
			toggleTabKey(regForm,val);//turn on or off
}


function slideContainer(C, From, To)
{
	if(getErrors())
	{
		alert('Please correct all errors before proceeding!');
		return false;
	}
	Container=document.getElementById(C);
	iPos=From;
	fPos=To;
	slide();
}

function slide()
{
	var timer="";
	timer=setTimeout("slide()",1);
	if(fPos<iPos || (fPos<=0 && iPos<=0))
		iPos+=30;
	else if(fPos>iPos &&(fPos>0))
		iPos-=30;
	if(Math.abs(fPos)==Math.abs(iPos))
		clearTimeout(timer);		
	Container.style.left=iPos +"px";
}

	
function validateFields(From, To)
{
	start=0;
	stop=0;
	currentElement=regForm.elements[start].name;
	lastElement=regForm.elements[stop].name;
	
	while(currentElement!=From && start<regForm.elements.length-1)
	{
		start++;
		currentElement=regForm.elements[start].name;
	}
	
	while(lastElement!=To && stop<regForm.elements.length-1)
	{
		stop++;
		lastElement=regForm.elements[stop].name;
	}
	
	for(var i=start;i<=stop;i++)
	{
		
		if(regForm.elements[i].name!="user" && regForm.elements[i].name!="URL" && regForm.elements[i].type!="hidden" && regForm.elements[i].name!="oState" && regForm.elements[i].name!="dState" )
			validate(regForm.elements[i].name, 'parentProcess');	
	}
	
}

function validate(field, process)
{		
	msgContainer=document.getElementById(field+".msg");
	currentErrors=parseInt(regForm.elements['errors'].value);
	if(process=="childProcess")//if field is validated by external page
	{		
		msgContainer.className=msgContainer.className.replace('invisible','visible');
		document.getElementById(field+".validator").src="/func/validateOnInput.php?field=" +field +"&value=" +regForm.elements[field].value;
	}
	else //field is validated on this page
	{
		formElement=regForm.elements[field];
		formElementName=formElement.parentNode.getElementsByTagName("label")[0].innerHTML;
		if(formElement.type=="text" || formElement.type=="password")
		{
			if(!formElement.value)
			{
				printMsg(msgContainer,'Please enter ' +formElementName, 1);
				regForm.elements['errors'].value=currentErrors+=1;//increment errors
				errorLog[errorLog.length]=field;//append field to errorLog
			}
			
			else if(formElement.name=="Email")
			{
				emailExp=/^([0-9A-Za-z])+\@([0-9A-Za-z])+\.([A-Za-z]+)$/;
				if(!emailExp.test(formElement.value))
				{
					printMsg(msgContainer,formElementName +' is invalid!', 1);
					if(!formerError(field))//if this field is not in log already
					{
						regForm.elements['errors'].value=currentErrors+=1;
						errorLog[errorLog.length]=field;
					}
				}
				else
				{
					printMsg(msgContainer,'', 0);
					if(formerError(field)>-1)
					{
						//regForm.elements['errors'].value=currentErrors-=1;
						errorLog.splice(formerError(field), 1);
					}
				}
			}
				
			else if(formElement.name=="DOB" || formElement.name=="DOD")
			{
			
				sqlDateExp=/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;//format: YYYY-MM-DD
				if(!sqlDateExp.test(formElement.value))
				{
					printMsg(msgContainer,formElementName +' is invalid!', 1);
					if(!formerError(field))//if this field is not in log already
					{
						regForm.elements['errors'].value=currentErrors+=1;
						errorLog[errorLog.length]=field;
					}
				}
				else
				{
					printMsg(msgContainer,'', 0);
					if(formerError(field)>-1)
					{
						//regForm.elements['errors'].value=currentErrors-=1;
						errorLog.splice(formerError(field), 1);
					}
				}
			}
			
			else if(formElement.value)
			{					
				printMsg(msgContainer,'', 0);
				if(formerError(field)>-1)
				{
					//regForm.elements['errors'].value=currentErrors-=1;
					errorLog.splice(formerError(field), 1);
				}
			}			
		
		}

		else if(formElement.type=="select-one")
		{
			if(formElement.name=="expirationDateMonth" || formElement.name=="expirationDateYear")
			{		
				if(formElement.value=="Year" || formElement.value=="Month")
				{			
					printMsg(msgContainer,'Please enter ' +formElementName, 1);
					regForm.elements['errors'].value=currentErrors+=1;//increment errors
					errorLog[errorLog.length]=field;//append field to errorLog
				}
				else
				{
					printMsg(msgContainer,'', 0);
					if(formerError(field)>-1)
					{
						//regForm.elements['errors'].value=currentErrors-=1;
						errorLog.splice(formerError(field), 1);
					}
				}				
			}			
		}
		
		else if(formElement.type=="file")
		{
			validExtensions=['gif','jpg','mp3','swf','wma','wav','avi'];
			filename=formElement.value;
			var valid=0;
			fileExt=filename.substring(filename.lastIndexOf('.')+1 , filename.length).toLowerCase();
			for(i=0;i<validExtensions.length;i++)
				if(fileExt==validExtensions[i])
					valid=1;
			if(!valid && fileExt )
			{
				
				printMsg(msgContainer,formElementName +' is not a valid file!', 1);
				if(!formerError(field))//if this field is not in log already
				{
					regForm.elements['errors'].value=currentErrors+=1;
					errorLog[errorLog.length]=field;
				}
			}
			else
			{
				printMsg(msgContainer,'', 0);
				if(formerError(field)>-1)
				{
					//regForm.elements['errors'].value=currentErrors-=1;
					errorLog.splice(formerError(field), 1);
				}
			}
				
		}	
	}
}

function printMsg(Container,msg,visible)
{
	if(visible)
		Container.className=Container.className.replace('invisible','visible');
	else
		Container.className=Container.className.replace('visible','invisible');
	Container.innerHTML=msg;	
}

function formerError(field)
{
	for(i=0;i<errorLog.length;i++)
		if(errorLog[i]==field)
			return i;
	return -1;
}

function pause(millis) 
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); } 
	while(curDate-date < millis);
} 

function addError(field)
{		
	if(formerError(field)==-1)
	{
		errorLog[errorLog.length]=field;
		currentErrors=parseInt(regForm.elements['errors'].value);
		regForm.elements['errors'].value=currentErrors+=1;
	}
}

function getErrors()
{
	errors=parseInt(regForm.elements['errors'].value);
	return errors;
}

function clearErrors()
{
	regForm.elements['errors'].value = 0;
}

function showElement(Elmt)
{
	Container.className=Container.className.replace('invisible','visible');
}

function hideElement(Elmt)
{
	Container.className=Container.className.replace('visible','invisible');
}

function submitForm()
{	
	var count = 0;
	clearErrors();
	validateFields('user','sAnswer');
	count += getErrors();
	validateFields('dFirstName','dLastName');
	count += getErrors();
	validateFields('DOB','DOD');
	count += getErrors();
	validateFields('cardNumber','cardCode');
	count += getErrors();

	if( count != 0 )	//|| regForm.elements['step2Reached'].value=="0")
	{
		alert('Please correct all errors before proceeding! Please go through all steps.');
		return false;
	}	
	document.getElementById('submitButton').disabled=true;
	showDropDown('Processing');
	return 0;
}

function setContinuationFlag()
{
	regForm.elements['step2Reached'].value="1"
}

function toggle(Obj,Index,hiddenField)
{
	if(hiddenField.length)
	{
		field=document.getElementById(hiddenField);
		toggleOn=parseInt(field.value);
		if(!toggleOn)
		{
			document.getElementById(Obj).style.display="none";
			field.value=1;
		}
		else
		{
			document.getElementById(Obj).style.display="inline";
			field.value=0;
		}
		
	}
	else
	{
		if(toggles[Index])
		{
			document.getElementById(Obj).style.display="none";
			toggles[Index]=0;
		}
		
		else
		{
			document.getElementById(Obj).style.display="block";
			toggles[Index]=1;
		}
	}
}

function showDropDown(Obj,Index)
{
	document.getElementById(Obj).style.display="block";
	toggles[Index]=1;
}

function hideDropDown(Obj,Index)
{
	document.getElementById(Obj).style.display="none";
	toggles[Index]=0;
}

function cancelSignUp()
{
	window.location="http://www.mypsalm23.com";
}

function cancelRegistration()
{
	if(confirm("Are you sure you want to cancel at this point? You are just one step away from owning a space at www.mypsalm23.com."))
	{
		regForm.action="/cancelCompletely";
		regForm.submit();
	}
}

function moreUploads()
{
	totalFiles=parseInt(regForm.elements['numFiles'].value);
	
	totalFiles++;
	/*var newRow;
		newRow="<li class=\"fileRow\" id=\"fileComment" +totalFiles +"\">";
		newRow+="<label class=\"basicLabel\">File " +totalFiles +"</label>";
		newRow+="<img src=\"/images/curvedRowCorner.png\" class=\"cornerCurve\" />";
		newRow+="<input type=\"text\" class=\"basicInput\" name=\"File" +totalFiles +"\" />";
		newRow+=<img src="/images/curvedRowRightCorner.png" class="cornerCurve" />
		newRow+="<div class=\"msg invisible\" id=\"File" +totalFiles +".msg\"></div>";
		newRow+="</li>";
	alert(newRow);
	
	*/

	container=document.getElementById("moreFiles");
	li=document.createElement("li");
	li.setAttribute("className","fileRow");
	li.setAttribute("id","fileRow"+totalFiles);
	
	commentsLink=document.createElement("a");
	commentsLink.setAttribute("href","javascript:addComments(" +totalFiles +");");
	commentsLink.setAttribute("title","Add a comment to File "  +totalFiles);
	//commentsLink.appendChild(document.createTextNode("(Add Comment)"));
	
	fieldTitle=document.createElement("label");
	fieldTitle.setAttribute("className","basicLabel");
	fieldTitleTxt=document.createTextNode("File "+totalFiles +" ");
	
	errorBox=document.createElement("div");
	errorBox.setAttribute("className","msg invisible");
	errorBox.setAttribute("id","File"+totalFiles+".msg");
	
	newFile=document.createElement("input");
	newFile.setAttribute("type","file");
	newFile.setAttribute("name","File"+totalFiles);
	newFile.setAttribute("className","basicFile");
	newFile.setAttribute("onblur","validate('File" +totalFiles +"','parentProcess')");
	
	commentBox=document.createElement("input");
	commentBox.setAttribute("type","hidden");
	commentBox.setAttribute("name","File" +totalFiles +"Comments");
	commentBox.setAttribute("id","File" +totalFiles +"Comments");
	commentBox.setAttribute("value","");
	
	fieldTitle.appendChild(fieldTitleTxt);
	fieldTitle.appendChild(commentsLink);
	li.appendChild(fieldTitle);
	li.appendChild(newFile);
	li.appendChild(commentBox);
	li.appendChild(errorBox);
	container.appendChild(li);
	
	regForm.elements['numFiles'].value=totalFiles;
	document.getElementById("deleteRow").disabled="";
}

function lessUploads()
{
	var container=document.getElementById("moreFiles");
	totalFiles=parseInt(regForm.elements['numFiles'].value);
	if(totalFiles>1)
	{
		var toRemove=document.getElementById("fileRow"+totalFiles);
		container.removeChild(toRemove);
		totalFiles--;
		regForm.elements['numFiles'].value=totalFiles;
	}
	if(totalFiles==1)
		document.getElementById("deleteRow").disabled=true;
}

function useSameAddress()
{
	regForm.elements['dAddress'].value=regForm.elements['oAddress'].value;
	regForm.elements['dState'].value=regForm.elements['oState'].value;
	regForm.elements['dCity'].value=regForm.elements['oCity'].value;
	regForm.elements['dZip'].value=regForm.elements['oZip'].value;
}

function addComments(NO)
{
	commentsDialog=document.getElementById('fileCommentsDialog');
	commentsDialogTxt=document.getElementById('commentsLabel');
	commentsDialogTxt.innerHTML="Comments for File " +NO;
	regForm.elements['Comments'].value=document.getElementById("File"+NO +"Comments").value;
	showDropDown('fileCommentsDialog',4,0);
	fileSelected=NO;
}
