String.prototype.trim = function(){return this.replace(/^\s+/,"").replace(/\s+$/,"");}
$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (!results) { return 0; }
	return results[1] || 0;
} 

$(document).ready(function() {
	
	//find cancel button and wire it to referrer url
	wireCancel();

	//bind event handlers
	$('input, textarea').each(function(){
		//fields with data masking (i.e. Number, Email)
		if (typeof($(this).attr("mask"))!="undefined"){
			bindEvents(this);
		}else{
			if (this.type=="text" || this.type=="textarea")
			{
				$(this).attr("mask", "alphanumeric");
				bindEvents(this);
			}
		}

		//strip invalid chars from inputs
		if ($(this).attr("type")=="text" || $(this)[0].nodeName.toLowerCase()=="textarea")
		{
			$(this).change(function(){
				var s = $(this).val();
				s = s.replace(">","").replace("<","").replace("%","percent").replace("{","").replace("}","").replace("&","and").replace("|","");
				$(this).val(s);
			});
		}

	});

    //re-populate fields
    $('input[type="hidden"]').each(function() {
        if (this.name != "file" && this.name != "") {

            var id = this.name; //.split("_")[3];

            //select fields
            var e = $('select#' + id)[0];
            if (e) {
                for (var i = 0; i < e.options.length; i++) {

					//some options may not have values
					var val = e.options[i].value;
					if (val=="") val = e.options[i].innerText;

                    if (val == this.value) {
                        e.options[i].selected = true;
						//force onchange event since its not firing by setting the value
						$(e).change();
						//if ($(e).attr("onchange")!=null) e.onchange();
                    } else {
                        e.options[i].selected = false;
                    }
                }
            } else {
                //inputs
                e = $('input#' + id)[0];
                if (e) {
                    //radios checkboxes
                    if (e.type == "radio" || e.type == "checkbox") {
                        e.checked = true;
                    } else {
                        //input type text
                        e.value = this.value;
                    }
                } else {
                    //textareas
                    e = $("textarea#" + id);
                    e.val(this.value);
                }
            }
        }
    });

	
});

function wireCancel(){
	var backurl = $.urlParam('backurl');

	if (backurl){
		$("input[name='backurl']").attr("value", backurl);
	}else{
		backurl = $("input[name='backurl']").attr("value");
	}

	if (backurl=="" || backurl==null)
	{
		backurl = "/";
	}

	var e = $("a:contains('Cancel')");
	if (e && backurl){
		$(e).attr("href", backurl);
	}
}

function bindEvents(e){
	switch ($(e).attr("mask"))
	{
		case "number":
			$(e).keyup(function(evt){
				
				if ($(e).val().length==0) return;  //first time focus from a tab command.
				if (evt.keyCode==9 || evt.keyCode==16) return;  //tabs
				
				if (!validator.testPattern(e, "number")){
					return false;
				}
				
				if ($(e).val().length==$(e).attr("maxlength"))
				{
					$(e).next().focus();
					$(e).next().select();
				}
			});
			break;
		case "email":
			$(e).change(function(){
				if (!validator.testPattern(e, "email")){
					$(e).focus();
				}
			});
			break;
		case "alphanumeric":
		    $(e).change(function(){
		        if (!validator.testPattern(e, "alphanumeric")){
		            $(e).focus();
		        }
		    });
		    break;
		case "alpha":
			$(e).change(function(){
				if (!validator.testPattern(e, "alpha")){
					$(e).focus();
				}
			});
			break;
		default:
			break;
	}
}

function go(where, action){
	var form = $("form[action='/cgi-bin/multiformpost.cgi']");

	//validate if going forward, not in reverse
	var b = false;
	if (action!=-1)
	{
		b = validator.validate();
	}else{
		b = true;
		action = null;  //reset for below
	}

    if (b){
		//set the field names
		$('form :input').each(function(){
			if (this.type!="hidden" && this.type!="button"){
				$(this).attr("name", this.id);
			}
		});

        //set the destination and go
	    $('input[name="file"]').val(where);
	    if (action) $(form).attr("action", action);
	    $(form).submit();
	}else{
	    var targetOffset = $("#CalloutError").offset().top;
        $('html,body').animate({scrollTop: targetOffset}, 1000);
        $("#CalloutError").focus();
	}

	return false;
}

function Validator(){
    this.calloutstate = false;
}
Validator.prototype.validate = function() {
    var t = this;
    var b = true;
    //turn off validation
    $('form :input').each(function() {
        if (this.type != "hidden" && this.type != "button") {
            t.toggleHighlight(this, false);
            t.toggleCallout(this, false);
        }
    });

    var nameditem = null;
    //turn on validation
    $('form :input').each(function() {
        
        if (this.type != "hidden" && this.type != "button") {
            if (this.type == "radio" && $(this).attr('required') == 1) {
                var ee = $('input[name="' + this.name + '"]');
                if (nameditem != this.name) {
                    nameditem = this.name;
                    var checked = false;
                    $(ee).each(function(){
                        checked = (this.checked ? true : checked);
                    });
                    if (checked == false) {
                        t.toggleHighlight(this, true);
                        t.toggleCallout(this, true);
                        b = false;
                    }
                }
            } else {
                //$(this).attr("required") isnt returning 0 | 1 on firefox 4.0
                var isRequired = this.getAttribute("required")==1;
                if (isRequired){
					if (this.value.trim().length == 0){
					    if ($(this).is(":visible")){
						    t.toggleHighlight(this, true);
						    t.toggleCallout(this, true);
						    b = false;
						}
					}else{
						if (typeof($(this).attr("mask"))!="undefined"){
							if (!t.testPattern(this, $(this).attr("mask")))
							{
								//t.toggleHighlight(this, true);
								//t.toggleCallout(this, true);
								b = false;
							}
						}
					}
                }
            }
        }
    });

    return b;
}
Validator.prototype.testPattern = function(e, type){
    var pattern = null;
	var val = null;

    switch (type) {
        case "email":
            pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/ig; 
			val = $(e).val().trim();
			if (typeof($(e).attr("validation"))=="undefined"){
				$(e).attr("validation", "Please enter a valid Email address.");
			}
            break;
		case "number":
			pattern = /[0-9]/g;
			val = $(e).val();
			if (typeof($(e).attr("validation"))=="undefined"){
				$(e).attr("validation", "Please enter a valid number.");
			}
			break;
		case "alphanumeric":
			pattern = /[A-Za-z0-9\s]/gi;
			val = $(e).val().trim();
			if (typeof($(e).attr("validation"))=="undefined"){
				$(e).attr("validation", "Please enter valid alphanumeric characters.");
			}
			break;
		case "alpha":
			pattern = /^[a-zA-Z\s]*$/gi;
			val = $(e).val().trim();
			if (typeof($(e).attr("validation"))=="undefined"){
				$(e).attr("validation", "Please enter valid alphabetic characters.");
			}
			break;
    }

    //toggle validation highlighting of offending field
	var result = pattern.test(val);

	if (result==false && type=="number"){
		val = new Number(val);
		if (new String(val)=="NaN"){
			result = false;
		}else{
			result = true;
		}
	}

    if (result) {
        this.toggleHighlight(e, false);
    } else {
        this.toggleHighlight(e, true);
    }
	return result;
}
Validator.prototype.toggleHighlight = function(e, b){
    var field = e;

    while (e.tagName!="BODY"){
        if (e.tagName=="TR" && 
            (e.className.indexOf("contentframework-altrow")!=-1 || 
             e.className.indexOf("contentframework-row")!=-1 ||
             e.className.indexOf("contentframework-required-cellhighlight")!=-1)){
            if (b){
                if (typeof(e.oldClass)=="undefined") e.oldClass = e.className;
                e.className = "contentframework-required-cellhighlight";
                o = this.GetContainer(e);
                if (o){
					if ($(field).attr("validating")==1) return;
                    $(o).html($(o).html() + this.WriteErrorString(field));
					$(field).attr("validating", "1");
                }
            }else{
                if (typeof(e.oldClass)=="string") e.className = e.oldClass;
                o = this.GetContainer(e);
                if (o){
                    $(o).html("");
					$(field).attr("validating", "0");
                }
            }
            break;
        }
        e = e.parentNode;
    }
}
Validator.prototype.toggleCallout = function(e, b){
    var o = $('#CalloutError');
    
    var ul = $(o).find('ul');
    if ($(e).attr("title") && $(e).attr("validation")){
		//generate error entry in callout (point hyperlink to field focus)
        var s = '<li><a href="#' + $(e).attr("id") + '" onclick="$(\'#' + $(e).attr("id") + '\').focus();return false;">' + $(e).attr("title") + '</a> - ' + $(e).attr("validation") + '</li>';
        $(ul).html($(ul).html() + s);
    }
    
    if (b==false){
        $(ul).html("");
        o.hide();
    }else{
        if ($(ul).html()!="") o.show();
    }
}
Validator.prototype.GetContainer = function(e){
    var o = $(e).find('div[name="container"]');
    if (o.length>0) return o[0];
    else{
        var td = $(e).find("td")[0];
        $(td).html($(td).html() + '<div name="container"></div>');
        return $(td).find('div[name="container"]');
    }
}
Validator.prototype.WriteErrorString = function(e){
    var s = "";
    s += '<a name="anc' + $(e).attr("id") + '"></a>';
    s += '<ul class="contentframework-required-description"><li>';
    s += '<img src="/files/static/uos/images/contentframework/icon-formerror.gif" alt="Error" class="contentframework-required-icon"/>';
    s += $(e).attr("validation");
    s += '</li></ul>';
    return s;
}

var validator = new Validator();
