
$("document").ready( function(){
	if (window.onload && window.onload.actions){
  		for (var ii = 0; window.onload.actions.length > ii; ii++) {
    		if (window.onload.actions[ii]) window.onload.actions[ii]();
    		window.onload.actions[ii] = null;
  		};
  	};
});

if (!window.onload){
	window.onload = [];
}
window.onload.actions =  Array();

$("document").ready( function()
{
	if (!document.getElementsByTagName) return null;
	var server = document.location.hostname;
	$('a').each(
		function(){
			href = $(this).href;
			if (!href){
				return;
			}
			var title = this.title;
			var id = this.id;
			var myClass = this.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(!this.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)
										this.setAttribute("target","_blank");
										this.setAttribute("title",title + " ["+href+"]");
									}
								}
							}
						}
					}
				}
			}
		
			if (href.indexOf('#bl') != -1){ // if it inlcudes our directive to open in a blank window
				this.setAttribute("target","_blank");
				this.setAttribute("title","Open in a new window");
			}

			if (href.indexOf('.pdf') != -1 || href.indexOf('.doc') != -1 || href.indexOf('.xls') != -1){ // if it's a PDF, Word, or Excel doc.
				this.setAttribute("target","_blank");
				this.setAttribute("title","Download File");
			}

			if ((href.replace("#","")) == (window.location.toString().replace("#","")) && (this.onclick == null) && (href.charAt(href.length-1) == "#")){
				// IF IT'S A NULL LINK, NOTE IT
				this.onclick = (function(){alert("Not yet implemented");return false;});
				this.setAttribute("title","Not yet implemented");
			}
		}
	);
	// FIND ANY LINKS WITH "_blank" and change the target
	$("._blank").each(function(){
		$(this).attr("target","_blank");
		$(this).attr("title",this.title+" ["+this.href+"]");
	});
	
	//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;
		if((typeof(forms[i].title) !== "undefined") && (forms[i].title.length > 1)){
			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){
}

$("document").ready( function()
{
	$("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 */
$("document").ready( function(){
	$("form.fs_form").not('.dont_validate').each(function(i){
		//this.oldSubmit = this.onSubmit;
		if (this.onsubmit) this.oldsubmit = this.onsubmit;
		this.onsubmit = validateForm;
	});
});


form_error = '';
function validateForm(e){
	result = true;
	form_error = '';
	if (this.oldsubmit){
		result = this.oldsubmit(e);
	};
	/* RESET ALL THE FIELDS */
	$("li").each(function(i){
		$(this).removeClass("error");
		$(".error_detail",this).remove();
	});
	
	$("fieldset",this).not(".dont_validate").each(function(){
		$(".required_oneof",this).not(".error").each(function(i){
			parentItem = this;
			if ($("input[@type=checkbox]:enabled:checked",this).length == 0){
				//they have to pick one of these
				$(parentItem).addClass("error");
					
				labelName = $("label",parentItem).html().replace(/\:/,'');
				if (labelName.length > 20) { labelName = "This field";}	
				this_error = labelName+' is a required field.';
				
				$(parentItem).append('<span class="error_detail">'+this_error+'</span>');
				if (form_error) form_error += "\n";
				form_error += this_error;
				this.parentObject = parentItem;
				$("input[@type=checkbox]",this).click(function(){
					o = $(this).parents('li.required_oneof');
					$(o).removeClass("error");
				});
				result = false;
			}
		});
		$(".required",this).not(".error").each(function(i){
			// EACH REQUIRED ITEM
			parentItem = this;
			$("input,textarea",this).each(function(){
				if ($(this).hasClass('other') && !$(this).hasClass('other_selected')){
					return;
				}
				if (this.value.length < 1){
					$(parentItem).addClass("error");
					
					labelName = $("label",parentItem).html().replace(/\:/,'');
					if (labelName.length > 20) { labelName = "This field";}				
					this_error = labelName+' is a required field.';
					
					$(parentItem).append('<span class="error_detail">'+this_error+'</span>');
					if (form_error) form_error += "\n";
					form_error += this_error;
					this.parentObject = parentItem;
					$(this).keyup(function(){
						if (this.value.length>0){
							//remove error
							$(this.parentObject).removeClass("error");
						} else {
							$(this.parentObject).addClass("error");
						}
					});
					result = false;
				};
			});
			if ($("input[@type=radio]",this).length){
				// ARE THERE RADIO BUTTONS?
				if (!$("input[@type=radio][@checked]",this).length){
					$(parentItem).addClass("error");
					
					labelName = $("label",parentItem).html().replace(/\:/,'');
					if (labelName.length > 20) { labelName = "This field";}				
					this_error = labelName+' needs a selection.';
					
					$(parentItem).append('<span class="error_detail">'+this_error+'</span>');
					if (form_error) form_error += "\n";
					form_error += this_error;
					
					$("input[@type=radio]",parentItem).each(function(){
						this.parentObject = parentItem;
						$(this).click(function(){
							//remove error
							$(this.parentObject).removeClass("error");
						});
					});
					
				}
			}
			$("select",this).each(function(){
				option = this.options[this.selectedIndex];
				val = option.value;
				if (val.length < 1 && !($(option).hasClass('pick_other'))){
					$(parentItem).addClass("error");
					
					labelName = $("label",parentItem).html().replace(/\:/,'');
					if (labelName.length > 20) { labelName = "This field";}
					this_error = labelName+' is a required field.';
					
					$(parentItem).append('<span class="error_detail">'+this_error+'</span>');
					if (form_error) form_error += "\n";
					form_error += this_error;
					this.parentObject = parentItem;
					$(this).change(function(){
						if (this.options[this.selectedIndex].value.length>0){
							//remove error
							$(this.parentObject).removeClass("error");
						} else {
							$(this.parentObject).addClass("error");
						}
					});
					result = false;
				}
			});
		});
			
		$(".format",this).not(".error").each(function(i){
			// EACH ITEM WITH A REQUIRED FORMAT
			parentItem = this;
			$("input,textarea",this).not("[@type=hidden]").each(function(){
				$validationText = $("#"+this.id+"_format").attr("value");
				if ($validationText){
					$validationArray = $validationText.split('|');
					var myExp = new RegExp($validationArray[0]);
					this.myExp = myExp;
					if (!myExp.test(this.value) && (this.value.length>0)){
						// Doesn't Match the Format:
						$(parentItem).addClass("error");
						if ($validationArray[2]) {
							this_error = $validationArray[2];
						} else {
					
							labelName = $("label",parentItem).html().replace(/\:/,'');
							if (labelName.length > 20) { labelName = "This field";}				
							this_error = labelName+' isn\'t in the right format';
							if ($validationArray[1]){
								this_error +=  '(i.e. '+$validationArray[1]+'.)';
							}
						}
						$(parentItem).append('<span class="error_detail">'+this_error+'</span>');
						if (form_error) form_error += "\n";
						form_error += this_error;
						this.parentObject = parentItem;
						$(this).keyup(function(){
							if (this.value.length>0){
								if (this.myExp.test(this.value)){
									$(this.parentObject).removeClass("error");
								} else {
									$(this.parentObject).addClass("error");
								}
							} else {
								$(this.parentObject).removeClass("error");
							}
						});
						
						
					}
				}
			});		
		
		});
	
	
		$(".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 error"><p>There were errors that you need to correct before submitting this form ...</p></div>';
		$(this).before($error_message);
		var targetOffset = $(this).offset().top-104;
		$('html,body').animate({scrollTop: targetOffset}, 500);
		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					
}


/* HANDLE FILE UPLOAD FORM STUFF */
$(document).ready(function(){
	SI.Files.stylizeAll();
});

// STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
if (!window.SI) { var SI = {}; };
SI.Files =
{
	htmlClass : 'SI-FILES-STYLIZED',
	fileClass : 'file',
	wrapClass : 'cabinet',
	
	fini : false,
	able : false,
	init : function()
	{
		this.fini = true;
		
		var ie = 0 //@cc_on + @_jscript_version
		if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
		this.able = true;
		
		var html = document.getElementsByTagName('html')[0];
		html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
	},
	
	stylize : function(elem)
	{
		if (!this.fini) { this.init(); };
		if (!this.able) { return; };
		
		elem.parentNode.file = elem;
		elem.parentNode.onmousemove = function(e)
		{
			if (typeof e == 'undefined') e = window.event;
			if (typeof e.pageY == 'undefined' &&  typeof e.clientX == 'number' && document.documentElement)
			{
				e.pageX = e.clientX + document.documentElement.scrollLeft;
				e.pageY = e.clientY + document.documentElement.scrollTop;
			};

			var ox = oy = 0;
			var elem = this;
			if (elem.offsetParent)
			{
				ox = elem.offsetLeft;
				oy = elem.offsetTop;
				while (elem = elem.offsetParent)
				{
					ox += elem.offsetLeft;
					oy += elem.offsetTop;
				};
			};

			var x = e.pageX - ox;
			var y = e.pageY - oy;
			var w = this.file.offsetWidth;
			var h = this.file.offsetHeight;

			this.file.style.top		= y - (h / 2)  + 'px';
			this.file.style.left	= x - (w - 30) + 'px';
		};
	},
	
	stylizeById : function(id)
	{
		this.stylize(document.getElementById(id));
	},
	
	stylizeAll : function()
	{
		if (!this.fini) { this.init(); };
		if (!this.able) { return; };
		
		var inputs = document.getElementsByTagName('input');
		for (var i = 0; i < inputs.length; i++)
		{
			var input = inputs[i];
			if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1)
			{
				this.stylize(input);
			};
		};
	}
};


function createRemove(input_name){
	obj = $('#'+input_name+' input.fs_input_remove');
	if (obj.size() > 0){
		return;
	}
	fobj = $('#'+input_name+' input.file').get(0);
	$('#'+input_name).append('<input type="hidden" name="'+fobj.name+'" value="REMOVE" class="fs_input_remove" />');
	fobj.name += '_remove';
}
function removeRemove(input_name){
	fobj = $('#'+input_name+' input.file').get(0);
	fobj.name = fobj.name.replace(/_remove$/,'');
	$('#'+input_name+' input.fs_input_remove').remove();
}
function fs_input_removeFile(input_name){
	$("#"+input_name+" .fs_input_thumb").html('');
	$("#"+input_name+" a.fs_input_remove_button").addClass("hidden");
	$("#"+input_name+" label.replace").removeClass("replace");
	createRemove(input_name);
	//$("#"+input_name+" input.fs_input_remove").val("1");	
}

function fs_input_removeImage(input_name){
	$("#"+input_name+" .fs_input_thumb").html('<img src="'+root+'fs_webkit/images/no_thumb.png">');
	$("#"+input_name+" a.fs_input_remove_button").addClass("hidden");
	$("#"+input_name+" label.replace").removeClass("replace");
	//$("#"+input_name+" input.fs_input_remove").val("1");
	createRemove(input_name);
}

function fs_input_replaceFile(input_name){
	fileInput = $("#"+input_name+" input[@type=file]").val();
	fileParts = fileInput.split(/\/|\\/);
	$("#"+input_name+" .fs_input_thumb").html(fileParts[fileParts.length-1]+'<br/><span class="small">(Queud for upload)</span>');
	$("#"+input_name+" a.fs_input_remove_button").removeClass("hidden");
	//$("#"+input_name+" input.fs_input_remove").val("0");
	removeRemove(input_name);
}

function fs_input_replaceImage(input_name){
	fileInput = $("#"+input_name+" input[@type=file]").val();
	fileParts = fileInput.split(/\/|\\/);
	$("#"+input_name+" .fs_input_thumb").html('<img src="'+root+'fs_webkit/images/file_queued.png"><br/>'+fileParts[fileParts.length-1]);
	$("#"+input_name+" a.fs_input_remove_button").removeClass("hidden");
	//$("#"+input_name+" input.fs_input_remove").val("0");
	removeRemove(input_name);
}

