window.onload = attachFormHandlers;
var purw = new PortalUrlRewriter();
var gShow; //variable holding the id where feedback will be sent to.
var sUrl = purw.url("/help/formvalidation.php?validationtype=ajax&val=", purw.LINK_TYPE_PLAIN);//url is the page which will be processing all of the information.  it is important to make sure validationtype is ajax
var gErrors = 0; //number of errors is set to none to begin with
var http = getHTTPObject();//trust the engrish



function attachFormHandlers()
{
	var form = document.getElementById('form_one') 

	if (document.getElementsByTagName)//make sure were on a newer browser
	{
		var objInput = document.getElementsByTagName('input');
		var objSelect = document.getElementsByTagName('select');
		var objTextArea = document.getElementsByTagName('textarea');
		for (var iCounter=0; iCounter<objInput.length; iCounter++){
			objInput[iCounter].onblur = function(){return validateMe(this.id);} //attach the onchange to each input field
		}
		for (var iCounter=0; iCounter<objSelect.length; iCounter++){
			objSelect[iCounter].onblur = function(){return validateSelect(this.id);} //attach the onchange to each select field
		}
		for (var iCounter=0; iCounter<objTextArea.length; iCounter++){
			objTextArea[iCounter].onblur = function(){return validateMe(this.id);} //attach the onchange to each textarea field
		}
	}
	form.onsubmit = function(){return validate();} //attach validate() to the form
}




/*validateMe is the function called with onblur each time the user leaves the input box
passed into it is the value entered, the rules (which you could create your own), and the id of the area the results will show in*/
function validateMe(objId) {
	sVal = document.getElementById(objId).value; //get value inside of input field
	sRules = objId.split('_'); // get all the rules from the input box id
	sRequired = sRules[1]; // determines if field is required or not
	sTypeCheck = sRules[2]; //typecheck are additional validation rules (ie. email, phone, date)
    gShow = sRules[3]; //gShow is the div id where feedback is sent to.
  
	//sends the rules and value to the php page to be validated
	http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, true);
  
	http.onreadystatechange = handleHttpResponse; 	// handle what to do with the feedback 
	http.send(null);  
}

function validateSelect(objId) {
	sVal = document.getElementById(objId).options[document.getElementById(objId).selectedIndex].innerHTML; //get value inside of select field
	sRules = objId.split('_'); // get all the rules from the input box id
	sRequired = sRules[1]; // determines if field is required or not
	sTypeCheck = sRules[2]; //typecheck are additional validation rules (ie. email, phone, date)
    gShow = sRules[3]; //gShow is the div id where feedback is sent to.
	//sends the rules and value to the php page to be validated
	http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, false);
	
	// Changed By: Joseph Lemke - Curt had me change the true on the last argument to false to async stuff
//	http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, true);
  
	http.onreadystatechange = handleHttpResponse; 	// handle what to do with the feedback 
	http.send(null);  
}


function handleHttpResponse() {
	//if the process is completed, decide to do with the returned data
	if (http.readyState == 4) 
  	{
  		sResults = http.responseText.split(","); //results is now whatever the feedback from the php page was
		//whatever the variable glo_show's (usermsg for example) innerHTML holds, is now whatever  was returned by the php page. 
		purw = new PortalUrlRewriter();
    	if(strip_tags(http.responseText, '') == "Valid"){
    		document.getElementById(gShow).innerHTML = "<img src=\"" + purw.url("/images/validation-good.gif", purw.LINK_TYPE_ASSET) + "\" />";
//    		document.getElementById(gShow).innerHTML = "<img src=\"images/good_val.gif\" />";
    	}else{
    		document.getElementById(gShow).innerHTML = "<img src=\"" + purw.url("/images/validation-error.gif", purw.LINK_TYPE_ASSET) + "\" />";
    	}
//		document.getElementById(gShow).appendChild(document.createTextNode(sResults[0]));
  	}
}

function strip_tags(str, allowed_tags) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
 
    var key = '', tag = '', allowed = false;
    var matches = allowed_array = [];
    
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
 
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
  
    str += '';
 
    // Match tags
    matches = str.match(/(<\/?[^>]+>)/gi);
 
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
        // Save HTML tag
        html = matches[key].toString();
        // Is tag not in allowed list? Remove from str!
        allowed = false;
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 			if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
    return str;
}

function validate()
{
var tables; 

tables = document.getElementsByTagName('div')

	for (i=0; i<tables.length; i++)//loop through all the <div> elements 
	{
		// if the class name of that div element is rules check to see if there are error warnings
		if (tables[i].className == "rules")
		{
			//if there is a thank you or its blank then it passes
			if (tables[i].innerHTML == 'Valid' || tables[i].innerHTML == '' )
			{
				tables[i].innerHTML = "<img src=\"../../images/checkmark.jpg\" />";
//				tables[i].innerHTML = "<img src=\"images/good_val.gif\" />";
//				tables[i].style.color = '#00FF00';//the color is changed to black or stays black
			}
			else
			{
				gErrors = gErrors + 1; //the error count increases by 1
//				tables[i].style.color = '#ff0000';//error messages are changed to red
				tables[i].innerHTML = "<img src=\"images/bad_val.gif\" />";
			}
		}
	}
		
	if (gErrors > 0)
	{
		//if there are any errors give a message
		alert ("Please make sure all fields are properly completed.  Errors are marked in red!");
		gErrors = 0;// reset errors to 0
		return false;
	}
	else return true;

}


function getHTTPObject() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try 
		{
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
		xmlhttp = false;
		}
	}
	return xmlhttp;
}

//this sets focus on load -- it is static.  Change element to grab focus or comment out
function setFocus(){
	document.getElementById("validate_required_none_fNameErr").focus();
}
