//v1.31
//includes dhtml error messages
var myCookie = document.cookie;
var today = new Date();
var expDate = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000); // plus 365 days

var lastInput;
var errorMsg = "";
var tempErrorMsg = null;

//browser & platform test
var exclude=1;
var agt=navigator.userAgent.toLowerCase();
var win=0;var mac=0;var lin=1;
if(agt.indexOf('win')!=-1){win=1;lin=0;}
if(agt.indexOf('mac')!=-1){mac=1;lin=0;}
var lnx=0;if(lin){lnx=1;}
var ice=0;
var ie=0;var ie4=0;var ie5=0;var ie6=0;var com=0;var dcm;
var op5=0;var op6=0;var op7=0;
var ns4=0;var ns6=0;var ns7=0;var mz7=0;var kde=0;var saf=0;
if(typeof navigator.vendor!="undefined" && navigator.vendor=="KDE"){
	var thisKDE=agt;
	var splitKDE=thisKDE.split("konqueror/");
	var aKDE=splitKDE[1].split("; ");
	var KDEn=parseFloat(aKDE[0]);
	if(KDEn>=2.2){
		kde=1;
		ns6=1;
		exclude=0;
		}
	}
else if(agt.indexOf('webtv')!=-1){exclude=1;}
else if(typeof window.opera!="undefined"){
	exclude=0;
	if(agt.indexOf("opera/5")!=-1||agt.indexOf("opera 5")!=-1){op5=1;}
	if(agt.indexOf("opera/6")!=-1||agt.indexOf("opera 6")!=-1){op6=1;}
	if(agt.indexOf("opera/7")!=-1||agt.indexOf("opera 7")!=-1){op7=1;}
	}
else if(typeof document.all!="undefined"&&!kde){
	exclude=0;
	ie=1;
	if(typeof document.getElementById!="undefined"){
		ie5=1;
		if(agt.indexOf("msie 6")!=-1){
			ie6=1;
			dcm=document.compatMode;
			if(dcm!="BackCompat"){com=1;}
			}
		}
	else{ie4=1;}
	}
else if(typeof document.getElementById!="undefined"){
	exclude=0;
	if(agt.indexOf("netscape/6")!=-1||agt.indexOf("netscape6")!=-1){ns6=1;}
	else if(agt.indexOf("netscape/7")!=-1||agt.indexOf("netscape7")!=-1){ns6=1;ns7=1;}
	else if(agt.indexOf("gecko")!=-1){ns6=1;mz7=1;}
	if(agt.indexOf("safari")!=-1 || (typeof document.childNodes!="undefined" && typeof document.all=="undefined" && typeof navigator.taintEnabled=="undefined")){mz7=0;ns6=1;saf=1;}
	}
else if((agt.indexOf('mozilla')!=-1)&&(parseInt(navigator.appVersion)>=4)){
	exclude=0;
	ns4=1;
	if(typeof navigator.mimeTypes['*']=="undefined"){
		exclude=1;
		ns4=0;
		}
	}
if(agt.indexOf('escape')!=-1){exclude=1;ns4=0;}
if(typeof navigator.__ice_version!="undefined"){exclude=1;ie4=0;}

	
for(i=0; i < document.forms.length; i++)
{
	//find all mybackend.com forms and load persistant values
	var form = document.forms[i];
	if(form.action.indexOf("mybackend.com") > -1)
	{
		//setTimeout("fillForm(form)", 1000); //kludge to get browser to wait for script to load
		fillForm(form);
	}
}

/********************** persistance ***************************/
function getCookie(name) 
{ 
  
  var myCookie = document.cookie;
  var index = myCookie.indexOf(name + "=");
  if (index == -1) 
  	return null;
  index = myCookie.indexOf("=", index) + 1;
  var endstr = myCookie.indexOf(";", index);
  if (endstr == -1) 
  	endstr = myCookie.length;
  return unescape(myCookie.substring(index, endstr));
  
}

function setCookie(name, value) 
{ 
  if (value != null && value != "")
  {
  	var curCookie = name + "=" + escape(value) + "; expires=" + expDate.toGMTString();
  	document.cookie = curCookie; // update cookie
  }
}

function fillForm(form)
{
	var i = 0;
	var value = new String("");
		
	for(i=0; i < form.length; i++)
	{
		value = getCookie(form[i].name)
		if(value != null)
		{
			//cookie has a value for this item
			fillInput(form,form[i],value);
		}
	}
}
function fillInput(form,input,value)
{
	if(input.type == "text" || input.type == "textarea")
	{
		input.value = value;
	}
	else if(input.type == "radio" || input.type == "checkbox")
	{
		
		var list = form.elements[input.name];
		var valid = false;
		var i,j;
		var valueArray;
				
				
		valueArray = value.split(",");
		
		for( i = 0; i < list.length; i++)
		{
			
			for( j=0; j < valueArray.length; j++)
			{
				if ( valueArray[j] == list[i].value)
				{
					list[i].checked = true;
				}
			}
						
		}
	}
	else if(input.type == "select-one")
	{
		for(i=0; i < input.length; i++)
		{
			if(input[i].value == value)
				input.selectedIndex = i;
		}		
	}
}


/********************** form validation ***************************/

//function for Survey Preview Results
function preview(form)
{
	form.preview.value = 1;
	//grab the current page
	form.page.value = document.location.href;
	form.submit();
}
//Open window with progress bar.
function ProgressBar(uploadID)
{
  //var ProgressURL = 'http://mybackend.com/builders/upload/progress-smooth.asp';
  //ProgressURL += '?UploadID=' + uploadID;
  //var v = window.open(ProgressURL,'_blank','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=350,height=150');
}

//function all submitting forms call
function MybackendSubmit(form)
{

	//exclude legacy browsers from advanced functionality
	if (!exclude)
	{
		//upper level browser continue with advanced functionality
		var i = form.length;
		var input;
	
		for(i = 0; i < form.length; i++)
		{
			input = form[i];
			//do validations
			if (input.type == "hidden" || input.type != "submit")
			{
				i = CheckValid(input,i,form);
			}
	
		}
		
		if(errorMsg != "")
		{
			//alert(errorMsg);
			//clear global vars
			errorMsg = "";
			return false;
		}
	}
	
	//grab the current page
	form.page.value = document.location.href;
	return true;
}

function CheckValidOnBlur()
{
	//alert(window.event.srcElement.name);
	var element = window.event.srcElement;
	var i = CheckValid(element,0,element.form);
	//alert(i);
}
//check to make sure free input is valid
function CheckValid(input,index,form)
{
    var validType = input.getAttribute("validation");
	var required = input.getAttribute("required");
	var persist = input.getAttribute("persist");
	var cookieValue = "";
	tempErrorMsg = null;
			
	//multiple inputs relate to the same validations
	//alert("***checking " + input.name + " r=" + required + " v=" + validType);
			
	
	if ( (input.type == "radio" || input.type == "checkbox") && required == "true")
	{
			var list = form.elements[input.name];
			var valid = false;
			var j;
			var cookieValue = "";
			
			//alert("length: " + input.name + " " + form.elements[input.name].length);
			
			for( j = 0; j < list.length; j++)
			{
				//test all in list
				//alert(j + " " + list[j].name + " " + list[j].checked);	
				
				if ( list[j].checked)
				{
					valid = true;
					if(persist == "true")
					{	
						if(cookieValue != "")
						{
							cookieValue = cookieValue + "," + list[j].value;
						}else{
							cookieValue = list[j].value;
						}
					}
				}
				
			}
						
			//alert("index=" + index + "j=" + j);
			if(j != 0)
			{
				index += (j-1);
			}else{
				//test a single checkbox or radio
				if ( input.checked){
					valid = true;
					cookieValue = input.value;
				}
			}
			if( !valid )
			{
				tempErrorMsg = "Required";
				errorMsg += input.getAttribute("alt") + " is required." + '\n';
				errorTip(input,tempErrorMsg);	
			}
			else
				removeTip(input);

	} //end of radio/checkbox validations
	
	else if ( required == "true" )
	{
		if( EmptyTest(input.value) )
		{
			tempErrorMsg = "Required";
			errorMsg += input.getAttribute("alt") + " is required." + '\n';
			errorTip(input,tempErrorMsg);
		}
		else
			removeTip(input);
	}
	
	if ( validType == "numeric" )
	{
		if( !validateNumeric(input.value) )
		{
			tempErrorMsg = "Enter only numbers";
			errorMsg += input.getAttribute("alt") + " must be numeric."  + '\n';
			errorTip(input,tempErrorMsg);
		}
		else
			removeTip(input);
	}
	else if ( validType == "date" )
	{
		//do some other range checking with the qualifiers
		var qualify = input.getAttribute("qualify");

		if( !validateDate(input.value) )
		{
			tempErrorMsg = "Enter a date";
			errorMsg += input.getAttribute("alt") + " must be a date." + '\n';
			errorTip(input,tempErrorMsg);
		}
		else
			removeTip(input);

	}
	else if ( validType == "email" )
	{
		if( !validateEmail(input.value) )
		{
			tempErrorMsg = "Enter a valid email address";
			errorMsg += input.getAttribute("alt") + " must be an email address." + '\n';
			errorTip(input,tempErrorMsg);
		}
		else
			removeTip(input);

	}
	else if ( validType == "usphone" )
	{
		if( !validateUSPhone(input.value) )
		{
			tempErrorMsg = "Enter a phone number";
			errorMsg += input.getAttribute("alt") + " must be a phone number." + '\n';
			errorTip(input,tempErrorMsg);
		}
		else
			removeTip(input);

	}
	else if ( validType == "uszip" )
	{
		if( !validateZip(input.value) )
		{
			tempErrorMsg = "Enter a zip code";
			errorMsg += input.getAttribute("alt") + " must be a zip code." + '\n';
			errorTip(input,tempErrorMsg);
		}
		else
			removeTip(input);
	}	
	
	//set cookie/persist
	if(tempErrorMsg == null && persist == "true")
	{
		
		if ( input.type == "select-one")
			setCookie(input.name,input[input.selectedIndex].value);
		else
			setCookie(input.name,input.value);
	}
	

	return index;
}

function EmptyTest(str)
{
  	//strip all whitespace from string and test
  	if(strip(" \n\r\t",str).length == 0)
		return true;
	else
		return false;
}

function validateNumeric(str){
  str = strip(' \n\r\t',str);
  if(isNaN(str))
	 return false;
  else
	 return true;
}

function validateInteger(str){
  str = strip(' \n\r\t',str);
  if(isNaN(parseInt(str)))
	 return false;
  else
	 return true;
}

function validateDate(str){
  var dateVar = new Date(str);
  if( isNaN(dateVar.valueOf()) )
	 return EmptyTest(str);
  else
	 return true;
}

function validateEmail(str){
  str = strip(" \n\r\t",str);
  if(str.indexOf("@") > -1 && str.indexOf(".") > -1)
	 return true;
  else
 	return EmptyTest(str); 
}

function validateUSPhone(str){
  str = strip("*() -./_\n\r\t\\",str);
  if(str.length == 10 || str.length == 7)
	 return true;
   else
 	return EmptyTest(str); 
}
function validateSSN(str){
  str = strip(" -.\n\r\t",str);
  if(validateInteger(str) && str.length == 9)
	 return true;
  else
 	return EmptyTest(str); 
}
function validateZip(str){
  str = strip("- \n\r\t",str);
  if(validateInteger(str) && (str.length==9 || str.length==5))
  	return true;
  else
 	return EmptyTest(str); 
}

function validateCC(str,type){
  str = strip("-./_\n\r\t\\",str);
  if(type=="1")
	 if(str.charAt(0)!="4")
		return false;
  if(type=="2")
	 if(str.charAt(0)!="5")
		return false;
  if(type=="3")
	 if(str.charAt(0)!="6")
		return false;
  if(type=="4")
	 if(str.charAt(0)!="3")
		return false;
  if(validateInteger(str) &&
	 ((str.length==15&&type=="4") ||
	 str.length==16))
	 return true;
  else
 	return EmptyTest(str); 
}


// Support Functions
function strip(filter,str){
  var i,curChar;
  var retStr = '';
  var len = str.length;
  for(i=0; i<len; i++){
	 curChar = str.charAt(i);
	 if(filter.indexOf(curChar)<0)
	   //not in filter, keep it
		retStr += curChar;
  }
  return retStr;
}

//error tooltips
// global vars
var i, pos, obj, tempObj, tempEle, winSize, extent, scrollHeight;
var imageHtml = "";
var image = "http://www.mybackend.com/includes/error.gif";

//toolTip object
var toolTip = null;
var toolTipParent = null;


//find object position
function getRealPos(ele,dir)
{
	(dir=="x") ? pos = ele.offsetLeft : pos = ele.offsetTop;
	tempEle = ele.offsetParent;
	while(tempEle != null)
	{
		pos += (dir=="x") ? tempEle.offsetLeft : tempEle.offsetTop;
		tempEle = tempEle.offsetParent;
	}
	return pos;
}

//create errorTip 
function errorTip(obj,msg)
{
	//alert(obj + " " + msg);
	tooltip = null;
	toolTipParent = null;
	
		//get window dimensions
		if(typeof window.innerWidth!="undefined")
		{
			winSize = {
				x : window.innerWidth,
				y : window.innerHeight
				};
		}
		else if(typeof document.documentElement.offsetWidth!="undefined")
		{
			winSize = {
				x : document.documentElement.offsetWidth,
				y : document.documentElement.offsetHeight
				};
		}
		else
		{
			winSize = {
				x : document.body.offsetWidth,
				y : document.body.offsetHeight
				};
		}

		//create toolTip
		toolTip = document.createElement('div');
		//add id
		toolTip.setAttribute('id','error' + obj.name);
		//add style
		toolTip.setAttribute('style','');
		toolTip.style.fontFamily = "verdana,helvetica,arial,sans-serif";

		toolTip.style.fontSize = "11px";
		toolTip.style.backgroundColor = "#f7f7f7";
		toolTip.style.border = "1px solid #003";
		toolTip.style.padding = "2px 4px 2px 4px;"
		toolTip.style.color = "#CC0000";
		toolTip.style.position = "absolute";
		toolTip.style.width = "auto";
		toolTip.style.height = "auto";
		toolTip.style.filter = "progid:DXImageTransform.Microsoft.Shadow(color=#666666,direction=135,strength=2)";
		//toolTip.style.MozOpacity = ".25";
	
		//get focussed object co-ordinates
		if(toolTipParent == null)
		{
			var platformX = 5;
			var platformY = 0;
			
			
			if(mac==1 && ie==1)
			{
				platformX += 5;
				platformY += 13;
			}
			
			toolTipParent = {
				x : getRealPos(obj,'x') + platformX,
				y : getRealPos(obj,'y') + platformY
			};
		}

		// offset tooltip from object
		toolTipParent.x += obj.offsetWidth;

		//apply tooltip position
		toolTip.style.left = toolTipParent.x + 'px';
		toolTip.style.top = toolTipParent.y + 'px';

		//toolTip.innerHTML = "<img src=" + image + " height=16 width=16 border=0 align=absmiddle> " + msg;
		toolTip.innerHTML = msg;
		
		//add to document
		document.body.appendChild(toolTip);

		//restrict width
		if(toolTip.offsetWidth > 300)
		{
			toolTip.style.width = '300px';
		}

		//get tooltip extent
		extent = {
				x : toolTip.offsetWidth,
				y : toolTip.offsetHeight
				};

		//if tooltip exceeds window width
		if((toolTipParent.x + extent.x) >= winSize.x)
		{
			//shift tooltip left
			toolTipParent.x -= extent.x;
			toolTip.style.left = toolTipParent.x + 'px';
		}

		//get scroll height
		if(typeof window.pageYOffset!="undefined")
		{
			scrollHeight = window.pageYOffset;
		}
		else if(typeof document.documentElement.scrollTop!="undefined")
		{
			scrollHeight = document.documentElement.scrollTop;
		}
		else
		{
			scrollHeight = document.body.scrollTop;
		}


}

function removeTip(obj)
{
	if(tempErrorMsg == null)
	{
		var id = "error" + obj.name;
		//alert("remove " + id);
		tooltip = document.getElementById(id)
		if(tooltip != null)
		{
			document.body.removeChild(tooltip);
		}
	}
}


window.onload = function()
{
	/*if(typeof document.getElementsByTagName!="undefined")
	{
		//get tags collection
		var allTags = document.getElementsByTagName('*');
		var allTagsLen = allTags.length;

		for (var i=0;i<allTagsLen;i++)
		{
			//if tag has title attribute
			if(allTags[i].name)
			{
				var name = allTags[i].name.toString();
				if(name.indexOf("_") > -1)
				{
					//attach event
					allTags[i].onblur = CheckValidOnBlur;
				}
			}
		}

	}
	*/
}

