function byId(el) { return document.getElementById(el); }

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

function launchForms() {	
		//alert('!!');		
		var allforms = document.getElementsByTagName('form');
		for(var i=0,l=allforms.length;i<l;i++){
			if( allforms[i].getAttribute('action')  && allforms[i].getAttribute('action').indexOf("www.salesforce.com") > -1 ){
				var f = new processForm();
				f.set(allforms[i]);
			}
		}
	}
//addLoadEvent( launchForms );
/***********************************************************************************************/

function processForm(){
	this.form = null;
	
	this.isSalesForceForm = true;
	
	this.validForm = true;
	
	this.counter = 0;
	
	this.additionalDescription = [];
	
	this.Errors = [];
	
	this.firstError = null;
	
	this.writeError = function(obj,message) {
		this.validForm = false;
		//if (obj.hasError) return;
		
		//alert(typeof obj + " " + obj + " " + typeof this.Errors[obj]);
		
		if (obj.hasError != null){
			return;
		}
		if (W3CDOM) {
			obj.className += ' error';
			var this_obj = this;
			var this_el = obj;
			obj.onchange = function(){ this_obj.removeError(this_el); };
			var sp = document.createElement('span');
			sp.className = 'error';
			sp.appendChild(document.createTextNode(message));
			//obj.parentNode.appendChild(sp);
			insertAfter(obj.parentNode, sp, obj)
			obj.hasError = ( this.Errors.length + 1); //so the first object won't be null
			
			this.Errors[ this.Errors.length ] = [obj, sp];
			
		}
		else {
			this.errorstring += obj.name + ': ' + message + '\n';
			//obj.hasError = true;
		}
		if (!this.firstError)
			this.firstError = obj;
	}
	
	this.isValidForm = function(){
		//alert('here');
		for(i in this.Errors){
			if(this.Errors[i] != null){
				//alert(typeof this.Errors[i]  );
				return false;
			}
		}
		return true;
	}
	
	this.removeAllErrors = function(){
		//var errors = getElementsByClass('error',this.form,'span');
		//alert(this.Errors.length);
		this.validForm = true;
		for(i in this.Errors) {
			var e = i;
				//alert( e );
			if(this.Errors[e] != null && typeof this.Errors[e][0] == "object" && typeof this.Errors[e][1] == "object" ){
				//alert( e + " "  + typeof this.Errors[e] + " "  + typeof this.Errors[e][0] + " " + typeof this.Errors[e][1]  );
				this.Errors[e][0].hasError = null
				this.Errors[e][0].className=this.Errors[e][0].className.replace(new RegExp("\\error\\b", "gi"), "");
				this.Errors[e][1].parentNode.removeChild(this.Errors[e][1]); 		
				this.Errors[e] = null;			
				//this.Errors.splice(e, e);			
			}
		}
	}
	
	this.removeError = function(el){
		//alert(el.hasError);
		if(typeof el == "undefined" || typeof el.nodeName == "undefined" ){
			el = this;
		}
		
		
		if(el.hasError != null){
			var index = (el.hasError-1);
				if(typeof this.Errors[ index ] != "undefined" ){
			
			//alert(typeof el);
			//el.className = el.className.substring(0,el.className.lastIndexOf(' '));
				el.className=el.className.replace(new RegExp("\\error\\b", "gi"), "");			
				this.Errors[index][1].parentNode.removeChild(this.Errors[index][1]);
				el.onchange = null;
				this.Errors[index] = null;
				el.hasError = null;
			}
		}			
	}
	
	this.assignSubmitButtons = function(formObj){
				
				
		var divHolders = getElementsByClass('blue-bg',this.form,'div');
		var obj = this;
		
		for(i in divHolders){
			var divHolder = divHolders[i];
			if(divHolder){
				
				var inputs = divHolder.getElementsByTagName('input');
				
				//if(  typeof inputs[x] == "object" ){
					//alert( divHolder.innerHTML );
				//}
				
				for(var x=0,l=inputs.length;x<l;x++){
				
					//if(typeof inputs[x] != "object" || inputs[x].type == null || inputs[x].type == 'undefined') continue;
					
					//alert( inputs[x].type );
					
					if( inputs[x].type.toLowerCase() == "image" || inputs[x].type.toLowerCase() == "submit"){
						//alert(inputs[x].type + " assigned ")
						inputs[x].onclick = function(){ return obj.validate() };	
						//inputs[x].onmouseover = function(){ //alert('test') };	
					}
				}	
			}
		}
	}
	
	
	this.set =  function(formObj){
		if(formObj){
			var obj = this;
			this.form = formObj;
			/*this.form.onsubmit = function(){ return obj.validate() };*/
			if(this.isSalesForceForm){
				this.assignSubmitButtons(formObj);
			}
			this.form.onreset = function(){ return obj.reset() };
			//alert('Set ' + this.form.getAttribute('action'));
		}
	}	
	
	this.fixCountry = function(){	
		var country1 = this.form.elements['country'];
		var country2 = this.form.elements['00N20000001GUeW'];
		
		if(country1 && country1.value.length > 0){
			if(!country2){
				country2 = this.createHiddenField('00N20000001GUeW');
				country2.value = country1.value
			}
		}
		
		if(country2 && country2.value.length > 0){
			if(!country1){
				country1 = this.createHiddenField('country');
				country1.value = country2.value;
			}
		}
		
		//alert(country1.name + "=" + country1.value + "\n" + country2.name + "=" + country2.value);
		
	}
	
	this.createHiddenField = function(name){
			var newEl = document.createElement("input");
			newEl.type = "hidden";
			newEl.name = name;
			this.form.appendChild( newEl );	
			return newEl;
	}
	
	this.addDescription = function(){
		
		var m = "------------Source page----------------\n"+
				"\n"+document.title+"\n"+location.href+"\n";
		
		var t = "\n\n--------Additional information--------\n";
		
		for(i in this.additionalDescription){
			if(typeof this.additionalDescription[i] != "object") continue;
			
			t+="\n" + i + ":\n";
			for(var d=0, o=this.additionalDescription[i].length;d<o;d++){
				t+="\t--"+this.additionalDescription[i][d]+"\n";
			}			
		}
		
		var x = "";
		var descEl = this.form.elements['description'];
		if(descEl){
			x = "\n\n--------Original message--------\n\n"+descEl.value;
			//descEl.name = "description1";
			//alert(descEl.name);
			//alert(this.form.elements['description'].name);
		}else{		
			var descEl = this.createHiddenField("description");					
		}
		
		descEl.value = m + x + t;		
		//alert(this.form.elements['description'].value);		
	}
	
	
	this.checkType = function(el){
		var rel = el.getAttribute("rel");
		if(typeof rel == "string" && rel.indexOf(":")  > -1){
			var type = rel.split(":")
			if(type[1] == "email"){		
				if(! isValidEmail( el.value ) ){
					this.writeError(el,errorMessages['notValidEmail']);
				}
			}
			
			if(type[1] == "checkboxgroup" || type[1] == "checkboxgroup-toDescription"){
				
				if(! this.hasChosen(el, type[1]) ){
					this.writeError(el,errorMessages['requiredField']);
				}
			}
			
			//alert( dump(type) );
		}
	}
	
	this.hasChosen = function(div, elType){
		var checkedexists = false;

		if(div){
			var x = div.getElementsByTagName('input');
			var divTitle = (div.title && div.title.length >0)? div.title : "Group of checkboxes "+(this.additionalDescription.length+1);
			for (var i=0;i<x.length;i++) {		
				if ( (x[i].type == "checkbox" || x[i].type == "radio" ) && x[i].checked ){	
					
					this.addToDescription(elType, x[i].value, divTitle);
					
					checkedexists = true;				
				}
				var this_obj = this;
				var this_el = div;
				x[i].onclick = function(){ if(this.checked) this_obj.removeError(this_el); };
			}
		}
		return checkedexists;
	}
	
	this.addToDescription = function(elType, elValue, elName){
		if(elType && elType.indexOf('toDescription') > -1){
			if(typeof this.additionalDescription[elName]== "undefined"){
				this.additionalDescription[elName] = [];
			}
			this.additionalDescription[elName].push(elValue);
		}
	}
	
	
	
	this.validate = function () {	
		//alert('!');
		if( this.form ){
			this.validForm = true;
			this.firstError = null;
			this.errorstring = '';
			this.removeAllErrors();
			
			var x = this.form.elements;
			this.additionalDescription = [];
			
	
			//check checkboxgroups
			var divObl = this.form.getElementsByTagName('div');
			for (var i=0;i<divObl.length;i++) {
				if (isObligatory(divObl[i])){					
					this.checkType( divObl[i] );
				}
			}			
			
			
			for (var i=0;i<x.length;i++) {		
				if (isObligatory(x[i])){
					if(!x[i].value){						
						this.writeError(x[i], errorMessages['requiredField']);
					}else{
						this.checkType(x[i]);
					}
				}
				
				this.addToDescription(x[i].getAttribute('rel'), x[i].value, x[i].name);
				
			}
						
			if (!W3CDOM)
				alert(this.errorstring);
			if (this.firstError)
				this.firstError.focus();
			if ( this.isValidForm() ){
				if(this.isSalesForceForm){
					setCookie( "FormCookie", "True", 30, "/" );
					this.addDescription();
					this.fixCountry();
				}
				
				return true;
			}
			
			return false;
		}
		return false;
	}
	
	this.reset = function (){
		if( this.form ){
			this.removeAllErrors();
		}
	}
	
}

//if( getCookie( "FormCookie" )){ alert("FormCookie="+getCookie( "FormCookie" )) };

/***********************************************************************************************/
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

/***********************************************************************************************/
var W3CDOM = (document.getElementsByTagName && document.createElement);
var errorMessages = []
errorMessages['requiredField'] = "This field is required";
errorMessages['notValidEmail'] = "Please enter a valid email address";

function isValidEmail(emailad) {
	var exclude=/[^@\-\.\w\']|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
	var check=/@[\w\-]+\./;
	var checkend=/\.[a-zA-Z]{2,6}$/;
	var isValid = ( ( (emailad.length > 80) || (emailad.search(exclude) != -1) || (emailad.search(check)) == -1 ) || (emailad.search(checkend) == -1) ) ? false : true;
	//alert(isValid);
	
	return isValid;
}

function isObligatory(el){
	var rel = el.getAttribute("rel");		
	if(typeof rel == "string" && rel.indexOf("obligatory") > -1){
		return true
	}
	return false;
}
