// Copyright (c) 2007, Einstein Industries, Inc. All rights reserved.
// 
// Requires: prototype.js (v1.6.0)


// EI Namespacing
//
// Author: 	Brian Smith (bsmith@einsteinindustries.com)
// Date: 	June 2007
 
// Set the global namespace
if(typeof EI == "undefined") {
	var EI = {};
}

// We can automatically create namespaces under EI with this function.
// Note: It assumes the EI prefix already, but will still work if you add it.
EI.namespace = function(new_namespace) {
	
 	var obj = EI;
 	var sub_objects = new_namespace.split(".");
	var i, j;
    
    // EI is implied, so it is ignored if it is included
    for (j = (sub_objects[0] == "EI") ? 1 : 0; j < sub_objects.length; j = j+1) {
        obj[ sub_objects[j] ] = obj[ sub_objects[j] ] || {};
        obj = obj[ sub_objects[j] ];
    }

    return obj;
}

// Form validation
//
// Author: 	 Andrew Waer (awaer@einsteinindustries.com)
// Date: 	 November 2007

EI.namespace("EI.VoteRicasa");

EI.namespace("EI.VoteRicasa.Forms");

EI.VoteRicasa.Forms = function() {
	
	// private functions and properties
	var _private = {
		elemsToValidate       : ['input','select'],   // form elements to validate
		classReqPrefix        : 'req_',               // class prefix used for validation type, e.g. req_email
		classToValidate       : 'validate',           // class signaling 'validate me!'
		classInvalid          : 'validate-error',
		classValid            : 'validate-ok',
		errorMessage          : 'Please complete all required fields. Errors are marked in red.',
		getElementsToValidate : function(formElt) {
			var elements = new Array();
			// for each tag element type
			for (var i = 0; i < this.elemsToValidate.length; i++) {
				// get all elements with specified className
				elements = elements.concat(
					formElt.select(this.elemsToValidate[i] + '.' + this.classToValidate)
				);
			}
			return elements;
		}
	}

	// public functions and properties
	var _public = {

		init : function() {
			var objForm = $$('form');
			for (var i = 0; i < objForm.length; i++) {
				var obj = _private.getElementsToValidate(objForm[i]);
				// attach onchange validation to each element
				for (var j = 0; j < obj.length; j++)
					obj[j].observe('change', function(){ return EI.VoteRicasa.Forms.test(this); })
				// attach validate() to the form
				if (obj.length > 0)
					objForm[i].observe('submit', function(e){ return EI.VoteRicasa.Forms.validate(this, e) });
			}
		},

		test : function(obj) {
			var classNames = obj.className.split(' ');
			for (var i=0; i<classNames.length; i++) {
				// only check fields prefixed correctly that aren't already flagged as invalid
				if (classNames[i].indexOf(_private.classReqPrefix) >= 0 && classNames[i].indexOf(_private.classInvalid) < 0) {
					// do validation checks & flag invalid
					switch (classNames[i]) {
						case _private.classReqPrefix + 'email':
							var isValid = _public.validEmail(obj.value);
							_public.updateValidState(obj,isValid);
						break;
						case _private.classReqPrefix + 'not_empty':
							var isValid = _public.validNotEmpty(obj.value);
							_public.updateValidState(obj,isValid);
						break;
						case _private.classReqPrefix + 'not_default_value':
							var isValid = _public.validNotDefaultValue(obj);
							_public.updateValidState(obj,isValid);
						break;
						case _private.classReqPrefix + 'not_default_select':
							var isValid = _public.validNotDefaultSelect(obj);
							_public.updateValidState(obj,isValid);
						break;
					}
				}
			}
		},

		validate : function(f, e) {
			// do one final validation fly-over
			var elems = _private.getElementsToValidate(f);
			for (var i = 0; i < elems.length; i++)
				_public.test(elems[i]);
			var elems_invalid = f.select('.' + _private.classInvalid);
			// are any required inputs flagged as invalid?
			if ( elems_invalid.length ) {
				alert(_private.errorMessage);
				elems_invalid[0].focus();
				e.stop(); return false;
			}
		},

		updateValidState : function(elem,isValid) {
			if (isValid) {
				// flag as valid
				elem.removeClassName(_private.classInvalid);
				elem.addClassName(_private.classValid);
				// CSS disabled
				elem.setAttribute('style', '');
			} else {
				// flag as invalid
				elem.addClassName(_private.classInvalid);
				elem.removeClassName(_private.classValid);
				// CSS disabled
				elem.setAttribute('style', 'border:2px solid #f00;');
			}
		},

		// validation routines
		validEmail : function(val) {
			// email regular expression (http://www.regexlib.com)
			var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
			return regex.test(val)
		},

		validNotEmpty : function(val) {
			// checks for empty or only whitespace
			var regex = /\S/;
			return regex.test(val);
		},

		validNotDefaultValue : function(obj) {
			// checks if default value is in a text field
			return (obj.value != obj.defaultValue);
		},

		validNotDefaultSelect : function(obj) {
			// checks if default option is selected
			return (obj.value != obj.options[0].value);
		}
	}
	return _public;
}();

document.observe('dom:loaded', EI.VoteRicasa.Forms.init);

//------------------- for clearing and replacing text in form input fields and textareas -------------------//
function clearText(thefield) {
  if (thefield.defaultValue==thefield.value) { thefield.value = "" }
} 
function replaceText(thefield) {
  if (thefield.value=="") { thefield.value = thefield.defaultValue }
}


//----------------------------- open new window----------------------------//
var newWindow = null;

function closeWin(){
	if (newWindow != null){
		if(!newWindow.closed)
			newWindow.close();
	}
}

function popUpWin(url, type, strWidth, strHeight){
	closeWin();
	if (type == "fullScreen"){
		strWidth = screen.availWidth - 10;
		strHeight = screen.availHeight - 160;
	}
	var tools="";
	if (type == "standard" || type == "fullScreen") tools = "resizable=no,toolbar=no,location=no,scroll=yes,scrollbars=yes,menubar=no,width="+strWidth+",height="+strHeight+",top=0,left=0";
	if (type == "console") tools = "resizable=no,toolbar=no,location=no,directories=no,status=no,scroll=no,scrollbars=no,menubar=no,width="+strWidth+",height="+strHeight+",left=0,top=0";
	newWindow = window.open(url, 'newWin', tools);
	newWindow.focus();
}



