// common JS library
// 1/27/2010

// thanks to http://phpjs.org/functions/number_format:481
var number_format = function(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }    return s.join(dec);
};

var formValidate = function(formId, inline, singleId) {
    var $f = jQuery("#" + formId);
    var okay = true;
    if (singleId) {
        // special case because :textarea selector breaks each()
        jQuery("#" + singleId + "[prmRequired=yes]:enabled:visible", $f).each(function(i) {
            if (jQuery(this).val() == "" || jQuery(this).hasClass("ghost")) { formAlert(formId, this.id, "Please enter a value for the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
        }); if (!okay) return false;
    } else {
        jQuery("input[prmRequired=yes]:text:enabled:visible, input[prmRequired=yes]:password:enabled:visible, input[prmRequired=yes]:radio:enabled:visible, input[prmRequired=yes]:hidden:enabled, textarea[prmRequired=yes]:enabled:visible, select[prmRequired=yes]:enabled:visible", $f).each(function(i) {
            if (jQuery(this).attr("type") == "radio") {
                if (jQuery("input:radio[name=" + jQuery(this).attr("name") + "]:checked:visible").length < 1)  { formAlert(formId, this.id, "Please select an option for the \"" + jQuery(this).attr("prmLabel") + "\" choice.", inline); okay = false; return false; }
            } else if (this.type.toLowerCase() == "select-multiple") {
                var s = jQuery.map(jQuery(this).find(":selected"), function(e) { return e.value; });
                if (s.length == 0) { formAlert(formId, this.id, "Please select at least one value for the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
            } else {
                if (jQuery(this).val() == null || jQuery(this).val() == "" || jQuery(this).hasClass("ghost")) { formAlert(formId, this.id, "Please enter a value for the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
            }
        }); if (!okay) return false;
    }
    jQuery("input[prmRequired=yes]:checkbox:enabled:visible:not(:checked)", $f).each(function(i) {
        formAlert(formId, this.id, "Please check the box next to the \"" + jQuery(this).attr("prmLabel") + "\" item.", inline); okay = false; return false;
    }); if (!okay) return false;
    jQuery("input[prmFormat=email][value]:enabled:visible", $f).each(function(i) {
        var re = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid email address in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=ssn][value]:enabled:visible", $f).each(function(i) {
        var re = /^(\d{3}\-\d{2}\-\d{4}|\d{9})$/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid SSN in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=date][value]:enabled:visible", $f).each(function(i) {
        var re = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid date in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=integer][value]:enabled:visible", $f).each(function(i) {
        var re = /[\D]/g;
        if (re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid whole number in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=float][value]:enabled:visible", $f).each(function(i) {
        var re = /[^0-9\.\-\+]/g;
        if (re.test(jQuery(this).val()) || parseFloat(jQuery(this).val()) == NaN) { formAlert(formId, this.id, "Please enter a valid decimal number in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=alpha][value]:enabled:visible", $f).each(function(i) {
        var re = /[^a-zA-Z]/g;
        if (re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter only alpha characters A-Z in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=alphanumeric][value]:enabled:visible", $f).each(function(i) {
        var re = /[^a-zA-Z0-9]/g;
        if (re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid alphanumeric string in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=url][value]:enabled:visible", $f).each(function(i) {
        var re = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid URL in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=urlshort][value]:enabled:visible", $f).each(function(i) {
        var re = /(https?:\/\/)?([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid URL in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=ipaddress][value]:enabled:visible", $f).each(function(i) {
        var re = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid IP address in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=usphone][value]:enabled:visible", $f).each(function(i) {
        var re = /^\(?\d{3}\)?(\s|-|\.)?\d{3}(\s|-|\.)?\d{4}$/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid phone number in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=intlphone][value]:enabled:visible", $f).each(function(i) {
        var re = /^\d(\d|-){7,20}$/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid international phone number in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=time12][value]:enabled:visible", $f).each(function(i) {
        var re = /^([1-9]|1[0-2]):[0-5]\d$/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid 12-hour time in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=time24][value]:enabled:visible", $f).each(function(i) {
        var re = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid 24-hour time in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmFormat=uszip][value]:enabled:visible", $f).each(function(i) {
        var re = /\D{5}(-\D{4})?/;
        if (!re.test(jQuery(this).val())) { formAlert(formId, this.id, "Please enter a valid US ZIP code in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmMinimum][value]:enabled:visible", $f).each(function(i) {
        var v = parseFloat(jQuery(this).val()), m = parseFloat(jQuery(this).attr("prmMinimum"));
        if (m == NaN) return true; // bad value specified for minimum, but don't die
        if (v == NaN || v < m)  { formAlert(formId, this.id, "Please enter a value no less than " + m + " in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[prmMaximum][value]:enabled:visible", $f).each(function(i) {
        var v = parseFloat(jQuery(this).val()), m = parseFloat(jQuery(this).attr("prmMaximum"));
        if (m == NaN) return true; // bad value specified for maximum, but don't die
        if (v == NaN || v < m)  { formAlert(formId, this.id, "Please enter a value no greater than " + m + " in the \"" + jQuery(this).attr("prmLabel") + "\" field.", inline); okay = false; return false; }
    }); if (!okay) return false;
    jQuery("input[customvalidate]:enabled:visible", $f).each(function(i) {
        var msg; eval("msg = " + jQuery(this).attr("customvalidate") + ";");
        if (msg != "") { formAlert(formId, this.id, msg, inline); okay = false; return false; }
    }); if (!okay) return false;
    
    return true;
};

var formAlert = function(formId, elementId, message, inline) {
    if (inline) {
        // special inline error/message
    } else {
        // normal error/message
        document.promptCallbackId = elementId;
        jQuery.prompt(message, { callback: function() { jQuery("#" + document.promptCallbackId).focus(); } });
    }
};

var ajaxPost = function(formId) {
    var $f = jQuery("#" + formId);
    var action = $f.attr("ajaxAction");
    if (!action) action = $f.attr("action");
    var json = { };
    var obj = $f.find("input[type!=button][type!=submit][type!=reset], select, textarea");
    for (var i = 0; i < obj.length; i++) {
        with (obj[i]) {
            if (type == "select-multiple") {
                var sel = Array();
                for (j = 0; j < options.length; j++) { if (options[j].selected) sel.push(options[j].value); }
                json[id] = sel;
            } else if (type == "textarea") {
                if (jQuery(obj[i]).hasClass("ghost")) json[id] = "";
                else json[id] = jQuery(obj[i]).val();
            } else if (type == "checkbox") {
                if (checked) json[id] = value;
                else json[id] = "";
            } else if (type == "radio") {
                if (!json[name] && checked) json[name] = value;
            } else {
                if (jQuery(obj[i]).hasClass("ghost")) json[id] = "";
                else json[id] = value;
            }
        }
    }
    jQuery.ajax({ url: action, type: "POST", data: json, dataType: "script", timeout: 30000, success: function() { }, error: function() { } });
    return false; // prevent <form> submission after we've done our AJAX action
};

jQuery(function() {
    jQuery("input[type=text][prmGhost], textarea[prmGhost]").each(function(i) {
        var t = jQuery(this);
        if (t.val() == "") t.addClass("ghost").val(t.attr("prmGhost"));
        t.focus(function() { var z = jQuery(this); if (z.val() == z.attr("prmGhost")) z.removeClass("ghost").val(""); if (z.hasClass("ghost")) z.removeClass("ghost"); });
        t.blur(function() { var z = jQuery(this); if (z.val() == "" || z.val() == z.attr("prmGhost")) z.addClass("ghost").val(z.attr("prmGhost")); else if (z.val() != z.attr("prmGhost")) z.removeClass("ghost"); });
        t.mouseleave(function() { var z = jQuery(this); if (z.val() != z.attr("prmGhost")) z.removeClass("ghost"); });
    });
    jQuery("[prmTip]:not([prmTipoptions]):not(.flagTipSetup)").hover(function() { Tip(jQuery(this).attr("prmTip")); }, function() { UnTip(); }).addClass("flagTipSetup");
    jQuery("[prmTip][prmTipoptions]:not(.flagTipSetup)").hover(function() { eval('Tip(jQuery(this).attr("prmTip"), ' + jQuery(this).attr("prmTipoptions") + ');'); }, function() { UnTip(); }).addClass("flagTipSetup");
    jQuery("[prmTagtip]:not([prmTipoptions]):not(.flagTipSetup)").hover(function() { TagToTip(jQuery(this).attr("prmTagtip")); }, function() { UnTip(); }).addClass("flagTipSetup");
    jQuery("[prmTagtip][prmTipoptions]:not(.flagTipSetup)").hover(function() { eval('TagToTip(jQuery(this).attr("prmTagtip"), ' + jQuery(this).attr("prmTipoptions") + ');'); }, function() { UnTip(); }).addClass("flagTipSetup");
});