

////////////////////////////////////////////////////////////
//
//  class CWebAppMgr
//
//  the main class for this web page
//  NB should only be one instance of this class!!
//



function CWebAppMgr()
{
    ////////////////////////////////////////////////////////////
    //
    //  attributes
    //


    //
    //  error codes from web services

    this.ERROR_NO_PERMISSION = 1100;



    this.szLicId = "";
    this.szLicTitle = "";

    this.debug = false;
    this.debugRegionTrace = false;

    this._bInMapDiv = false;

    this._topDivId = '#header';
    this._bottomDivId = '#bottomMenu';
    this._loadingDivId = '#topMenu p.loading';



    ////////////////////////////////////////////////////////////
    //
    //  methods
    //


    ////////////////////////////////////////////////////////////
    //
    //  onPageLoad()
    //
    //  called as a jQuery().ready function - which means 'this' is
    //  not gWebAppMgr!!!!! beware!!!
    //

    CWebAppMgr.prototype.onPageLoad =
        function()
        {
            //  parse GET params
            gWebAppMgr.debug = CPsWindowMgr.getURLParam('_debug2');
            gWebAppMgr.debugRegionTrace = CPsWindowMgr.getURLParam('_debugRegionTrace');


            //  we want to know when the mouse enters and leaves the map div
            jQuery('#map').hover(CWebAppMgr.prototype.onMapDivHoverEnter, CWebAppMgr.prototype.onMapDivHoverLeave);

            //  set popups to desired showing opacity before hiding
            //  so we can do simple fadeOut() and fadeIn() on the jQuery() object
            //  TODO - firefox displays text shittily at < 100% alpha
            jQuery('#projectPopup').css('opacity', 0.80).hide();
            jQuery('#storyPopup').css('opacity', 0.80).hide();
            jQuery('#breadcrumb').hide();


            //  handle window resize - we have to layout div's to fit browser window
            //  at all times
            window.onresize = CWebAppMgr.prototype.onResize;
            window.onresize();

            //  login form
            gWebAppMgr.manageLoginForm();

            //  wait before loading map to give user some visual feedback
            setTimeout(
                // have to preserve "this" for gMapMgr.loadMap
                function()
                {
                    gMapMgr.loadMap();
                },
                500);
        };

    CWebAppMgr.prototype.onPageUnload =
        function()
        {
            GUnload();
        };

    CWebAppMgr.prototype.onResize =
        function()
        {
            //  place and size the menus and map now - we have to position the map and bottom menu
            //  absolutely to get them where we want 'em
            var $map = jQuery('#map');
            var $top = jQuery(gWebAppMgr._topDivId);
            var nTopHgt = $top ? parseInt($top.css('height')) : 0;
            if (isNaN(nTopHgt))
            {
                nTopHgt = 0;
            }
            var $bottom = jQuery(gWebAppMgr._bottomDivId);
            var nBottomHgt = $bottom ? parseInt($bottom.css('height')) : 0;
            if (isNaN(nBottomHgt))
            {
                nBottomHgt = 0;
            }

            // need the teensy '-2' o/w we get scrollbars...
            var nMapHgt = CPsWindowMgr.height() - nTopHgt - nBottomHgt - 2;

            //  adjust position and height of map and bottom menu DOM elements
            $map.css({'top' : nTopHgt+'px', 'height' : nMapHgt+'px'});
            $bottom.css('top', nTopHgt+nMapHgt+'px');

            //  we need to tell google maps that its size has changed, so it does its tiling correctly
            //  nb, set off a timer to do this as it may take a short amount of time for the map height change
            //  to 'take effect'
            gMapMgr.checkResize();
        };

    CWebAppMgr.prototype.onMapDivHoverEnter =
        function(event)
        {
            gWebAppMgr._bInMapDiv = true;
        };

    CWebAppMgr.prototype.onMapDivHoverLeave =
        function(event)
        {
            gWebAppMgr._bInMapDiv = false;
        };

    CWebAppMgr.prototype.isInMapDiv =
        function()
        {
            return this._bInMapDiv;
        };


    CWebAppMgr.prototype.getMapDivHgt =
        function()
        {
            //  place and size the menus and map now - we have to position the map and bottom menu
            //  absolutely to get them where we want 'em
            var $map = jQuery('#map');
            var $top = jQuery(gWebAppMgr._topDivId);
            var nTopHgt = $top ? parseInt($top.css('height')) : 0;
            var $bottom = jQuery(gWebAppMgr._bottomDivId);
            var nBottomHgt = $bottom ? parseInt($bottom.css('height')) : 0;

            // need the teensy '-2' o/w we get scrollbars...
            return CPsWindowMgr.height() - nTopHgt - nBottomHgt - 2;
        };


    CWebAppMgr.prototype.getMapDivWid =
        function()
        {
            return CPsWindowMgr.width();
        };


    CWebAppMgr.prototype.setLoadingMsg =
        function(szMsg, nImg)
        {
            szMsg = szMsg == undefined ? "loading data" : szMsg;
            nImg = nImg == undefined ? 2 : nImg;

            var szImage = "";
            var nImgWid = 0;
            var nImgHgt = 0;
            var szDir = "/webcommon/images/common/";

            switch (nImg)
            {
            case 1:
                szImage = szDir + "loading1.gif";
                nImgWid = 16;
                nImgHgt = 16;
                break;
            case 2:
                szImage = szDir + "loading2.gif";
                nImgWid = 20;
                nImgHgt = 20;
                break;
            default:
                return;
            }

            var $kids = jQuery(gWebAppMgr._loadingDivId).children();
            if (!$kids)
            {
                return;
            }
            $kids.filter('img').attr( { src: szImage, width: nImgWid + 'px', height: nImgHgt + 'px' });
            $kids.filter('span').text(szMsg);
        };

    CWebAppMgr.prototype.clearLoadingMsg =
        function()
        {
            var $kids = jQuery(gWebAppMgr._loadingDivId).children();
            $kids.filter('img').attr( { src: '', width: '', height: '' } );
            $kids.filter('span').text('');
        };


    CWebAppMgr.prototype.setLicInfo =
        function(szLicId, szLicTitle)
        {
            this.szLicId = szLicId;
            this.szLicTitle = szLicTitle;
        };


    ////////////////////////////////////////////////////////////
    //
    //  manageLoginForm()
    //
    //  manage the login form and its effects
    //

    CWebAppMgr.prototype.manageLoginForm =
        function()
        {
            this.displayLoginInfo();

            jQuery('#loginForm').jqm(
                {
                    trigger:    'a.login',
                    modal:      true,
                    onShow:     function(h) {

                                    //  set the login text
                                    //jQuery('#loginForm > h3').html('Please enter your login details for the <span class=\'licence\'>"' + gWebAppMgr.szLicTitle + '"</span> community.');
                                    jQuery('#loginForm > h3').html('Please enter your login details for the PlaceStories System.');

                                    //  reset fields to empty
                                    var domLogin = jQuery('#loginForm .fldLogin')[0];
                                    domLogin.value = '';
                                    jQuery('#loginForm .fldPasswd')[0].value = '';

                                    //  reset error text to empty
                                    jQuery('#loginForm .error').text('');

                                    //  fade dialog in, then focus on login field
                                    h.w.fadeIn(400, function() {
                                        domLogin.focus();
                                    });
                                },
                    onHide:     function(h) {
                                    h.o.fadeOut(200);
                                    h.w.fadeOut(400);
                                },
                    overlay:    50
                }
            );

            jQuery('#loginForm .btnok').click(function() {

                jQuery('#loginForm').css('cursor', 'wait');

                szUrl = '/services/web_user_login' +
                                        '?lic=' + gWebAppMgr.szLicId +
                                        '&u=' + jQuery('#loginForm .fldLogin')[0].value +
                                        '&p=' + hex_md5(jQuery('#loginForm .fldPasswd')[0].value) +
                                        '&format=json' + 
                                        '&t=' + (new Date().getTime());

                jQuery.ajax({

                    url:        szUrl,

                    dataType:   'json',

                    success:    function(oJSON) {
                                    jQuery('#loginForm').css('cursor', 'default');
                                    if (oJSON.result != 'success')
                                    {
                                        jQuery('#loginForm .error').text('Error: ' + oJSON.reason);
                                        return;
                                    }

                                    var user = oJSON.user;
                                    var token = user.token;
                                    var name = user.name;
                                    var loginname = user.loginName;
                                    var role = user.role;
                                    gPsLoginMgr.setUser(token, name, loginname, role);

                                    jQuery('#loginForm').jqmHide();
                                    gWebAppMgr.displayLoginInfo();
                                    gMapMgr.refreshDataForCurrentView();
                                },

                    error:      function(XMLHttpRequest, textStatus, errorThrown) {
                                    jQuery('#loginForm').css('cursor', 'default');
                                    jQuery('#loginForm .error').text('HTTP Error: ' + textStatus);
                                    jQuery('#loginForm .fldLogin')[0].focus();
                                }
                });
            });

            jQuery('#loginForm .btncancel').click(function() {
                jQuery('#loginForm').jqmHide();
            });



            jQuery('a.logout').click(function() {

                function finishLogout(success, msg)
                {
                    if (!success)
                    {
                        alert('failed: ' + msg);
                    }
                    gPsLoginMgr.logout();
                    gWebAppMgr.displayLoginInfo();
                    gMapMgr.refreshDataForCurrentView();
                }


                //
                //  tell web server we are logging out...

                szUrl = '/services/web_user_logout' +
                            '?format=json' +
                            '&t=' + (new Date().getTime());

                jQuery.ajax({
                    url:        szUrl,
                    dataType:   'json',
                    success:    function() { finishLogout(true); },
                    error:      function(XMLHttpRequest, textStatus, errorThrown) { finishLogout(false, textStatus); }
                });

            });
        };


    ////////////////////////////////////////////////////////////
    //
    //  dispayLoginInfo
    //
    //  displays the right div for the current login info
    //

    CWebAppMgr.prototype.displayLoginInfo =
        function()
        {
            if (gPsLoginMgr.isLoggedOn())
            {
                jQuery('#notloggedin').hide();
                jQuery('#loggedin').show();
                jQuery('#loggedin .name').text(gPsLoginMgr.getLoginName());
                var strRole = gPsLoginMgr.getRole();
                jQuery('#loggedin .role').text('(' + (strRole ? strRole : 'normal user') + ')');
            }
            else
            {
                jQuery('#notloggedin').show();
                jQuery('#loggedin').hide();
            }
        };

};

//
//  init WebAppMgr global var

var gWebAppMgr = new CWebAppMgr();
jQuery().ready(gWebAppMgr.onPageLoad);

