/*
 *Checks if an email address is valid, modified from http://javascript.internet.com/forms/check-email.html
*/
function f_isValidEmail(a_sEmail, field)
{
   if (a_sEmail != null && a_sEmail != "")
   {
      /* The following pattern is used to check if the entered e-mail address
         fits the user@domain format.  It also is used to separate the username
         from the domain. */
      var emailPat=/^(.+)@(.+)$/;
      /* The following string represents the pattern for matching all special
         characters.  We don't want to allow special characters in the address.
         These characters include ( ) < > @ , ; : \ " . [ ]    */
      var specialCharsUser="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
      var specialCharsDomain="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]\\'";

      /* The following string represents the range of characters allowed in a
         username or domainname.  It really states which chars aren't allowed. */
      var validCharsUser="\[^\\s" + specialCharsUser + "\]";
      var validCharsDomain="\[^\\s" + specialCharsDomain + "\]";
      /* The following pattern applies if the "user" is a quoted string (in
         which case, there are no rules about which characters are allowed
         and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
         is a legal e-mail address. */
      var quotedUser="(\"[^\"]*\")";
      /* The following pattern applies for domains that are IP addresses,
         rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
         e-mail address. NOTE: The square brackets are required. */
      var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
      /* The following string represents an atom (basically a series of
         non-special characters.) */
      var atomUser=validCharsUser + '+';
      var atomDomain=validCharsDomain + '+';
      /* The following string represents one word in the typical username.
         For example, in john.doe@somewhere.com, john and doe are words.
         Basically, a word is either an atom or quoted string. */
      var wordUser="(" + atomUser + "|" + quotedUser + ")";
      // The following pattern describes the structure of the user
      var userPat=new RegExp("^" + wordUser + "(\\." + wordUser + ")*$");
      /* The following pattern describes the structure of a normal symbolic
         domain, as opposed to ipDomainPat, shown above. */
      var domainPat=new RegExp("^" + atomDomain + "(\\." + atomDomain +")*$");


      /* Finally, let's start trying to figure out if the supplied address is
         valid. */

      /* Begin with the coarse pattern to simply break up user@domain into
         different pieces that are easy to analyze. */
      var matchArray=a_sEmail.match(emailPat);
      if (matchArray==null)
      {
        /* Too many/few @'s or something; basically, this address doesn't
           even fit the general mould of a valid e-mail address. */
      	callAlertWithField("The format of the email address you entered is not valid for email addresses.", field);
      	return false;
      }
      var user=matchArray[1];
      var domain=matchArray[2];

      // See if "user" is valid
      if (user.match(userPat)==null)
      {
          // user is not valid
          callAlertWithField("Email username doesn't seem to be valid.", field);
          return false;
      }

      /* if the e-mail address is at an IP address (as opposed to a symbolic
         host name) make sure the IP address is valid. */
      var IPArray=domain.match(ipDomainPat);
      if (IPArray!=null)
      {
          // this is an IP address
      	  for (var i=1;i<=4;i++)
           {
      	    if (IPArray[i]>255)
             {
      	        callAlertWithField("Email IP address is invalid!", field);
      		     return false;
      	    }
          }
          return true;
      }

      // Domain is symbolic name
      var domainArray=domain.match(domainPat);
      if (domainArray==null)
      {
      	callAlertWithField("Email domain name doesn't seem to be valid.", field);
         return false;
      }

      /* domain name seems valid, but now make sure that it ends in a
         three-letter word (like com, edu, gov) or a two-letter word,
         representing country (uk, nl), and that there's a hostname preceding
         the domain or country. */

      /* Now we need to break up the domain to get a count of how many atoms
         it consists of. */
      var atomPat=new RegExp(atomDomain,"g");
      var domArr=domain.match(atomPat);
      var len=domArr.length;
      var topDomain = domArr[domArr.length-1];
      if ( topDomain.length<2 ) // the address must be greater than 1 char
      {
         callAlertWithField("Email address must end in a domain greater than 1 character.", field);
         return false;
      }

      // Make sure there's a host name preceding the domain.
      if (len<2)
      {
         var errStr="Email address is missing a hostname.";
         callAlertWithField(errStr, field);
         return false;
      }
   }

   // If we've gotten this far, everything's valid!
   return true;
}


function callAlert(alertMessage)
{
	if (typeof spAlert == "undefined")
		alert(alertMessage);
	else
		spAlert(alertMessage);
}

function callAlertWithField(alertMessage, field)
{
	if (typeof spAlert == "undefined") {
        alert(alertMessage);
        field.focus();
		field.select();
    }
    else {
        var okFunc = null;
        if (field) {
            okFunc = hitch({
                field: field,
                ok: function() {
                    this.field.focus();
                    this.field.select();
               	}
            }, 'ok');
        }
	spAlert(alertMessage, null, null, null, null, okFunc);
    }
}

var _selectHeight = 23;

function clearText(field)
{
    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;
}

function checkText(field)
{
	if (field.defaultValue == field.value)
	{
		alert("Please enter a search term");
		field.focus();
		return false;
	}
}

function checkRegion(field)
{
	if (field.selectedIndex == 0)
	{
		alert("Please select a Region");
		field.focus();
		return false;
	}
}

var _forms = document.getElementsByTagName('form');
var inputs = new Array();
var selects = new Array();
var labels = new Array();
var radios = new Array();
var radioLabels = new Array();
var checkboxes = new Array();
var checkboxLabels = new Array();
var buttons = new Array();
var selects = new Array();
var all_selects = false;
var active_select = null;
var agt = navigator.userAgent.toLowerCase();
var isMac = is_mac();
var selectText = "please select";
var IN_CFORMS = true;

function is_mac() {
	if (navigator.appVersion.indexOf("Safari") != -1)
	{
		if(!window.getComputedStyle)
		{
			return true;
		}
	}

	return false;
}

function initCastomForms() {
	if(!document.getElementById) {return false;}
	getElements();
	separateElements();
	replaceRadios();
	//replaceCheckboxes();
	replaceSelects();

	var _selects = document.getElementsByTagName('select');
	var _SelctClassName = [];
	var _nS = 0;
	if (_selects) {
		for (var i = 0; i < _selects.length; i++) {

			// so it doesn't affect all dropdowns on the page, only the Regions one
			if (_selects[i].id.indexOf('drp-regions') != -1) // i.e. it IS the Regions dropdown
			{
				if (_selects[i].className.indexOf('cs-1') != -1)
					_SelctClassName[_nS++] = ' cs-1-drop';
				if (_selects[i].className.indexOf('cs-2') != -1)
					_SelctClassName[_nS++] = ' cs-2-drop'
				if (_selects[i].className.indexOf('cs-3') != -1)
					_SelctClassName[_nS++] = ' cs-3-drop'
				if (_selects[i].className.indexOf('cs-4') != -1)
					_SelctClassName[_nS++] = ' cs-4-drop'
				if (_selects[i].className.indexOf('cs-5') != -1)
					_SelctClassName[_nS++] = ' cs-5-drop'
			}
		}
		for (var i = 0; i < _SelctClassName.length; i++) {
			var _selectDrop = document.getElementById('optionsDiv'+i);
			if (_selectDrop) {
				_selectDrop.className += _SelctClassName[i];
			}
		}
	}
}


// getting all the required elements
function getElements() {
	for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
		for(var nfi = 0; nfi < document.forms[nf].getElementsByTagName("input").length; nfi++) {inputs.push(document.forms[nf].getElementsByTagName("input")[nfi]);}
		for(var nfl = 0; nfl < document.forms[nf].getElementsByTagName("label").length; nfl++) {labels.push(document.forms[nf].getElementsByTagName("label")[nfl]);}
		for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName("select").length; nfs++) {selects.push(document.forms[nf].getElementsByTagName("select")[nfs]);}
	}
}

// separating all the elements in their respective arrays
function separateElements() {
	var r = 0; var c = 0; var t = 0; var rl = 0; var cl = 0; var tl = 0; var b = 0;
	for (var q = 0; q < inputs.length; q++) {
		if(inputs[q].type == "radio") {
			radios[r] = inputs[q]; ++r;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && labels[w].htmlFor == inputs[q].id)
				{
					radioLabels[rl] = labels[w];
					++rl;
				}
			}
		}
		if(inputs[q].type == "checkbox") {
			checkboxes[c] = inputs[q]; ++c;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && (labels[w].htmlFor == inputs[q].id))
				{
					checkboxLabels[cl] = labels[w];
					++cl;
				}
			}
		}
		if((inputs[q].type == "submit") || (inputs[q].type == "button")) {
			buttons[b] = inputs[q]; ++b;
		}
	}
}

//replacing radio buttons
function replaceRadios() {
	for (var q = 0; q < radios.length; q++) {
		radios[q].className = "outtaHere";
		var radioArea = document.createElement("div");
		if(radios[q].checked) {
			radioArea.className = "radioAreaChecked";
		}
		else
		{
			radioArea.className = "radioArea";
		}
		radioArea.id = "myRadio" + q;
		radios[q].parentNode.insertBefore(radioArea, radios[q]);
		radios[q]._ra = radioArea;

		radioArea.onclick = new Function('rechangeRadios('+q+')');
		if (radioLabels[q])
		{
			radioLabels[q].onclick = new Function('rechangeRadios('+q+')');
		}
	}
	return true;
}

//checking radios
function checkRadios(who) {
	var what = radios[who]._ra;
	for(var q = 0; q < radios.length; q++) {
		if((radios[q]._ra.className == "radioAreaChecked")&&(radios[q]._ra.nextSibling.name == radios[who].name))
		{
			radios[q]._ra.className = "radioArea";
		}
	}
	what.className = "radioAreaChecked";
}

//changing radios
function changeRadios(who) {
	if(radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name) {
				radios[q].checked = false;
			}
			radios[who].checked = true;
			checkRadios(who);
		}
	}
}

//rechanging radios
function rechangeRadios(who) {
	if(!radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name)	{
				radios[q].checked = false;
			}
			radios[who].checked = true;
			checkRadios(who);
		}
	}
}

//replacing checkboxes
function replaceCheckboxes() {
	for (var q = 0; q < checkboxes.length; q++) {
		checkboxes[q].className = "outtaHere";
		var checkboxArea = document.createElement("div");
		if(checkboxes[q].checked) {
			checkboxArea.className = "checkboxAreaChecked";
		}
		else {
			checkboxArea.className = "checkboxArea";
		}
		checkboxArea.id = "myCheckbox" + q;
		checkboxes[q].parentNode.insertBefore(checkboxArea, checkboxes[q]);
		checkboxes[q]._ca = checkboxArea;
		checkboxArea.onclick = checkboxArea.onclick2 = new Function('rechangeCheckboxes('+q+')');
		if (checkboxLabels[q])
		{
			checkboxLabels[q].onclick = new Function('changeCheckboxes('+q+')');
		}

		checkboxes[q].onkeydown = checkEvent;
	}
	return true;
}

//checking checkboxes
function checkCheckboxes(who, action) {
	var what = checkboxes[who]._ca;
	if(action == true) {
		what.className = "checkboxAreaChecked";
		what.checked = true;
	}
	if(action == false) {
		what.className = "checkboxArea";
		what.checked = false;
	}
}

//changing checkboxes
function changeCheckboxes(who) {
	if(checkboxes[who].checked) {
		checkCheckboxes(who, false);
	}
	else {
		checkCheckboxes(who, true);
	}
}

//rechanging checkboxes
function rechangeCheckboxes(who) {
	var tester = false;
	if(checkboxes[who].checked == true) {
		tester = false;
	}
	else {
		tester = true;
	}
	checkboxes[who].checked = tester;
	checkCheckboxes(who, tester);
}

//check event
function checkEvent(e) {
	if (!e) var e = window.event;
	if(e.keyCode == 32) {for (var q = 0; q < checkboxes.length; q++) {if(this == checkboxes[q]) {changeCheckboxes(q);}}} //check if space is pressed
}


function replaceSelects() {
	for(var q = 0; q < selects.length; q++) {

		// so it doesn't affect all dropdowns on the page, only the Regions one
		if (selects[q].id.indexOf('drop-regions') != -1) // i.e. it IS the Regions dropdown
		{
			if (!selects[q].replaced && selects[q].offsetWidth)
			{
				selects[q]._number = q;
				//create and build div structure
				var selectArea = document.createElement("div");
				var left = document.createElement("span");
				left.className = "left";
				selectArea.appendChild(left);

				var disabled = document.createElement("span");
				disabled.className = "disabled";
				selectArea.appendChild(disabled);

				selects[q]._disabled = disabled;
				var center = document.createElement("span");
				var button = document.createElement("a");
				var text = document.createTextNode(selectText);
				center.id = "mySelectText"+q;

				var stWidth = selects[q].offsetWidth;
				selectArea.style.width = stWidth + "px";
				if (selects[q].parentNode.className.indexOf("type2") != -1){
					button.href = "javascript:showOptions("+q+",true)";
				} else {
					button.href = "javascript:showOptions("+q+",false)";
				}
				button.className = "selectButton";
				selectArea.className = "selectArea";

				selectArea.className += " " + selects[q].className;
				selectArea.id = "sarea"+q;
				center.className = "center";
				center.appendChild(text);
				selectArea.appendChild(center);
				selectArea.appendChild(button);

				//hide the select field
				selects[q].className += " outtaHere";
				//insert select div
				selects[q].parentNode.insertBefore(selectArea, selects[q]);
				//build & place options div

				var optionsDiv = document.createElement("div");

				var optionsList = document.createElement("ul");
				optionsDiv.innerHTML += "<div class='select-top'><div></div></div>";
				optionsDiv.appendChild(optionsList);

				selects[q]._options = optionsList;

				optionsDiv.style.width = stWidth + "px";
				optionsDiv._parent = selectArea;

				optionsDiv.className = "optionsDivInvisible";
				optionsDiv.id = "optionsDiv"+q;


				populateSelectOptions(selects[q]);
				optionsDiv.innerHTML += "<div class='select-bottom'><div class='select-bottom-left'></div><div class='select-bottom-right'></div></div>";
				document.getElementsByTagName("body")[0].appendChild(optionsDiv);
				selects[q].replaced = true;
			}
			all_selects = true;
		}
	}
}

//collecting select options
function populateSelectOptions(me) {
	me._options.innerHTML = "";

	for(var w = 0; w < me.options.length; w++) {

		var optionHolder = document.createElement('li');
		var optionLink = document.createElement('a');
		var optionTxt = document.createTextNode(me.options[w].text);

		optionLink.href = "javascript:showOptions("+me._number+"); selectMe('"+me.id+"',"+w+","+me._number+");";
		optionLink.appendChild(optionTxt);
		optionHolder.appendChild(optionLink);
		me._options.appendChild(optionHolder);
		//check for pre-selected items
		if(me.options[w].selected) {
			selectMe(me.id,w,me._number);
		}
	}
	if (me.disabled) {
		me._disabled.style.display = "block";
	}
	else {
		me._disabled.style.display = "none";
	}
}

//selecting me
function selectMe(selectFieldId,linkNo,selectNo) {
	selectField = selects[selectNo];
	for(var k = 0; k < selectField.options.length; k++) {
		if(k==linkNo) {
			selectField.options[k].selected = true;
		}
		else {
			selectField.options[k].selected = false;
		}
	}

	//show selected option
	textVar = document.getElementById("mySelectText"+selectNo);
	var newText = document.createTextNode(selectField.options[linkNo].text);
	textVar.replaceChild(newText, textVar.childNodes[0]);
	if (selectField.onchange && all_selects)
		{
			eval(selectField.onchange());
		}
}
//showing options
function showOptions(g) {
		_elem = document.getElementById("optionsDiv"+g);
		if (active_select && active_select != _elem) {
			active_select.className = active_select.className.replace('optionsDivVisible','');
			active_select.className += " optionsDivInvisible";
			active_select.style.height = "auto";
		}
		if(_elem.className.indexOf("optionsDivInvisible") != -1) {
			_elem.style.left = "-9999px";
			_elem.style.top = findPosY(_elem._parent) + _selectHeight + 'px';
			_elem.className = _elem.className.replace('optionsDivInvisible','');
			_elem.className += " optionsDivVisible";
			/*if (_elem.offsetHeight > 200)
			{
				_elem.style.height = "200px";
			}*/
			_elem.style.left = findPosX(_elem._parent) + 'px';

			active_select = _elem;
		}
		else if(_elem.className.indexOf("optionsDivVisible") != -1) {
			_elem.style.height = "auto";
			_elem.className = _elem.className.replace('optionsDivVisible','');
			_elem.className += " optionsDivInvisible";
		}
		//_elem.onmouseout = hideOptions;
}

function findPosY(obj) {
	var posTop = 0;
	while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
	return posTop;
}
function findPosX(obj) {
	var posLeft = 0;
	while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
	return posLeft;
}
window.onload = initCastomForms;