﻿/* Common Javascript Description.
* Company              :   CargoFlash Infotech	Pvt. Ltd.
* Copyright            :   Copyright © 2010-2011 CargoFlash Infotech Pvt. Ltd.
* Purpose              :   This class takes care of the Default page and loading of the javascript and css on each page.
* Description          :   Add Methods related to CrossList(In case of add new,update and Delete)
*/

// Method to fill the drop down using json from another drop down...
// destinationDropdown: The dropdown that will be filled according to next param.
// entityName: The name of the table from which the drop down will be filled.
// valueColumn: The column that will go in the value column of the drop down.
// textColumn: The column which will be shown as the text in the destination drop down.
// whereCondition: The condition against which the destination drop down in the first param will be filled.
// firstValue: The first value that will be added in the starting or the end depending on the addAdditionalValueInStarting param. Keep null if not required.
// firstText: The first text that will be added in the starting or the end depending on the addAdditionalValueInStarting param. keep null if not required.
// addAdditionalValueInStarting: Weather to add the additional values in the end or in the starting.
function FillDropDownConditionally(destinationDropdownClientID, entityName, valueColumn, textColumn, whereCondition, firstValue, firstText, addAdditionalValueInStarting) {
    $("#" + destinationDropdownClientID).html("");
    $.ajax({
        url: '../Services/CustomValidation.ashx',
        cache: false,
        async: false,
        data: 'Entity=' + entityName + '&Columns=' + valueColumn + ' AS Value, ' + textColumn + ' AS Text&WhereCondition=' + whereCondition,
        success: function (data) {
            if (firstValue != null & firstText != null && addAdditionalValueInStarting)
                $("#" + destinationDropdownClientID).append($("<option></option>").val(firstValue).html(firstText));
            $.each(data.items, function (i, item) {
                if (item) {
                    $("#" + destinationDropdownClientID).append($("<option></option>").val(item.Value).html(item.Text));
                }
            });
        }
    });
}

function FillDropDownConditionallyForOuterPages(destinationDropdownClientID, entityName, valueColumn, textColumn,
whereCondition, firstValue, firstText, addAdditionalValueInStarting) {

    $("#" + destinationDropdownClientID + " >option").remove();
    $.ajax({
        url: './Services/CustomValidation.ashx',
        cache: false,
        async: false,
        data: 'Entity=' + entityName + '&Columns=' + valueColumn + ' AS Value, ' + textColumn + ' AS Text&WhereCondition=' + whereCondition,
        success: function (data) {
            if (firstValue != null & firstText != null && addAdditionalValueInStarting)
                $("#" + destinationDropdownClientID).append($("<option></option>").val(firstValue).html(firstText));
            $.each(data.items, function (i, item) {
                if (item) {
                    var myCombo = $("#" + destinationDropdownClientID);
                    $("#" + destinationDropdownClientID).append($("<option></option>").val(item.Value).html(item.Text));
                }
            });
        }
    });
}
// Method to split the rows for search control.
function SplitSearch(currentRowId, i) {
    var previousRowId = i;
    i = i + 1;
    var previousId = currentRowId.replace("trSearch", "");
    if ($("#txtSearch" + previousId).val() == "") {
        jAlert("Enter valid search value.", "Search List", function () { $("#txtSearch" + previousId).focus(); });
        return false;
    }
    var newId = "_" + i;

    var trHTML = $("#" + currentRowId).html();

    //Replace the split function id
    trHTML = trHTML.replace("SplitSearch('" + currentRowId + "'," + previousRowId + ");", "SplitSearch('trSearch" + newId + "'," + i + ");");

    // Replace the id of the new controls.
    trHTML = trHTML.replace(new RegExp(previousId, "g"), newId);

    //Get CSS of Current TR Row
    var trCss = $('#' + currentRowId).attr('class');
    var trNewHTML = "<tr id='trSearch" + newId + "' class=\"" + trCss + "\">" + trHTML + "</tr>";
    $(trNewHTML).insertAfter($('#' + currentRowId));
    $('#btnAdd' + previousId).attr('style', 'display:none;');

    $('#spna' + previousId).attr('style', 'display:none;');
    $('#btnRemove' + previousId).attr('style', 'display:inline;');
    $('#ddlOperator' + previousId).attr('style', 'display:inline;');

    $('#spna' + newId).attr('style', 'display:inline;');
    $('#btnRemove' + newId).attr('style', 'display:inline;');
    $('#txtSearch' + newId).val("");
}

// Method to Remove rows for loading instrcution.
function RemoveSearch(currentRowId) {
    var currentId = currentRowId.replace("trSearch_", "");
    var previousId = $("#" + currentRowId).prev().attr("id").replace("trSearch_", "");
    if ($('#spna_' + currentId).attr("style").indexOf("inline") >= 0) {
        if (previousId > 1) {
            $('#btnAdd_' + previousId).attr('style', 'display:inline;');
            $('#spna_' + previousId).attr('style', 'display:inline;');
            $('#btnRemove_' + previousId).attr('style', 'display:inline;');
            $('#ddlOperator_' + previousId).attr('style', 'display:none;');
        }
        else {
            $('#btnAdd_' + previousId).attr('style', 'display:inline;');
            $('#spna_' + previousId).attr('style', 'display:none;');
            $('#btnRemove_' + previousId).attr('style', 'display:none;');
            $('#ddlOperator_' + previousId).attr('style', 'display:none;');
        }
    }
    $("#" + currentRowId).remove();
}

//Method to fill search field dropdown based on DataType;
function FillSearchField(currentObject) {
    var dataType = $("#" + currentObject).val();
    var currentObjId = $("#" + currentObject).attr("id").replace("ddlSearchField", "");
    var searchObject = "ddlSearchCondition" + currentObjId;
    var searchOptions = "";
    $("#txtSearch" + currentObjId).datepicker("destroy");
    $("#txtSearch" + currentObjId).val("");
    if (dataType.indexOf("Int") >= 0 || dataType.indexOf("Float") >= 0 || dataType.indexOf("Decimal") >= 0 || dataType.indexOf("Double") >= 0) {
        searchOptions += "<option value=\"=\">" + 'Equals' + "</option>";
        searchOptions += "<option value=\">\">" + 'GreaterThan' + "</option>";
        searchOptions += "<option value=\"<\">" + 'LessThan' + "</option>";
        searchOptions += "<option value=\">=\">" + 'GreaterThanEqualsTo' + "</option>";
        searchOptions += "<option value=\"<=\">" + 'LessThanEqualsTo' + "</option>";
        var keywordHTML = "<input type=\"text\" class=\"inputTextBox\" id=\"txtSearch" + currentObjId + "\" style=\"text-transform: uppercase;\">";
        $("#tdKeyword" + currentObjId).html(keywordHTML);
        checkNumeric($("#txtSearch" + currentObjId).attr("id"));
    }
    else if (dataType.indexOf("String") >= 0) {
        searchOptions += "<option value=\"Contains`LIKE\">" + 'Contains' + "</option>";
        searchOptions += "<option value=\"Begins With`LIKE\">" + 'bew' + "</option>";
        searchOptions += "<option value=\"Ends With`LIKE\">" + 'EndsWith' + "</option>";
        searchOptions += "<option value=\"=\">" + 'Equals' + "</option>";
        var keywordHTML = "<input type=\"text\" class=\"inputTextBox\" id=\"txtSearch" + currentObjId + "\" style=\"text-transform: uppercase;\">";
        $("#tdKeyword" + currentObjId).html(keywordHTML);
        checkAlphaNumeric($("#txtSearch" + currentObjId).attr("id"));
    }
    else if (dataType.indexOf("Date") >= 0) {
        searchOptions += "<option value=\"BETWEEN\">" + 'Between' + "</option>";
        searchOptions += "<option value=\"<\">" + 'LessThan' + "</option>";
        searchOptions += "<option value=\">\">" + 'GreaterThan' + "</option>";
        var keywordHTML = "<input type=\"text\" class=\"inputTextBox\" id=\"txtSearch" + currentObjId + "\" style=\"text-transform: uppercase;\">";
        $("#tdKeyword" + currentObjId).html(keywordHTML);
        checkDate($("#txtSearch" + currentObjId).attr("id"));
    }
    else if (dataType.indexOf("Bool") >= 0) {
        searchOptions += "<option value=\"=\">" + 'Equals' + "</option>";
        var keywordHTML = "<select id=\"txtSearch" + currentObjId + "\" class=\"selectDropDownList\">";
        keywordHTML += "<option value=\"1\">" + 'True' + "</option>";
        keywordHTML += "<option value=\"0\">" + 'False' + "</option>";
        keywordHTML += "</select>";
        $("#tdKeyword" + currentObjId).html(keywordHTML);
    }
    $("#" + searchObject).html(searchOptions);
}


function validateSearch() {
    var isValid = true;
    $("#tblSearchControl tr").each(function () {
        if ($(this).attr("id") != "trHeaderSearch") {
            var currentObj = $(this).attr("id");
            var txtSearchId = $("#" + currentObj.replace("trSearch", "txtSearch")).attr("id");
            if ($("#" + txtSearchId).val() == "") {
                jAlert("Enter valid search value.", "Search List", function () { $("#" + txtSearchId).focus(); });
                isValid = false;
                return false;
            }
        }
    });
    return isValid;
}

function submitSearchFormValue() {
    $(document).data("validationGroup", "");
    var validate = validateSearch();
    if (validate) {
        var formValue = "";
        $("#tblSearchControl tr").each(function () {
            if ($(this).attr("id") != "trHeaderSearch") {
                var currentObj = $(this).attr("id");
                var operatorVal = ($("#" + currentObj.replace("trSearch", "ddlOperator")).attr("style").indexOf("none") >= 0) ? "" : $("#" + currentObj.replace("trSearch", "ddlOperator")).val();
                if (formValue == "")
                    formValue += ($("#" + currentObj.replace("trSearch", "ddlSearchField")).val().split('`'))[1];
                else
                    formValue += "^" + ($("#" + currentObj.replace("trSearch", "ddlSearchField")).val().split('`'))[1];
                formValue += "^" + $("#" + currentObj.replace("trSearch", "ddlSearchCondition")).val();
                formValue += "^" + $("#" + currentObj.replace("trSearch", "txtSearch")).val();
                formValue += "^" + operatorVal;
            }
        });
        $("#" + hdnSearchConditions).val(formValue);
        $("#" + hdnSearchControlHTML).val(getHtmlEncode($("#divSearchContent").html()));
        return true;
    }
    else {
        return false;
    }
}



function submitSearchFormValueForRate(idofControl) {
    var idofTable = "#" + idofControl + "_tblSearchControl";
    var validate = validateSearchRate(idofTable);

    if (validate) {
        var formValue = "";
        $("tr", $(idofTable)).each(function (i) {
            if (i > 0) {
                var currentObj = $(this).attr("id");
                var operatorVal = ($("#" + currentObj.replace("trSearch", "ddlOperator")).attr("style").indexOf("none") >= 0) ? "" : $("#" + currentObj.replace("trSearch", "ddlOperator")).val();
                if (formValue == "")
                    formValue += ($("#" + currentObj.replace("trSearch", "ddlSearchField")).val().split('`'))[1];
                else
                    formValue += "^" + ($("#" + currentObj.replace("trSearch", "ddlSearchField")).val().split('`'))[1];
                formValue += "^" + $("#" + currentObj.replace("trSearch", "ddlSearchCondition")).val();
                formValue += "^" + $("#" + currentObj.replace("trSearch", "txtSearch")).val();
                formValue += "^" + operatorVal;
            }
        });
        var idContainer = "#" + idofControl + "_ControlContainer";
        $("input[type='hidden'][id$='_hdnSearchConditions']", $(idContainer)).val(formValue);
        $("input[type='hidden'][id$='_hdnSearchControlHTML']", $(idContainer)).val(getHtmlEncode($("#divSearchContent", $(idContainer)).html()));
        $("#currentUserControlId").val(idContainer);
        return true;
    }
    else {
        return false;
    }
}
function submitClearSearch(idofControl) {
    return true;
}
function validateSearchRate(idofTable) {
    var isValid = true;
    $("tr", $(idofTable)).each(function (i) {
        if (i > 0) {
            var txtbox = $(this).find("input[id *='_txtSearch_']");
            if ($(txtbox).val() == "") {
                jAlert("Enter valid search value.", "Search List", function () { $(txtbox).focus(); });
                isValid = false;
                return false;
            }
        }
    });
    return isValid;

    //    $("#tblSearchControl tr", objt).each(function () {
    //        if ($(this).attr("id") != "trHeaderSearch") {
    //            var currentObj = $(this).attr("id");
    //            var txtSearchId = $("#" + currentObj.replace("trSearch", "txtSearch")).attr("id");
    //            if ($("#" + txtSearchId, objt).val() == "") {
    //                jAlert("Enter valid search value.", "Search List", function () { $("#" + txtSearchId, objt).focus(); });
    //                isValid = false;
    //                return false;
    //            }
    //        }
    //    });
    //    return isValid;
}


function checkNumeric(currentObject) {
    $("#" + currentObject).numeric();
}

function checkAlphaNumeric(currentObject) {
    $("#" + currentObject).alphanumeric({ allow: " ,;+-()&@." });
}

function checkDate(currentObject) {
    $("#" + currentObject).datepicker(
        {
            showOn: 'button',
            buttonImage: '../images/calendar.gif',
            buttonImageOnly: true,
            changeMonth: true,
            changeYear: true
        }
    );
    $("#" + currentObject).next().css({ position: 'relative', left: '2px', top: '3px', cursor: 'pointer' });
}

function checkAlpha(currentObject) {
    $("#" + currentObject).alpha({ allow: ' ' });
}



function OnAction(formAction, id, buttonId) {

    var str = formAction + '^' + id;
    __doPostBack(buttonId, str);
    //   form.submit();
}

function getHtmlEncode(t) {
    return t.toString().replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

function MutualExtender(ExtenderKey, currentObj) {
    $("span[" + ExtenderKey + "]").each(
        function () {
            var obj = $(this).find("input").attr("id");
            if (obj == currentObj)
                $("#" + obj).attr("checked", "checked");
            else
                $("#" + obj).attr("checked", "");
        }
    );
}

function closeSummery() {
    $("#divValidationControl").attr("style", "display:none;");
}
var validationGroup = '';
var buttonId;
var divValidationControl;
function IsValidateForm(validationgroup, id) {
    //alert(id);
    buttonId = id;

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_initializeRequest(onEachRequest);
    $.validator.setDefaults({
        submitHandler: function () { closeSummery(); }
    });
    validationGroup = validationgroup;
    $(document).data("validationGroup", validationGroup);
    $("#aspnetForm").validate();
    // Grab a reference to the Page Request Manager
}

var validationGroupRegister = '';
var buttonIdRegister;
var divValidationControlRegister;
function IsValidateFormRegister(validationgroup, id) {
    buttonId = id;

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_initializeRequest(onEachRequest);
    $.validator.setDefaults({
        submitHandler: function () { closeSummery(); }
    });
    validationGroup = validationgroup;
    $("#form1").validate();
    // Grab a reference to the Page Request Manager
}

//Declare delegate to store method as a object;
var onCustomValidation = null;
var onCustomValidation2 = null;
var onCustomValidation3 = null;
// Our own custom method to be attached to each new/future page request..
function onEachRequest(sender, args) {
    // Check to see if we need to Cancel this Postback based on Conditional Logic within this page..
    if ($("#aspnetForm").valid() || args.get_postBackElement().id != buttonId) {
        $("#divValidationControl").attr("style", "display:none;");
        args.set_cancel(false);
    }
    else {
        args.set_cancel(true);

    }
}

var fromDateControl = null;
var checkBlank = null;
function DateCheck(toDateControl) {
    var fromDate = new Date($('#' + fromDateControl).val());
    var toDate = '';
    if ($('#' + toDateControl).val().indexOf('yy') < 0) {
        toDate = new Date($('#' + toDateControl).val());
    }
    else
    { return true; }
    if ((checkBlank && toDate != '') || (!checkBlank)) {
        if (toDate >= fromDate)
            return true;
        else
            return false;
    }
}

onload = requiredFieldClass;
function requiredFieldClass() {
    $("input[ValdationType], textarea[ValdationType],  select[ValdationType]").each(function () {
        if ($(this).attr("ValdationType").indexOf("required") >= 0)
            $(this).attr("class", "Required");
    });
}


function TranslateScript(messageKey) {
    var e = window.parent.parent.document.getElementById("ddlCulture");
    var currentCulture;
    for (var i = 0; i < e.options.length; i++) {
        if (e.options[i].selected)
            currentCulture = e.options[i].value;
    }
    var messageVal;
    $.ajax({
        url: '../Services/GetGlobalResource.ashx',
        cache: false,
        async: false,
        data: 'key=' + messageKey + '&currentCulture=' + currentCulture,
        success: function (data) {
            messageVal = data;
        }
    });
    return messageVal;
}

//Check for duplicate records
function CheckDuplicate(entityName, checkFieldName, checkValueId) {
    checkValue = $("#" + checkValueId).val();
    $.ajax({
        url: "../Services/CheckDuplicate.ashx?EntityName=" + entityName + "&CheckFieldName=" + checkFieldName + "&CheckValue=" + checkValue,
        cache: false,
        dataType: "text",
        success: function (data) {
            if (data != null) {
                if (data == "1") {
                    jAlert("Already exists.");
                    $("#" + checkValueId).val('');
                }
            }
        }
    });
}
