/*Registering responders for prototype library
 If you are not using prototype library then
 there is no need of the next statement.*/


/*Registering responders for jQuery AJAX calls
 If you are not using jQuery’s AJAX methods(e.g. ajax, get, post) then
 there is no need of the next statement.*/

jQuery("#ajax_spinner").ajaxStart(function() {
    jQuery(this).show();
//    showWaitDialog();
});
jQuery("#ajax_spinner").ajaxComplete(function(event, xhr, options) {
    var data = httpData(xhr, options.dataType, options);
    var inputFieldIndex = -1;
    try {
        inputFieldIndex = data.indexOf("Session TimedOut url");
    } catch(err) {
    }
    if (inputFieldIndex > -1) {
        window.location.href = data.substring(data.indexOf("=") + 1, data.length);
    }
});

var httpData = $.httpData || function(xhr, type, s) { // lifted from jq1.4.4
    var ct = xhr.getResponseHeader("content-type") || "",
        xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
        data = xml ? xhr.responseXML : xhr.responseText;

    if (xml && data.documentElement.nodeName === "parsererror") {
        $.error("parsererror");
    }

    if (s && s.dataFilter) {
        data = s.dataFilter(data, type);
    }

    if (typeof data === "string") {
        if (type === "json" || !type && ct.indexOf("json") >= 0) {
            data = $.parseJSON(data);
        } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
            $.globalEval(data);
        }
    }
    return data;
};

jQuery("#ajax_spinner").ajaxStop(function() {
//    closeWaitDialog();
    jQuery(this).hide();
    var isPopUpExist = jQuery("#GB_window");
    if (isPopUpExist) {
        alignPopUp();
    }
});

function validateEditView() {
    var status = true;
    jQuery("#summaryError").hide();
    jQuery("#totalCostError").hide();
    if (jQuery("#summary").val() == '') {
        jQuery("#summaryError").fadeIn("slow");
        status = false;
    }
    if (jQuery("#totalCost").val().indexOf('.') >= 0 || jQuery("#totalCost").val() == '') {
        jQuery("#errorValue").html("Total Cost should be a whole number.");
        jQuery("#totalCostError").fadeIn("slow");
        status = false;
    }
    if (jQuery("#totalCost").val().indexOf('$') >= 0) {
        jQuery("#errorValue").html("Please enter NUMBERS only ($ is not an acceptable character).");
        jQuery("#totalCostError").fadeIn("slow");
        status = false;
    }
    return status;
}

function populateContract(costGroupId, url) {
    jQuery.getJSON(url, {id:costGroupId, ajax: 'true'}, function(contracts) {
        var htmlString = "<option>Choose a contract</option>";
        for (var i = 0; i < contracts.length; i++) {
            htmlString = htmlString + "<option value='" + contracts[i].id + "'>" + contracts[i].text + "</option>";
        }
        jQuery('#contract').html(htmlString);
    });
}
function filterContractsForEditView(costGroupId, issueId, url) {
    jQuery.getJSON(url, {id:costGroupId,issueId:issueId, ajax: 'true'}, function(contracts) {
        var htmlString = "";
        for (var i = 0; i < contracts.length; i++) {
            htmlString = htmlString + "<option value='" + contracts[i].id + "'>" + contracts[i].text + "</option>";
        }
        jQuery('#contract').html(htmlString);
    });
}

/*If you are not using jQuery you can show/hide the div using javascript(e.g. document.getElementById) to do the same*/
function validateSummary() {
    var status = true;
    if (jQuery("#changeOrderSummary").val() == '') {
        jQuery("#summaryError").show();
        status = false;
    }
    if (jQuery("#totalCost").val().indexOf('.') >= 0 || jQuery("#totalCost").val() == '') {
        jQuery("#errorValue").html("Total Cost should be a whole number.");
        jQuery("#totalCostError").show();
        status = false;
    }
    if (jQuery("#totalCost").val().indexOf('$') >= 0) {
        jQuery("#errorValue").html("Please enter NUMBERS only ($ is not an acceptable character).");
        jQuery("#totalCostError").show();
        status = false;
    }
    if (status) {
        jQuery('.fields').hide();
        jQuery('#authenticateForm').show();
        jQuery('#password').focus();
        adjustPopup("Authenicate Approval");
    }
}

function doNav(url) {
    window.location.href = url;
}

function bindWindowResizeToFixTableWrapper(tableId) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridWidth(jQuery(window).width() - 10);
            $("#" + tableId).setGridHeight(jQuery(window).height() - 230);
            removeScrollableDivScroll();
        }).trigger('resize');
}

function bindWindowResizeToFixTableWrapperForFileManager(tableId) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridWidth(jQuery("#leftPanel").width() - 50);
        }).trigger('resize');
}


function bindWindowResizeToFixTableWrapperForSetupWizard(tableId) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridHeight(jQuery(window).height() - 190);
            removeScrollableDivScroll()
        }).trigger('resize');
}

function bindWindowResizeToFixTableWrapperForSetupType1(tableId) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridWidth((jQuery(window).width() - jQuery("#setupWizardGrid").width() - 70));
            $("#" + tableId).setGridHeight(jQuery(window).height() - 260);
            removeScrollableDivScroll()
        }).trigger('resize');
}

function bindWindowResizeToFixTableWrapperForReasonCOR(tableId) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridHeight(jQuery(window).height() - 260);
            removeScrollableDivScroll()
        }).trigger('resize');
}

function bindWindowResizeToFixTableWrapperForCORMarkup(tableId) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridWidth((jQuery(window).width() - jQuery("#setupWizardGrid").width() - jQuery("#reasonForCORTable").width() - 170));
            $("#" + tableId).setGridHeight(jQuery(window).height() - 350);
            removeScrollableDivScroll()
        }).trigger('resize');
}

function bindWindowResizeToFixTableWrapperForListFilesDR(tableId) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridWidth(jQuery(window).width() - 10);
            $("#" + tableId).setGridHeight(jQuery(window).height() - 270);
            removeScrollableDivScroll()
        }).trigger('resize');
}

function bindWindowResizeToFixTableWrapperForSchedule(tableId, message) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridWidth(jQuery(window).width() - 10);
            if (message == "warning") {
                $("#" + tableId).setGridHeight(jQuery(window).height() - 310);
            } else {
                $("#" + tableId).setGridHeight(jQuery(window).height() - 300);
            }
            removeScrollableDivScroll()
        }).trigger('resize');
}

function bindWindowResizeToFixTableWrapperForDailyReports(tableId, message) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridWidth(jQuery(window).width() - 10);
            if (message == "warning") {
                $("#" + tableId).setGridHeight(jQuery(window).height() - 340);
            } else {
                $("#" + tableId).setGridHeight(jQuery(window).height() - 330);
            }
            removeScrollableDivScroll()
        }).trigger('resize');
}


function removeScrollableDivScroll() {
    $("#scrollable-layout").css('overflow-y', 'hidden');
}

function showPopUp(url, divId, cacheBoolean) {
    cacheBoolean = cacheBoolean ? cacheBoolean : false;
    jQuery.get(url, {ajaxDate:new Date(),ajax: 'true',cache:cacheBoolean }, function(receivedHtml) {
        if (divId) {
            jQuery('#' + divId).html(receivedHtml);
            alignPopUp();
        }
    });
}

function displayContentInDialogBox(url, title, width) {
    var divId = "#dialog-box-content";
    Ext.Ajax.request({
        url:url,
        success: function(response, options) {
            var html = response.responseText;
            jQuery("#dialog-box").dialog("destroy");
            jQuery(divId).html(html);
            jQuery("#dialog-box").dialog({
                title:title,
                modal: true,
                width:width
            });
        }
    });
}


function hidePopup(panelId) {
    jQuery('#GB_window').fadeOut('slow');
    jQuery('#GB_overlay').fadeOut('slow');
    jQuery('#GB_window').html("");
    jQuery('#GB_overlay').html("");
    jQuery('#GB_window').remove();
    jQuery('#GB_overlay').remove();
    jQuery("#cluetip").hide();
    jQuery.each(jQuery("input[type='button']"), function() {
        jQuery(this).attr({'disabled':''});
    });
    jQuery("#dialog-box").dialog("destroy");
    closePopupPanel(panelId);
}

function clearQueueOfFiles(url, attachmentDir, cacheBoolean) {
    cacheBoolean = cacheBoolean ? cacheBoolean : false;
    attachmentDir = (attachmentDir && attachmentDir != "undefined") ? attachmentDir : '';
    jQuery.get(url, {attachmentDir:attachmentDir,ajaxDate:new Date(),ajax: 'true',cache:cacheBoolean}, function(receivedHtml) {

    });
    jQuery("#dialog-box").dialog("destroy");
}

function showHideTaskNotes(id) {
    jQuery(".currentnav1").removeClass('currentnav1');
    jQuery("#" + id).addClass('currentnav1');
    jQuery("#taskNotes").hide();
    jQuery("#safetyNotes").hide();
    jQuery("#extraWorkNotes").hide();
    jQuery("#" + id + 's').show();
}

function editTranscription(id, transcription) {
    jQuery('#popup').show();
    jQuery('#transcription').html('');
    jQuery('#transcription').val(transcription);
    jQuery('.editTranscription').val(id);
}

function validateTitleSummary() {
    var status = true;
    if (jQuery("#title").val() == '') {
        jQuery("#titleError").fadeIn("slow");
        status = false;
    }
    return status;
}

function validateRfiSummary(isTrainingProject, clearFile, messLink) {
    var status = true;
    if (isTrainingProject == 'false') {
        if (jQuery("#summary").val() == '') {
            jQuery("#summaryError").fadeIn("slow");
            status = false;
        }
        if (Ext.getCmp('info').getValue() == '') {
            jQuery("#informationRequestedError").fadeIn("slow");
            status = false;
        }
    } else {
        status = false;
        checkTrainingProject(isTrainingProject, clearFile, messLink);
    }
    if (status) {
        showWaitDialog();
    }
    return status;
}

function showAttachmentPopup(issueId) {
    var divId = 'dialog-box-attachment';
    var attachWindowUrl = createUrl('util', 'bigAttachFilePopup') + '/' + issueId;
    showExtPopupInDiv(attachWindowUrl, 'Attach File', 950, divId);
}

function checkTrainingProject(isTrainingProject, clearFile, messLink) {
    var status = true;
    if (isTrainingProject == "true") {
        hidePopup();
        if (clearFile) {
            clearQueueOfFiles(clearFile);
        }
        showDialogBox(messLink);
        status = false
    }
    return status;
}

function showDialogBox(messLink) {
    jQuery.post(messLink, {ajaxDate:new Date(),ajax: 'true',cache:false}, function(data) {
        jQuery("#dialog-message").dialog("destroy");
        jQuery('#training-message-span').text(data);
        jQuery("#dialog-message").dialog({
            modal: true,
            width:500,
            buttons: {
                Ok: function() {
                    jQuery(this).dialog("close");
                },
                "RETURN TO HOMEPAGE": function() {
                    window.location.href = getPath();
                }
            }
        });
    });
}

function getPath() {
    var path = "/dashBoard/dashBoard";
    if (window.location.pathname.indexOf("Builder") == "1") {
        path = "/Builder" + path;
    }
    return path;
}


function validateMemoSummaryUsersAndDetails(isTrainingProject, clearFile, messLink) {
    var status = true;
    if (isTrainingProject == 'false') {
        if (jQuery("#summary").val() == '') {
            jQuery("#summaryError").fadeIn("slow");
            status = false;
        }
        if (Ext.getCmp('memoDetails').getValue() == '') {
            jQuery("#detailsError").fadeIn("slow");
            status = false;
        }

        if (jQuery("#namesUserMemo").html() == "") {
            jQuery("#userError").fadeIn('slow');
            status = false;
        }

    } else {
        status = false;
        checkTrainingProject(isTrainingProject, clearFile, messLink);
    }

    return status;
}

function remoteUpdate(element) {
    var value = jQuery(element).attr('name') + "_" + jQuery(element).val();
    var responseData;
    var path = "/fileManager/remoteUpdate";
    if (window.location.pathname.indexOf("Builder") == "1") {
        path = "/Builder" + path;
    }
    jQuery.get(path, {value:value,ajax: 'true',cache:false}, function(response) {
        responseData = response;
    });
    return responseData;
}

function reportUpdate(element) {
    var value = jQuery(element).val();
    var checked = jQuery(element).is(':checked');
    var responseData;
    var path = "/fileManager/reportUpdate";
    if (window.location.pathname.indexOf("Builder") == "1") {
        path = "/Builder" + path;
    }
    jQuery.get(path, {value:value,checked:checked,ajax: 'true',cache:false}, function(response) {
        responseData = response;
    });
    return responseData;
}

function reportUpdateComment(element) {
    var value = jQuery(element).val();
    var id = jQuery("#jobId").val();
    var responseData;
    var path = "/fileManager/reportUpdateComment";
    if (window.location.pathname.indexOf("Builder") == "1") {
        path = "/Builder" + path;
    }
    setTimeout(function() {
        jQuery.get(path, {value:value,id:id,ajax: 'true',cache:false}, function(response) {
            responseData = response;
        });
    }, 500);
    return false;
}

function deleteBluePrint(element) {
    var value = jQuery(element).attr('name') + "_" + jQuery(element).val();
    var responseData;
    var path = "/bbBluePrint/deleteBluePrint";
    if (window.location.pathname.indexOf("Builder") == "1") {
        path = "/Builder" + path;
    }
    jQuery.get(path, {value:value,ajax: 'true',cache:false}, function(response) {
        responseData = response;
        location.reload();
    });
    return responseData;
}


function remoteUpdateRequiredSubmital(url, id) {

    var value = jQuery("#" + id).val()
    var responseData;
    jQuery.get(url, {id:id,specSection:value,ajax: 'true',cache:false}, function(response) {
        responseData = response;
    });
    return responseData;
}


function updateContractor(element, updateId) {
    remoteUpdate(element);
    var elementId = jQuery(element).attr('id');
    var value = jQuery("#" + elementId + " option:selected").text();
    jQuery(element).hide();
    jQuery("#" + updateId).html(value);
}

function validateAgendaSummary(isTrainingProject, clearFile, messLink) {
    var status = true;
    if (jQuery("#summary").val() == '') {
        jQuery("#summaryError").fadeIn("slow");
        status = false;
    }
    if (status) {
        status = checkTrainingProject(isTrainingProject, clearFile, messLink);
    }
    return status
}

function alignPopUp() {
    var screenWidth = screen.width;
    var screenHeight = screen.height;
    var paddingLeftRight = (screenWidth * 0.2);
    var windowWidth = (screenWidth - paddingLeftRight);
    jQuery("#GB_window").css('width', windowWidth);
    jQuery("#GB_window").css('top', screenHeight / 15);
    jQuery("#GB_window").css('margin-right', paddingLeftRight / 2);
    jQuery("#GB_window").css('margin-left', paddingLeftRight / 2);
}

function changePassword(url, form) {
    var validate = true;
    var currentPassword = jQuery("#currentPassword").val();
    var password = jQuery("#password").val();
    var confirmPassword = jQuery("#confirmPassword").val();
    jQuery("#currentPasswordError").html("");
    jQuery("#passwordError").html("");
    jQuery("#confirmPasswordError").html("");
    if (currentPassword == '') {
        jQuery("#currentPasswordError").html("Please enter current password");
        jQuery("#currentPassword").focus();
        validate = false;
    }
    if (validate && password == '') {
        jQuery("#passwordError").html("Please enter password");
        jQuery("#password").focus();
        validate = false;
    }
    if (validate && confirmPassword == '') {
        jQuery("#confirmPasswordError").html("Please enter confirm password");
        jQuery("#confirmPassword").focus();
        validate = false;
    }

    if (validate && confirmPassword != password) {
        jQuery("#confirmPasswordError").html("Password and confirm password do not match");
        jQuery("#confirmPassword").focus();
        validate = false;
    }
    return validate;
}

function validateAddUser() {
    var firstname = jQuery("#firstName").val();
    var lastname = jQuery("#lastName").val();
    var tnhRole = jQuery("#tnhRole").val();
    var primaryEmail = jQuery("#primaryEmail").val();
    var confirmEmail = jQuery("#confirmEmail").val();
    var companyList = jQuery("#company").val();
    var validation = tnhRole == "4";
    jQuery("#firstnameError").html("");
    jQuery("#primaryEmailError").html("");
    jQuery("#confirmEmailError").html("");
    jQuery("#companyError").html("");
    if (companyList == '') {
        jQuery("#companyError").html("<font color='red'>Please choose an existing company from your network or ADD a new company by selecting the ADD NEW COMPANY button to the right.</font>");
        jQuery("#company").focus();
        validation = false;
    } else {
        validation = true;
    }

    if (validation && primaryEmail) {
        var primaryMailUrl = createUrl('contacts', 'verifyEmail');
        var email = primaryEmail;
        $.ajax({
            url: primaryMailUrl,
            data:{ajax: 'true',cache:false,email:email,responseType:'json'},
            dataType: 'json',
            async: false,
            success: function (data) {
                if (data.exist) {
                    var userFullName = data.contactDetail.firstname.toUpperCase() + ' ' + data.contactDetail.lastname.toUpperCase();
                    var str = "WARNING! THIS EMAIL ADDRESS IS ALREADY BEING USED BY USER " + userFullName + "! WOULD YOU LIKE TO ADD USER " + userFullName + " TO YOUR PROJECT?";
                    validation = false;
                    if (confirm(str)) {
                        var existingUserUrl = createUrl('contacts', 'addExistingUser')
                        addInviteExistingUser(existingUserUrl, data.contactDetail.id);
                    } else {
                        jQuery("#primaryEmailError").html("<font color='red'>Email Already Exists! Please Enter Different Email</font>");
                        jQuery("#primaryEmail").val('');
                        jQuery("#primaryEmail").focus();
                    }
                } else {
                    if (tnhRole == "4") {
                        if (primaryEmail != confirmEmail) {
                            jQuery("#confirmEmailError").html("<font color='red'>Do not match with email</font>");
                            jQuery("#confirmEmail").focus();
                            validation = false;
                        }
                    }

                    if (tnhRole != "4" && validation) {
                        if (firstname == '' && lastname == '') {
                            jQuery("#firstnameError").html("<font color='red'>Enter first name or last name</font>");
                            jQuery("#firstName").focus();
                            validation = false;
                        } else {
                            validation = true;
                        }
                        if (validation && primaryEmail == '') {
                            jQuery("#primaryEmailError").html("<font color='red'>Please enter email</font>");
                            jQuery("#primaryEmail").focus();
                            validation = false;
                        } else {
                            if (primaryEmail != confirmEmail) {
                                jQuery("#confirmEmailError").html("<font color='red'>Do not match with email</font>");
                                jQuery("#confirmEmail").focus();
                                validation = false;
                            } else {
                                if (validation) {
                                    validation = true;
                                }
                            }
                        }
                    }
                }
            }
        });
    }
    jQuery("#submitButtonId").disabled = false;
    return validation;
}
function validatePrimaryEmail(url, div) {
    var email = jQuery("#" + div).val()
    var status = false;
    jQuery.post(url, {ajax: 'true',cache:false,email:email}, function(data) {
        if (data.indexOf('exists') != -1) {
            jQuery("#primaryEmailError").html("<font color='red'>Email is Blank or Already Belong to Existing User! Please enter different email</font>");
            jQuery("#primaryEmail").focus();
        } else {
            status = true;
        }
    });
    return status;
}

function updateDropDown(ajaxUrl, selectBoxId) {
    jQuery.getJSON(ajaxUrl, function(data) {
        var selectBox = jQuery('#' + selectBoxId);
        jQuery(selectBox).html('');
        jQuery(selectBox).append('<option value="null">-------</option>');
        jQuery.each(data, function(index, jsonData) {
            jQuery(selectBox).append('<option value="' + jsonData.id + '">' + jsonData.name + '</option>');
        });
    });

}

function markSubmittalAsRecieved(url) {
    var password = jQuery("#password").val();
    var attachmentDir = jQuery("#attachmentDir").val();
    jQuery.get(url, {password:password,attachmentDir:attachmentDir,ajax: 'true',cache:false}, function(data) {
        if (data == 'failed') {
            jQuery("#errorMessage").show();
        } else {
            location.reload(true);
        }
    });
    return false;
}

function expandSubmittal(url, divId) {
    var str = jQuery("." + divId).next().html();
    var hasSubmittal;
    if (str) {
        hasSubmittal = str.indexOf("Meeting Agenda?");
        str = str.indexOf("onclick=\"expandSubmittal('/");
    }
    jQuery(".submittalExpand").remove();
    if (!str || (hasSubmittal == -1 && str != -1)) {
        jQuery.get(url, {date:new Date(),ajax: 'true',cache:false}, function(receivedHtml) {
            jQuery('.' + divId).after("<tr class='submittalExpand'> <td class='centm1' style='padding:0px;' colspan=9'>" + receivedHtml + "</td></tr>");
        });
    }
}

function expandSection(url, divId) {
    var str = jQuery("#" + divId).text();
    if (str != '') {
        jQuery("#" + divId).html('');
    }
    else {
        jQuery.get(url, {date:new Date(),ajax: 'true',cache:false}, function(receivedHtml) {
            jQuery('#' + divId).html(receivedHtml);
        });
    }
}

function searchUsers(url) {
    var issueId = jQuery("#issueId").val();
    var firstname = jQuery("#firstname").val();
    var lastname = jQuery("#lastname").val();
    var username = jQuery("#username").val();
    jQuery.post(url, {ajax: 'true',cache:false,firstname:firstname,lastname:lastname,username:username,issueId:issueId}, function(receivedHtml) {
        hidePopup();
        jQuery('#commonPopupDiv').html(receivedHtml);
    });
    return false;
}

function checkAll(name) {
    if (jQuery('#selectAll:checked').size() == 1) {
        jQuery("input[name=" + name + "]").attr('checked', 'checked');
    } else {
        jQuery("input[name=" + name + "]").attr('checked', '');
    }
}

function searchCompany(url) {
    var name = jQuery("#name").val();
    jQuery.post(url, {ajax: 'true',cache:false,name:jQuery.trim(name)}, function(receivedHtml) {
        hidePopup();
        jQuery('#commonPopupDiv').html(receivedHtml);
    });
    return false;
}

/*New Flow Script for Contact List*/
function addInviteExistingUser(url, contactDetailId) {
    closePopup();
    jQuery('#dialog-box-extjs').html('');
    var companyId = jQuery("#companyId").val();
    url = url + "&id=" + jQuery.trim(companyId);
    url = url + "&contactDetailId=" + jQuery.trim(contactDetailId);
    showExtPopup(url, 'Invite Existing User', 1023);
    return false;
}

function addNewUser(url) {
    var companyId = jQuery("#companyId").val();
    companyId = jQuery.trim(companyId);
    url = url + "/" + companyId;
    showExtPopup(url, 'Add New User', 1023);
    return false;
}

function searchAndPopulateCompany(url) {
    var name = jQuery("#name").val();
    setTimeout(function() {
        jQuery.post(url, {ajax: 'true',cache:false,name:jQuery.trim(name)}, function(receivedHtml) {
            /*hidePopup();*/
            jQuery('#companyResults').html(receivedHtml);
        });
    }, 500);
    return false;
}

var typingTimeout;
function startTypingTimer(input_field) {
    if (typingTimeout != undefined) {
        clearTimeout(typingTimeout);
    }
    typingTimeout = setTimeout(function() {
        eval(input_field.attr("onfinishinput"));
    }, 500);
}

function addNewCompany(url) {
    showExtPopup(url, 'Add New Company', 1023);
    return false;
}

function showCompanyInformation(url, companyId) {
    var id = companyId;
    var status = confirm('Do you want to add this company to your project');
    if (status) {
        addCompany(id, url);
    }
    return false;
}

function saveNewCompany(url) {
    var values = jQuery("#saveCompany").serialize();
    url = url + "?" + values;
    showExtPopup(url, 'Company Details', 1023);
    return false;
}
/*New Script end*/

function saveCompanyNetwork(url, id) {
    jQuery.post(url, {ajax: 'true',cache:false,id:id}, function(receivedHtml) {
        jQuery('#' + id).remove();
        if (jQuery("#companyResults tr").size() == 0) {
            jQuery("#companyResults").html('<tr bgcolor="#FFFFFF"><td align="left" valign="middle" style="font-size:15px; ">You have added all the companies to your network</td></tr>');
        }
    });


}

function addUsersToProject(rolesId, rolesName) {
    var selectBox = createRoleSelectBox(rolesId, rolesName);
    jQuery("#companyUsersTable").find('input:checked').each(function() {
        var checkBoxValue = jQuery(this).val();
        jQuery("#removeUser" + checkBoxValue).remove();
        jQuery("#saveUsersToProject").append("<input type='hidden' name='addUser' value='" + checkBoxValue + "' id='addUser" + checkBoxValue + "'/>");
    });
    jQuery("#companyUsersTable").find('input:checked').parent().parent().each(function() {
        var numRows = jQuery("#projectUsersTable tbody tr").size();
        var className = numRows % 2 == 0 ? "leftme9ed" : "leftmd0d8";
        var newRow = "<tr style='text-align:center;' class='" + className + "'>";
        jQuery(this).find('td').each(function() {
            var textValue = jQuery(this).html().toString();
            var checkBoxIndex = textValue.indexOf("<input");
            if (checkBoxIndex == -1) {
                newRow = newRow + "<td>" + textValue + "</td>";
            } else {
                newRow = newRow + "<td>" + selectBox + "</td>";
                newRow = newRow + "<td style='padding-right:20px;'>" + textValue + "</td>";
                newRow = newRow + "</tr>";
            }
        });
        jQuery("#projectUsersTable tbody>tr:first").before(newRow);
        jQuery(this).remove();
    });
}

function createRoleSelectBox(rolesId, rolesName) {
    var htmlString = "<select name='role'>";
    for (var i = 0; i < rolesId.length; i++) {
        htmlString = htmlString + "<option value='" + rolesId[i] + "'>" + rolesName[i] + "</option>";
    }
    htmlString = htmlString + "</select>";
    return htmlString;
}

function removeUsersFromProject() {
    jQuery("#projectUsersTable").find('input:checked').each(function() {
        var checkBoxValue = jQuery(this).val();
        jQuery("#addUser" + checkBoxValue).remove();
        jQuery("#saveUsersToProject").append("<input type='hidden' name='removeUser' value='" + checkBoxValue + "' id='removeUser" + checkBoxValue + "'/>");
    });
    jQuery("#projectUsersTable").find('input:checked').parent().parent().each(function() {
        var numRows = jQuery("#companyUsersTable tbody tr").size();
        var className = numRows % 2 == 0 ? "leftme9ed" : "leftmd0d8";
        var newRow = "<tr style='text-align:center;' class='" + className + "'>";
        jQuery(this).find('td').each(function(index, value) {
            var textValue = jQuery(value).html().toString();
            if (index != 2) {
                if (index == 3) {
                    newRow = newRow + "<td>" + textValue + "</td style='padding-right:20px;'></tr>";
                } else {
                    newRow = newRow + "<td>" + textValue + "</td>";
                }
            }
        });
        jQuery("#companyUsersTable tbody>tr:first").before(newRow);
        jQuery(this).remove();
    });
}

function showUserList(companyId) {
    jQuery("#savebutton").show();
    jQuery("#companyUsers").show();
    jQuery("#companyAdmins").show();
    jQuery("#companyId").val(companyId);
}

function markProjectAsComplete(url, id) {
    jQuery.post(url, {ajax: 'true',cache:false}, function(receivedHtml) {
        jQuery('#' + id).remove();
    });

}
function refreshPlSubCategory() {
    jQuery("#plSubCategory").html('<option value="null">-------</option>');

}
function refreshPlProblem() {
    jQuery("#plProblem").html('<option value="null">-------</option>');
}

function updatePhoto(url) {
    var note = jQuery("#note").val();
    var album = jQuery("#album").val();
    jQuery.get(url, {note:note,'album.id':album,ajax: 'true',cache:false}, function(data) {

    });
    jQuery('.editTask').hide();
    jQuery('.showTask').show();
    jQuery('#note').attr({'disabled': 'disabled'});
    jQuery("#noteSpan").html(note.substring(0, 57));
    jQuery("#noteSpan1").html(note.substring(0, 22) + "...");
}

function deletePhoto(url, id) {
    var value = confirm("Are you sure you want to delete this photo");
    if (value) {
        jQuery.get(url, {ajax: 'true',cache:false}, function(data) {

        });
        jQuery("#" + id).remove();
        hidePopup();
    }
}

function editTask() {
    jQuery('#message').hide();
    jQuery('.showTask').hide();
    jQuery('.editTask').show();

}

function showTask() {
    jQuery('.editTask').hide();
    jQuery('.showTask').show();
}

function selectMemoUsers(roleClass) {
    jQuery(".allUsers").find(":checkbox").attr({'checked':false});
    jQuery("#userRole").show();
    jQuery("." + roleClass).show();
    jQuery("." + roleClass).find(":checkbox").attr({'checked':'checked'});

}

function addAllMemoUsers() {
    jQuery("#userRole").show();
    jQuery(".allUsers").show();
    jQuery(".allUsers").find(":checkbox").attr({'checked':'checked'});
}

function refreshUsersMemo() {
    jQuery("#userRole").show();
    jQuery(".allUsers").show();
}

function sendPhoto(url) {
    var values = jQuery("#emailPhoto").find('input').serialize();
    values = values + "&" + jQuery("#emailPhoto").find('textarea').serialize();
    jQuery.post(url, values, function(data) {
        hidePopup();
    });
    return false;
}


function setFilterName(filterName) {
    jQuery("#filterName").html(filterName);
}

function setPdfFormAction(actionName) {
    var formAction = jQuery("#pdfFormContact").attr('action');
    formAction = formAction.substr(0, formAction.lastIndexOf("/") + 1);
    formAction = formAction + actionName;
    jQuery("#pdfFormContact").attr('action', formAction);
}

function changeIssuePriority(url) {
    showPopUp(url, '');
    var display = jQuery("#priorityHigh").css('display');
    if (display == 'none') {
        jQuery("#priorityLow").hide();
        jQuery("#priorityHigh").show();
    } else {
        jQuery("#priorityHigh").hide();
        jQuery("#priorityLow").show();
    }
}

function submitMyForm(url, formName) {
    var formData = jQuery("#" + formName).find('input').serialize();
    formData = formData + "&" + jQuery("#" + formName).find('textarea').serialize();
    formData = formData + "&" + jQuery("#" + formName).find('select').serialize();
    jQuery.post(url, formData, function(data) {
        jQuery("#commonPopupDiv").html(data);
    });
}

function companyTodoList(url) {
    var id = jQuery("#company").val();
    showPopUp(url + "/" + id, 'ext-gen41');
}

function toggleStatusLayer(element, id) {
    var nextElement = jQuery('#' + id);
    var className = jQuery(nextElement).attr('class');
    jQuery(".submitButton").css({'background-color':'#4885D0','color':'#fff'});
    jQuery(".showData").removeClass("showData").addClass("editTask");
    if (className == "editTask") {
        jQuery(nextElement).addClass("showData").removeClass("editTask");
        jQuery(element).css({'background-color':'#fff','color':'#000'});
    } else {
        jQuery(nextElement).addClass("editTask").removeClass("showData");
        jQuery(element).css({'background-color':'#4885D0','color':'#fff'});
    }
}

function showSchedule() {

    jQuery.each(jQuery(":checked[name='status']"), function() {
        var trClass = jQuery(this).val();
        jQuery("tr [class*='" + trClass + "']").show();
    });
}


function remoteDateUpdate(element, divId) {
    var name = jQuery(element).attr('name');
    var dateValue = '';
    jQuery.each(jQuery("select[name=" + name + "]"), function(index, value) {
        if (index != 0) {
            dateValue = dateValue + "/";
        }
        dateValue = dateValue + jQuery(value).val();
    });
    dateValue = name + "_" + dateValue;
    var path = "/fileManager/remoteDateUpdate";
    if (window.location.pathname.indexOf("Builder") == "1") {
        path = "/Builder" + path;
    }
    jQuery.get(path, {value:dateValue,ajax: 'true',cache:false}, function(response) {
        jQuery('#' + divId).html(response);
    });
}

function showBaseline() {
    hideAllBaseLine();
    jQuery.each(jQuery(":checked[name='baseline']"), function() {
        var baselineValue = jQuery(this).val();
        if (baselineValue == '0') {
            jQuery("table[bgcolor='#000000']").show();
        }
        if (baselineValue == '1') {
            jQuery(".actual").show();
        }
    });
}

function hideAllBaseLine() {
    jQuery("table[bgcolor='#000000']").hide();
    jQuery(".actual").hide();
}

function submitSearchUser() {
    jQuery(".errorMessage").html("");
    var submitForm = false;
    var firstName = jQuery("#firstname").val();
    var lastName = jQuery("#lastname").val();
    var userName = jQuery("#username").val();
    var company_id = jQuery("#company_id").val()


    if (jQuery.trim(firstName) || jQuery.trim(lastName) || jQuery.trim(company_id) || jQuery.trim(userName)) {
        submitForm = true;
    }
    if (!submitForm) {
        jQuery(".searchError").after("<tr class='errorMessage'><td colspan='2' align='center''><font size='3' color='red'>&nbsp;&nbsp;Please enter your search term</font></td></tr>");
        jQuery("#firstname").focus();
    }
    return submitForm;
}

function loadScheduleForTaskDescription(url, startDate, endDate, totalCount) {
    jQuery("#sortField").val("summary");
    toggleSortOrder();
    loadSchedule(url, startDate, endDate, totalCount, 0);
}

function toggleSortOrder() {
    if (jQuery("#sortOrder").val() == "desc") {
        jQuery("#sortOrder").val("asc");
    } else {
        jQuery("#sortOrder").val("desc");
    }
}

function loadScheduleForId(url, startDate, endDate, totalCount) {
    jQuery("#sortField").val("myNumber");
    toggleSortOrder();
    loadSchedule(url, startDate, endDate, totalCount, 0);
}


function loadSchedule(url, startDate, endDate, totalCount, maxListSize) {
    var offset = 0;
    var max = jQuery(".next").size() + maxListSize;
    var sortField = jQuery("#sortField").val();
    var sortOrder = jQuery("#sortOrder").val();
    jQuery.get(url, {startDate:startDate,endDate:endDate,offset:offset,max:max,sortField:sortField,sortOrder:sortOrder,ajax: 'true',cache:false}, function(response) {
        jQuery(".scheduleListBody").html(response);
        offset = jQuery(".next").size();

        if (offset == totalCount) {
            jQuery("#tableFooter a").remove();
        } else {
            jQuery("#tableFooter a").html("Showing " + offset + " of " + totalCount + " More");
        }
    });
}

function loadNext(url, totalCount) {
    jQuery(".filters").remove();
    var offset = jQuery(".next").size();
    jQuery.get(url, {offset:offset,ajax: 'true',cache:false}, function(response) {
        jQuery(".next:last").after(response);
        offset = jQuery(".next").size();
        if (offset == totalCount) {
            jQuery("#tableFooter a").html('');
        } else {
            jQuery("#tableFooter a").html("Showing " + offset + " of " + totalCount + " More");
        }
        jQuery(".tablesorter").tablesorter();
        jQuery.each(jQuery(".tablesorter"), function() {
            jQuery(this).tableFilter();
        });
    });
    jQuery(".tablesorter").tablesorter({
        textExtraction: function(node) {
            return (jQuery(node).text());
        }

    });
}
function validateFormPassword(url, formId) {
    var password = jQuery('#password').val();
    jQuery.post(url, {password:password,ajax:true,cache:false}, function(response) {
        if (response.indexOf("success") == -1) {
            jQuery("#errorMessage").show();
        } else {
            jQuery("#" + formId).submit();
        }
    });
    return false;
}


function validateAddLinItemForm(id, amount, amountused, note, isTrainingProject, clearFile, messLink) {
    var status = true;
    var newAmount = parseInt(jQuery("#" + id).val());
    var contractAmount = parseInt(amount)
    var amountUsed

    if (amountused == "NaN") {
        amountUsed = 0
    }
    else {
        amountUsed = parseInt(amountused)
    }

    jQuery("#descriptionError").hide();
    jQuery("#amountError").hide();
    if (jQuery("#description").val() == '') {
        alert("Please enter valid description");
        status = false;
    }
    if (jQuery("#amount").val() == '') {
        alert("Please enter valid amount");
        status = false;
    }
    if ((newAmount + amountUsed) > contractAmount) {
        alert(note);
        status = false;
    }

    if (status) {
        jQuery("#saveLineItem").submit();
    }
}

function moveBack() {
    var date = jQuery("#prevDate").val();
    jQuery("#date").val(date);
    jQuery("#moveSchedule").submit();
}

function moveNext() {
    var date = jQuery("#nextDate").val();
    jQuery("#date").val(date);
    jQuery("#moveSchedule").submit();
}

function fetchLineItems(url) {
    var select = "Line Items <select name='lineItem'>";
    var contract = jQuery("#contract").val()
    if (contract == 'null') {
        select = select + "</select>";
        jQuery("#lineItems").html(select);
    } else {
        jQuery.getJSON(url, {id:contract}, function(json) {
            jQuery.each(json.lineItems, function(i, item) {
                select = select + "<option value=''" + item.key + "'>" + item.value + "</option>"
            });
            select = select + "</select>";
            jQuery("#lineItems").html(select);
        });
    }
}

function validateUnusedAllowances(url) {
    var password = jQuery('#password').val();
    jQuery.post(url, {password:password,ajax:true,cache:false}, function(response) {
        if (response.indexOf("success") == -1) {
            jQuery("#responseText").html(response);
        } else {
            jQuery("#passwordTable").hide();
            jQuery("#contractsTable").show();
        }
    });
    return false
}

function validatePayApp(url, isTrainingProject, messLink) {
    var password = jQuery('#password').val();
    jQuery.post(url, {password:password,ajax:true,cache:false}, function(response) {
        if (response.indexOf("success") == -1) {
            jQuery('#errorMessage').show();
            jQuery('#password').focus();
        } else {
            jQuery("input[type='image']").disable = true;
            if (isTrainingProject == "true") {
                checkTrainingProject(isTrainingProject, null, messLink);
            } else {
                jQuery("#submitForm").submit();
            }
        }
    });
    return false;
}

function showPassword(url, status) {
    jQuery.post(url, {status:status,ajax:true,cache:false}, function(response) {
        jQuery("#commonPopupDiv").html(response);
    });
}

function selectTab(href) {
    var anchor = jQuery("#tasks1 ul li a[href*=" + href + "]");
    jQuery(anchor).attr('href', '#');
    jQuery(anchor).addClass('currentnav1');
}

function validateFirstAndLastName() {
    var status = true;
    if (jQuery("#firstname").val() == '') {
        jQuery("#firstNameError").fadeIn("slow");
        status = false;
    }
    if (jQuery("#lastname").val() == '') {
        jQuery("#lastNameError").fadeIn("slow");
        status = false;
    }
    return status
}

function rotateImage(id, value) {
    var browser = '';
    if (navigator.userAgent.indexOf("Firefox") != -1)
        browser = "firefox";
    if (navigator.userAgent.indexOf("MSIE") != -1)
        browser = "ie";
    if (navigator.userAgent.indexOf("Safari") != -1)
        browser = "safari";
    if (browser != "ie") {
        value = 90 * parseInt(value);
    }
    if (browser == "ie") {
        jQuery("#" + id).css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + value + ')')
    }
    if (browser == "firefox") {
        jQuery("#" + id).css('-moz-transform', 'rotate(' + value + 'deg)')
    }
    if (browser == "safari") {
        jQuery("#" + id).css('-webkit-transform', 'rotate(' + value + 'deg)')
    }

}

function expandTaskGroup(url, id) {
    var row = jQuery(".expendedGroup" + id);
    var filterRow = jQuery(".fllter");
    if (jQuery(row).size() > 0) {
        if (jQuery(row).css('display') == 'none') {
            jQuery("tr[class*=expendedGroup]").hide();
            jQuery(row).show();
        } else {
            jQuery("tr[class*=expendedGroup]").hide();
            jQuery(row).hide();
        }
    } else {
        jQuery("tr[class*=filter]").hide();
        jQuery("tr[class*=expendedGroup]").hide();
        jQuery.post(url, {ajax:true,cache:false}, function(response) {
            jQuery("#group" + id).after(response);
        });
    }
}

function filterCalendarItem() {
    jQuery(".date p.myCal").hide();
    jQuery(".date p.publicCal").hide();
    jQuery(".event_boxPublic").hide();
    jQuery(".event_boxMy").hide();
    jQuery("input[name='type']:checked").each(function() {
        var checkBoxValue = jQuery(this).val()
        if (checkBoxValue == 'public') {
            jQuery(".date p.publicCal").show();
            jQuery(".event_boxPublic").show();
        }
        if (checkBoxValue == 'my') {
            jQuery(".date p.myCal").show();
            jQuery(".event_boxMy").show();
        }
    })
}

function postForm(formId, divId) {
    var values = jQuery("#" + formId).find('input').serialize();
    var url = jQuery("#" + formId).attr('action');
    jQuery.post(url, values, function(data) {
        jQuery("#" + divId).html(data);
    });
    return false
}

function addPayAppNote(url, status, divId) {
    var note = jQuery("#" + divId).val()
    jQuery.post(url, {status:status,note:note,ajax:true,cache:false}, function(response) {
        jQuery("#commonPopupDiv").html(response);
    });
}

function fetchRecordFrom(url, id) {
    jQuery.post(url, {date:new Date(),ajax:true,cache:false}, function(receivedHtml) {
        jQuery('#' + id).after(receivedHtml);
        jQuery('#' + id).remove();
    });
}

function verifyAndShowPassword(id, url, alertUrl, status, cpd) {
    var updatedPercentageComplete = parseInt(jQuery("#updatedPercentageComplete").val())
    var currentPercentageComplete = parseInt(jQuery("#currentPercentageComplete").val())
    var newStoredMaterial = parseInt(jQuery("#newStoredMaterial").val())
    var currentPaymentDue = parseInt(cpd)
    var message = "WARNING!!! You are submitting a payment app for $0. Are you sure you want to submit a payment app for $0? "

    if (currentPaymentDue == 0) {
        jQuery.post(alertUrl, {date:new Date(),passedAction:'showPassword',passedController:'paymentApp',id:id,message:message,ajax:true,cache:false}, function(response) {
            jQuery("#commonPopupDiv").html(response);
        });
    } else {
        showPassword(url, status)
    }
}

function showAddAgendaItemForm(typeId, className) {
    var path = "/issue/addAgendaItem";
    if (window.location.pathname.indexOf("Builder") == "1") {
        path = "/Builder" + path;
    }
    jQuery.get(path, {typeId:typeId,className:className,ajax: 'true'}, function(rfiForm) {
        jQuery('#commonPopupDiv').html(rfiForm);
    });
}

function verifyPaymentAppSum(contractId, urlForVerification, url, status) {

    var contract = parseInt(contractId);
    var message = "";

    jQuery.post(urlForVerification, {date:new Date(),ajax:true,cache:false}, function(received) {
        if (received.indexOf("Success") >= 0) {
            jQuery.post(url, {status:status,ajax:true,cache:false}, function(response) {
                jQuery("#commonPopupDiv").html(response);
            });
        } else {
            alert(received);
        }
    });
}

function verifyPaymentAppSumSimple(contractId, urlForVerification, url) {

    var contract = parseInt(contractId);
    var message = "";
    jQuery.post(urlForVerification, {date:new Date(),ajax:true,cache:false}, function(received) {
        if (received.indexOf("Success") >= 0) {
            jQuery.post(url, {date:new Date(),ajax:true,cache:false}, function(response) {
                jQuery("#commonPopupDiv").html(response);
            });
        } else {
            alert(received);
        }
    });
}

function validateSummaryAsi(editMode) {
    var status = true;
    if (Ext.getCmp('asiSummary').getValue() == '') {
        jQuery("#asiSummaryError").show();
        status = false;
    }
    if (editMode && status) {
        jQuery("form #authenticateAsi").show();
        jQuery('#mainTable').hide();
        adjustPopup('Authenticate Approval')
        jQuery("#asiPassword").focus();
    }
    return status
}

function compatibleDirName(element) {
    var value = jQuery(element).val().split(/[\s/]+/).join('_').trim();
    jQuery(element).val(value);
}

function updateLineItemPopup(updateLineItemUrl, id) {
    var divId = 'commonPopupDiv';
    var cacheBoolean = cacheBoolean ? cacheBoolean : false;
    jQuery.get(updateLineItemUrl, {id:id,ajaxDate:new Date(),ajax: 'true',cache:cacheBoolean }, function(receivedHtml) {
        if (divId) {
            jQuery('#' + divId).html(receivedHtml);
            alignPopUp();
        }
    });

}

function doNavInNewWindow(url) {
    window.open(url);
}


function bindWindowResizeToFixTableWrapperForSubmittal(tableId) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridWidth((jQuery(window).width() - jQuery("#setupWizardGrid").width() - 70));
            $("#" + tableId).setGridHeight(jQuery(window).height() - 450);
            removeScrollableDivScroll()
        }).trigger('resize');
}

function openDialog(divId) {
    jQuery('#' + divId).dialog('open');
}

function closeDialog(divId) {
    jQuery('#' + divId).dialog('close');
}

function openInDialogBox(url, title, width) {
    jQuery.get(url, {ajaxDate:new Date(),ajax: 'true',cache:false }, function(receivedHtml) {
        displayResponseInDialog(title, receivedHtml, width);
    });
}

function displayResponseInDialog(title, data, width) {
    hidePopup();
    var divId = "#dialog-box-content";
    jQuery("#dialog-box").dialog("destroy");
    jQuery(divId).html(data);
    jQuery("#dialog-box").dialog({
        title:title,
        modal: true,
        width:width
    });
}


function verifyValuesForLineItemAndSubmit(title, errorMessage, invalidMessage) {
    var value = parseInt(jQuery("#amount").val());
    var sum = parseInt(jQuery("#exisitngLineItemSum").val());
    var originalBudget = parseInt(jQuery("#budget").val());

    if (isNaN(value) || isNaN(sum) || isNaN(originalBudget)) {
        showCloseDialog(title, invalidMessage)
    }
    else if (value + sum <= originalBudget) {
        jQuery('#saveOwnerInvoiceItem').submit();
    }
    else {
        showCloseDialog(title, errorMessage)
    }
}

function showCloseDialog(title, message) {
    setDialogBoxValues(title, message)
    closeDialogBox()
}

function showCloseDialogWithFunction(title, message, functionName) {
    setDialogBoxValues(title, message);
    closeDialogBoxWithFunction(functionName);
}


function closeDialogBox() {
    $("#dialog-confirm:ui-dialog").dialog("destroy");
    $("#dialog-confirm").dialog({
        width:800,
        modal: true,
        buttons: {
            "Close": function() {
                $(this).dialog("close");
            }
        }
    });
}

function showWelcomePopup() {
    var url = createUrl('util', 'displayWelcomeMessage');
    jQuery.post(url, {date:new Date(),ajax:true,cache:false}, function(data) {
        displayWelcomeMessage("WELCOME TO BUILDINGBLOK", data, 900)
    });
}

function showWelcomePopupForTrainingProject() {
    var url = createUrl('util', 'displayWelcomeMessageForTrainingProject');
    jQuery.post(url, {date:new Date(),ajax:true,cache:false}, function(data) {
        displayWelcomeMessage("WELCOME TO BUILDINGBLOK", data, 900)
    });
}

function displayWelcomeMessage(title, data, width) {
    var divId = "#training-welcome-message";
    jQuery("#training-dialog-welcome").dialog("destroy");
    jQuery(divId).html(data);
    jQuery("#training-dialog-welcome").dialog({
        title:title,
        width:width,
        modal: true,
        buttons: {
            "Close": function() {
                $(this).dialog("close");
            }
        }
    });
}

function closeDialogBoxWithFunction(closeFunctionName) {
    $("#dialog-confirm:ui-dialog").dialog("destroy");
    $("#dialog-confirm").dialog({
        width:800,
        modal: true,
        buttons: {
            "Close": function() {
                closeFunctionName();
            }
        }
    });
}


function showYesNoDialogBox(title, message, yesFunctionName) {
    setDialogBoxValues(title, message);
    yesNoDialogBox(yesFunctionName);
}

function setDialogBoxValues(title, message) {
    jQuery("#dialog-confirm").attr('title', title);
    jQuery("#textForModalDialog").text(message);
}

function yesNoDialogBox(yesFunctionName) {
    $("#dialog-confirm:ui-dialog").dialog("destroy");
    $("#dialog-confirm").dialog({
        width:800,
        modal: true,
        buttons: {
            "No": function() {
                $(this).dialog("close");
            },
            "Yes": function() {
                yesFunctionName()
            }
        }
    });
}
function bindWindowResizeToFixTableWrapperInvitationPages(tableId) {
    jQuery(window).bind('resize',
        function() {
            $("#" + tableId).setGridWidth(jQuery(window).width() - 10);
            $("#" + tableId).setGridHeight(jQuery(window).height() - 325 - jQuery('#' + tableId + '_pager').height());
            removeScrollableDivScroll();
        }).trigger('resize');
}

function showChangeOrderPopupForSub() {
    var url = createUrl('util', 'displayChangeOrderMessage');
    jQuery.post(url, {date:new Date(),ajax:true,cache:false}, function(data) {
        displayWelcomeMessage("Message", data, 800)
    });
}
function showRfiPopupForSub() {
    var url = createUrl('util', 'displayRfiMessage');
    jQuery.post(url, {date:new Date(),ajax:true,cache:false}, function(data) {
        displayWelcomeMessage("Message", data, 800)
    });
}
function displayResponseInDialogWithCloseButton(title, data, width) {
    hidePopup();
    var divId = "#dialog-box-content";
    jQuery("#dialog-box").dialog("destroy");
    jQuery(divId).html(data);
    jQuery("#dialog-box").dialog({
        title:title,
        modal: true,
        width:width,
        buttons: {
            "Close": function() {
                jQuery("#dialog-box").dialog("destroy");
            }
        }
    });
}

function showTagsPopUp(url) {
    showPopUp(url, 'uploadFileDiv');
    displayCloseDialogId("Tags ", 500, "uploadFileDiv", createDialogClose)
}

function showJQUIPopupWithCloseButton(url, title) {
    jQuery.post(url, {date:new Date(),ajax:true,cache:false}, function(data) {
        displayResponseInDialogWithCloseButton(title, data, 500)
    });
}


function displayContentInDialogBoxWithoutClosingPopup(url, title, width) {
    var divId = "#dialog-box-contract-content";
    jQuery.post(url, {ajaxDate:new Date(),ajax: 'true',cache:false}, function(data) {
        jQuery(divId).html(data);
        jQuery("#dialog-box-contract").dialog({
            title:title,
            modal: true,
            width:width
        });
    });
}

function alignDialog(position) {
    jQuery("#dialog-box").dialog("option", "position", position);
}

function showLoginPopup() {
    var url = createUrl('dashBoard', 'showLoginPopup');
    displayContentInDialogBox(url, 'login', 550)
}

function watermarkOnBlurForInput(el, watermarkText) {
    if (el.value == '') {
        el.value = watermarkText
    }
}

function watermarkOnFocusForInput(el, watermarkText) {
    if (el.value == watermarkText) {
        el.value = ''
    }
}
function displayContentInDialogBoxWithCloseButton(url, title, width) {
    var divId = "#dialog-box-content";
    jQuery.post(url, {ajaxDate:new Date(),ajax: 'true',cache:false}, function(data) {
        jQuery("#dialog-box").dialog("destroy");
        jQuery(divId).html(data);
        jQuery("#dialog-box").dialog({
            title:title,
            modal: true,
            width:width,
            buttons: {
                "Close": function() {
                    jQuery("#dialog-box").dialog("destroy");
                }
            }
        });
    });
}
function getUserTodoList(url) {
    var userId = jQuery("select[name=user]").val();
    var url = url + '?user=' + userId
    fetchTemplate(url, 'todo1');
}

function getDaysDiff(startDate, endDate) {
    var diff = Math.floor((Date.parse(endDate) - Date.parse(startDate)) / 86400000);
    return diff;
}

function deleteContact(url) {
    $.post(url, {ajaxDate:new Date(),ajax:true}, function(data) {
        var reassignUrl
        if (data == 'success') {
            reassignUrl = createUrl('contacts', 'listContact');
            window.location.href = reassignUrl
        } else {
            reassignUrl = createUrl('contacts', 'reassignToUser') + '/' + data;
            showExtPopup(reassignUrl, 'Reassign To', 700);
        }
    });
}

function updateCompanyDetails(divId) {
    var values = jQuery("#companyDetail").serialize();
    var url = jQuery("#companyDetail").attr('action');
    $.ajax({url: url,data:values,async: false,success: function (data) {
        if (data == "true") {
            location.reload();
        }
    }});
}


function hideProcessButton() {
    jQuery('input[name="_action_finalApproval"]').hide();
}

function isValidEmail(str) {
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function companyEmailExists(email) {
    var value = false;
    var url = createUrl('home', 'companyEmailExists');
    jQuery.ajax({
        async:false,
        url:    url,
        data : {email:email, ajax: 'true'},
        dataType : 'json',
        success: function(data) {
            value = data.companyEmailExists
        },
        complete : function() {}

    });
    return value
}


function companyExists(compName) {
    var value = false;
    var url = createUrl('home', 'companyExists');
    jQuery.ajax({
        url:    url,
        async:false,
        data : {companyName:compName, ajax: 'true'},
        dataType : 'json',
        success: function(data) {
            value = data.companyExists
        },
        complete : function() {}
    });
    return value
}

function getCurrentTimeInMillis(){
    var currentTimeInMillis = new Date().getTime();
    return currentTimeInMillis;
}

function getAttachmentDir(tempDirPath){
    var attachmentDir = tempDirPath + getCurrentTimeInMillis() + '/';
    return attachmentDir;
}




