// -------------------------------------------------------------------
// Copyright 2008 Long Term Results B.V., Valkenswaard, The Netherlands.
// All rights reserved. Reproduction or dissemination in whole or in
// part is prohibited without the written consent of the copyright
// holder.
// -------------------------------------------------------------------
//
// amh.js
//
// This scripts contains functions that are
// used on the www.alphamegahosting.com website
//
// -------------------------------------------------------------------

/**
 * @namespace The AMH object is the namespace all the future js on the Alphamega Hosting site.
 */
var AMH = {};

// The AMH.site object is the namespace for the common functions
/**
 * @namespace The AMH.site object is the namespace for the functions in this script
 */
AMH.site = {
        startdate : '20081027',
        livedate  : '20090720',
        version   : '0.1',
        loglines  : [],
        logmax    : 100,
        loglevel  : 'error',
        logcontid : 'amhsitelog',
        logcontobj: null,
        logtoconsole      : false,
        logstate          : false,
        cookie_default_id : 'amh823746',
        dialogcontainer   : {}
};
// ###################################################################

AMH.site.pushlog = function (level, message) {
    // level can be error|warn|info|debug
    if (AMH.site.logtoconsole === true) {
        console.log (level, message);
    }
    if (message === null || typeof(message)=='undefined') {
        message = level;
        level=AMH.site.loglevel;
    }

    // the objectToString methode might cause more trouble than it is worth
    // var strmessage = AMH.site.objectToString(message, 0);
    var strmessage = message.toString();

    if ( strmessage.length > 255 ) {
        strmessage = strmessage.slice(0,255);
    }
    AMH.site.loglines.push({ level: level, message: strmessage});
    if (AMH.site.loglines.length > AMH.site.logmax) {
        AMH.site.loglines.shift();
    }
    if (typeof(AMH.site.logcontobj)=='object' && AMH.site.logcontobj!==null) {
        var logstring = '';
        for (var i in AMH.site.loglines) {
            if (typeof(AMH.site.loglines[i])=='object') {
                logstring += AMH.site.loglines[i].message + '<br>';
            }
        }
        if (typeof(AMH.site.logcontobj)=='object') {
            AMH.site.logcontobj.innerHTML = logstring;
        }
    }
};

// This seems a bit more intuitive
AMH.site.log = AMH.site.pushlog;

// ###################################################################

AMH.site.objectToString = function (a, r) {
    recursiveCount     = r + 1;
    recursiveDelimeter = '== recursive limit ==';
    if (a === null) { return null; }
    if (typeof(a) == 'undefined' ) { return 'undefined'; }
    if (typeof(a) == 'function') { return "Function"; }
    if (typeof(a) == 'object') {
        var c = '';
        if (recursiveCount > 3) { return recursiveDelimeter; }
        if (recursiveCount < 2) { c = 'Object: '; }
        for (var keyname in a) {
            if (a[keyname]) {
                var value = AMH.site.objectToString(a[keyname], recursiveCount);
                if (value==recursiveDelimeter) { value ='[object]'; }
                d = "[" + keyname + "=" + value + "]";
                c = c + d + '; ';
            }
        }
        return (c.replace(/</g, "&gt;")).replace(/>/g, "&lt;");
    }
    return a + "\n";
};

// ###################################################################

AMH.site.showlog = function () {
    if (AMH.site.logcontobj===null) {
        AMH.site.logcontobj = document.getElementById(AMH.site.logcontid);
        if (AMH.site.logcontobj===null) {
            var element = document.createElement("div");
            element.setAttribute('id', AMH.site.logcontid);
            document.getElementsByTagName('body')[0].appendChild(element);
            AMH.site.logcontobj = document.getElementById(AMH.site.logcontid);
        }
    }
    AMH.site.logcontobj.style.position = 'absolute';
    AMH.site.logcontobj.style.right = '10px';
    AMH.site.logcontobj.style.top = '40px';
    AMH.site.logcontobj.style.width = '280px';
    AMH.site.logcontobj.style.height = '280px';
    AMH.site.logcontobj.style.backgroundColor = '#eee';
    AMH.site.logcontobj.style.textAlign = 'left';
    AMH.site.logcontobj.style.overflowY = 'scroll';
    AMH.site.logcontobj.style.border = '1px solid #999';
    AMH.site.pushlog('debug', 'showlog is On');
};

// ###################################################################

AMH.site.parameters = function () {
    // returns an object with a key/value hash
    var a={};
    var p=location.search.substring(1).split("&");
    for(var i=0;i<p.length;i++){
        var x=p[i].indexOf('=');
        if(x == -1) { continue; }
        a[p[i].substring(0,x)]=unescape(p[i].substring(x+1));
    }
    return a;
};

// ###################################################################

AMH.site.addToDom = function (a) {
    // a is an object with parameters: tagName, container, [id], [className]
    var newEl = document.createElement(a.tagName);
    if (a.id) { newEl.id = a.id; }
    if (a.className) { newEl.className = a.className; }
    var containerEl;
    if (typeof(a.container) == 'string' && containter.length>0) {
        containerEl = document.getElementById(a.container);
    }
    else if (typeof(a.container)=='object') {
        containerEl = a.container;
    }
    containerEl.appendChild(newEl);
    if (typeof(newEl)!='object') { AMH.site.log('error','newEl'); }
    return newEl;
};

// ###################################################################

AMH.site.checkEmail = function (emailadress) {
    if (/^\w+([\.\-]?\w+)*@\w+([\.\-]?\w+)*(\.\w{2,3})+$/.test(emailadress)) { return (true); }
    return (false);
};

// ###################################################################

AMH.site.toolTip = function ( toolTipArgs ) {
    // syntax: AMH.site.toolTip({ context: targetId, text: 'Something to say'});
    // optional: { container: containerid|node }
    var toolTipId  = 'tooltipcontainer_' + toolTipArgs.context;
    var config = { context: toolTipArgs.context, text: toolTipArgs.text };
    if (toolTipArgs.container && typeof(toolTipArgs.container)=='string') { config.container = toolTipArgs.container; }
    var toolTipObj = new YAHOO.widget.Tooltip(toolTipId, config);
};

// ###################################################################

AMH.site.confirmationDialog = function ( dialogArgs  ) {
    // syntax: AMH.site.confimationDialog({ header: '', question: '', parentElement: node|element, buttons: [{text:'', handler:function(){}, isDefault:true|false }]});
    // TODO: this function will create new divs without cleaning up old ones... this should be addressed at some time.
    var dialogParent             = document.getElementsByTagName('body')[0];
    var dialogId                 = YAHOO.util.Dom.generateId('dialogContainer_');
    dialogArgs          = dialogArgs          || {};
    dialogArgs.header   = dialogArgs.header   || 'Bevestiging';
    dialogArgs.question = dialogArgs.question || 'Weet je het zeker?';
    dialogArgs.buttons  = dialogArgs.buttons  || [{text:'Ja',handler:function(){alert('Ja');}},{text:'Nee',handler:function(){alert('Nee');}}];
    if (dialogArgs.parentElement) {
        // console.log(dialogArgs.parentElement);
        if (typeof(dialogArgs.parentElement)==='object') { dialogParent = dialogArgs.parentElement; }
        if (typeof(dialogArgs.parentElement)==='string') {
            var potentialParent = document.getElementById(dialogArgs.parentElement);
            if (potentialParent) { dialogParent = potentialParent; }
        }
    }
    dialogArgs.handlers = [];
    for (var i=0; i<dialogArgs.buttons.length; i++) {
        dialogArgs.handlers[i] = dialogArgs.buttons[i].handler;
        dialogArgs.buttons[i].handler = function (fn) {
            return function () {
                this.hide();
                fn();
            };
        } ( dialogArgs.handlers[i] );
    }
    var dialogContainerObj = new YAHOO.widget.SimpleDialog(dialogId, {
        width: "200px",
        fixedcenter: true,
        visible: false,
        draggable: false,
        close: true,
        text: dialogArgs.question,
        icon: YAHOO.widget.SimpleDialog.ICON_HELP,
        constraintoviewport: true,
        buttons: dialogArgs.buttons
    });
    dialogContainerObj.setHeader(dialogArgs.header);
    // Render the Dialog
    dialogContainerObj.render(dialogParent);
    dialogContainerObj.show();
};

// ###################################################################

AMH.site.scrollToAnchor = function (anchorName) {
                var srcOffset=45;
                var myFocus = document.getElementsByName(anchorName)[0];
                var scrOfY = YAHOO.util.Dom.getY(myFocus) - srcOffset;
                window.scroll(0,scrOfY); // horizontal and vertical scroll targets
                return true;
};

// ###################################################################

// Popup-Window Script
// Version: 1.22
// Used for the informing popups throughout the alphamegahosting site

AMH.site.popwin = {};

AMH.site.popupwin = function (theURL,winname) {
    var agt=navigator.userAgent.toLowerCase();
    var is_mac = (agt.indexOf("mac")!=-1);
    if ((AMH.site.popwin) && (is_mac === false)) {
        if (AMH.site.popwin.closed === false) {
            AMH.site.popwin.close();
        }
    }
    ///// standard Features, don't change /////
    features = 'width=600,height=600,resizable=no,scrollbars=no,menubar=yes,toolbar=yes,directories=no,location=no,status=no,innerWidth=0,innerHeight=0';
    ///////////// window Settings /////////////
    // terms you can use: 'screenX=100,screenY=20,top=20,left=100,status=yes,scrollbars=yes,menubar=no,width=600,height=400,innerWidth=0,innerHeight=0,resizable=yes,toolbar=yes,directories=no,location=no';
    if (winname=='policy') { features = 'status=no,scrollbars=yes,menubar=no,width=600,height=600,dependent=yes,resizable=yes'; }
    if (winname=='guarantee') { features = 'status=no,scrollbars=yes,menubar=no,width=600,height=600,dependent=yes,resizable=yes'; }
    if (winname=='fileman') { features = 'status=yes,scrollbars=yes,menubar=no,width=600,height=400,innerWidth=0,innerHeight=0,resizable=yes,toolbar=yes,directories=no,location=no'; }
    if (winname=='movie') { features = 'status=no,scrollbars=no,menubar=no,width=400,height=400,dependent=yes,resizable=no'; }
    if (winname=='portable') { features = 'status=no,scrollbars=yes,menubar=no,width=640,height=480,dependent=yes,resizable=yes'; }
    if (winname=='image') { features = 'status=no,scrollbars=no,menubar=no,width=660,height=505,dependent=yes,resizable=no'; }
    ///////////////////////////////////////////
    AMH.site.popwin=window.open(theURL,winname,features);
};

// ###################################################################

AMH.site.menuAction = function (menuname, state) {
    // a function to let the mainmenu work with the webgui- and swiftysite toolbars
    // the parameters are basicly obsolete now... */

    var menuWebguiWidth     = 160;
    var menubarSwiftyHeight = 39;
    var menuStates = {};

    var webguimenus = YAHOO.util.Dom.getElementsByClassName('accordion-menu');
    var swifty      = document.getElementById('wMainMenu');
    var amh         = document.getElementById('wMainAMHMenu');

    /* To find out if the WebGUI accordion-menu is loaded,
       we will have to look for a dl with classname accordion-menu and
       find out if it is showing.
    */
    menuStates.webgui = (typeof(webguimenus) !== null && typeof(webguimenus[0])=='object') ? 'on' : 'off';
    menuStates.amh    = (document.getElementById('wMainAMHMenu'))                          ? 'on' : 'off';
    menuStates.swifty = (document.getElementById('wMainMenu'))                             ? 'on' : 'off';

    if (menuStates.amh == 'off') {
        AMH.site.log('debug', 'AMH.site.menuAction was exited because there is no div#wMainAMHMenu');
        return false;
    }

    if (menuStates.webgui == 'on') {
        amh.style.left    = menuWebguiWidth + 'px';
        document.getElementById('wMainAMHMenuInner').style.paddingRight = "160px";
    }
    else {
        amh.style.left    = '0';
        document.getElementById('wMainAMHMenuInner').style.paddingRight = "0";
    }

    if (menuStates.swifty == 'on') {
        // amh.style.marginTop = '39px';
        // amh.style.top = '39px';
        YAHOO.util.Dom.setStyle(amh, 'top', '39px')
    }
    return true;
};

// ###################################################################

AMH.site.menuStartupActions = function () {
    YAHOO.util.Event.onContentReady( "alphamegahostingmenu", function ()
        {
            var oMenuBar = new YAHOO.widget.MenuBar("alphamegahostingmenu",
                {
                    autosubmenudisplay : true,
                    showdelay          : 0,
                    hidedelay          : 750,
                    lazyload           : true,
                    minscrollheight    : 5000,
                    maxheight          : 4999
                }
            );
            oMenuBar.render();
            // a function to let the mainmenu work with the webgui- and swiftysite toolbars
            // YAHOO.util.Event.on(window, "load", AMH.site.menuAction);
        }
    );
};

// ###################################################################

if (AMH.site.parameters().log == 'true') {
    // todo: store the log state in the new to build user preferences
    AMH.site.showlog();
}

/////// functions that are used on the alphamegahosting.com site
///////     (placed outside the AMH namespace for backwards compatibility )
var scrollToAnchor = AMH.site.scrollToAnchor;
var popwin         = AMH.site.popwin;
var popupwin       = AMH.site.popupwin;

/////// The Startup actions for the alphamegahosting.com site
// BB: 20090526: moved to an alphamegahosting.com specific script
// AMH.site.menuStartupActions();

/////// swifty site scripts to help the template
if (typeof(amh_setFooterHeight)=='function') { amh_setFooterHeight(0,undefined,35); }

// YAHOO.util.Event.on(window, "load", function(){
//    if (typeof(amh_onLoad)=='function') { amh_onLoad(); }
// });

/////// get the username
YAHOO.util.Event.onContentReady( "wgUsername", function () {
        var wgUsernameEl = document.getElementById('wgUsername');
        if (wgUsernameEl !== null) {
            AMH.site.wgUsername = wgUsernameEl.innerHTML;
        }
});
