/*** GLOBAL VARIABLES ***/

var User                    = null;
var Modules                 = null;
var contactModule           = null;
var cityModule              = null;
var stateModule             = null;
var domainModule            = null;
var mediaModule             = null;
var roleModule              = null;
var moduleModule            = null;
var subscriptionModule      = null;
var categoryModule          = null;
var marketingsourceModule   = null;
var metricModule            = null;
var settingsModule          = null;
var logModule               = null;
var formModule              = null;
var surveyModule            = null;
var formReportModule        = null;
var articleModule           = null;
var groupModule             = null;
var startupModule           = null;
var clientModule            = null;
var workflowModule          = null;
var SYSINFOTIMEOUT          = 2000; //msec to show sysinfo

var modulesIdlookup         = []; // key: name, value: id, assoc arr to convert module name to moduleid 
var modulesIndxIdlookup     = []; // key: id, value: indx, assoc arr to convert id to index

var Preferences = [];

//Preferences[1] = {"value":20}; //perpage
//Preferences[2] = {"value":1}; // default start module

//var CurrentModuleId = 0;
var CurrentModule = null;

var libraryDirectory = "";
var mediaDirectory   = "";
var photoDirectory   = "";

/** DEBUG **/
var DEBUG = false;
//var RESULT = ''; 
Ajax.debug = true;

window.onbeforeunload = confirmExit;
var needconfirm = false;
/****************************************/


function initmain(){   

    try { document.getElementById("search").onkeyup = searchPressed; } catch (e) {}

    needconfirm = true;
    getUser();
}

function login(){
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var act      = document.getElementById("act").value;

    document.getElementById("info").innerHTML = "";

    var ajx = new Ajax();
    ajx.addParameter("username", username);
    ajx.addParameter("password", password);
    ajx.addParameter("action",   act);
    ajx.sendRequest("authenticate.php","POST",Ajax.evalResult);    //    ajx.sendRequest("authenticate.php","POST",debugString);   
    return false;
}

function passwretriever(which){

    var str = "";
    var w = which == "password" ? "username" : "email";
    
    do {
        str = prompt("Enter your "+ w +":","");        
    }
    while (str == "");

    if (str == null) {
        return;
    }

    document.getElementById("info").innerHTML = "";

    var ajx = new Ajax();
    ajx.addParameter("value", str);    
    ajx.addParameter("action",   which);
    ajx.sendRequest("passwretriever.php","POST",Ajax.evalResult);    //    ajx.sendRequest("authenticate.php","POST",debugString);       
}

function exit(){
    if (!confirm("Exit?")) return;
    needconfirm = false;

    var ajx = new Ajax();
    ajx.addParameter("action", "exit");
    ajx.sendRequest("authenticate.php","POST",Ajax.evalResult);    
}

function getUser(){
    var ajx = new Ajax();
    ajx.addParameter("action", "getUser");
    ajx.sendRequest("authenticate.php","POST",Ajax.evalResult);  
}

function setUser($userArr){
    User = $userArr;  

    for (i in User) {
        User[i] = unescape(User[i]);
    }

    if (User.template == "") User.template = "default";    
}

function setModules(list){

    
    Modules = list;

    for (i in Modules) {
        for (j in Modules[i]) {
            Modules[i][j] = unescape(Modules[i][j]);
        }

        if (Modules[i].name == '') {
            Modules[i].name = Modules[i].modulename;
        }
        modulesIdlookup[Modules[i].module] = Modules[i].moduleid;
        modulesIndxIdlookup[Modules[i].moduleid] = i;
    }    
}

function setPreferences(list){

    Preferences = list;

    for (i in Preferences) {
        for (j in Preferences[i]) {
            Preferences[i][j] = unescape(Preferences[i][j]);
        }
    }
}

function error(msg){
    document.getElementById("info").innerHTML = unescape(msg);
}

function action(act) {

    switch(act){
    case "showMain":
        document.getElementById("login").style.visibility = 'hidden';
        document.getElementById("maindiv").style.visibility = 'visible';
        document.getElementById("userfullname").innerHTML = User.fname + " " + User.lname;
        document.getElementById("userrole").innerHTML = User.rolename;
        document.body.className = "body2";

        var h = [];

        // user login
        if (User.isuser == 1) {
        
            for (i in Modules) {
                if (Modules[i].disabled == 1 || Modules[i].hidden == 1) continue;
                var perm = (Modules[i].rolepermission | Modules[i].permission) & 4; 
    
                if (perm == 0) continue
                    
                h.push('<div class="menu_tab" onclick="selectModule('+Modules[i].moduleid+')" nowrap>');
                h.push(getPlural(Modules[i].name) +'</div>');
            }
        

            document.getElementById("modules").innerHTML = h.join("\n");
            
            var moduleid = Preferences[2].value;
            var moduleindx = modulesIndxIdlookup[moduleid];

            // selects the first module to load
            // if permission is not allowed find another module
            if (!(Modules[moduleindx].rolepermission & 4 || Modules[moduleindx].permission & 4)) {
    
                for (indx in Modules) {
                    // skip modules that do not have permission
                    if (Modules[indx].rolepermission & 4 || Modules[indx].permission & 4) {                        
                        moduleid = Modules[indx].moduleid;
                        break;
                    }
                }
            }

            selectModule(moduleid); //select default module on startup
        }

        // client login
        else {

            document.getElementById("search").value = '';

            Module.closeEditor();
            Module.closeEditor2();
            Module.closeEditor("editdiv3");
            Module.closeEditor("editdiv4");
            Module.closeUpload();

            var cl = factoryModule(34); // client module
            
            

/*        
            if (cl != null) { 
                cl.showClient = true;
                cl.permission = 6;

                cl.setSearch('');
                cl.setModuleActions();
                cl.setNewItem();// to generate object
                cl.editedobject.contactid = User.contactid;
                cl.displaydiv1 = "mainlist";
                cl.displayItem();
            }
*/            
            //CurrentModuleId = moduleid;
            CurrentModule = cl;

            for (tab in cl.menutabs) {                                
                h.push('<div class="menu_tab" onclick="clientModule.selectMenu(\''+ tab +'\')" nowrap>');                
                h.push(cl.menutabs[tab] +'</div>');
            }        

            document.getElementById("modules").innerHTML = h.join("\n");

            // forcing startup module typeid = 2 - to use clientstartup when available
            var indx = modulesIndxIdlookup[32];
            Modules[indx].typeid = 2;                        
            selectModule(32); // startup module
        }


        if (DEBUG) showdebug();
        
        break;

    case "sessionExpired":

        document.getElementById("info").innerHTML = "Your session expired";
        document.getElementById("login").style.visibility = 'visible';
        /*
        document.getElementById("maindiv").style.visibility = 'hidden';
        document.getElementById("editdiv").style.visibility = 'hidden';
        document.getElementById("searchdiv").style.visibility = 'hidden';
        */
        document.getElementById("username").value = User.username;

        //document.getElementById("password").value = "";
        document.getElementById("act").value = "renewSession";
        
        break;

    case "renewSession":
        document.getElementById("login").style.visibility = 'hidden';
        /*
        document.getElementById("maindiv").style.visibility = 'visible';
        document.getElementById("editdiv").style.visibility = 'visible';
        document.getElementById("searchdiv").style.visibility = 'visible';
        */
        break;

    case "exit":
        location.reload();
        break;

    case "showLogin":
        document.getElementById("login").style.visibility = 'visible';
        document.getElementById("maindiv").style.visibility = 'hidden';
        break;    

    default: 
        alert("no such action: " + act); 
    break;
    }
}


function setSearch(){
    var search = document.getElementById("search").value;

    CurrentModule.find(search);
}


function searchPressed(e){

    if (!e) var e = window.event;

    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    if (code == 13) { // enter
        setSearch();        
    }
}

function showSearchFields() {
    CurrentModule.showSearchFields();
}

/*
* Call the corresponding module
* set the menu for the module
*/
function selectModule(moduleid){

    moduleid = parseInt(moduleid);
    document.getElementById("search").value = '';

    Module.closeEditor();
    Module.closeEditor2();
    Module.closeEditor("editdiv3");
    Module.closeEditor("editdiv4");
    Module.closeUpload();

    var md = factoryModule(moduleid);

    if (md != null) {

        md.setSearch('');
        md.setModuleActions();
        md.getList();
    }
    
    //CurrentModuleId = moduleid;
    CurrentModule = md;
}

function factoryModule(moduleid) {

    var module, mod;
    var moduleindx = modulesIndxIdlookup[moduleid];

    if (typeof(Modules[moduleindx]) == "undefined"){                
        return null;
    }

    module = Modules[moduleindx];
    
    switch (module.module) {
    case 'contact':

        if (!self.ContactModule) loadScript("ContactModule.js");        

        contactModule = new ContactModule(moduleid);
        contactModule.contacttypeid = Modules[moduleindx].typeid;
        contactModule.isuser        = Modules[moduleindx].param;

        contactModule.isgrouprequired = ISGROUPIDREQUIRED;//contactModule.isuser != 1; // TODO later define this setting in db
        mod = contactModule;
        break;


    case 'module':
        if (moduleModule == null) {

            if (!self.ModuleModule) loadScript("ModuleModule.js");            

            moduleModule = new ModuleModule(moduleid);
        }

        mod = moduleModule;
        break;
    

    case 'domain':
        if (domainModule == null) {

            if (!self.DomainModule) loadScript("DomainModule.js");            

            domainModule = new DomainModule(moduleid);
        }

        mod = domainModule;
        break;

    case 'city':
        if (cityModule == null) {

            if (!self.CityModule) loadScript("CityModule.js");            

            cityModule = new CityModule(moduleid);
        }

        mod = cityModule;
        break;

    case 'media':

        if (mediaModule == null || 
            mediaModule.mediatypeid != Modules[moduleindx].typeid) {

            if (!self.MediaModule) loadScript("MediaModule.js");            

            mediaModule = new MediaModule(moduleid);
            mediaModule.mediatypeid = Modules[moduleindx].typeid;
            mediaModule.iscontactrequired = Modules[moduleindx].typeid == 2;
        }

        mod = mediaModule;
        break;

    case 'category':

            if (!self.CategoryModule) loadScript("CategoryModule.js");

            categoryModule = new CategoryModule(moduleid);
            categoryModule.typeid           = Modules[moduleindx].typeid;
            categoryModule.childtypeid      = Modules[moduleindx].param;
            categoryModule.haschildren      = (Modules[moduleindx].param != "");

        mod = categoryModule;
        break;

    case 'subscription':
        if (subscriptionModule == null) {

            if (!self.SubscriptionModule) loadScript("SubscriptionModule.js");            

            subscriptionModule = new SubscriptionModule(moduleid);
        }

        mod = subscriptionModule;
        break;

    case 'role':
        if (roleModule == null) { 

            if (!self.RoleModule) loadScript("RoleModule.js");            

            roleModule = new RoleModule(moduleid);
        }

        mod = roleModule;
        break;

    case 'state':
        if (stateModule == null) {

            if (!self.StateModule) loadScript("StateModule.js");           

            stateModule = new StateModule(moduleid);
        }

        mod = stateModule;
        break;

    case 'marketingsource':
        if (marketingsourceModule == null) {

            if (!self.MarketingsourceModule) loadScript("MarketingsourceModule.js");            

            marketingsourceModule = new MarketingsourceModule(moduleid);
        }

        mod = marketingsourceModule;
        break;

    case 'metric':
        if (metricModule == null) {

            if (!self.MetricModule) loadScript("MetricModule.js");            

            metricModule = new MetricModule(moduleid);
        }

        mod = metricModule;
        break;

    case 'settings':
        if (settingsModule == null) {

            if (!self.SettingsModule) loadScript("SettingsModule.js");            

            settingsModule = new SettingsModule(moduleid);
        }

        mod = settingsModule;
        break;

    case 'log':
        if (logModule == null) {

            if (!self.LogModule) loadScript("LogModule.js");

            logModule = new LogModule(moduleid);            
        }

        mod = logModule;
        break;

    case 'form':
        if (formModule == null) {

            if (!self.FormModule) loadScript("FormModule.js");

            formModule = new FormModule(moduleid);            
        }

        mod = formModule;
        break;

    case 'survey':
        if (surveyModule == null) {

            if (!self.SurveyModule) loadScript("SurveyModule.js");            

            surveyModule = new SurveyModule(moduleid);
        }

        mod = surveyModule;
        break;

    case 'formreport':
        if (formReportModule == null) {

            if (!self.FormReportModule) loadScript("FormReportModule.js");           

            formReportModule = new FormReportModule(moduleid);
            
        }

        mod = formReportModule;
        break;

    case 'article':
        if (articleModule == null) {

            if (!self.ArticleModule) loadScript("ArticleModule.js");            

            articleModule = new ArticleModule(moduleid);            
        }

        mod = articleModule;
        break;

    case 'group':
        if (groupModule == null) {

            if (!self.GroupModule) loadScript("GroupModule.js");

            groupModule = new GroupModule(moduleid);            
        }

        mod = groupModule;
        break;

    case 'startup':
        if (startupModule == null) {
            if (!self.StartupModule) loadScript("StartupModule.js");            
            startupModule = new StartupModule(moduleid);  
            startupModule.typeid = Modules[moduleindx].typeid;                    
        }

        mod = startupModule;
        break;

    case 'client':

        if (clientModule == null) {

            if (!self.ClientModule) loadScript("ClientModule.js");        

            clientModule = new ClientModule(moduleid);  
        }

        mod = clientModule;
        break;

    case 'workflow':
        if (workflowModule == null) {

            if (!self.WorkflowModule) loadScript("WorkflowModule.js");

            workflowModule = new WorkflowModule(moduleid);            
        }

        mod = workflowModule;
        break;

    default:
        alert("factoryModule: no such module: " + module.module);
        return null;
        break;
    }

    mod.modulename = Modules[moduleindx].name;
    mod.link       = 'modules/' + Modules[moduleindx].module + '.php';
    mod.maxrows    = parseInt(Preferences[1].value);
    mod.permission = Modules[moduleindx].rolepermission | Modules[moduleindx].permission;
    mod.setTemplatePath('template/'+ User.template);

    return mod;
}

function loadScript(script){

    var ajx = new Ajax();
    ajx.async = false;
    ajx.sendRequest("modules/"+script,"GET", Ajax.evalResult);
}

function showSaving() {
    showProgressDiv('Saving...');
}

function showProgress(){
    showProgressDiv('Loading...');
}

function showProgressDiv(msg){
    
    var ctrl = document.getElementById("progressdiv");
    
    //if (ctrl.style.visibility == 'visible') return;

    ctrl.innerHTML = msg;
    ctrl.style.visibility = 'visible';
    
    var wh = getWindowSize();
    var w = 200;
    var h = 50;

    ctrl.style.left = ((parseInt(wh[0]) - w) / 2) + "px";
    ctrl.style.top  = ((parseInt(wh[1]) - h) / 2) + "px";
    ctrl.style.width = w + "px";
    ctrl.style.height = h + "px";    
}

function showSysInfo(message){

    var ctrl = document.getElementById("sysinfo");
    ctrl.innerHTML = message;
    ctrl.style.visibility = 'visible';   

    var wh = getWindowSize();
    var w = 300;
    var h = 50;

    ctrl.style.left = ((parseInt(wh[0]) - w) / 2) + "px";
    ctrl.style.top  = ((parseInt(wh[1]) - h) / 2) + "px";
    ctrl.style.width = w + "px";
    ctrl.style.height = h + "px";    

    if (typeof(cmtimer) != "undefined") {
        clearTimeout(cmtimer);
    }

    if (message == "") return;

    cmtimer = setTimeout("hideSysInfo()", SYSINFOTIMEOUT);    
}

function hideSysInfo(){

    var ctrl = document.getElementById("sysinfo");
    ctrl.style.visibility = 'hidden';     
}

function resize(){

    var l1 = 325;//375
    var t1 = 83;
    var l2 = 450;//500
    var t2 = 240;
    var l3 = 400;
    var t3 = 150;
    var l4 = 450;
    var t4 = 307;


    if (arguments.length > 2) {

        switch(arguments[0]) {
        case 1 :
            l1 = arguments[1];
            t1 = arguments[2];
            break;
        case 2 :
            l2 = arguments[1];
            t2 = arguments[2];
            break;
        case 3 :
            l3 = arguments[1];
            t3 = arguments[2];
            break;
        case 4 :
            l4 = arguments[1];
            t4 = arguments[2];
            break;
        }
    }

    var wh = getWindowSize();

    var ed  = document.getElementById("editdiv");
    var ed2 = document.getElementById("editdiv2");
    var ed3 = document.getElementById("editdiv3");
    var ed4 = document.getElementById("editdiv4");

    if (ed.style.visible = 'visible') {        
        ed.style.left = l1 + "px";
        ed.style.top  = t1 + "px";
        ed.style.width = (parseInt(wh[0]) - l1 - 20) + "px";
        ed.style.height = (parseInt(wh[1]) - t1 - 20) + "px";
    }

    if (ed2.style.visible = 'visible') {   
        ed2.style.left = l2 + "px";
        ed2.style.top  = t2 + "px";
        ed2.style.width = (parseInt(wh[0]) - l2 - 40) + "px";
        ed2.style.height = (parseInt(wh[1]) - t2 - 40) + "px";
    }
    if (ed3.style.visible = 'visible') {        
        ed3.style.left = l3 + "px";
        ed3.style.top  = t3 + "px";
        ed3.style.width = (parseInt(wh[0]) - l3 - 20) + "px";
        ed3.style.height = (parseInt(wh[1]) - t3 - 20) + "px";
    }
    if (ed4.style.visible = 'visible') {
        ed4.style.left = l4 + "px";
        ed4.style.top  = t4 + "px";
        ed4.style.width = (parseInt(wh[0]) - l4 - 40) + "px";
        ed4.style.height = (parseInt(wh[1]) - t4 - 40) + "px";
    }


}
/**
 * positons the provided div 
 * in the current window left, center right
 * calculates the div size based on the 
 * provided width and hight parameters
 * 
 * @param div: div object
 * @param w: width in pixels
 * @param h: hight in pixels
 * @position: first char is horizontal position: "l", "c", "r"
 *            second character vertical positioning: "t", "c", "b"
 * 
 * @param offsetx: offset from left or righ
 * @param offsety: offset from top or bottom
 * 
 * example: postion div in the window right bottom 100 px wide, 50 pix high
 *          setDivSize(mydiv, 100, 50, "rb")
 */

function setDivSize(div, w, h, position){

    var xoffset = 0;
    var yoffset = 0;

    if (arguments.length > 4) {
        xoffset = arguments[4];
    }

    if (arguments.length > 5) {
        yoffset = arguments[5];
    }

    var wh = getWindowSize();
    var l, t;

    //log(wh);

    if (typeof(w) == "string" && w.indexOf("%") > -1) {
        w = parseInt(w) / 100 * wh[0];
        w = parseInt(w);
    }

    if (typeof(h) == "string" && h.indexOf("%") > -1) {
        h = parseInt(h) / 100 * wh[1];
        h = parseInt(h);
    }


    var xpos = position.substr(0,1);
    var ypos = position.substr(1,1);

    switch (xpos) {
    case 'c': l = (parseInt(wh[0]) - w) / 2; break;
    case 'l': l = xoffset; break;
    case 'r': l = parseInt(wh[0]) - w - xoffset; break;
    default: alert('undefined x position:' + xpos); break;
    }

    switch (ypos) {
    case 'c': t = (parseInt(wh[1]) - h) / 2; break;
    case 't': t = yoffset; break;
    case 'b': t = parseInt(wh[1]) - h - yoffset; break;
    default: alert('undefined y position:' + ypos); break;
    }

    //log(w + "-" + h + "-" + l + "-" + t);

    div.style.left   = l + "px";
    div.style.top    = t + "px";
    div.style.width  = w + "px";
    div.style.height = h + "px";
}

function hideProgress(){

    var ctrl = document.getElementById("progressdiv");
    ctrl.style.visibility = 'hidden';     
}

function stopEvent(e){
    if (!e) var e = window.event;
    if (e == null) return;
    e.cancelBubble = true;   
    if (e.stopPropagation) e.stopPropagation();
}

function getWindowSize() {

    var w = 0, y = 0;

    if( typeof(window.innerWidth) == 'number') { //Non-IE
        w = window.innerWidth;
        h = window.innerHeight;
    } 
    else if(document.documentElement && 
           (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        w = document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
    } 
    else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
    //IE 4 compatible
        w = document.body.clientWidth;
        h = document.body.clientHeight;
    }
    return [w, h];  
}

function getScrollXY() {

    var scrOfX = 0, scrOfY = 0;

    if(typeof(window.pageYOffset) == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } 
    else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } 
    else if(document.documentElement &&
             (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }

    return [scrOfX, scrOfY];
}

function isemail(val){
   return (val.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
}


function getkbsize(size){
    var s = new Number(size);

    if (s > 1048576) {
        return (Math.round(s / 104857.6) / 10) + "M";
    }
    else if (s > 1024) {
        return Math.round(s / 1024) + "k";
    }
    else{
        return s;
    }
}

function help(){
    alert('help');
}

function preferences(){

    if (typeof(modulesIdlookup['settings']) == "undefined") {
        alert("settings module undefined");
        return;
    }
    
    selectModule(modulesIdlookup['settings']);
}

function checkList(name){
    var obj = document.getElementsByName(name);
    for (i = 0; i < obj.length; i++) {
        obj[i].checked = !obj[i].checked;
    }
}

function getcheckedIds(name){
    var idarr = [];

    var obj = document.getElementsByName(name);

    if (obj == null || obj.length == 0) return idarr;

    for(i = 0; i < obj.length; i++){                
        if (obj[i].checked) idarr[idarr.length] = obj[i].value;
    }
    return idarr;
}

function formatUrl(url) {
    if (url.substr(0,4).toLowerCase() != 'http') {
        return 'http://'+ url;
    }

    return url;
}

function getPlural(name) {

    var vowels = "aeiou";
    var nm = name.toLowerCase();

    if (nm == "media" || 
        nm == "welcome") return name;

        
    var lastchar = name.substr(name.length - 1);
    var lastprec = name.substr(name.length - 2, 1);

    switch(lastchar) {
    case "y" : 
        if (vowels.search(lastprec) > -1) {
            return name + "s";
        }
        else {                
            return name.substr(0, name.length - 1) + "ies";
        }
    break; // ies rule
    case "o" : return name + "es"; break; // oes rule
    default: return name + "s"; break;
    }    
}

function cloneObject(obj) {
    for (i in obj) {
        this[i] = obj[i];
    }
}

function nbsp(str) {
    if (str == "") return "&nbsp;";
    return str;
}

function splitvalue(str) {

    if (str == "") return [];

    if (str.search("\n") > -1) {
        return str.split("\n");
    }

    if (str.search("\r") > -1) {
        return str.split("\r");
    }

    return [];
}

function confirmExit() {    
    if (needconfirm) return "Do you want to leave the application?";
}


function killnl(str, trimlength) {

    if (str == "") return "";

    var s = trimlength > 0 ? str.substr(0, trimlength) : str;
    return s.replace(/\n/g, " ");
}

/*
function works with a list of objects that has a parentid property
list index is the id of the object
children property added to object if child exists

*/
function getTree(list){ 

    for (i in list) {


        var parentid = list[i].parentid == "" ? 0 : list[i].parentid;

        //list[i].haschildren = false; // adding property to all -- causes error

        if (parentid != 0){ // does item has a parent ?

            if (typeof(list[parentid]) != "undefined") { // does parent exist ?
                if (typeof(list[parentid].children) == "undefined"){ // does parent have children ?
                    list[parentid].children = []; // not - create it
                    
                }

                list[parentid].children[i] = list[i]; // add child to parent
                list[parentid].haschildren = true;
            }
            //else alert("no parent");
        }
    }

    var tree = [];

    // copy all in root node to tree
    for (i in list) {        
        if (list[i].parentid == 0){ // is item a root node

            //alert("adding root node");
            tree[i] = list[i];
        }
    }


    return tree;
}

// trim method added to string
String.prototype.trim = function() {
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};


String.prototype.escapeHTML = function () {                                        
    return(                                                                 
        this.replace(/&/g,'&amp;').                                         
            replace(/>/g,'&gt;').                                           
            replace(/</g,'&lt;').                                           
            replace(/"/g,'&quot;')                                         
    );                                                                      
};

function addComma(str) {  
	var num = new String(str).replace(/,/g, '');  
	while(num != (num = num.replace(/^(-?\d+)(\d{3})/, '$1,$2')));  
	return num;  
}

/********************* DEBUGGING FUNCTIONS **********************/


function showdebug(){
    var h = '<a href="#" onclick="dbgglobals()">dbg globals</a><br>';
	    h+= '<a href="#" onclick="dbginnerhtml(\'modules\')">dbg menu</a><br>';
        h+= '<a href="#" onclick="debugString(Ajax.result)">dbg Ajax Result</a><br>';
        h+= '<a href="#" onclick="debugString(Ajax.params + Ajax.log)">dbg Ajax.log</a><br>';

        document.getElementById("sysinfo").innerHTML = h;

        DEBUGDIV = document.createElement("div");
        DEBUGDIV.style.position   = "absolute";
        DEBUGDIV.style.zIndex = 1005;
        DEBUGDIV.style.border = "#000000 solid 1px";
        DEBUGDIV.style.background = "#EEEEEE";
        DEBUGDIV.style.overflow = "auto";
        
        document.body.appendChild(DEBUGDIV);

        //window.scrollbars.visible = false;
        

        setDivSize(DEBUGDIV, "80%", 200, "rb")
}


/******************** DEBUG FUCTIONS ************************/

function dbgglobals(){
        var h = "";

    for (i in Modules) {

        h+= i + "|\n";

        for (j in Modules[i]) {
            h+= j + ":" + Modules[i][j] + "\n";
        }

    }

    for (i in Preferences) {

        h+= i + "|\n";

        for (j in Preferences[i]) {
            h+= j + ":" + Preferences[i][j] + "\n";
        }

    }

/*
    for (i in User) {
        h+= i + ":" + User[i] + "\n";
    }
*/

    debugString(h);
}

function dbginnerhtml(id){
    debugString(document.getElementById(id).innerHTML);
}

debugdepth = 0;
maxdepth = 3;

function debugobj(obj) {
    var str = [];
    var i;
    
    for (i in obj) {

        var type =  typeof(obj[i]);

        str.push(i + ":" + obj[i] + " - "+ type);
        //document.write(i + ":" + obj[i] + " - "+ type + "<br>\n");
        

        if (type == "object" && maxdepth > debugdepth) {

            debugdepth++;
            //document.write(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><br>\n");
            str.push(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            var s = debugobj(obj[i]);
            str.push(s);
            //document.write("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<br>\n");
            str.push("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<br>\n");
            debugdepth--;
        }
    }   

    return str.join("\n");
}

function debugobjw(obj){
    var dbg = window.open('','debug','scrollbars=yes,resizable=yes,width=400,height=300');
	
    dbg.document.write(debugobj(obj));

    dbg.document.close();
    dbg.focus();
}

function debug(obj){
	
    var dbg = window.open('','debug','scrollbars=yes,resizable=yes,width=400,height=300');
	
    for (p in obj){
        dbg.document.write(p + ":" + obj[p] + "<br>\n");
    }
    dbg.document.close();
    dbg.focus();
}

function debugList(list){
	
    var dbg = window.open('','debug','scrollbars=yes,resizable=yes,width=400,height=300');


    for (i in list) {
        dbg.document.write(i + "=");

        for (p in list[i]){
            dbg.document.write(p + ":" + list[i][p] + "<br>\n");
        }
        dbg.document.write("<br>\n");
    }
    dbg.document.close();
    dbg.focus();
}


function debugString(str){
    var nl2br = arguments.length > 1 ? arguments[1] : false;

    var dbg = window.open('','debug','scrollbars=yes,resizable=yes,width=400,height=300');
    str = unescape(str);

    if (nl2br) str = str.replace(/\n/g, "<br>\n");
    
    dbg.document.write(str);
    dbg.document.close();
    dbg.focus();
}


function log(msg){
    DEBUGDIV.innerHTML+= msg + "<br>\n";
    DEBUGDIV.scrollTop = DEBUGDIV.scrollHeight;
}


/* 
 * TinyMCE Editor - 2/18/09 - Daisuke
 */
var tinyMCE_elements = new String();
function tinyMceEditor(elementIDs) {

	/* elementIDs:[Input] 
	 * 		ID of target TextArea fields for TinyMCE editor.
	 *		Multiple IDs can be accepted with comma delimiters.
	 *		Will be input to the global valiable tinyMCE_elements.
	 */
	if (elementIDs.length == 0) return;
	tinyMCE_elements = elementIDs;
	
	tinyMCE.init(
	{
		mode : "exact",
		elements : elementIDs,
		width : "100%",
		theme : "advanced",
		//plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups",
		plugins : "iespell,insertdatetime,preview,paste,template",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,forecolor,backcolor,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,insertdate,inserttime,iespell,|,cleanup,help,code",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		valid_elements : "*[*]",
		
		setup : function(ed) {
			ed.onBeforeSetContent.add(
				function(ed, o) {
					o.content = tinyCleanContent(o.content);
				}
			);
		}
	}
	);
}

function tinyGetContent() {
	if (tinyMCE_elements.length == 0) return;
	var elements = tinyMCE_elements.split(",");
	for (var key in elements) {
		//tinyMCE.get(elements[key]).setContent(tinyCleanContent(elements[key]));
		document.getElementById(elements[key]).value = tinyMCE.get(elements[key]).getContent();
	}
}

function tinyCleanContent(content) {
	/* Filters that TinyMCE cannot handle */
	content = content.replace(/<font=[^>]*>/im, "");
	
	return content;
}



