// onload will process an array we can push any functions to that we want
/*var old = window.onload; // catch any existing onload calls 1st
window.onload = function (e) {
  if (old) { // execute existing onloads
    old(e);
  };
  for (var ii = 0; arguments.callee.actions.length > ii; ii++) {
    if (arguments.callee.actions[ii]) arguments.callee.actions[ii](e);
    arguments.callee.actions[ii] = null;
  };
};*/

$("document").ready( function(){
  for (var ii = 0; window.onload.actions.length > ii; ii++) {
    if (window.onload.actions[ii]) window.onload.actions[ii]();
    window.onload.actions[ii] = null;
  };
});

window.onload.actions = [];

function fixLinks()
{
	if (!document.getElementsByTagName) return null;
	var server = document.location.hostname;
	var anchors = document.getElementsByTagName("a");
	var id, href, title;
	for(var i=0; i < anchors.length; i++){
	if(!anchors[i].href) continue;
		href = anchors[i].href;
		title = anchors[i].title;
		id = anchors[i].id;
		myClass = anchors[i].className;
		if(myClass.indexOf("open_within_window")== -1){
			if (root.length ==0 || root.indexOf('http') == -1 || (root.length > 0 && root.indexOf('http') != -1 && href.indexOf(root)) == -1) {// it's not a file within the path of the root if we're using an absolute path (for instance if we have a template on someone else's site
				if(href.indexOf(server) == -1){ // Href is not a file on my server
					if(href.indexOf("javascript:") == -1){ // Href is not a javascript call
						if(!anchors[i].onclick){ // Href does not have an onclick event
							if(href.indexOf("mailto:") == -1){ // Href is not a mailto:
								if((href.indexOf("http://") != -1) || (href.indexOf("https://") != -1)){ // Href is not relative (for Safari)
									anchors[i].setAttribute("target","_blank");
									anchors[i].setAttribute("title",title + " ["+href+"]");
								}
							}
						}
					}
				}
			}
		}
		
		if (href.indexOf('.pdf') != -1 || href.indexOf('.doc') != -1 || href.indexOf('.xls') != -1){ // if it's a PDF, Word, or Excel doc.
			anchors[i].setAttribute("target","_blank");
			anchors[i].setAttribute("title","Download File");
		}

		if ((href.replace("#","")) == (window.location.toString().replace("#","")) && (anchors[i].onclick == null) && (href.charAt(href.length-1) == "#")){
			// IF IT'S A NULL LINK, NOTE IT
			anchors[i].onclick = (function(){alert("Not yet implemented");return false;});
			anchors[i].setAttribute("title","Not yet implemented");
		}
	}
	
	//DO THE SAME FOR FORMS

	var forms = document.getElementsByTagName("form");
	for(var i=0; i < forms.length; i++){
	if(!forms[i].action) continue;
		href = forms[i].action;
		title = forms[i].title;
		id = forms[i].id;
		myClass = forms[i].className;
		if(myClass.indexOf("open_within_window")== -1){
			if (root.length ==0 || root.indexOf('http') == 0 || (root.length > 0 && root.indexOf('http') != -1 && href.indexOf(root)) == -1){
				if(href.indexOf(server) == -1){ // Href is not a file on my server
					if((href.indexOf("http://") != -1) || (href.indexOf("https://") != -1)){ // Href is not relative (for Safari)
						forms[i].setAttribute("target","_blank");
					}
				}
			}
		}
	}
	
	
	return null;
}
window.onload.actions.push(fixLinks);

function trace(src){
}

function beautifyForms()
{
	$("input[@type=text]").addClass("text");
	$("input[@type=password]").addClass("password");
	$("input[@type=radio]").addClass("radio");
	$("input[@type=checkbox]").addClass("checkbox");
	$("input[@type=button]").addClass("button");
	$("input[@type=submit]").addClass("submit");
	
	$("input").focus(function(){$(this).addClass("focused");});
	$("input").blur(function(){$(this).removeClass("focused");});
	
}
window.onload.actions.push(beautifyForms);

/*
* PHP Serialize
* Morten Amundsen
* mor10am@gmail.com
*/
function fs_serialize(obj)
{
    var string = '';

    if (typeof(obj) == 'object') {
        if (obj instanceof Array) {
            string = 'a:';
            tmpstring = '';
            for (var key in obj) {
                tmpstring += php_serialize(key);
                tmpstring += php_serialize(obj[key]);
            }
            string += obj.length + ':{';
            string += tmpstring;
            string += '}';
        } else if (obj instanceof Object) {
            classname = obj.toString();

            if (classname == '[object Object]') {
                classname = 'StdClass';
            }

            string = 'O:' + classname.length + ':"' + classname + '":';
            tmpstring = '';
            count = 0;
            for (var key in obj) {
                tmpstring += php_serialize(key);
                if (obj[key]) {
                    tmpstring += php_serialize(obj[key]);
                } else {
                    tmpstring += php_serialize('');
                }
                count++;
            }
            string += count + ':{' + tmpstring + '}';
        }
    } else {
        switch (typeof(obj)) {
            case 'number':
                if (obj - Math.floor(obj) != 0) {
                    string += 'd:' + obj + ';';
                } else {
                    string += 'i:' + obj + ';';
                }
                break;
            case 'string':
                string += 's:' + obj.length + ':"' + obj + '";';
                break;
            case 'boolean':
                if (obj) {
                    string += 'b:1;';
                } else {
                    string += 'b:0;';
                }
                break;
        }
    }

    return string;
}


// LITTLE CODE SNIPPIT TO STOP IE FROM FLASHING WHEN YOU MOUSEOVER
try {
	document.execCommand('BackgroundImageCache', false, true);
} 
catch(e) {}


/* WORK ON FORM VALIDATION & REFORMATTING */
function processForm(){
	$("form.fs_form").not('.dont_validate').each(function(i){
		//this.oldSubmit = this.onSubmit;
		if (this.onsubmit) this.oldsubmit = this.onsubmit;
		this.onsubmit = validateForm;
	
	});
/*	$("body").each=function(i){
		alert(i);
	}*/
}
window.onload.actions.push(processForm);


form_error = '';
function validateForm(e){
	result = true;
	form_error = '';
	if (this.oldsubmit){
		result = this.oldsubmit(e);
	};
	/* RESET ALL THE FIELDS */
	$("li",this).each(function(i){
		$(this).removeClass("error");
		$(".error_detail",this).remove();
	});
	
	
	$(".required",this).not(".error").each(function(i){
		// EACH REQUIRED ITEM
		if($("input,textarea",this).get(0).value.length < 1){
			$(this).addClass("error");
			this_error = $("label",this).html().replace(/\:/,'')+' is a required field.';
			$(this).append('<span class="error_detail">'+this_error+'</span>');
			if (form_error) form_error += "\n";
			form_error += this_error;
			$("input,textarea",this).get(0).parentObject = this;
			$("input,textarea",this).get(0).onkeyup=$("input,textarea",this).get(0).onchange=function(){
				if (this.value.length>0){
					//remove error
					$(this.parentObject).removeClass("error");
				} else {
					$(this.parentObject).addClass("error");
				}
			};
			result = false;
		}
	});

	$(".email",this).not(".error").each(function(i){
		// EACH EMAIL ITEM
		if (!_checkEmail($("input,textarea",this).get(0).value)){
			$(this).addClass("error");
			this_error= $("label",this).html().replace(/\:/,'')+' needs to be a valid email address.';
			$(this).append('<span class="error_detail">'+this_error+'</span>');
			if (form_error) form_error += "\n";
			form_error += this_error;
			$("input,textarea",this).get(0).parentObject = this;
			$("input,textarea",this).get(0).onkeyup=$("input,textarea",this).get(0).onchange=function(){
				if (_checkEmail(this.value)){
					//remove error
					$(this.parentObject).removeClass("error");
				} else {
					$(this.parentObject).addClass("error");
				}
			};
			result = false;
		}
	});

	$(".min_length",this).not(".error").each(function(i){

		input_object = $("input,textarea",this).get(0)
		
		if (!_checkMinLength(input_object)){
			$(this).addClass("error");
			this_error = $("label",this).html().replace(/\:/,'')+' needs to be at least '+input_object.alt+' characters long.';
			$(this).append('<span class="error_detail">'+this_error+'</span>');
			if (form_error) form_error += "\n";
			form_error += this_error;
			$("input,textarea",this).get(0).parentObject = this;
			$("input,textarea",this).get(0).onkeyup=$("input,textarea",this).get(0).onchange=function(){
				if (_checkMinLength(this)){
					//remove error
					$(this.parentObject).removeClass("error");
				} else {
					$(this.parentObject).addClass("error");
				}
			};
			result = false;
		}
	});

	
	$("fieldset").each(function(i){
		linkedValue = '';
		firstLinkedName = '';
		$(".linked",this).not(".error").each(function(i){
			if (linkedValue){
				if($("input,textarea",this).get(0).value != linkedValue){
					this_error = firstLinkedName+'s don\'t match.';			
					$(this).addClass("error");
					$(this).append('<span class="error_detail">'+this_error+'</span>');
					if (form_error) form_error += "\n";
					form_error += this_error;
				}
			} else {
				linkedValue = $("input,textarea",this).get(0).value;
				firstLinkedName = $("label",this).html().replace(/\W*$/g,'');
			}
		});
	});

	if (form_error) {
		$(".form_error",this.parentObject).remove();
		$error_message = '<div class="form_error"><p>There were errors that you need to correct before submitting this form ...</p></div>';
		$(this).before($error_message);
		return false;
	} else {
		return true;
	}
}

function _checkMinLength(input_field){
	if ((input_field.value.length < input_field.alt) && (input_field.value.length > 0)){
		return false;
	}
	return true;
}

function _checkEmail(str){

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		//alert("Invalid E-mail ID")
		return false
	}	
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		//alert("Invalid E-mail ID")
		return false
	}	
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		//alert("Invalid E-mail ID")
		return false
	}	
	if (str.indexOf(at,(lat+1))!=-1){
		//alert("Invalid E-mail ID")
		return false
	}	
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		//alert("Invalid E-mail ID")
		return false
	}	
	if (str.indexOf(dot,(lat+2))==-1){
		//alert("Invalid E-mail ID")
		return false
	}	
	if (str.indexOf(" ")!=-1){
		//alert("Invalid E-mail ID")
		return false
	}
	
	return true					
}