/**
 * this function create HttpRequests, checks to see what objects the browser
 * supports in order to create the right kind of XMLHttpRequest tyoe object to
 * return.
 *
 * @return Returns an XMLHttpRequest type object or false
 * @type Object | Boolean
 */
// Global Variables
var txtPos = null;
var file = 'rmsAjaxRequests.php';
var wait = '<span class="waitText">Updating ... </span><img src="../admin/images/pleasewait2.gif" title="Please Wait" align="right"/>';
var GRAPHICS_PATH = '../images/graphics/';
var ICON_PATH = '../images/icons/';

var plusimg = GRAPHICS_PATH + 'plus.png';
var minusimg = GRAPHICS_PATH + 'minus.png';
var waitPos = 'ajaxWait';
var bcid = 'brdCrumb';
var FCKeditorAPI = '';
// var file = '../library/php/rmsPath.php';



/**
 * This function requestData, takes the passed /pReq/ object and sends the
 * passed /pData/ to the passed /pURl/. The /pReq object calls the /pFunc/
 * function on /onreadystatechange/.
 *
 */
function poison(){
	return new Date().getTime();
}

function requestData(pUrl, pData, pMethod, divID, func) {
    var mytime = '&formAction=' + pUrl + '&ajax=1&ms=' + new Date().getTime();
    var data = pData + mytime + '&sxn='+divID;
    var result = '';
    func = isset(func) ? func : 'doNothing';
    txtPos = divID;

    // $(divID).innerHTML = 'test';
    clearMsgDiv();
    var req = new Ajax.Updater(divID, pUrl, {
        method : pMethod,
        parameters : data,
        onLoading : showWait,
        onLoaded : hideWait,
        onSuccess : function() {
            hideWait();
        },
        onComplete : function(response) {
            result = response.responseText;
            var pos = $(divID);
            if (pos) {
                pos.innerHTML = result;
                if (pos.id == 'ajaxErrors') {
                    pos.className = 'showPass';
                }
                pos.show();
            }
            resetTableSort();
            explorerTreeRefreshAll();
        }
    });
}

function doNothing(resp) {

}

function resetSession() {
    var parm = 'action=resetSession';
    requestData(file, parm, 'Post', 'ajaxErrors', 'doNothing');
}

function clearMsgDiv() {
    var flds = [ 'rmsErrors', 'ajaxErrors' ];
    for ( var e = 0; e < flds.length; e++) {
        var pos = $(flds[e]);
        if (pos) {
            pos.innerHTML = '';
            pos.hide();
        }
    }
}

function updateMyAccount(pUrl, pData, pMethod, divID) {
    if ($(divID) && $('dispeventCal')) {
        requestData(pUrl, pData, pMethod, divID);
    } else {
        document.location.href = pUrl + '?' + pData;
    }
}

function sectionUpdate(pUrl, pData, pMethod, div1, div2) {
    var mytime = '&ajax=1&amp;ms=' + new Date().getTime();
    var data = pData + mytime;
    txtPos = divID;
    // $(divID).innerHTML = 'test';

    var req = new Ajax.Updater(divID, pUrl, {
        method : pMethod,
        parameters : data,
        onLoading : function() {
            showWait();
        },
        onLoaded : function() {
            hideWait();
        },
        onSuccess : function(response) {
            var data = response.responseText.evalJSON(true);
            $(div1).innerHTML = data.rec.left;
            $(div2).innerHTML = data.rec.right;
        },
        onComplete : function() {
            resetTableSort();
        }
    });
}
function deassign(menid, parm, obj) {
    parm      = unescape(parm);
    var param = parm + '&action=deassign&ajax=1&menuID=' + menid;
    var res = requestData(file, param, 'Post', 'ajaxErrors');
    $(obj).remove();
}

function delAllCache() {
    var param = 'action=deleteCache&ajax=1&file=';
    requestData(file, param, 'Post', 'ajaxErrors');
    $('ajaxErrors').className = 'showPass';
    $('ajaxErrors').show();
}

function refreshPage(id) {
    id = isset(id) ? id : '';
    var param = 'action=refreshPage&ajax=1&file=&pageid=' + id;
    requestData(file, param, 'Post', 'ajaxErrors');
    $('ajaxErrors').className = 'showPass';
    $('ajaxErrors').show();
}

function resetTableSort() {
    var rec = $('record');
    if (rec !== null) {
        SortableTable.init('record');
    // SortableTable.load();
    }
}

function addInnerHTML(pReq) {
    $(txtPos).innerHTML = pReq.responseText;
}

function showInAlert() {
    var div = $(id);
}

/**
 * This function set the class attribute for the tag with the id id = the id of
 * the element to be given the class attr = the attribute to be set for the
 * element e.g. class val = the value of the attrubute to set
 */

function rmsSetAttrib(id, attr, val) {
    var elemt  = $(id);
    elemt.attr = val;
}

/**
 *
 *
 */
function rmsAddText(id, data) {
    var elemt = $(id);
    elemt.appendChild(document.createTextNode('data'));
}

function rmsDisp(id, data) {
    var elemt = $(id);
    elemt.innerHTML = data;
}

/**
 * This function inserts a row to a table the row spans the number of columns
 * specified a div with id more is created within the row.
 */
function rmsInRowSpan(tbl, ind, span, rId) {
    var curtbl = $(tbl).insertRow(cInd);
    var filter = 'STYLE="filter:blendTrans(duration=12)"';
    browser = navigator.appName;
    var curRow = $(rId);
    curRow.setAttribute('class', 'expand');
    curRow.innerHTML = 'happy';
/*
	 * if(browser=="Microsoft Internet Explorer"){ var cRow =
	 * curtbl.insertCell(0); cRow.colSpan = span;
	 * cRow.setAttribute('class','expand'); cRow.setAttribute('colspan',span);
	 * cRow.innerHTML = '<div id="' + rId + ' " class="expand" ' + filter +
	 * '>this text shuld not display after th ecick</div>'; } else{
	 * curtbl.innerHTML = '<td colspan="' + span + '"><div id="' + rId + '"
	 * class="expand" ' + filter + '>test ajax</div></td>'; }
	 */

}

function rmsRowDel(id, ind) {
    var row = $(id).deleteRow(ind);
}

function rmsExpand(sign, rowID, data, span) {
    data += '&ajax=1&amp;ms=' + new Date().getTime();
    var trs = $$('tr[id]');
    var hyp = $$('a[id]');
    var disp = '';
    var colspan = parseInt(span) + 2;
    var img = $('aExpand' + rowID + 'Img');
    var getMore = img.src.endsWith('plus.png') ? true : false;
    var divRow = 'rec_' + rowID;
    var rId = 'more' + rowID;

    hyp.each(function(elm) {
        if (elm.id.startsWith('aExpand')) {
            elm.value = '+';
            $(elm.id + 'Img').src = GRAPHICS_PATH + 'plus.png';
        }
    });

    trs.each(function(t) {
        if (t.id.startsWith('more')) {
            t.hide();
        }
    });

    if (getMore) {
        if ($(rId) != null) {
            $(rId).remove();
        }
        disp = '-';
        sign.value = disp;
        sign.title = 'Show less details';
        img.src = GRAPHICS_PATH + 'minus.png'; // requestData(file,data,'Post',rId);

        var req = new Ajax.Request(file, {
            method : 'Post',
            parameters : data + '&ajax=1',
            onLoading : function() {
                showWait();
            },
            onLoaded : function() {
                hideWait();
            },
            onComplete : function(response) {
                var result = response.responseText;
                var rec = $('record');
                if (rec != null) {
                    SortableTable.init('record');
                    //SortableTable.load();
                }
                var rowClass = $('rec_' + rowID).className;
                var tdClass = (rowClass == 'd0') ? 'd1' : 'd0';
                var str = '<tr id="more' + rowID + '" class="' + rowClass
                + '"><td colspan="2" id="' + tdClass
                + '">&nbsp;</td><td colspan="' + colspan
                + '" class="expand"><span>' + result
                + '</span></td></tr>';
                // alert(divRow);
                new Insertion.After(divRow, str);
            // insert(divRow,{after: str});

            }
        });

    } else {
        $(rId).hide();
        // Effect.SlideUp(rId);
        sign.title = 'View more details';
    }
}

function doSlideShow(param, divID) {
    // var file = '../library/php/rmsAjaxRequests.php';
    requestData(file, param, 'GET', divID);
    $('pbLinks').innerHTML = 'related items';
}

function rmsEdit(intxt, rowID, data) {

    // rmsExpand(intxt,rowID,data)
    var disp = '';
    // var url = '../library/php/rmsAjaxRequests.php';
    cInd = intxt.parentNode.parentNode.rowIndex + 1;
    rId = 'more' + cInd;
    txtPos = rId;

    $(rId).show();
    $(divRow).className = 'show';

    var rmsAjax = new Ajax.Request(file, {
        method : 'get',
        parameters : data + '&ajax=1',
        onComplete : addInnerHTML
    });
}

function showEdit() {

}

function showCalender() {
    var cal = $('rmsDate');
    cal.setAttribute('class', 'show');
}

function doDateUpdate(divID, dLink) {
    document.frmAdmin.divID.value = dLink;
    alert(dLink);
}

function showSubmit(sBn) {
    // $('bnAction').show();
    $('hiddenBn').value = 0;
    if (sBn.value == '') {
    // $('bnAction').hide();
    } else {
        // if($('bnAction')) $('bnAction').show();
        $('frmAdmin').submit( {
            method : 'Post'
        });
    }
}

function getHiddenTextArea(flds, frm) {
    var str = [];
	 var obj = {};
	 var fld = '';
    var cnt = 0;
    if (FCKeditorAPI != '') {
        var arr = flds.evalJSON();
        for (cnt = 0; cnt < arr.length; cnt++) {
            var val = '';
            var oEditor = FCKeditorAPI.GetInstance(arr[cnt]);
            if (oEditor != null) {
                val      = oEditor.GetData();
					 fld      = arr[cnt];
					// str[cnt] = arr[cnt] + '=' + val.escapeHTML();
					 obj[fld] = oEditor.GetData() ;//val.escapeHTML();
            }
        }
    }

	 var ins = $(frm).getInputs();
	 var ins = $$('input[type=checkbox]');
	 ins.each(function(e) {
		  if (!e.id.startsWith('int_') && !e.checked) {
				cnt++;
			 //  str[cnt] = e.name + '=0';
				obj[e.name] = 0;
		  }
	 });


   // return str.join('&');
	return obj;
}

function submitForm(name, action, page, editorFld, act) {
    clearMsgDiv();
	 var mor   ='';
    var posid = 'ajaxErrors';
    var pos = $(posid);
    var doReset = false;
    $('hiddenBn').value = 1;
    switch (action) {
        case 'View': {
            var t = $F('table');
            var g = $F('curGrp');
            var id = $('ID') ? $F('ID') : '';
            if (page == 'rmsTech.php') {
                document.location.href = "rmsTech.php?action=" + act + "&table="
                + t + "&curGrp=" + g + "&ID=" + id + "";
            } else {
                document.location.href = "rmsRecordManager.php?action=" + act
                + "&table=" + t + "&curGrp=" + g + "&ID=" + id + "";
            }
            break;
        }
		  //case 'BuildCategory':
        case 'AssignMenu':
        case 'DeassignMenu':
            $(name).submit();
            break;
        case 'AddRecord':
            doReset = true;
        default: {
				if(editorFld){
					var parm = getHiddenTextArea(editorFld, name);
				}
            //var parm = (mor == '') ? {} : mor.toQueryParams();
            parm.ajax = 1;
            parm.action = action;

            $(name).request( {
                parameters : parm,
                onLoading : function() {
                    hideBody();
                },
                onLoaded : function() {
                    showBody();
                },
                onComplete : function(responce) {
                    var data = responce.responseText.evalJSON(true);
                    var pass = parseInt(data.pass);
                    var pos = $(posid);
                    if (pass) {
                        if (isset(data.content)) {
                            for ( var i in data.content) {
                                var sxn = $(i);
                                if (sxn) {
                                    sxn.innerHTML = data.content[i];
                                }
                            }
                        }
                        pos.className = 'showPass';
                        if (doReset) {
                            $(name).reset();
                        }
                    // pos.innerHTML = data.msg;
                    } else {
                        pos.className = 'showErrors';
                    }
                    pos.innerHTML = data.msg;
                    pos.show();

                }
            });
        }
    }
}

function loginUser() {
    var login = $('rmsLogin');
    login.innerHTML = '<button>logout</button>';
}

function openSmiley() {
    w = window
    .open(
        "rmsSmileys.php",
        "smileys",
        "fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=300,height=300");
    if (!w.opener) {
        w.opener = self;
    }
}

function showAnswer(num) {
    var id     = 'faq' + num;
    var plus   = $('img_' + num);
    var toshow = 'answer_' + num;
	
	var ans  = $$('span[id ^=answer_]');
	var imgs = $$('img[id ^=img_]');
	
	ans.invoke('hide');
	imgs.each(function(e){
	   var ens = e.src;
		if(ens.endsWith('minus.png')){
			e.src = ens.replace('minus.png','plus.png');
			if(e.id == plus.id){
				Effect.SlideUp(toshow);
			}
		}else{
			if(e.id == plus.id){
				plus.src = ens.replace('plus.png','minus.png');
				Effect.SlideDown(toshow);
			}
		}
	}); 
 
}

function registerNewUser() {

}

function switchDisplay(one, two, three) {
    $(one).style.display = 'inline';
    $(two).style.display = 'none';
    $(three).style.display = 'none';
    $('Errors').innerHTML = '';
}

function submitInquiry(frmID, divID) {
    var pUrl = "rmsFormMail.php";
    var pData = $(frmID).serialize();
    var pos = $('rmsErrors');
    var comp = [ 'firstname', 'surname', 'email', 'subject', 'message', 'title' ];
    var lbl = [];
    var labels = $$('label');
    var error = false;
    clearMsgDiv();

    labels.each(function(e) {
        e.className = '';
    });

    for ( var i = 0; i < comp.length - 1; i++) {
        var val = $F(comp[i]);
        if (val.strip().empty()) {
            $('lbl_' + comp[i]).className = 'error';
            error = true;
        }
    }

    /*
	 * $(frmID).action = pUrl; $(frmID).submit();
	 */
    // requestData(file,pData,"Post",divID) ;
    // $(divID).innerHTML = pData;
    if (error == false) {
        $(frmID).request( {
            method : 'Post',
            parameters : pData + '&ajax=1&action=inquiry',
            onLoading : showWait,
            onLoaded : hideWait,
            onSuccess : function(response) {
                var data = response.responseText.evalJSON(true);
                var type = parseInt(data.type);
                if (type == 0) {
                    var pos = $('rmsErrors');
                    pos.innerHTML = data.msg;
                    pos.className = 'showErrors';
                    pos.show();
                } else if (type == 1) {
                    $(divID).innerHTML = data.msg;
                }
            }
        });
    } else {
        pos.innerHTML = 'There are errors with your form. Please complete the fields highlighted in red.';
        pos.className = 'showErrors';
        pos.show();
    }
}

function playSound(obj, filename, where) {
    if (obj) {
        $(where).innerHTML = "<embed src='"
        + filename
        + "' hidden='true' height='0px' width='0px' type='audio/mpeg' loop='true' autostart='true'> ";
    } else {
        $(where).innerHTML = '';
    }
    $('playbox').value = obj ? 1 : 0;
}

function resetForm(frmName) {
    $(frmName).submit();
}

function sendFeedBack(elm) {
    elm.form.submit();
}

function dispIconImage(path, file, use) {
    var divid = $('dispIcon');
    if (use == '1') {
        file = file + 'thumb.gif';
    }
    divid.src = path + "/" + file;
}

function switchCSSClass(id, newClass) {
    var divid = $(id);
    // divid.setAttribute('class',newClass);
    divid.className = newClass;
}

function rmsDeleteRecord(table, id, pge) {
    pge = isset(pge) ? pge : file;
    pReq = new Ajax.Updater('ajaxErrors', pge, {
        method : 'Post',
        parameters : {
            'table' : table,
            'itemID' : id,
            'action' : 'deleteRecord',
            'ajax' : 1
        },
        onComplete : function(response) {
            $('rmsErrors').innerHTML = response.responseText;
            $('rmsErrors').className = 'showPass';
            if ($('rec_' + id)) {
                $('rec_' + id).hide();
            }
        }
    });
}

function updateGrid(obj, table, fld1, val1, fld2, val2) {
    var pos = $('ajaxErrors');
    var msg = '';
    $('rmsErrors').hide();
    var val = 0;
    if ($(obj).checked) {
        val = 1;
    }

    var flds = Array();
    var vals = Array();

    flds[0] = fld1;
    flds[1] = fld2;

    vals[0] = val1;
    vals[1] = val2;

    var reg = new Ajax.Request(file, {
        method : 'Post',
        parameters : {
            'table' : table,
            'fields[]' : flds,
            'values[]' : vals,
            'action' : 'updGrid',
            'add' : val,
            'ajax' : 1
        },
        onLoading : function() {
            pos.innerHTML = wait;
            pos.className = '';
        },
        onSuccess : function(response) {
            var data = response.responseText.evalJSON();
            var pass = parseInt(data.pass);
            if (pass) {
                pos.className = 'showPass';
            } else {
                pos.className = 'showError';
            }
            pos.innerHTML = data.msg;
            pos.show();
        // pos.fade({ duration: 6.0, from: 1, to: 0 });
        }
    });
}

function toggleBox(chk, table, id, fld, mod) {
    var pos = $('ajaxErrors');
    $('rmsErrors').hide();
    var val = $F(chk);
    if (chk.type == 'checkbox') {
        val = $(chk).checked ? 1 : 0;
    }
    var reg = new Ajax.Request(file, {
        method : 'Post',
        parameters : {
            'table' : table,
            'recID' : id,
            'field' : fld,
            'action' : 'toggle',
            'value' : val,
            'ajax' : 1,
            'module' : mod
        },
        onLoading : function() {
            pos.innerHTML = wait;
            pos.className = '';
            showWait();
        },
        onLoaded : hideWait,
        onSuccess : function(response) {
            var data = response.responseText;
            pos.innerHTML = '1 . Updating record ' + id + ' in table ' + table
            + ', setting ' + fld + ' = ' + val + ' (' + data + ')';
            pos.className = 'showPass';
            pos.show();
        // pos.fade({ duration: 4.0, from: 1, to: 0 });

        }
    });
}

function showSxn(sxn, toClose) {
    var divs = document.getElementsByTagName('div');
    var i = 0;
    var id = '';
    for (i = 0; i < divs.length; i++) {
        id = divs[i].id;
        if (id.startsWith(toClose)) {
            $(id).hide();
        }
    }
    $(sxn).show();
}

function resetDisplay() {
    var divs = document.getElementsByTagName('div');
    var id = '';
    for ( var i = 0; i < divs.length; i++) {
        id = divs[i].id;
        if (id && id.startsWith('sxn')) {
            $(id).hide();
        }
    }
    for ( var k = 1; k < 5; k++) {
        var dd = $('sxn' + k);
        dd.show();
    }
}

function chooseTitle(value) {
    if (value == 'others') {
        $('seltitle').name = '';
        $('other').enable();
    } else {
        $('seltitle').name = 'title';
        $('other').disable();
    }
}

function showFrm(frm) {
    var cur = '';
    var title = '';
    var arDiv = new Array();
    arDiv = $$('div');
    $('rmsErrors').hide();

    arDiv.each(function(cur) {
        if (cur.id.startsWith('frm')) {
            cur.hide();
        }
    });
    $(frm).show();

    switch (frm) {
        case 'frmLogin':
            title = 'Existing Member - Login';
            break;
        case 'frmReg':
            title = 'New Member Registration';
            break;
        case 'frmForgot':
            title = 'Forgotten Password';
            break;
    }

    $('frmTitle').innerHTML = title;
}

function pageRecords($dir, $page, frmName) {
    $('cpage').value = $page;
    $('pgc').value = $dir;
    $(frmName).submit();
    return false;
}

function showMore(id, typ) {
    var pos = $('tag' + id);
    var arows = new Array();
    var curSign = $('sign' + id).innerHTML;
    var curVal = pos.value;
    arows = $$(typ + '[id]');
    arows.each(function(tr) {
        if (tr.id.endsWith('SEL')) {
            tr.hide();
            $('sign' + tr.id).innerHTML = '+';
            $('tag' + tr.id).value = 0;
        }
    });
    if ((curVal == '1') || (curSign == '-')) {
        $('sign' + id).innerHTML = '+';
        $('tag' + id).value = 0;
        $(id).hide();
    } else {
        $(id).show();
        $('sign' + id).innerHTML = '-';
        $('tag' + id).value = 1;
    }
}

function updateChkField(obj, table, id, fld, where) {
    var val = obj.checked ? 1 : 0;
    updateField(val, table, id, fld, where, 1);
}

function updateField(val, table, id, fld, where, force, showMsg) {
    var div = $('ajaxWait');
    showMsg = isset(showMsg) ? parseInt(showMsg) : 1;
    if (!isset(where)) {
        where = '';
    }
    force = isset(force) ? force : 0;
    $('rmsErrors').hide();
    var reg = new Ajax.Request(file, {
        method : 'Post',
        parameters : {
            'table' : table,
            'recID' : id,
            'field' : fld,
            'action' : 'toggle',
            'value' : val,
            'ajax' : 1,
            'where' : where,
            'force' : force
        },
        onLoading : showWait,
        onLoaded : hideWait,
        onSuccess : function(response) {
            var pos = $('ajaxErrors');
            var data = response.responseText.evalJSON();
            if (isset(data.showUpRes) && (parseInt(data.showUpRes) == 1)) {
                if (showMsg) {
                    var disp = val.toString().truncate(10, ' [...]');
                    var out = '1 . Updating record ' + id + ' in table '
                    + table + ', setting ' + fld + ' = ' + disp;
                    pos.innerHTML = out;
                    pos.className = 'showPass';
                    pos.show();
                }
            }
        // pos.fade({ duration: 4.0, from: 1, to: 0 });
        },
        onComplete : function() {
            resetTableSort();
        }
    });
}




function getFieldData(obj, typ) {
    typ = isset(typ) ? typ : {};
    typ = decodeURIComponent(typ);
    var parm = typ.evalJSON();
    var imgscr = $(obj).src;
    var ta = $(parm.field + 'sel');
    var more = imgscr.endsWith('plus.png') ? true : false;
    if (more) {
        // showMore(fld+'sel','span');
        ta.show();
        $(obj).src = minusimg;
        var reg = new Ajax.Request(file, {
            method : 'Post',
            parameters : parm,
            onLoading : function() {
                showWait();
            },
            onSuccess : function(response) {
                var data = response.responseText;
                ta.innerHTML = data;
                // obj.src = minusimg;
                hideWait();
            },
            onComplete : function() {
                var ancid = 'anc_' + parm.field;
					 if(parm.field == 'Content'){
						ancid = 'sxnRecRight';
						$$('div[id $= Tech]').invoke('hide');
						$('taTech').show();
					 }
                //Effect.ScrollTo(ancid);
                resetTableSort();
            }
        });
    } else {
        ta.hide();
        $(obj).src = plusimg;
    }
}

function pageNav(pag, parm, divid) {
    // var dxn = $('sortField').value;
    // direc = $('th_'+ dxn).className ;
    var posid = '';
    if($(divid)){
        posid = divid;
    }else{
        var kids  = $$('div [id]');
        kids.each(function(elm){
            if(elm.hasClassName(divid)){
                posid = elm.id;
                return;
            }
        });
    }
    var tmp   = parm.toQueryParams();
    tmp.alpha = $('hiddenAlpha') ? $F('hiddenAlpha') : '';
    var num = tmp.page;
    var cur = 'page_' + num;
    $('cpage').value = num;
    makeActive(cur, 'page_', 'li[id ^= page_]');
    requestData(pag, parm, 'Post', posid);
}

function getNextRecord(pag, parm, divID) {
    var showMore = ($('pageDet') && $('pageDet').visible()) ? 1 : 0;
    parm += '&showMore=' + showMore + '&ajax=1&ms=' + new Date().getTime();
    txtPos = divID;
    // $(divID).innerHTML = 'test';
    clearMsgDiv();
    var req = new Ajax.Updater(divID, pag, {
        method : 'Post',
        parameters : parm,
        onLoading : function() {
            showWait();
        },
        onLoaded : function() {
            hideWait();
        },
        onSuccess : function() {
            // Effect.ScrollTo('rmsContents');
            if (pag == 'rmsPageEdit.php') {
                listInit();
            }
        },
        onComplete : function(response) {
            $(divID).innerHTML = response.responseText;
            $(divID).show();
				editComp(parm);
        }
    });

// requestData(pag,parm,'Post',divid);
}

function saveOrder(str, table) {

}

function confirmDelete(id, ask, url) {
    temp = window.confirm(ask);
    if (temp) {
        window.location = url + id;
    }
}
function openWindow(link, w, h) {
    var win = "width=" + w + ",height=" + h
    + ",menubar=no,location=no,resizable=yes,scrollbars=yes";
    return window.open(link, 'newWin', win);
}

function swapField(id) {
    var tgt = 'swap' + id;
    var plus = $('plus' + id);
    var img = $('img' + id);
    var newid = $('swapNew' + id);
    if (plus.value == '+') {
        var req = new Ajax.Request(file, {
            method : 'Post',
            parameters : {
                'fld' : id,
                'action' : 'quickField',
                'Ajax' : 1
            },
            onLoading : function() {
                showWait();
            },
            onSuccess : function(response) {
                var data = response.responseText;
                new Insertion.After(tgt, data);
                $(tgt).name = '';
                hideWait();
            }
        });
        img.src = minusimg;
        plus.value = '-';
    } else {
        $(tgt).name = id;
        img.src = plusimg;
        plus.value = '+';
        if (newid) {
            newid.name = '';
            newid.hide();
        }
    }

}

function closePos(fld) {
    $('swapNew' + fld).hide();
    $('img' + fld).src = plusimg;
}

function changeCalender(m, y, tbl, div, id, f, act) {
    var param = "month=" + m + "&year=" + y + "&divID=" + div + "&action="
    + act + "&table=" + tbl + "&curid=" + id;
    requestData(f, param, 'Post', 'disp' + div);
}

function saveField(table, id, fld, typ) {
    var val = $F(fld);
    if ((val == '') && (typ == 'ta')) {
        var oEditor = FCKeditorAPI.GetInstance(fld);
        if (oEditor != null) {
            val = oEditor.GetData();
        }
    }
    updateField(val, table, id, fld);
}

function saveMultiData(fld, tab, id) {
    var val = $F(fld).join('|');
    // alert(val);
    updateField(val, tab, id, fld);

}

function listCats(id, div, tag) {
    var curSign = $('sign' + tag).innerHTML;
    if (curSign == '+') {
        var req = new Ajax.Updater(div, file, {
            method : 'Post',
            parameters : {
                'id' : id,
                'action' : 'buildCat'
            }
        });
    }
}
function toggleSwitch(img, div) {
    var obj = $(img);
    var src = obj.src;
    if (src.endsWith('plus.png')) {
        src = src.replace(/plus.png/, 'minus.png');
        Effect.SlideDown(div);
    } else {
        src = src.replace(/minus.png/, 'plus.png');
        Effect.SlideUp(div);
    }
    obj.src = src;
}

function toggleList(e) {
    var element = $(e).style;
    var plus = $(e + 'plus');
    var sign = plus.value;
    var img = $(e + 'img');
    element.display == 'none' ? element.display = 'block'
    : element.display = 'none';
    if (sign == '+') {
        img.src = GRAPHICS_PATH + 'minus.png';
        plus.value = '-';
        $(e + 'Total').hide();
    } else {
        img.src = GRAPHICS_PATH + 'plus.png';
        plus.value = '+';
        $(e + 'Total').show();
    }
}

function quickAdd(table, fld) {
    // var desc = $('desc'+fld).value;
    // var title = $('Title'+fld).value;
    var pos = $('ajaxErrors');
    var inps = $$('input[id]');
    var str = {};
    str.action = 'quickAdd';
    str.table = table;

    inps.each(function(elm) {
        if (elm.id.endsWith(fld) && (elm.name != '')) {
            str[elm.name] = elm.value;
        }
    });
    new Ajax.Request(
        file,
        {
            method : 'Post',
            parameters : str,
            onLoading : function() {
                showWait();
            },
            onSuccess : function(response) {
                var data = response.responseText.evalJSON(true);
                // var data = response.responseText;
                var pass = parseInt(data.pass);
                if (pass) {
                    pos.innerHTML = 'New record added to  table ' + table + ' succesffully';
                    $('swapNew' + fld).hide();
                    pos.className = 'showPass';
                    var opt = '<option value"' + data.newid
                    + '" selected="selected">[CR] - ' + data.prime
                    + '</option>';
                    new Insertion.Bottom(fld, opt);
                } else {
                    pos.innerHTML = data.msg;
                    pos.className = 'showErrors';
                }
                pos.show();
                hideWait();
            },
            onComplete : function() {
                resetTableSort();
            }
        });
}

function getMoreInfo(menuid, divid) {
    var pos = $(divid);
    showWait('ajaxWait');
    pos.show();
    pos.innerHTML = 'here you go: menuid = ' + menuid;

}

function hideBody() {
    var main = $('main_body');
    var ajax = $('ajax_body');
    if (main && ajax) {
        main.hide();
        ajax.show();
    }
}

function showBody() {
    var main = $('main_body');
    var ajax = $('ajax_body');
    if (main && ajax) {
        ajax.hide();
        main.show();
    }

}

function showWait() {
    var divWait = $(waitPos);
    if (divWait != null) {
        divWait.innerHTML = wait;
        divWait.show();
    }
}

function hideWait() {
    var divid = $(waitPos);
    if (divid != null) {
        divid.innerHTML = '&nbsp;';
    }
}

function isset(v) {
    return (((typeof (v) == 'undefined') || (v.length == 0)) ? false : true);
}

function updTable(pUrl, pData, pMethod, divID, table) {
    requestData(pUrl, pData, pMethod, divID);
    if (pUrl == 'rmsRecordManager.php') {
        // requestData(pUrl,'subTemplate=tpl.rmsControlPanel.htm&table='+table,'Post','cpanel');
        requestData('rmsRecordManager.php',
            'ajaxTemp=tpl.rmsControlPanel.htm&table=' + table, 'Post',
            'cpanel');
    // resetTableSort();
    } else {
        refreshPanel(table);
    }
}

function refreshPanel(table) {
    requestData(file, 'techPage=rmsTech.php&action=refreshRecs&table=' + table,
        'Post', 'recList');
}

function setTableRecords(table) {

}

function updLic(siteid) {
    var pos = $('ajaxErrors');
    var lics = $$('input[id=sitelic]');
    var add = new Array();
    var cnt = 0;
    lics.each(function(elm) {
        if (elm.checked) {
            add[cnt] = elm.value;
            cnt++;
        }
    });

    var req = new Ajax.Request(file, {
        method : 'Post',
        parameters : {
            'action' : 'updLic',
            'modid[]' : add,
            'siteid' : siteid,
            'ajax' : 1
        },
        onLoading : function() {
            showWait();
        },
        onLoaded : function() {
            hideWait();
        },
        onSuccess : function(response) {
            var res = response.responseText.evalJSON(true);
            var pass = parseInt(res.pass);
            pos.className = pass ? 'showPass' : 'showError';
            pos.innerHTML = res.msg;
            pos.show();
        // pos.fade({ duration: 4.0, from: 1, to: 0 });
        }
    });

}

function nextAlbum(parm) {
    varb = $('playbox').value;
    document.location.href = parm + varb;
}

function moreHelp(hid) {
    var pos = $$('div[id]');
    var sign = $('hlpPlus' + hid).src;
    if ($('collapse').checked) {
        pos.each(function(e) {
            if (e.id.startsWith('hCont')) {
                e.hide();
            }
        });
    }

    if (sign.endsWith('plus.png')) {
        $('hCont' + hid).show();
        $('hlpPlus' + hid).src = minusimg;
    } else {
        $('hlpPlus' + hid).src = plusimg;
        $('hCont' + hid).hide();
    }

}

function editLabel(fld, tbl, curtable) {
    var parm = 'title=' + fld + '&table=' + tbl
    + '&action=EditRecord&subAction=GetIDFrmTitle';
    if (curtable != 'admin_datadict') {
        document.location.href = 'rmsTech.php?' + parm;
    } else {
        requestData('rmsTech.php', parm, 'Post', 'sxnRecRight');
    }
}

function uploadFile(obj, fld) {
    var re_text = /\.exe|\.xml|\.php|\.js/i;
    var filename = obj.value;
    if (filename.search(re_text) != -1) {
        alert("File does not have text(txt, xml, zip) extension");
        obj.form.reset();
        return false;
    }
    clearStats();
    showWait();

    obj.form.submit();
    obj.disabled = true;
    return true;
}

function setUploadItem(obj) {
    var flds = $$('input');
    var cur = obj.selectedIndex;
    var str = obj.options[cur].innerHTML;

    $('curRec').innerHTML = str;
    $('itemid').value = cur;
    clearStats();

    if (cur == '') {
        flds.each(function(e) {
            e.disable();
        });
    } else {
        flds.each(function(e) {
            e.enable();
        });
    }
}

function clearStats() {
    var stat = $$('td[id]');
    stat.each(function(e) {
        if (e.id.startsWith('status')) {
            e.innerHTML = '';
        }
    });
}

function downloadFile(file, desc) {
    var req = new Ajax.Request('rmsUploadItems.php', {
        method : 'Post',
        parameters : {
            'fileName' : file,
            'desc' : desc,
            'todo' : 'download'
        }
    });
}

function checkAvail(table, fld, id) {
    var val = $F(id).strip();
    if (val != '') {
        var parm = 'action=checkAvail&table=' + table + '&field=' + fld
        + '&value=' + val;
        new Ajax.Autocompleter(id, 'autoComplete', file, {
            method : 'Post',
            paramName : fld,
            frequency : 0.5,
            parameters : parm,
            // indicator: waitPos,
            afterUpdateElement : floodByTitle
        });
    }
}

function floodByTitle(elm, val) {
    var table = $('curTable').innerHTML.strip();
    var fld = elm.name;
    val = elm.value;
    var parm = 'table=' + table + '&subAction=floodByTitle&hiddenBn=1&' + fld
    + '=' + val;
    requestData('rmsTech.php', parm, 'Post', 'sxnRecRight');
}

function toggleDivTitle(obj, divid, hideTitle, showTitle) {
    var pos = $(divid);
    if (pos.visible()) {
        // pos.hide();
        Effect.SlideUp(divid);
        obj.innerHTML = hideTitle;
    } else {
        // pos.show();
        Effect.SlideDown(divid);
        obj.innerHTML = showTitle;
    }
}

function resetLayout(page, tab) {
    var pageid = $F('editPage');
    var parm = 'ID=' + pageid + '&table=' + tab + '&amp;action=EditPage';
    requestData(file, 'action=resetLayout&pageid=' + pageid, 'Post',
        'ajaxErrors');
    getNextRecord(page, parm, 'sxnRecRight');
}

function searchFAQ(pag) {
    var key = $('keys').value;
    requestData(pag, 'action=search&keywords=' + key, 'Post', 'techRightCol');
}

function adminAlphaFilter(pag, parm, bet, sxn) {
    var val = $F('alphaFilter');
    $('hiddenAlpha').value = bet;
    parm += '&alpha=' + bet + '&alphaFilter=' + val;
    requestData(pag, parm, 'Post', sxn);
    makeActive('alpha-' + bet, 'alpha-', 'li');
}

function doAlphaSearch(bets, pge, table, amnt) {
    var add = $$('input[type=checkbox]');
    var resFilter = Array();

    var more = Form.serializeElements(add);
    var parm = 'alpha=' + bets + '&page=' + pge + '&table=' + table
    + '&amount=' + amnt + '&action=alphaFilter&' + more;
    requestData('rmsResource.php', parm, 'Post', 'techRightCol');
    makeActive('alpha-' + bets, 'alpha-', 'li');
}

function doSongSearch(frm) {
    clearMsgDiv();
    var keys = $F('keywords').strip();
    if (keys.empty()) {
        var errpos = $('rmsErrors');
        errpos.innerHTML = 'Please enter keywords to search';
        errpos.show();
    } else {
        $('action').value = 'songSearch';
        var parm = $(frm).serialize();
        requestData('rmsResource.php', parm, 'Post', 'techRightCol');
    }
}

function setTitle(obj, tbl, id, fld) {
    var txt = obj.options[obj.selectedIndex].text;
    var parts = txt.split('|');
    $('Title').value = parts[1];
    if (id != '') {
        updateField(parts[1], tbl, id, fld);
    }
}

function previewPage(obj) {
    var alink = $('Link').value;
    myRef = window
    .open(
        alink,
        'mywin',
        'left=20,top=20,width=800,height=800,toolbar=no,resizable=yes,location=no,directories=no,menubar=no,scrollbars=no,status=no');

    obj.value = myRef;
}

function closePage(obj) {
    obj.value.close();
}
function reqExtData(extUrl) {
    var url = '/proxy?url=' + encodeURIComponent('http://www.google.com/search?q=Prototype');
    new Ajax.Request(url,
    {
        method : 'get',
        onSuccess : function(transport) {
            var notice = $('notice');
            if (transport.responseText
                .match(/href="http:\/\/prototypejs.org/)) {
                notice.update('Yeah! You are in the Top 10!').setStyle(
                {
                    background : '#dfd'
                });
            } else {
                notice.update('Damn! You are beyond #10...').setStyle( {
                    background : '#fdd'
                });
            }
        }
    });
}

function showItem(pos) {
    var spns = $$('div');
    spns.each(function(e) {
        if (e.id.startsWith('item')) {
            e.hide();
        }
    });
    $('item_' + pos).show();
    // $('item_'+pos).enable();
    $('curItem').value = pos;
}

function listInit(layout, index) {
    var temp = $F('layoutTemplate');
    sortList('sxnContent', 'LI', 'sortul', 'sortli', 'sort_hover',
        'updSequence', temp, layout);
    sortList('sxnContent', 'DIV', 'sxnContent', 'sortdiv', '', 'updSxnSeq',
        temp, index);
// Sortable.create('sxnContent', param);
}

function initLayoutSort(temp, tab, index) {
    /*
	 * var parm = {}; parm.tag = 'DIV'; ;;parm.onUpdate = function(){};
	 * parm.ghosting = true; parm.handles = $$('movehandle'); ;;parm.handle =
	 * true; ;;parm.dropOnEmpty = true; var tops = $$('div.parSxn');
	 * tops.each(function(elm){ var str = '#'+elm.id+' DIV.elmTab';
	 * parm.elements = $$(str); parm.containment = elm.id;
	 * Sortable.create(elm.id,parm); }); //parm.only = ['elmTab','elmTab_hide'];
	 */

 	var mainSxns = $$('div[id ^= sxnHolder_]');
	mainSxns.each(function(sxn){
		//sortList('sxnContent', 'DIV', sxn.id, 'parSxn', '', 'updSequence', temp, tab, 1, 'id');
		var curTemp = $F(sxn.id+'_temp');
		var str  = '#'+sxn.id+' div[id ^= pgeSxn]';
		var sons = $$(str);
		sons.each(function(xx){
			sortList('sxnContent', 'DIV', xx.id, 'elmTab', '', 'updSequence', curTemp, tab, 1,'id');
		});

		sortList('sxnContent', 'DIV', sxn.id, 'parSxn', '', 'updSxnSeq', curTemp, index, 1,'id');
	});



}

function elemInit(obj, tab) {
    obj = $(obj);
    if (obj.innerHTML == '-') {
        sortList('order', 'TR', 'order', 'row', '', 'updSequence', 0, tab);
    }
/*
	 * var param = { 'tag' : 'TR', 'ghosting' : true, 'only' : 'row', 'elements' :
	 * $$('#elemOrder tr') }; Sortable.create('elemOrder', param);
	 */
}

function sortList(divid, typ, par_css, chd_css, hov_css, act, temp, tab, ok,attrib) {
    ok = isset(ok) ? parseInt(ok) : 0;
	 attrib = isset(attrib) ? attrib : 'class';
    //
	 if(ok){
		var elms = $$('div['+attrib+' ^='+par_css+']');
	}else{
	   var elms = $A(document.getElementsByClassName(par_css));
	}
    var param = {
        'tag' : typ,
        'handle' : 'movehandle',
        'ghosting' : true,
        //'handle' : true,
        'dropOnEmpty' : true,
        'only' : chd_css,
        'hoverclass' : hov_css
    };

    for ( var i = 0; i < elms.length; i++) {
        var curElm = elms[i];
        if ((typ == 'LI') || (typ == 'TR')) {
            var elmstr = '#' + curElm.id + ' ' + typ.toLowerCase();
            param.elements = $$(elmstr);
            param.containment = curElm.id;
        } else {
            if (ok == 1) {
                param.elements = $A(curElm.getElementsByClassName(chd_css));
               // param.containment = curElm.id;
            }
        }
        param.onUpdate = function(curElm) {
				var pageid = '';
				if(ok && act == 'updSxnSeq'){
				   pageid = $F(par_css+'_page');
				}else{
					pageid = $('editPage') ? $F('editPage') : ($('ID') ? $F('ID'):'');
				}
            var order = {
                'seq[]' : Sortable.sequence(curElm.id),
                'action' : act,
                'ajax' : 1,
                'temp' : temp,
                'pageid' : pageid,
                'table' : tab
            };
            var reg = new Ajax.Request(file, {
                parameters : order,
                method : 'Post',
                onComplete : function() {
                    refreshPage($F('editPage'));
                }
            });
        };

      //  if(isset(param.elements) && param.elements.length > 1){
            Sortable.create(curElm, param);
      //  }
    }

}
function dispHelpType(suffix){
	//var smn = $$('span[id ^=hlp]');
	$$('span[id ^=hlp]').invoke('hide');
	$('hlp'+suffix).show();
}
function viewHelp(hid, pos, ok, helpID, typ) {
    var open = isset(ok) ? parseInt(ok) : ($(hid).visible() ? 0 : 1);
    var chld = $(pos + helpID);
    if (open) {
        $(hid + helpID).hide();
    } else {
		 var ttm   = "<div id='#{help_pos}#{help_id}' class='helpDiv'>";
		 ttm      += "<span id='helpHandle' class='helpHandle'><span class='qTitle'><img src='#{image_path}help3.png' border='0' class='helpFavicon' align='left'/><h4>Quick Help</h4></span>";
		 ttm      += "<span id='helpBtn'><img src='#{image_path}close.png' alt='close' border='0' align='right' onclick=\"$(\'#{help_pos}#{help_id}\').remove(); return false\" title='Close Help'/></span>";
		 ttm      += "</span>";
		 ttm      += "<div class='helpContent waitHelp' id='helpContent_#{help_id}'><h3>Searching - Please wait ... </h3><img src='#{graphics_path}spin.gif' border='0'/></div>";
		 ttm      += "<div class='helpBottom'><span class='helpOptions'><label onclick=\"dispHelpType('Content');\">Main Content</label><label onclick=\"dispHelpType('Related');\">Related Items</label> <label  onclick=\"dispHelpType('Faq');\">FAQs</label><label onclick=\"dispHelpType('Tech');\">Technical</label></span>";
		 ttm      += "<input type='submit' name='close' value='close' onclick=\"$('#{help_pos}#{help_id}').remove(); return false\" title='Close help' /></div></div>";


        var temp = new Template(ttm);
        var show = {
            position : pos,
            help_id : helpID,
            image_path : ICON_PATH,
            help_type : typ,
            help_pos : hid,
            graphics_path : GRAPHICS_PATH
        };
        var str = temp.evaluate(show);
        new Insertion.Before(chld, str);
        var par = $(hid + helpID);
        new Draggable(par, {
            handle : 'helpHandle'
        });

        var req = new Ajax.Request(file, {
            method : 'Post',
            parameters : {
                'helpType' : typ,
                'helpID' : helpID,
                'action' : 'getHelp',
                'helpPos' : hid
            },
            onSuccess : function(response) {
                var data = response.responseText.evalJSON(true);
                var cont = $('helpContent_' + helpID);
                cont.removeClassName('waitHelp');
                cont.innerHTML = data.main;
					 //alert(data.main);
            },
            onComplete : function() {
            }
        });

    }
}

function adjValue(id, table, recid, fld, up) {
    up = parseInt(up);
    var val = parseInt($(id).innerHTML);
    var nVal = (up == 1) ? val + 1 : val - 1;
    if (nVal < 0) {
        nVal = 0;
    } else {
        updateField(nVal, table, recid, fld);
    }
    $(id).innerHTML = nVal;
}

function deleteLayout(itemid, pageid, pge, bin, divid) {
    divid = isset(divid) ? divid : 'sxnRecRight';
    bin   = isset(bin) ? bin : 1;
    var req = new Ajax.Updater(divid, pge, {
        method : 'Post',
        parameters : {
            'ajax' : 1,
            'itemID' : itemid,
            'action' : 'deleteItem',
            'ID' : pageid,
            'bin' : bin
        },
        onComplete : function(response) {
            var data = response.responseText;
        }
    });
}

function toggleChildren(parid, pre, selid) {
    parid   = $(parid).id;
    var grp = $(parid);
    var leave = parseInt($F('leave_' + selid));
    $('leave_' + selid).value = 0;
    if (grp.tagName == 'OPTGROUP') {
        // var grp = $(par);
		  var opts  = $(selid).childElements();

       // var kids = grp.childElements();
        // var opts = $$('#'+selid+ '_optgroup[id]');
        //var opts = grp.siblings();

        if ($('curGrp')) {
            $('curGrp').value = grp.label;
        }
		/*
        opts.each(function(e) {
            if (e.id.startsWith(pre)) {
                if (e != grp) {
                    e.className = 'close';
                    var chld = e.childElements();
                    for ( var k = 0; k < chld.length; k++) {
                        var c = chld[k];
                        if (c.visible()) {
                            c.hide();
                        }
                    }
                }
            }
        });
		  */
		  opts.each(function(cc){
				var kk = cc.childElements();
				kk.each(function(xx){
					if(cc.id == parid){
						xx.show();
					}else{
						xx.hide();
					}
				});
				if(cc.id != parid){
					cc.addClassName('close');
					cc.removeClassName('open');
				} else{
                cc.addClassName('open');
                cc.removeClassName('close');
				}
		  });

        /*for ( var i = 0; i < kids.length; i++) {
            var elm = kids[i];
            if (leave == 0) {
                elm.toggle();
            }
        }

        var bkgnd = grp.getStyle('background');
        if (leave == 0) {
            if (grp.hasClassName('open')) {
                grp.addClassName('close');
                grp.removeClassName('open');
            } else {
                grp.addClassName('open');
                grp.removeClassName('close');
            }
        }*/
    }
}

function optGroupNav(obj, pg, t, i, a, g, pm) {
    var opts = $$('optgroup[id]');
    var grp = $F('curGrp');
    document.location.href = pg + '?table=' + t + '&ID=' + i + '&action=' + a
    + '&tagONESEL=1&curGrp=' + grp + '&' + pm;
}

function updateLayout(pge, rads, temp, id,all,remove) {
    rms.clearMsgDiv();
	 all     = parseInt(all);
	 remove  = isset(remove) ? parseInt(remove) : 0;
	 var msg;
    var typ = $('curItem').value;
    var selid = $('select_' + typ);
    var sel = $(selid);
    var elms = [];
    var sxn = [];
    var cnt = 0;
    var optGrp = $F('curGrp');
    if (sel != null) {
        for ( var i = 0; i < sel.length; i++) {
            if (sel.options[i].selected && !sel.options[i].value.empty()) {
                elms[cnt] = sel.options[i].value;
                cnt++;
            }
        }
    }

    if (cnt > 0) {
        cnt = 0;
        var chk = $$('input.posBox');
        for ( var x = 0; x < chk.length; x++) {
            if (chk[x].checked) {
                sxn[cnt] = $F(chk[x]);
                cnt++;
            }
        }

        if (cnt > 0) {
            var sxn2 = sxn.toJSON();
            var elm2 = elms.toJSON();
            var req = new Ajax.Updater('sxnRecRight', pge, {
                method : 'Post',
                parameters : {
                    'curGrp' : optGrp,
                    'sxn' : sxn2,
                    'items' : elm2,
                    'ajax' : 1,
                    'item' : typ,
                    'action' : 'updateLayout',
                    'TemplateID' : temp,
                    'ID' : id,
						  'allPages': all,
						  'remove'  : remove
                },
					 onLoading  : showWait,
					 onLoaded   : hideWait,
                onComplete : function(response) {
                    sortList('sxnContent', 'LI', 'sortul', 'sortli',
                        'sort_hover');
                    //var data = response.responseText;
                }
            });
        } else {
				msg = 'Select at least one section to add the selected items(s) to';
				rms.showMsg(msg);
            //alert(msg);
        }
    } else {
				msg = 'Select one or more items to add to the current page';
				rms.showMsg(msg);
           // alert(msg);
    }
}

function sortTreeList(elm, pos, loc, tb) {
    var topid = elm + '-' + loc;
    var items = $$('ul[id ^=' + elm + ']', 'ul[id=' + elm + ']',
        'ul[id=' + topid + ']');
    var par = [ elm + '-', topid ];
    var param = {
        'containment' : items,
        'dropOnEmpty' : true
    };

    for ( var e = 0; e < items.length; e++) {
        var cur = items[e];
        param.onUpdate = function(cur) {
            var order = {
                'seq[]' : Sortable.sequence(cur.id),
                'parm' : Sortable.serialize(cur.id),
                'action' : 'updNavTree',
                'ajax' : 1,
                'MenuLoc' : pos,
                'parent' : cur.id,
                'table' : tb
            };
            var reg = new Ajax.Request(file, {
                parameters : order,
                method : 'Post',
                onLoading : showWait,
                onLoaded : hideWait
            });
        };
        Sortable.create(cur.id, param);
    }

    for (e = 0; e < par.length; e++) {
        cur = $(par[e]);
        if (cur) {
            Sortable.create(cur.id, param);
        }
    }

    $('menuMode').innerHTML = 'Edit';
    $('menuMode').addClassName('pass');
}

function changeMenuLoc(pUrl, pData, pMethod, divID) {
    pData += '&MenuLoc=' + $F('MenuLoc');
    requestData(pUrl, pData, pMethod, divID);
}

function editConfig(conid, typ, ttle, curVal, userLevel, longdesc) {
    var str = '';
    var source = $F('source_' + conid);
    var edit = $('configEdit_' + conid);
    var dis_opt = (parseInt(userLevel) < 1) ? "" : " disabled='disabled'";
    var rdy_opt = (parseInt(userLevel) > 0) ? "" : " readonly='readonly'";
    var varID = "variable_" + typ;

    $$("div [id ^=configEdit_]").each(function(e) {
        e.hide();
    });
    var tempstr = "<span id='helpHandle' class='helpHandle'><span class='qTitle'><img src='#{image_path}help3.png' border='0' class='helpFavicon' align='left'/>";
    tempstr += "<h4>Edit #{span_title} Setting</h4></span><span id='helpBtn'><img src='#{image_path}close.png' alt='close' border='0' align='right' onclick=\"$('configEdit_#{configID}').hide()\; return false\" title='Close'/></span></span>";
    tempstr += "<span class='configContent waitHelp' id='mainContent_#{configID}'><h3>Searching - Please wait ... </h3><img src='#{graphics_path}spin.gif' border='0'/></span>";
    tempstr += "<div class='configBottom'><span class='updateOption'><label>Default</label><input type='checkbox' name='default' value='1' id='default' #{disable_opt} />";
    tempstr += "<label>User</label><input type='checkbox' name='user' value='1' id='user' checked='checked' #{rdy_opt}/></span>";
    tempstr += "<span class='popUpBtn'><img src='#{image_path}cancel_f2.png' border='0' title='cancel' alt'cancel' onclick=\"$('configEdit_#{configID}').hide()\" />";
    tempstr += "<img src='#{image_path}apply_f2.png' border='0' title='update' alt'update' onclick=\"updateConfig('#{configID}','#{contype}')\" /></span></div>";
    var temp = new Template(tempstr);

    var show = {
        rdyly : rdy_opt,
        configID : conid,
        image_path : ICON_PATH,
        contype : typ,
        graphics_path : GRAPHICS_PATH,
        span_title : ttle,
        disable_opt : dis_opt
    };
    var output = temp.evaluate(show);

    edit.innerHTML = output;
    new Draggable(edit);
    edit.show();
    var mainID = 'mainContent_' + conid;
    var main = $(mainID);
    main.removeClassName('sel');

    switch (typ) {
        case "Table": {
            if (source) {
                var par = {};
                par.action = "getTableItems";
                par.table = source;
                var query = Object.toQueryString(par) + "&parms[Deleted]=0";
                var req = new Ajax.Request(file, {
                    method : 'Post',
                    parameters : query,
                    onLoading : showWait,
                    onLoaded : hideWait,
                    onComplete : function(response) {
                        var res = response.responseText.evalJSON();
                        multi = parseInt(res.multi);
                        var obj = buildSelect(res.data, "variable", varID, curVal,
                            "ShortDesc", "ID", multi, res.total);
                        var pref = "<h4>Tips</h4><p>" + res.tips + "</p>"
                        + longdesc;
                        pref += "<label>Select </label><br />";
                        $(mainID).innerHTML = '';
                        $(mainID).addClassName('sel');
                        new Insertion.Top(mainID, pref);
                        new Insertion.Bottom(mainID, obj);
                    }

                });
            }
            break;
        }

        case "Bool": {
            var isOff='';
            var isOn ='';
            if (parseInt(curVal) == 1) {
                isOn = 'checked="checked"';
                isOff = '';
            } else {
                isOff = 'checked="checked"';
                isOn = '';
            }

            str = "<label><input type='radio' name='variable' value='1' id='"
            + varID + "' " + isOn + " /> On</label>";
            str += "<label><input type='radio' name='variable' value='0' id='"
            + varID + "' " + isOff + " /> Off</label>";
            break;
        }

        case "Numeric":
        case "Float":
        case "Text":
        default:
            str = "<label>Enter free text</label><input type='text' value='"
            + curVal + "' name='variable' id='" + varID + "' value='' />";
            break;
    }

    if (str != '') {
        main.innerHTML = '';
        main.innerHTML = "<h4>Tips</h4>" + longdesc + str;
    }
    main.removeClassName('waitHelp');
}

function updateConfig(conid, typ) {
    var val = "";
    var disp = "";
    var valid = "variable_" + typ;
    var elem = $(valid);
    var user = $('user');
    var deft = $('default');
    switch (typ) {
        case "Bool": {
            var obj = getSelected(valid);
            val = $F(obj);
            disp = (parseInt(val) == 1) ? "on" : "off";
            break;
        }
        case "Table": {
            val = $F(elem);
            multi = Object.isArray(val) ? true : false;
            if (multi) {
                val = $F(elem).join('|');
                disp = val;
            } else {
                val = $F(elem);
                disp = elem.options[elem.selectedIndex].text;
            }
            break;
        }
        default: {
            val = $F(elem);
            disp = val;
            break;
        }
    }

    if (user.checked) {
        updateField(val, 'rms_config', conid, 'Param', 'ModConfigID', 1);
        $("config_" + conid).innerHTML = disp;
    }

    if (deft.checked) {
        updateField(val, 'admin_modconfig', conid, 'Param', '', 0);
        $("default_" + conid).innerHTML = disp;
    }
}
