﻿function editModeConstants() {
    this.adding = "A";
    this.copying = "C";
    this.editing = "E";
    this.deleting = "D";
    this.viewing = "V";
    this.searching = "S";
    this.picking = "P";
    this.other = "O";
    this.exportToCsv = "EX_CSV";
    this.exportToPdf = "EX_PDF";
    this.queryStringAdding = "E_MODE=A";
    this.queryStringCopying = "E_MODE=C";
    this.queryStringEditing = "E_MODE=E";
    this.queryStringDeleting = "E_MODE=D";
    this.queryStringViewing = "E_MODE=V";
    this.queryStringSearching = "E_MODE=S";
    this.queryStringPicking = "E_MODE=P";
    this.queryStringOther = "E_MODE=O";
    this.queryStringExportCsv = "E_MODE=EX_CSV";
    this.queryStringExportPdf = "E_MODE=EX_PDF";
    
    this.getQueryString = function(mode) {
        if (mode == "A") {
            return "E_MODE=A";
        }
        else if (mode == "C") {
            return "E_MODE=C";
        }
        else if (mode == "E") {
            return "E_MODE=E";
        }
        else if (mode == "D") {
            return "E_MODE=D";
        }
        else if (mode == "V") {
            return "E_MODE=V";
        }
        else if (mode == "S") {
            return "E_MODE=S";
        }
        else if (mode == "P") {
            return "E_MODE=P";
        }
        else if (mode == "O") {
            return "E_MODE=O";
        }
        else if (mode == "EX_CSV") {
            return "E_MODE=EX_CSV";
        }
        else if (mode == "EX_PDF") {
            return "E_MODE=EX_PDF";
        }
    }
}
var editMode = new editModeConstants();

function RecordUpdateStatus() {
    this.ERROR_OCCURED = "EC";
    this.NONE = "N";
    this.RECORD_UPDATED = "RU";
    this.RECORD_DELETED = "RD";
    this.CANCELLED = "CL";
    this.ADDED_THEN_CANCELLED = "ACL";
}
var rUpdateStatus = new RecordUpdateStatus();

function AppConstants() {
    this.defaultModalDialogFeatures = "center:yes; resizable:no; scroll:no; status:no; ";
    this.PK_QS_ID = "PKID";
    this.MID_QS_ID = "MID";
    this.SessionDataTable_QS_ID = "SDTID";
    this.PageBaseSessionKey_QS_ID = "PBSKID";
}
var gConst = new AppConstants();

function LaunchFromConstants() {
    this.LaunchFromKey = "LAUNCH_FROM";
    this.MemberZone = "MEMBER_ZONE";
    this.AdminZone = "ADMIN_ZONE";
    this.GuestZone = "GUEST_ZONE";

    this.QS_MemberZone = "LAUNCH_FROM=MEMBER_ZONE";
    this.QS_AdminZone = "LAUNCH_FROM=ADMIN_ZONE";
    this.QS_GuestZone = "LAUNCH_FROM=GUEST_ZONE";
}
var launchFromConst = new LaunchFromConstants();

function selectRGRowOnRowClick(sender, eventArgs) {
    var dataItem = sender.get_masterTableView().get_dataItems()[eventArgs.get_itemIndexHierarchical()];
    sender.get_masterTableView().selectItem(dataItem.get_element(), true);
}

// RadGrid Context Menu
function showRowContextMenu(sender, eventArgs, mnu) {
    try{
        var evt = eventArgs.get_domEvent();
        if (evt.target.tagName == "INPUT" || evt.target.tagName == "A") {
            return;
        }
        var dataItem = sender.get_masterTableView().get_dataItems()[eventArgs.get_itemIndexHierarchical()];
        sender.get_masterTableView().selectItem(dataItem.get_element(), true);
        mnu.show(evt);
        evt.cancelBubble = true;
        evt.returnValue = false;
        if (evt.stopPropagation) {
            evt.stopPropagation();
            evt.preventDefault();
        }
    }
    catch (e)
    {
    }
}

function getSelectedRGCellValue(grid, colName) {
    try {
        var masterTable = grid.get_masterTableView();
        var rows = masterTable.get_selectedItems();
        if (rows == null || rows <= 0) return "-1";
        var cell = masterTable.getCellByColumnUniqueName(rows[0], colName);
        return cell.innerHTML;
    }
    catch (e) {
        return "-1";
    }
}

function getRGCellValueByItemIndex(grid, colName) {
    try {
        var masterTable = grid.get_masterTableView();
        var rows = masterTable.get_selectedItems();
        if (rows == null || rows <= 0) return "-1";
        var cell = masterTable.getCellByColumnUniqueName(rows[0], colName);
        return cell.innerHTML;
    }
    catch (e) {
        return "-1";
    }
}

function showDialog(isModal, url, parameterObj, features) {
    if (window.showModalDialog) {
        if (isModal) {
            window.showModalDialog(url, parameterObj, features);
        }
        else {
            window.showModelessDialog(url, parameterObj, features);
        }
    }
    else {
    }
}

function getRadWindow() {
    var oWindow = null;
    if (window.radWindow)
        oWindow = window.radWindow;
    else if (window.frameElement.radWindow)
        oWindow = window.frameElement.radWindow;
    return oWindow;
}

function pageObject() {
    this.recordUpdateStatus = rUpdateStatus.NONE;
    this.isOnceUpdated = false;
    this.focusObject = null;
    this.focusObjectCode = null;
    this.defaultFocusObject = null;
    this.defaultFocusObjectCode = null;
    this.ajaxManager = null;
    this.ajaxLoadingPanel = null;
    this.windowManager = null;
    this.currentWindow = null;
    this.ajaxEventName = ""; // this variable is used to distinguish different Ajax Target
    this.rowContextMenu = null;
    this.mainRG = null; // search page rad grid
    this.moduleKey = "";
    this.formEditingMode = "";
    this.primaryKeyField = "";
    this.primaryKey = "";
    this.hfGridHeight = 250;
    this.closeWindowNow = false;    // After Ajax Completion
}
// Global document Varibales
var pgObj = new pageObject();
pgObj.currentWindow = window;

function showRADDialog(isModal, url, paramObj, width, height, mode) {
    var oWnd = getRootWindow().pgObj.windowManager.open(url);

    paramObj.mode = mode;
    paramObj.recordUpdateStatus = rUpdateStatus.NONE;
    paramObj.isOnceUpdated = false;
    oWnd.argument = paramObj;
    oWnd.set_modal(isModal);
    oWnd.setSize(width, height);
    oWnd.show();
}

function setRCBContext(context, fs, vw, cr, tf, vf) {
    context["FilterString"] = fs;
    context["VW"] = vw;
    context["CR"] = cr;
    context["TF"] = tf;
    context["VF"] = vf;
}

function alertIfEmpty(ctrlID, errMsg, compareWithMember, useCliendID, focusMethod) {
    try {
        var _focusMethod;
        _focusMethod = ((focusMethod == null || focusMethod == undefined) ? "focus()" : focusMethod);
        this._control = (useCliendID) ? $find(ctrlID) : $get(ctrlID);
        if (this._control == null || eval("this._control." + compareWithMember + " == ''")) {
            alert(errMsg);
            eval("this._control." + _focusMethod);
            return true;
        }
        return false;
    }
    catch (e) {
        return true;
    }
}

function alertIfInvalid(ctrlID, errMsg, comparisionString, isCliendID, focusMethod, codeIfInvalid) {
    try {
        var _focusMethod;
        _focusMethod = ((focusMethod == null || focusMethod == undefined) ? "focus()" : focusMethod);
        this._control = (isCliendID) ? $find(ctrlID) : $get(ctrlID);
        if (this._control == null || eval(comparisionString)) {
            alert(errMsg);
            eval("this._control." + _focusMethod);
            eval(codeIfInvalid);
            return true;
        }
        return false;
    }
    catch (e) {
        return true;
    }
}

function setEntryFormRWSize(widthFromCtrlID, heightFromCtrlID) {
    var oWnd = getRadWindow();
    if (oWnd) {
        oWnd.set_height($(document.getElementById(heightFromCtrlID)).position().top + 80);
        oWnd.set_width($(document.getElementById(widthFromCtrlID)).width() + 45);
        oWnd.center();
    }
}

function adjustSearchPageLayout() {
    try {
        var grd = pgObj.mainRG;
        //var gHeight = $($get("dvMain")).height() - $($get("dvTopSection")).height() - $(grd.GridHeaderDiv).height() - 40;
        var gHeight = $($get("dvMain")).height() - $($get("dvTopSection")).height() - 15;
        var scrollArea = grd.GridDataDiv;
        if (gHeight > 120) {
            //$(scrollArea).height(gHeight);
            $(grd.get_element()).height(gHeight);
            grd.repaint();
            pgObj.hfGridHeight.value = gHeight;
        }
    }
    catch (e) {
    }
}

function doDefaultSearchPageActions(pagePath, mode, keyField, pKey, additionalQueryString) {
    var _keyField;
    var _pKey;
    var _additionalQueryString;
    try {
        _keyField = ((!keyField || keyField == undefined) ? pgObj.primaryKeyField : keyField);
        _pKey = ((!pKey || pKey == undefined) ? getSelectedRGCellValue(pgObj.mainRG, _keyField) : pKey);
        _additionalQueryString = ((!additionalQueryString || additionalQueryString == undefined) ? "" : additionalQueryString);
        
        var paramObj = new Object();
        var url = pagePath + "?" +
                    gConst.PK_QS_ID + "=" + _pKey + "&" +
                    editMode.getQueryString(mode) +
                    ((_additionalQueryString == "") ? "" : "&" + _additionalQueryString);

        paramObj.pgObj = pgObj;

        if (mode != editMode.adding && _pKey == "-1") {
            alert("No Record Selected for this operation");
            return;
        }

        if (mode == editMode.adding || mode == editMode.copying || mode == editMode.editing || mode == editMode.deleting || mode == editMode.viewing) {
            var rWnd = getRootWindow();
            showRADDialog(true, url, paramObj, ($(rWnd.document).width() - 40), ($(rWnd.document).height() - 40), mode);
            return;
        }

        if (mode == editMode.exportToCsv) {
            pgObj.ajaxManager.ajaxRequestWithTarget(pgObj.hlExportCsvUID, '');
        }
        else if (mode == editMode.exportToPdf) {
            pgObj.ajaxManager.ajaxRequestWithTarget(pgObj.hlExportPdfUID, '');
        }
    }
    catch (e) {
    }
}

function doDefaultAjaxManagerRequestStart(sender, eventArgs) {
    try {
        var target = eventArgs.get_eventTargetElement();
        var ralpStyle = pgObj.ajaxLoadingPanel.get_element().style;
        ralpStyle.position = 'absolute';
        ralpStyle.left = target.offsetLeft + target.offsetWidth + "px";
        ralpStyle.top = target.offsetTop + "px";
    }
    catch (e) {
    }
}

function rmiQuickLinks_Click(sendenr, args) {
    if (args.get_item().get_value() == "ROOT") return;
    var paramObj = new Object();
    paramObj.pgObj = pgObj;
    pageUrl = args.get_item().get_attributes().getAttribute('FullPath');
    var rWnd = getRootWindow();
    showRADDialog(true, pageUrl, paramObj, ($(rWnd.document).width() - 40), ($(rWnd.document).height() - 40), editMode.adding);
}

function callWSSynchronously(wsUrl, parameters, successFunction) {
    var _successFunction;
    var resData = new Array(2);
    try {
        if (!successFunction || successFunction == undefined) {
            _successFunction = function(response) {
                resData[0] = (typeof response.d) != 'string' ? eval('(' + response.d + ')') : response.d;
            }
        }
        else {
            _successFunction = successFunction;
        }

        resData[1] = $.ajax({ url: wsUrl, global: false, type: "POST",
            data: parameters, contentType: "application/json; charset=utf-8", dataType: "json", async: false,
            success: _successFunction
        }).responseText;
    }
    catch (e) {
        resData[0] = "";
        resData[1] = "";
    }

    return resData;
}

function quickLaunchPickerForm(sender, moduleKey, mode, primaryKey) {
    try {
        var _mode;
        var _primaryKey;

        var launchModeQS = "";
        var launchMode = "";
        var path = "";
        var parameters = "{'key':'" + moduleKey + "'}";
        var paramObj = new Object();

        paramObj.pgObj = pgObj;

        _mode = ((!mode || mode == undefined) ? pgObj.formEditingMode : mode);
        if (!primaryKey || primaryKey == undefined) {
            if (sender.controlType == "RCB") _primaryKey = sender.get_value();
        }
        else {
            _primaryKey = primaryKey;
        }

        if (_mode == editMode.adding || _mode == editMode.copying || _mode == editMode.editing || _mode == editMode.picking) {
            launchModeQS = editMode.queryStringPicking;
            launchMode = editMode.picking;
            paramObj.isRecordPickerMode = true;
            paramObj.pickByControl = sender;
            paramObj.pickedValue = "";
            paramObj.pickedText = "";
            paramObj.isPicked = false;
            path = callWSSynchronously("/WebServices/ProjectUtilsService.asmx/GetModuleItemFullPagePathByKey", parameters)[0];
        }
        else if (_mode == editMode.viewing || _mode == editMode.deleting) {
            launchModeQS = editMode.queryStringViewing;
            launchMode = editMode.viewing;
            path = callWSSynchronously("/WebServices/ProjectUtilsService.asmx/GetModuleItemFullEntryPagePathByKey", parameters)[0];
        }

        var url = path + "?" + gConst.PK_QS_ID + "=" + _primaryKey + "&" + launchModeQS;
        var rWnd = getRootWindow();
        showRADDialog(true, url, paramObj, ($(rWnd.document).width() - 40), ($(rWnd.document).height() - 40), launchMode);

    }
    catch (e) {
    }
}

function onPickerFormClosed(argObj) {
    try {
        if (!argObj.isPicked) return;
        if (argObj.pickByControl.controlType == "RCB") {
            argObj.pickByControl.set_value(argObj.pickedValue);
            argObj.pickByControl.set_text(argObj.pickedText);
        }
    }
    catch (e) {
    }
}

function onPickerFormRowClick(textField) {
    var _textField;
    try {
        _textField = ((!textField || textField == undefined) ? "vName" : textField);
        if (pgObj.formEditingMode != editMode.picking) return;
        var text = getSelectedRGCellValue(pgObj.mainRG, _textField);
        var keyValue = getSelectedRGCellValue(pgObj.mainRG, pgObj.primaryKeyField);
        var oWnd = getRadWindow();
        argObj = oWnd.argument;
        argObj.pickedValue = keyValue;
        argObj.pickedText = text;
        if (argObj.pickByControl.controlType == "RCB") {
            argObj.pickByControl.set_text(text);
            argObj.pickByControl.set_value(keyValue);
            doFocusWait(argObj.pickByControl.get_inputDomElement());
        }
        argObj.isPicked = true;
        oWnd.close();
    }
    catch (e) {
    }
}

function ServiceRequest_OnError(e) {
    alert("Error from server : \n" + e);
}

function ServiceRequest_OnTimeOut(e) {
    alert("Operation timed out or Server is not responding");
}

