/*
* File: hotel.js
* Purpose: Provides suport functions for hotel pages
* 
* Last JSLint: 07/1/2009
* By: John Ware
* NOTE: Didn't fix everything, but started the process (127 warnings down to 26)
*

Functions:
iwin.
iwin.

TODO: Fill in

*/
/* JSLINT hinting */
/*global 
  Prototype, Ajax, Event, $, i$, $F, $$, PeriodicalExecuter
  pageTracker, 
  hideObj, showObj, console, 
  window, location, document */
  
  
// TODO: clear up window.external... calls

// If user try to leave the page with items still in your cart or with item-moves he
// made not yet saved, a Javascript warning appear and give him the chance
// to save things.
var UNLOAD_MSG = "You still have items in your shopping cart. Are you sure you want to leave?";
var isCartEmpty = true;


///////////////////////////////////////////////////////////////////////////////////////
///   callbacks   /////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////

if (!window.iwin) {
    var iwin = {};
}

if (!iwin.hotel) {
    iwin.hotel = {};
}

// init iwin.hotel.callbacks object
if (!iwin.hotel.callbacks) {
    iwin.hotel.callbacks = {};
}

// init iwin.hotel.utils object
if (!iwin.hotel.utils) {
    iwin.hotel.utils = {};
}

// init iwin.hotel.auth object
if (!iwin.hotel.auth) {
    iwin.hotel.auth = {};
}


///////////////////////////////////////////////////////////////////////////////////////
///   IWGM callbacks   ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////

// Update avatar in the IWGM after avatar is saving
iwin.hotel.callbacks.updateAvatar = function () {
    if (iwin.hotel.utils.isInArcade()) {
        window.external.UpdateAvatar(); 
    }
};

// Update opals in the IWGM 
iwin.hotel.callbacks.updateOpalsInfo = function () {
    if (iwin.hotel.utils.isInArcade()) {
        window.external.UpdateOpalsInfo();
    }
};

// Change cart state from client
iwin.hotel.callbacks.updateCart = function (status) {
   isCartEmpty = status;
};

// invoked from any flash, checks to see if sound is enabled
iwin.hotel.callbacks.isSoundEnabled = function () {
    if (iwin.hotel.utils.isInArcade()) {
        return iwin.Util.isSoundEnabled();
    } else {
        return true; // assume always enabled in regular browser
    }
};



///////////////////////////////////////////////////////////////////////////////////////
///   Hotel callbacks   ///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////

// opens new browser window
iwin.hotel.callbacks.openNewWindow = function (url) {
    if (iwin.hotel.utils.isInArcade()) {
        window.external.ArcadePopupShow("hotelWindow", url, 1024, 600);
    } else {
        window.open(url);
    }
}

// redirects window location to new url
iwin.hotel.callbacks.redirectWindow = function (url) {
    window.location = url;
};

// Opens up login window/popup
iwin.hotel.callbacks.openLogin = function () {
    // check to see if UI is constructed, otherwise build it
    
    // show the signin, defaults to slightly above center in the screen
    // iwin.AuthUI.Login.show('The page you are trying to access requires you to sign in.');
    iwin.AuthUI.Login.show('The page you are trying to access requires you to sign in.');
};

// opens up help window
iwin.hotel.callbacks.openHelp = function () {
    iwin.hotel.callbacks.redirectWindow("http://support.iwin.com");
};

// invoked from RoomBrowser, opens up specified user room
iwin.hotel.callbacks.openUserRoom = function (userName, floor) {
    var url = iwin.hotel.utils.getServerURL() + "/hotel?room=" + userName + "/" + floor;
    iwin.hotel.callbacks.redirectWindow(url);
};

// invoked from RoomBrowser, opens up hotel shop
iwin.hotel.callbacks.openShop = function (shop) {
    var url = iwin.hotel.utils.getServerURL() + "/hotel?shop=" + shop;
    iwin.hotel.callbacks.redirectWindow(url);
};

// invoked from Hotel, opens up RoomBrowser
iwin.hotel.callbacks.openRoomBrowser = function (menu) {
    var url = iwin.hotel.utils.getServerURL() + "/hotel/roombrowser?menu=" + ((menu === null || menu === "") ?"main" :menu);
    iwin.hotel.callbacks.redirectWindow(url);
};

// invoked from Hotel and RoomBrowser, opens up OnlineGames/ParadisRoom application
iwin.hotel.callbacks.openOnlineGames = function () {
    var url = iwin.hotel.utils.getServerURL() + "/hotel/onlinegames";
    iwin.hotel.callbacks.redirectWindow(url);
};

// invoked from Main Menu (RoomBrowser) and Top Menu, opens up iWin Forums
iwin.hotel.callbacks.openForums = function () {
    var url = iwin.hotel.utils.getServerURL() + "/forums";
    iwin.hotel.callbacks.redirectWindow(url);
};

// invoked from Top Menu, opens up Hotel Chat
iwin.hotel.callbacks.openChat = function () {
    var url = iwin.hotel.utils.getServerURL() + "/hotel/chat";

    //if (iwin.hotel.utils.isInArcade()) {
    //   window.external.ArcadePopupShow("hotelWindow", url, 1030, 725);
    //} else {
    //    window.open(url,'Hotel Live Chat',"width=1020,height=696,status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=yes");
    //}
    
    // temporary fix of Arcade's issue
    iwin.hotel.callbacks.redirectWindow(url);
};



///////////////////////////////////////////////////////////////////////////////////////
///   Hotel utils   ///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////

// Invoke when user leave the page
iwin.hotel.utils.doBeforeUnload = function () {
    if (isCartEmpty) {
        return; 
    }
    if (window.event) {
        window.event.returnValue = UNLOAD_MSG; // IE
    } else {
        return UNLOAD_MSG; // FX
    }
};

iwin.hotel.utils.isInArcade = function () {   
    try {
        return iwin.Util.isInArcade();
    } catch (err) {
        return false;
    }
};

// finds the swf browser independently
iwin.hotel.utils.getSwfObject = function (swfName) {
    if (navigator.appName.indexOf("Microsoft") !== -1) {
        return window[swfName];
    } else {
        return document[swfName];
    }
};

iwin.hotel.utils.getCurrentSwfObject = function () {
    if (iwin.hotel.utils.getSwfObject("HotelRoomBrowser")) {
        return iwin.hotel.utils.getSwfObject("HotelRoomBrowser");
    } else if (iwin.hotel.utils.getSwfObject("HotelIWin")) {
        return iwin.hotel.utils.getSwfObject("HotelIWin");
    } else if (iwin.hotel.utils.getSwfObject("OnlineGames")) {
        return iwin.hotel.utils.getSwfObject("OnlineGames");
    } else if (iwin.hotel.utils.getSwfObject("WheelOfOpalescence")) {
        return iwin.hotel.utils.getSwfObject("WheelOfOpalescence");
    }
    return null;
};

// returns current server url
iwin.hotel.utils.getServerURL = function () {
    return window.location.protocol + "//" + window.location.host;
};

// returns url parameter by name
iwin.hotel.utils.getParameter = function (param) {
    var result = iwin.Util.getUrlParameter(param);
    return (result === null) ?"" :result;
};

// builds the flash embed tag
iwin.hotel.utils.swfEmbedTag = function (swfName, baseUrl, userName, height, width) {
    // Major version of Flash required
    var requiredMajorVersion = 9;
    // Minor version of Flash required
    var requiredMinorVersion = 0;
    // Minor version of Flash required
    var requiredRevision = 115;

    if (typeof(swfName) !== "string") {
        // error and return
        console.error("swfEmbedTag called with invalid swfName: %s", swfName);
        return (false);
    }
    if (typeof(baseUrl) !== "string") {
        // error and return
        console.error("swfEmbedTag called with invalid baseUrl: %s", baseUrl);
        return (false);
    }
    if (typeof(userName) !== "string") {
        // error and return
        console.error("swfEmbedTag called with invalid userName, setting to empty: %s", userName);
        userName = ""; // not fatal, falling through
    }
    if (typeof(width) !== "number") {
        // error and return
        console.error("swfEmbedTag called with invalid width, setting to 1022: %s", height);
        width = 1022; // not fatal, falling through
    }
    if (typeof(height) !== "number") {
        // error and return
        console.error("swfEmbedTag called with invalid height, setting to 604: %s", height);
        height = 604; // not fatal, falling through
    }
    
    // Version check for the Flash Player that has the ability to start Player Product Install (6.0r65)
    var hasProductInstall = DetectFlashVer(6, 0, 65);
    // Version check based upon the values defined in globals
    var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
    
    // params which are passed to Flash
    var flashvars = "authToken=" + iwin.Util.readCookie("JSESSIONID") + 
                    "&userName=" + userName + 
                    "&serverURL=" + baseUrl + 
                    "&room=" + iwin.hotel.utils.getParameter("room") + 
                    "&shop=" + iwin.hotel.utils.getParameter("shop") + 
                    "&menu=" + iwin.hotel.utils.getParameter("menu");
    
    
    if (hasProductInstall  && !hasRequestedVersion) {
        // DO NOT MODIFY THE FOLLOWING FOUR LINES
        // Location visited after installation is complete if installation is required
        var MMPlayerType = (isIE === true) ? "ActiveX" : "PlugIn";
        var MMredirectURL = window.location;
        document.title = document.title.slice(0, 47) + " - Flash Player Installation";
        var MMdoctitle = document.title;
    
        AC_FL_RunContent(
            "src", "flash/player-product-install",
            "FlashVars", "MMredirectURL=" + MMredirectURL + '&MMplayerType=' + MMPlayerType + '&MMdoctitle=' + MMdoctitle + "",
            "width", width,
            "height", height,
            "align", "middle",
            "id", "asmovie",
            "quality", "high",
            "bgcolor", "#FFFFFF",
            "name", swfName,
            "allowScriptAccess", "always",
            "type", "application/x-shockwave-flash",
            "pluginspage", "http://www.adobe.com/go/getflashplayer",
            "wmode", "opaque"
        );
    } else {
        if (hasRequestedVersion) {
            // if we've detected an acceptable version
            // embed the Flash Content SWF when all tests are passed
            AC_FL_RunContent(
                    "src", swfName,
                    "width", width,
                    "height", height,
                    "align", "middle",
                    "id", "asmovie",
                    "quality", "high",
                    "bgcolor", "#FFFFFF",
                    "menu", "false",
                    "name", swfName,
                    "flashvars", flashvars,
                    "allowScriptAccess", "always",
                    "type", "application/x-shockwave-flash",
                    "pluginspage", "http://www.adobe.com/go/getflashplayer",
                    "wmode", "opaque"
            ); 
            //"flashvars","authToken=" + iwin.Util.readCookie("JSESSIONID") + "&userName=" + userName + "&serverURL=" + baseUrl + "&room=" + getParameter("room") + "&shop=" + getParameter("shop") + "&menu=" + getParameter("menu"),
        } else {  // flash is too old or we can't detect the plugin
            var alternateContent = 'This content requires the Adobe Flash Player. <a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
            document.write(alternateContent);  // insert non-flash content
        }
    }
};



///////////////////////////////////////////////////////////////////////////////////////
///   auth functions   ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////

// Observe Logout event

Event.observe(document, 'dom:loaded', function () {
    // login and logout, wait until after dom is loaded (and js)
    Event.observe(document, 'iwin:auth:login:success', iwin.hotel.auth.onAjaxLogin);
	Event.observe(document, 'iwin:auth:logout:success', iwin.hotel.auth.onAjaxLogout);
});

// notifies swf that user has logged in or switches to the
// correct page as the case may be.
iwin.hotel.auth.onAjaxLogin = function () {
    console.debug('Entering iwin.hotel.auth.onAjaxLogin');
    var userName = iwin.Auth.getCurrentCredentials().username;
    var swf = iwin.hotel.utils.getCurrentSwfObject();
    if (swf !== null) {
        console.debug('iwin.hotel.auth.onAjaxLogin login with username: %s', userName);
        swf.onAjaxLogin(userName);
    }
};

// notifies swf that user has logged out or switches to the
// correct page as the case may be.
iwin.hotel.auth.onAjaxLogout = function () {
    console.debug('Entering iwin.hotel.auth.onAjaxLogout');
    if (iwin.hotel.utils.getSwfObject("HotelIWin")) {
        isCartEmpty = true;
        iwin.hotel.callbacks.openRoomBrowser();
    } else if (iwin.hotel.utils.getSwfObject("WheelOfOpalescence")) {
        iwin.hotel.callbacks.openOnlineGames();
    } else {
        var swf = iwin.hotel.utils.getCurrentSwfObject();
	if (swf !== null) {
            swf.onAjaxLogout();
        }
    }
};

///////////////////////////////////////////////////////////////////////////////////////
///  other functions   //////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////

// added listener on the leaving page
if (window.body) {
    window.body.onbeforeunload = iwin.hotel.utils.doBeforeUnload; // IE
} else {
    window.onbeforeunload = iwin.hotel.utils.doBeforeUnload; // FX
}

// called from IWGM on balance updating
function iwin_hotel_utils_updateOpalsInfo(balance, lifetimeOpals, maxFloor) {
    try {
        iwin.hotel.utils.getCurrentSwfObject().onOpalsInfoUpdated();
    } catch (err) {
        console.debug('iwin_hotel_utils_updateOpalsInfo failure with err: %s', err);
    }
}
