// JavaScript Document
var scores = new Array();
var cell_height = new Array();
var comment_cell_height = new Array();
var step = 10;
var interval = 10;
var max_findings_height = 330;
var max_comments_height = 105;

var j$ = jQuery.noConflict();

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function AC_AddExtension(src, ext) {
	if (src.indexOf('?') != -1) {
		return src.replace(/\?/, ext + '?'); 
	} else {
		return src + ext;
	}
}

function AC_Generateobj(objAttrs, params, embedAttrs) {
	var str = '<object ';
	for (var i in objAttrs) { str += i + '="' + objAttrs[i] + '" '; }
	str += '>';
	for (var i in params) { str += '<param name="' + i + '" value="' + params[i] + '" /> '; }
	str += '<embed ';
	for (var i in embedAttrs) { str += i + '="' + embedAttrs[i] + '" '; }
	str += ' ></embed></object>';
	document.write(str);
}

function AC_FL_RunContent() {
	var ret = 
		AC_GetArgs(arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
		AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent() {
	var ret = 
		AC_GetArgs(arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000", null);
		AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType) {
	var ret = new Object();
	ret.embedAttrs = new Object();
	ret.params = new Object();
	ret.objAttrs = new Object();
	for (var i = 0; i < args.length; i = i + 2) {
		var currArg = args[i].toLowerCase();	 
		switch(currArg) {	
			case "classid":
				break;
			case "pluginspage":
				ret.embedAttrs[args[i]] = args[i + 1];
				break;
			case "src":
			case "movie":	
				args[i + 1] = AC_AddExtension(args[i + 1], ext);
				ret.embedAttrs["src"] = args[i + 1];
				ret.params[srcParamName] = args[i + 1];
				break;
			case "onafterupdate":
			case "onbeforeupdate":
			case "onblur":
			case "oncellchange":
			case "onclick":
			case "ondblClick":
			case "ondrag":
			case "ondragend":
			case "ondragenter":
			case "ondragleave":
			case "ondragover":
			case "ondrop":
			case "onfinish":
			case "onfocus":
			case "onhelp":
			case "onmousedown":
			case "onmouseup":
			case "onmouseover":
			case "onmousemove":
			case "onmouseout":
			case "onkeypress":
			case "onkeydown":
			case "onkeyup":
			case "onload":
			case "onlosecapture":
			case "onpropertychange":
			case "onreadystatechange":
			case "onrowsdelete":
			case "onrowenter":
			case "onrowexit":
			case "onrowsinserted":
			case "onstart":
			case "onscroll":
			case "onbeforeeditfocus":
			case "onactivate":
			case "onbeforedeactivate":
			case "ondeactivate":
			case "type":
			case "codebase":
				ret.objAttrs[args[i]] = args[i + 1];
				break;
			case "width":
			case "height":
			case "align":
			case "vspace": 
			case "hspace":
			case "class":
			case "title":
			case "accesskey":
			case "name":
			case "id":
			case "tabindex":
				ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i + 1];
				break;
			default:
				ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i + 1];
		}
	}
	ret.objAttrs["classid"] = classid;
	if (mimeType) ret.embedAttrs["type"] = mimeType;
	return ret;
}

j$("#btnClose").live("click", function() {
    window.close();
});

j$("#btnReturn").live("click", function() {
    window.location.href = j$("#returnHref").val();
});
    //function validateCorrectiveAction() {
j$("#btnCASubmit").live("click", function() {
    var action = j$(this).val();
    if (action.indexOf("Approve") > -1 || action.indexOf("Close") > -1 || action.indexOf("Submit") > -1) {
        var val = j$('#proposedCorrectiveAction').val();
        if (val == null || val == '') {
            alert('Proposed corrective action is blank and cannot be accepted.');
            return false;
        }
        return true;
    }
    else if (j$(this).val() == "Reject Corrective Action") {
        //reset the correctiveactionsubmitted flag
        var ccqID = 0;
        var fID = 0;
        var hID = 0;
        if (j$("#hazrepid").val() != null) {
            hID = j$("#hazrepid").val();
        }
        if (j$("#customerChecklistQuestionID").val() != null) {
            ccqID = j$("#customerChecklistQuestionID").val();
        }
        if (j$("#findingID").val() != null) {
            fID = j$("#findingID").val();
        }

        if (j$("#module").val().indexOf("ASSURANCECHECK") > -1) {
            var isAC = 1;
        }
        else {
            var isAC = 0;
        }
        var customerID = j$("#customerID").val();
        var data = "{'CustomerChecklistQuestionID':'" + ccqID + "','FindingID':'" + fID + "','HazrepID':'" + hID;
        data = data + "','IsAssuranceCheck':'" + isAC + "','CustomerID':'" + customerID + "'}"; ;
        var url = "/PRISMServices/PrismServices.asmx/RejectCorrectiveAction";
        j$.ajax({
            async: true,
            type: "POST",
            url: url,
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                //swap the reject and accept buttons for a "Reassign" button
                if (j$("#hdnRoles").val().indexOf("Close") > -1) {
                    j$("#divSubmit").html(response.d);
                }
            },
            failure: function(msg) {
                j$("div.divMsg").html(msg);
            }
        });
        if (j$("#hdnRoles").val() == "Approve") { return true;} else {return false; }
    }
});

    function DeleteUploadedFile(hazrepid, fileid) {
        if (confirm("Are you sure you want to delete this file?")) {
            var data = "{'HazrepID':'" + hazrepid + "','FileID':'" + fileid + "'}";
            j$.ajax({
                async: false,
                type: "POST",
                timeout: 10000,
                mode: "queue",
                url: "/PRISMServices/PrismServices.asmx/DeleteUploadedFile",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    if (response.d && response.d.length > 0)
                    { j$("#divAttachedFiles").html(response.d); }
                    else
                    { j$("#divAttachedFiles").html("<table></table>"); }

                },
                failure: function(msg) {
                    alert(msg);
                }
            });
        }
    }

    function RefreshUploadedFiles(hazrepid) {
        if (hazrepid > 0) {
            var data = "{'HazrepID':'" + hazrepid + "'}";
            j$.ajax({
                async: false,
                type: "POST",
                timeout: 10000,
                mode: "queue",
                url: "/PRISMServices/PrismServices.asmx/RefreshUploadedFiles",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    if (response.d && response.d.length > 0)
                    { j$("#divAttachedFiles").html(response.d); }
                    else
                    { j$("#divAttachedFiles").html("<table></table>"); }
                },
                failure: function(msg) {
                    alert(msg);
                }
            });
        }
    }

    function DeleteHazrep(hazrepid) {
        if (confirm("Are you sure you want to delete this item?")) {
            var data = "{'HazrepID':'" + hazrepid + "'}";
            j$.ajax({
                async: false,
                type: "POST",
                timeout: 10000,
                mode: "queue",
                url: "/PRISMServices/PrismServices.asmx/DeleteHazrep",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                },
                failure: function(msg) {
                    alert(msg);
                }
            });
        }
    }

    function AutoSaveHazrep(hazrepid, customerid) {
        //hazard details
        var categoryid = j$('input[name=categoryId]:checked').val()
        var severity = j$('input[name=severity]:checked').val()
        var assignedto;
        var selectedUserName = j$("#selectUser :selected").text();
        if (selectedUserName != null) {
            assignedto = selectedUserName;
            j$("#assigned_to").val(selectedUserName);
        }
        else {
            assignedto = j$("#assigned_to").val();
        }
        var duedate = j$("#date_due").val();
        if (duedate == null || duedate == "") {
            var curDate = new Date();
            var curMonth = curDate.getMonth();
            var curDay = curDate.getDate();
            var curYear = curDate.getFullYear();
            duedate = (curMonth + 1).toString() + "/" + curDay.toString() + "/" + curYear.toString();
        }
        var details = j$("#details").val();
        if (details != null) {
            var data = "{'HazrepID':'" + hazrepid + "','CustomerID':'" + customerid;
            data = data + "','HazrepCategoryID':'" + categoryid + "','Severity':'";
            data = data + severity + "','HazardDetails':'" + details + "','DueDate':'" + duedate + "','AssignedTo':'" + assignedto + "'}";
            j$.ajax({
                async: false,
                type: "POST",
                timeout: 10000,
                mode: "queue",
                url: "/PRISMServices/PrismServices.asmx/AutoSaveHazrep",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var returnData = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
                    //update the corrective action notification link with the returned hazrep id
                    if (j$("#selectUser").val() != null) {
                        var selectedval = j$("#selectUser").val().split("|");
                        var userid = selectedval[selectedval.length - 1];
                        /*build the link to send to the corrective action notification page*/
                        var notificationHref = "\CorrectiveActionNotification.aspx?type=1&module=HAZ";
                        notificationHref = notificationHref + "&hID=" + returnData.toString() + "&to=" + userid.toString();
                        j$("#notifyLink").attr("href", notificationHref);
                    }
                    var fileUploadHref = "\FileUpload.aspx?hazrep_id=" + returnData.toString() + "&new_hazrep=0";
                    j$("#FileUploadLink").attr("href", fileUploadHref);
                    var href = "index.aspx?module=hazrep&action=tracker&id=" + returnData.toString();
                    if (hazrepid == 0 && returnData > 0) {
                        href = href + "&notify=true";
                    }
                    window.location.href = href;
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
        }
    }

    function HazrepNotify(hazrepid, customerid) {
        if (!checkUserSelection(-1))
        { return false; }
        else {
            AutoSaveHazrep(hazrepid, customerid, false);
        }
        return true;
    }

    function SaveComments(checklistquestionid, customerchecklistquestionid) {
        //auto-save comments
        var comments = j$("#txtcomments_" + checklistquestionid).val();
        if (comments != null) {
            var data = "{'ChecklistQuestionID':'" + checklistquestionid + "','CustomerChecklistQuestionID':'";
            var data = data + customerchecklistquestionid + "','Comments':'" + comments + "'}";

            j$.ajax({
                async: false,
                type: "POST",
                timeout: 10000,
                mode: "queue",
                url: "PRISMServices/PrismServices.asmx/SaveIEPComments",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    var returnVal = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
                    if (returnVal == 1) {
                        //change the circle icon to red
                        j$("#comments_button_" + checklistquestionid).attr("src", "images/iep/circle_down_red2.png");
                    }
                },
                failure: function(msg) {
                    alert(msg);
                }
            });
        }
    }

    function SaveFindingDetails(customerchecklistquestionid, findingid, hazrepid, isassurancecheck, checklistquestionid, checklistid) {
        //pick up finding details that were typed in
        var duedate = j$("#findings_" + checklistquestionid + "_date_due").val();
        var score = j$("#question_score_" + checklistquestionid).val();
        if (duedate == null || duedate == "") {
            var curDate = new Date();
            var curMonth = curDate.getMonth();
            var curDay = curDate.getDate();
            var curYear = curDate.getFullYear();
            duedate = (curMonth + 1).toString() + "/" + curDay.toString() + "/" + curYear.toString();
        }
        var assignedto = "";
        if (j$("#selectUser_" + checklistquestionid) != null) {
            var selectedUserName = j$("#selectUser_" + checklistquestionid + " option:selected").text();
            if (selectedUserName != null) {
                assignedto = selectedUserName;
            }
            else {
                assignedto = j$("#findings[" + checklistid + "][assigned_to]").val();
            }
        }
        var details = j$("#finding_details_" + checklistquestionid).val();
        if (details != null) {
            var data = "{'CustomerChecklistQuestionID':'" + customerchecklistquestionid + "','FindingID':'" + findingid;
            data = data + "','HazrepID':'" + hazrepid + "','IsAssuranceCheck':'" + isassurancecheck + "','FindingDetails':'";
            data = data + details + "','DueDate':'" + duedate + "','Score':'" + score + "','AssignedTo':'" + assignedto + "'}";
            j$.ajax({
                async: false,
                type: "POST",
                timeout: 10000,
                mode: "queue",
                url: "../PRISMServices/PrismServices.asmx/SaveFindingDetails",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    //var returnData = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
                    if (response.d.ChangeIcon == 1) {
                        //change the circle icon to red
                        j$("#findings_button_" + checklistquestionid).attr("src", "images/iep/circle_right_red2.png");
                    }
                    //update the corrective action notification link with the returned finding id
                    var selectedval = j$("#selectUser_" + checklistquestionid).val().split("|");
                    var userid = selectedval[selectedval.length - 1];
                    var hrefString = "\CorrectiveActionNotification.aspx?type=1&module=IEP&ccqID=" + customerchecklistquestionid;
                    hrefString = hrefString + "&fID=" + response.d.FindingID + "&to=" + userid;
                    window.location.href = "index.aspx?module=iep&action=open_checklist&id=" + checklistid + "&open_finding=" + checklistquestionid;
                    j$("#notifyLink_" + checklistquestionid).attr("href", hrefString);
                },
                failure: function(msg) {
                    alert(msg);
                }
            });
        }
    }

    function SaveAssuranceCheck(customerchecklistquestionid, findingid, hazrepid, isassurancecheck, checklistquestionid, module) {
        j$("#divMsg").html("");
        //pick up finding details that were typed in
        var duedate = j$("#date_due").val();
        var score = 0; //pass 0 so score is not updated
        if (duedate == null || duedate == "") {
            var curDate = new Date();
            var curMonth = curDate.getMonth();
            var curDay = curDate.getDate();
            var curYear = curDate.getFullYear();
            duedate = (curMonth + 1).toString() + "/" + curDay.toString() + "/" + curYear.toString();
        }
        var assignedto = "";
        if (j$("#selectUser") != null) {
            var selectedUserName = j$("#selectUser option:selected").text();
            if (selectedUserName != null) {
                assignedto = selectedUserName;
            }
            else {
                assignedto = j$("#assigned_to").val();
            }
        }
        if (j$("#finding_details").val() == null || j$("#finding_details").val() == "") {
            j$("#divMsg").html("Please input the assurance check finding details.");
            return false;
        }
        var data = "{'CustomerChecklistQuestionID':'" + customerchecklistquestionid + "','FindingID':'" + findingid;
        data = data + "','HazrepID':'" + hazrepid + "','IsAssuranceCheck':'" + isassurancecheck + "','FindingDetails':'";
        data = data + j$("#finding_details").val() + "','DueDate':'" + duedate + "','Score':'" + score + "','AssignedTo':'" + assignedto + "'}";
        j$.ajax({
            async: false,
            type: "POST",
            timeout: 10000,
            mode: "queue",
            url: "/PRISMServices/PrismServices.asmx/SaveFindingDetails",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                //var returnData = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
                //update the corrective action notification link with the returned finding id
                var selectedval = j$("#selectUser").val().split("|");
                var userid = selectedval[selectedval.length - 1];
                var hrefString = "\CorrectiveActionNotification.aspx?type=1&module=";
                if (module == "HAZASSURANCECHECK") {
                    hrefString = hrefString + "HAZASSURANCECHECK&hID=" + hazrepid.toString() + "&fID=" +
                    response.d.FindingID + "&to=" + userid.toString();
                }
                else {
                    hrefString = hrefString + "IEPASSURANCECHECK&ccqID=" + customerchecklistquestionid.toString() +
                    "&fID=" + response.d.FindingID + "&to=" + userid.toString();
                }
                j$("#notifyLink").attr("href", hrefString);
            },
            failure: function(msg) {
            j$("#divMsg").html(msg);
                return false;
            }
        });
        return true;
    }

    function toggleNotifySection() {
        if (j$('#cbToggleNotify').is(":checked")) {
            j$('#divNotifyEnabled').removeClass("disabled");
            j$('#divNotifyEnabled').addClass("enabled");

            j$('#divNotifyDisabled').removeClass("enabled");
            j$('#divNotifyDisabled').addClass("disabled");
        }
        else {
            j$('#divNotifyEnabled').removeClass("enabled");
            j$('#divNotifyEnabled').addClass("disabled");
            j$('#divNotifyDisabled').removeClass("disabled");
            j$('#divNotifyDisabled').addClass("enabled");
        }
    }

    function toggleIEPNotifySection(id) {
        if (j$('#cbToggleNotify_' + id).is(":checked")) {
            j$('#divNotifyEnabled_' + id).removeClass("disabled");
            j$('#divNotifyEnabled_' + id).addClass("enabled");

            j$('#divNotifyDisabled_' + id).removeClass("enabled");
            j$('#divNotifyDisabled_' + id).addClass("disabled");
        }
        else {
            j$('#divNotifyEnabled_' + id).removeClass("enabled");
            j$('#divNotifyEnabled_' + id).addClass("disabled");
            j$('#divNotifyDisabled_' + id).removeClass("disabled");
            j$('#divNotifyDisabled_' + id).addClass("enabled");
        }
    }

    function checkUserSelection(id) {
        //if id = -1, then it is not an IEP, which is the only page that has multiple questions/findings
        //if the id > -1, then the id corresponds to the IEP question/finding combination 
        var selectedval;
        if (id > -1) {
            selectedval = j$("#selectUser_" + id.toString()).val().split("|");
        }
        else {
            selectedval = j$("#selectUser").val().split("|");
        }
        var userid = selectedval[selectedval.length - 1];
        if (userid == 0) {
            alert("Please select a user.");
            return false;
        }
        return true;
    }

    function setAssignedToLink(id, questionid, hazrepID, findingID, module) {
        if (module == "IEP") {
            var selectedval = j$("#selectUser_" + id).val().split("|");
        }
        else {
            var selectedval = j$("#selectUser").val().split("|");
        }
        var userid = selectedval[selectedval.length - 1];
        /*make sure the user selected a name*/
        if (userid > 0) {
            if (module == "IEP") {
                var selectedName = j$("#selectUser_" + id + " option:selected").text();
            }
            else {
                var selectedName = j$("#selectUser option:selected").text();
            }
            var hrefString = "\CorrectiveActionNotification.aspx?type=1&module=";
            /*build the link to send to the corrective action notification page*/
            if (module == "HAZASSURANCECHECK") {
                hrefString = hrefString + "HAZASSURANCECHECK&hID=" + hazrepID.toString();
                hrefString = hrefString + "&fID=" + findingID.toString() + "&to=" + userid.toString();

                /*update the text field with the selected name so that the record can be updated*/
                j$("[name=assigned_to]").val(selectedName);
            }
            if (module == "HAZ") {
                hrefString = hrefString + "HAZ&hID=" + hazrepID + "&to=" + userid.toString();

                /*update the text field with the selected name so that the record can be updated*/
                j$("[name=assigned_to]").val(selectedName);
            }
            if (module == "IEPASSURANCECHECK") {
                /*build the link to send to the corrective action notification page*/
                hrefString = hrefString + "IEPASSURANCECHECK&ccqID=" + questionid.toString() +
                "&fID=" + findingID.toString() + "&to=" + userid.toString();

                /*update the text field with the selected name so that the record can be updated*/
                var inputName = "findings[" + questionid.toString() + "][assigned_to]";
                j$("[name=" + inputName + "]").val(selectedName);
            }
            if (module == "IEP") {
                hrefString = hrefString + "IEP&ccqID=" + questionid.toString() + "&fID=" + findingID.toString() +
                "&to=" + userid.toString();
                /*update the text field with the selected name so that the record can be updated*/
                var inputName = "findings[" + id + "][assigned_to]";
                j$("[name=" + inputName + "]").val(selectedName);
            }

            //set link with new href string
            if (module == "IEP") {
                j$("#notifyLink_" + id).attr("href", hrefString);
            }
            else {
                j$("#notifyLink").attr("href", hrefString);
            }
        }
    }

    j$("select#ReportsByGroup").change(function() {
        var levelID = this.id.split("_");
        j$("#preview_" + levelID[1]).css({ "background-color": j$(this).val() });
    });
    
    function AssuranceCheckNotify(customerchecklistquestionid, findingid, hazrepid, isassurancecheck, checklistquestionid, module) {
        if (!checkUserSelection(-1))
        { return false; }
        else {
            if (!SaveAssuranceCheck(customerchecklistquestionid, findingid, hazrepid, isassurancecheck, checklistquestionid, module)) {
                return false;
            }
        }
        return true;
    }

    function change_score(id, score) {
        scores[id] = score;
        document.getElementById("question_score_" + id).value = score;
        update_score_graphics(id);

        if (score < 3) {
            show_findings(id);
        }
        else {
            hide_findings(id);
        }
    }

    function score_image_over(id, score) {
        var img_id = "score_icon_" + id + "_" + score;
        var score_img = document.getElementById(img_id);
        var my_score = scores[id];

        if (score_img) {
            if (my_score != score) {
                score_img.src = 'images/iep/' + score + '_gray.png';
            }
            else {
                score_img.src = 'images/iep/' + score + '_sel.png';
            }
        }
    }

    function score_image_out(id, score) {
        var img_id = "score_icon_" + id + "_" + score;
        var score_img = document.getElementById(img_id);
        var my_score = scores[id];

        if (score_img) {
            if (my_score == score) {
                score_img.src = 'images/iep/' + score + '_sel.png';
            }
            else if (my_score > score) {
                score_img.src = 'images/iep/blue.png';
            }
            else if (my_score > 0) {
                score_img.src = 'images/iep/gray.png';
            }
            else {
                score_img.src = 'images/iep/' + score + '_gray.png';
            }
        }
    }

    function update_score_graphics(id) {
        var my_score = scores[id];
        var img_id = "score_icon_" + id;

        for (var i = 1; i <= 5; i++) {
            var score_img = document.getElementById(img_id + "_" + i);
            if (score_img) {
                if (my_score == i) {
                    score_img.src = "images/iep/" + i + "_sel.png";
                }
                else if (my_score > i) {
                    score_img.src = "images/iep/blue.png";
                }
                else {
                    score_img.src = "images/iep/gray.png";
                }
            }
        }
    }

    function toggle_findings(id) {
        if (cell_height[id] == 0) {
            show_findings(id);
            j$('#historylink_' + id).removeClass("disabled");
            j$('#historylink_' + id).addClass("enabled");
        }
        else {
            hide_findings(id);
            j$('#historylink_' + id).removeClass("enabled");
            j$('#historylink_' + id).addClass("disabled");
        }
    }

    j$(document).ready(function() {
        j$("a.toggleDashboardDetails").live("click", function() {
            //get the area that is being shown
            var hazardID = this.id.split("_");

            if (j$("#toggleImg_" + hazardID[1].toString()).attr("src").indexOf("right") > -1) {
                j$("#divRiskAssDashboardDetails_" + hazardID[1].toString()).slideDown('slow', function() {
                    //show the full details
                    j$("#toggleImg_" + hazardID[1].toString()).attr("src", "/images/iep/circle_down_red2.png");
                    j$("#divRiskAssDashboardDetails_" + hazardID[1].toString()).removeClass("hidden");
                });
            }
            else if (j$("#toggleImg_" + hazardID[1].toString()).attr("src").indexOf("down") > -1) {
                j$("#divRiskAssDashboardDetails_" + hazardID[1].toString()).slideUp('slow', function() {
                    j$("#toggleImg_" + hazardID[1].toString()).attr("src", "/images/iep/circle_right_red2.png");
                    j$("#divRiskAssDashboardDetails_" + hazardID[1].toString()).addClass("hidden");
                });
            }
            return false;
        });

        j$("a.toggleProjectDashboardDetails").live("click", function() {
            //get the area that is being shown
            var projectManagerID = this.id.split("_");

            if (j$("#toggleProjectImg_" + projectManagerID[1].toString()).attr("src").indexOf("right") > -1) {
                j$("#divProjectDashboardDetails_" + projectManagerID[1].toString()).slideDown('slow', function() {
                    //show the full details
                j$("#toggleProjectImg_" + projectManagerID[1].toString()).attr("src", "/images/iep/circle_down_red2.png");
                j$("#divProjectDashboardDetails_" + projectManagerID[1].toString()).removeClass("hidden");
                });
            }
            else if (j$("#toggleProjectImg_" + projectManagerID[1].toString()).attr("src").indexOf("down") > -1) {
            j$("#divProjectDashboardDetails_" + projectManagerID[1].toString()).slideUp('slow', function() {
            j$("#toggleProjectImg_" + projectManagerID[1].toString()).attr("src", "/images/iep/circle_right_red2.png");
                j$("#divProjectDashboardDetails_" + projectManagerID[1].toString()).addClass("hidden");
                });
            }
            return false;
        });
        
        j$("tr.trDashboardDetail").live("click", function() {
            var ID = this.id.split("_");
            window.location.href = j$(this).find("#lnkAssignmentDetail_" + ID[1]).attr("href");
        });

        j$(".raDashDetailsTable tr:even").addClass("alt");

        j$(".raDashDetailsTable tr.trDashboardDetail").mouseover(function() {
            j$(this).addClass("highlight");
            j$(this).find("td").each(function() {
                j$(this).attr("style", "color:#ffffff;");
            });
        });

        j$(".raDashDetailsTable tr.trDashboardDetail").mouseout(function() {
            j$(this).removeClass("highlight");
            j$(this).find("td").each(function() {
                j$(this).attr("style", "color:#6c6d6e;");
            });
        });

        j$("#raDashboard tr.dashboardRow").mouseover(function() {
            j$(this).addClass("highlight");
            j$(this).find("td").each(function() {
                j$(this).attr("style", "color:#ffffff;");
            });
        });

        j$("#raDashboard tr.dashboardRow").mouseout(function() {
            j$(this).removeClass("highlight");
            j$(this).find("td").each(function() {
                j$(this).attr("style", "color:#6c6d6e;");
            });
        });

        j$("#divNotifyEnabled").hide();
        j$("#cbToggleNotify").live("click", function() {
            if (j$("#cbToggleNotify").is(":checked")) {
                j$("#divNotifyEnabled").show();
                j$("#divNotifyDisabled").hide();
            }
            else {
                j$("#divNotifyEnabled").hide();
                j$("#divNotifyDisabled").show();
            }
        });

        j$("div[id*=divNotifyEnabled_]").hide();
        j$("input:checkbox[id*=cbToggleNotify_]").live("click", function() {
            if (j$(this).is(":checked")) {
                j$("div[id*=divNotifyEnabled_]").show();
                j$("div[id*=divNotifyDisabled_]").hide();
            }
            else {
                j$("div[id*=divNotifyEnabled_]").hide();
                j$("div[id*=divNotifyDisabled_]").show();
            }
        });
    });
function show_findings(id) {
    var findings_cell = document.getElementById("findings_" + id);
    var findings_button = document.getElementById("findings_button_" + id);

    if (findings_cell) {
        cell_height[id] = cell_height[id] + step;
        if (cell_height[id] > max_findings_height) cell_height[id] = max_findings_height;
        findings_cell.style.height = cell_height[id] + "px";

        if (findings_button) {
            if (findings_button.src.indexOf("red2.png") >= 0) {
                findings_button.src = "images/iep/circle_down_red2.png";
            }
            else {
                findings_button.src = "images/iep/circle_down.png";
            }
        }

        if (cell_height[id] < max_findings_height) setTimeout("show_findings(" + id + ")", interval);
    }
}

function hide_findings(id) {
    var findings_cell = document.getElementById("findings_" + id);
    var findings_button = document.getElementById("findings_button_" + id);

    //    if (scores[id] < 3 && scores[id] > 0) alert("For any score less than 3, you must enter findings.");

    if (findings_cell)      // && (scores[id] > 2 || scores[id] == 0)
    {
        cell_height[id] = cell_height[id] - step;
        if (cell_height[id] < 0) cell_height[id] = 0;
        findings_cell.style.height = cell_height[id] + "px";

        if (findings_button) {
            if (findings_button.src.indexOf("red2.png") >= 0) {
                findings_button.src = "images/iep/circle_right_red2.png";
            }
            else {
                findings_button.src = "images/iep/circle_right.png";
            }
        }

        if (cell_height[id] > 0) setTimeout("hide_findings(" + id + ")", interval);
    }
}


function toggle_comments(id) {
    if (comment_cell_height[id] == 0) {
        show_comments(id);
    }
    else {
        hide_comments(id);
    }
}

function show_comments(id) {
    var comments_cell = document.getElementById("comments_" + id);
    var comments_button = document.getElementById("comments_button_" + id);

    if (comments_cell) {
        comment_cell_height[id] = comment_cell_height[id] + step;
        if (comment_cell_height[id] > max_comments_height) comment_cell_height[id] = max_comments_height;
        comments_cell.style.height = comment_cell_height[id] + "px";

        if (comments_button) {
            if (comments_button.src.indexOf("red2.png") >= 0) {
                comments_button.src = "images/iep/circle_down_red2.png";
            }
            else {
                comments_button.src = "images/iep/circle_light_down.png";
            }
        }

        if (comment_cell_height[id] < max_comments_height) setTimeout("show_comments(" + id + ")", interval);
    }
}

function hide_comments(id) {
    var comments_cell = document.getElementById("comments_" + id);
    var comments_button = document.getElementById("comments_button_" + id);

    if (comments_cell) {
        comment_cell_height[id] = comment_cell_height[id] - step;
        if (comment_cell_height[id] < 0) comment_cell_height[id] = 0;
        comments_cell.style.height = comment_cell_height[id] + "px";

        if (comments_button) {
            if (comments_button.src.indexOf("red2.png") >= 0) {
                comments_button.src = "images/iep/circle_right_red2.png";
            }
            else {
                comments_button.src = "images/iep/circle_light_right.png";
            }
        }

        if (comment_cell_height[id] > 0) setTimeout("hide_comments(" + id + ")", interval);
    }
}

function Notify(customerchecklistquestionid, findingid, hazrepid, isassurancecheck, checklistquestionid, checklistid) {
    if (!checkUserSelection(checklistquestionid))
    { return false; }
    else {
        SaveFindingDetails(customerchecklistquestionid, findingid, hazrepid, isassurancecheck, checklistquestionid, checklistid);
    }
    return true;
}

function swapHomePageImages() {
    var j$active = j$('.PRISMHomePageImage .activeImage');
    var j$next = (j$('.PRISMHomePageImage .activeImage').next().length > 0) ? j$('.PRISMHomePageImage .activeImage').next() : j$('.PRISMHomePageImage div:first');
    j$active.fadeOut(800, function() { j$active.removeClass('activeImage'); j$next.fadeIn(800).addClass('activeImage'); });
}

j$(document).ready(function () {
    j$("#btnExtCustomerSetup").click(function () {
        var bValid = true;
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        var errormsg = "";
        j$("#errorMsg").html("");

        if (j$("#txtCompanyName").val() == "") {
            errormsg += "<li>Please input your company's name</li>";
            bValid = false;
            j$("#txtCompanyName").addClass("errorStyle");
        }
        else {
            j$("#txtCompanyName").removeClass("errorStyle");
        }

        if (j$("#txtEmail").val() == "") {
            errormsg += "<li>Please input your e-mail address</li>";
            bValid = false;
            j$("#txtEmail").addClass("errorStyle");
        }
        else if (!pattern.test(j$("#txtEmail").val())) {
            errormsg += "<li>E-mail address has an invalid format</li>";
            bValid = false;
            j$("#txtEmail").addClass("errorStyle");
        }
        else {
            j$("#txtEmail").removeClass("errorStyle");
        }

        if (!bValid) {
            j$("#errorMsg").html("<ul>" + errormsg + "</ul>");
        }
        else {
            j$("#frmExternalSetup").submit();
            j$("#errorMsg").html("");
        }
    });

    j$("a#toggleFRATFilter").click(function () {
        if (j$("#toggleImg").attr("src").indexOf("right") > -1) {
            j$("#FRATFilterArea").slideDown('slow', function () {
                //show the text area for the full details
                j$("#toggleImg").attr("src", "/images/iep/circle_down.png");
                j$("#FRATFilterArea").removeClass("hidden");
            });
        }
        else if (j$("#toggleImg").attr("src").indexOf("down") > -1) {
            j$("#FRATFilterArea").slideUp('slow', function () {
                j$("#toggleImg").attr("src", "/images/iep/circle_right.png");
                j$("#FRATFilterArea").addClass("hidden");
            });
        }
        return false;
    });

    j$("a#filtertoggle").click(function () {
        if (j$("#imgtoggle").attr("src").indexOf("right") > -1) {
            j$("#filterArea").slideDown('slow', function () {
                //show the text area for the full details
                j$("#imgtoggle").attr("src", "/images/iep/circle_down_gray.png");
                j$("#filterArea").removeClass("hidden");
            });
        }
        else if (j$("#imgtoggle").attr("src").indexOf("down") > -1) {
            j$("#filterArea").slideUp('slow', function () {
                j$("#imgtoggle").attr("src", "/images/iep/circle_right_gray.png");
                j$("#filterArea").addClass("hidden");
            });
        }
        return false;
    });

    j$("#AddLeg").click(function () {
        j$("#action").val("add_leg");
        if (j$('select[id$=pic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedPICName") != null) {
            j$("#selectedPICName").val((j$('select[id$=pic] :selected').text()));
        }
        else if (j$("input[id=pic]") != null && j$("#selectedPICName") != null) {
            j$("#selectedPICName").val(j$("input[id=pic]").val());
        }
        if (j$('select[id$=sic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedSICName") != null) {
            j$("#selectedSICName").val((j$('select[id$=sic] :selected').text()));
        }
        else if (j$("input[id=sic]") != null && j$("#selectedSICName") != null) {
            j$("#selectedSICName").val(j$("input[id=sic]").val());
        }
        j$("#print").val("");
        j$("#frmEditReport").removeAttr("target");
        j$("#frmEditReport").submit();
        return false;
    });

    j$("#ShowLeg").click(function () {
        j$("#action").val("show_leg");
        if (j$('select[id$=pic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedPICName") != null) {
            j$("#selectedPICName").val((j$('select[id$=pic] :selected').text()));
        }
        else if (j$("input[id=pic]") != null && j$("#selectedPICName") != null) {
            j$("#selectedPICName").val(j$("input[id=pic]").val());
        }
        if (j$('select[id$=sic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedSICName") != null) {
            j$("#selectedSICName").val((j$('select[id$=sic] :selected').text()));
        }
        else if (j$("input[id=sic]") != null && j$("#selectedSICName") != null) {
            j$("#selectedSICName").val(j$("input[id=sic]").val());
        }
        j$("#print").val("");
        j$("#frmEditReport").removeAttr("target");
        j$("#frmEditReport").submit();
        return false;
    });

    j$('#cbShowOriginComments').click(function () {
        if (j$(this).is(':checked')) {
            var frrid = j$("#frrid").val();
            if (j$('select[id$=pic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedPICName") != null) {
                j$("#selectedPICName").val((j$('select[id$=pic] :selected').text()));
            }
            else if (j$("input[id=pic]") != null && j$("#selectedPICName") != null) {
                j$("#selectedPICName").val(j$("input[id=pic]").val());
            }
            if (j$('select[id$=sic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedSICName") != null) {
                j$("#selectedSICName").val((j$('select[id$=sic] :selected').text()));
            }
            else if (j$("input[id=sic]") != null && j$("#selectedSICName") != null) {
                j$("#selectedSICName").val(j$("input[id=sic]").val());
            }

            j$("#ap").val("o");
            j$("#action").val("view_comments");
            j$("#print").val("");
            j$("#frmEditReport").removeAttr("target");
            j$("#frmEditReport").submit();
        }
    });

    j$('#cbShowDestinationComments').click(function () {
        if (j$(this).is(':checked')) {
            var frrid = j$("#frrid").val();
            if (j$('select[id$=pic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedPICName") != null) {
                j$("#selectedPICName").val((j$('select[id$=pic] :selected').text()));
            }
            else if (j$("input[id=pic]") != null && j$("#selectedPICName") != null) {
                j$("#selectedPICName").val(j$("input[id=pic]").val());
            }
            if (j$('select[id$=sic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedSICName") != null) {
                j$("#selectedSICName").val((j$('select[id$=sic] :selected').text()));
            }
            else if (j$("input[id=sic]") != null && j$("#selectedSICName") != null) {
                j$("#selectedSICName").val(j$("input[id=sic]").val());
            }
            j$("#ap").val("d");
            j$("#action").val("view_comments");
            j$("#print").val("");
            j$("#frmEditReport").removeAttr("target");
            j$("#frmEditReport").submit();
        }
    });

    j$('#cbShowMissionAreaComments').click(function () {
        if (j$(this).is(':checked')) {
            var frrid = j$("#frrid").val();
            if (j$('select[id$=pic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedPICName") != null) {
                j$("#selectedPICName").val((j$('select[id$=pic] :selected').text()));
            }
            else if (j$("input[id=pic]") != null && j$("#selectedPICName") != null) {
                j$("#selectedPICName").val(j$("input[id=pic]").val());
            }
            if (j$('select[id$=sic]') != null && j$("select[id$=pic]").length > 0 && j$("#selectedSICName") != null) {
                j$("#selectedSICName").val((j$('select[id$=sic] :selected').text()));
            }
            else if (j$("input[id=sic]") != null && j$("#selectedSICName") != null) {
                j$("#selectedSICName").val(j$("input[id=sic]").val());
            }
            j$("#ap").val("m");
            j$("#action").val("view_comments");
            j$("#print").val("");
            j$("#frmEditReport").removeAttr("target");
            j$("#frmEditReport").submit();
        }
    });

    j$("input[id*=SaveChanges]").click(function () {
        j$("#action").val("save_report_changes");
        j$("#print").val("");
        j$("#frmEditReport").removeAttr("target");
        if (j$('select[id$=pic]') != null && j$("select[id$=pic]").length > 0) {
            j$("#selectedPICName").val((j$('select[id$=pic] :selected').text()));
        }
        else if (j$("input[id=pic]") != null)
            j$("#selectedPICName").val(j$("input[id=pic]").val());

        if (j$('select[id$=sic]') != null && j$("select[id$=pic]").length > 0) {
            j$("#selectedSICName").val((j$('select[id$=sic] :selected').text()));
        }
        else if (j$("input[id=sic]") != null)
            j$("#selectedSICName").val(j$("input[id=sic]").val());
    });

    j$("input[id*=close_report]").click(function () {
        j$("#action").val("save_report_changes");
        j$("#print").val("");
        j$("#frmEditReport").removeAttr("target");
        if (j$('select[id$=pic]') != null && j$("select[id$=pic]").length > 0) {
            j$("#selectedPICName").val((j$('select[id$=pic] :selected').text()));
        }
        else if (j$("input[id=pic]") != null)
            j$("#selectedPICName").val(j$("input[id=pic]").val());

        if (j$('select[id$=sic]') != null && j$("select[id$=pic]").length > 0) {
            j$("#selectedSICName").val((j$('select[id$=sic] :selected').text()));
        }
        else if (j$("input[id=sic]") != null)
            j$("#selectedSICName").val(j$("input[id=sic]").val());

        var answer1 = confirm("Are you sure you want to close this report?  Once you have closed it, you cannot make any changes to your flight information or scores.");
        if (answer1) {
            if (j$('#sl_Legs option').length > 1) {
                var answer2 = confirm("This trip has multiple legs.  Close all legs associated with this trip?");
                if (answer2)
                    j$("#close_all_legs").val("1");
                else
                    j$("#close_all_legs").val("0");
            }
            return true;
        }
        return false;
    });

    j$("#lnkTemplateCategorySave").live("click", function () {
        j$("#fr_edit_template").submit();
    });

    j$("#lnkAddCategory").live("click", function () {
        j$("#mode").val("addcat");
        j$("#fr_edit_template").submit();
    });

    j$("#lnkAddQuestion").live("click", function () {
        j$("#mode").val("question");
        j$("#fr_edit_template").submit();
    });

    j$("#lnkUpdateTemplateName").live("click", function () {
        j$("#mode").val("name");
        j$("#fr_edit_template").submit();
    });

    j$("#lnkUpdateScoringThresholds").live("click", function () {
        j$("#mode").val("scores");
        j$("#fr_edit_template").submit();
    });

    j$("#lnkUpdateFormat").live("click", function () {
        j$("#mode").val("format");
        j$("#fr_edit_template").submit();
        return false;
    });

    j$("a[id*=deleteFTQLink_]").live("click", function () {
        var questionId = j$(this).attr("id").split("_");
        if (questionId != null && questionId.length == 2) {
            j$("#row_" + questionId[1]).addClass("selectedRow");
            var msg = "Are you sure you want to delete this question?";
            if (parseInt(j$("#CatQCount_" + questionId[1]).val()) < 2)
                msg = msg + "\r\nThis category will be removed from the template.";
            var answer = confirm(msg);
            if (answer) {
                j$("#question_id").val(questionId[1]);
                j$("#mode").val("delete");
                j$("#fr_edit_template").submit();
            }
            else
                j$("#row_" + questionId[1]).removeClass("selectedRow");
        }
    });

    j$("a[id*=editFTQLink_]").live("click", function () {
        var questionId = j$(this).attr("id").split("_");
        j$("#qId_" + questionId[1]).addClass("hidden");
        j$("#qTextId_" + questionId[1]).addClass("hidden");
        j$("#qEditId_" + questionId[1]).removeClass("hidden");
        j$("#qEditTextId_" + questionId[1]).removeClass("hidden");
        j$("#question_id").val(questionId[1]);
        j$("#score" + questionId[1]).focus();
        return false;
    });

    j$("a[id*=btnQSave_]").live("click", function () {
        var questionId = j$(this).attr("id").split("_");
        j$("#mode").val("update");
        var qText = j$("#qEditTextId_" + questionId[1]).find("#editQuestionText");
        var qScore = j$("#qEditId_" + questionId[1]).find("#editScore");
        j$("#current_question_text").val(qText.val());
        j$("#current_question_score").val(qScore.val());
        j$("#fr_edit_template").submit();
    });

    j$("a[id*=btnQCancel_]").live("click", function () {
        var questionId = j$(this).attr("id").split("_");
        j$("#qId_" + questionId[1]).removeClass("hidden");
        j$("#qTextId_" + questionId[1]).removeClass("hidden");
        j$("#qEditId_" + questionId[1]).addClass("hidden");
        j$("#qEditTextId_" + questionId[1]).addClass("hidden");
        j$("#question_id").val(0);
        j$("#current_question_text").val("");
        j$("#current_question_score").val(0);
        return false;
    });

    j$("a[id*=EditCatLink_]").live("click", function () {
        var catId = j$(this).attr("id").split("_");
        j$("#tCat_" + catId[1]).addClass("hidden");
        j$("#tCatEdit_" + catId[1]).removeClass("hidden");
        j$("#current_cat").val(catId[1]);
        j$("#tCatName_" + catId[1]).focus();
        j$(this).addClass("hidden");

        if (j$("a#DeleteCatLink_" + catId[1]))
            j$("a#DeleteCatLink_" + catId[1]).addClass("hidden");

        if (j$("a#DeleteCatLinkAdmin_" + catId[1]))
            j$("a#DeleteCatLinkAdmin_" + catId[1]).addClass("hidden");
        return false;
    });

    j$("a[id*=btnSaveCat_]").live("click", function () {
        var catId = j$(this).attr("id").split("_");
        j$("#mode").val("upcat");
        var catName = j$("#tCatEdit_" + catId[1]).find("#tCatName_" + catId[1]);
        var catSeq = j$("#tCatEdit_" + catId[1]).find("#tCatSeq_" + catId[1]);
        var catTW = j$("#tCatEdit_" + catId[1]).find("#tCatTW_" + catId[1]);
        var catTWMsg = j$("#tCatEdit_" + catId[1]).find("#tCatTWMsg_" + catId[1]);
        var catTC = j$("#tCatEdit_" + catId[1]).find("#tCatTC_" + catId[1]);
        var catTCMsg = j$("#tCatEdit_" + catId[1]).find("#tCatTCMsg_" + catId[1]);
        var catUseTH = j$("#tUseCatTH_" + catId[1]).is(':checked');
        j$("#current_cat").val(catId[1]);
        j$("#current_cat_name").val(catName.val());
        j$("#current_cat_seq").val(catSeq.val());
        j$("#current_cat_tw").val(catTW.val());
        j$("#current_cat_tw_msg").val(catTWMsg.val());
        j$("#current_cat_tc").val(catTC.val());
        j$("#current_cat_tc_msg").val(catTCMsg.val());
        j$("#current_cat_use_th").val(catUseTH);
        j$("a#EditCatLink_" + catId[1]).removeClass("hidden");
        j$("a#DeleteCatLink_" + catId[1]).removeClass("hidden");
        j$("#fr_edit_template").submit();
    });

    j$("a[id*=btnCancelCat_]").live("click", function () {
        var catId = j$(this).attr("id").split("_");
        j$("#tCat_" + catId[1]).removeClass("hidden");
        j$("#tCatEdit_" + catId[1]).addClass("hidden");
        j$("#current_cat").val("0");
        j$("#current_cat_name").val("");
        j$("#current_cat_seq").val("");
        j$("#current_cat_tw").val("");
        j$("#current_cat_tw_msg").val("");
        j$("#current_cat_tc").val("");
        j$("#current_cat_tc_msg").val("");
        j$("#current_cat_use_th").val("0");
        j$("a#EditCatLink_" + catId[1]).removeClass("hidden");
        if (j$("a#DeleteCatLink_" + catId[1])) {
            j$("a#DeleteCatLink_" + catId[1]).removeClass("hidden");
        }

        if (j$("a#DeleteCatLinkAdmin_" + catId[1]))
            j$("a#DeleteCatLinkAdmin_" + catId[1]).removeClass("hidden");
        return false;
    });

    j$("a[id*=DeleteCatLink_]").live("click", function () {
        if (confirm("Warning! Deleting this category from the template will also delete all questions associated with this category.  Continue?")) {
            var catId = j$(this).attr("id").split("_");
            var id = j$("#frtId").val();
            window.location.href = "index.aspx?module=flightrisk&action=edit_template&mode=delcat&id=" + id + "&catid=" + catId[1];
        }
        return false;
    });

    j$("a[id*=DeleteCatLinkAdmin_]").live("click", function () {
        if (confirm("Warning! Deleting this category from the template will also delete all questions associated with this category.  Continue?")) {
            var catId = j$(this).attr("id").split("_");
            //            var id = j$("#frtId").val();
            j$("#mode").val("delcat");
            j$("#current_cat").val(catId[1]);
            j$("#fr_edit_template").submit()
        }
        return false;
    });

    j$("img[id*=_drop]").bind("click", function () {
        var id = j$(this).attr("id").split("_");
        var filtername = "";
        if (id.length > 2) {
            for (k = 0; k < id.length - 1; k++) {
                if (filtername.length > 0)
                    filtername = filtername + "_";
                filtername = filtername + id[k];
            }
        }
        else {
            filtername = id[0];
        }
        if (j$("div#" + filtername + "_Filter").hasClass("hidden"))
            j$("div#" + filtername + "_Filter").removeClass("hidden");
        else
            j$("div#" + filtername + "_Filter").addClass("hidden");
    });

    j$("input[id*=cb_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        var selection = j$('input[name=' + j$(this).attr("id") + ']:checked');
        var selectionlist = "";
        var selectionnamelist = "";
        var selectNameAndId = "";
        for (i = 0; i < selection.length; i++) {
            if (selectionlist.length > 0)
                selectionlist = selectionlist + ',';

            //create array of id + names for template formats
            if (id[1].indexOf("templateformat") > -1) {
                if (selectNameAndId.length > 0)
                    selectNameAndId = selectNameAndId + ',';

                selectNameAndId = selectNameAndId + selection[i].value + "|" + selection[i].title;
            }

            //used to capture template names since we need to display them in the dropdown text box, but pass
            //the template ids to the search function
            if (selectionnamelist.length > 0)
                selectionnamelist = selectionnamelist + ',';

            selectionlist = selectionlist + selection[i].value;

            if (id[1].indexOf("Template") > -1) {
                selectionnamelist = selectionnamelist + selection[i].title;
            }
        }

        if (id[1].indexOf("addtemplateformat") > -1) {
            j$("#Selected_addtemplateformat_ids").val(selectNameAndId);
        }
        else if (id[1].indexOf("templateformat") > -1) {
            j$("#Selected_templateformat_ids_" + id[2]).val(selectNameAndId);
        }
        else if (id[1].indexOf("Template") > -1) {
            j$("#SelectedTemplateIds").val(selectionlist);
            j$("#Selected_" + id[1]).val(selectionnamelist);
        }
        else {
            j$("#Selected_" + id[1]).val(selectionlist);
        }
    });

    j$("a[id*=PerformRA_]").live("click", function () {
        var qId = j$(this).attr("id").split("_");
        j$("#frmPerformRA_" + qId[1]).submit();
        return false;
    });

    j$("label[id*=labelQT_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        var cb = j$("#score_check_" + id[id.length - 2] + '_' + id[id.length - 1]);
        if (cb.attr("checked"))
            cb.attr("checked", false);
        else
            cb.attr("checked", true);

        var hdn = j$("#hdn_" + id[id.length - 2] + '_' + id[id.length - 1]);
        if (hdn.val() != null && hdn.val().length > 0)
            updateScores(hdn.val());
        else
            updateScores(0);
    });

    j$("input[id*=score_check_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        var hdn = j$("#hdn_" + id[id.length - 2] + '_' + id[id.length - 1]);
        if (hdn.val() != null && hdn.val().length > 0)
            updateScores(hdn.val());
        else
            updateScores(0);
    });

    j$('tr.selectedHazrepByCat').live("click", function () {
        var catId = j$(this).attr("id").split("_");
        window.location.href = 'index.aspx?module=hazrep&action=results&mode=category&catId=' + catId[1];
    });

    j$('tr.selectedHazrepByCat').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
    });

    j$('tr.selectedHazrepByCat').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
    });

    j$('tr.selectedHazrep').live("click", function () {
        window.location.href = j$(this).find("a.lnkHazrep").attr("href");
    });

    j$('tr.selectedHazrep').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
    });

    j$('tr.selectedHazrep').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
    });

    j$('tr.dashboardHAC').live("click", function () {
        window.location.href = j$(this).find("a.lnkHAC").attr("href");
    });

    j$('tr.dashboardHAC').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
        j$(this).find("a.lnkHAC").css("color", "white");
        j$(this).find("a.lnkHAC").css("text-decoration", "none");
    });

    j$('tr.dashboardHAC').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
        j$(this).find("a.lnkHAC").css("color", "#6c6d6e");
        j$(this).find("a.lnkHAC").css("text-decoration", "none");
    });

    j$('tr.selected_ro_Hazrep').live("click", function () {
        var hazrepId = j$(this).attr("id").split("_");
        window.location.href = "/Hazrep/ViewReport?hazrep_id=" + hazrepId[1];
    });

    j$('tr.selected_ro_Hazrep').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
    });

    j$('tr.selected_ro_Hazrep').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
    });

    j$("#btnKeywordSearch").live("click", function () {
        j$("#currentmode").val("keyword");
        j$("#frmHazreps").submit();
    });

    j$("#btnDateRangeSearch").live("click", function () {
        j$("#currentmode").val("date");
        j$("#frmHazreps").submit();
    });

    j$("#btnCategorySearch").live("click", function () {
        j$("#currentmode").val("category");
        j$("#frmHazreps").submit();
    });

    j$("#btnStatusSearch").live("click", function () {
        j$("#currentmode").val("status");
        j$("#frmHazreps").submit();
    });

    j$("#btnSeveritySearch").live("click", function () {
        j$("#currentmode").val("severity");
        j$("#frmHazreps").submit();
    });

    j$("a[id*=deleteLink_]").live("click", function () {
        var answer = confirm("Are you sure you want to delete this report?");
        if (answer) {
            var fRiskId = j$(this).attr("id").split("_");
            window.location.href = "index.aspx?module=flightrisk&action=delete_report&id=" + fRiskId[1];
        }
        return false;
    });

    j$("a[id*=editLink_]").live("click", function () {
        var fRiskId = j$(this).attr("id").split("_");
        window.location.href = "index.aspx?module=flightrisk&action=edit_report&id=" + fRiskId[1];
        return false;
    });

    j$("a[id*=deleteHazrepLink_]").live("click", function () {
        var answer = confirm("Are you sure you want to delete this report?");
        if (answer) {
            var hazrepId = j$(this).attr("id").split("_");
            window.location.href = "index.aspx?module=hazrep&action=delete&id=" + hazrepId[1];
        }
        return false;
    });

    j$("a#GraphViewLink").click(function () {
        j$("#divGraph").removeClass("hidden");
        j$("#divReport").addClass("hidden");
        j$("input#printmode").val("graph");
    });

    j$("a#ReportViewLink").click(function () {
        j$("#divGraph").addClass("hidden");
        j$("#divReport").removeClass("hidden");
        j$("input#printmode").val("report");
    });

    j$("#comments").bind("notext", function () {
        j$("input#submitbtn").attr("disabled", "disabled");
    });

    j$("#comments").bind("hastext", function () {
        j$("input#submitbtn").removeAttr("disabled");
    });

    j$("input#missionarea").bind("notext", function () {
        j$("input#SubmitMissionAreaComments").attr("disabled", "disabled");
        j$("input#cbShowMissionAreaComments").attr("disabled", "disabled");
    });

    j$("input#missionarea").bind("hastext", function () {
        j$("input#SubmitMissionAreaComments").removeAttr("disabled");
        j$("input#cbShowMissionAreaComments").removeAttr("disabled");
    });

    j$("input#origin").bind("notext", function () {
        j$("input#cbShowOriginComments").attr("disabled", "disabled");
        if (j$("input#destination").val() == null || j$("input#destination").val() == "") {
            j$("input#SubmitAirportComments").attr("disabled", "disabled");
        }
    });

    j$("input#origin").bind("hastext", function () {
        j$("input#SubmitAirportComments").removeAttr("disabled");
        j$("input#cbShowOriginComments").removeAttr("disabled");
    });

    j$("input#destination").bind("notext", function () {
        j$("input#cbShowDestinationComments").attr("disabled", "disabled");
        if (j$("input#origin").val() == null || j$("input#origin").val() == "") {
            j$("input#SubmitAirportComments").attr("disabled", "disabled");
        }
    });

    j$("input#destination").bind("hastext", function () {
        j$("input#SubmitAirportComments").removeAttr("disabled");
        j$("input#cbShowDestinationComments").removeAttr("disabled");
    });

    j$("input#SubmitAirportComments").live("click", function () {
        j$("#action").val("submit_comments");
        j$("#comment_type").val("ap");
        j$("#frmEditReport").submit();
    });

    j$("input#SubmitMissionAreaComments").live("click", function () {
        j$("#action").val("submit_comments");
        j$("#comment_type").val("ma");
        j$("#frmEditReport").submit();
    });

    j$("#filterBtn").live("click", function () {
        //clear any saved filter values as user is selecting new ones
        j$("#SelectedFilterValues").val("");
        j$("input#print").val("0");
        j$("#frmFilter").removeAttr("target");
    });

    j$("#RFS_PrintViewLink").click(function () {
        j$("input#print").val("1");
        j$("input#big_graph").val("0");
        j$("#frmFilter").attr("target", "_blank");
        j$("#frmFilter").submit();
    });

    j$("#lnkShowBigGraph").live("click", function () {
        j$("input#big_graph").val("1");
        j$("input#print").val("1");
        j$("#frmFilter").attr("target", "_blank");
        j$("#frmFilter").submit();
    });

    j$("#btnPrintFRAT").live("click", function (e) {
        e.preventDefault();
        j$("input#print").val("1");
        j$("#action").val("print_report");
        if (j$('select[id$=pic]') != null && j$("select[id$=pic]").length > 0) {
            j$("#selectedPICName").val((j$('select[id$=pic] :selected').text()));
        }
        else if (j$("input[id=pic]") != null)
            j$("#selectedPICName").val(j$("input[id=pic]").val());

        if (j$('select[id$=sic]') != null && j$("select[id$=pic]").length > 0) {
            j$("#selectedSICName").val((j$('select[id$=sic] :selected').text()));
        }
        else if (j$("input[id=sic]") != null)
            j$("#selectedSICName").val(j$("input[id=sic]").val());
        j$("#frmEditReport").attr("target", "_blank");
        j$("#frmEditReport").submit();
        return false;
    });

    j$("#CancelUnsavedChanges").live("click", function () {
        var answer = confirm('You have unsaved changes that will be discarded. Do you want to continue?');
        if (answer) {
            j$("input#print").val("0");
            j$("#action").val("cancel_report_changes");
            j$("#frmEditReport").removeAttr("target");
        }
    });

    j$("#fratbacklink_UC").live("click", function () {
        var answer = confirm('You have unsaved changes that will be discarded. Do you want to continue?');
        if (answer) {
            j$("input#print").val("0");
            j$("#action").val("cancel_report_changes");
            j$("#frmEditReport").removeAttr("target");
            j$("#frmEditReport").submit();
            return false;
        }
    });

    j$("#filterCommentsBtn").live("click", function () {
        j$("#frmAdminViewComments").submit();
    });

    j$("img[id*=btnOrderUp_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        j$("#question_id").val(id[1]);
        j$("#question_sequence").val(-1);
        j$("#mode").val("sequence");
        j$("#fr_edit_template").submit();
    });

    j$("img[id*=btnOrderDown_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        j$("#question_id").val(id[1]);
        j$("#question_sequence").val(1);
        j$("#mode").val("sequence");
        j$("#fr_edit_template").submit();
    });


    j$("img[id*=deleteQuestion_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        var answer = confirm("Are you sure you want to delete this question?");
        if (answer) {
            j$("#question_id").val(id[1]);
            j$("#mode").val("delete");
            j$("#fr_edit_template").submit();
        }
    });

    j$("a#btnCancelNewCatAdmin").click(function () {
        j$("#divAddCatAdmin").addClass("hidden");
        return false;
    });

    j$("a#btnSaveNewCatAdmin").click(function () {
        j$("#frmAddCat").submit();
    });

    j$("a[id*=lnkClearAlert_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        var answer = confirm("Are you sure you want to clear this alert?");
        if (answer)
            window.location.href = "index.aspx?module=smshome&action=clear_alert&id=" + id[1];
    });

    j$('tr.hazrepdetail').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
    });

    j$('tr.hazrepdetail').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
    });

    j$("tr.hazrepdetail").live("click", function () {
        var id = j$(this).attr("id").split("_");
        window.location.href = "/Hazrep/EditReport?hazrep_id=" + id[1];
    });

    j$('tr.hazrep_ro_detail').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
    });

    j$('tr.hazrep_ro_detail').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
    });

    j$("tr.hazrep_ro_detail").live("click", function () {
        var id = j$(this).attr("id").split("_");
        window.location.href = "/Hazrep/ViewReport?hazrep_id=" + id[1];
    });

    //    j$("#btnSearchHazreps").live("click", function () {
    //        j$("#frmSearchHazreps").submit();
    //    });

    j$("#btnCreateBuiltInHazrep").click(function () {
        var id = j$("#builtin_template_id").val();
        window.location.href = '/Hazrep/CreateNewHazrep?templateid=' + id;
    });

    j$("#btnCreateCustomHazrep").click(function () {
        var id = j$("#custom_template_id").val();
        window.location.href = '/Hazrep/CreateNewHazrep?templateid=' + id;
    });

    j$("img.datepicker").live("mouseover", function () {
        j$(this).addClass("redbackground");
    });

    j$("img.datepicker").live("mouseout", function () {
        j$(this).removeClass("redbackground");
    });

    j$("a[id*=lnkFileRefresh_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        if (id[1] > 0) {
            var data = "{'HazrepID':'" + id[1] + "'}";
            j$.ajax({
                async: false,
                type: "POST",
                timeout: 10000,
                mode: "queue",
                url: "/Hazrep/RefreshUploadedFiles",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) { },
                failure: function (msg) { }
            });
        }
    });

    j$("a[id*=nkDeleteUploadedFile_]").live("click", function () {
        if (confirm("Are you sure you want to delete this file?")) {
            var id = j$(this).attr("id").split("_");
            var data = "{'hazrep_id':'" + id[1] + "','fileupload_id':'" + id[2] + "'}";
            j$.ajax({
                async: false,
                type: "POST",
                timeout: 10000,
                mode: "queue",
                url: "/Hazrep/DeleteUploadedFile",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) { },
                failure: function (msg) { }
            });
        }
    });
    j$("#btnSaveTemplate").click(function () {
        j$("#frmEditHazrepTemplate").submit();
    });

    //    j$("#btnBackToList").click(function () {
    //        window.location.href = '/Hazrep/TemplateIndex/';
    //    });

    j$('tr[id*=lnkSearchHazrepsByTemplate_]').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
    });

    j$('tr[id*=lnkSearchHazrepsByTemplate_]').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
    });

    j$("tr[id*=lnkSearchHazrepsByTemplate_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        window.location.href = '/Hazrep/SearchReportsByTemplateID?templateID=' + id[1];
    });

    j$("#btnGetOpenHazreps").live("click", function () {
        window.location.href = '/Hazrep/SearchReportsByStatus?status=Open';
    });

    j$("#btnGetClosedHazreps").live("click", function () {
        window.location.href = '/Hazrep/SearchReportsByStatus?status=Closed';
    });

    j$("#btnSubmitHazrep").live("click", function () {
        j$("#submit_hazrep").val("true");
        j$("#frmEditHazrep").submit();
    });

    j$("#notifyLink").live("click", function () {
        j$(this).target = "_blank";
        var recipient = j$("[id*=selectUser_]").val();
        var id = j$("[id*=selectUser_]").attr("id").split("_");
        j$(this).attr("href", "/CorrectiveActionNotification/GenerateHazrepNotification?hazrep_id=" + id[1] + "&is_ac=false&recipient_id=" + recipient + "&newNotification=true");
    });

    //    j$("#iep_ac_send_btn").live("click", function (e) {
    //        e.preventDefault()

    //        j$("#submit_value").val("Send Notification");
    //        j$("#frmIEPAssuranceCheck").attr("target", "_blank");
    //        j$("#frmIEPAssuranceCheck").submit(); 
    //    });

    //    j$("#iep_ac_save_btn").live("click", function (e) {
    //        e.preventDefault()

    //        j$("#submit_value").val("Save Changes");
    //        j$("#frmIEPAssuranceCheck").removeAttr("target");
    //        j$("#frmIEPAssuranceCheck").submit();
    //    });

    //    j$("#iep_ac_cancel_btn").live("click", function (e) {
    //        e.preventDefault()

    //        j$("#submit_value").val("Cancel");
    //        j$("#frmIEPAssuranceCheck").removeAttr("target");
    //        j$("#frmIEPAssuranceCheck").submit();
    //    });

    j$("a[id*=lnkDeleteUploadedFile_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        var answer = confirm("Are you sure you want to delete this file?");
        if (answer) {
            window.location.href = '/Hazrep/DeleteUploadedFile?hazrep_id=' + id[1] + '&fileupload_id=' + id[2];
        }
    });
    j$("a.lnkDeleteUploadedFile").live("click", function () {
        if (confirm("Are you sure you want to delete this item?")) {
            var url = j$(this).attr("href");
            j$.ajax({
                async: true,
                type: "POST",
                url: url,
                data: "{}",
                contentType: "text/html; charset=utf-8",
                dataType: "html",
                success: function (response) {
                    j$("#divUploadedFiles").html(response);
                },
                failure: function (msg) {
                    j$("#divUploadedFiles").html(msg);
                }
            });
        }
        return false;
    });

    j$("a#lnkRefreshUploadedFiles").live("click", function () {
        var url = j$(this).attr("href");
        j$.ajax({
            async: true,
            type: "POST",
            url: url,
            data: "{}",
            contentType: "text/html; charset=utf-8",
            dataType: "html",
            success: function (response) {
                j$("#divUploadedFiles").html(response);
            },
            failure: function (msg) {
                j$("#divUploadedFiles").html(msg);
            }
        });
        return false;
    });

    //    j$("#btnSearchOptIn").click(function () {
    //        var customer_id = 0;
    //        var customer_name = '';
    //        if (j$("#customer_id").val() != null && j$("#customer_id").val() != '') {
    //            customer_id = j$("#customer_id").val();
    //        }
    //        if (j$("#customer_name").val() != null && j$("#customer_name").val() != '') {
    //            customer_name = j$("#customer_name").val();
    //        }
    //        j$.ajax({
    //            async: true,
    //            type: "POST",
    //            url: '/HazrepAdmin/SearchAllOptIn?id_input=' + customer_id + '&name_input=' + customer_name,
    //            data: {},
    //            contentType: "text/html; charset=utf-8",
    //            dataType: "html",
    //            success: function (response) {
    //                j$("#divCustomerOptIn").empty().append(response);
    //            },
    //            failure: function (msg) {
    //                j$("#divErrorMessage").empty().append(msg);
    //            }
    //        });
    //        return false;
    //    });

    //    j$("#frmOptIn").submit(function (e) {
    //        e.preventDefault();
    //        dataString = j$("#frmOptIn").serialize();
    //        j$.ajax({
    //            async: true,
    //            type: "POST",
    //            url: "/HazrepAdmin/SetCustomerOptIn/",
    //            data: dataString,
    //            dataType: "json",
    //            success: function (response) {
    //                j$("#divCustomerOptIn").empty().append(response);
    //            },
    //            failure: function (msg) {
    //                j$("#divErrorMessage").empty().append(msg);
    //            }
    //        });
    //    });

    j$("#notifyHACLink").live("click", function () {
        j$(this).target = "_blank";
        var recipient = j$("[id*=selectUser_]").val();
        var id = j$("[id*=selectUser_]").attr("id").split("_");
        j$(this).attr("href", "/CorrectiveActionNotification/GenerateHazrepNotification?hazrep_id=" + id[1] + "&is_ac=true&recipient_id=" + recipient + "&newNotification=true");
    });

    j$("#hac_send_notification_btn").live("click", function (e) {
        e.preventDefault()
        var recipient = j$("[id*=selectUser_]").val();
        if (recipient == null || recipient == '0') {
            j$("#divErrorMessage").empty().append("Please select a recipient for the corrective action notification.");
            return false;
        }
        j$("#request_type").val("Send Notification");
        //j$("#frmEditHazrepAssuranceCheck").attr("target", "_blank");
        j$("#frmEditHazrepAssuranceCheck").submit();
    });

    j$("#hac_save_changes_btn").live("click", function (e) {
        e.preventDefault()
        j$("#request_type").val("Save Changes");
        j$("#frmEditHazrepAssuranceCheck").removeAttr("target");
        j$("#frmEditHazrepAssuranceCheck").submit();
    });

    j$("#hac_cancel_changes_btn").live("click", function (e) {
        e.preventDefault()
        j$("#request_type").val("Cancel");
        j$("#frmEditHazrepAssuranceCheck").removeAttr("target");
        j$("#frmEditHazrepAssuranceCheck").submit();
    });

    j$("a.lnkAddTemplateField").colorbox({ href: "#divAddTemplateField", width: "700px", inline: true, height: "650px" })
    j$("a#lnkAddTemplateCategory").colorbox({ href: "#divTemplateCategory", width: "600px", inline: true, height: "400px" })
    j$("a.lnkEditTemplateCategory").colorbox({ href: "#divTemplateCategory", width: "600px", inline: true, height: "400px" })
    j$("a.lnkEditTemplateField").colorbox({ href: "#divEditTemplateField", width: "700px", inline: true, height: "650px" })
    j$("a.lnkEditCATemplateField").colorbox({ href: "#divEditTemplateCAField", width: "600px", inline: true, height: "400px" })
    j$("a.lnkEditTemplateDetailField").colorbox({ href: "#divEditTemplateDetailField", width: "600px", inline: true, height: "400px" })
    j$("a.lnkHazrep").addClass("hidden");
    j$("td.radio_only").addClass("hidden");
    j$("tr.dashboardHazrep td a").addClass("hazrep_dashboard_link");
    //    j$("a.search_template_link").live("click", function () {
    //    //disables link unless no javascript
    //        return false;
    //    });

    j$("#field_type").change(function () {
        if (j$(this).val() == '4')
            j$("td.radio_only").removeClass("hidden");
        else
            j$("td.radio_only").addClass("hidden");
    });

    j$("a.lnkAddTemplateField").live("click", function () {
        j$.ajax({
            async: true,
            type: "POST",
            url: j$(this).attr("href"),
            data: "{}",
            contentType: "text/html; charset=utf-8",
            dataType: "html",
            success: function (response) {
                j$("#divAddTemplateField").empty().append(response);
            },
            failure: function (msg) {
                j$("#divAddTemplateField").find("div.modalMsg").empty().append(msg);
            }
        });
        return false;
    });

    j$("a.lnkEditTemplateField").live("click", function () {
        j$.ajax({
            async: true,
            type: "POST",
            url: j$(this).attr("href"),
            data: "{}",
            contentType: "text/html; charset=utf-8",
            dataType: "html",
            success: function (response) {
                j$("#divEditTemplateField").empty().append(response);
            },
            failure: function (msg) {
                j$("#divEditTemplateField").find("div.modalMsg").empty().append(msg);
            }
        });
        return false;
    });

    j$("a.lnkEditTemplateDetailField").live("click", function () {
        j$.ajax({
            async: true,
            type: "POST",
            url: j$(this).attr("href"),
            data: "{}",
            contentType: "text/html; charset=utf-8",
            dataType: "html",
            success: function (response) {
                j$("#divEditTemplateDetailField").empty().append(response);
            },
            failure: function (msg) {
                j$("#divEditTemplateDetailField").find("div.modalMsg").empty().append(msg);
            }
        });
        return false;
    });

    j$("a.lnkEditCATemplateField").live("click", function () {
        j$.ajax({
            async: true,
            type: "POST",
            url: j$(this).attr("href"),
            data: "{}",
            contentType: "text/html; charset=utf-8",
            dataType: "html",
            success: function (response) {
                j$("#divEditTemplateCAField").empty().append(response);
            },
            failure: function (msg) {
                j$("#divEditTemplateCAField").find("div.modalMsg").empty().append(msg);
            }
        });
        return false;
    });

    j$("#btnAddTemplateField").live("click", function (e) {
        e.preventDefault();
        var msg = "";
        if (j$("#field_name").val() == null || j$("#field_name").val().length == 0) {
            msg = msg + "<li>Field name is required</li>";
        }
        if (j$("#FieldPositionSelect").val() == "0") {
            if (j$("#divpositions").val() == "Before" || j$("#divpositions").val() == "After") {
                msg = msg + "<li>Please specify the position of the new field</li>";
            }
        }
        if (j$("#field_type").val() == null || j$("#field_type").val() == '0|Select') {
            msg = msg + "<li>Field Type is required</li>";
        }
        else if (j$("#field_type").val() == "8|hyperlink" && (j$("#link_url").val() == null || j$("#link_url").val() == "")) {
            msg = msg + "<li>Web address is required for hyperlinks</li>";
        }
        if (msg == "")
            j$("#frmAddTemplateField").submit();
        else {
            msg = "<ul>" + msg + "</ul>";
            j$("#divAddTemplateField").find("div.modalMsg").empty().append(msg);
        }
    });

    j$("#btnEditTemplateFieldSubmit").live("click", function (e) {
        e.preventDefault();
        var msg = "";
        if (j$("#field_name").val() == null || j$("#field_name").val().length == 0) {
            msg = msg + "<li>Field name is required</li>";
        }
        if (j$("#FieldPositionSelect").val() == "0") {
            if (j$("#divpositions").val() == "Before" || j$("#divpositions").val() == "After") {
                msg = msg + "<li>Please specify the position of the new field</li>";
            }
        }
        if (j$("#field_type").val() == null || j$("#field_type").val() == '0') {
            msg = msg + "<li>Field Type is required</li>";
        }
        else if (j$("#field_type").val() == "8|hyperlink" && (j$("#link_url").val() == null || j$("#link_url").val() == "")) {
            msg = msg + "<li>Web address is required for hyperlinks</li>";
        }
        if (msg == "")
            j$("#frmEditTemplateField").submit();
        else {
            msg = "<ul>" + msg + "</ul>";
            j$("#divEditTemplateField").find("div.modalMsg").empty().append(msg);
        }
    });

    j$("a.lnkDeleteTemplateField").live("click", function () {
        var answer = confirm("Are you sure you want to delete this field from the template?");
        if (answer) {
            return true;
        }
        else {
            return false;
        }
    });

    j$("a.lnkDeleteTemplateDetailField").live("click", function () {
        var answer = confirm("Are you sure you want to delete this field from the template?");
        if (answer) {
            return true;
        }
        else {
            return false;
        }
    });

    j$("a.lnkDeleteCATemplateField").live("click", function () {
        var answer = confirm("Are you sure you want to delete this field from the template?");
        if (answer) {
            return true;
        }
        else {
            return false;
        }
    });

    j$("a[id*=lnkSaveTemplateName_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        if (j$("#Template_name_" + id[1]).val() == null && j$("#Template_name_" + id[1]).val() == "") {
            j$("#divmessage").empty().append("Template name is required");
        }
        else {
            j$("#frmEditHazrepTemplate").submit();
        }
        return false;

    });

    j$("a.lnkRemoveOptTemplateCat").live("click", function () {
        var answer = confirm("Are you sure you want to delete this category from the template?");
        if (answer) {
            return true;
        }
        else {
            return false;
        }
    });

    j$("a.lnkEditTemplateCategory").live("click", function () {
        j$.ajax({
            async: true,
            type: "POST",
            url: j$(this).attr("href"),
            data: "{}",
            contentType: "text/html; charset=utf-8",
            dataType: "html",
            success: function (response) {
                j$("#divTemplateCategory").empty().append(response);
            },
            failure: function (msg) {
                j$("#divmessage").empty().append(msg);
            }
        });
        return false;
    });

    j$("a#lnkAddTemplateCategory").live("click", function () {
        j$.ajax({
            async: true,
            type: "POST",
            url: j$(this).attr("href"),
            data: "{}",
            contentType: "text/html; charset=utf-8",
            dataType: "html",
            success: function (response) {
                j$("#divTemplateCategory").empty().append(response);
            },
            failure: function (msg) {
                j$("#divmessage").empty().append(msg);
            }
        });
        return false;
    });

    j$("tr[id*=SanitizeHazrep_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        window.location.href = "/HazrepAdmin/SanitizeHazrep?hazrep_id=" + id[1];
    });

    j$('tr[id*=SanitizeHazrep_]').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
    });

    j$('tr[id*=SanitizeHazrep_]').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
    });

    j$('tr[id*=SanitizedHazrep_]').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
    });

    j$('tr[id*=SanitizedHazrep_]').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
    });

    j$("input[name*=btnSubmit_]").live("click", function () {
        if (confirm("Delete this sanitized hazrep?"))
            return true;
        return false;
    });

    j$("a[id*=lnkOptIn_]").live("click", function () {
        var id = j$(this).attr("id").split("_");
        var url = j$(this).attr("href");
        if (j$("cbOptIn_" + id[1]).is(":checked")) {
            url = url + "&opt_in=true";
        }
        else {
            url = url + "&opt_in=false";
        }
        j$.ajax({
            async: true,
            type: "POST",
            url: url,
            data: "{}",
            contentType: "text/html; charset=utf-8",
            dataType: "html",
            success: function (response) {
                j$("#divCustomerOptIn").empty().append(response);
            },
            failure: function (msg) {
                j$("#divErrorMessage").empty().append(msg);
            }
        });
        return false;
    });

    j$("#btnReturnToUnsanitizedHazreps").click(function () {
        window.location.href = '/HazrepAdmin/GetUnsanitizedHazreps/';
    });

    j$("a.lnkDeleteHazrep").live("click", function () {
        var answer = confirm("Are you sure you want to delete this hazrep?");
        if (answer)
            return true;
        else
            return false;
    });

    j$(".lnkDeleteHazrepFromSearch").live("click", function () {
        if (confirm("Are you sure you want to delete this hazrep?")) {
            return true;
        }
        return false;
    });

    j$("a.lnkDeleteOpenHazrep").live("click", function () {
        if (confirm("Are you sure you want to delete this hazrep?")) {
            j$.ajax({
                async: true,
                type: "POST",
                url: j$(this).attr("href"),
                data: "{}",
                contentType: "text/html; charset=utf-8",
                dataType: "html",
                success: function (response) {
                    j$("#divOpenHazreps").empty().append(response);
                },
                failure: function (msg) {
                    j$("#divErrorMessage").empty().append(msg);
                }
            });
        }
        return false;
    });

    j$("a.lnkDeleteClosedHazrep").live("click", function () {
        if (confirm("Are you sure you want to delete this hazrep?")) {
            j$.ajax({
                async: true,
                type: "POST",
                url: j$(this).attr("href"),
                data: "{}",
                contentType: "text/html; charset=utf-8",
                dataType: "html",
                success: function (response) {
                    j$("#divClosedHazreps").empty().append(response);
                },
                failure: function (msg) {
                    j$("#divErrorMessage").empty().append(msg);
                }
            });
        }
        return false;
    });

    j$("#btnGetOpenMultiplePrintView").live("click", function (e) {
        e.preventDefault();
        j$("#frmGetOpenMultiplePrintView").attr("target", "_blank");
        j$("#frmGetOpenMultiplePrintView").submit();
    });

    j$("#btnGetClosedMultiplePrintView").live("click", function (e) {
        e.preventDefault()
        j$("#frmGetClosedMultiplePrintView").attr("target", "_blank");
        j$("#frmGetClosedMultiplePrintView").submit();
    });

    j$("#btnGetSearchMultiplePrintView").live("click", function (e) {
        e.preventDefault()
        j$("#frmGetSearchMultiplePrintView").attr("target", "_blank");
        j$("#frmGetSearchMultiplePrintView").submit();
    });

    j$("#select_radio_group").live("change", function () {
        if (j$(this).val() != 'Select')
            j$("#radio_group_name").val("");
    });

    j$("#radio_group_name").blur(function () {
        if (j(this).val() != "")
            j$("#select_radio_group").val("Select");
    });

    j$('tr.dashboardHazrep').live("mouseover", function () {
        j$(this).addClass("hazrepMouseOver");
    });

    j$('tr.dashboardHazrep').live("mouseout", function () {
        j$(this).removeClass("hazrepMouseOver");
    });

    //    j$("tr[id*=SanitizeHazrep_]").live("click", function () {
    //        var id = j$(this).attr("id").split("_");
    //        window.location.href = "/Hazrep/EditReport?hazrep_id=" + id[1];
    //    });

    j$("#btnHazrepCASubmit").live("click", function (e) {
        var action = j$(this).val();
        var msg = "";
        var recipientID = 0;
        if (action.indexOf("Approve") > -1 || action.indexOf("Close") > -1 || action.indexOf("Submit") > -1) {
            var val = j$('#proposedCorrectiveAction').val();
            if (val == null || val == '') {
                msg += '<li>Proposed corrective action cannot be blank.</li>';
            }
        }
        if (action.indexOf("Close") == -1 && action.indexOf("Submit") == -1 && j$("#selectAssignedTo") != null) {
            if (j$("#selectAssignedTo").val() == null || j$("#selectAssignedTo").val() == "") {
                msg += '<li>Please select a recipient</li>';
            }
            else {
                var recipient = j$("#selectAssignedTo").val().split('|');
                if (recipient.length > 2) {
                    recipientID = parseInt(recipient[1]);
                }
                if (recipientID <= 0) {
                    msg += '<li>Please select a recipient</li>';
                }
            }
        }

        if (msg.length > 0) {
            j$("div#divErrorMessage").empty().append('<ul>' + msg + '</ul>');
            return false;
        }
        return true;
    });

    j$("a.lnkRemoveUnsanitizedHazrep").live("click", function () {
        if (confirm("Remove this hazrep from the unsanitized list?"))
            return true;
        else
            return false;
    });

    j$("a.lnkDeleteFieldFromSanitizedHazrep").live("click", function () {
        if (confirm("Remove this field from the sanitized hazrep?"))
            return true;
        else
            return false;
    });

    j$("#btnGetFields").addClass("hidden");
    j$("select#template_list").live("click", function () {
        if (j$(this).val() != null && j$(this).val() != '0') {
            j$("#show_full_screen_view").val("0");
            j$("#create_graph").val("0");
            j$("#frmCreateGraph").removeAttr("target");
            j$("#frmCreateGraph").submit();
        }
    });

    j$('input[name=btnShowFullScreenView]').live("click", function (e) {
        e.preventDefault();
        j$("#show_full_screen_view").val("1");
        j$("#create_graph").val("1");
        j$("#frmCreateGraph").attr("target", "_blank");
        j$("#frmCreateGraph").submit();
    });

    j$('input[name=btnSubmitCreateGraph]').live("click", function (e) {
        e.preventDefault();
        j$("#create_graph").val("1");
        j$("#show_full_screen_view").val("0");
        j$("#frmCreateGraph").removeAttr("target");
        j$("#frmCreateGraph").submit();
    });

    j$("input:checkbox[id*=cb_Template_]").live("click", function () {
        if (j$(this).is(":checked")) {
            var id = j$(this).attr("id").split("_");
            j$.ajax({
                async: false,
                type: "POST",
                timeout: 10000,
                mode: "queue",
                url: "/Hazrep/FilterFieldsByTemplate?hazrep_template_id=" + id[2],
                data: {},
                contentType: "text/html; charset=utf-8",
                dataType: "html",
                success: function (response) {
                    j$("#Field_Filter").empty().append(response);
                },
                failure: function (msg) {
                    j$("#divErrorMessage").empty().append(msg);
                }
            });
        }
    });

    //hides the suspended customers when page is loaded
    j$("div#suspended_customers").addClass("hidden");

    j$("#toggle_current_customers").bind("click", function () {
        if (j$("#toggle_current_customers").attr("src").indexOf("right") > -1) {
            //show current customers
            j$("div#current_customers").slideDown('slow', function () {
                j$("#toggle_current_customers").attr("src", "/images/iep/circle_down.png");
                j$("#toggle_current_customers").attr("title", "Click to hide current customers");
                j$("div#current_customers").removeClass("hidden");
            });
        }
        else if (j$("#toggle_current_customers").attr("src").indexOf("down") > -1) {
            //hide current customers
            j$("div#current_customers").slideUp('slow', function () {
                j$("#toggle_current_customers").attr("src", "/images/iep/circle_right.png");
                j$("#toggle_current_customers").attr("title", "Click to show current customers");
                j$("div#current_customers").addClass("hidden");
            });
        }
    });

    j$("#toggle_suspended_customers").bind("click", function () {
        if (j$("#toggle_suspended_customers").attr("src").indexOf("right") > -1) {
            //show suspended customers
            j$("div#suspended_customers").slideDown('slow', function () {
                j$("#toggle_suspended_customers").attr("src", "/images/iep/circle_down.png");
                j$("#toggle_suspended_customers").attr("title", "Click to hide suspended customers");
                j$("div#suspended_customers").removeClass("hidden");
            });
        }
        else if (j$("#toggle_suspended_customers").attr("src").indexOf("down") > -1) {
            //hide suspended customers
            j$("div#suspended_customers").slideUp('slow', function () {
                j$("#toggle_suspended_customers").attr("src", "/images/iep/circle_right.png");
                j$("#toggle_suspended_customers").attr("title", "Click to show suspended customers");
                j$("div#suspended_customers").addClass("hidden");
            });
        }
    });
}); 
    
