﻿// dependencies
// jquery-1.2.6.js

// namespace declaration 
// (TODO: namespace and methods mapping, currently namespace decl. is just for show, 
//  must be implemented later)
var yjit = {};
yjit.doc = {};
yjit.win = {};
yjit.events = {};
yjit.config = {};
yjit.keyCode = {};
yjit.config.doc = {};
yjit.config.controls = {};


// document variables
yjit.doc = {
    isModified: false       // TODO: currently controlled by gDocModified, replace all in source code with appropriate method
};

// configuration values
yjit.config.prototype = {
    debugMode: true
};

yjit.config.doc = {
    AllCaps: true
};

yjit.config.mainWindow = {
    showStatus: true
};

yjit.config.controls.buttons = {
    New:      { Type: 'New',      HasState: true,   Validate: false },
    Clear:    { Type: 'Clear',    HasState: true,   Validate: false },
    Retrieve: { Type: 'Retrieve', HasState: true,   Validate: true  },
    Search:   { Type: 'Search',   HasState: true,   Validate: true  },
    Edit:     { Type: 'Edit',     HasState: true,   Validate: true  }, 
    Save:     { Type: 'Save',     HasState: true,   Validate: true  },
    Delete:   { Type: 'Delete',   HasState: true,   Validate: true  },
    Print:    { Type: 'Print',    HasState: false,  Validate: false },
    Download: { Type: 'Download', HasState: false,  Validate: false },
    General:  { Type: 'General',  HasState: false,  Validate: false }
};

yjit.keyCode = {
    keyF1       : 112,
    keyF2       : 113,
    keyF3       : 114,
    keyF4       : 115,
    keyF5       : 116,
    keyF6       : 117,
    keyF7       : 118,
    keyF8       : 119,
    keyF9       : 120,
    keyF10      : 121,
    keyF11      : 122,
    keyF12      : 123,
    keyEsc      :  27,
    keyEnter    :  13,
    keyTab      :   9
};

var SEL_ALL_ELEMENTS = ':yjinput';
var SEL_FORM_ELEMENTS = ':yjinput:not(:grid)';

jQuery.extend(jQuery.expr[":"], {
  grid     :  function(a){return "yjwebgrid"==a.className;},
  yjinput  : function(a){return ((/input|select|textarea/i.test(a.nodeName))&&(a.type!='button'))||((/object|div/i.test(a.nodeName))&&(a.className=='yjwebgrid')&&(a.id));}
});

function $vf(selector,scope) {

    scope = scope || document;
    selector = selector || SEL_ALL_ELEMENTS;
    
    var ret;

	if ( scope.nodeType ) {
		ret = $(selector, scope);
	}
	if ( typeof scope == "string" ) {
	    ret = $("#"+scope+" "+selector);
	}

    return ret;

}

// initialize document after DOM is ready to be manipulated
$(document).ready(function() {

    // anchor for hidden elements dynamically which when added causes 
    // the rendered document to become longer, breaking the screen UI design
    window.hiddenAnchor = document.forms[0] || document.body;
    
	// bind event handlers   
	// window events
	$(window).load(function () {if(doc_def_onload) return doc_def_onload();});
//	$(window).unload(function () {if(doc_def_onunload) return doc_def_onunload();});
//	$(document).unload(function () {if(doc_def_onunload) return doc_def_onunload();});
	$(window).resize(function () {if(doc_def_onresize) return doc_def_onresize();});
    $(document)[0].oncontextmenu = function(e) { if(doc_def_oncontextmenu) return doc_def_oncontextmenu(window.event.srcElement); };
	
	// document events
	$(document).click(function () {if(doc_def_onclick) return doc_def_onclick();});
	$(document).keydown(function (e) {if(doc_def_onkeydown) return doc_def_onkeydown(e);});
	
	// help event
    window.onhelp = function() {if(win_def_onhelp) return win_def_onhelp(); };
    document.onhelp = function() {if(doc_def_onhelp) return doc_def_onhelp(); };
    
    var $HelpButton = $("#PGM_HDR_ICON");
    if ($HelpButton.length>=1) {
        $HelpButton.click(function(e) { document.onhelp(); });
    }
    
    // disable form submit event
    $("form").submit(function () { 
        var e = window.event;
        if (e.type=="keydown") {
            return false; 
        }
    });

    // focus behaviour
    $(":input:not(:radio):not(:checkbox):not(:button):not(:submit):not(select)").focus(function() {if(doc_input_onfocus) return doc_input_onfocus(this); });
    $(":input:not(:radio):not(:checkbox):not(:button):not(:submit):not(select)").blur(function() {if(doc_input_onblur) return doc_input_onblur(this); });
    
    // form controls events
    $(":input:not(:button)").keypress(function (e) {if(doc_input_onkeypress) return doc_input_onkeypress(e); });
    $(":input:not(:button)").keydown(function (e) {if(doc_input_onkeydown) return doc_input_onkeydown(e); });
    $(":input:not(:button)").change(function (e) {if(doc_input_onchange) return doc_input_onchange(e); });
    $(".Button").click(function (e) {if(doc_button_onclick) return doc_button_onclick(e, this); });
    $(".FlatButton").click(function (e) {if(doc_button_onclick) return doc_button_onclick(e, this); });
    $(".ImgButton").click(function (e) {if(doc_button_onclick) return doc_button_onclick(e, this); });
    
    // setup mask plugin and apply
    
//    var maskOptions = {   
//        attr: 'alt', // an attr to look for the mask name or the mask itself   
//        mask : null, // the mask to be used on the input   
//        type : 'fixed', // the mask of this mask   
//        defaultValue : '', // the default value for this input   
//        onInvalid : function(){}, // called when receive wrong input   
//        onValid : function(){}, // called when receive correct input   
//        onOverflow : function(){} // called when the input should receive more input   
//    };

    if ($.mask) {
        $.mask.masks.yjdate     = {mask : '9999-19-39' };
        $.mask.masks.yjtime     = {mask : '29:59' };
        $.mask.masks.yjdatetime = {mask : '9999-19-39 29:59'};
    //    $.mask.masks.yjint = { mask : '999,999,999,999', type : 'reverse', defaultValue: '0' };
    //    $.mask.masks.yjdec = { mask : '99.999,999,999,999', type : 'reverse', defaultValue: '000' };

        //$('input:text').setMask(maskOptions);
        $('.DateBox').setMask();
        $(":input[datatype='DT()']").setMask();
        $(":input[datatype='TM()']").setMask();
        $(":input[datatype='DTM()']").setMask();
    }
    
    // initialize calendars
    if ($.datepicker) {
        $(":input[datatype='DT()']").datepicker({
            showAnim: null, 
            showOn: null, 
            dateFormat: 'yy-mm-dd',
            changeFirstDay: false,
            //monthNames: ['01','02','03','04','05','06','07','08','09','10','11','12'],
            
            onSelect: function(dateText) {
                setFocus(this);
            }
        });
    }

    // setup blockUI component
    var defaultMsg = '';
    defaultMsg += '    <div style="text-align:center;border:1px solid #aaa;padding-top:3px;padding-bottom:3px;background-color: #FFFFFF;">                                                                                                                                                       '
    defaultMsg += '        <iframe style="z-index: 5000; margin: 3; padding: 3; position: absolute; width: 100%; height: 100%; top: 0; left: 0;filter: progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);" src=""></iframe>                            '
    defaultMsg += '        <img src="/App_Themes/Default/images/progress/ajax-loading2.gif">                                                                                                          '
    defaultMsg += '        <br>                                                                                                                                                                                        '
    defaultMsg += '        <br>                                                                                                                                                                                        '
    defaultMsg += '        <font style="color: #555555">잠시만 기다리세요...</font>                                                                                                                                          '
    defaultMsg += '    </div>                                                                                                                                                                                          '
    
    $.blockUI.defaults.message = defaultMsg;
    $.blockUI.defaults.css.border = 'none';
    $.blockUI.defaults.css.width = "15%";
    $.blockUI.defaults.css.left = "42%";
    $.blockUI.defaults.overlayCSS.backgroundColor = '#EEF';
    //$.blockUI.defaults.fadeOut = 'fast';

    // setup select boxes with code information to be updatable
    // TODO: need to check for circular reference (need to prevent forever refreshing)
    $("select").each(function() {
        if (!this.codeinfo)         { return true; }
        var codeinfo = eval('(' + this.codeinfo + ')');

        // if precondition specified, add current element to the refresh list of the precond control
        if (codeinfo.precond) {
            var rl;
            for (var i=0; i< codeinfo.precond.length; i++) {
                rl = $("#"+codeinfo.precond[i].toUpperCase()).data("refreshList");
                if (!rl) { rl = [this]; }
                else { rl.push(this); }
                $("#"+codeinfo.precond[i].toUpperCase()).data("refreshList", rl);
            }
        }
        
        // if optional condition specified, add current element to the refresh list of the precond control
        if (codeinfo.optcond) {
            var rl;
            for (var i=0; i< codeinfo.optcond.length; i++) {
                rl = $("#"+codeinfo.optcond[i].toUpperCase()).data("refreshList");
                if (!rl) { rl = [this]; }
                else { rl.push(this); }
                $("#"+codeinfo.optcond[i].toUpperCase()).data("refreshList", rl);
            }
        }
        
        $.extend(this, { refresh: doc_select_refresh });
    });
    
    // additional style manipulation for regular asp controls
    $(".RadioButton > :input[type=radio]").attr("class","RadioButton");
    $(".SearchPanel label").attr("class","SearchLabel");
    $(".SearchPanel .Label").attr("class","SearchLabel");
    
    // fix button width
    $(".Button").each( function() {
        if (this.offsetWidth < 63) {
            this.style.width = "63px";
        }
    });

});

// Event Handlers
// document level
// 
function doc_def_onload(){

    gCurState = DS_INIT;
    doc_track_events();
    
    if (this.winType) {
        if (this.winType == 'MAINWIN') {
            this.mdi.init("TabList","PanelList");
           // document.getElementById('BG_HOLDER').style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src='+themeURL+'images/main_page/main_bg.png)';
        }
    }
    
    doc_def_onresize();
    
    // refresh any combos with refresh methods assigned (i.e. with code info)
    $("select").each(function() {
        if (this.refresh) { this.refresh(); }
    });
    
    server.ready(function() {
        // execute custom onload function
        if (eval('self.onLoad')) { if (eval('onLoad()')==false) return false; }  
    });

    if(this.DefaultFocus) {
        $("#"+DefaultFocus).focus();
    }
    
//     window.setTimeout("if (eval('self.onLoad')) { if (!eval('onLoad()')) return false;}",0)  
    

    // perform this at the end
    // do auto load if there is data to auto load
//    if (gAutoLoad) {
//        if (gAutoLoadFn!=null && gAutoLoadFn!='') {
//            var oButton = document.all(gAutoLoadFn);
//            if (oButton) {
//                setTimeout('document.all("'+gAutoLoadFn+'").fireEvent("onclick");', 30); 
//            }
//        }    
//    }

    
}

function doc_def_onunload() {
    alert('unload');
}

function doc_def_onclick() {
    //TODO: bug - open different window and click back on this window
    if (top.window.menu) { top.window.menu.onblur(); }
}

function doc_def_onresize() {

    if (this.winType) {
        if (this.winType == 'MAINWIN') {
            if (!document.getElementById('BG_HOLDER')) { return; }
            if (!document.getElementById('PANELLIST')) { return; }
            if (!document.getElementById('MAIN_HEADER_AREA')) { return; }
            if (!document.getElementById('MAIN_MENU_AREA')) { return; }
            if (!document.getElementById('MAIN_TAB_AREA')) { return; }
            if (!document.getElementById('MAIN_FOOTER_AREA')) { return; }

            var BG  = document.getElementById('BG_HOLDER'),
                CW  = document.getElementById('PANELLIST'),
                HDR = document.getElementById('MAIN_HEADER_AREA'),
                MNU = document.getElementById('MAIN_MENU_AREA'),
                TAB = document.getElementById('MAIN_TAB_AREA'),
                FTR = document.getElementById('MAIN_FOOTER_AREA');
                
            var availHeight, panelHeight;
            
            availHeight = document.documentElement.clientHeight-25;
            panelHeight = availHeight - HDR.offsetHeight - MNU.offsetHeight - TAB.offsetHeight - FTR.offsetHeight;
            
            if (typeof(availHeight)=='number') {
                if (availHeight > 0) {
                    BG.style.height = availHeight;
                }
            }
            if (typeof(panelHeight)=='number') {
                if (panelHeight > 0) {
                    CW.style.height = panelHeight;
                }
            }
        } else if (this.winType=='MASTERWIN') {
            if (!document.getElementById('MP_HDR')) { return; }
            if (!document.getElementById('PGM_CONTENT_AREA')) { return; }
            if (!document.getElementById('MP_PGM_HDR_LEFT_PADDING')) { return; }
            if (!document.getElementById('MP_PGM_HDR_RIGHT_PADDING')) { return; }
            if (!document.getElementById('MP_PGM_HDR_ICON')) { return; }
            if (!document.getElementById('MP_PGM_HDR_BUTTONS')) { return; }
            if (!document.getElementById('MP_PGM_HDR_TITLE')) { return; }

            var HDR      = document.getElementById('MP_HDR'),
                PGM      = document.getElementById('PGM_CONTENT_AREA'),
                HDR_LP   = document.getElementById('MP_PGM_HDR_LEFT_PADDING'),
                HDR_RP   = document.getElementById('MP_PGM_HDR_RIGHT_PADDING'),
                HDR_ICON = document.getElementById('MP_PGM_HDR_ICON'),
                HDR_BTNS = document.getElementById('MP_PGM_HDR_BUTTONS'),
                PGM_TTL  = document.getElementById('MP_PGM_HDR_TITLE');
                
            var availHeight, availWidth, pgmHeight, titleWidth;
            
            availHeight = document.documentElement.clientHeight-25;
            availWidth  = document.documentElement.clientWidth;
            
            pgmHeight  = availHeight - HDR.offsetHeight;
            titleWidth = availWidth - HDR_LP.offsetWidth - HDR_LP.offsetWidth - HDR_ICON.offsetWidth - HDR_BTNS.offsetWidth;
            
            if (typeof(pgmHeight)=='number') {
                if (pgmHeight > 0) {
                    PGM.style.height = pgmHeight;
                }
            }
            if (typeof(titleWidth)=='number') {
                if (titleWidth > 0) {
                    PGM_TTL.style.width = titleWidth;
                }
            }
        } else if (this.winType == 'RPTWIN') {
            //if (!document.getElementById('RPT_COMMAND')) { return; }
            if (!document.getElementById('RPT_FRAME')) { return; }

            var RC  = document.getElementById('RPT_COMMAND'),
                RF  = document.getElementById('RPT_FRAME');                
            var availHeight, panelHeight;
            
            availHeight = document.documentElement.clientHeight-25;
            if (!RC) {
                panelHeight = availHeight;
            } else {
                panelHeight = availHeight - RC.offsetHeight;
            }
            
            if (typeof(panelHeight)=='number') {
                if (panelHeight > 0) {
                    RF.style.height = panelHeight;
                }
            }
        }
        
    } else {
        if (!document.getElementById('HDR')) { return; }
        if (!document.getElementById('PGM_CONTENT_AREA')) { return; }
        if (!document.getElementById('PGM_HDR_LEFT_PADDING')) { return; }
        if (!document.getElementById('PGM_HDR_RIGHT_PADDING')) { return; }
        if (!document.getElementById('PGM_HDR_ICON')) { return; }
        if (!document.getElementById('PGM_HDR_BUTTONS')) { return; }
        if (!document.getElementById('PGM_HDR_TITLE')) { return; }

        var HDR      = document.getElementById('HDR'),
            PGM      = document.getElementById('PGM_CONTENT_AREA'),
            HDR_LP   = document.getElementById('PGM_HDR_LEFT_PADDING'),
            HDR_RP   = document.getElementById('PGM_HDR_RIGHT_PADDING'),
            HDR_ICON = document.getElementById('PGM_HDR_ICON'),
            HDR_BTNS = document.getElementById('PGM_HDR_BUTTONS'),
            PGM_TTL  = document.getElementById('PGM_HDR_TITLE');
            
        var availHeight, availWidth, pgmHeight, titleWidth;
        
        availHeight = document.documentElement.clientHeight-25;
        availWidth  = document.documentElement.clientWidth;
        
        pgmHeight  = availHeight - HDR.offsetHeight;
        titleWidth = availWidth - HDR_LP.offsetWidth - HDR_LP.offsetWidth - HDR_ICON.offsetWidth - HDR_BTNS.offsetWidth;
        
        if (typeof(pgmHeight)=='number') {
            if (pgmHeight > 0) {
                PGM.style.height = pgmHeight;
            }
        }
        if (typeof(titleWidth)=='number') {
            if (titleWidth > 0) {
                PGM_TTL.style.width = titleWidth;
            }
        }
    }

}

// TODO: load custom help engine
function doc_def_onhelp(){
    doc_track_events();
    alert('doc help'+this.location);
    return true;
}

// cancelled window help
function win_def_onhelp(){
    doc_track_events();
    alert('win help'+this.location);
    return false;
}

function doc_def_onkeydown(e) {
    var key = e.keyCode;
    var config = yjit.config.doc;
    var oThis = window.event.srcElement;
	var isShift = e.shiftKey;
    var isCtrl = e.ctrlKey;

    doc_track_events();
//    if (key==yjit.keyCode.keyF12) {
//        toggleCommandPrompt();
//    }
    
    return true;
}

// document input elements level
// change style on focus and blur
function doc_input_onfocus(oThis){
    doc_track_events();

    $(oThis).addClass("onFocusNormal");
    oThis.lastVal = oThis.value;
    window.lastFocus = oThis.id;
    return false;
}

function doc_input_onblur(oThis){
    doc_track_events();

    var $oThis = $(oThis);
    
    $oThis.removeClass("onFocusNormal");
    $oThis.removeClass("onFocusSearch");
    $oThis.removeClass("onFocusRequired");

    oThis.lastVal = oThis.lastVal || '';
    
    if (oThis.lastVal != oThis.value) {
        if ($oThis.data('mask')) {
            $oThis.trigger('change');
        }
    }

    return true;
}

// handle when user inputs data (excluding grid)
function doc_input_onkeypress(e){
    var key = e.keyCode;
    var config = yjit.config.doc;
    var oThis = window.event.srcElement;
	var isShift = e.shiftKey;
    var isCtrl = e.ctrlKey;

    doc_track_events();

    // filter allcaps
    if (isAllCaps(oThis)==true) {
        if ((key > 0x60) && (key < 0x7B)) {
            window.event.keyCode = key-0x20;
        }
    }

}

// handle when user inputs data (keydown) (excluding grid)
function doc_input_onkeydown(e){
    var key = e.keyCode;
    var config = yjit.config.doc;
    var oThis = window.event.srcElement;
	var isShift = e.shiftKey;
    var isCtrl = e.ctrlKey;

    doc_track_events();

    if (eval('self.'+oThis.id+'_onKeyDown')) { if (!eval('self.'+oThis.id+'_onKeyDown(oThis)')) return false; }  

    if (key==13) {
        if (oThis.tagName=='TEXTAREA' && !isCtrl) {return;}
        if (oThis.tagName=='INPUT' && (oThis.type=='button' || oThis.type=='submit')) { return true; }

	    // handle default button if specified
	    if (oThis.attributes.getNamedItem("DefaultButton") != null) {
	        var btnID = oThis.attributes.getNamedItem("DefaultButton").value;
	        if(doc_input_onchange(oThis)==false) {return;}
	        if(document.all(btnID)) {
	            if(document.all(btnID).length && document.all(btnID).length > 1) {
	                alert('한 ID에 두개 이상의 버튼 존재합니다: ' + btnID);
	                return false;
	            }
	            document.all(btnID).fireEvent('onclick');
	            return false;
	        } else {
	            alert('버튼 ID가 잘못되었습니다: '+ btnID);
	        }
	    }

        mf(oThis);
        // this is to stop propagation
        // for forms with one input box, hitting enter will submit the form
        return false; 

    } else if (key==113) {
        if (oThis.codeinfo) {
            search_code(eval('('+oThis.codeinfo+')'));
        }
        if (oThis.datatype) {
            if (oThis.datatype == 'DT()') {
                yjcPickDate(oThis);
            }
        }
    }

}

// handle when data has changed
function doc_input_onchange(e){

    var config = yjit.config.doc;
    var oThis = window.event.srcElement;
	var isShift = e.shiftKey;
    var isCtrl = e.ctrlKey;

    doc_track_events();

	if (eval('self.'+oThis.name + '_onChange')) { if (eval(oThis.name + '_onChange(oThis);')==false) {return;} }

    // added 20081106: requested by TPL Project, so that user confirm message is not displayed for
    // search/retrieve even if search/retrieve conditions have been modified
    if ($(".SearchPanel #"+oThis.id).length==0) {
        gDocModified = true;
    }
    
    if (oThis.id) {
        if (yjit.config.debugMode==true) {
            setStatus('Modified: '+obj.id);
        }
    }
    
	if ((oThis.tagName.toUpperCase()=='INPUT' && oThis.type.toUpperCase()=='TEXT') || oThis.tagName.toUpperCase()=='TEXTAREA') {
        if (!defValidate(oThis)) {
            window.event.cancelBubble = true;
            return false;
        }
    }
	
	// fire the refresh method for each control in refresh list
	var rl = $("#"+oThis.id).data("refreshList");
	if (rl) {
	    for (var i=0; i<rl.length; i++) {
	        rl[i].refresh();
	    }
	}
}

// handles pre-defined buttons click events
// supports: new, clear, retrieve, search, edit, save, delete, print
// rule :
// set button ID
// when click, server function of ID+"_Form" will be called
function doc_button_onclick(e, oThis){

    if (!oThis) { oThis = window.event.srcElement; }
	var opt = {
	    ID: oThis.id,
	    Type: ''
	};
	
    doc_track_events();

	if (!oThis.id) {
	    alert('ID가 잘못되었습니다!');
	    return true;
	    
	} else {
	    opt.Type = (oThis.buttontype) ? oThis.buttontype : 'NONE';
	    opt.scope = (oThis.scope)       ? oThis.scope : '';

        // TODO: if no effect to any project need to delete the following redundant code
//        // if buttontype is not set, devs will code custom onclick function
//        if (opt.Type=='') {
//            // if devs define onclick function, it will be executed. default action will not be executed	
//            if (eval('self.'+opt.ID+'_onClick')) { 
//                return eval('self.'+opt.ID+'_onClick();'); 
//            // this part is included so that programs using the old version of AutoButton will not break
//            } else if (eval('self.'+opt.ID.toLowerCase()+'Data'))  { 
//                return eval('self.'+opt.ID.toLowerCase()+'Data();');
//            } else {
//                return true;
//            }
//        }

        if (opt.Type=='NONE') {
	        opt.HasState = false;
	        opt.Validate = false;
        } else {
	        var config = yjit.config.controls.buttons[opt.Type];
	        opt.HasState = config.HasState;
	        opt.Validate = config.Validate;
        }
        opt.UsePostBack = (oThis.UsePostBack) ? eval(oThis.UsePostBack) : false;
    }
    	
	if(!opt.ID) {return false;}
	opt.Type = (opt.Type) ? opt.Type : null;
	opt.scope = (opt.scope) ? opt.scope : null;
	opt.HasState = (opt.HasState) ? true : false;
	opt.Validate = (opt.Validate) ? true : false;

    // if devs define onbeforeclick function, it will be executed. return false to cancel further action	
    if (eval('self.'+opt.ID+'_onBeforeClick')) { if (eval('self.'+opt.ID+'_onBeforeClick()')==false) return false; }  

    // if devs define onclick function, it will be executed. default action will not be executed	
    if (eval('self.'+opt.ID+'_onClick'))       { return eval('self.'+opt.ID+'_onClick();'); }
    // this part is included so that programs using the old version of AutoButton will not break
    else if (eval('self.'+opt.ID.toLowerCase()+'Data'))  { return eval('self.'+opt.ID.toLowerCase()+'Data();'); }

	switch (opt.Type.toUpperCase()) {
	
		case "CLEAR":
			if(opt.HasState==true) {
				if (!IsValidStateFor(opt.Type)) {
					return false;
				} 
			}
            clearFormFor(opt.scope);
            setReadOnly(null,opt.scope);
            gDocModified=false;
	        SetPostState(opt.Type);
		    break;

		case "NEW":
		case "RETRIEVE":
		case "SEARCH":
		case "EDIT":
		case "SAVE":
		case "DELETE":
		case "GENERAL":
		case "PRINT":
			if(opt.HasState==true) {
				// check if current state is valid for requested operation
				if (!IsValidStateFor(opt.Type)) {
					return false;
				} 
			}
			// for "NEW" or "RETRIEVE" operation, clear screen first
            if (opt.Type.toUpperCase()=="NEW" || opt.Type.toUpperCase()=="RETRIEVE") {
                clearFormFor(opt.Type,opt.scope); 
            }
            
			// for "NEW" operation, load default value
            if (opt.Type.toUpperCase()=="NEW") {
                loadDefaultVal(null,opt.scope);
                gDocModified=true;
            }

            // validate form
            if (opt.Validate==true){
//                  if ($("#form1").valid()==false) { return false; }
                if (!chkIsReqFor(opt.Type,opt.scope)) { return;	}
                if (!defValidateForm(opt.Type,opt.scope)) { return;	}
                if (eval('self.'+opt.ID+'_Validate')) { if (eval(opt.ID+'_Validate();')==false) return false; }
            }

            clearReadOnly(null,opt.scope);

            // add data to post to server
            var pb = new PostBox('POST_CALL');
            if(opt.scope) {
                pb.AddVForm(opt.scope);
            } else {
                pb.AddVFormAll();
            }
            if (opt.Type.toUpperCase()=="SAVE") {
                if (gUseStateNew) {
                    if (gCurState==DS_NEW) { pb.Add('INSFLAG','I'); } else { pb.Add('INSFLAG','U'); }
                } else {
                    if (gDocModified) { pb.Add('INSFLAG','I'); } else { pb.Add('INSFLAG','U'); }
                }
            }

            // specify which server function to call
            pb.AddCalls(opt.ID+'_Form');

            if(opt.HasState==true) {
            // set state so that the state can be updated correctly once returned from server
                SetPostState(opt.Type);
            }
            // call
            if (opt.UsePostBack) { __doPostBack(oThis.id,''); }
            else { pb.PostBackArgs(doc_button_onafterclick,opt); }
            break;

//		case "PRINT":
//            var pb = new PostBox("POST_CALL");

//            if(opt.scope) {
//                pb.AddVForm(opt.scope);
//            } else {
//                pb.AddVFormAll();
//            }

//            // specify which server function to call
//            pb.AddCalls(opt.ID+'_Form');

//            window.prtStr = pb.ToString();
//            var rpt = window.open("/common/reporter.aspx","_blank","width=1014,height=710,top=0,left=0,scrollbars=auto,status=no,resizable=yes,maximize=1");
//            break;

		case "DOWNLOAD":
            // add data to post to server
            var pb = new PostBox('POST_CALL');
            if(opt.scope) {
                pb.AddVForm(opt.scope);
            } else {
                pb.AddVFormAll();
            }

            // specify which server function to call
            pb.AddCalls(opt.ID+'_Form');

            // call
            if (opt.UsePostBack) { __doPostBack(oThis.id,''); }
            else { pb.Post(null,doc_button_onafterclick,opt); }
            break;
            
		default:
            if (opt.UsePostBack) { __doPostBack(oThis.id,''); }
			break;
	}
	
	return true;
	
}

function doc_button_onafterclick(rb, flags) {

	var opt = flags;
	
    doc_track_events();

	if(!opt.ID) {return false;}
	opt.Type = (opt.Type) ? opt.Type.toUpperCase() : null;
	opt.scope = (opt.scope) ? opt.scope : null;
	opt.HasState = (opt.HasState) ? true : false;
	opt.Validate = (opt.Validate) ? true : false;

	if (opt.HasState==true) {UpdatePostState();}

    if (opt.Type.toUpperCase()=="DELETE") {
        clearFormFor(opt.Type,opt.scope); 
    }


	// if devs define onafterclick function, it will be executed. return false to cancel further action	
    if (eval('self.'+opt.ID+'_onAfterClick')) { if (eval('self.'+opt.ID+'_onAfterClick(rb)')==false); return false; }  
}

function doc_select_refresh(){

    clearField(this);

    if (!this.codeinfo) { return true; }
    var codeinfo = eval('('+this.codeinfo+')');

    // cannot proceed if codeid is missing        
    if (codeinfo.codeid=='') { return true; }

    // cannot proceed if pre condition items are missing        
    if (codeinfo.precond) {
        var precond;
        for (var i=0; i< codeinfo.precond.length; i++) {
            precond = document.all(codeinfo.precond[i]);
            if (!precond) { continue; }
            if (chkFieldEmpty(precond)==true) {
                //alert(precond.title + ' is required!');
                return false;
                break;
            }
        }
    }

    var pb = new PostBox('POST_CALL');
    
    var codedata = {
        precond: [],
        optcond: []
    };
    
    for (var i=0; i<codeinfo.precond.length; i++) {
        codedata.precond[i] = document.all(codeinfo.precond[i]) ? document.all(codeinfo.precond[i]).value : '';
    }
    for (var i=0; i<codeinfo.optcond.length; i++) {
        codedata.optcond[i] = document.all(codeinfo.optcond[i]) ? document.all(codeinfo.optcond[i]).value : '';
    }
    
    if (codeinfo.codeid == 'CustomDef') {
        pb.AddCalls(codeinfo.codeid + '_List', codeinfo.dbFields, codeinfo.dbTables, codeinfo.dbWhere, codedata.precond, codedata.optcond);
    } else {        
        pb.AddCalls(codeinfo.codeid + '_List', codedata.precond, codedata.optcond);
    }

    server.q.enter("refresh",this.id+"_refresh");

    pb.PostCodeList(codeinfo,this,doc_select_refresh_return);

}

function doc_select_refresh_return(oThis,rb){

    var retArr = rb.ResultData;
    if (retArr == 'null') {return;}
    
    for (i=1;i< retArr.length;i++){
        CmbAdd(oThis, retArr[i][0], retArr[i][1]);
    }

    server.q.exit("refresh",oThis.id+"_refresh");
    
}


function doc_def_oncontextmenu(src) {

    if (!src) { return true; }
    
    if (src.contextMenu) {
        alert(src.contextMenu + ' x=' + window.event.clientX + ' y=' + window.event.clientY);
        return false;
    }
    
    if (src.parentElement) {
        return doc_def_oncontextmenu(src.parentElement);
    }

    return true;

    //check if user click on tab
    var nTop,nLeft,nTopMost,nLeftMost;
    for (var i=0;i<nTabCount;i++)
    {
        //nTop = parseInt(eTabList.rows[0].cells[i].style.top);
        nTop = parseInt(eTabList.offsetTop);
        nLeft = parseInt(eTabList.rows[0].cells[i].offsetLeft);
        nTopMost = nTop + nTabHeight;
        nLeftMost = nLeft + nTabWidth;
        if (event.clientY >= nTop && event.clientY <= nTopMost && event.clientX >=nLeft && event.clientX <=nLeftMost){
            var nPopupSelectedTab = parseInt(eTabList.rows[0].cells[i].id.substr(6));
            var arrPopup = new Array(
                ['Close Others',    'closeOtherTabs(' + nPopupSelectedTab + ')'],
                ['Close',           'closeTab(' + nPopupSelectedTab + ')'],
                ['Refresh',         'refreshTab(' + nPopupSelectedTab + ')']
            );
            showPopupMenu(arrPopup,80,70);
            return false ;  
        }
    }
    return true;    //show IE's page property page
}

var output = {};

output.write = function(str) {
    var debug = document.all("debug");

    if(debug) {
        if(!debug.lastIndex) { debug.lastIndex = 0;}
        debug.innerHTML = '[' + debug.lastIndex++ + '] ' + str + "<br>" + debug.innerHTML;
    }
};

function doc_track_events(einfo) {
    var cevent = einfo;
    var str = '';
    
    if (window.event) {
        if (window.event.srcElement) {
            if (window.event.srcElement.name) {
                str = "element: " + window.event.srcElement.name + " event: " + window.event.type;
            } else if (window.event.srcElement.id) {
                str = "element: " + window.event.srcElement.id + " event: " + window.event.type;
            } else {
                str = "element: Unknown Element event: " + window.event.type;
            }
        } else {
            str = "element: Unknown Element event: " + window.event.type;
        }
        output.write(str);
    }
    if (cevent) {
        str = "element: " + cevent.src + " event: " + cevent.type;
        output.write(str);
    }
}

function config(cfgid) {
    alert(eval('yjit.config.'+cfgid.toString()));
}

function toggleCommandPrompt() {
    var pmt = (window.top.document.all("CMD")) ? window.top.document.all("CMD") : null;
    if (pmt) {
        if (pmt.style.display=='') {
            hideCommandPrompt(); 
        } else {
            showCommandPrompt(); 
        }
    } else {
        createCommandPrompt();
    }

}

function showCommandPrompt() {

    var topDoc = window.top.document;
    var pmt = (topDoc.all("CMD")) ? topDoc.all("CMD") : createCommandPrompt() ;
    pmt.style.display = '';

}

function hideCommandPrompt() {
    var topDoc = window.top.document;
    var pmt = (topDoc.all("CMD")) ? topDoc.all("CMD") : null ;
    if (pmt) { pmt.style.display = 'none'; }
}

function createCommandPrompt() {
    var topDoc = window.top.document;
    var pmtHolder = document.createElement("<div>");
    pmtHolder.style.position = 'absolute';
    pmtHolder.style.zIndex = 30000;
    pmtHolder.style.top = "10px";
    pmtHolder.style.left = "10px";
    pmtHolder.style.display = '';
    pmtHolder.id = "CMD";

    // create dummy layers to enable display over activex
    var iFrame = document.createElement('<iframe style="scrolling: no;" marginwidth="0" marginheight="0" frameborder="0" src=""></iframe>');
    iFrame.id = 'CMDiFrame';
    iFrame.style.position = "absolute";
    iFrame.style.zIndex = -1;
    iFrame.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';
    pmtHolder.appendChild(iFrame);
    
    var pmt = document.createElement("<input type='text'>");
    pmt.style.width = "300px";
    pmtHolder.appendChild(pmt);
    
    topDoc.body.appendChild(pmtHolder);

    return pmtHolder;

}

