// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function tab_toggle(which) {
	myBlock = document.getElementById(which);
	
	if (myBlock.className.match(" closed")) {
		myBlock.className = myBlock.className.replace(" closed", " open");
	} else {
		myBlock.className = myBlock.className.replace(" open", " closed");
	}
}
	
function validateTextLength( text_id, error_id, max){

	valid = true;
  
	text_string = $(text_id).value.replace('\n', ' ');
	tokens = text_string.split(" ")
	for( var i = 0; i < tokens.length; i++){
	
		if( tokens[i].length > max )
		{	
			valid = false;
			$(error_id).focus();
			$(error_id).innerHTML = "Max word length is " + max + " characters"
			break;
		}
	}
	
	return valid;
}	

function populateHeightTo( height_from, height_to, max_height){
	
	var selected_to = height_to.options[height_to.selectedIndex].value;

	height_to.options.length = 0;
	for( var i = height_from.options[height_from.selectedIndex].value ; i <= max_height; i++){
		option = document.createElement("option");
        option.value = i;
        option.text = HEIGHTS[0].name;
		
		if( i == selected_to)
			option.selected = true;
		
        height_to.options[height_to.options.length] = option;
	}
}
function populateHeightFrom( height_from, height_to, min_height){
	
	var selected_from = height_from.options[height_from.selectedIndex].value;

	height_from.options.length = 0;
	for( var i = min_height; i <= height_to.options[height_to.selectedIndex].value; i++){
		option = document.createElement("option");
        option.value = i;
        option.text = HEIGHTS[0].name;
		
		if( i == selected_from)
			option.selected = true;
		
        height_from.options[height_from.options.length] = option;
	}
}


	
function populateAgeFrom( age_from, age_to){
	
	var selected_from = age_from.options[age_from.selectedIndex].value;

	age_from.options.length = 0;
	for( var i = 18; i <= age_to.options[age_to.selectedIndex].value; i++){
		option = document.createElement("option");
        option.value = i;
        option.text = i;
		
		if( i == selected_from)
			option.selected = true;
		
        age_from.options[age_from.options.length] = option;
	}
}	
function populateAgeTo( age_from, age_to){
	
	var selected_to = age_to.options[age_to.selectedIndex].value;
    var selected_from = age_from.options[age_from.selectedIndex].value;

    if (selected_from < 18)
	   selected_from = 18;

	age_to.options.length = 0;
	for( var i = selected_from; i <= 99; i++){
		option = document.createElement("option");
        option.value = i;
        option.text = i;
		
		if( i == selected_to)
			option.selected = true;
		
        age_to.options[age_to.options.length] = option;
	}
}	

function tab_toggleAll(which, onoff) {
	myParent = document.getElementById(which);

	for (var i = 0; i < myParent.getElementsByTagName("div").length; i++) {
		thisID = myParent.getElementsByTagName("div")[i].id;
		
		if (thisID != "") {
			currentDIV = document.getElementById(thisID);
			if (onoff == 1) {
				document.getElementById("expand").className = "none";
				document.getElementById("collapse").className = "";
				currentDIV.className = currentDIV.className.replace(" closed", " open");
			} else {
				document.getElementById("expand").className = "";
				document.getElementById("collapse").className = "none";
				currentDIV.className = currentDIV.className.replace(" open", " closed");
			}
		}
	}
}

var textSize = loadUserSettings('fontsize');
Event.observe(window, 'load', function() { setFontSize(textSize); });

function setFontSize( fontSize){
	document.getElementById('content').style.fontSize = fontSize + "%";	
}

function increaseTextSize(){
	textSize = parseInt(textSize) + 10;
	saveUserSettings( 'fontsize', textSize)
	setFontSize(textSize);
}

function decreaseTextSize(){
	textSize = parseInt(textSize) - 10;
	saveUserSettings( 'fontsize', textSize)
	setFontSize(textSize);
}

function loadUserSettings( name)
{
   return loadSaveUsersettings('load', name);
}

function saveUserSettings( name, value)
{
   return loadSaveUsersettings('save', name, value);
}

function loadSaveUsersettings( type, name, value)
{
 
   if (type == "save")
   {   
	   var date = new Date(2099, 12, 31);
       var setCookie = name + "=" + escape(value) + "; expires=" + date.toGMTString() + "; path=/";
       document.cookie = setCookie;
   }
   else
   {    
	   var aCookies = document.cookie.split("; ");
       
	   for (var i=0; i < aCookies.length; i++){
	   	
           var sCookie = aCookies[i].split("=");
           
		   if (name == sCookie[0])
			   return unescape(sCookie[1]);
       }
	   
	   return 100;
   }
}

// moveOptionsAcross
//
// Move selected options from one select list to another
//
var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);

function addOption(theSel, theText, theValue)
{
  var newOpt = new Option(theText, theValue);
  var selLength = theSel.length;
  if (theText != "" && theText != "Doesn't Matter" && theText != "Please select a language.")
{
  theSel.options[selLength] = newOpt;
}
}

function deleteOption(theSel, theIndex)
{ 
  var selLength = theSel.length;
  if(selLength>0)
  {
    theSel.options[theIndex] = null;
  }
}


function moveOptions(theSelFrom, theSelTo)
{
	var selLength = theSelFrom.length;
	  var selectedText = new Array();
	  var selectedValues = new Array();
	  var selectedCount = 0;

	  var i;



	  // Find the selected Options in reverse order
	  // and delete them from the 'from' Select.
	 if(theSelTo.options[0].text == "Doesn't Matter" || theSelTo.options[0].text == "Please select a language.")
	{
		deleteOption(theSelTo, 0)
	}
	
	if (!theSelFrom.options.length)
	{
		option = document.createElement("option");
		option.value = "0";
		option.text = "Doesn't Matter";
		theSelTo.options[theSelFrom.options.length] = option;
	}
	
	
	  for(i=selLength-1; i>=0; i--)
	  {
	    if(theSelFrom.options[i].selected)
	    {
	      selectedText[selectedCount] = theSelFrom.options[i].text;
	      selectedValues[selectedCount] = theSelFrom.options[i].value;
	      deleteOption(theSelFrom, i);
	      selectedCount++;
	    }
	  }

	  // Add the selected text/values in reverse order.
	  // This will add the Options to the 'to' Select
	  // in the same order as they were in the 'from' Select.
	  for(i=selectedCount-1; i>=0; i--)
	  {
	    addOption(theSelTo, selectedText[i], selectedValues[i]);
	  }

	  if(NS4) history.go(0);

}
function moveOptionsWrapper(fromSelectList, toSelectList, direction)
{
	var c = moveOptions(fromSelectList, toSelectList);

	if (c && direction)
	{
		for (var i = 0; i < toSelectList.options.length; i++)
		{
			
			if (!toSelectList.options[i].value.length)
			{
				toSelectList.removeChild(toSelectList.options[i]);
				i--;
			}
		}
	}
	if (!direction && !fromSelectList.options.length)
	{
		option = document.createElement("option");
		option.value = "0";
		option.text = "Doesn't Matter";
		fromSelectList.options[fromSelectList.options.length] = option;
	}
}

function selectAllOptions(selStr)
{
  var selObj = document.getElementById(selStr);
  if (selObj.options[0].text != "Doesn't Matter"){
  for (var i=0; i<selObj.options.length; i++) {
    selObj.options[i].selected = true;
  }
 }
}


function hideShowSelect( select, div){
					
	if (select.options.length > 1)
	    div.style.display = 'block';
	else
		div.style.display = 'none';	
				
}

function isdefined( variable)
{
    return (typeof variable) == "undefined" ?  false: true;
}
	
function populate( a, b, selectedChoices, choices, suppressDoesntMatter){
	
	var index = 0;	
	
	if( suppressDoesntMatter === undefined)
	   suppressDoesntMatter = false;
	
	for (var i = 0; i < choices.length; i++)
	{
		option = document.createElement("option");
		option.__meta = { position: i};
		option.value = choices[i][1];
		option.text = choices[i][0];
        
		selected = false;
		for (var k = 0, l = selectedChoices.length; k < l; k++){
			
			if (selectedChoices[k] && option.value == selectedChoices[k][1] )
			{
				selected = true;
				break;
			}
		}

		if (selected)
			b.options[b.options.length] = option;	
		else
			a.options[a.options.length] = option;
		
		index++;
	};
	
	if (!b.options.length && !suppressDoesntMatter) {
	    option = document.createElement("option");
		option.value = "";
		option.text = "Doesn't Matter";
		b.options[b.options.length] = option;	
	};
	   
}	
	
var dependent_select_interface = function(a1, a2, b1, b2, a_ids, b_ids, data, zipHack)
{
	this.a1 = $(a1);
	this.a2 = $(a2);
	this.b1 = $(b1);
	this.b2 = $(b2);
	this.data = data;
	this.zipHack = zipHack;

	this.find_a_by_id = function(id)
	{
		for (a_id in this.data)
		{
			if (this.data[a_id].id == id)
			{
				return this.data[a_id];
			}
		}
		return null;
	}
	this.find_b_by_id = function(id)
	{
		for (a_id in this.data)
		{
			for (b_id in this.data[a_id].children)
			{
				if (this.data[a_id].children[b_id].id == id)
				{
					return {a: this.data[a_id], b: this.data[a_id].children[b_id]};
				}
			}
		}
		return null;
	}

	this.populate = function(a_ids, b_ids)
	{
		var index = 0;
		
		for (a_id in this.data)
		{
			option = document.createElement("option");
			// option.__meta = { position: index, a: this.data[a_id]};
			option.value = this.data[a_id].id;
			option.text = this.data[a_id].name;

			selected = false;
			for (var i = 0, l = a_ids.length; i < l; i++)
			{
				if (a_id == a_ids[i])
				{
					selected = true;
					break;
				}
			}

			if (selected)
			{
				this.a2.options[this.a2.options.length] = option;
			}
			else
			{
				this.a1.options[this.a1.options.length] = option;
			}
			
			index++;
		}

		for (i = 0, l = b_ids.length; i < l; i++)
		{
			ret = this.find_b_by_id(b_ids[i]);
			if (ret)
			{	
				option = document.createElement("option");
				option.__meta = {position: index, a: ret.a, b: ret.b};
				option.value = ret.b.id;
				option.text = ret.b.name;
				this.b2.options[this.b2.options.length] = option;
			}
		}
	
		this.update();
	}

	this.update = function(direction)
	{
		selected_a_ids = [];
		for (var i = 0, l = this.a2.options.length; i < l; i++)
		{
			if (this.a2.options[i].value.length)
			{
				selected_a_ids[selected_a_ids.length] = this.a2.options[i].value;
			}
		}

		if (!direction)
		{
			for (i = 0; i < this.b2.options.length; i++)
			{
				ok = false;
				for (j = 0, m = selected_a_ids.length; j < m; j++)
				{
					if (this.b2.options[i].value.length && this.b2.options[i].__meta.a.id == selected_a_ids[j])
					{
						ok = true
						break;
					}
				}
				if (!ok)
				{
					this.b2.removeChild(this.b2.options[i]);
					i--;
				}
			}
			
			if (!this.b2.options.length){
				option = document.createElement("option");
				option.value = "";
				option.text = "Doesn't Matter";
				this.b2.options[this.b2.options.length] = option;
			}
		}

		while(this.b1.firstChild) { this.b1.removeChild(this.b1.firstChild) };
		for (var i = 0, l = this.a2.options.length; i < l; i++)
		{
			if (this.a2.options[i].value.length)
			{
				count = 0;
				for (var j = 0, k = this.data[this.a2.options[i].value].children.length; j < k; j++)
				{
					ok = true;
					for (iii = 0, lll = this.b2.options.length; iii < lll; iii++)
					{
						if (this.b2.options[iii].value == this.data[this.a2.options[i].value].children[j].id)
						{
							ok = false;
							break;
						}
					}
					if (ok)
					{
						count++;
						var pos = (( this.b1.options.length) ? this.b1.options.length : 0);
						
						option = document.createElement("option");
						option.__meta = {position: pos, a: this.data[this.a2.options[i].value], b: this.data[this.a2.options[i].value].children[j]}
						option.value = this.data[this.a2.options[i].value].children[j].id;
						option.text = this.data[this.a2.options[i].value].children[j].name;

						this.b1.options[this.b1.options.length] = option;
					}
				}
				if (count && i < (l - 1))
				{
					option = document.createElement("option");
					option.value = '';
					option.text = '----------';
					option.__meta = {position: 999999}
					this.b1.options[this.b1.options.length] = option;
				}
				if (this.zipHack && this.zipHack[this.a2.options[i].value])
				{
					$(this.zipHack[this.a2.options[i].value]).style.display = 'block';
				}
			}
		}

		for (key in this.zipHack)
		{
			tmp = $(this.zipHack[key]);
			if (tmp)
			{
				ok = false;
				for (var i = 0; i < this.a2.options.length;  i++)
				{
					if (this.a2.options[i].value == key)
					{
						ok = true;
						break;
					}
				}
				tmp.style.display = ok ? 'block' : 'none';
			}
		}

		this.b1.parentNode.parentNode.parentNode.style.display = ((this.b1.options.length) ? 'block' : 'none');
	}

	this.populate(a_ids, b_ids);
};

var default_checkbox_interface = function(fields)
{
	var scopeThis = this;

	this.fields = [];
	for (var i = 0, l = fields.length; i < l; i++)
	{
		tmp = $(fields[i]);
		tmp.observe
		(
			'click',
			function(evt)
			{
				var el = Event.element(evt);

				dm = (el.id == scopeThis.fields[0].id);

				var c = 0;
				for (var ii = 1, ll = scopeThis.fields.length; ii < ll; ii++)
				{
					if (dm)
					{
						scopeThis.fields[ii].checked = false;
					}
					else
					{
						c += scopeThis.fields[ii].checked ? true : false;
					}
				}
				scopeThis.fields[0].checked = c ? false : true;
			}
		);
		this.fields[this.fields.length] = tmp;
	}
	return this;
}

Event.observe(window,'load', function() {
  new ClearOnSubmit($$('input.clearonfocus').map(function(element) {
      return new ClearOnFocus(element);
  }))
})



var ClearOnSubmit = Class.create();
Object.extend(ClearOnSubmit.prototype, {
  initialize: function(clearOnFocusElements) {
    if(clearOnFocusElements.size() > 0) {
      this.clearOnFocusElements = clearOnFocusElements;
      this.form = $(this.clearOnFocusElements.first().element.up('form'));
      this.originalOnSubmit = this.form.onsubmit;
      this.form.onSubmit = function(){return false};
      this.form.observe('submit', this.onSubmit.bind(this));
    }
  },
  onSubmit: function(event) {
    this.clearOnFocusElements.each(function(element) {
      element.onFocus();
    })
	  // This was causing the submit event to fire twice.
	 if (this.originalOnSubmit) {
	 	this.originalOnSubmit.bind(this.form);
	 }
  }
})

var ClearOnFocus = Class.create();
Object.extend(ClearOnFocus.prototype, { 
  initialize: function(element) { 
    this.element = $(element);
    this.originalValue = $F(element);
    this.element.observe('blur', this.onBlur.bind(this));
    this.element.observe('focus', this.onFocus.bind(this));
  }, 
  onFocus: function(event) { 
    if($F(this.element) == this.originalValue) { 
      this.element.value = '';
      this.element.removeClassName('clearonfocus');
    } 
  }, 
  onBlur: function(event) { 
    if($F(this.element).match(/^\s*$/)) { 
      this.element.value = this.originalValue;
      this.element.addClassName('clearonfocus');
    } 
  } 
})

/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
    highlightEndTag = "</font>";
  }
  
  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
    
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  
  return newText;
}

/*
* Sets the value of the submitObj to the sum of all the options
* in the selectValuesObj object. See languages on edit my
* profile for example of usage. 
*/
function sumSelectValues( selectValuesObj, submitObj){
		
	var submitValue = 0;
	
	for (var i = 0; i < selectValuesObj.length; i++) {
		
		value =  parseInt(selectValuesObj.options[i].value);
		
		if (!isNaN(value))
            submitValue += value

	}
	
	submitObj.value = submitValue;
}


function get_castes(ele){
	
	var strParams = 'search[criteria_data][religion]['
	  var selObj = document.getElementById(ele);
	  // if (selObj.options[0].text != "Doesn't Matter"){
	  for (var i=0; i<selObj.options.length; i++) {
		selObj.options[i].selected = true;
	    strParams += selObj.options[i].value;
		if (i< selObj.options.length - 1) {
			strParams += ", "
		}
	  }
	strParams += "]"

	new Ajax.Request('/search/update_castes', {
		asynchronous:true, evalScripts:true, parameters: strParams});
}

function get_states(ele){
	
	var strParams = 'contact_filter[country_ids]['
	  var selObj = document.getElementById(ele);
	  // if (selObj.options[0].text != "Doesn't Matter"){
	  for (var i=0; i<selObj.options.length; i++) {
		selObj.options[i].selected = true;
	    strParams += selObj.options[i].value;
		if (i< selObj.options.length - 1) {
			strParams += ", "
		}
	  }
	strParams += "]"

	new Ajax.Request('/profile/update_states', {
		asynchronous:true, evalScripts:true, parameters: strParams});
}

/*
 * This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted.
 */
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag, bodyTextElement)
{
  // if the treatAsPhrase parameter is true, then we should search for 
  // the entire phrase that was entered; otherwise, we will split the
  // search string so that each word is searched for and highlighted
  // individually
  if (bodyTextElement == null)
      return
  
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(",");
  }
  
  var bodyText = bodyTextElement.innerHTML;
  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }
  
  bodyTextElement.innerHTML = bodyText;
  return true;
}

function jumpTo(url) {
	location.href = url;
}

	function update_length_display(field,display,minlength,maxlength,suppressClasses){
		scrollTop = 0
		if (field.scrollTop) {
			scrollTop = field.scrollTop
		}
		field.value = $F(field).replace(/[\n|\r]{3,}/g,'\n\n');
		if ($F(field).length > maxlength) {
			field.value = $F(field).substr(0,maxlength);
		}
		if ($F(field).length <= maxlength && $F(field).length > minlength && suppressClasses != 1) {
			field.addClassName('LV_valid_field');
			field.removeClassName('LV_invalid_field');
		} else if (suppressClasses != 1) {
			field.addClassName('LV_invalid_field');
			field.removeClassName('LV_valid_field');
		}
	
		display.update(maxlength - $F(field).length);
		if (scrollTop > 0) {
			field.scrollTop = scrollTop;
		}
	}
	
	function checkWordLength(field,maxlength) {
		if (!maxlength) {
			maxLength = 50;
		}
		words = field.value.split(/[ |\r|\n]/i);
		wordsLength = words.length;
		for (i=0;i<words.length-1;i++) {
			if (words[i].length >= maxLength) {
				//if (window.console) { window.console.log("word length:" + words[i].length)}
				break;
				return false;
			}
		}
	}
	
	
	// LiveValidation 1.3 (prototype.js version)
	// Copyright (c) 2007-2008 Alec Hill (www.livevalidation.com)
	// LiveValidation is licensed under the terms of the MIT License
	var LiveValidation=Class.create();Object.extend(LiveValidation,{VERSION:"1.3 prototype",TEXTAREA:1,TEXT:2,PASSWORD:3,CHECKBOX:4,SELECT:5,FILE:6,massValidate:function(C){var D=true;for(var B=0,A=C.length;B<A;++B){var E=C[B].validate();if(D){D=E;}}return D;}});LiveValidation.prototype={validClass:"LV_valid",invalidClass:"LV_invalid",messageClass:"LV_validation_message",validFieldClass:"LV_valid_field",invalidFieldClass:"LV_invalid_field",initialize:function(B,A){if(!B){throw new Error("LiveValidation::initialize - No element reference or element id has been provided!");}this.element=$(B);if(!this.element){throw new Error("LiveValidation::initialize - No element with reference or id of '"+B+"' exists!");}this.elementType=this.getElementType();this.validations=[];this.form=this.element.form;this.options=Object.extend({validMessage:"Thankyou!",onValid:function(){this.insertMessage(this.createMessageSpan());this.addFieldClass();},onInvalid:function(){this.insertMessage(this.createMessageSpan());this.addFieldClass();},insertAfterWhatNode:this.element,onlyOnBlur:false,wait:0,onlyOnSubmit:false},A||{});var C=this.options.insertAfterWhatNode||this.element;this.options.insertAfterWhatNode=$(C);Object.extend(this,this.options);if(this.form){this.formObj=LiveValidationForm.getInstance(this.form);this.formObj.addField(this);}this.boundFocus=this.doOnFocus.bindAsEventListener(this);Event.observe(this.element,"focus",this.boundFocus);if(!this.onlyOnSubmit){switch(this.elementType){case LiveValidation.CHECKBOX:this.boundClick=this.validate.bindAsEventListener(this);Event.observe(this.element,"click",this.boundClick);case LiveValidation.SELECT:case LiveValidation.FILE:this.boundChange=this.validate.bindAsEventListener(this);Event.observe(this.element,"change",this.boundChange);break;default:if(!this.onlyOnBlur){this.boundKeyup=this.deferValidation.bindAsEventListener(this);Event.observe(this.element,"keyup",this.boundKeyup);}this.boundBlur=this.validate.bindAsEventListener(this);Event.observe(this.element,"blur",this.boundBlur);}}},destroy:function(){if(this.formObj){this.formObj.removeField(this);this.formObj.destroy();}Event.stopObserving(this.element,"focus",this.boundFocus);if(!this.onlyOnSubmit){switch(this.elementType){case LiveValidation.CHECKBOX:Event.stopObserving(this.element,"click",this.boundClick);case LiveValidation.SELECT:case LiveValidation.FILE:Event.stopObserving(this.element,"change",this.boundChange);break;default:if(!this.onlyOnBlur){Event.stopObserving(this.element,"keyup",this.boundKeyup);}Event.stopObserving(this.element,"blur",this.boundBlur);}}this.validations=[];this.removeMessageAndFieldClass();},add:function(A,B){this.validations.push({type:A,params:B||{}});return this;},remove:function(A,B){this.validations=this.validations.reject(function(C){return(C.type==A&&C.params==B);});return this;},deferValidation:function(A){if(this.wait>=300){this.removeMessageAndFieldClass();}if(this.timeout){clearTimeout(this.timeout);}this.timeout=setTimeout(this.validate.bind(this),this.wait);},doOnBlur:function(){this.focused=false;this.validate();},doOnFocus:function(){this.focused=true;this.removeMessageAndFieldClass();},getElementType:function(){switch(true){case (this.element.nodeName.toUpperCase()=="TEXTAREA"):return LiveValidation.TEXTAREA;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="TEXT"):return LiveValidation.TEXT;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="PASSWORD"):return LiveValidation.PASSWORD;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="CHECKBOX"):return LiveValidation.CHECKBOX;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="FILE"):return LiveValidation.FILE;case (this.element.nodeName.toUpperCase()=="SELECT"):return LiveValidation.SELECT;case (this.element.nodeName.toUpperCase()=="INPUT"):throw new Error("LiveValidation::getElementType - Cannot use LiveValidation on an "+this.element.type+" input!");default:throw new Error("LiveValidation::getElementType - Element must be an input, select, or textarea!");}},doValidations:function(){this.validationFailed=false;for(var C=0,A=this.validations.length;C<A;++C){var B=this.validations[C];switch(B.type){case Validate.Presence:case Validate.Confirmation:case Validate.Acceptance:this.displayMessageWhenEmpty=true;this.validationFailed=!this.validateElement(B.type,B.params);break;default:this.validationFailed=!this.validateElement(B.type,B.params);break;}if(this.validationFailed){return false;}}this.message=this.validMessage;return true;},validateElement:function(A,C){var D=(this.elementType==LiveValidation.SELECT)?this.element.options[this.element.selectedIndex].value:this.element.value;if(A==Validate.Acceptance){if(this.elementType!=LiveValidation.CHECKBOX){throw new Error("LiveValidation::validateElement - Element to validate acceptance must be a checkbox!");}D=this.element.checked;}var E=true;try{A(D,C);}catch(B){if(B instanceof Validate.Error){if(D!==""||(D===""&&this.displayMessageWhenEmpty)){this.validationFailed=true;this.message=B.message;E=false;}}else{throw B;}}finally{return E;}},validate:function(){if(!this.element.disabled){var A=this.doValidations();if(A){this.onValid();return true;}else{this.onInvalid();return false;}}else{return true;}},enable:function(){this.element.disabled=false;return this;},disable:function(){this.element.disabled=true;this.removeMessageAndFieldClass();return this;},createMessageSpan:function(){var A=document.createElement("span");var B=document.createTextNode(this.message);A.appendChild(B);return A;},insertMessage:function(B){this.removeMessage();var A=this.validationFailed?this.invalidClass:this.validClass;if((this.displayMessageWhenEmpty&&(this.elementType==LiveValidation.CHECKBOX||this.element.value==""))||this.element.value!=""){$(B).addClassName(this.messageClass+(" "+A));if(nxtSibling=this.insertAfterWhatNode.nextSibling){this.insertAfterWhatNode.parentNode.insertBefore(B,nxtSibling);}else{this.insertAfterWhatNode.parentNode.appendChild(B);}}},addFieldClass:function(){this.removeFieldClass();if(!this.validationFailed){if(this.displayMessageWhenEmpty||this.element.value!=""){if(!this.element.hasClassName(this.validFieldClass)){this.element.addClassName(this.validFieldClass);}}}else{if(!this.element.hasClassName(this.invalidFieldClass)){this.element.addClassName(this.invalidFieldClass);}}},removeMessage:function(){if(nxtEl=this.insertAfterWhatNode.next("."+this.messageClass)){nxtEl.remove();}},removeFieldClass:function(){this.element.removeClassName(this.invalidFieldClass);this.element.removeClassName(this.validFieldClass);},removeMessageAndFieldClass:function(){this.removeMessage();this.removeFieldClass();}};var LiveValidationForm=Class.create();Object.extend(LiveValidationForm,{instances:{},getInstance:function(A){var B=Math.random()*Math.random();if(!A.id){A.id="formId_"+B.toString().replace(/\./,"")+new Date().valueOf();}if(!LiveValidationForm.instances[A.id]){LiveValidationForm.instances[A.id]=new LiveValidationForm(A);}return LiveValidationForm.instances[A.id];}});LiveValidationForm.prototype={initialize:function(A){this.element=$(A);this.fields=[];this.oldOnSubmit=this.element.onsubmit||function(){};this.element.onsubmit=function(C){var B=(LiveValidation.massValidate(this.fields))?this.oldOnSubmit.call(this.element,C)!==false:false;if(!B){Event.stop(C);}}.bindAsEventListener(this);},addField:function(A){this.fields.push(A);},removeField:function(A){this.fields=this.fields.without(A);},destroy:function(A){if(this.fields.length!=0&&!A){return false;}this.element.onsubmit=this.oldOnSubmit;LiveValidationForm.instances[this.element.id]=null;return true;}};var Validate={Presence:function(A,B){var C=Object.extend({failureMessage:"Can't be empty!"},B||{});if(A===""||A===null||A===undefined){Validate.fail(C.failureMessage);}return true;},Numericality:function(B,C){var A=B;var B=Number(B);var C=C||{};var D={notANumberMessage:C.notANumberMessage||"Must be a number!",notAnIntegerMessage:C.notAnIntegerMessage||"Must be an integer!",wrongNumberMessage:C.wrongNumberMessage||"Must be "+C.is+"!",tooLowMessage:C.tooLowMessage||"Must not be less than "+C.minimum+"!",tooHighMessage:C.tooHighMessage||"Must not be more than "+C.maximum+"!",is:((C.is)||(C.is==0))?C.is:null,minimum:((C.minimum)||(C.minimum==0))?C.minimum:null,maximum:((C.maximum)||(C.maximum==0))?C.maximum:null,onlyInteger:C.onlyInteger||false};if(!isFinite(B)){Validate.fail(D.notANumberMessage);}if(D.onlyInteger&&((/\.0+$|\.$/.test(String(A)))||(B!=parseInt(B)))){Validate.fail(D.notAnIntegerMessage);}switch(true){case (D.is!==null):if(B!=Number(D.is)){Validate.fail(D.wrongNumberMessage);}break;case (D.minimum!==null&&D.maximum!==null):Validate.Numericality(B,{tooLowMessage:D.tooLowMessage,minimum:D.minimum});Validate.Numericality(B,{tooHighMessage:D.tooHighMessage,maximum:D.maximum});break;case (D.minimum!==null):if(B<Number(D.minimum)){Validate.fail(D.tooLowMessage);}break;case (D.maximum!==null):if(B>Number(D.maximum)){Validate.fail(D.tooHighMessage);}break;}return true;},Format:function(A,B){var A=String(A);var C=Object.extend({failureMessage:"Not valid!",pattern:/./,negate:false},B||{});if(!C.negate&&!C.pattern.test(A)){Validate.fail(C.failureMessage);}if(C.negate&&C.pattern.test(A)){Validate.fail(C.failureMessage);}return true;},Email:function(A,B){var C=Object.extend({failureMessage:"Must be a valid email address!"},B||{});Validate.Format(A,{failureMessage:C.failureMessage,pattern:/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i});return true;},Length:function(A,B){var A=String(A);var B=B||{};var C={wrongLengthMessage:B.wrongLengthMessage||"Must be "+B.is+" characters long!",tooShortMessage:B.tooShortMessage||"Must not be less than "+B.minimum+" characters long!",tooLongMessage:B.tooLongMessage||"Must not be more than "+B.maximum+" characters long!",is:((B.is)||(B.is==0))?B.is:null,minimum:((B.minimum)||(B.minimum==0))?B.minimum:null,maximum:((B.maximum)||(B.maximum==0))?B.maximum:null};switch(true){case (C.is!==null):if(A.length!=Number(C.is)){Validate.fail(C.wrongLengthMessage);}break;case (C.minimum!==null&&C.maximum!==null):Validate.Length(A,{tooShortMessage:C.tooShortMessage,minimum:C.minimum});Validate.Length(A,{tooLongMessage:C.tooLongMessage,maximum:C.maximum});break;case (C.minimum!==null):if(A.length<Number(C.minimum)){Validate.fail(C.tooShortMessage);}break;case (C.maximum!==null):if(A.length>Number(C.maximum)){Validate.fail(C.tooLongMessage);}break;default:throw new Error("Validate::Length - Length(s) to validate against must be provided!");}return true;},Inclusion:function(C,D){var E=Object.extend({failureMessage:"Must be included in the list!",within:[],allowNull:false,partialMatch:false,caseSensitive:true,negate:false},D||{});if(E.allowNull&&C==null){return true;}if(!E.allowNull&&C==null){Validate.fail(E.failureMessage);}if(!E.caseSensitive){var A=[];E.within.each(function(F){if(typeof F=="string"){F=F.toLowerCase();}A.push(F);});E.within=A;if(typeof C=="string"){C=C.toLowerCase();}}var B=(E.within.indexOf(C)==-1)?false:true;if(E.partialMatch){B=false;E.within.each(function(F){if(C.indexOf(F)!=-1){B=true;}});}if((!E.negate&&!B)||(E.negate&&B)){Validate.fail(E.failureMessage);}return true;},Exclusion:function(A,B){var C=Object.extend({failureMessage:"Must not be included in the list!",within:[],allowNull:false,partialMatch:false,caseSensitive:true},B||{});C.negate=true;Validate.Inclusion(A,C);return true;},Confirmation:function(A,B){if(!B.match){throw new Error("Validate::Confirmation - Error validating confirmation: Id of element to match must be provided!");}var C=Object.extend({failureMessage:"Does not match!",match:null},B||{});C.match=$(B.match);if(!C.match){throw new Error("Validate::Confirmation - There is no reference with name of, or element with id of '"+C.match+"'!");}if(A!=C.match.value){Validate.fail(C.failureMessage);}return true;},Acceptance:function(A,B){var C=Object.extend({failureMessage:"Must be accepted!"},B||{});if(!A){Validate.fail(C.failureMessage);}return true;},Custom:function(A,B){var C=Object.extend({against:function(){return true;},args:{},failureMessage:"Not valid!"},B||{});if(!C.against(A,C.args)){Validate.fail(C.failureMessage);}return true;},now:function(A,D,C){if(!A){throw new Error("Validate::now - Validation function must be provided!");}var E=true;try{A(D,C||{});}catch(B){if(B instanceof Validate.Error){E=false;}else{throw B;}}finally{return E;}},Error:function(A){this.message=A;this.name="ValidationError";},fail:function(A){throw new Validate.Error(A);}};



	//Set the element name and id of the active master checkbox to masterclick to use this function.
	//It will keep the master checkbox in sync with the resultset.
	function check_this(val) {
	  var n=document.getElementById(val);
	  if (n.checked) 
	    n.checked=true
	  else
	    n.checked=false
	}

	//Set form name and id to opcheckboxes to use this function.
	//All checkboxes on the form will respond to the uncheckall method.  
	function unCheckAll() {
	  var form=$('opcheckboxes'); 
	  var i=form.getElements('checkbox');
	  i.each(function(item) {
	    if (document.getElementById('masterclick').checked) 
		  item.checked=true
	    else
	      item.checked=false
	  });
	}	