
// js-eval ajax shortcut
var coordinator_jajax = function(callURL, postData, timeoutMS) {
    if (!timeoutMS) timeoutMS = 60000;
    jQuery.ajax({
        url: callURL,
        type: "POST",
        data: postData,
        dataType: "script",
        timeout: timeoutMS,
        success: function(data, textStatus) { return true; },
        error: function(xmlhr, textStatus, errorThrown) {
            jQuery.prompt("AJAX request error: " + textStatus + "\n\nPlease try again.");
        }
    });
};

if (typeof jQuery != 'undefined') {
    jQuery(function() {
        jQuery(".coordinator a.addWorker").click(function() {
        });
        jQuery(".coordinator a.removeWorker").click(function() {
        });
        
        jQuery(".coordinator a.addEvent").click(function() {
        });
        jQuery(".coordinator a.editEvent").click(function() {
        });
        jQuery(".coordinator a.removeEvent").click(function() {
        });
        
        jQuery(".coordinator a.addAssignment").click(function() {
        });
        jQuery(".coordinator a.removeAssignment").click(function() {
        });
        
        jQuery(".coordinator a.addExclusion").click(function() {
        });
        jQuery(".coordinator a.removeExclusion").click(function() {
        });
        
        jQuery(".coordinator ul.tabs li a").click(function() {
            var $t = jQuery(this);
            var id = $t.parents("form:first").attr("id");
            var selected = this.href.substr(this.href.indexOf("#") + 1);
            var $tabs = $t.parent().parent().children().removeClass("active");
            jQuery("#" + id + "_" + selected).addClass("active");
            jQuery("#" + id + "_tabdata_" + selected).show().siblings(".tabdata").hide();
            return false;
        });
        
        jQuery(".coordinator select.userStatus").change(function() {
            var $t = jQuery(this);
            window.location = "?page=coordinator-workers&act=workerstatus&id=" + $t.attr("tag") + "&status=" + $t.val();
            //coordinator_jajax("?page=coordinator-workers&ajax=1&act=workerstatus", { ID: $t.attr("tag"), status: $t.val() });
        });
        
        jQuery(".coordinator #event_date").change(function() {
            jQuery(".coordinator #txtRecurStartDate_recur").val(jQuery.formatDate(jQuery(this).val()));
        });
        
        jQuery(".coordinator #txtRecurStartDate_recur").change(function() {
            jQuery(".coordinator #event_date").val(jQuery.formatDate(jQuery(this).val()));
        });
        
        jQuery(".coordinator #recurs").change(function() {
            if (jQuery(this).val() == "1") {
                jQuery(".coordinator div.recur").show();
            } else {
                jQuery(".coordinator div.recur").hide();
            }
        }).change();
        
        jQuery("#event_save").click(function() { jQuery("#coordinator_event").submit(); });
        jQuery("#event_cancel").click(function() { window.location = '?page=coordinator-events'; });
        
        jQuery("input.date:text").dateField();
        jQuery("input.time:text").timeField();
        
        jQuery("select.multiselect").multiSelect({ selectAll: false, oneOrMoreSelected: '*', blur:
            function($obj) {
                var id = $obj.attr("id").substr(10);
                var workers = [];
                var $c = jQuery("input[name^=assignment" + id + "]:checked").each(function() { workers.push(this.value); });
                coordinator_jajax("?page=coordinator-assignments&ajax=1&act=saveassignment", { id: id, 'workers[]': workers });
            }
        });
    });

    jQuery.formatDate = function(str) {
        if (str != "") {
            str = str.toString();
            var parts = str.split(/[-\/]/);
            if (parts.length == 3) {
                // month/day/year
                var m = parseInt(parts[0], 10);
                var d = parseInt(parts[1], 10);
                var y = parseInt(parts[2], 10);
                if (m > 12 || m < 1) {
                    // alternate form YYYY-mm-dd
                    y = parseInt(parts[0], 10);
                    m = parseInt(parts[1], 10);
                    d = parseInt(parts[2], 10);
                }
                if (!isNaN(m) && !isNaN(d) && !isNaN(y) && m >= 1 && m <= 12 && d >= 1 && d <= 31) {
                    if (y < 100 && y >= 70) {
                        y += 1900;
                    } else if (y < 70) {
                        y += 2000;
                    } else {
                        y = (y % 100) + 2000;
                    }
                    return (m + "/" + d + "/" + y);
                } else {
                    return "";
                }
            } else if (parts.length == 2) {
                // only month/day (OR month/year)
                var m = parseInt(parts[0], 10);
                var d = parseInt(parts[1], 10);
                if ((parts[1].length == 2 && parts[1][0] == '0') || parts[1].length == 4) {
                    if (!isNaN(m) && !isNaN(d) && m >= 1 && m <= 12) {
                        if (d < 10) d += 2000;
                        return (m + "/1/" + d); // d is actually y in this case
                    } else {
                        return "";
                    }
                } else {
                    if (!isNaN(m) && !isNaN(d) && m >= 1 && m <= 12 && d >= 1 && d <= 31) {
                        var y = new Date().getYear();
                        if (y > 99 && y < 1970) y += 1900;
                        return (m + "/" + d + "/" + y);
                    } else {
                        return "";
                    }
                }
            } else {
                // unknown...reset
                return "";
            }
        } else return "";
    };

    jQuery.fn.dateField = function() {
        return this.each(function() {
            if (jQuery(this).attr("autoDateFieldEnabled")) return; // already enabled
            jQuery(this).attr("autoDateFieldEnabled", true);
            //jQuery(this).after("<img src=\"images/cal.gif\" id=\"datetrigger" + this.id + "\" align=\"absmiddle\" style=\"cursor: pointer; border: 1px solid black; margin-right: 8px;\" title=\"Date selector\" />");
            //Calendar.setup({inputField: this.id, ifFormat: "%m/%d/%Y", button: "datetrigger" + this.id, align:"bR", singleClick:true});
            //jQuery("#datetrigger" + this.id).mouseover(function() { this.style.borderColor="#FF0000"; }).mouseout(function() { this.style.borderColor="#000000"; });
            jQuery(this).change(function() {
                if (jQuery(this).attr("prmFormat")) {
                    var tD = new Date(jQuery.formatDate(jQuery(this).val()));
                    jQuery(this).val(tD.formatDate(jQuery(this).attr("prmFormat")));
                } else {
                    jQuery(this).val(jQuery.formatDate(jQuery(this).val()));
                }
            });
        });
    };

    jQuery.formatTime = function(str) {
        if (str != "") {
            var parts = jQuery.trim(str.replace(/\s+/, " ")).split(/[: ]/);
            var num, h = 0, m = 0, s = 0, assumePM = false, detail = 0, timeStr = "", pmStr = "";
            if (parts[0] > 99 && parts[0] < 2400) { // for lazy people
                m = parts % 100;
                h = (parts - m) / 100
                parts[0] = m;
                parts.unshift(h);
            } else if (parts[0] < 100 && parts[0] > 12 && parts.length == 1) { // for EXTRA lazy people
                m = parts % 10;
                h = (parts - m) / 10;
                m *= 10;
                if (m < 60) { parts[0] = m; parts.unshift(h); }
            }
            for (var i = 0; i < parts.length; i++) {
                num = parseInt(parts[i]);
                if (i == 0) {           // hours first
                    if (isNaN(num) || num < 0 || num > 23) { timeStr = ""; break; }
                    else if (num > 12) { h = num - 12; pmStr = " PM"; }
                    else if (num == 0) { h = 12; pmStr = " AM"; }
                    else h = num;
                    timeStr += (h + 0);
                    if (h < 8 || h == 12) assumePM = true;
                    detail++;
                } else if (i == 1) {    // then minutes, if supplied
                    if (isNaN(num) || num < 0 || num > 59) break;
                    else m = num;
                    timeStr += ":" + ((m < 10) ? "0" : "") + m;
                    detail++;
                } else if (i == 2) {    // then seconds, if supplied
                    if (isNaN(num) || num < 0 || num > 59) break;
                    else s = num;
                    timeStr += ":" + ((s < 10) ? "0" : "") + s;
                    detail++;
                }
            }
            if (timeStr != "") {
                if (detail < 2) timeStr += ":00";   // add minutes
                //if (detail < 3) timeStr += ":00";   // add seconds
                if (pmStr != "") timeStr += pmStr;
                else timeStr += (str.match(/(pm|p)/i) || (assumePM && !str.match(/(am|a)/i))) ? " PM" : " AM";
            }
            return timeStr;
        } else return "";
    };

    jQuery.fn.timeField = function() {
        return this.each(function() {
            if (jQuery(this).attr("autoTimeFieldEnabled")) return; // already enabled
            jQuery(this).attr("autoTimeFieldEnabled", true);
            jQuery(this).change(function() {
                jQuery(this).val(jQuery.formatTime(jQuery(this).val()));
            });
        });
    };
    
}