var $D = YAHOO.util.Dom, //
 $C = $D.getElementsByClassName, //
 $E = YAHOO.util.Event, //
 $CONN = YAHOO.util.Connect, //
 $ = YAHOO.util.Dom.get, //
 $LANG = YAHOO.lang, //
 $J = YAHOO.lang.JSON, //
 sString = 'some text', //
 $W = YAHOO.widget, //
 $L = YAHOO.log, //
 o1 = {}, //
 SharedlogException = function(message, exceptionName){
    this.message = message;
    this.name = exceptionName || "SharedlogException";
}, //
 oAjaxObject = {
    handleSuccess: function(o){
        //alert('got something');
        // This member handles the success response
        // must determine what the result is for:
        // can be for doc or tpl or can be a text with css
        // we should test the returned text which should always be a JSON object
        var json, sDoc, sTpl, //
 eLogin = $("nbar"), //
 strContentType = $LANG.trim(o.getResponseHeader["Content-Type"]);
        //alert(strContentType);
        switch (strContentType) {
            case 'text/json; charset=UTF-8':
                try {
                    json = $J.parse(o.responseText);
                //alert(json);
                } 
                catch (e) {
                    alert("Invalid json data in responceText " + $LANG.dump(e) + " strContentType " + strContentType + "\noRespnose: " + $LANG.dump(o.responseText));
                }
                
                switch (true) {
                    case json.hasOwnProperty('error'):
                        oSL.setLoginError(json.error);
                        // alert(json.error);
                        /*
                 
                 if (oSL.eErrTd) {
                 $D.setStyle(oSL.eErrTd, "backgroundColor", "#FFFFCC");
                 //alert(eErrTd.innerHTML + "\n" + json.error);
                 oSL.eErrTd.innerHTML = json.error;
                 oSL.fColorChange(oSL.eErrTd, '#FFFFFF', '#FF0000');
                 $('go').disabled = false;
                 }
                 else {
                 alert(json.error);
                 }
                 */
                        break;
                        
                    case json.hasOwnProperty('redirect'):
                        window.location.assign(json.redirect);
                        break;
                        
                    case json.hasOwnProperty('navbar'):
                        oSL.fMakeNavBar(json);
                        break;
                        
                    case json.hasOwnProperty('message'):
                        eLogin.innerHTML = json.message;
                        //oSL.fColorChange(eLogin, '#00FF00', '#FFFFFF');
                        break;
                        
                }
                
        }
    },
    handleFailure: function(o){
        alert($LANG.dump(o));
    }
}, //
 oSL = {
    toString: function(){
        return 'object oSL';
    },
    oCallback: {
        success: oAjaxObject.handleSuccess,
        failure: oAjaxObject.handleFailure,
        scope: oAjaxObject
    },//
    fAddIcon: function(s, b){
        var el = (typeof(s) === 'string') ? $(s) : s;
        
        if (!this.eLoader) {
            this.eLoader = document.createElement("img");
            this.eLoader.src = '/images/ajax-loader.gif';
            this.eLoader.id = "loadericon";
        }
        //$L("314 el: " + el + " oEditor.eLoader: " + oEditor.eLoader, "user");
        if (this.eLoader) {
            if (b && b === true) {
                el.innerHTML = '';
            }
            
            el.appendChild(this.eLoader);
            
        }
    }, //
    /**
     * Compares 2 HTML form Dom nodes
     *
     * @param {Object} oNewForm a new HTML form, usually the one use tries to submit
     * @param {Object} oOldForm an old HTML form,
     * usually the one with default values (valued when page first loaded)
     * @return boolean true if at least one of new form's values is different
     * from the same one in old form or if the new form has a form element
     * that is not present in the old form.
     */
    fCompareForms: function(oNewForm, oOldForm){
        $L($CONN.setForm(oNewForm));
        $L($CONN.setForm(oOldForm));
        
        if ($CONN.setForm(oNewForm) === $CONN.setForm(oOldForm)) {
            return true;
        }
        
        return false;
    },//
    /**
     * Use color animation to change background-color
     * of an element slowly from one color to a new color,
     * then back to sFromColor, then set backgroundColor to its
     * original (the one before this function)
     * This can be used to display changes or
     * to attract attention to some message inside a div
     * like to a new error message.
     *
     * @param {Object} el
     * @param {Object} sToColor
     */
    fColorChange: function(el, sFromColor, sToColor){
        $L('starting fColorChange for ' + el);
        var myChange, curBg, myChangeBack, //              
 element = (typeof el === 'string') ? $(el) : el, //
 sToColor = (sToColor && typeof sToColor === 'string') ? sToColor : '#FF0000', //
 sFromColor = (sFromColor && typeof sFromColor === 'string') ? sFromColor : '#FFFFFF';
        
        $L('element is: ' + element);
        
        if (element) {
        
            curBg = $D.getStyle(element, 'background-color');
            $D.setStyle(element, 'background-color', sFromColor);
            myChange = new YAHOO.util.ColorAnim(element, {
                backgroundColor: {
                    to: sToColor
                }
            });
            
            /**
             * Change the background back to
             * what if was before the animation started
             */
            myChangeBack = function(){
                element.style.backgroundColor = curBg;
            }
            
            myChange.onComplete.subscribe(myChangeBack);
            myChange.animate();
            
        }
    }, //
    fMakeMeNav: function(id, o){
    
        // return true; // for testing without navbar just return here
        var oMerged = null;
        if (o && o.merged) {
            oMerged = o.merged;
        }
        
        $L('101 starting fMakeMeNav ' + id);
        //var id = 'menav';
        var elMenav = $(id);
        $L('104 elMenav ' + elMenav);
        if (elMenav == 'undefined' || null === elMenav) {
            return true;
        }
        
        var elParent = elMenav.parentNode;
        var elClone = elMenav.cloneNode(true);
        elParent.innerHTML = '';
        var nRoot = $('nbar');
        nRoot.appendChild(elClone);
        
        o1.oMenu = new $W.MenuBar(elClone, {
            position: "static",
            autosubmenudisplay: true,
            hidedelay: 550,
            lazyload: false
        });
        o1.oMenu.render();
        this.makeSwitchMenu(oMerged);
        
    }, //
    fMakeNavBar: function(o){
        var sHTML = o.navbar,//
 eNavBar = $('nbar');
        if (!eNavBar) {
            return false;
        }
        if (o1 && o1.oMenu) {
            o1.oMenu.destroy(); // this also destroys menav div element itself
        }
        
        eNavBar.innerHTML = sHTML;
        this.fMakeMeNav('menav', o);
    }, //
    fGetErrTd: function(){
        this.eErrTd = $("titleWarning");
        return this.eErrTd;
    }, //
    setLoginError: function(message){
    
        if (this.eErrTd) {
            $D.setStyle(oSL.eErrTd, "backgroundColor", "#FFFFCC");
            this.eErrTd.innerHTML = message;
            this.fColorChange(oSL.eErrTd, '#FFFFFF', '#FF0000');
            $('go').disabled = false;
        }
        else {
            alert(json.error);
        }
    }, //
    validateLogin: function(oFrm){
        if (oFrm && oFrm.elements) {
            for (var element in oFrm.elements) {
                var fElement = oFrm.elements[element];
                if (fElement && fElement.name) {
                    var elName = oFrm.elements[element].name;
                    if (elName === 'login' || elName === 'pwd') {
                        if ('' === fElement.value) {
                            fElement.style.borderWidth = "2px";
                            fElement.style.borderStyle = "solid";
                            fElement.style.borderColor = "#FF0000";
                            if (oFrm.elements['r']) {
                                this.setLoginError(oFrm.elements['r'].value);
                            }
                            return false;
                        }
                        else {
                            fElement.style.borderWidth = '';
                            fElement.style.borderStyle = '';
                            fElement.style.borderColor = '';
                        }
                    }
                }
            }
        }
        
        return true;
    },//   
    fLogin: function(o){
        var target = $E.getTarget(o), //
 errTd = oSL.fGetErrTd(), //
 formObject = $("frmLogin");
        
        if (target && target.type && formObject &&
        target.type.toLowerCase() === 'submit') {
        
            $E.stopEvent(o);
            
            if (oSL.validateLogin(formObject)) {
                target.disabled = true;
                if (errTd) {
                    oSL.fAddIcon(errTd);
                }
                $CONN.setForm(formObject);
                // This example facilitates a POST transaction.
                // An HTTP GET can be used as well.
                $CONN.asyncRequest("POST", "/index.php", oSL.oCallback, "ajax=1");
            }
        }
        else {
            if (target.nodeName &&
            target.nodeName.toLowerCase() === 'a' &&
            target.href.toLowerCase().match('logout')) {
                $E.stopEvent(o);
                target.href = '#';
                oSL.fAddIcon(target);
                
                /*
                 * resetFormState() is very important because
                 * if the page has had another setForm() ran
                 * for a different form, the $CONN will still
                 * be configured with a different form object
                 */
                $CONN.resetFormState();
                $CONN.asyncRequest("GET", "/index.php?a=logout&ajax=1", oSL.oCallback);
            }
        }
        
    },//
    fMakeLangSelect: function(id){
        /*
         
         var oSplitButton1 = new $W.Button("splitbutton1", {
         type: "split",
         menu: "splitbutton1select"
         });
         }
         */
        $E.onAvailable(id, function(){
            if ($('splitbutton1')) {
                var oSplitButton1 = new $W.Button("splitbutton1", {
                    type: "split",
                    menu: "splitbutton1select"
                });
            }
        });
    }, //
    /**
     * Closure based object constructor
     * do NOT use 'new' to instantiate!
     *
     * @param {Object} o
     */
    oSwitcharoo: function(o){
    
        /**
         * Upon calling this constructor
         * validate the input object
         * and may throw SharedlogException
         * if object is missing
         * some expected elements
         */
        this.validateParsed(o);
        
        /**
         * These vars will be private
         * through closure:
         * any function of returned object
         * will have access to these
         * but they cannot be accessed directly
         * no can they be changed directly
         */
        var oUsers = o.users, //
 sMenuId = "switcmenu1", //
 sSwitchItemId = "switcher1", //
 sPostUrl = '/index.php', //
 sLabel = o.sLabel;
        $L('361 oUsers: ' + $LANG.dump(oUsers));
        
        var oRet = {
            toString: function(){
                return 'Switcharoo object'
            },//
            onMenuItemClick: function(p_sType, p_aArgs, p_oValue){
                $CONN.asyncRequest('POST', oSL.oS.getPostUrl(), oSL.oCallback, oSL.oS.makeFormParams(p_oValue));
            },//
            getMenuId: function(){
                return sMenuId;
            },//
            getSwitchItemId: function(){
                return sSwitchItemId;
            },//
            getPostUrl: function(){
                return sPostUrl;
            },//
            getUid: function(sUsername){
                for (var uid in oUsers) {
                    if (oUsers[uid] === sUsername) {
                        return uid;
                    }
                }
                
                return null;
            },//
            makeFormParams: function(uid){
                //var uid = this.getUid(sUsername);
                if (!uid) {
                    throw new SharedlogException('userid not found for this username: ' + sUsername);
                }
                
                return 'qf_version=' + o.qf_version + '&a=' + o.a + '&uid=' + uid;
            }, //
            getA: function(){
                return o.a;
            },//
            getToken: function(){
                return o.qf_version;
            },//
            getSwitchText: function(){
                return sLabel;
            },//
            getUsersArray: function(){
                var oMyUser, aMyUsers = [];
                for (var id in oUsers) {
                    oMyUser = {
                        text: oUsers[id],
                        onclick: {
                            fn: oSL.oS.onMenuItemClick,
                            obj: id
                        }
                    };
                    aMyUsers.push(oMyUser);
                }
                
                return aMyUsers;
            }
        }
        
        return oRet;
    },//
    makeSwitchMenu: function(o){
        try {
            if (!o || (o === null)) {
                var o = this.parseSwitchForm();
                $L('397 o: ' + $LANG.dump(o));
            }
            else {
                $L('418 o: ' + $LANG.dump(o));
            }
            if (this.oS) {
            
                // delete (this['oS']);
            }
            this.oS = this.oSwitcharoo(o);
        } 
        catch (e) {
            $L("424 Caught error: " + e.message, "error");
            return false;
        }
        
        
        //$L('412 items: ' + $LANG.dump(this.oS.getMenuItems()) + ' messenger uid: ' + this.oS.getUid('messenger'));
        /**
         * check if oMenu exists,
         * if it has menu oWelcome
         * if oWelcome already has item with id 'switcharoo'
         * then remove it (along with sub-menu)
         * append item with id 'switcharoo' and submenu
         * find the newly created item object and subscribe
         * it to onClick event
         */
        if (o1 && o1.oMenu) {
            $L('489 starting this is ' + this);
            
            var oSwitchMenu, oMenuBar = o1.oMenu; // , oMyMenu = this.oS.getMenuObject()
            $L('493');
            var aItems = oMenuBar.getItems();
            $L('495');
            var oWelcomeMenu = aItems[0].cfg.getProperty("submenu");
            $L('497');
            var aMyUsers = this.oS.getUsersArray();
            $L('499 aMyUsers: ' + $LANG.dump(aMyUsers));
            var sSubId = this.oS.getMenuId();
            $L('501 sSubId ' + sSubId);
            var oSub1 = new $W.Menu(sSubId);
            var sLabelText = this.oS.getSwitchText();
            $L('504 sLabelText ' + sLabelText);
            var sMyItemId = this.oS.getSwitchItemId();
            oSub1.addItems(aMyUsers);
            
            $L('487: ' + oSub1);
            
            oWelcomeMenu.insertItem({
                id: sMyItemId,
                text: sLabelText
            }, 0);
            /**
             * oSwitchMenu is not the first menuItem
             * in the welcom menu
             */
            oSwitchMenu = oWelcomeMenu.getItem(0);
            
            oSwitchMenu.cfg.setProperty("submenu", oSub1);
            oWelcomeMenu.render();
            
        }
    }, //
    validateParsed: function(oRes){
        if (!oRes.a || !oRes.qf_version || !oRes.sLabel || !oRes.users) {
            throw new SharedlogException('Not all required elements found in form');
        }
    }, //
    parseSwitchForm: function(){
        var sLabel, sName, sType, elParent, sQfv, oRes = {}, oUsers = {}, bUser = false, oFrm = $('fSwitch');
        if (!oFrm || !oFrm.elements) {
            throw new SharedlogException('Form "fSwitch" not found in document');
        }
        
        elParent = oFrm.parentNode;
        $L('545 form parent: ' + elParent);
        /**
         * Now can remove actual form
         * from the page
         */
        if (elParent) {
            elParent.removeChild(oFrm);
        }
        
        for (var element in oFrm.elements) {
            var fElement = oFrm.elements[element];
            if (fElement) {
                sName = fElement.name;
                sType = fElement.type;
                if ((sName) && (sName === 'a' || sName === 'qf_version')) {
                    oRes[sName] = fElement.value;
                }
                if (fElement.type === 'submit') {
                    oRes['sLabel'] = fElement.value;
                }
                if (sName === 'amerged' && fElement.options) {
                    $L('399 num options: ' + fElement.options.length);
                    for (var i = 0; i < fElement.options.length; i++) {
                        var oOption = fElement.options[i];
                        if (oOption.value && oOption.text) {
                            bUser = true;
                            oUsers[oOption.value] = oOption.text;
                        }
                    }
                    if (bUser) {
                        oRes['users'] = oUsers;
                    }
                }
            }
        }
        
        this.validateParsed(oRes);
        $L('414 oRes: ' + $LANG.dump(oRes));
        
        return oRes;
    },//
    makeHomeTabs: function(){
        var rootdiv1 = $("mybody");
        if (rootdiv1 == "undefined") {
            alert('no element "mybody"');
        };
        
        var recentHTML = rootdiv1.innerHTML;
        
        rootdiv1.innerHTML = "";
        $L('537 rootdiv1: ' + rootdiv1);
        var navblock = $("navBlock");
        if (navblock == "undefined") {
            alert('no element "navBlock"');
        }
        $L('542 navblock: ' + navblock);
        
        var aLinks = navblock.getElementsByTagName("a");
        var tabView = new $W.TabView();
        $L('546 tabView: ' + tabView);
        
        for (var i = 0; i < aLinks.length; i++) {
            var sTitle = aLinks[i].getAttribute("title");
            // if aLinks[i].getAttribute("href") has ? then separate by &, else by ?
            var href = aLinks[i].getAttribute("href");
            var separator = (href.search(/\?/) > 0) ? "&" : "?";
            var sHref = href + separator + "do=home";
            
            if (i === 0) {
                tabView.addTab(new $W.Tab({
                    label: sTitle,
                    content: recentHTML,
                    active: true
                }));
            }
            else {
                tabView.addTab(new $W.Tab({
                    label: sTitle,
                    dataSrc: sHref,
                    cacheData: true,
                    active: false
                }));
            }
            
        }
        $L('570 tabView: ' + tabView);
        navblock.innerHTML = "";
        tabView.appendTo("mybody");
    }, //
    validateTos: function(frm, errMsg){
        var value = '', errFlag = [], qfGroups = {}, _qfMsg = '', value = frm.elements['terms'].checked ? '1' : '';
        
        if (value == '' && !errFlag['terms']) {
            errFlag['terms'] = true;
            _qfMsg = _qfMsg + '\n' + errMsg + '\n';
        }
        
        if (_qfMsg != '') {
            alert(_qfMsg);
            return false;
        }
        return true;
    }
    
    
}, //
 doExit = function(){
    alert("somethig wrong");
    return;
}, //
 /*
 myLogReader = new $W.LogReader(),
 */
//

set_tbl_new = function(){

    var obj1 = document.getElementById('tblNew');
    //
    if (typeof obj1 != 'undefined') {
        //
        if (obj1.style.display == "none") {
            obj1.style.display = "block";
            //alert(1);
        }
        else {
            obj1.style.display = "none";
            //alert(2);
        }
        
    }
    
};

oSL.fMakeLangSelect('langForm');
/*
 $E.onAvailable('menav', function(){
 oSL.fMakeMeNav('menav');
 });
 */
$E.onDOMReady(function(){
    oSL.fMakeMeNav('menav'); // making this onAvailable results in rendering menu twice when loaded by ajax
    $E.addListener('nbar', "click", oSL.fLogin);
    // oSL.fShowMenu();
});

