﻿/// <reference path="jquery-1.4.2.min.js" />

//BEGIN GENERAL FUNCTIONS

function debug(msg) {
    if ((_console == null) || (_console.closed)) {
        _console = window.open("", "console", "width=800,height=600,resizable,scrollbars");
        _console.document.open("text/plain");
    }

    _console.focus();
    _console.document.writeln(msg);
}

function initializeGlobalStyles(selector) {

    if (selector) {
        $(selector + ' input').addClass('ui-corner-all centerText');
        $(selector + ' textarea').addClass('ui-corner-all');
    }
    else {
        $('input:not(:hidden)').addClass('ui-corner-all centerText');
        $('textarea').addClass('ui-corner-all');
    }

}

function XMLtoString(strX) {
    var rx1 = /</g;
    var rx2 = />/g;

    return strX.replace(rx1, "&lt;").replace(rx2, "&gt;");
}

// returns number of days elapsed betwixt 2 js date objects.  plug more recent date into date1
function daysElapsed(date1, date2) {
    var difference = Date.UTC(date1.getYear(), date1.getMonth(), date1.getDate(), 0, 0, 0) - Date.UTC(date2.getYear(), date2.getMonth(), date2.getDate(), 0, 0, 0);
    return difference / 1000 / 60 / 60 / 24;
}

function LogFormData(formData, fileName) {
    $.ajax({
        type: "POST",
        url: "/ajaxServants/Generic/LogFormData.aspx",
        data:
            {
                url: window.location.href,
                formData: formData,
                fileName: fileName
            },
        async: false,
        error: function (xhr, textStatus, errorThrown) {
            alert("An error occurred.\n\nxhr response: " + xhr.responseText + "\n\nHTTP status code: " + xhr.status + "\n\nerrorThrown: " + errorThrown);
        }
    });
}

function iFrameHeightSetter(pnl) {
    var theFrame = $("iframe", pnl);
    theFrame.height(theFrame.contents().find("body").height() + 33);
}

//END GENERAL FUNCTIONS

//BEGIN MASTER PAGE FUNCTIONS

function initializeMasterPage(preventInitGlobalStyles) {

    $("#nav li").hover(function () { $(this).find('ul:first').css({ visibility: "visible", display: "none" }).show(400); }, function () { $(this).find('ul:first').css({ visibility: "hidden" }); });

    //set CSS styles
    $('.cContent').addClass('someContent ui-corner-all ui-widget-content');
    $('.cHeading1').addClass('ui-corner-all ui-widget-content divHeading');
    $('.cHeading2').addClass('ui-widget-header ui-corner-all ui-widget-content divHeading');
    $('.cHeading3').addClass('ui-widget-header ui-corner-all ui-widget-content divHeadingSmall');

    if (!preventInitGlobalStyles) { initializeGlobalStyles(); }

    //This Class will add on blur validation of date
    $('.dateCheckAlert').blur(function () { dateCheckWarning(this); });

    //This Class will add on blur validation of date Time
    $('.dateTimeCheckAlert').blur(function () { dateTimeCheckWarning(this); });

    //This Class will add on blur validation of number
    $('.numberCheckAlert').blur(function () { numberCheckWarning(this); });

    $('.emailCheckAlert').blur(function () { emailCheckWarning(this); });

    //This Class will add onfocus and onblur functions for the control
    $('.highlightSelection').focus(function () { selectionChange(this); });
    $('.highlightSelection').blur(function () { selectionBack(this); });

}

//END MASTER PAGE FUNCTIONS

//BEGIN SUB PAGE FUNCTIONS

var columnWidth = 150;
var $container;

function setColWidths(jqObj) {
    jqObj.children().each(function () {
        $container = $(this);
        $container.width(Math.ceil($container.width() / columnWidth) * columnWidth);
    })
}

//chrome does not handle margin:auto well, so this is the workaround
function setMargins(jqObj) { jqObj.each(function () { $(this).css("margin-left", ($(this).parent().width() / 2) - ($(this).width() / 2)) }); }

function addBox(containerDiv, className, ajaxPage, callback) {
    $(containerDiv).append('<div id="ajaxLoader" style="margin:33px 0px 0px 33px;"><img alt="" src="../images/ajaxLoadGifs/cupertino/ajax-loader1.gif" /></div>');
    $('#ajaxLoader').fadeIn('slow');

    $.ajax({
        type: "GET",
        url: "../ajaxServants/ProspectDashboard/" + ajaxPage + ".aspx",
        success: function (returnData) {
            if (returnData.substr(0, 14) == "SessionExpired") { window.location = "../Default.aspx"; }
            else {
                $('#ajaxLoader').remove();
                $(containerDiv).append(returnData.replace(className, className + ' ui-helper-hidden'));
                $(containerDiv + ' .' + className + ':last').fadeIn('slow');
                initializeGlobalStyles(containerDiv);
                setColWidths($(containerDiv + " > div"));
                setMargins($("input, select", containerDiv));
                callback != null ? callback() : null;
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert("An error occurred.\n\nxhr response: " + xhr.responseText + "\n\nHTTP status code: " + xhr.status + "\n\nerrorThrown: " + errorThrown);
        }
    });
}

function removeBox(theBox) { confirm("Are you sure you want to delete this?") ? $(theBox).parent().parent().fadeOut(function () { $(this).remove(); }) : null; }

function handleRadioButtonGroup(selectedButton, buttonClass) { $(buttonClass).not(selectedButton).attr("checked", false); }

function ShowDynamicForm(url, title, refresh) {
    var frame = document.getElementById("dynamicForm");
    frame.src = url;
    var dlg = $("#divDynamicForm").dialog(
        {
            close: function (event, ui) {
                if (refresh == true) {
                    window.location.href = window.location.href;
                }
            },
            title: title,
            width: 1000,
            height: 575,
            position: [13, 33],
            success: function (event, ui) {
                $(this).dialog('close');
            }
        }
    );
    dlg.parent().appendTo(jQuery("form:first"));
}

function ShowProspectDashBoardDynamicForm(url, title, refresh) {
    var frame = document.getElementById("dynamicForm");
    frame.src = url;
    var dlg = $("#divDynamicForm").dialog(
        {
            close: function (event, ui) {
                window.frames[4].location.reload();
            },
            title: title,
            width: $(window).width() - 60,
            height: $(window).height() - 60,
            position: 'center',
            success: function (event, ui) {
                $(this).dialog('close');
            }
        }
    );
    dlg.parent().appendTo(jQuery("form:first"));
}

//END SUB PAGE FUNCTIONS

//BEGIN VALIDATION FUNCTIONS

function isNotEmpty(txt) { if (txt == null || txt.length == 0) { return false; } else { return true; } }

function isNumber(str) {
    var re = /^[-]?\d*\.?\d*$/;
    str = str.toString();
    if (!isNotEmpty(str) || !re.test(str)) { return false; } else { return true; }
}

function isValidEmail(str) {
    var re = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; //regular expression will check to make sure that the entered text is a valid email address – i.e. contains at least one “.”, an “@” symbol and an appropriate top-level domain suffix (e.g. .com, .net, etc)
    str = str.toString();
    if (!isNotEmpty(str) || !str.match(re)) { return false; } else { return true; }
}

function isValidDate(dt) {
    var theDateArr = dt.split("/");
    if (theDateArr.length != 3) { return false; }
    else if (theDateArr[0] < 1 || theDateArr[0] > 12) { return false; }
    else if (theDateArr[1] < 1 || theDateArr[1] > 31) { return false; }
    else if (theDateArr[2] < 1980 || theDateArr[2] > 2050) { return false; }
    return true;
}

function isValidTime(tm) {
    var theTimeArr = tm.split(":");
    if (theTimeArr.length != 2) { return false; }
    else if (theTimeArr[0] < 1 || theTimeArr[0] > 12) { return false; }
    else if (theTimeArr[1] > 59) { return false; }
    return true;
}

function isValidDateTime(dttm) {
    var theDateTimeArr = dttm.split(" ");
    if (theDateTimeArr.length != 3) { return false; }
    else if (!isValidDate(theDateTimeArr[0])) { return false; }
    else if (!isValidTime(theDateTimeArr[1])) { return false; }
    else if (theDateTimeArr[2] != "am" && theDateTimeArr[2] != "pm") { return false; }
    return true;
}

//END VALIDATION FUNCTIONS

//Date Check Warning alert

function dateCheckWarning(obj) {
    var $element = $(obj);
    if ($element.val() != "") {
        if (!isValidDate($element.val())) {
            alert("Date is invalid");
            $element.val("");
        }
    }

}

function dateTimeCheckWarning(obj) {
    var $element = $(obj);
    if ($element.val() != "") {
        if (!isValidDateTime($element.val())) {
            alert("Date or Time is invalid");
            $element.val("");
        }
    }

}

function numberCheckWarning(obj) {
    var $element = $(obj);
    if (!isNumber($element.val())) {
        alert("Invalid Input");
        $element.val("");
    }

}

function emailCheckWarning(obj) {
    var $element = $(obj);
    if (!isValidEmail($element.val())) {
        alert("Invalid Email");
        $element.val("");
    }

}

// Below Two Functions are for onfucus and onblur properties respectively, to make the selected controls corresponding label orange then back to black.
function selectionChange(obj) {
    var $label = $(obj).parent().prev().children('label');
    $label.attr('style', 'color:orange;');
}

function selectionBack(obj) {
    var $label = $(obj).parent().prev().children('label');
    $label.attr('style', 'color:black;');

}

// Search functions

function ShowSearch() {
    $("#divSearch").dialog({
        modal: true,
        minHeight: 100,
        minWidth: 535,
        position: ["left", 25]
    }).parent().appendTo($("#divmodal"));
}

function CheckSearchVal(type) {
    if ($("#txtSearchTerm").val().length > 0) {
        location.href = "/" + type + "/Search.aspx?t=" + escape($("#txtSearchTerm").val()) + "&sc=" + $("#selType").val();
    } else { return false; }
}

//Evaluation Form Function for manipulation of recruiting Person Day Options

function RecruitingDayPersonOptions(sportId) {

    if (sportId == "3" || sportId == "15" || sportId == "31" || sportId == "13" || sportId == "67" || sportId == "18" || sportId == "54") {
        switch ($('[id$=dropEvalType]').val()) {
            case "S":
                $('.trRPDType').removeAttr('style');
                $('.trRDCount').attr("style", "display:none;");
                break;
            case "T":
                $('.trRPDType').attr("style", "display:none;");
                $('.trRDCount').removeAttr('style');
                break;
            case "TT":
                $('.trRPDType').attr("style", "display:none;");
                $('.trRDCount').removeAttr('style');
                break;
            case "SU":
                $('.trRPDType').removeAttr('style');
                $('.trRDCount').attr("style", "display:none;");
                break;
        }
    }
    else {
        $('.trRPDType').attr("style", "display:none;");
        $('.trRDCount').attr("style", "display:none;");
    }
}

function EnableRecruitingDayPersonSport(sportId) {
    if (sportId == "3" || sportId == "15" || sportId == "31" || sportId == "13" || sportId == "67" || sportId == "18" || sportId == "54")
        return true;
    else
        return false;
}
