/*****************************************************
 * EOS.WebControls.js Copyright (C) CHAOS 2007
 *****************************************************/

/* declare const. */
var UPLOAD_PICTURE_WEBFORM = "../../CommonPages/EOS.Web.UploadPic.aspx?PATH=";
var UPLOAD_FILE_WEBFORM = "../../CommonPages/EOS.Web.UploadFile.aspx?PATH=";
var SELECT_CODE_WEBFORM = "../../CommonPages/EOS.Web.Code.htm?PATH=";
var SELECT_CODES_WEBFORM = "../../CommonPages/EOS.Web.Codes.aspx?PATH=";
var SELECT_DATA_WEBFORM = "../../CommonPages/EOS.Web.Select.htm?PATH=";
var SELECT_OFFICE_FILE = "../../CommonPages/EOS.Web.OfficeFile.aspx";
var URL_PARAMETER_PK_OF_DATABASE = "PK";
var URL_PARAMETER_PARENTID_OF_TREE = "ParID";

function DoOver(e){
    e.bgColor = '#E8E6FF';
}

function DoOut(e){
    var ch = e.getElementsByTagName("INPUT");
    if (ch.length > 0 && ch[0].type == "checkbox" && ch[0].checked) e.bgColor = "#E4FFFF";
    else e.bgColor = '#FFFFFF';
}

/* 000: Show user-department dialog to select user-dialog. */
function ctlShowUserDialog(id, jsFunction, value){
    var hid_value = document.getElementById(id + "_hid").value;
    if (hid_value == "") hid_value = "|";
    hid_value = hid_value + "|" + document.getElementById(id).value;
    var url = "../../CommonPages/EOS.Web.SelectUser.aspx?DepartmentUser=" + hid_value;
    var res = pageShowDialog(url, 550, 490);
    
    if (res != null && res != "") {
        var vals = res.split("|");        
        document.getElementById(id).value = vals[2];
        document.getElementById(id + "_hid").value = vals[0] + "|" + vals[1];
        
        if(jsFunction && jsFunction != "") {
            eval(jsFunction + "('" + vals[2] + "','" + vals[0] + "|" + vals[1] + "');");
        }
    }
}
 
/* 001: Show code dialog to select code/value. */
function ctlShowCodeDialog(id, code, path, field, func, par, where, multi, orderby, tree){
    var partern = /\{\w{1,}\}/g;
	var res = where.match(partern);
	if (res != null){
	    for (var i = 0; i < res.length; i++){
	        var pid = res[i].substr(1, res[i].length-2);
	        var hid = id.id.substr(0, id.id.lastIndexOf('_') + 1) + pid;
	        var val = document.getElementById(hid);	    
	        if (val == null){ alert('条件ID配置错误！'); return; }
	        else if (val.value == '') { alert('请选择父级字段！'); return; }
	        else { where = where.replace(res[i], val.value); }
	    }
	}
	
    var url;
    if (!tree) url = SELECT_CODE_WEBFORM + path + "&F=" + field + "&CODE=" + code + "&PARID=" + par+"&Where=" + where+"&Orderby=" + orderby;
    else url = "../../CommonPages/EOS.Web.Tree.aspx?PATH=" + path + "&CODE=" + code + "&Where" + where + "&Orderby=" + orderby;
    if (multi){
        var multiVal = document.getElementById(id.id + '_hid').value;
        url = SELECT_CODES_WEBFORM + path + "&F=" + field + "&CODE=" + code + "&VAL=" + multiVal;
    }
    var res = pageShowDialog(url, 550, 490);
    
    if (res != null && res != ""){
        var vals = res.split("|");
        
        if (vals.length > 2){
            document.getElementById(id.id + "_ext").value = vals[2];
        }
        
        id.value = vals[1];
        document.getElementById(id.id + "_hid").value = vals[0];
        
        // clear sub text box's text.
        clearSubBox(id);
        
        if (typeof func != "undefined" && func != null && func != ""){
            eval(func + "(vals);");
        }
    }
}

/* Clear sub children box's value. */
function clearSubBox(TextId){							
	var subIndex = TextId.id.indexOf('_P');
	var objSub = null, objSubHid = null;
	if (subIndex > -1){
		objSub = document.getElementById(TextId.id.substr(0, subIndex));
		objSubHid = document.getElementById(TextId.id.substr(0, subIndex) + '_hid');
		if (objSub != null)
		{
			objSub.value = '';
			objSubHid.value = '';									
		}
	}
}

/* 002: AjaxGrid client call server events. */
function ctlAjaxGrid(objId, command, val){
    var v = val == null ? null : ('I:'+val);
    if (typeof sender == "undefined" || sender == null) sender = "";
    ajaxCallback(objId, command, v, null);
}

/* 002: AjaxGrid client call export excel events. */
function ctlAjaxGridExcel(objId){
    ajaxCallback(objId, "TestExportExcel", null, ctlAjaxGridExcel_callback, objId);
}

function ctlAjaxGridExcel_callback(rv){
    if (rv.value.split(':')[0] == '0') alert('导出Excel出错：' +rv.value.split(':')[1]);
    else {
        var url = "../../CommonPages/EOS.Web.Download.aspx?DID=" + rv.value.split(':')[1];
        document.getElementById("frm_" + rv.value.split(':')[2]).src = url;
    }
}

/* 003: Show upload picture box. */
function ctlShowPicDialog(hid, img, path){
    var url = UPLOAD_PICTURE_WEBFORM + path + "&PK=" + hid.value;
    var res = pageShowDialog(url, 100, 100);
    if (res != null && res != ""){
         hid.value = res.split(eos_SplitChar)[0];
         img.src = "../../" + res.split(eos_SplitChar)[1];
    }  
}

/* Show upload file box. */
function ctlShowFileDialog(hid, href, path){
    var url = UPLOAD_FILE_WEBFORM + path + "&PK=" + hid.value;
    var res = pageShowDialog(url, 100, 100);
   
    if (res != null && res != ""){
         hid.value = res.split(eos_SplitChar)[0];
         href.innerText = res.split(eos_SplitChar)[1];
         href.title = res.split(eos_SplitChar)[1];
         href.href = "../../" + res.split(eos_SplitChar)[2]; 
         href.target = "_blank";
    }  
}

/* 004: View save client action. */
function ctlViewSave(objId, command, callback){
    if (typeof callback == "undefined" || callback == null){
        ajaxCallback(objId, command, null, ctlViewSave_callback);
    }
    else{
        ajaxCallback(objId, command, null, callback);
    }
}

/* View save client action call back. */
function ctlViewSave_callback(rv){
    if (rv.value.split(':')[0] == "0"){
        alert("保存出错！" + rv.value.split(':')[1]);
    }
    else{
        alert("保存成功！");        
        window.returnValue = 1;
        
        if (rv.value.split(':').length > 2){
            window.close();
        }
    }
}

/* 005: Tree client add action. */
function ctlTreeAdd(obj, objId, url, deptid){
    if (typeof deptid == "undefined" || deptid == null) deptid = "";
    if (obj.SelectedNode == null){
        alert("选择某一节点做为父节点进行[添加]操作！");
    }
    else{
        if(deptid != obj.SelectedNode.Value.substr(0,deptid.length) && deptid != ""){
            alert("选择本机构的节点做为父节点进行[添加]操作！");
        }
        else
        {
            url += URL_PARAMETER_PK_OF_DATABASE + "=&" + URL_PARAMETER_PARENTID_OF_TREE + "=" + obj.SelectedNode.Value;
            var res = pageShowDialog(url, 100, 100);
            if (res == "1"){
                pageRefresh();
            }
        }
    }
}

/* 006: Tree client edit action. */
function ctlTreeEdit(obj, objId, url){
    if (obj.SelectedNode == null){
        alert("选择某一节点方可进行[编辑]操作！");
    }
    else if (obj.SelectedNode.Parent != null){
        url += URL_PARAMETER_PK_OF_DATABASE + "=" + obj.SelectedNode.Value + "&" + URL_PARAMETER_PARENTID_OF_TREE + "=" + obj.SelectedNode.Parent.Value;
        var res = pageShowDialog(url, 100, 100);
        if (res == "1"){
            pageRefresh();
        }
    }
    else{
        alert('根节点不能进行[编辑]操作！');
    }
}

/* 007: Tree client delete action. */
function ctlTreeDelete(obj, objId, cls){
    var p = null;
    if (obj.SelectedNode == null){
        alert("选择某一底层节点方可进行[删除]操作！");
    }
    else{
        if (obj.SelectedNode.Nodes.length > 0){
            alert("存在子节点，禁止进行[删除]操作！");
        }
        else{
            if (typeof cls == "underfined" || cls == null) cls = "";
            if (cls != "") { cls += "."; p = "S:"+obj.SelectedNode.Value; }
            if (confirm("确定要删除数据？")){
                ajaxCallback(objId, cls+"Delete", p, ctlTreeDelete_callback);
            }
        }
    }
}

/* Tree client delete action call back. */
function ctlTreeDelete_callback(rv){
    if (rv.value.split(':')[0] == "1"){
        pageRefresh();
    }
    else{
        alert(rv.value.split(':')[1]);
    }
}

/* 008: Common Add/Edit action. */
function ctlAddOrEdit(objId, url, intw, inth){
    if (typeof intw == "underfined" || intw == null) intw = 100;
    if (typeof inth == "underfined" || inth == null) inth = 100;
    var fk = window.location.toString().getQuery("FK");
    if (fk != null) {
        if (url.indexOf("?") > 0) url += "&FK=" + fk;
        else url += "?FK=" + fk;
    }
    var res = pageShowDialog(url, intw, inth);
    if (res == "1"){
        ctlAjaxGrid(objId, "BindData", null, null);
    }
}

/* 009: Grid checkbox/radiobox action. */
function ctlAjaxGridCheckItem(e, objId){
    // set checked row color.
    e.parentElement.parentElement.bgColor = e.checked ? "#e4ffff" : "";
    
    // check if all checked.
    var allCheckBox = document.getElementById(objId+"_all");
    if (!e.checked) allCheckBox.checked = false;
    else{
        var items = document.getElementsByName(objId+"_item");
        for (var i=0; i<items.length; i++){
            if (!items[i].checked) return;
        }
        allCheckBox.checked = true;
    }
}

/* 010: Grid check all action. */
function ctlAjaxGridCheckAll(e, objId){
    var items = document.getElementsByName(objId+"_item");
	for (var i=0; i<items.length; i++){
		items[i].parentElement.parentElement.bgColor = e.checked ? "#e4ffff" : "";
		items[i].checked = e.checked;
	}
}

function ctlAjaxGridEC(img, rowId, show){
    if (typeof show == "underfined" || show == null){
        if (img.src.indexOf("+.gif") > 0){
            img.src = "../../images/-.gif";
            show = true;
        }
        else if (img.src.indexOf("-.gif") > 0){
            img.src = "../../images/+.gif";
            show = false;
        }
    }
    else if (img.src.indexOf("..gif") < 0){
        if (show) img.src = "../../images/-.gif";
        else img.src = "../../images/+.gif";
    }
    var end = parseInt(img.alt);
    for (var i = 0; i < end; i++){
        var tr = document.getElementById(rowId+"."+i);
        tr.style.display = show ? "": "none";
        if (!show && tr.getElementsByTagName("IMG").length > 0){
            ctlAjaxGridEC(tr.getElementsByTagName("IMG")[0], tr.id, show);
        }
    }
}

function ctlAjaxGridGetTreeSelected(objId, count){
    if (typeof count == "underfined" || count == null) count = eval(objId+'_count');
    var rv = '';
    for (var i=0; i<count; i++){
        var tr = document.getElementById(objId+'.'+i);
        var childCount = parseInt(tr.getElementsByTagName("img")[0].alt);
        var chk = tr.getElementsByTagName("input")[0];
        if (chk.checked || objId.indexOf('.')>0){
            var childRv = ctlAjaxGridGetTreeSelected(objId+'.'+i, childCount);
            if (childRv != '') rv += ',' + childRv + ',' + chk.value;
            else rv += ',' + chk.value;
        }
    }
    return rv == '' ? rv : rv.substr(1);
}

/* 011: Grid get selected action. */
function ctlAjaxGridGetSelected(objId){
    var items = document.getElementsByName(objId+"_item");
    var result = "";
    for (var i=0; i<items.length; i++){
		if (items[i].checked){
			if (result != ""){
				result += "," + items[i].value;
			}
			else{
			    result = items[i].value;
			}
		}
	}
	return result;
}

/* 012: EosSearch control action. */
function ctlSearch(objId){
    ajaxCallback(objId, "Search", null);
}

/* 012: EosSearch control action. */
function ctlReset(objId){
    ajaxCallback(objId, "Reset", null);
}

/* 013: Grid delete action. */
function ctlAjaxGridDel(objId, cls, ids){
    if (typeof ids == "undefined" || ids == null || ids == ""){
        ids = ctlAjaxGridGetSelected(objId);
    }
    if (ids == "") {
        alert("请选中项后进行批量操作！");
        return;
    }
    if (typeof cls == "underfined" || cls == null) cls = "";
    if (cls != "") cls += ".";
    if (confirm("确定要删除数据？")){
        ajaxCallback(objId, cls+"Delete", "S:" + ids, ctlAjaxGridDel_callbak);
    }
}

function ctlAjaxGridDel_callbak(rv){
    if (rv.value.split(':')[0] == "1"){
        if(typeof rv.value.split(':')[1] != "undefined" && rv.value.split(':')[1] != null)
            alert("操作成功！\n" + rv.value.split(':')[1]);
        else
            alert("操作成功！");
    }
    else{
        alert(rv.value.split(':')[1]);
    }
}

/* 014: Logout action. */
function ctlLogout(objId){
    ajaxCallback(objId, "Logout", null, ctlLogout_callback);
}

function ctlLogout_callback(rv){
    if (rv.value == null || (rv.value != null && rv.value.split(':')[0] == "1")){
        if (window.parent != null) window.parent.location = "../../default.htm"; 
        else window.location = "../../default.htm"; 
    }
}

/* 015a: Select action. */
function ctlSingleSelectUser(objId, path, t, f, pk, where, url, show){
    if (typeof show == "undefined" || show == null) show = "0";
    if (typeof url == "undefined" || url == null || url == ""){
        url = SELECT_DATA_WEBFORM;
    }
    url = url + path + "&T=" + t + "&F=" + f + "&PK=" + pk + "&Where=" + where + "&ShowDept=" + show + "&RadioSelect=1";

    var res = pageShowDialog(url, 500, 400);
    if (res != null && res != ""){
        document.getElementById(objId).value = res.split('|')[0];
        document.getElementById(objId + "_hid").value = res.split('|')[1];
    }
}

/* 015: Select action. */
function ctlSelect(objId, path, t, f, pk, targetObj, where, url, show){
    if (typeof show == "undefined" || show == null) show = "0";
    if (typeof url == "undefined" || url == null || url == ""){
        url = SELECT_DATA_WEBFORM;
    }
    url = url + path + "&T=" + t + "&F=" + f + "&PK=" + pk + "&Where=" + where + "&ShowDept=" + show;
    var res = pageShowDialog(url, 500, 400);
    if (res != null && res != ""){
        ajaxCallback(objId, "Execute", "S:" + res, ctlSelect_callback, targetObj);
    }
}

function ctlSelect_callback(rv){
    if(rv.value.split(':')[0] == "1" && rv.value.split(':')[1] != ""){
        ajaxCallback(rv.value.split(':')[1], "BindData", null);
    }
}

/* 016: Call server methods. */
function ctlExec(gridObjId, objId, ids){
    if (typeof ids == "undefined" || ids == null || ids == ""){
        if (gridObjId == null || gridObjId == "") ids = 'NONE';
        else ids = ctlAjaxGridGetSelected(gridObjId);
    }
    if (ids == "") {
        alert("请选中项后进行批量操作！");
        return;
    }
    ajaxCallback(objId, 'Execute', 'S:'+ids, ctlExec_callback, gridObjId);
}

function ctlExec_callback(rv){
    if (rv.value.split(':')[0] == '1'){
        alert('操作成功！');
        ctlAjaxGrid(rv.value.split(':')[1], "BindData", null, null);
    }
    else{
        alert('操作失败！' + rv.value.split(':')[1]);
    }
}

/* 00X Tab control click action. */
function Tabclick_event(objId){
    var tablecells = objId.parentNode.cells;
    var test = /_TabHeader_/g; 

    for (var i = 0; i < tablecells.length - 1; i++){
        if(tablecells[i] != objId){
            tablecells[i].className = "TabNotClick";	
	        document.getElementById(tablecells[i].id.replace(test, "_TabContent_")).style.display = "none";
        }
    }

    objId.className = "TabClick";
    document.getElementById(objId.id.replace(test,"_TabContent_")).style.display = "";
}

/* 00Y: View save client action. */
function ctlViewSaveDynamic(objId, command, prams, callback){
    if (typeof callback == "undefined" || callback == null){
        ajaxCallback(objId, command, prams, ctlViewSave_callback);
    }
    else{
        ajaxCallback(objId, command, prams, callback);
    }
}

/* 00Z: Batch file client action. */
function ctlShowBatchFileDialog(hidname, hrefname, divname, num, path){
    ctlNewFile(hidname, hrefname, divname, num, path, '');
}

function ctlNewFile(hidname, hrefname, divname, num, path, TemplateName){
    var hid, href, div, editbtn, url;
    for (var i = 1; i <= num; i++){
        hid = document.getElementById(hidname+i);
        if (hid.value == ""){
            href = document.getElementById(hrefname+i);
            div = document.getElementById(divname+i);
	        editbtn = document.getElementById(hidname.replace(/_hid/g,"_editbtn")+i);
            break;
        }
        else { hid = null; }
    }

    if (hid == null){ alert("最多只能上传"+num+"个文件"); }
    else {
        if (TemplateName != '') url = "../../CommonPages/EOS.Web.Office.aspx?TEMPLATENAME="+TemplateName+"&PATH="+path;
        else url = UPLOAD_FILE_WEBFORM + path + "&PK=" + hid.value;
        var res = pageShowDialog(url, 300, 150);
    	if (!(typeof res == "undefined" || res == null || res == "")){
            var fileinfo = res.split(eos_SplitChar);
            var pk,filename,suffix;
            if (TemplateName != ''){
                pk = fileinfo[2];
                filename = fileinfo[0];
                url = "../../" +fileinfo[3];
                suffix = fileinfo[1];
            }
            else{
                pk = fileinfo[0];
                filename = fileinfo[1].split('.')[0];
                url = "../../" + fileinfo[2]; 
                suffix = fileinfo[2].substring(fileinfo[2].lastIndexOf(".")+1);
            }   	    
	        var v = document.getElementById(hidname.replace(/_hid/g,"_hValue"));
	        if (!(typeof v == "undefined" || v == null)) {
		        if (typeof v.value == "undefined" || v.value == null || v.value == "") v.value = pk;
		        else v.value=v.value+","+pk;
	        }
		
	        if (!(typeof editbtn == "undefined" || editbtn == null)){		    
	            editbtn.onclick=function() {window.open(SELECT_OFFICE_FILE+'?FILEID='+pk+'&PATH='+path+'&TYPE='+suffix);}
	        }
	        
            hid.value = pk;
            href.innerText = filename+"."+suffix;
            href.title = filename+"."+suffix;
            href.href = url; 
            href.target = "_blank";
            div.style.display="";

            if (TemplateName != '') {
                url = SELECT_OFFICE_FILE+"?FILEID="+pk+"&PATH="+path+"&FILENAME="+filename+"&TYPE="+suffix;
                window.open(url, "", "toolbar=no,status=no,resizable=yes");
            }
            else if(suffix.toLocaleLowerCase()!="doc" && suffix.toLocaleLowerCase()!="xls"){
		        if(!(typeof editbtn=="undefined" || editbtn==null)) editbtn.style.display="none";
	        }   
        }
	}
}

function ctlEditFile(FILEID, PATH, TYPE,ISREVISIONS,USER){
    var url = SELECT_OFFICE_FILE+'?FILEID='+FILEID+'&PATH='+PATH+'&TYPE='+TYPE+'&ISREVISIONS='+ISREVISIONS+'&USER='+USER;
    window.open(url,"","toolbar=no,status=no,resizable=yes");
}

function ctlDeleteBatchFile(objid, hidname, hrefname, divname, index, num){
    var parms = document.getElementById(hidname+index).value;
    if (index != num){
        for (var i = index; i < num; i++){
            document.getElementById(hidname+i).value = document.getElementById(hidname+(i+1)).value;
            document.getElementById(hrefname+i).innerText = document.getElementById(hrefname+(i+1)).innerText;
            document.getElementById(hrefname+i).title = document.getElementById(hrefname+(i+1)).title;
            document.getElementById(hrefname+i).href = document.getElementById(hrefname+(i+1)).href;
            document.getElementById(hrefname+i).target = document.getElementById(hrefname+(i+1)).target;
            document.getElementById(divname+i).style.display = document.getElementById(divname+(i+1)).style.display;
            
            var editbtn = hidname.replace(/_hid/g,"_editbtn");
	        if (!(typeof document.getElementById(editbtn+i) == "undefined" || document.getElementById(editbtn+i) == null)){
	            document.getElementById(editbtn+i).href=document.getElementById(editbtn+(i+1)).href;
	        }            
        }
    }
    
    document.getElementById(hidname+num).value = "";
    document.getElementById(hrefname+num).innerText = "";
    document.getElementById(divname+num).style.display = "none";    
	var v = document.getElementById(hidname.replace(/_hid/g,"_hValue"));
	if(!(typeof v == "undefined" || v == null)){
		v.value = (","+v.value).replace(","+parms, "").substring(1,v.value.length);
	}
    ajaxCallback(objid, "BatchFile", "S:Delete;S:"+parms, null);
}
