var GLOBAL_DEBUGGING = false;

//var REQUEST_DESTINATION_URL = "http://dynamic-lb.mobwarsapp.com/mob";
var REQUEST_DESTINATION_URL = "http://sns.fontera.net/myspace/counterstrike/api";

var GBL = {};

    GBL.APP_CANVAS_URL = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=108545&";
    
    GBL.APP_NOT_INSTALLED = 0;
    GBL.APP_INSTALLED = 1;
    GBL.APP_JUST_INSTALLED = 2;
    GBL.app_install_state = GBL.APP_INSTALLED;

    GBL.TOMS_ID = 6221;


    GBL.POST_AS_STRING = false;


    GBL.MAIN_DATA = undefined;
    GBL.STATUS_DIV = undefined;
    GBL.MAIN_TABS = undefined;
    GBL.REFRESH_STATUS = undefined;

    GBL.SHOW_USER_ID = "show_user_id";


//var ABTEST_DESTINATION_URL = "http://fremont02.youplusplus.com";
//var ABTEST_DESTINATION_URL ="http://sns.fontera.net";
//function abTest(userId, testName) {
//      makeXMLNotCachedRequest(ABTEST_DESTINATION_URL + "/abtest?userId=" + userId + "&app=mob&abTestName=" + testName);
//}





    var XML_REQUEST_QUEUE = new XMLRequestQueue();
    XMLRequestQueue.DO_POST = 1;
    XMLRequestQueue.DO_GET = 2;
    XMLRequestQueue.MAX_RETRIES = 1;
    XMLRequestQueue.MAX_TIMEOUT = 20000;
    XMLRequestQueue.PREEMPT_REQUESTS = false;
    XMLRequestQueue.SESSION_KEY = 0;


    function makeXMLNotCachedRequest(a_url, a_callback, a_param, a_maxRetries){

        if(isValid(a_param)){
            try{
                var l_total_ids = 0;
                if(isValid(a_param.user_id)) l_total_ids += parseInt(a_param.user_id) % 123431;
                if(isValid(a_param.target_id)) l_total_ids += parseInt(a_param.target_id) % 123431;
                a_param.session_id = hex_sha1(""+l_total_ids);
            }catch(err){
                a_param.session_id = "none";               
            }

            a_param.session_key = hex_sha1(""+XMLRequestQueue.SESSION_KEY);
        }
       var l_maxRetries = a_maxRetries;
        if(!isValid(l_maxRetries)){
            l_maxRetries = XMLRequestQueue.MAX_RETRIES;
        }
       XML_REQUEST_QUEUE.addRequest(XMLRequestQueue.DO_GET, a_url, a_callback, a_param, l_maxRetries);
    }

    function XMLRequestQueue(){

        var m_numProcessedRequests = 0;
        var m_types = new Array();
        var m_urls = new Array();
        var m_callbacks = new Array();
        var m_params = new Array();
        var m_numRetries = new Array();
        var m_maxRetries = new Array();
        var m_requestIds = new Array();

        var m_cur_type = undefined;
        var m_cur_url = undefined;
        var m_cur_callback = undefined;
        var m_cur_param = undefined;
        var m_cur_startTime = undefined;
        var m_cur_maxRetries = undefined;
        var m_cur_retries = 0;
        // allowing for timeouts and other goodness
        var m_cur_request_id = -1;

        // simple lock
        var m_preemptable = true;


        this.addRequest = addRequest;
        this.timeoutRequest = timeoutRequest;

        function addRequest(a_type, a_url, a_callback, a_param, a_maxRetries){

            if(XMLRequestQueue.PREEMPT_REQUESTS && m_preemptable && isValid(m_cur_startTime)){
                outputDebug("Request to " + m_cur_url + " has been pre-empted by " + a_url);

                m_types.push(m_cur_type);
                m_urls.push(m_cur_url);
                m_callbacks.push(m_cur_callback);
                m_params.push(m_cur_param);
                m_maxRetries.push(m_cur_maxRetries);
                m_numRetries.push(m_cur_retries);
                m_requestIds.push(m_cur_request_id);
                clearCurState();
            }

            m_numProcessedRequests += 1;
            m_types.push(a_type);
            m_urls.push(a_url);
            m_callbacks.push(a_callback);
            m_params.push(a_param);
            m_maxRetries.push(a_maxRetries);
            m_numRetries.push(0);
            m_requestIds.push(m_numProcessedRequests);

            makeNewRequest();
        }

        function makeNewRequest(){
            if(m_urls.length == 0){
                return;
            }

            // When request timeout, queue is not started until there are new request
            if(m_cur_startTime != undefined){
                return;
            }

            m_cur_type = m_types.pop();
            m_cur_url = m_urls.pop();
            m_cur_callback = m_callbacks.pop();
            m_cur_param = m_params.pop();
            m_cur_startTime = (new Date()).getTime();
            m_cur_maxRetries = m_maxRetries.pop();
            m_cur_retries = m_numRetries.pop();
            m_cur_request_id = m_requestIds.pop();
            
            if(m_cur_retries > m_cur_maxRetries){                
                var l_tempCallback = m_cur_callback;
                clearCurState();

                if(isValidFunction(l_tempCallback)){
                    outputDebug("calling callback with undefined ");
                    l_tempCallback(undefined);
                }
                makeNewRequest();

           } else {
               doRequest();
           }
        }

        function retryRequest(){
           m_cur_retries += 1;
           outputDebug("retrying with id="+ m_cur_request_id + " url=" + m_cur_url + " num_retries=" + m_cur_retries + " retries");
           m_types.unshift(m_cur_type);
           m_urls.unshift(m_cur_url);
           m_callbacks.unshift(m_cur_callback);
           m_params.unshift(m_cur_param);
           m_maxRetries.unshift(m_cur_maxRetries);
           m_numRetries.unshift(m_cur_retries);
           m_requestIds.unshift(m_cur_request_id);

           clearCurState();
           makeNewRequest();
        }


        function timeoutRequest(a_request_id){
            if(m_cur_request_id != a_request_id){
                outputDebug("Timeout request is already over for request with id: " + a_request_id);
                return;
            }

            outputDebug("Timeout for request with id: " + m_cur_request_id);
            retryRequest();
        }


        function doRequest(){
            window.setTimeout("XML_REQUEST_QUEUE.timeoutRequest(parseInt("+m_cur_request_id+"));",XMLRequestQueue.MAX_TIMEOUT);

            if(m_cur_type == XMLRequestQueue.DO_GET){
                doGetRequest(m_cur_request_id);
            } else if(m_cur_type == XMLRequestQueue.DO_POST){
                doPostRequest(m_cur_request_id);
            } else {
                outputDebug("UNRECOGNIZED REQUEST TYPE!!! " + m_cur_type);
                clearCurState();
                makeNewRequest();
            }
        }


        function doGetRequest(a_request_id){
            var f_curFinishFunction = function(response){
                onFinishRequest(response, a_request_id);
            }

            var l_sep = "?";
            if (m_cur_url.indexOf("?") > -1) {
                l_sep = "&";
            }

            var l_request_url = m_cur_url;
            if(isValid(m_cur_param)){
                var l_param_str = "";
                for(var l_id in m_cur_param){
                    if(typeof(m_cur_param[l_id]) == "number" || typeof(m_cur_param[l_id]) == "string" || typeof(m_cur_param[l_id]) == "boolean"){
                        l_param_str += l_id + "=" + m_cur_param[l_id] + "&";
                    }
                }
                if (l_param_str.length > 0 && l_param_str.lastIndexOf('&') == l_param_str.length - 1) {
                    l_param_str = l_param_str.substr(0, l_param_str.length - 1);
                }
                l_request_url += l_sep + l_param_str;
            }

            l_sep = "?";
            if (l_request_url.indexOf("?") > -1) {
                l_sep = "&";
            }
            var l_ts = new Date().getTime();
            l_request_url = [ l_request_url, l_sep, "nocache=", l_ts ].join("");

            var l_params = {};
            l_params['METHOD'] = 'GET';
            l_params['CONTENT_TYPE'] = gadgets.io.ContentType.DOM;
            l_params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;


            outputDebug("GET request with id " + a_request_id + " sent to " + l_request_url);

            gadgets.io.makeRequest(l_request_url, f_curFinishFunction, l_params);
        }

        function doPostRequest(a_request_id){
            var f_curFinishFunction = function(response){
                onFinishRequest(response, a_request_id);
            }

             if(isValid(GBL.POST_AS_STRING) && GBL.POST_AS_STRING){
                var l_param_str = "";
                for(var l_id in m_cur_param){
                    if(typeof(m_cur_param[l_id]) == "number" || typeof(m_cur_param[l_id]) == "string" || typeof(m_cur_param[l_id]) == "boolean"){
                        l_param_str += l_id + "=" + m_cur_param[l_id] + "&";
                    }
                }
                l_param_str += "nocache=" + new Date().getTime();

                var l_params = {};
                l_params[gadgets.io.RequestParameters.POST_DATA] = l_param_str;
                l_params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
                l_params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
                l_params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;

                outputDebug("POST string request with id " + a_request_id + " sent to " + m_cur_url + " with param " + l_param_str);
                gadgets.io.makeRequest(m_cur_url, f_curFinishFunction, l_params);

            }else{
                m_cur_param.nocache = new Date().getTime();
                var l_params = {};
                l_params[gadgets.io.RequestParameters.POST_DATA] = m_cur_param;
                l_params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
                l_params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
                l_params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;

                outputDebug("POST object request with id " + a_request_id + " sent to " + m_cur_url + " with param " + m_cur_param);
                gadgets.io.makeRequest(m_cur_url, f_curFinishFunction, l_params);
            }
        }

        function onFinishRequest(a_response, a_request_id){
            if(m_cur_request_id != a_request_id){
                outputDebug(" OUT of order request came back with id: " + a_request_id);
                return;
            }

            m_preemptable = false;

            if(m_cur_type == XMLRequestQueue.DO_GET){
                outputDebug(" GET request with id " + a_request_id + " cameback for " + m_cur_url + " after " + m_cur_retries + " num retries in " + ((new Date()).getTime() - m_cur_startTime) + " >>> " + a_response);
            } else {
                outputDebug(" POST request with id " + a_request_id + " cameback for " + m_cur_url + " after " + m_cur_retries + " num retries in " + ((new Date()).getTime() - m_cur_startTime) + " >>> " + a_response);
            }


            var l_responseValid = true;
            try{
                l_responseValid = isValid(a_response.data) || isValid(a_response.text);
            } catch(err){
                l_responseValid = false;
            }


            if(!l_responseValid){
                outputDebug(" response is not valid");
                retryRequest();

            } else {

                // update session key
                try{
                    var l_xmlDoc = getGadgetResponseData(a_response);
                    if(isValid(getXMLNodeValue(l_xmlDoc, "request_id")))
                        XMLRequestQueue.SESSION_KEY = getXMLNodeValue(l_xmlDoc, "request_id");
                }catch(err){};

                // do callback
                var l_tempCallback = m_cur_callback;
                clearCurState();
                if(isValidFunction(l_tempCallback)){
                    l_tempCallback(a_response);
                }
                makeNewRequest();
            }

            m_preemptable = true;
        }

        function clearCurState(){
            m_cur_type = undefined;
            m_cur_url = undefined;
            m_cur_callback = undefined;
            m_cur_param = undefined;
            m_cur_startTime = undefined;
            m_cur_maxRetries = XML_REQUEST_QUEUE.MAX_RETRIES;
            m_cur_retries = 0;
            m_cur_request_id = -1;
        }
    }


    function getGadgetResponseData(a_response){
        if(a_response.data == null || a_response.data == undefined){
            outputDebug("Unfortunately, there was an unknown error. Please check back later: " + a_response.errors);
            return undefined;
        }
        return a_response.data;
    }

    function getGadgetResponseText(a_response){
        if(a_response.text == null || a_response.text == undefined){
            outputDebug("Unfortunately, there was no text. Please check back later: " + a_response.errors);
            return undefined;
        }
        return a_response.text;
    }

    function parseXML(a_text) {
        if (typeof DOMParser != "undefined") {
            // Mozilla, Firefox, and related browsers
            return (new DOMParser()).parseFromString(a_text, "application/xml");
        }
        else if (typeof ActiveXObject != "undefined") {
            // Internet Explorer.
            var doc = XML.newDocument( );   // Create an empty document
            doc.loadXML(a_text);              //  Parse text into it
            return doc;                     // Return it
        }
        else {
            // As a last resort, try loading the document from a data: URL
            // This is supposed to work in Safari. Thanks to Manos Batsis and
            // his Sarissa library (sarissa.sourceforge.net) for this technique.
            var l_url = "data:text/xml;charset=utf-8," + encodeURIComponent(a_text);
            var l_request = new XMLHttpRequest();
            l_request.open("GET", l_url, false);
            l_request.send(null);
            return l_request.responseXML;
        }
    }


    function getXMLFirstNode(a_doc, a_attribute){
        var l_attArray = a_doc.getElementsByTagName(a_attribute);
        if(isValid(l_attArray) && l_attArray.length > 0 && isValid(l_attArray[0])){
            return l_attArray[0];
        } else {
            return undefined;
        }
    }

    function getXMLNodeValue(a_node, a_attribute){
        var l_attArray = a_node.getElementsByTagName(a_attribute);
        if(isValid(l_attArray) && l_attArray.length > 0 &&
           isValid(l_attArray[0].firstChild) &&
           isValid(l_attArray[0].firstChild.nodeValue)){

            return l_attArray[0].firstChild.nodeValue;
        }else{
            return undefined;
        }
    }

    function getXMLEncodedStringNodeValue(a_node, a_attribute) {
        var l_node = getXMLNodeValue(a_node, a_attribute);
        if (l_node == undefined) return undefined;
        else {
            return decodeURIComponent(l_node);
        }
    }

    function customEncoding(a_text) {
        return "cstm_" + encodeURIComponent(a_text).replace(/%/g, "@");
    }   

    function decodeEncodedStringValue(a_value){
        if (a_value == undefined){
            return undefined;
        } else {
            return decodeURIComponent(a_value);
        }
    }

    function addEvent(a_obj, a_evType, a_fn){
        if (a_obj.addEventListener){
            a_obj.addEventListener(a_evType, a_fn, false);
            return true;
        } else if (a_obj.attachEvent){
            var l_r = a_obj.attachEvent("on"+a_evType, a_fn);
            return l_r;
        } else {
            return false;
        }
    }

    function addEventWithParameter(a_obj, a_evType, a_fn, a_param){
        if (a_obj.addEventListener){
            a_obj.addEventListener(a_evType, function(){a_fn(a_param); return false;}, false);
            return true;
        } else if (a_obj.attachEvent){
            var l_r = a_obj.attachEvent("on"+a_evType, function(){a_fn(a_param); return false;});
            return l_r;
        } else {
            return false;
        }
    }


    function showMessage(a_messageHTML){
        var a_messageDiv = document.getElementById("messageBox");
        if(a_messageDiv == undefined || a_messageDiv == null){
            outputDebug("can't find messageBox");
            return;
        }
        a_messageDiv.innerHTML = a_messageHTML;
        a_messageDiv.style.display = "block";
    }

    function hideMessage(){
        var l_messageDiv = document.getElementById("messageBox");
        if(l_messageDiv == undefined || l_messageDiv == null){
            outputDebug("can't find messageBox");
            return;
        }
        l_messageDiv.innerHTML = "";
        l_messageDiv.style.display = "none";
    }

    function isValid(a_obj) {
        return (a_obj != undefined && a_obj != null);
    }

    function isValidFunction(a_obj){
        return isValid(a_obj) && (typeof(a_obj) == 'function');
    }

    function encodeText(a_text) {
        var l_result = "";
        for (var l_i = 0; l_i < a_text.length; l_i++) {
            var l_num = a_text.charCodeAt(l_i);
            // Don't encode a to z and A to Z unless it's the first character
            if ((l_i != 0) &&
                ((64 <= l_num && l_num < 64 + 26) ||
                 (97 <= l_num && l_num < 97 + 26))) {
                l_result += a_text.charAt(l_i);
            } else {
                // '#' disappears if I put all of the below in one line
                // i.e., this is bad: result += "&#" + num + ";";
                l_result += "&";
                l_result += "#";
                l_result += l_num;
                l_result += ";";
                // outputDebug("Encode " + i + ": " + result);
            }
        }
        return encodeURIComponent(l_result);
    }

    function getBooleanValue(a_value){

        if(!isValid(a_value)){
            return false;
        }

        var l_strValue = ""+a_value;
        l_strValue.toLowerCase();
        
        if(l_strValue == "true"){
            return true;
        } else if(l_strValue == "false"){
            return false;
        } else {
            return Boolean(a_value);
        }
    }


    function validateAmount(a_value){
        if(!isValid(a_value) || a_value.length == 0){
            return false;
        }

        var l_amount = undefined;
        try{
            l_amount = parseInt(a_value);
        }catch(err){ l_amount = undefined; }

        if(!isValid(l_amount)){
            return false;
        } else {
            return true;
        }
    }


    function extendClass(a_subClass, a_baseClass) {
       function l_inheritance() {}
       l_inheritance.prototype = a_baseClass.prototype;

       a_subClass.prototype = new l_inheritance();
       a_subClass.prototype.constructor = a_subClass;
       a_subClass.baseConstructor = a_baseClass;
       a_subClass.superClass = a_baseClass.prototype;
    }



    function isDebugging(){
        try{
            return (isValid(GLOBAL_DEBUGGING) && GLOBAL_DEBUGGING);
        }catch(err){
            return false;
        }
    }

    function outputDebug(a_text) {
        try{                        
            if(isDebugging()){
                var debugElement = document.getElementById('debugOutput');
                if(isValid(debugElement) && isValid(debugElement.style) && debugElement.style.display != "none"){
                    document.getElementById('debugOutput').innerHTML += a_text + '<br>';
                }
            }
        }catch(err){};
    }    


    function outputAlert(a_text) {
        try{
            if(isDebugging()){
                alert(a_text);
            }
        }catch(err){};
    }

    function getOpenSocialParameter(a_paramId){
        try{
            var l_params = gadgets.views.getParams();
            if(isValid(l_params[a_paramId])){
                return l_params[a_paramId];
            } else {
                return undefined;
            }
        }catch(err){
            outputDebug("getOSParam Error: " + err);
        }
    }

   function shortenedStringKeepEscapedCharacters(a_long_string, a_max_length) {
        if(!isValid(a_long_string)){
            return a_long_string;
        }

        if (a_long_string.length < a_max_length) {
            return a_long_string;
        }
        var l_first_half = a_long_string.substring(0, a_max_length);
        var l_second_half = a_long_string.substring(a_max_length - 1, a_long_string.length - 1)
        var l_ampersand_location = l_first_half.lastIndexOf("&");
        var l_comma_location = l_second_half.indexOf(";");
        //note -- 9 is my best guess
        if (l_ampersand_location !== -1 && l_comma_location !== -1 && a_max_length - l_ampersand_location - 1 + l_comma_location < 9) {
            return l_first_half + l_second_half.substring(0, l_comma_location + 1) + "..";
        } else {
            return l_first_half + "..";
        }
    }


    function getRandomNumbers(a_max, a_numNumbers){
        var a_numbers = new Array();
        if(a_max < a_numNumbers){
            for(var l_index = 0; l_index <= a_max; l_index++){
                a_numbers.push(l_index);
            }
            return a_numbers;
        }

        var a_numbers = new Array();
        var a_pickedNumbers = {};

        for(var l_index = 0; l_index < a_numNumbers; l_index++){
            var l_current = Math.round(Math.random() * a_max);
            while(isValid(a_pickedNumbers[l_current])){
                l_current = (l_current+1)%a_max;
            }
            a_pickedNumbers[l_current] = 1;
            a_numbers.push(l_current);
        }

        return a_numbers;
    }



     // from http://pajhome.org.uk/crypt/md5/sha1src.html
    var g_hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
    var g_chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */
    function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * g_chrsz));}

    function core_sha1(x, len)
    {
      /* append padding */
      x[len >> 5] |= 0x80 << (24 - len % 32);
      x[((len + 64 >> 9) << 4) + 15] = len;

      var w = Array(80);
      var a =  1732584193;
      var b = -271733879;
      var c = -1732584194;
      var d =  271733878;
      var e = -1009589776;

      for(var i = 0; i < x.length; i += 16)
      {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;
        var olde = e;

        for(var j = 0; j < 80; j++)
        {
          if(j < 16) w[j] = x[i + j];
          else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
          var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                           safe_add(safe_add(e, w[j]), sha1_kt(j)));
          e = d;
          d = c;
          c = rol(b, 30);
          b = a;
          a = t;
        }

        a = safe_add(a, olda);
        b = safe_add(b, oldb);
        c = safe_add(c, oldc);
        d = safe_add(d, oldd);
        e = safe_add(e, olde);
      }
      return Array(a, b, c, d, e);

    }
    function sha1_ft(t, b, c, d)
    {
      if(t < 20) return (b & c) | ((~b) & d);
      if(t < 40) return b ^ c ^ d;
      if(t < 60) return (b & c) | (b & d) | (c & d);
      return b ^ c ^ d;
    }
    function sha1_kt(t){
      return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
             (t < 60) ? -1894007588 : -899497514;
    }
    function safe_add(x, y){
      var lsw = (x & 0xFFFF) + (y & 0xFFFF);
      var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
      return (msw << 16) | (lsw & 0xFFFF);
    }
    function rol(num, cnt){
      return (num << cnt) | (num >>> (32 - cnt));
    }
    function str2binb(str)
    {
      var bin = Array();
      var mask = (1 << g_chrsz) - 1;
      for(var i = 0; i < str.length * g_chrsz; i += g_chrsz)
        bin[i>>5] |= (str.charCodeAt(i / g_chrsz) & mask) << (32 - g_chrsz - i%32);
      return bin;
    }
    function binb2hex(binarray)
    {
      var hex_tab = g_hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
      var str = "";
      for(var i = 0; i < binarray.length * 4; i++)
      {
        str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
               hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
      }
      return str;
    }









/////////////////////////////////////////////////////////
// utility functions
/////////////////////////////////////////////////////////

function isPostToTargetLive(){
    var supported = l_OSContainer.getMySpaceEnvironment().getSupportedPostToTargets();
    for(var i = 0; i < supported.length; i++){
        if(supported[ i ] === "SHARE_APP"){
            return true;
        }
    }
    return false;
}

/////////////////////////////////////////////////////////
// to other people
/////////////////////////////////////////////////////////

function sendMessage(a_targetUser, a_subject, a_content, a_postToCallback){

    var l_OSContainer = opensocial.Container.get();
    var l_OSToken = MyOpenSpace.MySpaceContainer.OSToken;

    var l_message;
	l_message = opensocial.newMessage(a_content);
    l_message.setField(opensocial.Message.Field.TITLE, a_subject);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.SEND_MESSAGE);

    goToPageTop();
    l_OSContainer.postTo(l_OSToken, l_message, a_targetUser, a_postToCallback);
}


function sendComment(a_targetUser, a_content, a_postToCallback){

    var l_OSContainer = opensocial.Container.get();
    var l_OSToken = MyOpenSpace.MySpaceContainer.OSToken;

    var l_message;
	l_message = opensocial.newMessage(a_content);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.COMMENTS);

    goToPageTop();
    l_OSContainer.postTo(l_OSToken, l_message, a_targetUser, a_postToCallback);
}


function sendCommentWOGoToPageTop(a_targetUser, a_content, a_postToCallback){

    var l_OSContainer = opensocial.Container.get();
    var l_OSToken = MyOpenSpace.MySpaceContainer.OSToken;

    var l_message;
	l_message = opensocial.newMessage(a_content);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.COMMENTS);

    l_OSContainer.postTo(l_OSToken, l_message, a_targetUser, a_postToCallback);
}


function sendInvite(a_targetUser, a_content, a_postToCallback){

    var l_message = opensocial.newMessage(a_content);
    opensocial.requestShareApp(a_targetUser.getUserId(), l_message, a_postToCallback);
}

/////////////////////////////////////////////////////////
// to the viewer's own account only
/////////////////////////////////////////////////////////

function postToProfile(a_targetUser, a_content, a_postToCallback){

    var l_OSContainer = opensocial.Container.get();
    var l_OSToken = MyOpenSpace.MySpaceContainer.OSToken;

    var l_message;
	l_message = opensocial.newMessage(a_content);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.PROFILE);

    goToPageTop();
    l_OSContainer.postTo(l_OSToken, l_message, a_targetUser, a_postToCallback);
}

function postToBlog(a_targetUser, a_subject, a_content, a_postToCallback){

    var l_OSContainer = opensocial.Container.get();
    var l_OSToken = MyOpenSpace.MySpaceContainer.OSToken;

    var l_message;
	l_message = opensocial.newMessage(a_content);
    l_message.setField(opensocial.Message.Field.TITLE, a_subject);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.BLOG);

    goToPageTop();
    l_OSContainer.postTo(l_OSToken, l_message, a_targetUser);
}

function postToBulletin(a_targetUser, a_subject, a_content, a_postToCallback){

    var l_OSContainer = opensocial.Container.get();
    var l_OSToken = MyOpenSpace.MySpaceContainer.OSToken;

    var l_message;
	l_message = opensocial.newMessage( a_content);
    l_message.setField(opensocial.Message.Field.TITLE, a_subject);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.BULLETINS);

    goToPageTop();
    l_OSContainer.postTo(l_OSToken, l_message, a_targetUser, a_postToCallback);
}

function postToBulletinWOGoToPageTop(a_targetUser, a_subject, a_content, a_postToCallback){

    var l_OSContainer = opensocial.Container.get();
    var l_OSToken = MyOpenSpace.MySpaceContainer.OSToken;

    var l_message;
	l_message = opensocial.newMessage( a_content);
    l_message.setField(opensocial.Message.Field.TITLE, a_subject);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.BULLETINS);

    l_OSContainer.postTo(l_OSToken, l_message, a_targetUser, a_postToCallback);
}


// User
    function User(a_userData) {
        // standard
        this.m_userId = undefined;
        this.m_name = undefined;
        this.m_thumbnail_url = undefined;
        this.m_profile_url = undefined;
        this.m_age = undefined;
        this.m_gender = undefined;

        // specific to mobsters
        this.m_mobName = undefined;
        this.m_mobClass = undefined;
        this.m_mobSize = undefined;
        this.m_cash = undefined;
        this.m_cashInBank = undefined;
        this.m_attackStrength = undefined;
        this.m_defenseStrength = undefined;
        this.m_health = undefined;
        this.m_maxHealth = undefined;
        this.m_energy = undefined;
        this.m_maxEnergy = undefined;
        this.m_stamina = undefined;
        this.m_maxStamina = undefined;
        this.m_experience = undefined;
        this.m_percentToNextLevel = undefined;
        this.m_expPointsToNextLevel = undefined;
        this.m_level = undefined;
        this.m_skillPoints = undefined;
        this.m_favorPoints = undefined;
        this.m_secondsToHealthRefresh = undefined;
        this.m_secondsToEnergyRefresh = undefined;
        this.m_secondsToStaminaRefresh = undefined;
        this.m_numRequests = undefined;
        this.m_joinedDaysAgo = undefined;
        this.m_income = undefined;
        this.m_upkeep = undefined;
        this.m_partOfViewerMob = undefined;
        this.m_requestedByUser = undefined;

        this.m_is_cheater = undefined;

        // for opensocial
        this.m_is_owner = false;
        this.m_is_viewer = false;


        if(isValid(a_userData)){
            this.createOsUser(a_userData);
        }
    }


    User.prototype.createOsUser = function(a_osUserData) {
        this.m_userId = a_osUserData.getField(opensocial.Person.Field.ID);
        this.m_name = a_osUserData.getDisplayName();
        this.m_age = a_osUserData.getField(opensocial.Person.Field.AGE);
        this.m_gender = a_osUserData.getField(opensocial.Person.Field.GENDER);
        this.m_thumbnail_url = a_osUserData.getField(opensocial.Person.Field.THUMBNAIL_URL);
        this.m_profile_url = a_osUserData.getField(opensocial.Person.Field.PROFILE_URL);
    }

    User.prototype.createXMLUser = function(a_userInfoNode){
       try{this.m_userId = getXMLNodeValue(a_userInfoNode, "user_id"); }catch(err){};
       try{this.m_name = getXMLEncodedStringNodeValue(a_userInfoNode, "display_name"); }catch(err){};
       try{this.m_thumbnail_url = getXMLEncodedStringNodeValue(a_userInfoNode, "thumbnail_url"); }catch(err){};
       try{this.m_profile_url = getXMLEncodedStringNodeValue(a_userInfoNode, "profile_url"); }catch(err){};
       this.fillSpecificInfoFromXML(a_userInfoNode);
    }


    User.prototype.constructParamForReq = function() {
        var l_params = {};
        l_params.user_id = this.m_userId;
		UserID= l_params.user_id;
        if (isValid(this.m_age)) l_params.age = this.m_age;
        if (isValid(this.m_gender)) l_params.gender = this.m_gender;
        if (isValid(this.m_thumbnail_url)) l_params.thumbnail_url = this.m_thumbnail_url;
        if (isValid(this.m_profile_url)) l_params.profile_url = this.m_profile_url;
        if (isValid(this.m_name)) l_params.display_name = customEncoding(this.m_name);
        return l_params;
    }

    User.prototype.signInViewer = function(onFinishCallback) {
       if (isValid(this.m_userId)) {
           var l_params = this.constructParamForReq();
           l_params.sign_in = "true";
           makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/sign_in", onFinishCallback, l_params);
		}
    }



    User.prototype.getUserId = function(){
        return this.m_userId;
    }

    User.prototype.getGender = function(){
        return this.m_gender;
    }

    User.prototype.getAge = function(){
        return this.m_age;
    }

    User.prototype.getThumbnailUrl = function(){
        return this.m_thumbnail_url;
    }

    User.prototype.getName = function() {
        return this.m_name;
    }

    User.prototype.getShortName = function(){
        return shortenedStringKeepEscapedCharacters(this.m_name, 12);        
    }

    User.prototype.getProfileUrl = function() {
        return this.m_profile_url;
    }


    User.prototype.output = function() {
        outputDebug("userId: " + this.m_userId);
        outputDebug("name: " + this.m_name);
        outputDebug("gender: " + this.m_gender);
    }


    ////////////////////////////////////////////////////////////
    // Specific to Mobsters

    User.prototype.fillSpecificInfoFromXML = function(a_xmlNode){
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"mob_name"))) this.m_mobName = getXMLEncodedStringNodeValue(a_xmlNode,"mob_name"); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"mob_class"))) this.m_mobClass = getXMLEncodedStringNodeValue(a_xmlNode,"mob_class"); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"mob_size"))) this.m_mobSize = parseInt(getXMLNodeValue(a_xmlNode,"mob_size")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"cash"))) this.m_cash = parseInt(getXMLNodeValue(a_xmlNode,"cash")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"cash_in_bank"))) this.m_cashInBank = parseInt(getXMLNodeValue(a_xmlNode,"cash_in_bank")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"attack_strength"))) this.m_attackStrength = parseInt(getXMLNodeValue(a_xmlNode,"attack_strength")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"defense_strength"))) this.m_defenseStrength = parseInt(getXMLNodeValue(a_xmlNode,"defense_strength")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"health"))) this.m_health = parseInt(getXMLNodeValue(a_xmlNode,"health")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"max_health"))) this.m_maxHealth = parseInt(getXMLNodeValue(a_xmlNode,"max_health")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"energy"))) this.m_energy = parseInt(getXMLNodeValue(a_xmlNode,"energy")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"max_energy"))) this.m_maxEnergy = parseInt(getXMLNodeValue(a_xmlNode,"max_energy")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"stamina"))) this.m_stamina = parseInt(getXMLNodeValue(a_xmlNode,"stamina")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"max_stamina"))) this.m_maxStamina = parseInt(getXMLNodeValue(a_xmlNode,"max_stamina")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"experience"))) this.m_experience = parseInt(getXMLNodeValue(a_xmlNode,"experience")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"percent_to_next_level"))) this.m_percentToNextLevel = parseInt(getXMLNodeValue(a_xmlNode,"percent_to_next_level")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"exp_pt_to_next_level"))) this.m_expPointsToNextLevel = parseInt(getXMLNodeValue(a_xmlNode,"exp_pt_to_next_level")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"level"))) this.m_level = parseInt(getXMLNodeValue(a_xmlNode,"level")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"skill_points"))) this.m_skillPoints = parseInt(getXMLNodeValue(a_xmlNode,"skill_points")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"favor_points"))) this.m_favorPoints = parseInt(getXMLNodeValue(a_xmlNode,"favor_points")); }catch(err){};

       try{ this.m_secondsToHealthRefresh = undefined; if(isValid(getXMLNodeValue(a_xmlNode,"seconds_to_health_refresh"))) this.m_secondsToHealthRefresh = parseInt(getXMLNodeValue(a_xmlNode,"seconds_to_health_refresh")); }catch(err){};
       try{ this.m_secondsToEnergyRefresh = undefined; if(isValid(getXMLNodeValue(a_xmlNode,"seconds_to_energy_refresh"))) this.m_secondsToEnergyRefresh = parseInt(getXMLNodeValue(a_xmlNode,"seconds_to_energy_refresh")); }catch(err){};
       try{ this.m_secondsToStaminaRefresh = undefined; if(isValid(getXMLNodeValue(a_xmlNode,"seconds_to_stamina_refresh"))) this.m_secondsToStaminaRefresh = parseInt(getXMLNodeValue(a_xmlNode,"seconds_to_stamina_refresh")); }catch(err){};

       try{ if(isValid(getXMLNodeValue(a_xmlNode,"num_requests"))) this.m_numRequests = parseInt(getXMLNodeValue(a_xmlNode,"num_requests")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"joined_days_ago"))) this.m_joinedDaysAgo = parseInt(getXMLNodeValue(a_xmlNode,"joined_days_ago")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"land_income"))) this.m_income = parseInt(getXMLNodeValue(a_xmlNode,"land_income")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"item_upkeep"))) this.m_upkeep = parseInt(getXMLNodeValue(a_xmlNode,"item_upkeep")); }catch(err){};

       try{ this.m_partOfViewerMob = getXMLNodeValue(a_xmlNode,"part_of_viewer_mob"); }catch(err){};
       try{ this.m_requestedByUser = getXMLNodeValue(a_xmlNode,"requested_by_viewer"); }catch(err){};
    }

    User.prototype.getMobName = function(){
        return this.m_mobName;
    }

    User.prototype.getShortMobName = function(a_max){
        if(!isValid(this.m_mobName) || !isValid(a_max) || this.m_mobName.length <= a_max){
            return this.m_mobName;
        }
        return this.m_mobName.substr(0, a_max-2) + "...";
    }

    User.prototype.getMobClass = function(){
        return this.m_mobClass;
    }

    User.prototype.getMobSize = function(){
        return this.m_mobSize;
    }

    User.prototype.getCash = function(){
        return this.m_cash;
    }

    User.prototype.getCashInBank = function(){
        return this.m_cashInBank;
    }

    User.prototype.getAttackStrength = function(){
        return this.m_attackStrength;
    }

    User.prototype.getDefenseStrength = function(){
        return this.m_defenseStrength;
    }

    User.prototype.getHealth = function(){
        return this.m_health;
    }

    User.prototype.getMaxHealth = function(){
        return this.m_maxHealth;
    }

    User.prototype.getEnergy = function(){
        return this.m_energy;
    }

    User.prototype.getMaxEnergy = function(){
        return this.m_maxEnergy;
    }

    User.prototype.getStamina = function(){
        return this.m_stamina;
    }

    User.prototype.getMaxStamina = function(){
        return this.m_maxStamina;
    }

    User.prototype.getExperience = function(){
        return this.m_experience;
    }

    User.prototype.getPercentToNextLevel = function(){
        return this.m_percentToNextLevel;
    }

    User.prototype.getExpPointsToNextLevel = function(){
        return this.m_expPointsToNextLevel;
    }

    User.prototype.getLevel  = function(){
        return this.m_level;
    }

    User.prototype.getSkillPoints = function(){
        return this.m_skillPoints;
    }

    User.prototype.getFavorPoints = function(){
        return this.m_favorPoints;
    }

    User.prototype.getSecondsToHealthRefresh = function(){
        return this.m_secondsToHealthRefresh;
    }

    User.prototype.getSecondsToEnergyRefresh = function(){
        return this.m_secondsToEnergyRefresh;
    }

    User.prototype.getSecondsToStaminaRefresh = function(){
        return this.m_secondsToStaminaRefresh;
    }

    User.prototype.getNumRequests = function(){
        return this.m_numRequests;
    }

    User.prototype.getJoinedDaysAgo = function(){
        return this.m_joinedDaysAgo;
    }

    User.prototype.getIncome = function(){
        return this.m_income;
    }

    User.prototype.getUpkeep = function(){
        return this.m_upkeep;
    }

    User.prototype.getpartOfViewerMob = function(){
        return getBooleanValue(this.m_partOfViewerMob); 
    }

    User.prototype.setRequestedByUser = function(a_value){
        if(!this.getpartOfViewerMob()){
            this.m_requestedByUser = a_value;
        }
    }

    User.prototype.getRequestedByUser = function(){
        return getBooleanValue(this.m_requestedByUser);
    }

    User.prototype.getRequestedByUser = function(){
        return getBooleanValue(this.m_requestedByUser);
    }

    User.prototype.getRequestedByUser = function(){
        return getBooleanValue(this.m_requestedByUser);
    }

    User.prototype.setIsCheater = function(a_is_cheater){
        this.m_is_cheater = a_is_cheater;
    }

    User.prototype.getIsCheater = function(){
        return this.m_is_cheater;
    }

    ////////////////////////////////////////////////////////////
    // for opensocial compliance

    User.prototype.getField = function(a_key){
        // this has to handle some things
        switch(a_key){
            case opensocial.Person.Field.ID: return this.m_userId;
            case opensocial.Person.Field.NAME: return this.m_name;
            case opensocial.Person.Field.AGE: return this.m_age;
            case opensocial.Person.Field.GENDER: return this.m_gender;
            case opensocial.Person.Field.THUMBNAIL_URL: return this.m_thumbnail_url;
            case opensocial.Person.Field.PROFILE_URL: return this.m_profile_url;
        }
        return undefined;
    }
    User.prototype.getDisplayName = function(){
        return this.m_name;
    }

    User.prototype.getId = function(){
        return this.m_userId;
    }

    User.prototype.isOwner = function(){
        return this.m_is_owner;
    }

    User.prototype.setIsOwner = function(a_is_owner){
        this.m_is_owner = a_is_owner;
    }

    User.prototype.isViewer = function(){
        return this.m_is_viewer;
    }

    User.prototype.setIsViewer = function(a_is_viewer){
        this.m_is_viewer = a_is_viewer;
    }
// end user









function CachedOSFriendList(a_query_backend){

    var m_query_backend = a_query_backend;
    var m_totalNumUsers = undefined;
    var m_cachedUsers = undefined;
    var m_cachedUserIdUserMap = new Object();

    this.invalidateCache = invalidateCache;

    var m_numUsersFinishCallback = undefined;
    this.getNumUsers = getNumUsers;

    var m_usersFinishCallback = undefined;
    this.getUsers = getUsers;
    this.getUserById = getUserById;


    function invalidateCache(){
        outputDebug("invalidate CachedOSFriendList cache");
        m_totalNumUsers = undefined;
        m_cachedUsers = new Array();
        m_cachedUserIdUserMap = new Object();
    }


    function getNumUsers(a_finishCallback){
        outputDebug("CachedOSFriendList: getNumUsers");

        if(isValid(m_totalNumUsers)){
            a_finishCallback(m_totalNumUsers);
            return;
        }

        m_numUsersFinishCallback = a_finishCallback;

        // just get the number of friends
        var l_param = {};
        l_param[opensocial.DataRequest.PeopleRequestFields.FIRST] = 0;
        l_param[opensocial.DataRequest.PeopleRequestFields.MAX] = 0;
        var l_req = opensocial.newDataRequest();
        l_req.add(l_req.newFetchPeopleRequest('VIEWER_FRIENDS', l_param), 'numFriends');
        l_req.send(onGetNumUsers);
    }

    function onGetNumUsers(a_response){
        outputDebug("CachedOSFriendList: onGetNumUsers");

        try{
            m_totalNumUsers = parseInt(a_response.get('numFriends').getData().getTotalSize())
        }catch (err) {
            m_totalNumUsers = undefined;
            outputDebug(err);
        }

        m_cachedUsers = new Array();
        for(var l_index = 0; l_index < m_totalNumUsers; l_index++){
            m_cachedUsers.push(undefined);
        }

        if(isValidFunction(m_numUsersFinishCallback)){
            var l_tempCallback = m_numUsersFinishCallback;
            m_numUsersFinishCallback = undefined;
            l_tempCallback(m_totalNumUsers);
        }
    }


    function getUsers(a_requiredStart, a_requiredNum, a_finishFetchCallback){
        outputDebug("CachedOSFriendList: getUsers start " + a_requiredStart + " num " + a_requiredNum);

        if(a_requiredNum % 40 != 0){
            outputAlert("Can only handle indices in multiples of 40, since myspace pages friends");
        }

        if(!isValid(m_totalNumUsers)){
            getNumUsers(function(){
               getUsers(a_requiredStart, a_requiredNum, a_finishFetchCallback);
            });
            return;
        }


        var l_upperLimit = Math.min(a_requiredStart + a_requiredNum, m_totalNumUsers);
        outputDebug("l_upperLimit: " + l_upperLimit);

        var l_entriesCached = true;
        if(m_cachedUsers.length >= l_upperLimit){
            for(var l_index = a_requiredStart; l_entriesCached && l_index < l_upperLimit; l_index ++ ){
                l_entriesCached = isValid(m_cachedUsers[l_index]);
            }
        }

        outputDebug("l_entriesCached: " + l_entriesCached);

        if(l_entriesCached){
            a_finishFetchCallback(m_cachedUsers);
        } else {
            m_usersFinishCallback = a_finishFetchCallback;
            getOSUsers(a_requiredStart);
        }
    }

    function getOSUsers(a_requiredStart){
        outputDebug("getOSUsers: " + a_requiredStart);

        var l_param = {};
        l_param[opensocial.DataRequest.PeopleRequestFields.FIRST] = a_requiredStart;
        l_param[opensocial.DataRequest.PeopleRequestFields.MAX] = 40;

        var l_req = opensocial.newDataRequest();
        l_req.add(l_req.newFetchPeopleRequest('VIEWER_FRIENDS', l_param), 'viewerFriends');

        l_req.send(function(a_dataResponse) {
            onLoadFriends(a_requiredStart, a_dataResponse);
        });
    }


    function onLoadFriends(a_startIndex, a_dataResponse){
        outputDebug("onLoadFriends: " + a_startIndex);

        var l_success = false;
        var l_currentIndex = a_startIndex;
        var l_queryIdString ="";
        
        try{
            var l_ownerFriends = a_dataResponse.get('viewerFriends').getData();
            if(isValid(l_ownerFriends)){
                l_success = true;
                l_ownerFriends.each(
                    function(a_person) {
                        var l_nonAppUser = new User(a_person);
                        if(!isValid(m_cachedUserIdUserMap[l_nonAppUser.getUserId()])){
                            l_queryIdString += l_nonAppUser.getUserId() + ",";
                        }
                        m_cachedUsers[l_currentIndex] = l_nonAppUser;
                        m_cachedUserIdUserMap[l_nonAppUser.getUserId()] = l_nonAppUser;
                        l_currentIndex += 1;
                    }
                );
            }
        }catch (err) {
            l_success = false;
            outputDebug("onLoadFriends " + err);
        }

        if(!l_success){
            outputDebug("Getting OS Users failed, should I retry?");
        } else {
        }

        
        if(m_query_backend && isValid(l_queryIdString) && l_queryIdString.length > 0){
            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.query_ids= l_queryIdString;

            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_app_users",
                    onLoadAppFriends,
                    l_params, true);
            return;
        }

        if(isValidFunction(m_usersFinishCallback)){
            var l_tempCallback = m_usersFinishCallback;
            m_usersFinishCallback = undefined;
            l_tempCallback(m_cachedUsers);
        }
    }   

    function onLoadAppFriends(a_requestData){
        outputDebug("onLoadAppFriends");

        var l_xmlDoc = getGadgetResponseData(a_requestData);
        if(l_xmlDoc != undefined){
            var l_userNodes = l_xmlDoc.getElementsByTagName("user");
            if(isValid(l_userNodes) && l_userNodes.length > 0){
                for(var l_index = 0; l_index < l_userNodes.length; l_index++){
                    try{
                        var l_userId = getXMLNodeValue(l_userNodes[l_index], "user_id");
                        var l_user = m_cachedUserIdUserMap[l_userId];
                        if(isValid(l_user)){
                            l_user.fillSpecificInfoFromXML(l_userNodes[l_index]);
                        }
                    } catch (err){
                        outputDebug("onLoadAppFriends: " + err);
                    }
                }
            }
        }

        if(isValidFunction(m_usersFinishCallback)){
            var l_tempCallback = m_usersFinishCallback;
            m_usersFinishCallback = undefined;
            l_tempCallback(m_cachedUsers);
        }
    }

    function getUserById(id){
        return m_cachedUserIdUserMap[id];
    }
}








CachedUserList.MY_REQUESTS = 1;
CachedUserList.MY_MOB = 2;

function CachedUserList(a_type){

    var m_type = a_type;
    var m_totalNumUsers = undefined;
    var m_cachedUsers = new Array();
    var m_cachedUserIdUserMap = new Object();


    this.setTotalNumUsers = setTotalNumUsers;
    this.addUser = addUser;
    this.invalidateCache = invalidateCache;

    var m_numUsersFinishCallback = undefined;
    this.getNumUsers = getNumUsers;
    this.onLoadNumUsers = onLoadNumUsers;

    var m_usersFinishCallback = undefined;
    this.getUsers = getUsers;
    this.onLoadUsers = onLoadUsers;
    this.getUserById = getUserById;


    function setTotalNumUsers(a_totalNumUsers){
        m_totalNumUsers = a_totalNumUsers;
    }

    function addUser(a_user){
        m_cachedUsers.push(a_user);
        m_cachedUserIdUserMap[a_user.getUserId()] = a_user;
    }

    function invalidateCache(){
        outputDebug("invalidate user cache");
        m_totalNumUsers = undefined;
        m_cachedUsers = new Array();
        m_cachedUserIdUserMap = new Object();
    }

    function getNumUsers(a_finishCallback){
        if(m_totalNumUsers != undefined){
            a_finishCallback(m_totalNumUsers);
            return;
        }

        m_numUsersFinishCallback = a_finishCallback;

        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.action = getActionURI(m_type);
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_num_users", onLoadNumUsers, l_params);
    }

    function onLoadNumUsers(a_requestData){
        var l_xmlDoc = getGadgetResponseData(a_requestData);
        if(l_xmlDoc != undefined){
            try{
                m_totalNumUsers = getXMLNodeValue(l_xmlDoc, "num");
            }catch(err){outputAlert(err);}
        }

        if(isValidFunction(m_numUsersFinishCallback)){
            var l_tempCallback = m_numUsersFinishCallback;
            m_numUsersFinishCallback = undefined;
            l_tempCallback(m_totalNumUsers);
        }
    }


    function getUsers(a_requiredStart, a_requiredNum, a_finishFetchCallback){
        if(m_cachedUsers.length >= m_totalNumUsers || m_cachedUsers.length >= (a_requiredStart + a_requiredNum-1)){
            a_finishFetchCallback(m_cachedUsers);
            return;
        }
//        outputAlert("cached length: " + m_cachedUsers.length + " required: " + requiredStart + " for " + requiredNum);
        var l_startIndex = Math.min(m_cachedUsers.length, a_requiredStart);
        var l_numToFetch = (a_requiredStart + a_requiredNum) - l_startIndex;
        m_usersFinishCallback = a_finishFetchCallback;

        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.action = getActionURI(m_type);
        l_params.start = l_startIndex;
        l_params.num = l_numToFetch;

        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_users", onLoadUsers, l_params);
    }


    function onLoadUsers(requestData){
        var l_xmlDoc = getGadgetResponseData(requestData);
        if(l_xmlDoc != undefined){
            var l_users = l_xmlDoc.getElementsByTagName("user");
            if(isValid(l_users) && l_users.length > 0){
                for(var l_index = 0; l_index < l_users.length; l_index++){
                    var l_pet = new User(undefined);
                    l_pet.createXMLUser(l_users[l_index]);
                    m_cachedUsers.push(l_pet);
                    m_cachedUserIdUserMap[l_pet.getUserId()] = l_pet;
                }
            }
        }

        if(isValidFunction(m_usersFinishCallback)){
            var l_tempCallback = m_usersFinishCallback;
            m_usersFinishCallback = undefined;
            l_tempCallback(m_cachedUsers);
        }
    }

    function getUserById(a_id){
        return m_cachedUserIdUserMap[a_id];
    }

    function getActionURI(a_typeCode){
        switch(a_typeCode){
            case CachedUserList.MY_REQUESTS:
                return "request";
            case CachedUserList.MY_MOB:
                return "my_mob";
            default:
                outputDebug("Unrecognized category code " + a_typeCode);
                return undefined;
        }
    }
}









function CentralData(a_finishInitialLoadCallback, a_loadStatusDiv){

    var m_finishInitialLoadCallback = a_finishInitialLoadCallback;
    var m_loadStatusDiv = a_loadStatusDiv;

    var m_viewer = undefined;
    var m_owner = undefined;
    var m_viewerFriends = undefined;
    var m_viewerNotBackedFriends = undefined;

    var m_viewerMobRequestList = undefined;
    var m_viewerMobMembersList = undefined;


    this.createUsers = createUsers;
    this.onLoadUsers = onLoadUsers;
    this.isInit = isInit;


    this.getOwner = getOwner;
    this.getViewer = getViewer;
    this.getViewerFriends = getViewerFriends;
    this.getViewerNotBackedFriends = getViewerNotBackedFriends;
    this.getCachedUsers = getCachedUsers;

    createUsers();

    function createUsers() {
        outputDebug("createUsers");
        var req = opensocial.newDataRequest();

        outputDebug("creating Param");
        var param = {};
        param[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
                   [opensocial.Person.Field.ID,
                    opensocial.Person.Field.NAME,
                    opensocial.Person.Field.THUMBNAIL_URL,
                    opensocial.Person.Field.AGE,
                    opensocial.Person.Field.GENDER ];

        req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER, param), 'owner');
        req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER, param), 'viewer');
        req.send(onLoadUsers);
    }


    function onLoadUsers(dataResponse) {
        outputDebug("load user called");

        try {
            var ownerData = dataResponse.get('owner').getData();
            m_owner = new User(ownerData);
        }  catch (err) {
            outputDebug(err);
            m_owner = null;
        }


        try {
            var viewerData = dataResponse.get('viewer').getData();
            m_viewer = new User(viewerData);
            m_loadStatusDiv.getTextDiv().innerHTML = "<span style='font-weight:bold;'> Loading your info... </span> <br/> <span style='font-size:10px;'> (Please do not refresh unless this takes more than 8 seconds) </span>";
            m_viewer.signInViewer(onFinishSignIn);

        }  catch (err) {
            outputDebug(err);
            m_viewer = null;
        }
    }

    function onFinishSignIn(a_response){
        var l_responseXML = undefined;
        try{
            l_responseXML = getGadgetResponseData(a_response);
        }catch(err){};

        if(!isValid(l_responseXML)){
            m_loadStatusDiv.getTextDiv().style.width = "500px";
            m_loadStatusDiv.getTextDiv().innerHTML = GBL.APP_ERROR_MSG;
            return;
        }

        m_viewerFriends = new CachedOSFriendList(true);
        m_viewerNotBackedFriends = new CachedOSFriendList(false);

        var l_viewerInfoNode = getXMLFirstNode(l_responseXML, "viewer");
        if(isValid(l_viewerInfoNode)) {
            m_viewer.fillSpecificInfoFromXML(l_viewerInfoNode);                    
        }

        m_viewerMobRequestList = new CachedUserList(CachedUserList.MY_REQUESTS);
        m_viewerMobMembersList = new CachedUserList(CachedUserList.MY_MOB);

        
        if(getBooleanValue(getXMLNodeValue(l_responseXML, "is_cheater"))){
            m_viewer.setIsCheater(true);
        } else {
            m_viewer.setIsCheater(false);
        }

        m_finishInitialLoadCallback();
    }



    function getOwner() {
        return m_owner;
    }

    function getViewer() {
        return m_viewer;
    }

    function getViewerFriends(){
        return m_viewerFriends;
    }

    function getViewerNotBackedFriends(){
        return m_viewerNotBackedFriends;
    }

    function getCachedUsers(a_type){
        switch(a_type){
        case CachedUserList.MY_REQUESTS: return m_viewerMobRequestList;
        case CachedUserList.MY_MOB: return m_viewerMobMembersList;      
        }
        return undefined;
    }

    function isInit() {
        return (m_owner != undefined || m_viewer != undefined);
    }
}




function goToPageTop(){
   location.href = "#mainFrameTop";
}

/** Shorthand for setting CSS style on an alement */
function setStyle(a_node, a_style) {
    if(isValid(a_style))        {
        for(var i in a_style) {
            a_node.style[i] = a_style[i];
        }
    }
    return a_node;
}

/** Shorthand for creating elements
 * @param tag string tag kind for document.createElement
 * @param parent DOM node
 * @param style array
 */
function makeElement(a_tag, a_parent, a_style) {
    var l_result = document.createElement(a_tag);
    a_parent.appendChild(l_result);
    return setStyle(l_result, a_style);
}


function navigateToCanvas(){
    var surfaces = gadgets.views.getSupportedViews();
    var surfaceRef = surfaces['canvas'];
    gadgets.views.requestNavigateTo(surfaceRef);
}


function formatNumberWithCommas(a_number){
    a_number += '';
    var l_numberParts = a_number.split('.');
    var l_beforeDecimal = l_numberParts[0];
    var l_afterDecimal = l_numberParts.length > 1 ? '.' + l_numberParts[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(l_beforeDecimal)) {
        l_beforeDecimal = l_beforeDecimal.replace(rgx, '$1' + ',' + '$2');
    }
    return l_beforeDecimal + l_afterDecimal;
}


function Button(a_parentDiv, a_buttonString, a_callback){
    var m_parentDiv = a_parentDiv;
    var m_buttonString = a_buttonString;
    var m_callback = a_callback;

    this.createDiv = createDiv;

    if(m_parentDiv != undefined){
        createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        var l_buttonA = document.createElement("a");
        l_buttonA.className = "blueButton";
        l_buttonA.href = "#";
        l_buttonA.appendChild(document.createTextNode(m_buttonString));
        addEvent(l_buttonA, "click", m_callback);

        var l_buttonSpan = document.createElement("span");
        l_buttonSpan.setAttribute("style", "text-align:center;");
        l_buttonSpan.className = "blueButton";
        l_buttonSpan.appendChild(l_buttonA);

        m_parentDiv.appendChild(l_buttonSpan);
    }
}

function BigButton(a_parentDiv, a_buttonString, a_callback){
    var m_parentDiv = a_parentDiv;
    var m_buttonString = a_buttonString;
    var m_callback = a_callback;

    this.createDiv = createDiv;

    if(m_parentDiv != undefined){
        createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        var l_buttonA = document.createElement("a");
        l_buttonA.className = "bigBlueButton";
        l_buttonA.href = "#";
        l_buttonA.appendChild(document.createTextNode(m_buttonString));
        addEvent(l_buttonA, "click", m_callback);

        var l_buttonSpan = document.createElement("span");
        l_buttonSpan.style.textAlign = "CENTER";
        l_buttonSpan.className = "bigBlueButton";
        l_buttonSpan.appendChild(l_buttonA);

        m_parentDiv.appendChild(l_buttonSpan);
    }
}


function DivButton(a_parentDiv, a_buttonString, a_callback, a_callbackArgs, a_center){
    var m_parentDiv = a_parentDiv;
    var m_buttonString = a_buttonString;
    var m_callback = a_callback;
    var m_callbackArgs = a_callbackArgs;
    var m_center = a_center;

    var m_buttonDiv = undefined;

    this.createDiv = createDiv;
    this.getButtonDiv = getButtonDiv;

    if(m_parentDiv != undefined){
        createDiv(m_parentDiv);
    }

    function createDiv(_parentDiv){
        m_parentDiv = _parentDiv;

        m_buttonDiv = document.createElement("div");
        m_parentDiv.appendChild(m_buttonDiv);
        m_buttonDiv.style.textAlign = "center";
        m_buttonDiv.style.padding = "5px 10px 5px 10px";
        m_buttonDiv.style.backgroundColor = "#3b5998";
        m_buttonDiv.style.color = "white";
        m_buttonDiv.style.fontSize = "12px";
        m_buttonDiv.style.fontWeight = "bold";

        m_buttonDiv.style.borderLeft = "solid 0px #505050";        
        m_buttonDiv.style.borderTop = "solid 0px #505050";
        m_buttonDiv.style.borderRight = "solid 2px #808080";
        m_buttonDiv.style.borderBottom = "solid 2px #808080";

        if(isValid(m_center) && m_center){
            m_buttonDiv.style.marginLeft = "auto";
            m_buttonDiv.style.marginRight = "auto";
        }


        m_buttonDiv.style.cursor = "pointer";

        m_buttonDiv.innerHTML = m_buttonString;

        addEventWithParameter(m_buttonDiv, "click", m_callback, m_callbackArgs);
    }

    function getButtonDiv(){
        return m_buttonDiv;
    }
}


function LinkButton(a_parentDiv, a_buttonString, a_buttonLink){
    var m_parentDiv = a_parentDiv;
    var m_buttonString = a_buttonString;

    this.createDiv = createDiv;

    if(m_parentDiv != undefined){
        createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        var l_buttonA = document.createElement("a");
        l_buttonA.className = "blueButton";
        l_buttonA.href = a_buttonLink;
        l_buttonA.appendChild(document.createTextNode(m_buttonString));

        var l_buttonSpan = document.createElement("span");
        l_buttonSpan.setAttribute("style", "text-align:center;");
        l_buttonSpan.className = "blueButton";
        l_buttonSpan.appendChild(l_buttonA);

        m_parentDiv.appendChild(l_buttonSpan);
    }
}


function ImageDiv(a_parentDiv, a_imageUrl, a_width, a_height, a_bgTransparent){

    var m_parentDiv = a_parentDiv;
    var m_imageUrl = a_imageUrl;
    var m_width = a_width;
    var m_height = a_height;
    var m_bgTransparent = a_bgTransparent;

    var m_imageDiv = null;

    this.createDiv = createDiv;
    this.getContainerDiv = getContainerDiv;

    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        //outputDebug("ImageDiv: createDiv");

        m_imageDiv = document.createElement("div");
        m_parentDiv.appendChild(m_imageDiv);

        m_imageDiv.style.backgroundImage = "url('"+m_imageUrl+"')";
        m_imageDiv.style.backgroundPosition = "center center";
        m_imageDiv.style.backgroundRepeat = "no-repeat";
        
        if(isValid(m_bgTransparent) && m_bgTransparent){
        } else {
            m_imageDiv.style.backgroundColor = "#EEEEEE";
        }

        m_imageDiv.style.width = m_width;
        m_imageDiv.style.height = m_height;
    }

    function getContainerDiv(){
        return m_imageDiv;
    }    
}


function PaginationDiv(a_parentDiv, a_pageCallback, a_numPages, a_currentPage, a_maxPages){

    var m_parentDiv = a_parentDiv;
    var m_pageNumDiv = undefined;
    var m_numPages = a_numPages;
    var m_currentPage = a_currentPage;
    var m_maxPages = a_maxPages;
    var m_pageCallback = a_pageCallback;

    if(isValid(m_parentDiv)){
        createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        m_pageNumDiv = document.createElement("div");
        m_parentDiv.appendChild(m_pageNumDiv);
        m_pageNumDiv.style.margin = "5px 50px 5px 0px";
        m_pageNumDiv.style.textAlign = "right";

        if(m_numPages > 1 && m_currentPage > 1){
            var l_prevA = document.createElement("a");
            l_prevA.href = "#";
            l_prevA.className = "paginationProgressionLink";
            l_prevA.appendChild(document.createTextNode("prev<<"));
            m_pageNumDiv.appendChild(l_prevA);

            addEventWithParameter(l_prevA, "click", m_pageCallback, m_currentPage-1);
        }

        m_pageNumDiv.appendChild(document.createTextNode("  "));


        var l_distToStart = Math.max(Math.ceil(a_maxPages / 2), m_maxPages - (m_numPages - m_currentPage));
        var l_startPageNum = Math.max(1, m_currentPage - l_distToStart);

        var l_distToEnd = Math.max(Math.ceil(a_maxPages / 2), m_maxPages - m_currentPage);
        var l_endPageNum = Math.min(m_numPages, m_currentPage + l_distToEnd);

        if(l_startPageNum > 1){
            var l_numA = document.createElement("a");
            l_numA.appendChild(document.createTextNode("1"));
            m_pageNumDiv.appendChild(l_numA);
            l_numA.href = "#";
            l_numA.className = "paginationPageNum";

            m_pageNumDiv.appendChild(document.createTextNode("..."));

            addEventWithParameter(l_numA, "click", m_pageCallback, 1);
        }

        for(var l_pageNum = l_startPageNum; l_pageNum <= l_endPageNum; l_pageNum++){
            if(l_pageNum != m_currentPage){
                var l_numA = document.createElement("a");
                l_numA.href = "#";
                l_numA.className = "paginationPageNum";
                l_numA.appendChild(document.createTextNode(l_pageNum));
                m_pageNumDiv.appendChild(l_numA);

                addEventWithParameter(l_numA, "click", m_pageCallback, l_pageNum);

            }else{
                var l_curNumSpan = document.createElement("span");
                m_pageNumDiv.appendChild(l_curNumSpan);
                l_curNumSpan.className = "paginationCurPageNum";
                l_curNumSpan.appendChild(document.createTextNode(l_pageNum));
            }
        }


        if(l_endPageNum < m_numPages){
            m_pageNumDiv.appendChild(document.createTextNode("..."));

            var l_numA = document.createElement("a");
            l_numA.appendChild(document.createTextNode(m_numPages));
            l_numA.href = "#";
            l_numA.className = "paginationPageNum";
            m_pageNumDiv.appendChild(l_numA);

            addEventWithParameter(l_numA, "click", m_pageCallback, m_numPages);
        }


        if(a_numPages > 1 && m_currentPage < a_numPages){
            var l_nextA = document.createElement("a");
            l_nextA.href = "#"
            l_nextA.className = "paginationProgressionLink";
            l_nextA.appendChild(document.createTextNode("next>>"));
            m_pageNumDiv.appendChild(l_nextA);

            addEventWithParameter(l_nextA, "click", m_pageCallback, m_currentPage+1);
        }
    }
}





function SideBySideCells(a_parentDiv, a_centered){

    var m_parentDiv = a_parentDiv;
    var m_containerDiv = undefined;
    var m_centered = a_centered;
    var m_table = undefined;
    var m_leftTd = undefined;
    var m_rightTd = undefined;

    this.createDiv = createDiv;
    this.getTable = getTable;
    this.getContainerDiv = getContainerDiv;
    this.getLeftCell = getLeftCell;
    this.getRightCell = getRightCell;

    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);

        m_table = document.createElement("table");
        m_containerDiv.appendChild(m_table);
        var l_tbody = document.createElement("tbody");
        m_table.appendChild(l_tbody);
        var l_tr = document.createElement("tr");
        l_tbody.appendChild(l_tr);

        m_leftTd = document.createElement("td");
        l_tr.appendChild(m_leftTd);

        m_rightTd = document.createElement("td");
        l_tr.appendChild(m_rightTd);

        if(m_centered){
            m_containerDiv.style.textAlign = "center";
            m_table.style.marginLeft = "auto";
            m_table.style.marginRight = "auto";
        }
    }

    function getContainerDiv(){
        return m_containerDiv;
    }

    function getLeftCell(){
        return m_leftTd;
    }

    function getRightCell(){
        return m_rightTd;
    }

    function getTable(){
        return m_table;
    }
}



// TabsDiv
    function TabsDiv(a_parentDiv, a_tabsNamesArray, a_tabsCallbacksArray, a_tabsAlignArray, a_defaultTabIndex,
                                  a_unSelectedSpanClassName, a_selectedSpanClassName, a_leftWidth){

        this.m_showContentDivTopPosition = "155px";
        this.m_hideContentDivTopPosition = "-10000px";

        this.m_parentDiv = a_parentDiv;
        this.m_tabsNamesArray = a_tabsNamesArray;
        this.m_tabsCallbacksArray = a_tabsCallbacksArray;
        this.m_tabsAlignArray = a_tabsAlignArray;
        this.m_defaultTabIndex = a_defaultTabIndex;
        this.m_unSelectedSpanClassName = a_unSelectedSpanClassName;
        this.m_selectedSpanClassName = a_selectedSpanClassName;
        this.m_leftWidth = a_leftWidth;

        this.m_curSelectedTabIndex = -1;
        this.m_curSelectedTabContent = undefined;
        this.m_curSelectedTabCreationCallback = undefined;
        this.m_curSelectedTabCreationCallbackArgs = undefined;

        this.m_tabSpansArray = new Array();

        this.m_containerDiv = undefined;
        this.m_tabsDiv = undefined;
        this.m_contentDivArray = new Array();
        this.m_contentInitializedArray = new Array();
        this.m_noTabContentDiv = undefined;

        this.createDiv();
    }


    TabsDiv.prototype.decorateUnselectedTab = function(a_nonSelectedTabSpan){
        a_nonSelectedTabSpan.className = this.m_unSelectedSpanClassName;
    }

    TabsDiv.prototype.decorateSelectedTab = function(a_selectedTabSpan){
        a_selectedTabSpan.className = this.m_selectedSpanClassName;
    }


    TabsDiv.prototype.createDiv = function(){

        var IE = document.all?true:false;
        if(IE){
            this.m_showContentDivTopPosition = "85px";
        } else {
            this.m_showContentDivTopPosition = "185px";
        }

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);

        this.m_tabsDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_tabsDiv);
        this.createTabs();

       // var l_bgContentDiv = document.createElement("div");
       // this.m_containerDiv.appendChild(l_bgContentDiv);
       // l_bgContentDiv.className = "tabContentFrame";
       // l_bgContentDiv.style.zIndex = "-1";

        // create where the content of the tabs are going to live
        for(var l_tabIndex = 0; l_tabIndex < this.m_tabsNamesArray.length; l_tabIndex++){
            var tabContentDiv = document.createElement("div");
            tabContentDiv.style.position = "absolute";
            tabContentDiv.style.top = this.m_hideContentDivTopPosition;
            tabContentDiv.style.left = "55px";
            tabContentDiv.style.width = "860px";
            tabContentDiv.style.zIndex = "1";
            this.m_containerDiv.appendChild(tabContentDiv);
            this.m_contentDivArray.push(tabContentDiv);

            this.m_contentInitializedArray.push(false);
        }


        // create the one that is going to created dynamically
        this.m_noTabContentDiv = document.createElement("div");
        this.m_noTabContentDiv.style.position = "absolute";
        this.m_noTabContentDiv.style.top = this.m_hideContentDivTopPosition;
        this.m_noTabContentDiv.style.left = "50px";
        this.m_noTabContentDiv.style.width = "860px";
        this.m_noTabContentDiv.style.zIndex = "1";
        this.m_containerDiv.appendChild(this.m_noTabContentDiv);


        this.switchToTab(this.m_defaultTabIndex);
    }

    TabsDiv.prototype.createTabs = function(){

        this.m_tabsDiv.innerHTML = "";

        var l_tabsTable = document.createElement("table");
        this.m_tabsDiv.appendChild(l_tabsTable);
        l_tabsTable.style.borderCollapse = "collapse";
        l_tabsTable.style.cellSpacing = "0px";
        l_tabsTable.style.margin = "0px";
        var l_tabsTbody = document.createElement("tbody");
        l_tabsTable.appendChild(l_tabsTbody);
        var l_tr = document.createElement("tr");
        l_tabsTbody.appendChild(l_tr);

        var l_leftTabs = document.createElement("td");
        l_tr.appendChild(l_leftTabs);
        l_leftTabs.style.textAlign = "left";
        l_leftTabs.style.paddingTop = "10px";
        l_leftTabs.style.paddingBottom = "5px";

        if(isValid(this.m_leftWidth)){
            l_leftTabs.style.width = this.m_leftWidth;            
        } else {
            l_leftTabs.style.width = "1000px";
        }


        var l_rightTabs = document.createElement("td");
        l_tr.appendChild(l_rightTabs);
        l_rightTabs.style.textAlign = "right";
        l_rightTabs.style.paddingTop = "10px";
        l_rightTabs.style.paddingBottom = "5px";

        var l_self = this;
        
        for(var l_tabIndex = 0; l_tabIndex < this.m_tabsNamesArray.length; l_tabIndex ++){

            var l_tabspan = document.createElement("span");
            l_tabspan.style.cursor = "pointer";
            this.decorateUnselectedTab(l_tabspan);
            l_tabspan.appendChild(document.createTextNode(this.m_tabsNamesArray[l_tabIndex]));

            if(this.m_tabsAlignArray[l_tabIndex] == "right"){
                l_rightTabs.appendChild(l_tabspan);
            } else {
                l_leftTabs.appendChild(l_tabspan);
            }

            this.m_tabSpansArray.push(l_tabspan);
            addEventWithParameter(l_tabspan, "click", function(a_index){l_self.switchToTab(a_index);}, l_tabIndex);
        }
    }

    TabsDiv.prototype.switchToTabWithName = function(a_tabName){
        for(var l_index = 0; l_index < this.m_tabsNamesArray.length; l_index++){
            if(this.m_tabsNamesArray[l_index] == a_tabName){
                this.switchToTab(l_index);
                return;
            }
        }
    }

    TabsDiv.prototype.switchToTab = function(a_tabIndex){
        if(this.m_curSelectedTabIndex >= 0){
            var l_tabspan = this.m_tabSpansArray[this.m_curSelectedTabIndex];
            this.decorateUnselectedTab(l_tabspan);

            var l_prevTabContentDiv = this.m_contentDivArray[this.m_curSelectedTabIndex];
            l_prevTabContentDiv.style.top = this.m_hideContentDivTopPosition;
        }

        this.m_noTabContentDiv.innerHTML = "";
        this.m_noTabContentDiv.style.top = this.m_hideContentDivTopPosition;


        this.m_curSelectedTabIndex = a_tabIndex;

        var l_curspan = this.m_tabSpansArray[this.m_curSelectedTabIndex];
        this.decorateSelectedTab(l_curspan);

        this.m_curSelectedTabContent = this.m_contentDivArray[this.m_curSelectedTabIndex];
        this.m_curSelectedTabContent.style.top = this.m_showContentDivTopPosition;

        this.m_curSelectedTabCreationCallback = this.m_tabsCallbacksArray[this.m_curSelectedTabIndex];
        this.m_curSelectedTabCreationCallbackArgs = undefined;
        this.m_curSelectedTabCreationCallback(this.m_curSelectedTabContent, this.m_contentInitializedArray[this.m_curSelectedTabIndex]);

        this.m_contentInitializedArray[this.m_curSelectedTabIndex] = true;

        goToPageTop();
        return false;
    }


    TabsDiv.prototype.switchToDynamicTab = function(a_createCallback, a_createCallbackArgs){

        if(this.m_curSelectedTabIndex >= 0){
            var l_tabspan = this.m_tabSpansArray[this.m_curSelectedTabIndex];
            this.decorateUnselectedTab(l_tabspan);

            var l_prevTabContentDiv = this.m_contentDivArray[this.m_curSelectedTabIndex];
            l_prevTabContentDiv.style.top = this.m_hideContentDivTopPosition;
        }
        this.m_curSelectedTabIndex = -1;
        goToPageTop();

        this.m_noTabContentDiv.innerHTML = "";
        this.m_noTabContentDiv.style.top = this.m_showContentDivTopPosition;
        a_createCallback(this.m_noTabContentDiv, false, a_createCallbackArgs);

        this.m_curSelectedTabContent = this.m_noTabContentDiv;
        this.m_curSelectedTabCreationCallback = a_createCallback;
        this.m_curSelectedTabCreationCallbackArgs = a_createCallbackArgs;

        return false;
    }

    TabsDiv.prototype.refreshTab = function(){
        if(isValidFunction(this.m_curSelectedTabCreationCallback) && isValid(this.m_curSelectedTabContent)){
            this.m_curSelectedTabContent.innerHTML = "";
            this.m_curSelectedTabCreationCallback(this.m_curSelectedTabContent, false, this.m_curSelectedTabCreationCallbackArgs);
        }
    }


    TabsDiv.prototype.invalidateTabs = function(){
        for(var l_index = 0; l_index < this.m_contentInitializedArray.length; l_index++){
           this.m_contentInitializedArray[l_index] = false;
        }
    }   
// TabsDiv





function TextBoxDiv(a_parentDiv, a_defaultText){

    var m_parentDiv = a_parentDiv;
    var m_defaultText = a_defaultText;
    var m_textDiv = null;
    var m_textArea = null;

    this.createDiv = createDiv;
    this.getText = getText;
    this.getTextArea = getTextArea;
    this.clear = clear;

    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        m_textDiv = document.createElement("div");
        m_parentDiv.appendChild(m_textDiv);

        m_textArea = document.createElement("textarea");
        m_textDiv.appendChild(m_textArea);
        m_textArea.rows = "3";
        m_textArea.style.fontSize = "11px";
        m_textArea.style.fontFamily = "lucida grande,tahoma,verdana,arial,sans-serif";
        if(m_defaultText != undefined && m_defaultText != null){
            m_textArea.appendChild(document.createTextNode(m_defaultText));
        }
    }

    function clear(){
        m_textArea.innerHTML = "";
    }

    function getText(){
        return m_textArea.value;
    }

    function getTextArea(){
        return m_textArea;
    }
}


function TextFieldDiv(a_parentDiv, a_defaultText, size, maxLength){

    var m_parentDiv = a_parentDiv;
    var m_defaultText = a_defaultText;
    var m_textDiv = null;
    var m_textField = null;
    var m_size = size;
    var m_maxLength = maxLength;

    this.createDiv = createDiv;
    this.getText = getText;

    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        outputDebug("TextFieldDiv: createDiv");

        m_textDiv = document.createElement("div");
        m_parentDiv.appendChild(m_textDiv);

        try{
           m_textField = document.createElement("<input type='text' size='"+m_size+"' maxlength='"+m_maxLength+"'/>");    // IE
        }catch(error){
            m_textField = document.createElement("input");    // firefox
            m_textField.type = "text";
            m_textField.size = m_size;
            m_textField.maxLength = maxLength;
        }
        if(m_defaultText != undefined && m_defaultText != null){
           m_textField.value = a_defaultText;
        }
        m_textDiv.appendChild(m_textField);
    }

    function getText(){
        return m_textField.value;
    }
}

function CenteredTextMessageDiv(a_parentDiv, a_messageText, a_width){

    var m_parentDiv = a_parentDiv;
    var m_messageText = a_messageText;
    var m_width = a_width;
    var m_outerDiv = null;
    var m_textDiv = null;

    this.createDiv = createDiv;
    this.getTextDiv = getTextDiv;

    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        outputDebug("CenteredTextMessageDiv: createDiv");

        m_outerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_outerDiv);
        m_outerDiv.style.textAlign  = "center";

        m_textDiv = document.createElement("div");
        m_outerDiv.appendChild(m_textDiv);
        m_textDiv.style.backgroundColor = "#f7f7f7";
        m_textDiv.style.marginLeft = "auto";
        m_textDiv.style.marginRight = "auto";
        m_textDiv.style.width = m_width;
        m_textDiv.style.padding = "5px 5px 5px 10px";
        m_textDiv.style.color = "#333333";
        m_textDiv.style.borderStyle = "solid";
        m_textDiv.style.borderWidth = "0px";
        m_textDiv.style.borderColor = "#7f93bc";

        m_textDiv.innerHTML = m_messageText;
    }

    function getTextDiv(){
        return m_textDiv;
    }
}


function TextMessageDiv(a_parentDiv, a_messageText){

    var m_parentDiv = a_parentDiv;
    var m_messageText = a_messageText;
    var m_textDiv = null;

    this.createDiv = createDiv;
    this.getContainerDiv = getContainerDiv;

    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        outputDebug("HTMLDiv: createDiv");

        m_textDiv = document.createElement("div");
        m_parentDiv.appendChild(m_textDiv);
        m_textDiv.style.backgroundColor = "#fff9d7";
        m_textDiv.style.margin = "5px 10px 10px 10px";
        m_textDiv.style.padding = "5px 5px 5px 10px";
        m_textDiv.style.color = "#333333";
        m_textDiv.style.borderStyle = "solid";
        m_textDiv.style.borderWidth = "0px";
        m_textDiv.style.borderColor = "#e2c822";

        m_textDiv.innerHTML = m_messageText;
    }

    function getContainerDiv(){
        return m_textDiv;
    }
}


function switchTabs(a_index){
    GBL.MAIN_TABS.switchToTab(a_index);
}

function showViewerStats(){
    GBL.STATUS_DIV.showViewerStats();
}

function showUserStats(a_userId){
    window.open(GBL.APP_CANVAS_URL + "appParams=%7B%22"+GBL.SHOW_USER_ID+"%22%3A%22"+a_userId+"%22%7D");
}

function showMobStats(a_userId){
    window.open(GBL.APP_CANVAS_URL + "appParams=%7B%22"+GBL.SHOW_USER_ID+"%22%3A%22"+a_userId+"%22%7D");
}


function createWhiteDiv(a_parentDiv){
    var l_div = document.createElement("div");
    a_parentDiv.appendChild(l_div);
    l_div.style.color = "#000000";
    l_div.style.textAlign = "left";
    return l_div;
}


function addHeaderStyle(a_element){
    a_element.style.borderLeft = "solid 0px #AAAAAA";
    a_element.style.borderTop = "solid 0px #AAAAAA";
   // a_element.style.borderRight = "solid 2px #454545";
  //  a_element.style.borderBottom = "solid 2px #454545";
    a_element.style.padding = "6px";
    a_element.style.color = "white";
    a_element.style.fontSize = "11px";
    a_element.style.fontWeight = "bold";
    a_element.style.fontStyle = "italic";
}

function addHeaderStyleWithInnerDiv(a_container, a_title, a_width){
    a_container.style.width = a_width;
    a_container.style.paddingLeft = "5px";
    a_container.style.paddingRight = "5px";
    
    var l_div = document.createElement("div");
    a_container.appendChild(l_div);
    l_div.style.borderLeft = "solid 0px #AAAAAA";
    l_div.style.borderTop = "solid 0px #AAAAAA";
    l_div.style.borderRight = "solid 0px #454545";
    l_div.style.borderBottom = "solid 0px #454545";
    l_div.style.padding = "6px";
    l_div.style.color = "white";
    l_div.style.fontSize = "11px";
    l_div.style.fontWeight = "bold";
    l_div.style.textAlign = "left";
    l_div.style.fontStyle = "italic";
    l_div.innerHTML = a_title;
}



function createTitleDiv(a_globalTitleDiv, a_titleHTML, a_optionsTitleArray, a_optionsTitleCallbacks, a_sameRow){

    a_globalTitleDiv.innerHTML = "";

    var l_topTitleDiv = document.createElement("div");
    a_globalTitleDiv.appendChild(l_topTitleDiv);
    l_topTitleDiv.style.borderBottom = "solid 0px #777777";
    l_topTitleDiv.style.textAlign = "left";

    var l_contentTable = document.createElement("table");
    l_topTitleDiv.appendChild(l_contentTable);
    var l_contentTBody = document.createElement("tbody");
    l_contentTable.appendChild(l_contentTBody);
    var l_tr = document.createElement("tr");
    l_contentTBody.appendChild(l_tr);

    var l_td = document.createElement("td");
    l_tr.appendChild(l_td);
    l_td.style.marginLeft = "50px";
    l_td.style.textAlign = "left";
    l_td.style.fontSize = "20px";
    l_td.style.fontWeight = "bold";
    l_td.style.color = "#FFFFFF";
    l_td.innerHTML = a_titleHTML;

    outputDebug("options length: " + a_optionsTitleArray + " same row: " + a_sameRow);

    if(!isValid(a_optionsTitleArray) || a_optionsTitleArray.length <= 0){
        return;
    }

    outputDebug("doing options");

    if(!a_sameRow){
        var l_subTitleDiv = document.createElement("div");
        a_globalTitleDiv.appendChild(l_subTitleDiv);
        l_subTitleDiv.style.textAlign = "left";
        l_subTitleDiv.style.borderBottom = "solid 0px #777777";
        var l_sub_contentTable = document.createElement("table");
        l_subTitleDiv.appendChild(l_sub_contentTable);
        var l_sub_contentTBody = document.createElement("tbody");
        l_sub_contentTable.appendChild(l_sub_contentTBody);
        l_tr = document.createElement("tr");
        l_sub_contentTBody.appendChild(l_tr);
    }


    for(var l_index = 0; l_index < a_optionsTitleArray.length; l_index++){
        l_td = document.createElement("td");
        l_tr.appendChild(l_td);

        l_td.style.fontSize = "12px";
        l_td.style.fontWeight = "bold";
        l_td.style.paddingLeft = "5px";
        l_td.style.paddingRight = "5px";
        l_td.style.verticalAlign = "bottom";
        l_td.innerHTML = a_optionsTitleArray[l_index];

        if(isValidFunction(a_optionsTitleCallbacks[l_index])){
            l_td.style.color = "#88BBEE";
            l_td.style.cursor = "pointer";
            addEvent(l_td, "click", a_optionsTitleCallbacks[l_index]);
        }else{
            l_td.style.color = "#FFFFFF";            
        }

        if(l_index > 0){
            l_td.style.borderLeft = "solid 2px #FFFFFF";
        }
    }
}


function handleResult(a_response, a_resultDiv, a_refreshCallback){
    var l_xmlDoc = undefined;

    try{
        l_xmlDoc = getGadgetResponseData(a_response);
    } catch(err){
        l_xmlDoc = undefined;
    }

    if(!isValid(l_xmlDoc)){
        a_resultDiv.showMessage(undefined, "Sorry, there was an unexpected error. Please refresh and try again.");
        return;
    }

    var l_success = getBooleanValue(getXMLNodeValue(l_xmlDoc, "success"));
    var l_msg = getXMLEncodedStringNodeValue(l_xmlDoc, "message");
    var l_bulletinInfoNode = getXMLFirstNode(l_xmlDoc, "bulletin");
    var l_updatedInfoNode = getXMLFirstNode(l_xmlDoc, "viewer");
    var l_prevViewerLevel = GBL.MAIN_DATA.getViewer().getLevel();

    if(isValid(l_success)){
        if(l_success){
            a_resultDiv.showMessage(true, l_msg, l_bulletinInfoNode);
            GBL.MAIN_DATA.getViewer().fillSpecificInfoFromXML(l_updatedInfoNode);

            if(isValid(GBL.MAIN_TABS) && l_prevViewerLevel != GBL.MAIN_DATA.getViewer().getLevel()){
                GBL.MAIN_TABS.invalidateTabs();
            }

            if(isValid(GBL.STATUS_DIV) && isValid(GBL.REFRESH_STATUS)){
                GBL.STATUS_DIV.refreshStatus();
                GBL.REFRESH_STATUS.refreshStatus();
            }
            if(isValidFunction(a_refreshCallback)){
                a_refreshCallback();
            }
        } else {
            a_resultDiv.showMessage(false, l_msg);
        }
    } else {        
        a_resultDiv.showMessage(undefined, "Sorry, there was an unexpected error. Please refresh and try again.");
    }
}


function createItemsListDiv(a_parentDiv, a_itemsArray, a_numItemsPerRow){
    if(!isValid(a_itemsArray) || a_itemsArray.length <= 0){
        return;
    }

    var l_div = document.createElement("div");
    a_parentDiv.appendChild(l_div);
    l_div.style.padding = "8px";

    var l_contentTable = document.createElement("table");
    l_div.appendChild(l_contentTable);
    var l_contentTBody = document.createElement("tbody");
    l_contentTable.appendChild(l_contentTBody);

    var l_tr = undefined;

    for(var l_index = 0; l_index < a_itemsArray.length; l_index++){
        if(l_index % a_numItemsPerRow == 0){
            l_tr = document.createElement("tr");
            l_contentTBody.appendChild(l_tr);
        }

        var l_itemData = a_itemsArray[l_index];

        var l_numTd = document.createElement("td");
        l_tr.appendChild(l_numTd);
        l_numTd.style.paddingLeft = "10px" ;
        l_numTd.style.color = "#FFFFFF";
        l_numTd.style.verticalAlign = "middle";
        var l_message = "<span style='font-weight:bold;'>";
        if (isValid(l_itemData.probability)) {
            l_message += l_itemData.probability + "% chance of "
        }
        if (isValid(l_itemData.number)) {
            l_message += l_itemData.number + " x "
        }
        l_message += "</span>";
        l_numTd.innerHTML = l_message;

        var l_itemTd = document.createElement("td");
        l_tr.appendChild(l_itemTd);

        var l_img = document.createElement("img");
        l_itemTd.appendChild(l_img);
        l_img.src = l_itemData.image_url;

        var l_whiteDiv = createWhiteDiv(l_itemTd);
        l_whiteDiv.style.fontSize = "11px";
        l_whiteDiv.innerHTML = l_itemData.name;
    }
}


function NumberSelectActionDiv(a_parentDiv, a_maxNumber, a_actionTitle, a_callback, a_buttonColor){

    var m_parentDiv = a_parentDiv;
    var m_containerDiv = undefined;
    var m_maxNumber = a_maxNumber;
    var m_actionTitle = a_actionTitle;
    var m_callback = a_callback;
    var m_buttonColor = a_buttonColor;

    var m_select = undefined;
    var m_selectOptions = new Array();

    createDiv();

    function createDiv(){

        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);

        var l_ssCells = new SideBySideCells(m_containerDiv);

        m_select = document.createElement("select");
        l_ssCells.getLeftCell().appendChild(m_select);
        for(var l_index = 1; l_index <= m_maxNumber; l_index++){
            createOption(l_index, l_index, l_index == 1);
        }

        var l_button = new DivButton(l_ssCells.getRightCell(), m_actionTitle, function(){
            m_callback(getSelectedNumber());
        });
        if(isValid(m_buttonColor)){
            l_button.getButtonDiv().style.backgroundColor = m_buttonColor;
        }
    }


    function createOption(a_text, a_value, a_selected){
        var l_option = document.createElement("OPTION");
        l_option.innerHTML = a_text;
        l_option.value = a_value;
        l_option.selected = a_selected;
        m_select.appendChild(l_option);
        m_selectOptions.push(l_option);
    }

    function getSelectedNumber(){
        for(var l_index = 0; l_index < m_selectOptions.length; l_index++){
            if(m_selectOptions[l_index].selected){
                return m_selectOptions[l_index].value;
            }
        }
        return undefined;
    }
}
/*
//InitialChooserDiv
    function InitialChooserDiv(a_parentDiv, a_finish_callback){

        this.m_parentDiv = a_parentDiv;
        this.m_finishCallback = a_finish_callback;
        this.m_containerDiv = undefined;
        this.m_title = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;


        this.m_chooseNameTitle = undefined;
        this.m_chooseNameExplanation = undefined;
        this.m_chooseClassTitle = undefined;
        this.m_chooseClassExplanation = undefined;
        this.m_classDescriptionsArray = undefined;
        this.m_classNameArray = undefined;

        this.initialize();
        this.createDiv();
    }

    InitialChooserDiv.prototype.initialize = function(){
        this.m_chooseNameTitle = "Choose Mob Name";
        this.m_chooseNameExplanation = "Choose your mob name (please be tasteful):";
        this.m_warningText = "<span style='color:#FF0000; fot-weight:bold;'> Warning! Please change your mob name. </span> <br> Users have complained that your mob name is inappropriate. <br>" +
                             "<span style='font-style:italic;'>If your name is reported as inappropriate again, your account will be banned.</span>";

        this.m_chooseClassTitle = "Choose Mob Class";
        this.m_chooseClassExplanation = "Choose your mob class:";

        this.m_classNameArray = new Array();
        this.m_classDescriptionsArray = new Array();

        this.m_classNameArray.push("Insomniac");
        this.m_classDescriptionsArray.push("Insomniac (get energy faster)");

        this.m_classNameArray.push("Bulletproof");
        this.m_classDescriptionsArray.push("Bulletproof (heal faster)");

        this.m_classNameArray.push("Tycoon");
        this.m_classDescriptionsArray.push("Tycoon (get money faster)");
    }

    InitialChooserDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";

        this.m_title = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_title);

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.color = "#FFFFFF";

        this.refresh();
    }


    InitialChooserDiv.prototype.refresh = function(){
        this.m_refreshDiv.innerHTML = "";

        if(!isValid(GBL.MAIN_DATA.getViewer().getMobName())){
            this.createChooseNameInterface();

        } else if(!isValid(GBL.MAIN_DATA.getViewer().getMobClass())){
            this.createChooseMobClassInterface();

        } else {            
            this.m_finishCallback();
        }
    }

    InitialChooserDiv.prototype.createChooseNameInterface = function(){
        createTitleDiv(this.m_title, this.m_chooseNameTitle);

        var l_viewerExp = GBL.MAIN_DATA.getViewer().getExperience();
        if(isValid(this.m_warningText) && isValid(l_viewerExp) && l_viewerExp > 0){
            var l_warningDiv = createWhiteDiv(this.m_refreshDiv);
            l_warningDiv.innerHTML = this.m_warningText;
        }


        var l_contentTable = document.createElement("table");
        this.m_refreshDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_tr = document.createElement("tr");
        l_contentTBody.appendChild(l_tr);


        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = this.m_chooseNameExplanation;



        var l_nameField = undefined;
        try{
            l_nameField = document.createElement("<input type='text' maxlength='20' />");    // IE
        }catch(error){
            l_nameField = document.createElement("input");    // firefox
            l_nameField.type = "text";
            l_nameField.maxLength = "20";
        }
        l_nameField.style.width = "150px";
        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.appendChild(l_nameField);



        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";

        var l_self = this;

        new Button(l_td, "Choose Name", function(){
            l_self.m_resultDiv.showMessage(undefined, "Checking ... ");

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.mob_name =encodeURIComponent(l_nameField.value);

            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/choose_name",
                function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                l_params);
        });
    }


    InitialChooserDiv.prototype.createChooseMobClassInterface = function(){

        createTitleDiv(this.m_title, this.m_chooseClassTitle);

        var l_contentTable = document.createElement("table");
        this.m_refreshDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_tr = document.createElement("tr");
        l_contentTBody.appendChild(l_tr);


        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = this.m_chooseClassExplanation;



        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";

        var l_select = document.createElement("select");
        l_td.appendChild(l_select);

        var l_options = new Array();
        var l_option = undefined;

        for(var l_index = 0; l_index < this.m_classNameArray.length; l_index++){
            l_option = this.createOption(this.m_classDescriptionsArray[l_index], this.m_classNameArray[l_index], l_index==0);
            l_select.appendChild(l_option);
            l_options.push(l_option);
        }


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";

        var l_self = this;
        new Button(l_td, "Choose", function(){
            l_self.m_resultDiv.showMessage(undefined, "Checking ... ");

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            for(var l_index = 0; l_index < l_options.length; l_index++){
                if(l_options[l_index].selected){
                    l_params.mob_class = l_options[l_index].value;
                    break;
                }
            }

            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/choose_class",
                function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                l_params);
        });
    }

    InitialChooserDiv.prototype.createOption = function(a_text, a_value, a_selected){
        var l_option = document.createElement("OPTION");
        l_option.innerHTML = a_text;
        l_option.value = a_value;
        l_option.selected = a_selected;
        return l_option;
    }*/
//end InitialChooserDiv

function MobDoRefresh(){
    var l_params = {};
    l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
   /* makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/refresh_stat",
            function(a_response){
                var l_xmlDoc = getGadgetResponseData(a_response);
                var l_updatedInfoNode = getXMLFirstNode(l_xmlDoc, "viewer");
                GBL.MAIN_DATA.getViewer().fillSpecificInfoFromXML(l_updatedInfoNode);

                if(isValid(GBL.STATUS_DIV) && isValid(GBL.REFRESH_STATUS)){
                    GBL.MAIN_DATA.getCachedUsers(CachedUserList.MY_REQUESTS).invalidateCache();
                    GBL.MAIN_DATA.getCachedUsers(CachedUserList.MY_MOB).invalidateCache();
                    GBL.STATUS_DIV.refreshStatus();
                    GBL.REFRESH_STATUS.refreshStatus();
                    GBL.MAIN_TABS.refreshTab();
                }
            },
            l_params);*/
}



//ViewerStatusDiv
    function ViewerStatusDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;

        this.m_cashLabel = undefined;
        this.m_healthLabel = undefined;
        this.m_energyLabel = undefined;
        this.m_staminaLabel = undefined;
        this.m_expLabel = undefined;
        this.m_mobLabel = undefined;
        this.m_statsDiv = undefined;

        this.m_refreshButtonDiv = undefined;
        this.m_refreshButtonEnabled = true;

        this.m_maxNameLength = 12;


        this.initialize();
      //  this.createDiv();
    }

    ViewerStatusDiv.prototype.initialize = function(){
        this.m_cashLabel = "Cash";
        this.m_healthLabel = "Health";
        this.m_energyLabel = "Energy";
        this.m_staminaLabel = "Stamina";
        this.m_expLabel = "Exp";
        this.m_mobLabel = "Mob";
        this.m_statsDiv = StatsDiv;
        this.m_lastRefreshTime = (new Date()).getTime();
    }


    ViewerStatusDiv.prototype.createDiv = function(){
        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.textAlign  = "center";

        this.refreshStatus();
    }


    ViewerStatusDiv.prototype.refreshStatus = function(){

        this.m_containerDiv.innerHTML = "";

        var l_user = GBL.MAIN_DATA.getViewer();

        var l_contentTable = document.createElement("table");
        this.m_containerDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderCollapse = "separate";
        l_contentTable.style.borderSpacing = "8px 3px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);
        var l_contentTR = document.createElement("tr");
        l_contentTBody.appendChild(l_contentTR);



        var l_statusTd = document.createElement("td");
        l_contentTR.appendChild(l_statusTd);
        this.addStandardStyle(l_statusTd);
        this.addLinkToMyBoss(l_statusTd);

        var l_statusTable = document.createElement("table");
        l_statusTd.appendChild(l_statusTable);
        l_statusTable.style.borderCollapse = "separate";
        l_statusTable.style.borderSpacing = "8px 0px";
        var l_statusTBody = document.createElement("tbody");
        l_statusTable.appendChild(l_statusTBody);
        var l_statusTR = document.createElement("tr");
        l_statusTBody.appendChild(l_statusTR);


        var l_nameTD = document.createElement("td");
        l_statusTR.appendChild(l_nameTD);
        this.addTextStyle(l_nameTD);
        l_nameTD.innerHTML = "<span style='color:#FFA500; font-size:12px; font-weight:bold;'>" + GBL.MAIN_DATA.getViewer().getShortMobName(this.m_maxNameLength) + "</span>";        

        var l_healthTD = document.createElement("td");
        l_statusTR.appendChild(l_healthTD);
        this.addTextStyle(l_healthTD);
        l_healthTD.innerHTML = this.m_healthLabel + ": " + l_user.getHealth() + "/" + l_user.getMaxHealth();

        var l_energyTD = document.createElement("td");
        l_statusTR.appendChild(l_energyTD);
        this.addTextStyle(l_energyTD);
        //l_energyTD.innerHTML = this.m_energyLabel + ": " + l_user.getEnergy() + "/" + l_user.getMaxEnergy();

        var l_staminaTD = document.createElement("td");
        l_statusTR.appendChild(l_staminaTD);
        this.addTextStyle(l_staminaTD);
        //l_staminaTD.innerHTML = this.m_staminaLabel + ": " + l_user.getStamina() + "/" + l_user.getMaxStamina();


        var l_cashTD = document.createElement("td");
        l_statusTR.appendChild(l_cashTD);
        this.addTextStyle(l_cashTD);
       // l_cashTD.innerHTML = this.m_cashLabel + ": $" + formatNumberWithCommas(l_user.getCash());


        var l_mobTD = document.createElement("td");
        l_statusTR.appendChild(l_mobTD);
        this.addTextStyle(l_mobTD);
       // l_mobTD.innerHTML = this.m_mobLabel + ": (" + l_user.getMobSize() + ")";

        
        var l_expTD = document.createElement("td");
        l_statusTR.appendChild(l_expTD);
        this.addTextStyle(l_expTD);
       // l_expTD.innerHTML = this.m_expLabel + ": " + l_user.getExperience();



        var l_levelTD = document.createElement("td");
        l_statusTR.appendChild(l_levelTD);
        this.addTextStyle(l_levelTD);
        l_levelTD.style.color = "#32CD32";
        l_levelTD.style.textAlign = "left";
        l_levelTD.style.fontWeight = "bold";
       // l_levelTD.innerHTML = "Level:" + l_user.getLevel();

        var l_percent = GBL.MAIN_DATA.getViewer().getPercentToNextLevel();
        if(isValid(l_percent)){
            var l_barOutDiv = document.createElement("div");
            l_levelTD.appendChild(l_barOutDiv);
            l_barOutDiv.style.height = "3px";
            l_barOutDiv.style.overflow = "hidden";

            var l_percentLevelDiv = document.createElement("div");
            l_barOutDiv.appendChild(l_percentLevelDiv);
            l_percentLevelDiv.style.backgroundColor = "#38B0DE";
            l_percentLevelDiv.style.width = l_percent + "%";
            l_percentLevelDiv.style.height = "3px";                        
        }        





        var l_statsTD = document.createElement("td");
        l_contentTR.appendChild(l_statsTD);
        this.addStandardStyle(l_statsTD);
        this.addLinkToStats(l_statsTD);
        l_statsTD.style.color = "#70DBDB";
        l_statsTD.style.textDecoration = "underline";        
        //l_statsTD.innerHTML = "My Stats";



        
        var l_refreshTD = document.createElement("td");
        l_contentTR.appendChild(l_refreshTD);
        l_refreshTD.style.paddingLeft = "10px";

        this.m_refreshButtonEnabled = true;

        this.m_refreshButtonDiv = document.createElement("div");
        l_refreshTD.appendChild(this.m_refreshButtonDiv);
        this.m_refreshButtonDiv.style.borderLeft = "solid 0px #2F2F4F";
        this.m_refreshButtonDiv.style.border = "solid 0px #555555";
        this.m_refreshButtonDiv.style.backgroundColor = "#2F2F4F"
        this.m_refreshButtonDiv.style.paddingTop = "3px";
        this.m_refreshButtonDiv.style.paddingBottom = "3px";
        this.m_refreshButtonDiv.style.paddingLeft = "10px";
        this.m_refreshButtonDiv.style.paddingRight = "10px";
        this.m_refreshButtonDiv.style.color = "white";
        this.m_refreshButtonDiv.style.fontSize = "11px";
        //this.m_refreshButtonDiv.innerHTML = "REFRESH";
        this.m_refreshButtonDiv.style.cursor = "pointer";

        var l_self = this;
        addEvent(this.m_refreshButtonDiv, "click", function(){
            if(l_self.m_refreshButtonEnabled){
                l_self.m_refreshButtonEnabled = false;

                l_self.m_refreshButtonDiv.style.cursor = "default";
                l_self.m_refreshButtonDiv.style.backgroundColor = "#555555"
                l_self.m_refreshButtonDiv.innerHTML = "refreshing...";

                window.setTimeout("GBL.STATUS_DIV.enableRefreshButton()", 1000);
                MobDoRefresh();
            }
        });  
    }

    ViewerStatusDiv.prototype.enableRefreshButton = function(){
        this.m_refreshButtonEnabled = true;
        this.m_refreshButtonDiv.style.cursor = "pointer";
        this.m_refreshButtonDiv.style.backgroundColor = "#2F2F4F"
        this.m_refreshButtonDiv.innerHTML = "REFRESH";

    }

    ViewerStatusDiv.prototype.addLinkToMyMob = function(a_td){
        a_td.style.cursor = "pointer";
        addEvent(a_td, "click", function(){
            GBL.MAIN_TABS.switchToTab(9);
        });
    }


    ViewerStatusDiv.prototype.addLinkToMyBoss = function(a_td){
        a_td.style.cursor = "pointer";
        addEvent(a_td, "click", function(){
            GBL.MAIN_TABS.switchToTab(10);
        });
    }


    ViewerStatusDiv.prototype.addLinkToStats = function(a_td){
        a_td.style.cursor = "pointer";
        var l_self = this;
        addEvent(a_td, "click", function(){
            GBL.MAIN_TABS.switchToDynamicTab(
                    function(a_contentDiv){
                        a_contentDiv.innerHTML = "";
             //           new l_self.m_statsDiv(a_contentDiv, GBL.MAIN_DATA.getViewer().getUserId());
                    }
            );
        });
    }

    ViewerStatusDiv.prototype.addTextStyle = function(a_td){
        a_td.style.paddingLeft = "6px";
        a_td.style.paddingRight = "6px";
        a_td.style.color = "white";
        a_td.style.fontSize = "11px";
    }


    ViewerStatusDiv.prototype.addStandardStyle = function(a_td){
        a_td.style.borderLeft = "solid 0px #AAAAAA";
        a_td.style.borderTop = "solid 0px #AAAAAA";
        a_td.style.borderRight = "solid 0px #000000";
        a_td.style.borderBottom = "solid 0px #000000";
        a_td.style.backgroundColor = "#000000"
        a_td.style.paddingTop = "3px";
        a_td.style.paddingBottom = "3px";
        a_td.style.paddingLeft = "6px";
        a_td.style.paddingRight = "6px";
        a_td.style.color = "white";
        a_td.style.fontSize = "11px";        
    }

    ViewerStatusDiv.prototype.showViewerStats = function(){
        var l_self = this;
        GBL.MAIN_TABS.switchToDynamicTab(
                function(a_contentDiv){
                    a_contentDiv.innerHTML = "";
                    new l_self.m_statsDiv(a_contentDiv, GBL.MAIN_DATA.getViewer().getUserId());
                }
        );
    }
// end ViewerStatusDiv







function Timer(a_timerId, a_millis, a_tickCallback){
    var m_timerId = a_timerId;
    var m_millis = a_millis;
    var m_tickCallback = a_tickCallback;

    var m_running = false;

    this.start = start;
    this.stop = stop;
    this.tick = tick;
    this.isRunning = isRunning;

    function start(){
        m_running = true;
        tick();
    }

    function isRunning(){
        return m_running;
    }

    function stop(){
        m_running = false;
    }

    function tick(){
        if(m_running){
            m_tickCallback();
            window.setTimeout(m_timerId+".tick()", m_millis);
        }
    }
}



ViewerRefreshStatus.TIMER = undefined;

// ViewerRefreshStatus
    function ViewerRefreshStatus(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_secondsToHealth = undefined;
        this.m_secondsToEnergy = undefined;
        this.m_secondsToStamina = undefined;

        this.m_secondsToEnergySuffix = undefined;
        this.m_secondsToHealthSuffix = undefined;
        this.m_secondsToStaminaSuffix = undefined;

        this.initialize();            
        this.createDiv();
    }

    ViewerRefreshStatus.prototype.initialize = function(){
      //  this.m_secondsToEnergySuffix = " sec until more energy.<br>";
       // this.m_secondsToHealthSuffix = " sec until more health.<br>";
       // this.m_secondsToStaminaSuffix = " sec until more stamina.<br>";
    }

    ViewerRefreshStatus.prototype.createDiv = function(){
        outputDebug("ViewerStatusDiv: createDiv");

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.textAlign  = "center";
        this.m_containerDiv.style.position = "absolute";
        this.m_containerDiv.style.left = "760";
        this.m_containerDiv.style.top = "20";
        this.m_containerDiv.style.color = "#AAAAAA";
        this.m_containerDiv.style.fontSize = "11px";

        this.refreshStatus();

        var l_self = this;
        if(!isValid(ViewerRefreshStatus.TIMER)){
            ViewerRefreshStatus.TIMER = new Timer("ViewerRefreshStatus.TIMER", 1000, function(){l_self.onTick();});
            ViewerRefreshStatus.TIMER.start();
        }
    }

    ViewerRefreshStatus.prototype.refreshStatus = function(){
        var l_user = GBL.MAIN_DATA.getViewer();
        this.m_secondsToHealth = l_user.getSecondsToHealthRefresh();
        this.m_secondsToEnergy = l_user.getSecondsToEnergyRefresh();
        this.m_secondsToStamina = l_user.getSecondsToStaminaRefresh();

        if(isValid(this.m_secondsToEnergy)){ this.m_secondsToEnergy = parseInt(this.m_secondsToEnergy) + 2;}
        if(isValid(this.m_secondsToHealth)){ this.m_secondsToHealth = parseInt(this.m_secondsToHealth) + 2;}
        if(isValid(this.m_secondsToStamina)){ this.m_secondsToStamina = parseInt(this.m_secondsToStamina) + 2;}


        this.onTick();
    }


    ViewerRefreshStatus.prototype.onTick = function(){

        var l_user = GBL.MAIN_DATA.getViewer();
        if(!isValid(l_user)){
            return;
        }

        this.m_containerDiv.innerHTML = "";

        if(!isValid(l_user.getSecondsToHealthRefresh()) &&
           !isValid(l_user.getSecondsToEnergyRefresh()) &&
           !isValid(l_user.getSecondsToStaminaRefresh())) {

          //  this.m_containerDiv.innerHTML = "<span style='color:#00FF00'>Status: normal </span>";
            return;
        }
        

        var l_needsRefresh = false;
        if(isValid(this.m_secondsToHealth)){
            if(this.m_secondsToHealth >= 1){
                this.m_containerDiv.innerHTML += this.m_secondsToHealth + this.m_secondsToHealthSuffix;
            } else {
               l_needsRefresh = true;
            }
            this.m_secondsToHealth -= 1;
        }

        if(isValid(this.m_secondsToEnergy)){
            if(this.m_secondsToEnergy >= 1) {
                this.m_containerDiv.innerHTML += this.m_secondsToEnergy + this.m_secondsToEnergySuffix;
            } else {
               l_needsRefresh = true;
            }
            this.m_secondsToEnergy -= 1;
        }

        if(isValid(this.m_secondsToStamina)){
            if(this.m_secondsToStamina >= 1) {
                this.m_containerDiv.innerHTML += this.m_secondsToStamina + this.m_secondsToStaminaSuffix;
            } else {
               l_needsRefresh = true;
            }
            this.m_secondsToStamina -= 1;
        }

        if(l_needsRefresh){
         //   this.m_containerDiv.innerHTML = "<a class='standardLink' href='#' onclick='MobDoRefresh();return false;'>Please refresh </a>";        
        }

    }
// end ViewerRefreshStatus


//NewsFeedEntry
    function NewsFeedEntry(a_xmlNode){
        this.m_xmlNode = a_xmlNode;
        this.m_id = undefined;
        this.m_timeAgo = undefined;
        this.m_messageHTML = undefined;

        this.fillFromXML();
    }

    NewsFeedEntry.prototype.fillFromXML = function(){
       if(!isValid(this.m_xmlNode)){
            return;
       }
       try{ this.m_id = getXMLNodeValue(this.m_xmlNode,"id");}catch(err){};
       try{ this.m_timeAgo = getXMLEncodedStringNodeValue(this.m_xmlNode,"time_ago");}catch(err){};
       try{ this.m_messageHTML = getXMLEncodedStringNodeValue(this.m_xmlNode,"message_html");}catch(err){};
    }

    NewsFeedEntry.prototype.getId = function(){
        return this.m_id;
    }

    NewsFeedEntry.prototype.getTimeAgo = function(){
        return this.m_timeAgo;
    }

    NewsFeedEntry.prototype.getMessageHTML = function(){
        return this.m_messageHTML;
    }
//end NewsFeedEntry



/*

//NewsFeedDiv
    function NewsFeedDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_sendCommandText = undefined;

        this.initialize();
        this.createDiv();
    }

    NewsFeedDiv.prototype.initialize = function(){
        this.m_sendCommandText = "Broadcast a message to your mob for ";
    }

    NewsFeedDiv.prototype.createBulletinSubject = function(){
        return  "A broadcast to my Mob Family!";
    }

    NewsFeedDiv.prototype.createBulletin = function(a_msg){
        return  a_msg +
                "<br><br>------------------------------------------------------<br>" +
                "<a href='"+GBL.APP_CANVAS_URL+"track=command'>This message sent from: Mobsters. Start a Mob with your friends. Rise from a petty thief to Mafia Don. Rule MySpace!</a>";
    }

    NewsFeedDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.margin = "20px";
        this.m_containerDiv.style.padding = "10px";
        this.m_containerDiv.style.border = "solid 1px #AAAAAA";

        if(isValid(this.m_sendCommandText)){
            this.createCommentInputDiv();
        }

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.marginTop = "20px";        
        this.m_refreshDiv.style.paddingTop = "10px";
        this.m_refreshDiv.style.height = "1000px";
        this.m_refreshDiv.style.overflow = "auto";

        this.refresh();
    }


    NewsFeedDiv.prototype.createCommentInputDiv = function(){

        var l_commandInputDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_commandInputDiv);
        l_commandInputDiv.style.marginTop = "10px";


        var l_expDiv = document.createElement("div");
        l_commandInputDiv.appendChild(l_expDiv);
        l_expDiv.style.color = "#EEEEEE";
        l_expDiv.style.fontWeight = "bold";
        l_expDiv.style.fontSize = "12px";
        l_expDiv.innerHTML = this.m_sendCommandText + " $"+formatNumberWithCommas(25*GBL.MAIN_DATA.getViewer().getMobSize()) ;


        this.m_resultDiv = new ResultDiv(l_commandInputDiv);

        var l_commentMsg = new TextBoxDiv(l_commandInputDiv);
        l_commentMsg.getTextArea().style.width = "320px";


        var l_self = this;
        var l_sendButton = new DivButton(l_commandInputDiv, "Send Broadcast & Bulletin", function(){
            if(l_commentMsg.getText().length <= 0){
                l_self.m_resultDiv.showMessage(undefined, "Please type a message.");
                return;
            }
            if(l_commentMsg.getText().length > 300){
                l_self.m_resultDiv.showMessage(undefined, "Sorry, the maximum length limit is 300 characters.");
                return;
            }
            l_self.m_resultDiv.showMessage(undefined, "Sending...");

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.message = customEncoding(l_commentMsg.getText());
            l_params.cost = (25*GBL.MAIN_DATA.getViewer().getMobSize());

            postToBulletin(GBL.MAIN_DATA.getViewer(),
                            l_self.createBulletinSubject(),
                            l_self.createBulletin(l_commentMsg.getText()),
                            function(a_status){});
            
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/broadcast",
                                    function(a_response){
                                        handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();});},
                                    l_params, 0);
        });

        l_sendButton.getButtonDiv().style.marginTop = "5px";
        l_sendButton.getButtonDiv().style.marginLeft = "10px";
        l_sendButton.getButtonDiv().style.width = "200px";
        l_sendButton.getButtonDiv().style.fontSize = "11px";
    }



    NewsFeedDiv.prototype.refresh = function(){
        this.m_refreshDiv.style.display = "none";
        this.m_refreshDiv.innerHTML = "";

        var l_self = this;
        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_newsfeeds", function(a_responseData){
           l_self.onGetNewsfeeds(a_responseData);
        },l_params);
    }


    NewsFeedDiv.prototype.onGetNewsfeeds = function(a_responseData){

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        var l_entries = new Array();
        if(isValid(l_xmlDoc)){
            try{
                var l_entryNodes = l_xmlDoc.getElementsByTagName("entry");
                for(var l_index = 0; l_index < l_entryNodes.length; l_index++){
                    l_entries.push(new NewsFeedEntry(l_entryNodes[l_index]));
                }
            } catch (err) { outputAlert("onGetStockpileList " + err);}
        }

        if(l_entries.length <= 0){
            return;
        }

        this.m_refreshDiv.style.display = "block";
        var l_titleCells = new SideBySideCells(this.m_refreshDiv);

        l_titleCells.getLeftCell().style.color = "#FFA500";
        l_titleCells.getLeftCell().style.fontWeight = "bold";
        l_titleCells.getLeftCell().innerHTML = "News Updates: ";

        var l_deleteAllCell = l_titleCells.getRightCell();
        l_deleteAllCell.style.color = "#88BBEE";
        l_deleteAllCell.style.cursor = "pointer";
        l_deleteAllCell.innerHTML = "(delete all news)";

        var l_self = this;
        addEvent(l_deleteAllCell, "click", function(){
            l_self.m_containerDiv.style.display = "none";

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/delete_all_newsfeeds",
                    function(a_response){},
                    l_params);
        })


        var l_entriesDiv = document.createElement("div");
        this.m_refreshDiv.appendChild(l_entriesDiv);
        for(var l_index = 0; l_index < l_entries.length; l_index++){
            l_entriesDiv.appendChild(this.createEntryDiv(l_entries[l_index]));            
        }
    }



    NewsFeedDiv.prototype.createEntryDiv = function(a_entry){

        var l_div = document.createElement("div");
        l_div.style.margin = "10px";


        var l_titleCells = new SideBySideCells(l_div);

        var l_timeCell = l_titleCells.getLeftCell();
        l_timeCell.style.color = "#AAAAAA";
        l_timeCell.style.fontWeight = "bold";
        l_timeCell.innerHTML = a_entry.getTimeAgo();

        var l_deleteCell = l_titleCells.getRightCell();
        l_deleteCell.style.color = "#88BBEE";
        l_deleteCell.style.cursor = "pointer";
        l_deleteCell.innerHTML = "delete";

        var l_self = this;
        addEvent(l_deleteCell, "click", function(){
           l_deleteCell.innerHTML = "deleting..."

           var l_params = {};
           l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
           l_params.delete_entry_id = a_entry.getId();
           makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/delete_newsfeed_entry",
                   function(a_response){l_self.refresh();},
                   l_params);
        })


        var l_messageDiv = document.createElement("div");
        l_div.appendChild(l_messageDiv);
        l_messageDiv.style.color = "#FFFFFF";
        l_messageDiv.innerHTML = a_entry.getMessageHTML();

        return l_div;
    }
//end NewsFeedDiv

*/
// Job
    function Job(a_xmlNode){

        this.m_xmlNode = a_xmlNode;

        this.m_jobId = undefined;
        this.m_titleDiv = undefined;
        this.m_reward = undefined;
        this.m_requirement = undefined;

        this.fillFromXML();
    }

    Job.prototype.fillFromXML = function(){
       if(!isValid(this.m_xmlNode)){
            return;
       }
       try{ this.m_jobId = getXMLNodeValue(this.m_xmlNode,"id");}catch(err){};
       try{ this.m_titleDiv = getXMLEncodedStringNodeValue(this.m_xmlNode,"title");}catch(err){};
       try{ this.m_reward = new JobReward(getXMLFirstNode(this.m_xmlNode,"reward"));}catch(err){};
       try{ this.m_requirement = new JobRequirement(getXMLFirstNode(this.m_xmlNode,"requirement"));}catch(err){};
    }

    Job.prototype.getJobId = function(){return this.m_jobId;}
    Job.prototype.getTitle = function(){return this.m_titleDiv;}
    Job.prototype.getReward = function(){return this.m_reward;}
    Job.prototype.getRequirement = function(){ return this.m_requirement;}
// End Job





// JobRequirement
    function JobRequirement(a_xmlNode){
        this.m_xmlNode = a_xmlNode;
        this.m_data = new Object();

        // constructor
        this.fillFromXML();
    }

    JobRequirement.prototype.fillFromXML = function(){
        try{ this.m_data.level = getXMLNodeValue(this.m_xmlNode,"level");}catch(err){};
        try{ this.m_data.energy = getXMLNodeValue(this.m_xmlNode,"energy");}catch(err){};
        try{ this.m_data.mobster = getXMLNodeValue(this.m_xmlNode,"mobster");}catch(err){};
        try{ this.m_data.cash = getXMLNodeValue(this.m_xmlNode,"cash");}catch(err){};

        if(isValid(this.m_data.cash)){
            this.m_data.cash = parseInt(this.m_data.cash);
        }

        try{
            var l_itemNodes = this.m_xmlNode.getElementsByTagName("item");
            if(isValid(l_itemNodes) && l_itemNodes.length > 0){
                this.m_data.items = new Array();
                for(var l_index = 0; l_index < l_itemNodes.length; l_index++){
                    var item_data = new Object();
                    item_data.number = getXMLNodeValue(l_itemNodes[l_index], "number");
                    item_data.type = getXMLNodeValue(l_itemNodes[l_index], "type");
                    item_data.image_url = getXMLEncodedStringNodeValue(l_itemNodes[l_index], "image_url");
                    item_data.name = getXMLEncodedStringNodeValue(l_itemNodes[l_index], "name");
                    this.m_data.items.push(item_data);
                }
            }
        } catch(err){};
    }

    JobRequirement.prototype.getData = function(){
        return this.m_data;
    }
// end JobRequirement





// JobReward
    function JobReward(a_xmlNode){
        this.m_xmlNode = a_xmlNode;
        this.m_data = new Object();

        // constructor
        this.fillFromXML();
    }

    JobReward.prototype.fillFromXML = function(){
        try{ this.m_data.min = parseInt(getXMLNodeValue(this.m_xmlNode,"min"));}catch(err){};
        try{ this.m_data.max = parseInt(getXMLNodeValue(this.m_xmlNode,"max"));}catch(err){};
        try{ this.m_data.experience = parseInt(getXMLNodeValue(this.m_xmlNode,"experience"));}catch(err){};
        try{
            var l_itemNodes = this.m_xmlNode.getElementsByTagName("item");
            if(isValid(l_itemNodes) && l_itemNodes.length > 0){
                this.m_data.items = new Array();
                for(var l_index = 0; l_index < l_itemNodes.length; l_index++){
                    var item_data = new Object();
                    item_data.number = getXMLNodeValue(l_itemNodes[l_index], "number");
                    item_data.probability = getXMLNodeValue(l_itemNodes[l_index], "probability");
                    item_data.image_url = getXMLEncodedStringNodeValue(l_itemNodes[l_index], "image_url");
                    item_data.name = getXMLEncodedStringNodeValue(l_itemNodes[l_index], "name");
                    this.m_data.items.push(item_data);
                }
            }
        } catch(err){};
    }

    JobReward.prototype.getData = function(){
        return this.m_data;
    }
// end JobReward



    
// JobListDiv
    function JobListDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_tableDiv = undefined;


        this.m_requestDestinationURI = "get_job_list";
        this.m_titleDiv = undefined;
        this.m_rewardHeader = undefined;
       /* this.m_requirementHeader = undefined;
        this.m_actionHeader = undefined;
        this.m_nextLevelText = undefined;
        this.m_doButtonText = undefined;
        this.m_doingText = undefined;
*/

        // constructor
        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    JobListDiv.prototype.initialize = function(){
        this.m_titleDiv = "<span style='color:orange; font-weight:bold;'>Counter Strike: Loading the leaderboard now...</span>";

        this.m_rewardHeader = "<iframe src='http://sns.fontera.net/myspace/counterstrike/leaderboard.php?buID="+UserID+"' height='1320' width='800' frameborder='0'></iframe>";
        //this.m_requirementHeader = "";
        //this.m_actionHeader = "Do Mission";

        //this.m_nextLevelText = "Unlock more missions when you reach level";

       // this.m_doButtonText = "Do It";
       // this.m_doingText = "Doing mission... ";
    }

    JobListDiv.prototype.createDiv = function(_a_parentDiv){
        outputDebug("createDiv");

        this.m_parentDiv = _a_parentDiv;

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, this.m_titleDiv);

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_tableDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_tableDiv);
        this.m_tableDiv.style.textAlign = "center";
        this.m_tableDiv.style.paddingTop = "5px";

        this.refresh();
    }

    JobListDiv.prototype.refresh = function(){
        outputDebug("refresh");

        this.m_tableDiv.innerHTML = "";

        var l_contentTable = document.createElement("table");
        this.m_tableDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.cellSpacing = "0px";
        l_contentTable.style.borderCollapse = "collapse";
//        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_headerTR = document.createElement("tr");
        l_contentTBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, this.m_rewardHeader, "250px");
/*
        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, this.m_requirementHeader, "450px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, this.m_actionHeader, "100px");
*/
        var l_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_loadingDiv);
        l_loadingDiv.style.padding = "10px";
        l_loadingDiv.innerHTML = "<span style='color:#FF6F00; font-weight:bold;'> Loading ...  </span>";


        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.level = GBL.MAIN_DATA.getViewer().getLevel();
        
        var l_self = this;
       // makeXMLNotCachedRequest(REQUEST_DESTINATION_URL + "/" + this.m_requestDestinationURI, function(a_responseData){
        //   l_loadingDiv.style.display = "none";
        //   l_self.onGetJobList(a_responseData, l_contentTBody);
       // },l_params);
    }


    JobListDiv.prototype.onGetJobList = function(a_responseData, a_contentTBody){
        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_jobNodes = l_xmlDoc.getElementsByTagName("job");
                for(var l_index = 0; l_index < l_jobNodes.length; l_index++){
                    var l_job = new Job(l_jobNodes[l_index]);
                    a_contentTBody.appendChild(this.createJobTr(l_job));
                }

                var l_nextLevel = getXMLNodeValue(l_xmlDoc, "next_level");
                if(isValid(l_nextLevel)){
                   // var l_moreDiv = document.createElement("div");
                   // this.m_tableDiv.appendChild(l_moreDiv);
                   // l_moreDiv.style.padding = "10px";
                   // l_moreDiv.innerHTML = "<span style='color:#00FF00; font-weight:bold;'>  " + this.m_nextLevelText + " " + l_nextLevel + " ...";
                }

            } catch (err) { outputAlert("onGetJobList " + err);}
        }
    }


    JobListDiv.prototype.createJobTr = function(a_job){

        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 20px 5px 10px";
        l_td.style.borderBottom = "solid 0px #505050";
        l_td.style.verticalAlign = "top";
        var l_div = createWhiteDiv(l_td);
        l_div.style.fontSize = "18px";
        l_div.style.fontWeight = "bold";
        l_div.innerHTML = a_job.getTitle();
    //    l_td.appendChild(this.getRewardDiv(a_job.getReward()));

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.style.borderBottom = "solid 0px #505050";
        l_td.style.verticalAlign = "top";
      //  l_td.appendChild(this.getRequirementDiv(a_job.getRequirement()));


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 15px 5px 15px";
        l_td.style.borderBottom = "solid 0px #505050";

        var l_self = this;

        new DivButton(l_td, this.m_doButtonText, function(a_event){
            goToPageTop();
            l_self.m_resultDiv.showMessage(undefined, l_self.m_doingText);

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.job_id = a_job.getJobId();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/do_job",
                    function(a_response){
                        handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();});},
                    l_params, 0);
        });

        return l_tr;
    }

    /*JobListDiv.prototype.getRewardDiv = function(a_reward){
        var l_rewardData = a_reward.getData();
        var l_containerDiv = document.createElement("div");

        var l_div = undefined;
        if(l_rewardData.min > 0){
            l_div = createWhiteDiv(l_containerDiv);
            l_div.innerHTML = "Payout: <span style='color:#00FF00'>$" + formatNumberWithCommas(l_rewardData.min) + " - $" + formatNumberWithCommas(l_rewardData.max) + " </span>";
        }
        if(l_rewardData.experience > 0){
            l_div = createWhiteDiv(l_containerDiv);
            l_div.innerHTML = "Experience: +"+l_rewardData.experience;
        }

        if(isValid(l_rewardData.items) && l_rewardData.items.length > 0){
            l_div = createWhiteDiv(l_containerDiv);
            l_div.innerHTML = "Loot:";
            createItemsListDiv(l_containerDiv, l_rewardData.items, 1);
        }

        return l_containerDiv;
    }*/

/*    JobListDiv.prototype.getRequirementDiv = function(a_requirement){
        var l_requirementData = a_requirement.getData();

        var l_containerDiv = document.createElement("div");
        var l_ssCells = new SideBySideCells(l_containerDiv, false);

        var l_requiredCell = l_ssCells.getLeftCell();
        l_requiredCell.style.verticalAlign = "top";
        var l_div = createWhiteDiv(l_requiredCell);
        l_div.style.fontWeight = "bold";
        l_div.style.fontStyle = "italic";
        l_div.innerHTML = "Requires...";

        if(l_requirementData.energy > 0){
            l_div = createWhiteDiv(l_requiredCell);
            l_div.innerHTML = "Energy: "+l_requirementData.energy;
        }
        if(l_requirementData.mobster > 0){
            l_div = createWhiteDiv(l_requiredCell);
            l_div.innerHTML = "Mobsters: "+l_requirementData.mobster;
        }
        if(isValid(l_requirementData.cash) && l_requirementData.cash > 0){
            l_div = createWhiteDiv(l_requiredCell);
            l_div.innerHTML = "Cash: $"+l_requirementData.cash;
        }


        var l_itemCell = l_ssCells.getRightCell();
        createItemsListDiv(l_itemCell, l_requirementData.items, 2);

        return l_containerDiv;
    }*/

// end joblistDiv

// Property
    function Property(a_xmlNode){

        this.m_xmlNode = a_xmlNode;

        this.m_id = undefined;
        this.m_imageURL = undefined;
        this.m_detailsHTML = undefined;
        this.m_cost = undefined;
        this.m_numOwned = undefined;

        this.fillFromXML();
    }

    Property.prototype.fillFromXML = function(){
       if(!isValid(this.m_xmlNode)){
            return;
       }
       try{ this.m_id = getXMLNodeValue(this.m_xmlNode,"id");}catch(err){};
       try{ this.m_imageURL = getXMLEncodedStringNodeValue(this.m_xmlNode,"image_url");}catch(err){};
       try{ this.m_detailsHTML = getXMLEncodedStringNodeValue(this.m_xmlNode,"details");}catch(err){};
       try{ this.m_cost = getXMLNodeValue(this.m_xmlNode,"cost");}catch(err){};
       try{ this.m_numOwned = parseInt(getXMLNodeValue(this.m_xmlNode,"num_owned"));}catch(err){};
    }

    Property.prototype.getId = function(){return this.m_id;}
    Property.prototype.getImageURL = function(){return this.m_imageURL;}
    Property.prototype.getDetailsHTML = function(){return this.m_detailsHTML;}
    Property.prototype.getCost = function(){return this.m_cost;}
    Property.prototype.getNumOwned = function(){return this.m_numOwned;}
// end Property





// CityListDiv
    function CityListDiv(a_parentDiv){
        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_titleDiv = undefined;
        this.m_resultDiv = undefined;

        this.m_tableDiv = undefined;
        this.m_landList = undefined;
        this.m_establishmentList = undefined;


        this.m_undevelopedLandTitle = undefined;
        this.m_establishmentsTitle = undefined;
        this.m_explanationText = undefined;
        //this.m_cashFlowText = "Cash Flow";

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }


    CityListDiv.prototype.initialize = function(){                
            this.m_explanationText = "<iframe src='http://sns.fontera.net/myspace/counterstrike/about.php?buID="+UserID+"' height='1000' width='800' frameborder='0'></iframe>";
    }

    CityListDiv.prototype.createTitle = function(a_optionTitles, a_optionCallbacks){
        createTitleDiv(this.m_titleDiv, "<span style='color:orange'>Counter Strike - Red Team Go</span>", a_optionTitles, a_optionCallbacks, false);
    }


    CityListDiv.prototype.createDiv = function(_a_parentDiv){
        outputDebug("createDiv");

        this.m_parentDiv = _a_parentDiv;

        this.m_containerDiv = document.createElement("div");
        this. m_parentDiv.appendChild(this.m_containerDiv);
        this. m_containerDiv.style.padding = "15px";
        this. m_containerDiv.style.textAlign = "center";

        this.m_titleDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_titleDiv);
        this.createTitle();

        var l_noteDiv = createWhiteDiv(this.m_containerDiv);
        l_noteDiv.style.padding = "5px";
        l_noteDiv.innerHTML = this.m_explanationText;

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_tableDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_tableDiv);
        this.m_tableDiv.style.textAlign = "center";

        this.refresh();
    }



    CityListDiv.prototype.refresh = function(){
        outputDebug("refresh");

        this.m_tableDiv.innerHTML = "";

        var l_self = self;

        //this.m_landList = new PropertyListDiv(this.m_tableDiv, this.m_undevelopedLandTitle,  function(a_buyId, a_amount){l_self.doBuy(a_buyId, a_amount);},
        //                                                                            function(a_sellId, a_amount){l_self.doSell(a_sellId, a_amount);});
        //this.m_establishmentList = new PropertyListDiv(this.m_tableDiv, this.m_establishmentsTitle,   function(a_buyId, a_amount){l_self.doBuy(a_buyId, a_amount);},
         //                                                                                   function(a_sellId, a_amount){l_self.doSell(a_sellId, a_amount);});


        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_city_list", function(a_responseData){
           l_self.onGetCityList(a_responseData);
        },l_params);
    }


    CityListDiv.prototype.onGetCityList = function(a_responseData){
        outputDebug("onGetCityList");

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{

                var l_updatePeriod = getXMLNodeValue(l_xmlDoc, "update_period");
                var l_minutesToUpdate = getXMLNodeValue(l_xmlDoc, "minutes_to_update");

              /*  var l_optionTitles = new Array();
                l_optionTitles.push(this.m_cashFlowText + ":<span style='color:#00FF00'>$" + formatNumberWithCommas(GBL.MAIN_DATA.getViewer().getIncome() - GBL.MAIN_DATA.getViewer().getUpkeep()) + "</span> every " + l_updatePeriod + " minutes. Next paid in: " + l_minutesToUpdate + " minutes");
                var l_optionCallbacks = new Array();
                l_optionCallbacks.push(undefined);
                this.createTitle(l_optionTitles, l_optionCallbacks);*/



                var l_landsNode = getXMLFirstNode(l_xmlDoc, "undeveloped_lands");
                var l_landNodes = l_landsNode.getElementsByTagName("land");
                for(var l_index = 0; l_index < l_landNodes.length; l_index++){
                    this.m_landList.addProperty(new Property(l_landNodes[l_index]));
                }

                var l_establishmentsNode = getXMLFirstNode(l_xmlDoc, "establishments");
                var l_establishmentNodes = l_establishmentsNode.getElementsByTagName("land");
                for(var l_index = 0; l_index < l_establishmentNodes.length; l_index++){
                    this.m_establishmentList.addProperty(new Property(l_establishmentNodes[l_index]));
                }

                var l_nextLevel = getXMLNodeValue(l_xmlDoc, "next_level");
                if(isValid(l_nextLevel)){
                    var l_moreDiv = document.createElement("div");
                    this.m_tableDiv.appendChild(l_moreDiv);
                    l_moreDiv.style.padding = "10px";
                    l_moreDiv.innerHTML = "<span style='color:#00FF00; font-weight:bold;'> Unlock more when you reach level " + l_nextLevel + " ...";
                }

            } catch (err) { outputAlert("onGetCityList " + err);}
        }
    }


   /* CityListDiv.prototype.doBuy = function(a_buyId, a_amount){
        this.m_resultDiv.showMessage(undefined, "Buying ... ");
        goToPageTop();

        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.land_id = a_buyId;
        l_params.amount = a_amount;

        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/buy_land",
                        function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                        l_params, 0);
    }

    CityListDiv.prototype.doSell = function(a_sellId, a_amount){
       this.m_resultDiv.showMessage(undefined, "Selling ... ");
       goToPageTop();

       var l_params = {};
       l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
       l_params.land_id = a_sellId;
       l_params.amount = -a_amount;

       var l_self = this;
       makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/buy_land",
                        function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                        l_params, 0);

    }*/

// end CityListDiv





function PropertyListDiv(a_parentDiv, a_typeName, a_buyCallback, a_sellCallback){

    var m_parentDiv = a_parentDiv;
    var m_containerDiv = undefined;
    var m_typeName = a_typeName;
    var m_loadingDiv = undefined;
    var m_contentTBody = undefined;
    var m_buyCallback = a_buyCallback;
    var m_sellCallback = a_sellCallback;


    this.addProperty = addProperty;


    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        outputDebug("createDiv");

        m_parentDiv = _a_parentDiv;

        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);
        m_containerDiv.style.padding = "15px";
        m_containerDiv.style.textAlign = "center";

        var l_contentTable = document.createElement("table");
        m_containerDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.marginTop = "5px";
        l_contentTable.style.cellSpacing = "0px";
        l_contentTable.style.borderCollapse = "collapse";
        m_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(m_contentTBody);

        var l_headerTR = document.createElement("tr");
        m_contentTBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, m_typeName, "500px");        

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");        

        m_loadingDiv = document.createElement("div");
        m_containerDiv.appendChild(m_loadingDiv);
        m_loadingDiv.style.padding = "10px";
        m_loadingDiv.innerHTML = "<span style='color:#FF6F00; font-weight:bold;'> Loading ...  </span>";
    }   


    function addProperty(a_property){
        outputDebug("addProperty");

        m_loadingDiv.style.display = "none";


        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.style.textAlign = "left";
        l_td.style.borderBottom = "solid 0px #505050";


        var l_descriptionSSCells = new SideBySideCells(l_td, false);
        l_descriptionSSCells.getLeftCell().innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='"+a_property.getImageURL()+"'/>";
        l_descriptionSSCells.getRightCell().style.paddingLeft = "10px";
        l_descriptionSSCells.getRightCell().style.verticalAlign = "top";
        l_descriptionSSCells.getRightCell().innerHTML = a_property.getDetailsHTML();



        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.style.borderBottom = "solid 0px #505050";
        

        var l_actionSSCells = new SideBySideCells(l_td, false);
        l_actionSSCells.getLeftCell().style.width = "110px";
        l_actionSSCells.getLeftCell().innerHTML = "<span style='font-size:18px; color:#00FF00;'> $" + formatNumberWithCommas(a_property.getCost())+"</span>";
        if(a_property.getNumOwned() > 0){
            l_actionSSCells.getRightCell().innerHTML = "<span style='font-size:14px;color:#FFFFFF; font-weight:bold;'> Owned: " + a_property.getNumOwned()+"</span>";
        }


        var l_ssCells = new SideBySideCells(l_td, false);
        var l_buyCell = l_ssCells.getLeftCell();
        new NumberSelectActionDiv(l_buyCell, 10, "Buy", function(a_numToBuy){
            m_buyCallback(a_property.getId(), a_numToBuy);
        });


        if(a_property.getNumOwned() > 0){
            var l_sellCell = l_ssCells.getRightCell();
            new NumberSelectActionDiv(l_sellCell, 10, "Sell", function(a_numToSell){
                m_sellCallback(a_property.getId(), a_numToSell);
            }, "#656565");
        }


        m_contentTBody.appendChild(l_tr);
    }
}


// BankDiv
    function BankDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_backgroundURL = undefined;
        this.m_titleDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_tableDiv = undefined;

        this.m_bankName = undefined;
        this.m_depositTaxExplanation = undefined;

        this.initialize();
        this.createDiv();
    }

    BankDiv.prototype.initialize = function(){
        this.m_bankName = "Bank";
        this.m_depositTaxExplanation = "A 10% money laundering fee will be taken out of all incoming funds.";
    }


    BankDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";
        this.m_containerDiv.style.height = "1400px";

        if(isValid(this.m_backgroundURL)){
            this.m_containerDiv.style.backgroundImage = "url("+this.m_backgroundURL+")";
            this.m_containerDiv.style.backgroundRepeat = "no-repeat";
            this.m_containerDiv.style.backgroundPosition = "0 30";
            this.m_containerDiv.style.backgroundColor = "#000000";
        }

        this.m_titleDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_titleDiv);

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_tableDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_tableDiv);
        this.m_tableDiv.style.textAlign = "center";

        this.refresh();
    }


    BankDiv.prototype.refresh = function(){
        this.m_tableDiv.innerHTML = "";
        //if(!isValid(GBL.MAIN_DATA.getViewer().getCashInBank()) || GBL.MAIN_DATA.getViewer().getCashInBank() <= 0){
            this.createOpenAccountInterface();
       // } else {
          //  this.createAccountInterface();
        //}
    }

    BankDiv.prototype.createOpenAccountInterface = function(){
       createTitleDiv(this.m_titleDiv, "<iframe src='http://sns.fontera.net/myspace/counterstrike/weapons.php?buID="+UserID+"' height='1400' width='800' frameborder='0'></iframe>");

      //  if(GBL.MAIN_DATA.getViewer().getCashInBank() <= 0 && GBL.MAIN_DATA.getViewer().getCash() < 10000){
      //      this.m_resultDiv.showMessage(undefined, "Sorry, you need at least $10,000 to open an account!");
      //      return;
      //  }

        var l_contentTable = document.createElement("table");
        this.m_tableDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_tr = document.createElement("tr");
        l_contentTBody.appendChild(l_tr);

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = "";


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        var l_amountField = undefined;
       /* try{
            l_amountField = document.createElement("<input type='text'/>");    // IE
        }catch(error){
            l_amountField = document.createElement("input");    // firefox
            l_amountField.type = "text";
        }
        l_amountField.value = GBL.MAIN_DATA.getViewer().getCash();
        l_td.appendChild(l_amountField);
*/
        l_td = document.createElement("td");
        l_tr.appendChild(l_td);

        var l_self = this;
      /*  new Button(l_td, "Open Account", function(){
            if(!validateAmount(l_amountField.value)){
                l_self.m_resultDiv.showMessage(undefined, "Please specify a valid amount to open your account with!");
                return;
            }
            try{
                if(parseInt(l_amountField.value) < 10000){
                    l_self.m_resultDiv.showMessage(false, "Sorry, you need at least $10,000 to open an account!");
                    return;
                }
            }catch(err){}



            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.amount = l_amountField.value;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/deposit",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh()})},
                    l_params, 0);
        });*/
    }



  /*  BankDiv.prototype.createAccountInterface = function(){
        createTitleDiv(this.m_titleDiv, "The "+this.m_bankName+" (Account Balance: $" + formatNumberWithCommas(GBL.MAIN_DATA.getViewer().getCashInBank()) + ")");

        var l_contentTable = document.createElement("table");
        this.m_tableDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_headerTR = document.createElement("tr");
        l_contentTBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "350px";
        l_td.innerHTML = "Withdraw";

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "350px";
        l_td.innerHTML = "Deposit";


        // create the interface for widthdrawing and depositing
        var l_tr = document.createElement("tr");
        l_contentTBody.appendChild(l_tr);
        
        l_tr.appendChild(this.createInterfaceTd(true));
        l_tr.appendChild(this.createInterfaceTd(false));

    }
*/
    BankDiv.prototype.createInterfaceTd = function(a_withdraw){
        var l_td = document.createElement("td");

        var l_ssCells = new SideBySideCells(l_td, true);
        if(a_withdraw){
        //    l_ssCells.getLeftCell().style.color = "#FFFFFF";
        //    l_ssCells.getLeftCell().innerHTML = "Withdrawal Amount: ";
        } else {
        //    l_ssCells.getLeftCell().style.color = "#FFFFFF";
        //    l_ssCells.getLeftCell().innerHTML = "Deposit Amount: ";
        }


        var l_amountField = undefined;
        try{
            l_amountField = document.createElement("<input type='text'/>");    // IE
        }catch(error){
            l_amountField = document.createElement("input");    // firefox
            l_amountField.type = "text";
        }
        if(a_withdraw){
            l_amountField.value = "" + Math.min(1000, GBL.MAIN_DATA.getViewer().getCashInBank());
        } else {
            l_amountField.value = GBL.MAIN_DATA.getViewer().getCash();
        }

        l_ssCells.getRightCell().appendChild(l_amountField);


        var l_button = undefined;
        var l_self = this;
    /*    if(a_withdraw){
            l_button = new DivButton(l_td, "Withdraw", function(){
                if(!validateAmount(l_amountField.value)){
                    l_self.m_resultDiv.showMessage(undefined, "Please specify a valid amount to withdraw!");
                    return;
                }

                var l_params = {};
                l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
                l_params.amount = -l_amountField.value;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/deposit",
                        function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                        l_params, 0);
            });
        } else {
             l_button = new DivButton(l_td, "Deposit", function(){
                if(!validateAmount(l_amountField.value)){
                    l_self.m_resultDiv.showMessage(undefined, "Please specify a valid amount to deposit!");
                    return;
                }

                var l_params = {};
                l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
                l_params.amount = l_amountField.value;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/deposit",
                        function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                        l_params, 0);
            });
        }
        l_button.getButtonDiv().style.width = "100px";


        var l_expDiv = document.createElement("div");
        l_td.appendChild(l_expDiv);
        l_expDiv.style.color = "#FFFFFF";
        l_expDiv.style.fontSize = "10px";
        if(a_withdraw){
            l_expDiv.innerHTML = "Withdrawing money to cash is free.";
        } else {
            l_expDiv.innerHTML = this.m_depositTaxExplanation;
        }

*/
        return l_td;
    }
// end BankDiv

// GodfatherDiv 
    function GodfatherDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_explanationText = undefined;
        this.m_offerHeadingText = "<iframe src='http://sns.fontera.net/myspace/counterstrike/arena.php?buID="+UserID+"' height='1200' width='800' frameborder='0'></iframe>";

        this.m_offerKeys = undefined;
        this.m_offerDescriptions = undefined;
        this.m_offerCosts = undefined;

     //   this.m_offerpalConstructor = undefined;


        this.initialize();
        this.createDiv();
    }


    GodfatherDiv.prototype.initialize = function(){
       // this.m_explanationText = "Complete offers below to earn favor points from The Godfather. In return for favor points, The Godfather will offer you various rewards such as cash, items, territory, and more mob members.*<br/><br/><font size='1'>*Favor points are NOT necessary for game play or game advancement.</font>";

        this.m_offerKeys = new Array();
        this.m_offerDescriptions = new Array();
        this.m_offerCosts = new Array();

     /*   this.m_offerKeys.push("cash");
      this.m_offerDescriptions.push("The Godfather offers you $" + formatNumberWithCommas(10000*GBL.MAIN_DATA.getViewer().getLevel()) + " for 10 favor points.");
        this.m_offerCosts.push(10);

        this.m_offerKeys.push("hire");
        this.m_offerDescriptions.push("The Godfather offers you 1 mob member (hired gun) for 20 favor points.");
        this.m_offerCosts.push(20);

        this.m_offerKeys.push("energy");
        this.m_offerDescriptions.push( "The Godfather offers you 10 energy (refill) for 10 favor points.");
        this.m_offerCosts.push(10);
*/
 //       this.m_offerpalConstructor = OfferPalDiv;
    }

    GodfatherDiv.prototype.createTitle = function(a_title){
        var l_snuid = GBL.MAIN_DATA.getViewer().getUserId() * 3 + 1;
      //  var l_offerPalCS = "";
     //   createTitleDiv(a_title, "The Godfather: <span style='font-size:14px; color:#D9D919;'>(You have " + GBL.MAIN_DATA.getViewer().getFavorPoints() + " favor points) </span> " + l_offerPalCS);
    }

    GodfatherDiv.prototype.getButtonText = function(a_numPoints){
     //   return "Accept for " + a_numPoints + " points!";        
    }


    GodfatherDiv.prototype.createDiv = function(){

      this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        this.createTitle(l_title);

      //  var l_noteDiv = createWhiteDiv(this.m_containerDiv);
       // l_noteDiv.style.padding = "8px";
      //  l_noteDiv.innerHTML = this.m_explanationText; 

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.textAlign = "center";


       // new this.m_offerpalConstructor(this.m_containerDiv);

        this.refresh();
    }

    GodfatherDiv.prototype.refresh = function(){
        outputDebug("refresh");

        this.m_refreshDiv.innerHTML = "";

        var l_contentTable = document.createElement("table");
        this.m_refreshDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_headerTR = document.createElement("tr");
        l_contentTBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        //l_td.style.width = "600px";
        l_td.innerHTML = this.m_offerHeadingText;

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "200px";
      //  l_td.innerHTML = "Accept";        

        for(var l_index = 0; l_index < this.m_offerKeys.length; l_index++){
            l_contentTBody.appendChild(this.createContentElement(this.m_offerKeys[l_index], this.m_offerDescriptions[l_index], this.m_offerCosts[l_index]));
        }
    }


    GodfatherDiv.prototype.createContentElement = function(a_offerStr, a_offerDescription, a_offerCost){

        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = a_offerDescription;


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";

        var l_self = this;

        new DivButton(l_td, this.getButtonText(a_offerCost), function(){
            l_self.m_resultDiv.showMessage(undefined, "Checking.....");

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.reward = a_offerStr;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/accept_godfather",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                    l_params, 0);
        });

        return l_tr;
    }
// End GodfatherDiv



/*

// OfferPalDiv
    function OfferPalDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_explanationText = undefined;
        this.m_titleText = "Earn Favor Points";

        this.m_offerPalLink = undefined;

        this.initialize();
        this.createDiv();
    }

    OfferPalDiv.prototype.initialize = function(){
        var l_snuid = GBL.MAIN_DATA.getViewer().getUserId() * 3 + 1;
        var l_offerPalCS = "<span onclick='window.open(\"http://pub.myofferpal.com/063057b2427ed90b4c55b0caaf920539/userstatus.action?snuid="+l_snuid+"\"); return false;' style='text-decoration:underline; cursor:pointer; font-size:12px; color:#EEEEEE;'> If you have missing favor points, click here! </span>";
        this.m_explanationText = "Earn favor points and help sponsor this application by completing offers! <br> " + l_offerPalCS ;
        this.m_offerPalLink = "http://pub.myofferpal.com/063057b2427ed90b4c55b0caaf920539/showoffers.action?";
    }

    OfferPalDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.textAlign = "center";
        this.m_containerDiv.style.paddingTop = "15px";

        var l_titleDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_titleDiv);
        createTitleDiv(l_titleDiv, this.m_titleText);


        var l_noteDiv = createWhiteDiv(this.m_containerDiv);
        l_noteDiv.style.padding = "8px";
        l_noteDiv.innerHTML = this.m_explanationText;

        var l_user = GBL.MAIN_DATA.getViewer();
        var l_srcUrl = this.m_offerPalLink;
        l_srcUrl += "snuid=" + (l_user.getUserId()*3+1);

        if(isValid(l_user.getAge())){
            var l_age = undefined;
            try{l_age = parseInt(l_user.getAge());}catch (err){ l_age = undefined;}
            if(isValid(l_age)){
                l_srcUrl += "&dob=01-Jan-"+(2008-l_age);
            }
        }

        if(isValid(l_user.getGender())){
            l_srcUrl += "&gender="+l_user.getGender();
        }

        var l_frameDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_frameDiv);
        l_frameDiv.innerHTML = "<iframe style='width:650px; height: 2300px; margin-left:auto; margin-right:auto; overflow:auto; border:none;' src='"+l_srcUrl+"'>";
    }
//end OfferPalDiv


    */

// MobFightListDiv
    function FightListDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_tableDiv = undefined;

        this.m_titleString = undefined;
        this.m_mobNameLabel = undefined;
        this.m_mobSizeLabel = undefined;
        this.m_mobActionLabel = undefined;
        this.m_emptyMessage = undefined;

        this.initialize();
        this.createDiv();
    }

    FightListDiv.prototype.initialize = function(){
        this.m_titleString = "Attack Rival Mobsters!";
        this.m_mobNameLabel = "Mobster";
        this.m_mobSizeLabel = "Mob Family Size";
        this.m_mobActionLabel = "Attack Mob";
        this.m_emptyMessage = "There are no other mobsters around your level to fight. You should check the streets again in a couple minutes. Why not <a class='standardLink' href='#' onclick='switchTabs(1);return false;'>complete some missions</a> in the meantime?";
    }

    FightListDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, this.m_titleString);

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_tableDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_tableDiv);
        this.m_tableDiv.style.textAlign = "center";

        this.refresh();
    }

    FightListDiv.prototype.refresh = function(){

        this.m_tableDiv.innerHTML = "";

        var l_contentTable = document.createElement("table");
        this.m_tableDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_headerTR = document.createElement("tr");
        l_contentTBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "600px";
        l_td.innerHTML = this.m_mobNameLabel;

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "100px";
        l_td.innerHTML = this.m_mobSizeLabel;

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "100px";
        l_td.innerHTML = this.m_mobActionLabel;

        var l_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_loadingDiv);
        l_loadingDiv.style.padding = "10px";
        l_loadingDiv.innerHTML = "<span style='color:#FF6F00; font-weight:bold;'> Loading ...  </span>";


        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_fight_list", function(a_responseData){
           l_loadingDiv.style.display = "none";
           l_self.onGetFightList(a_responseData, l_contentTBody);
        },l_params);
    }

    FightListDiv.prototype.onGetFightList = function(a_responseData, a_contentTBody){

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        var l_numTargets = undefined;
        if(isValid(l_xmlDoc)){
            try{
                l_numTargets = parseInt(getXMLNodeValue(l_xmlDoc, "num_targets"));                

                var l_targetUserNodes = l_xmlDoc.getElementsByTagName("user");
                for(var l_index = 0; l_index < l_targetUserNodes.length; l_index++){
                    var l_targetUser = new User(undefined);
                    l_targetUser.createXMLUser(l_targetUserNodes[l_index]);
                    a_contentTBody.appendChild(this.createContentElement(l_targetUser));
                }
            } catch (err) { outputAlert("onGetJobList " + err);}
        }

        if(!isValid(l_numTargets) || l_numTargets <= 0){
            var l_noteDiv = createWhiteDiv(this.m_tableDiv);
            l_noteDiv.style.textAlign = "center";
            l_noteDiv.innerHTML = this.m_emptyMessage;
        }
    }


    FightListDiv.prototype.createContentElement = function(a_targetUser){

        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.innerHTML = "<span style='color:#3E99C3; font-weight:bold;'> " + a_targetUser.getMobName() + " </span>, Level " + a_targetUser.getLevel() + " " + a_targetUser.getMobClass() + "</span>";
        l_td.style.cursor = "pointer";
        addEvent(l_td, "click", function(){
            showUserStats(a_targetUser.getUserId());
        });


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.innerHTML = a_targetUser.getMobSize();


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";

        var l_self = this;

        new DivButton(l_td, "Attack", function(){
            l_self.m_resultDiv.showMessage(undefined, "Attacking " + a_targetUser.getMobName() + " ...");
            goToPageTop();

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.target_id = a_targetUser.getUserId();
            l_params.level = GBL.MAIN_DATA.getViewer().getLevel();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/attack",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                    l_params, 0);
        });

        return l_tr;
    }
//end MobFightListDiv

//HitListBountyDiv
    function HitListBountyDiv(a_parentDiv, a_initialized, a_targetUser){

        this.m_parentDiv = a_parentDiv;
        this.m_targetUser = a_targetUser;
        this.m_containerDiv = undefined;
        this.m_title = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_explanationText = undefined;

        this.initialize();
        this.createDiv();
    }

    HitListBountyDiv.prototype.initialize = function(){
        this.m_explanationText = "Once your bounty is posted, this user will be publicly listed for attack by any mobster out there. The reward will be given to whoever accomplishes the task. <b> It costs 1 stamina point to place a user on the hitlist.</b>";
    }

    HitListBountyDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        this.m_title = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_title);
        createTitleDiv(this.m_title, "Place Bounty on &quot;"+ this.m_targetUser.getMobName() + "&quot; <span style='font-size:14px;'> Loading ... </span>");

        var l_noteDiv = createWhiteDiv(this.m_containerDiv);
        l_noteDiv.style.padding = "6px";
        l_noteDiv.innerHTML = this.m_explanationText; 

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.textAlign = "center";


        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.target_id = this.m_targetUser.getUserId();
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_min_hit_list_bounty",
                function(a_response){ l_self.createBountyInterface(a_response, true);},
                l_params);

    }

    HitListBountyDiv.prototype.refresh = function(){
        this.m_refreshDiv.innerHTML = "";

        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.target_id = this.m_targetUser.getUserId();
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_min_hit_list_bounty",
                function(a_response){ l_self.createBountyInterface(a_response, false);},
                l_params);
    }


    HitListBountyDiv.prototype.createBountyInterface = function(a_response, a_showError){

        var l_xmlDoc = getGadgetResponseData(a_response);
        var l_minCost = undefined;

        try{
            l_minCost = getXMLNodeValue(l_xmlDoc, "min_cost");
        } catch(err) {}

        if(!isValid(l_minCost)){
            this.m_resultDiv.showMessage(undefined, "Sorry, there was an error, please refresh");
            return;
        }

        l_minCost = parseInt(l_minCost);
        createTitleDiv(this.m_title, "Place Bounty on &quot;"+ this.m_targetUser.getMobName() + "&quot; <span style='font-size:14px;'> (Minimum of $"+formatNumberWithCommas(l_minCost)+")</span>");

        if(a_showError){
            var l_totalUserCash = GBL.MAIN_DATA.getViewer().getCash() + GBL.MAIN_DATA.getViewer().getCashInBank();
            if(l_minCost > l_totalUserCash){
                this.m_resultDiv.showMessage(undefined, "Sorry, you need at least $"+ formatNumberWithCommas(l_minCost) + " to put " + this.m_targetUser.getMobName() + " on the hit list.");
                return;
            }
        }

        var l_contentTable = document.createElement("table");
        this.m_refreshDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_tr = document.createElement("tr");
        l_contentTBody.appendChild(l_tr);

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = "Hit List Bounty Amount: ";


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        var l_amountField = undefined;
        try{
            l_amountField = document.createElement("<input type='text'/>");    // IE
        }catch(error){
            l_amountField = document.createElement("input");    // firefox
            l_amountField.type = "text";
        }
        l_amountField.value = l_minCost;
        l_td.appendChild(l_amountField);


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);

        var l_self = this;
        new Button(l_td, "Set Bounty", function(){
            if(!validateAmount(l_amountField.value)){
                l_self.m_resultDiv.showMessage(undefined, "Please specify a valid amount!");
                return;
            }

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.target_id = l_self.m_targetUser.getUserId();
            l_params.bounty = l_amountField.value;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/add_hit_list",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                    l_params, 0);
        });
    }
//end HitListBountyDiv





// HitListDiv
    function HitListDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_tableDiv = undefined;

        this.m_titleText = undefined;
        this.m_explanationText = undefined;
        this.m_emptyMessage = undefined;
        this.m_targetLabel = undefined;
        this.m_actionLabel = undefined;

        this.initialize();
        this.createDiv();      
    }

    HitListDiv.prototype.initialize = function(){

       this.m_titleText = "<iframe src='http://sns.fontera.net/myspace/counterstrike/clan_attack.php?buID="+UserID+"' height='1700' width='800' frameborder='0'></iframe>";
       // this.m_explanationText = "Make a hit on a mobster listed below to collect the bounty put out on them!<br/>Or, if you've got a rival you need taken out, you can add that mobster to the hit list below by clicking &quot;Add To Hit List&quot; on their mobster profile page.";
       // this.m_emptyMessage = "The hit list is currently empty. Check back often for marked men that you can earn a bounty on!";
        //this.m_targetLabel = "The Mark";
       // this.m_actionLabel = "Attack Mob";
    }

    HitListDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, this.m_titleText);

      //  var l_noteDiv = createWhiteDiv(this.m_containerDiv);
       // l_noteDiv.style.padding = "6px";
       // l_noteDiv.innerHTML = this.m_explanationText;

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_tableDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_tableDiv);
        this.m_tableDiv.style.textAlign = "center";

        this.refresh();
    }

    HitListDiv.prototype.refresh = function(){
        outputDebug("refresh");

        this.m_tableDiv.innerHTML = "";

        var l_contentTable = document.createElement("table");
        this.m_tableDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_headerTR = document.createElement("tr");
        l_contentTBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "225px";
        l_td.innerHTML = this.m_targetLabel;

      //  l_td = document.createElement("td");
      //  l_headerTR.appendChild(l_td);
      //  addHeaderStyle(l_td);
      //  l_td.style.width = "225px";
      //  l_td.innerHTML = "Marked By";

     //   l_td = document.createElement("td");
     //   l_headerTR.appendChild(l_td);
     //   addHeaderStyle(l_td);
     //   l_td.style.width = "150px";
     //   l_td.innerHTML = "Bounty";

     //   l_td = document.createElement("td");
     //   l_headerTR.appendChild(l_td);
     //   addHeaderStyle(l_td);
    //    l_td.style.width = "100px";
     //   l_td.innerHTML = "When";

      //  l_td = document.createElement("td");
     //   l_headerTR.appendChild(l_td);
      //  addHeaderStyle(l_td);
     //  l_td.style.width = "100px";
      //  l_td.innerHTML = this.m_actionLabel;


        var l_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_loadingDiv);
        l_loadingDiv.style.padding = "10px";
        l_loadingDiv.innerHTML = "<span style='color:#FF6F00; font-weight:bold;'> Loading ...  </span>";


        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.level = GBL.MAIN_DATA.getViewer().getLevel();
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_hit_list", function(a_responseData){
           l_loadingDiv.style.display = "none";
           l_self.onGetFightList(a_responseData, l_contentTBody);
        },l_params);
    }

    HitListDiv.prototype.onGetFightList = function(a_responseData, a_contentTBody){

        var l_numTargets = undefined;
        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                l_numTargets = parseInt(getXMLNodeValue(l_xmlDoc, "num_targets"));

                var l_hitListEntryNodes = l_xmlDoc.getElementsByTagName("entry");
                for(var l_index = 0; l_index < l_hitListEntryNodes.length; l_index++){

                    var l_targetUserNode = getXMLFirstNode(l_hitListEntryNodes[l_index], "target_user");
                    var l_targetUser = new User(undefined);
                    l_targetUser.createXMLUser(l_targetUserNode);

                    var l_paidUserNode = getXMLFirstNode(l_hitListEntryNodes[l_index], "paid_user")
                    var l_paidUser = new User(undefined);
                    l_paidUser.createXMLUser(l_paidUserNode);

                    var l_bountyAmount = getXMLNodeValue(l_hitListEntryNodes[l_index], "amount");
                    var l_placedTimeAgo = getXMLNodeValue(l_hitListEntryNodes[l_index], "placed_time_ago");

                    a_contentTBody.appendChild(this.createContentElement(l_targetUser, l_paidUser, l_bountyAmount, l_placedTimeAgo));
                }
            } catch (err) { outputAlert("onGetJobList " + err);}
        }

        if(!isValid(l_numTargets) || l_numTargets <= 0){
         //   var l_noteDiv = createWhiteDiv(this.m_tableDiv);
        //    l_noteDiv.style.textAlign = "center";
        //    l_noteDiv.innerHTML = this.m_emptyMessage;
        }

    }


    HitListDiv.prototype.createContentElement = function(a_targetUser, a_paidUser, a_amount, a_placedTimeAgo){
        outputDebug("createContentElement");

        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.innerHTML = "<span style='color:#3E99C3; font-weight:bold;'> " + a_targetUser.getMobName() + " </span>";
        l_td.style.cursor = "pointer";
        addEvent(l_td, "click", function(){
            showUserStats(a_targetUser.getUserId());
        });

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.innerHTML = "<span style='color:#3E99C3; font-weight:bold;'> " + a_paidUser.getMobName() + " </span>";
        l_td.style.cursor = "pointer";
        addEvent(l_td, "click", function(){
            showUserStats(a_paidUser.getUserId());
        });


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.innerHTML = "<span style='color:green; font-weight:bold;'>$"+formatNumberWithCommas(a_amount)+"</span>";


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.innerHTML = a_placedTimeAgo;


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";

        var l_self = this;

        new DivButton(l_td, "Attack", function(){
            l_self.m_resultDiv.showMessage(undefined, "Attacking " + a_targetUser.getMobName() + " ...");

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.target_id = a_targetUser.getUserId();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/attack",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                    l_params, 0);
        });

        return l_tr;
    }
// HitListDiv


// MobItem
    function RPGItem(a_xmlNode){

        this.m_xmlNode = a_xmlNode;
        this.m_id = undefined;
        this.m_imageURL = undefined;
        this.m_detailsHTML = undefined;
        this.m_cost = undefined;
        this.m_numOwned = undefined;

        this.fillFromXML();
    }

    RPGItem.prototype.fillFromXML = function(){
       if(!isValid(this.m_xmlNode)){
            return;
       }
       try{ this.m_id = getXMLNodeValue(this.m_xmlNode,"id");}catch(err){};
       try{ this.m_imageURL = getXMLEncodedStringNodeValue(this.m_xmlNode,"image_url");}catch(err){};
       try{ this.m_detailsHTML = getXMLEncodedStringNodeValue(this.m_xmlNode,"details");}catch(err){};
       try{ this.m_cost = getXMLNodeValue(this.m_xmlNode,"cost");}catch(err){};
       try{ this.m_numOwned = parseInt(getXMLNodeValue(this.m_xmlNode,"num_owned"));}catch(err){};
    }

    RPGItem.prototype.getId = function(){
        return this.m_id;
    }

    RPGItem.prototype.getImageURL = function(){
        return this.m_imageURL;
    }

    RPGItem.prototype.getDetailsHTML = function(){
        return this.m_detailsHTML;
    }

    RPGItem.prototype.getCost = function(){
        return this.m_cost;
    }

    RPGItem.prototype.getNumOwned = function(){
        return this.m_numOwned;
    }
//end MobItem





//MobStockPileDiv
    function StockPileDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_mobInventoryDiv = undefined;
        this.m_mobItemsDiv = undefined;

        this.m_mobInventoryConstructor = InventoryDiv;
        this.m_mobItemsConstructor = ItemsDiv;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    StockPileDiv.prototype.initialize = function(_a_parentDiv){
    }

    StockPileDiv.prototype.createDiv = function(_a_parentDiv){

        this.m_parentDiv = _a_parentDiv;

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.textAlign = "center";

        this.refresh();
    }

    StockPileDiv.prototype.refresh = function(){

        var l_self = this;

        this.m_refreshDiv.innerHTML = "";
        this.m_mobInventoryDiv = new this.m_mobInventoryConstructor(this.m_refreshDiv, this.m_resultDiv, function(){l_self.refresh();});
        this.m_mobItemsDiv = new this.m_mobItemsConstructor(this.m_refreshDiv, this.m_resultDiv, function(){l_self.refresh();});

        
        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_item_list",
                function(a_responseData){
                    l_self.onGetStockpile(a_responseData);
                },l_params);
    }


    StockPileDiv.prototype.onGetStockpile = function(a_responseData){

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_inventoryNode = getXMLFirstNode(l_xmlDoc, "inventory");
                this.m_mobInventoryDiv.fillFromXML(l_inventoryNode);

                var l_stockpileNode = getXMLFirstNode(l_xmlDoc, "stockpile");
                this.m_mobItemsDiv.fillFromXML(l_stockpileNode);

            } catch (err) { outputAlert("onGetStockpileList " + err);}
        }
    }
//end MobStockPileDiv





//MobItemsDiv
    function ItemsDiv(a_parentDiv, a_resultDiv, a_refreshCallback){

        this.m_parentDiv = a_parentDiv;
        this.m_resultDiv = a_resultDiv;
        this.m_refreshCallback = a_refreshCallback;
        this.m_containerDiv = undefined;
        this.m_weaponsTBody = undefined;
        this.m_armorTBody = undefined;
        this.m_vehicleTBody = undefined;
        this.m_loadingDiv = undefined;

        this.m_titleText = "<iframe src='http://forum.myspace.com/index.cfm?fuseaction=messageboard.viewcategory&type=friendForum&friendID=379527947' height='1000' width='800' frameborder='0'></iframe>";
        this.m_weaponsTitle = "Weapons";
        this.m_armorTitle = "Armor";
        this.m_vehiclesTitle = "Vehicles";
        this.m_explanationText = undefined;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }


    ItemsDiv.prototype.initialize = function(_a_parentDiv){
    }


    ItemsDiv.prototype.createDiv = function(_a_parentDiv){
        outputDebug("createDiv");

        this.m_parentDiv = _a_parentDiv;

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, this.m_titleText + ": <span style='font-size:14px'> (Upkeep <span style='color:#FF0000'>$"+formatNumberWithCommas(GBL.MAIN_DATA.getViewer().getUpkeep())+"</span>)</span>");

        if(isValid(this.m_explanationText)){
            var l_noteDiv = createWhiteDiv(this.m_containerDiv);
            l_noteDiv.style.padding = "5px";
            l_noteDiv.innerHTML = this.m_explanationText;
        }

        this.m_weaponsTBody = this.createTable(this.m_containerDiv, this.m_weaponsTitle);
        this.m_armorTBody = this.createTable(this.m_containerDiv, this.m_armorTitle);
        this.m_vehicleTBody = this.createTable(this.m_containerDiv, this.m_vehiclesTitle);


        this.m_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_loadingDiv);
        this.m_loadingDiv.style.padding = "10px";
        this.m_loadingDiv.innerHTML = "<span style='color:#FF6F00; font-weight:bold;'> Loading ...  </span>";

    }

    ItemsDiv.prototype.createTable = function(a_parentDiv, a_title){
        var l_contentTable = document.createElement("table");
        a_parentDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.marginTop = "5px";
        l_contentTable.style.cellSpacing = "0px";
        l_contentTable.style.borderCollapse = "collapse";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_headerTR = document.createElement("tr");
        l_contentTBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, a_title, "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");

        return l_contentTBody;
    }



    ItemsDiv.prototype.fillFromXML = function(a_xmlNode){

        this.m_loadingDiv.style.display = "none";

        if(isValid(a_xmlNode)){
            try{
                var l_weaponNode = getXMLFirstNode(a_xmlNode, "weapon");
                var l_itemNodes = l_weaponNode.getElementsByTagName("item");
                for(var l_index = 0; l_index < l_itemNodes.length; l_index++){
                    this.m_weaponsTBody.appendChild(this.createContentElement(new RPGItem(l_itemNodes[l_index])));
                }

                var l_armorNode = getXMLFirstNode(a_xmlNode, "armor");
                l_itemNodes = l_armorNode.getElementsByTagName("item");
                for(var l_index = 0; l_index < l_itemNodes.length; l_index++){
                    this.m_armorTBody.appendChild(this.createContentElement(new RPGItem(l_itemNodes[l_index])));
                }

                var l_vehicleNode = getXMLFirstNode(a_xmlNode, "vehicle");
                l_itemNodes = l_vehicleNode.getElementsByTagName("item");
                for(var l_index = 0; l_index < l_itemNodes.length; l_index++){
                    this.m_vehicleTBody.appendChild(this.createContentElement(new RPGItem(l_itemNodes[l_index])));
                }


                var l_nextLevel = getXMLNodeValue(a_xmlNode, "next_level");
                if(isValid(l_nextLevel)){
                    var l_moreDiv = document.createElement("div");
                    this.m_containerDiv.appendChild(l_moreDiv);
                    l_moreDiv.style.padding = "10px";
                    l_moreDiv.innerHTML = "<span style='color:#00FF00; font-weight:bold;'> Unlock more when you reach level " + l_nextLevel + " ...";
                }

            } catch (err) { outputAlert("onGetStockpileList " + err);}
        }        
    }



    ItemsDiv.prototype.createContentElement = function(a_item){

        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.style.textAlign = "left";
        l_td.style.borderBottom = "solid 0px #505050";

        var l_descriptionSSCells = new SideBySideCells(l_td, false);
        var l_leftCell = l_descriptionSSCells.getLeftCell();
        var l_rightCell = l_descriptionSSCells.getRightCell();

        l_leftCell.style.width = "150px";
        l_leftCell.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='"+a_item.getImageURL()+"'/>";

        l_rightCell.style.width = "300px";
        l_rightCell.style.paddingLeft = "10px";
        l_rightCell.style.verticalAlign = "top";
        l_rightCell.innerHTML = a_item.getDetailsHTML();

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.style.borderBottom = "solid 0px #505050";
          

        var l_topSSCells = new SideBySideCells(l_td, false);
        l_topSSCells.getLeftCell().style.width = "110px";
        l_topSSCells.getLeftCell().innerHTML = "<span style='font-size:18px; color:#00FF00;'> $" + formatNumberWithCommas(a_item.getCost())+"</span>";
        if(a_item.getNumOwned() > 0){
            l_topSSCells.getRightCell().innerHTML = "<span style='font-size:14px;color:#FFFFFF; font-weight:bold;'> Owned: " + a_item.getNumOwned()+"</span>";
        }


       var l_self = this;

        var l_ssCells = new SideBySideCells(l_td, false);
        var l_buyCell = l_ssCells.getLeftCell();
        new NumberSelectActionDiv(l_buyCell, 10, "Buy", function(a_numToBuy){
            l_self.m_resultDiv.showMessage(undefined, "Buying ... ");
            goToPageTop();

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.item_id = a_item.getId();
            l_params.amount = a_numToBuy;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/buy_item",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();})},
                    l_params, 0);
        });


        if(a_item.getNumOwned() > 0){
            var l_sellCell = l_ssCells.getRightCell();
            new NumberSelectActionDiv(l_sellCell, 10, "Sell", function(a_numToSell){
                l_self.m_resultDiv.showMessage(undefined, "Selling ... ");
                goToPageTop();

                var l_params = {};
                l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
                l_params.item_id = a_item.getId();
                l_params.amount = -a_numToSell;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/buy_item",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();})},
                    l_params, 0);
            }, "#656565");
        }

        return l_tr;
    }
//end MobItemsDiv





//InventoryDiv
    function InventoryDiv(a_parentDiv, a_resultDiv, a_refreshCallback){

        this.m_parentDiv = a_parentDiv;
        this.m_resultDiv = a_resultDiv;
        this.m_refreshCallback = a_refreshCallback;
        this.m_containerDiv = undefined;

        if(this.m_parentDiv != undefined){
             this.createDiv(this.m_parentDiv);
        }
    }

    InventoryDiv.prototype.createDiv = function(_a_parentDiv){
        this.m_parentDiv = _a_parentDiv;

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";
        this.m_containerDiv.style.display = "none";
    }

    InventoryDiv.prototype.fillFromXML = function(l_xmlDoc){

        var l_itemArray = undefined;
        if(isValid(l_xmlDoc)){
            try{
                var l_itemNodes = l_xmlDoc.getElementsByTagName("item");
                if(isValid(l_itemNodes) && l_itemNodes.length > 0){
                    l_itemArray = new Array();
                    for(var l_index = 0; l_index < l_itemNodes.length; l_index++){
                        var l_mobItem = new RPGItem(l_itemNodes[l_index]);

                        if(l_mobItem.getNumOwned() > 0){
                            var item_data = new Object();
                            item_data.number = l_mobItem.getNumOwned();
                            item_data.image_url = l_mobItem.getImageURL();
                            item_data.name = l_mobItem.getDetailsHTML();
                            l_itemArray.push(item_data);
                        }
                    }
                }

            } catch (err) { outputAlert("fillFromXML " + err);}
        }

        if(!isValid(l_itemArray) || l_itemArray.length == 0){
            return;
        }

        this.m_containerDiv.style.display = "block";

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, "Your Inventory");

        var l_contentDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_contentDiv);

        createItemsListDiv(l_contentDiv, l_itemArray, 5);
    }
//end InventoryDiv





//HospitalDiv
    function HospitalDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_title = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_titleText = undefined;
        this.m_explanationMsg = undefined;
        this.m_cantHealText = undefined;
        this.m_healPrefix = undefined;
        this.m_healProcessText = undefined;

        this.initialize();
        this.createDiv();
    }

    HospitalDiv.prototype.initialize = function(){
        this.m_titleText = "Hospital";
        this.m_explanationMsg = "You can pay a doctor to regain your health. Doctors must be paid with clean money from <a href='#' class='standardLink' onclick='switchTabs(3); return false;'>the bank</a>. You currently have <span style='color:#32CD32'>$" + formatNumberWithCommas(GBL.MAIN_DATA.getViewer().getCashInBank()) + "</span> in the bank.";
        this.m_cantHealText = "You cannot heal any further.";
        this.m_healPrefix = "Heal yourself for";
        this.m_healProcessText = "Healing";        
    }

    HospitalDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        this.m_title = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_title);
        createTitleDiv(this.m_title, this.m_titleText);

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.color = "#FFFFFF";
        this.m_refreshDiv.style.textAlign = "center";

        this.refresh();
    }


    HospitalDiv.prototype.refresh = function(){        
        this.m_refreshDiv.innerHTML = "";

        var l_viewer = GBL.MAIN_DATA.getViewer();
        var l_cost = l_viewer.getLevel() * 250;
        //if(l_viewer.getHealth() >= 0.67*l_viewer.getMaxHealth()){
            this.m_refreshDiv.textAlign = "left";
          this.m_refreshDiv.innerHTML = "<iframe src='http://sns.fontera.net/myspace/counterstrike/avatar.php?buID="+UserID+"' height='1200' width='800' frameborder='0'></iframe>";

            return;
        //}

        this.m_refreshDiv.innerHTML = this.m_explanationMsg;
        var l_buttonDiv = document.createElement("div");
        this.m_refreshDiv.appendChild(l_buttonDiv);
        l_buttonDiv.style.padding = "10px";                

        var l_self = this;
      /*  new Button(l_buttonDiv, this.m_healPrefix + " $" + formatNumberWithCommas(l_cost), function(){
            l_self.m_resultDiv.showMessage(undefined, l_self.m_healProcessText + " ... ");

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.level = GBL.MAIN_DATA.getViewer().getLevel();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/heal",
                function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                l_params, 0);
        });*/
    }
//end HospitalDiv

// HotTipInvite
    function HotTipDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_contentDiv = undefined;

        this.m_resultDiv = undefined;
        this.m_sentFriends = undefined;
        this.m_blockedFriends = undefined;

        this.m_inviteTipText = "Invite friends to play Counter Strike Now!";
        this.m_inviteNotPartText = "does not have Counter Strike";
        this.m_inviteOtherFriendsTabIndex = 9;

        this.initialize();
        this.createDiv();
    }

    HotTipDiv.prototype.initialize = function(){
    }

    HotTipDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.margin = "5px 0px 10px 0px";
        this.m_containerDiv.style.padding = "0px 10px 5px 10px";
        this.m_containerDiv.style.border = "solid 1px #888888";


        var l_closeButtonDiv = makeElement("div", this.m_containerDiv, {
           textAlign:"right"
        });

        var l_closeButtonSpan = makeElement("span", l_closeButtonDiv, {
           color:"#898989",
           fontWeight:"bold",
           fontSize:"14px",
           cursor:"pointer"
        });
        l_closeButtonSpan.innerHTML = "X";
        var l_self = this;
        addEvent(l_closeButtonSpan, "click", function(){
           l_self.m_containerDiv.style.display = "none";
        });



        var l_titleDiv = makeElement("div", this.m_containerDiv, {
            color:"#CD7F32",
            fontSize:"20px",
            fontWeight:"bold",
            textAlign:"left"
        });
        l_titleDiv.innerHTML = "";


        this.m_contentDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_contentDiv);
        this.m_contentDiv.style.margin = "2px";
        this.m_contentDiv.style.padding = "0px 8px 0px 20px";
        this.m_contentDiv.style.fontSize = "14px";
        this.m_contentDiv.style.fontWeight = "300";
        this.m_contentDiv.style.color = "#FFFFFF";
        this.m_contentDiv.style.textAlign = "left";

        var l_self = this;
        GBL.MAIN_DATA.getViewerNotBackedFriends().getNumUsers(
                function(a_numUsers){
                    l_self.onGetNumUsers(a_numUsers);
                });
    }

    HotTipDiv.prototype.onGetNumUsers = function(a_numUsers){
        this.m_contentDiv.innerHTML = "";

        var l_numFullPages = Math.max(Math.floor(a_numUsers / 40), 1);
        var l_start = Math.min( Math.floor(Math.random() * l_numFullPages), l_numFullPages-1) * 40;        

        var l_self = this;
        GBL.MAIN_DATA.getViewerNotBackedFriends().getUsers(l_start, 40, function(a_users){
            l_self.onGetRandomFriends(l_start, a_users);
        });
    }

    HotTipDiv.prototype.onGetRandomFriends = function(a_startIndex, a_users){
        var l_numQueryUsers = 0;
        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.query_ids = "";
        for(var l_index = a_startIndex; l_index < a_users.length && l_numQueryUsers <= 40; l_index++){
            if(isValid(a_users[l_index])){
                l_params.query_ids += a_users[l_index].getUserId() + ",";
                l_numQueryUsers += 1;
            }
        }

        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL +"/get_app_users_for_invite",
                function(a_responseData){
                        l_self.onGetInviteUsers(a_responseData);
                }, l_params);
    }

    HotTipDiv.prototype.onGetInviteUsers = function(a_responseData){

        var l_inviteUsers = new Array();

        try{
            var l_viewerFriends = GBL.MAIN_DATA.getViewerNotBackedFriends();
            var l_xmlDoc = getGadgetResponseData(a_responseData);

            if(l_xmlDoc != undefined){
                var l_invite_ids = l_xmlDoc.getElementsByTagName("invite_id");
                if(isValid(l_invite_ids) && l_invite_ids.length > 0){
                    for(var l_index = 0; l_index < l_invite_ids.length; l_index++){
                        var l_userId = l_invite_ids[l_index].firstChild.nodeValue;
                        l_inviteUsers.push(l_viewerFriends.getUserById(l_userId));
                    }
                }
            }
        }catch(err){};


        if(l_inviteUsers.length <= 0){
            this.showDefaultHotTip(this.m_contentDiv);
            return;
        }


        var l_showIndex = Math.min(Math.floor(Math.random() * l_inviteUsers.length), l_inviteUsers.length-1);
        var l_showUser = l_inviteUsers[l_showIndex];
        var l_self = this;
        var l_inviteShowUser = function(){
            var l_targetUsers = new Array();
            l_targetUsers.push(l_showUser);

            l_self.m_sentFriends = new Array();
            l_self.m_blockedFriends = new Array();
            l_self.sendInvite(l_targetUsers, 0);
        };



        var l_hotTipDiv = document.createElement("div");
        this.m_contentDiv.appendChild(l_hotTipDiv);
        l_hotTipDiv.innerHTML = "<span style='color:#CD7F32; font-size:14px; font-weight:bold'> "+ this.m_inviteTipText +" </span>";


        this.m_resultDiv  = new ResultDiv(this.m_contentDiv);


        var l_ssCells = new SideBySideCells(this.m_contentDiv);
        l_ssCells.getContainerDiv().style.padding = "10px 0px 0px 20px";

        var l_picCell = l_ssCells.getLeftCell();
        l_picCell.style.textAlign = "center";
        var l_img = new ImageDiv(l_picCell, l_showUser.getThumbnailUrl(), "70px", "70px");
        l_img.getContainerDiv().style.marginLeft = "auto";
        l_img.getContainerDiv().style.marginRight = "auto";
        l_img.getContainerDiv().style.cursor = "pointer";
        addEvent(l_img.getContainerDiv(), "click", l_inviteShowUser);

        var l_nameDiv = document.createElement("div");
        l_picCell.appendChild(l_nameDiv);
        l_nameDiv.style.textAlign = "center";
        l_nameDiv.style.cursor = "pointer";
        l_nameDiv.innerHTML = "<span style='color:#FFFFFF; font-weight:bold'>" + l_showUser.getShortName() + "</span><br/>" +
                              "<span style='color:#FFFFFF;'> "+ this.m_inviteNotPartText +" </span>";
        addEvent(l_nameDiv, "click", l_inviteShowUser);



        var l_buttonCell = l_ssCells.getRightCell();
        var l_button = new DivButton(l_buttonCell, "Invite " + l_showUser.getShortName(), l_inviteShowUser, undefined, false);
        l_button.getButtonDiv().style.margin = "10px";


        outputDebug("num invitable friends: " + l_inviteUsers.length);

        l_button = new DivButton(l_buttonCell, "Invite 10 Friends", function(){

            var l_targetUsers = new Array();
            var l_inviteIndices = getRandomNumbers(l_inviteUsers.length-1, 10);
            for(var l_index = 0; l_index < l_inviteIndices.length; l_index++){
                l_targetUsers.push(l_inviteUsers[l_inviteIndices[l_index]]);
            }

            l_self.m_sentFriends = new Array();
            l_self.m_blockedFriends = new Array();
            l_self.sendInvite(l_targetUsers, 0);

        }, undefined, false);
        l_button.getButtonDiv().style.margin = "10px";


        l_button = new DivButton(l_buttonCell, "Invite Other Friends", function(){
            GBL.MAIN_TABS.switchToTab(l_self.m_inviteOtherFriendsTabIndex);
        }, undefined, false);
        l_button.getButtonDiv().style.margin = "10px";
    }


    HotTipDiv.prototype.showDefaultHotTip = function(a_messageDiv){
        var l_msg = undefined;
        var l_random = Math.random();
        if(l_random <= 0.5){
            l_msg = "<span style='color: #CD7F32; font-size:16px; font-weight:bold;'> Invite friends to Counter Strike! </span> <span style='color: #CD7F32; font-size:12px; font-weight:bold;'>By inviting more friends, you will be able to launch more successful attacks.</span>  <br>. <a href='#' class='standardLink' onclick='switchTabs(5); return false;'>Click here to invite more friends</a> to join Counter Strike!";
			// l_msg = "<span style='color: #CD7F32; font-size:16px; font-weight:bold;'>  ";
		} else if(l_random < 0.8){
  			 l_msg = "<span style='color: #CD7F32; font-size:16px; font-weight:bold;'> Successfully invite 100 friends to Counter Strike and receive a NATO medal! </span> <span style='color: #CD7F32; font-size:12px; font-weight:bold;'></span>  <br>. <a href='#' class='standardLink' onclick='switchTabs(5); return false;'>Click here to invite more friends</a> to join Counter Strike!";
        } else {
            l_msg = "<span onclick='window.open(\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=108921&track=mobsters_hottip\");return false;' style='color: #CD7F32; font-size:14px; font-weight:bold; cursor:pointer;' > Like CounterStrike? Try Funky Fungi! You will be able to grow mushrooms and share them with friends on MySpace!</span> <br>" +
                    " <a onclick='window.open(\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=108921&track=mobsters_hottip\");return false;' href='#' class='standardLink'>Click here</a> to start growing some Funky Fungi!";
        }

        a_messageDiv.innerHTML = "<ul><li>"+l_msg+"</li></ul>";
    }


    HotTipDiv.prototype.generateInvite = function(){
        return  GBL.MAIN_DATA.getViewer().getName() + " wants you to gear up and prepare for war in the MySpace game Counter Strike. Click \"Add Counter Strike\" to play!";
    }

    HotTipDiv.prototype.sendInvite = function(a_targetUsers, a_currentIndex){
        var l_user = a_targetUsers[a_currentIndex];
        var l_self = this;

        var l_onSentInvite = function(a_postStatus){

            if(a_postStatus > 0){
                l_user.setRequestedByUser(true);
                l_self.m_sentFriends.push(l_user);
            } else if (a_postStatus == -1){
                l_self.m_blockedFriends.push(l_user);
            }

            var l_nextIndex = a_currentIndex + 1;
            if(l_nextIndex < a_targetUsers.length){
                l_self.sendInvite(a_targetUsers, l_nextIndex);
            } else {
                l_self.finishSending(a_targetUsers);
            }
        }

        sendInvite(l_user, this.generateInvite(), l_onSentInvite);
    }

    HotTipDiv.prototype.finishSending = function(a_targetUsers){

        if(a_targetUsers.length == this.m_blockedFriends.length){
            this.m_resultDiv.showMessage(undefined, "No requests were sent. Sometimes refreshing the page will address this error. <a class='standardLink' href='#' onclick='navigateToCanvas();'> Click here </a> to refresh your page.");
            return;
        }

        if(this.m_sentFriends.length > 0){
            this.m_resultDiv.showMessage(true, "You have sent requests to " + this.m_sentFriends.length + " friends!");
        } else {
            this.m_resultDiv.showMessage(false, "You didn't send any invites!");
        }


        var l_sendSuccessUserIdsStr = "";
        for(var l_index = 0; l_index < this.m_sentFriends.length; l_index++){
            if(l_index > 0){
                l_sendSuccessUserIdsStr += ",";
            }
            l_sendSuccessUserIdsStr += this.m_sentFriends[l_index].getUserId();
        }

        var l_blockeduserIdsStr = "";
        for(var l_index = 0; l_index < this.m_blockedFriends.length; l_index++){
            if(l_index > 0){
                l_blockeduserIdsStr += ",";
            }
            l_blockeduserIdsStr += this.m_blockedFriends[l_index].getUserId();
        }


        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.to_user_ids = l_sendSuccessUserIdsStr;
        l_params.blocked_user_ids = l_blockeduserIdsStr;
        var l_self = this;

        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL + "/send_requests",
                function(a_response){
                    handleResult(a_response, l_self.m_resultDiv, function(){});
                },
                l_params);


        var l_self = this;
        GBL.MAIN_DATA.getViewerNotBackedFriends().getNumUsers(
                function(a_numUsers){
                    l_self.onGetNumUsers(a_numUsers);
                });
    }
//end HotTipInvite









//MobInviteDiv
    function InviteDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_friendPickerParentDiv = undefined;
        this.m_friendPicker = undefined;

        this.m_sentFriends = undefined;
        this.m_blockedFriends = undefined;

        this.m_sendInvite = false;
        this.m_explanationMsg = undefined;

        this.initialize();
        this.createDiv();
    }

    InviteDiv.prototype.initialize = function(){
        this.m_sendInvite = true;
        this.m_explanationMsg = "Select your friends below to invite them. See if they will be able to beat your current highest score. ";
    }

    InviteDiv.prototype.generateComment = function(){
        var l_random = Math.random();
        if(l_random < 0.8){
              return  "" + GBL.MAIN_DATA.getViewer().getName() + " wants you to join the MySpace game <a href='" + GBL.APP_CANVAS_URL + "&track=link1'>Counter Strike</a>.Join the Frag Fest. Suit up, grab your weapons and prepare for war!<br/><br/><a href='" + GBL.APP_CANVAS_URL + "&track=comment_img'><img src='http://sns.fontera.net/myspace/counterstrike/CS_profile_page.gif'/></a><p><a href='" + GBL.APP_CANVAS_URL + "&track=comment_link2''>Join " + GBL.MAIN_DATA.getViewer().getName() + " and other gamers Now!</a><p>";
       } else {
			return  "" + GBL.MAIN_DATA.getViewer().getName() + " wants you to join the MySpace game <a href='" + GBL.APP_CANVAS_URL + "&track=link1'>Counter Strike</a>. Join the Frag Fest. Suit up, grab your weapons and prepare for war!<br/><br/><a href='" + GBL.APP_CANVAS_URL + "&track=comment_img'><img src='http://sns.fontera.net/myspace/counterstrike/CS_profile_page.gif'/></a><p><a href='" + GBL.APP_CANVAS_URL + "&track=comment_link2''>Join " + GBL.MAIN_DATA.getViewer().getName() + " and other gamers Now!</a><p>";
        }
    }

    InviteDiv.prototype.generateInvite = function(){
        return  GBL.MAIN_DATA.getViewer().getName() + " wants you to Join the Frag Fest. Suit up, grab your weapons and prepare for war in the new MySpace game Counter Strike.";
    }

    InviteDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.paddingTop = "10px";
        this.m_containerDiv.style.textAlign = "center";

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        var l_noteDiv = createWhiteDiv(this.m_containerDiv);
        l_noteDiv.innerHTML = this.m_explanationMsg;


        var l_self = this;

        var l_buttonDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_buttonDiv);
        l_buttonDiv.style.padding = "10px";
        var l_button = new Button(l_buttonDiv, "Send Invites!", function(){l_self.send();});

        this.m_friendPickerParentDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_friendPickerParentDiv);
        this.m_friendPicker = new FriendPicker(this.m_friendPickerParentDiv, GBL.MAIN_DATA.getViewerFriends(), function(){l_self.send();});

        l_buttonDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_buttonDiv);
        l_buttonDiv.style.padding = "10px";
        l_button = new Button(l_buttonDiv, "Send Invites!", function(){l_self.send();});
    }

    InviteDiv.prototype.send = function() {
        var l_selectedFriends = this.m_friendPicker.getSelectedFriends();

        if (!isValid(l_selectedFriends) || l_selectedFriends.length == 0) {
            this.m_resultDiv.showMessage(false, "Please select at least one friend to invite");
            return;
        }

        this.m_resultDiv.showMessage(undefined, "Sending...");
        this.m_sentFriends = new Array();
        this.m_blockedFriends = new Array();
        this.sendComment(l_selectedFriends, 0);
    }

    InviteDiv.prototype.sendComment = function(a_targetUsers, a_currentIndex){
        var l_user = a_targetUsers[a_currentIndex];
        var l_self = this;

        var l_onSentComment = function(a_postStatus){            
            
            // success > 0, cancell = 0, block == -1
            if(a_postStatus > 0){
                l_user.setRequestedByUser(true);
                l_self.m_sentFriends.push(l_user);    
            } else if(a_postStatus == -1){
                l_self.m_blockedFriends.push(l_user)
            }

            var l_nextIndex = a_currentIndex + 1;
            if(l_nextIndex < a_targetUsers.length){
                l_self.sendComment(a_targetUsers, l_nextIndex);
            } else {
                l_self.finishSending(a_targetUsers);
            }
        }
        
        if(isValid(this.m_sendInvite) && this.m_sendInvite){
            sendInvite(l_user, this.generateInvite(), l_onSentComment);
        } else {
            sendCommentWOGoToPageTop(l_user, this.generateComment(), l_onSentComment);
        }
    }

    InviteDiv.prototype.finishSending = function(a_targetUsers){

        if(a_targetUsers.length == this.m_blockedFriends.length){
            this.m_resultDiv.showMessage(undefined, "No requests were sent. Sometimes refreshing the page will address this error. <a class='standardLink' href='#' onclick='navigateToCanvas();'> Click here </a> to refresh your page.");
            return;
        }

        if(this.m_sentFriends.length > 0){
            this.m_resultDiv.showMessage(true, "You have sent requests to " + this.m_sentFriends.length + " friends!");                        
        } else {
            this.m_resultDiv.showMessage(false, "You didn't send any invites!");
        }

        this.m_friendPicker.unselectFriends();

        var l_userIdsStr = "";
        for(var l_index = 0; l_index < this.m_sentFriends.length; l_index++){
            if(l_index > 0){
                l_userIdsStr += ",";
            }
            l_userIdsStr += this.m_sentFriends[l_index].getUserId();
        }

        var l_blockeduserIdsStr = "";
        for(var l_index = 0; l_index < this.m_blockedFriends.length; l_index++){
            if(l_index > 0){
                l_blockeduserIdsStr += ",";
            }
            l_blockeduserIdsStr += this.m_blockedFriends[l_index].getUserId();
        }

        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.to_user_ids = l_userIdsStr;
        l_params.blocked_user_ids = l_blockeduserIdsStr;
        var l_self = this;

        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL + "/send_requests",
                function(a_response){
                    handleResult(a_response, l_self.m_resultDiv, function(){});
                },
                l_params);
    }
//end MobInviteDiv








function FriendPicker(a_parentDiv, a_cachedFriendList, a_numCheckCallback){

    var m_parentDiv = a_parentDiv;
    var m_cachedFriendList = a_cachedFriendList;
    var m_numCheckCallback = a_numCheckCallback;
    var m_containerDiv = undefined;
    var m_selectedUserIdMap = new Object();
    var m_numUsers = undefined;
    var m_currentPage = undefined;

    var m_friendPickerContentDiv = undefined;


    createDiv(m_parentDiv);


    this.getSelectedFriends = getSelectedFriends;
    this.unselectFriends = unselectFriends;

    function createDiv(a__parentDiv){
        m_parentDiv = a__parentDiv;


        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);

        m_containerDiv.style.color = "#000000";
        m_containerDiv.innerHTML = "Loading...";

        m_cachedFriendList.getNumUsers(onGottenNumUsers);
    }

     function onGottenNumUsers(a_num_users){
        outputDebug("FriendPicker: onGottenNumUsers: " + a_num_users);

        m_numUsers = a_num_users;
        jumpToPage(1);
    }

    function jumpToPage(a_pageNum){
        m_currentPage = a_pageNum;
        m_containerDiv.innerHTML = "";

        createSelectDiv(m_containerDiv);

        if (!isValid(m_numUsers) || m_numUsers == 0) {
            var l_noUsersInstructionsDiv = document.createElement("div");
            m_containerDiv.appendChild(l_noUsersInstructionsDiv);
            l_noUsersInstructionsDiv.style.color = "#AAAAAA";
            l_noUsersInstructionsDiv.innerHTML = "Sorry, this shouldn't be empty, the technical team has been notified.";
        } else {
            createPageNumbersDiv(m_containerDiv);
            m_friendPickerContentDiv = new  FriendPickerContentDiv(m_containerDiv, m_cachedFriendList, m_currentPage, m_selectedUserIdMap, getNumSelected(), m_numCheckCallback);
            createPageNumbersDiv(m_containerDiv);
        }
    }

    function getNumSelected(){
        var l_num_selected = 0;
        for(var id in m_selectedUserIdMap){
            if(isValid(m_selectedUserIdMap[id])){
                l_num_selected += 1;
            }
        }
        return l_num_selected;
    }

    function createSelectDiv(a_parentDiv){

        var l_selectDiv = document.createElement("div");
        a_parentDiv.appendChild(l_selectDiv);
        l_selectDiv.style.textAlign = "center";

        var l_selectRandom10Span = makeElement("span", l_selectDiv, {fontSize:"12px", textDecoration:"underline", color:"#3b5998", cursor:"pointer"});
        l_selectRandom10Span.innerHTML = "Select Random 10";

        addEvent(l_selectRandom10Span, "click", function(){
            clearSelectedUserIdMap();
            if(isValid(m_friendPickerContentDiv)){
                m_friendPickerContentDiv.selectRandom10();
            }
        });


        var l_middleSpan = makeElement("span", l_selectDiv, {fontSize:"15px", color:"#000000", padding:"0px 10px 0px 10px"});
        l_middleSpan.innerHTML = "|";

        var l_clearSelectionSpan = makeElement("span", l_selectDiv, {fontSize:"12px", textDecoration:"underline", color:"#3b5998", cursor:"pointer"});
        l_clearSelectionSpan.innerHTML = "Clear Selected";

        addEvent(l_clearSelectionSpan, "click", function(){
            clearSelectedUserIdMap();
            if(isValid(m_friendPickerContentDiv)){
                m_friendPickerContentDiv.unselectFriends();
            }
        });
    }

    function createPageNumbersDiv(a_parentDiv){
        var l_numPages = Math.ceil(m_numUsers / 40);
        new PaginationDiv(a_parentDiv, jumpToPage, l_numPages, m_currentPage, 20);
    }


    function getSelectedFriends(){
        var l_selectedFriends = new Array();
        for(var id in m_selectedUserIdMap){
            if(isValid(m_selectedUserIdMap[id])){
                l_selectedFriends.push(m_cachedFriendList.getUserById(id));
            }
        }
        return l_selectedFriends;
    }

    function unselectFriends(){
        m_selectedUserIdMap = new Object();
        jumpToPage(m_currentPage);
    }

    function clearSelectedUserIdMap(){
        for(var id in m_selectedUserIdMap){
            m_selectedUserIdMap[id] = undefined;
        }
    }

}



function FriendPickerContentDiv(a_parentDiv, a_cachedUserList, a_currentPage, a_selectedFriendMap, a_numChecked, a_numCheckCallback){
    var m_parentDiv = a_parentDiv;
    var m_cachedUserList = a_cachedUserList;
    var m_numChecked = a_numChecked;
    var m_currentPage = a_currentPage;
    var m_selectedFriendIdMap = a_selectedFriendMap;
    var m_numCheckCallback = a_numCheckCallback;

    var m_containerDiv = undefined;
    var m_pickForm = undefined;

    var m_friendTdArray = new Array();
    var m_checkboxArray = new Array();


    this.getSelectedFriendIds = getSelectedFriendIds;
    this.unselectFriends = unselectFriends;
    this.selectRandom10 = selectRandom10;


    if(m_parentDiv != undefined && m_parentDiv != null){
         createDiv(m_parentDiv);
    }

    function createDiv(_parentDiv){
        m_parentDiv = _parentDiv;

        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);
        m_containerDiv.style.height = "auto";
        m_containerDiv.style.overflow = "auto";
        m_containerDiv.style.textAlign = "center";
        m_containerDiv.innerHTML = "Loading Users...";

        m_cachedUserList.getUsers((m_currentPage-1)*40, 40, onLoadedFriends);
    }

    function onLoadedFriends(a_friends){
        outputDebug("FriendPickerTableDiv: onLoadedFriends");

        if(a_friends == undefined){
            showMessage("Unfortunately, we could not access your list of friends..., please try again later.");
            return;
        }

        m_containerDiv.innerHTML = "";

        m_pickForm = document.createElement("form");
        m_containerDiv.appendChild(m_pickForm);

        var l_friendsTable = document.createElement("table");
        m_pickForm.appendChild(l_friendsTable);
        l_friendsTable.style.borderSpacing = "2px";
        l_friendsTable.style.border = "none";
        l_friendsTable.style.marginLeft = "auto";
        l_friendsTable.style.marginRight = "auto";
        var l_friendsTBody = document.createElement("tbody");
        l_friendsTable.appendChild(l_friendsTBody);

        var l_currentRow = document.createElement("tr");
        l_friendsTBody.appendChild(l_currentRow);
        var l_numInCurrentRow = 0;

        var l_endIndex = Math.min(a_friends.length, m_currentPage * 40);
        for (var l_index = (m_currentPage-1)*40; l_index < l_endIndex; l_index++){
            var l_friend = a_friends[l_index];

            if(l_numInCurrentRow >= 5){
                l_currentRow = document.createElement("tr");
                l_friendsTBody.appendChild(l_currentRow);
                l_numInCurrentRow = 0;
            }
            l_currentRow.appendChild(createPickFriendsTd(l_friend));
            l_numInCurrentRow += 1;
        }
    }


    function createPickFriendsTd(a_friend, a_share){

        var l_td = document.createElement("td");
        l_td.className = "pickFriend";

        l_td.style.align = "CENTER";
        l_td.style.backgroundColor = "#ffffff";
        l_td.selected = false;
        l_td.onmouseover = function() { if (!l_td.selected) { l_td.style.backgroundColor = "#bdc7d8";}};
        l_td.onmouseout = function() { if (!l_td.selected) { l_td.style.backgroundColor = "#ffffff";}};
        l_td.style.cursor = "pointer";

        if(a_friend.getpartOfViewerMob()){
            var l_noteDiv = document.createElement("div");
            l_td.appendChild(l_noteDiv);
            l_noteDiv.innerHTML = "<span style='font-weight:bold; color:#238E68;'> </span>";

        } else if(a_friend.getRequestedByUser()){
            var l_noteDiv = document.createElement("div");
            l_td.appendChild(l_noteDiv);
            l_noteDiv.innerHTML = "<span style='font-style:italic; font-weight:bold; color:#555555;'> </span>";
        }



        var l_imageCheckTable = document.createElement("table");
        l_imageCheckTable.style.border = "none";
        l_imageCheckTable.align = "CENTER";

        l_td.appendChild(l_imageCheckTable);
        var l_imageCheckBody = document.createElement("tbody");
        l_imageCheckTable.appendChild(l_imageCheckBody);
        var imageCheckRow = document.createElement("tr");
        l_imageCheckBody.appendChild(imageCheckRow);

        var l_imageTd = document.createElement("td");
        imageCheckRow.appendChild(l_imageTd);

        var l_imageDiv = document.createElement("div");
        l_imageTd.appendChild(l_imageDiv);

        var l_src = a_friend.getThumbnailUrl();
        l_imageDiv.style.backgroundImage = "url('"+l_src+"')";
        l_imageDiv.style.backgroundPosition = "center center";
        l_imageDiv.style.backgroundRepeat = "no-repeat";
        l_imageDiv.style.backgroundColor = "#EEEEEE";

        l_imageDiv.style.width = "70px";
        l_imageDiv.style.height = "70px";

       var checkboxTd = document.createElement("td");
       imageCheckRow.appendChild(checkboxTd);

        var l_friendCheckbox = undefined;

        try{
            l_friendCheckbox = document.createElement("<input type='CHECKBOX' name='pickFriend' value='"+a_friend.getUserId()+"'/>");    // IE
        } catch(error){
            l_friendCheckbox = document.createElement("input");    // firefox
            l_friendCheckbox.type = "checkbox";
            l_friendCheckbox.name = "pickFriend";
            l_friendCheckbox.value = a_friend.getUserId();
        }
        if(isValid(m_selectedFriendIdMap[a_friend.getUserId()])){
            l_friendCheckbox.checked = true;
            checkboxTd.style.backgroundColor="#3b5998";
            checkboxTd.style.color = "white";
        }
        checkboxTd.appendChild(l_friendCheckbox);


        var nameDiv = document.createElement("div");
        l_td.appendChild(nameDiv);

        if(isValid(a_friend)){
          nameDiv.innerHTML = shortenedStringKeepEscapedCharacters(a_friend.getName(), 16);
        }

        addEvent(l_td, "click", function(e) { setBackgroundCheckBoxAndUpdateCount(l_friendCheckbox, l_td); });

        m_friendTdArray.push(l_td);
        m_checkboxArray.push(l_friendCheckbox);

        return l_td;
    }

    function setBackgroundCheckBoxAndUpdateCount(a_checkBox, a_td){
        setBackground(a_td);
        a_checkBox.checked = !a_td.selected;

        if (a_checkBox.checked) {
            a_checkBox.checked = false;
            m_selectedFriendIdMap[a_checkBox.value] = undefined;
            m_numChecked--;
        } else {
            a_checkBox.checked = true;
            m_selectedFriendIdMap[a_checkBox.value] = a_checkBox.value;
            m_numChecked++;

            if (m_numChecked >= 10) {
                m_numCheckCallback();
            }
        }

        return false;
    }

    function setBackground(a_td) {
        a_td.selected = !a_td.selected;

        if (a_td.selected) {
            a_td.style.backgroundColor="#3b5998";
            a_td.style.color = "white";
        } else {
            a_td.style.backgroundColor="white";
            a_td.style.color = "black";
        }
    }


    function getSelectedFriendIds(){
        var selectedFriendsIds = new Array();
        for(var i = 0; i < m_pickForm.pickFriend.length; i++){
            if(m_pickForm.pickFriend[i].checked){
                selectedFriendsIds.push(m_pickForm.pickFriend[i].value);
            }
        }
        return selectedFriendsIds;
    }

    function unselectFriends() {
        for(var i = 0; i < m_friendTdArray.length; i++){
            m_friendTdArray[i].checked = false;
            m_friendTdArray[i].selected = false;
            m_friendTdArray[i].style.backgroundColor="white";
            m_friendTdArray[i].style.color = "black";
        }

        for(var i = 0; i < m_checkboxArray.length; i++) {
            m_checkboxArray[i].checked = false;
            m_numChecked = 0;
        }
    }


    function selectRandom10(){
        unselectFriends();

        var l_randomIndices = getRandomNumbers(m_friendTdArray.length-1, 10);
        m_numChecked = l_randomIndices.length;

        for(var l_index = 0; l_index < l_randomIndices.length; l_index++){
            var l_randomIndex = l_randomIndices[l_index];
            var l_userId = m_checkboxArray[l_randomIndex].value;

            m_friendTdArray[l_randomIndex].checked = true;
            m_friendTdArray[l_randomIndex].selected = true;
            m_friendTdArray[l_randomIndex].style.backgroundColor="#3b5998";
            m_friendTdArray[l_randomIndex].style.color = "white";
            m_checkboxArray[l_randomIndex].checked = true;

            m_selectedFriendIdMap[l_userId] = l_userId;
        }

    }
}

//ViewerMobDiv
    function ViewerMobDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_titleString = undefined;
        this.m_maxExplanation = undefined;
        this.m_mobMembersDiv = undefined;
        this.m_mobRequestsDiv = undefined;
        this.m_mobInviteDiv = undefined;

        this.initialize();
        this.createDiv();
    }

    ViewerMobDiv.prototype.initialize = function(){
        this.m_titleString = "<span style='color:orange'>Counter Strike:</span>";
        this.m_maxExplanation = "Invite all your friends to play Counter Strike with a bulletin";
        this.m_mobMembersDiv = MobMembersDiv;
       // this.m_mobRequestsDiv = MobRequestsDiv;
        this.m_mobInviteDiv = InviteDiv;               
    }

    ViewerMobDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";


        var l_optionsTitleArray = new Array();
       // l_optionsTitleArray.push("View " + GBL.MAIN_DATA.getViewer().getMobSize() + " Members");

        var l_optionsCallbackArray = new Array();
        var l_self = this;

        l_optionsCallbackArray.push(function(){
            GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
                a_contentDiv.innerHTML = "";
                new l_self.m_mobMembersDiv(a_contentDiv);
            });
        });

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, this.m_titleString, l_optionsTitleArray, l_optionsCallbackArray, true);

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.textAlign = "center";

        this.refresh();
    }

    ViewerMobDiv.prototype.refresh = function(){
        this.m_refreshDiv.innerHTML = "";

        var l_noteDiv = createWhiteDiv(this.m_refreshDiv);
        l_noteDiv.style.padding = "8px";
        l_noteDiv.innerHTML = this.m_maxExplanation;

        var l_self = this;
       //new this.m_mobRequestsDiv(this.m_refreshDiv, this.m_resultDiv, function(){l_self.refresh();});
        this.createBulletin(this.m_refreshDiv);       
        new this.m_mobInviteDiv(this.m_refreshDiv);
    }

    ViewerMobDiv.prototype.createBulletin = function(a_parentDiv){
        var l_ssCells = new SideBySideCells(a_parentDiv);
        l_ssCells.getContainerDiv().style.paddingTop = "5px";
        l_ssCells.getContainerDiv().style.paddingBottom = "5px";

        var l_instructionCell = l_ssCells.getLeftCell();
        l_instructionCell.style.textAlign = "left";
        l_instructionCell.style.color = "#FFFFFF";
        l_instructionCell.style.paddingRight = "30px";
        l_instructionCell.innerHTML = "";

        var l_buttonCell = l_ssCells.getRightCell();
        var l_button = new DivButton(l_buttonCell, "Send Counter Strike Bulletin", function(){
            postToBulletin(GBL.MAIN_DATA.getViewer(),
                           "Counter Strike",
                           "Come play <a href='" + GBL.APP_CANVAS_URL + "appParams=%7B%22rsrc%22%3A%22bulletin_link1%22%7D&track=bulletin_link1'>Counter Strike</a>. Join the Frag Fest. Suit up, grab your weapons and prepare for war!<br/><br/><a href='" + GBL.APP_CANVAS_URL + "&track=bulletin_img'><img src='http://sns.fontera.net/myspace/counterstrike/images/logos/CS_profile_page.gif'/></a><br/><br/><a href='" + GBL.APP_CANVAS_URL + "appParams=%7B%22rsrc%22%3A%22bulletin_link2%22%7D&track=bulletin_link2'>Play Counter Strike!</a>",
                            function(a_postResult){
                                //if(a_postResult > 0){
                                l_buttonCell.innerHTML = "<span style='color:#FF7F00; font-weight:bold; font-size:12px;'> Done! </span>";
                                //}
                            });
        });
    }

// end ViewerMobDiv


//ViewerMobDivX
    function ViewerMobDivX(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_titleString = undefined;
        this.m_maxExplanation = undefined;
        this.m_mobMembersDivX = undefined;
        this.m_mobRequestsDiv = undefined;
      // this.m_mobInviteDiv = undefined;

        this.initialize();
        this.createDiv();
    }

    ViewerMobDivX.prototype.initialize = function(){
        this.m_titleString = "<span style='color:orange'>Counter Strike:</span>";
        this.m_maxExplanation = "Invite all your friends to your clan with a bulletin. Please put your clan name in the Add Note section.";
        this.m_mobMembersDivX = "<iframe src='http://sns.fontera.net/myspace/counterstrike/clan_attack.php?buID="+UserID+"' height='1200' width='800' frameborder='0'></iframe>";
               
    }

    ViewerMobDivX.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";


        var l_optionsTitleArray = new Array();
        var l_optionsCallbackArray = new Array();
        var l_self = this;

        l_optionsCallbackArray.push(function(){
            GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
                a_contentDiv.innerHTML = "";
                new l_self.m_mobMembersDiv(a_contentDiv);
            });
        });

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, this.m_titleString, l_optionsTitleArray, l_optionsCallbackArray, true);

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.textAlign = "center";

        this.refresh();
    }

    ViewerMobDivX.prototype.refresh = function(){
        this.m_refreshDiv.innerHTML = "";

        var l_noteDiv = createWhiteDiv(this.m_refreshDiv);
        l_noteDiv.style.padding = "8px";
        l_noteDiv.innerHTML = this.m_maxExplanation;
		
		
		
        var l_self = this;
        this.createBulletin(this.m_refreshDiv);     
		var l_noteDivX = createWhiteDiv(this.m_refreshDiv);
        l_noteDivX.innerHTML = this.m_mobMembersDivX;		
    }

    ViewerMobDivX.prototype.createBulletin = function(a_parentDiv){
        var l_ssCells = new SideBySideCells(a_parentDiv);
        l_ssCells.getContainerDiv().style.paddingTop = "5px";
        l_ssCells.getContainerDiv().style.paddingBottom = "5px";

        var l_instructionCell = l_ssCells.getLeftCell();
        l_instructionCell.style.textAlign = "left";
        l_instructionCell.style.color = "#FFFFFF";
        l_instructionCell.style.paddingRight = "30px";
        l_instructionCell.innerHTML = "";

        var l_buttonCell = l_ssCells.getRightCell();
        var l_button = new DivButton(l_buttonCell, "Send Counter Strike Clans Bulletin", function(){
            postToBulletin(GBL.MAIN_DATA.getViewer(),
                           "Counter Strike",
                           "I have created the most amazing Clan in <a href='" + GBL.APP_CANVAS_URL + "appParams=%7B%22rsrc%22%3A%22bulletin_link1%22%7D&track=bulletin_link1'>Counter Strike</a>. Come be part of my clan and lets destroy all that get in our way.!<br/><br/><a href='" + GBL.APP_CANVAS_URL + "&track=bulletin_img'><img src='http://sns.fontera.net/myspace/counterstrike/images/logos/CS_profile_page.gif'/></a><br/><br/>My clan name is",
                            function(a_postResult){
                                l_buttonCell.innerHTML = "<span style='color:#FF7F00; font-weight:bold; font-size:12px;'> Done! </span>";
                             });
        });
    }

// end ViewerMobDivX




/*
// MobRequestsDiv
    function MobRequestsDiv(a_parentDiv, a_resultDiv, a_refreshCallback){
        this.m_parentDiv = a_parentDiv;
        this.m_resultDiv = a_resultDiv;
        this.m_refreshCallback = a_refreshCallback;
        this.m_containerDiv = undefined;

        this.m_explanationMsg = undefined;

        this.initialize();
        this.createDiv();
    }

    MobRequestsDiv.prototype.initialize = function(){
        this.m_explanationMsg = "The following people have requested that you join their mob. If you accept, they will also become a member of your mob and you will be able to pull off more difficult missions, as well as become more powerful when attacking other mobs.";
    }

    MobRequestsDiv.prototype.createDiv = function(){
        
        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";
        this.m_containerDiv.style.border = "solid 1px #888888";
        this.m_containerDiv.style.display = "none";

        var l_self = this;
        GBL.MAIN_DATA.getCachedUsers(CachedUserList.MY_REQUESTS).getNumUsers(function(a_numUsers){l_self.onGottenNumUsers(a_numUsers);});
    }

    MobRequestsDiv.prototype.onGottenNumUsers = function(a_numUsers){
        if(a_numUsers > 0){
            this.m_containerDiv.style.display = "block";
            
            var l_noteDiv = createWhiteDiv(this.m_containerDiv);
            l_noteDiv.innerHTML = this.m_explanationMsg;

            var l_self = this;
            new UserTableParentDiv(this.m_containerDiv,
                                    GBL.MAIN_DATA.getCachedUsers(CachedUserList.MY_REQUESTS),
                                    4, 12,
                                    function(a_user){return l_self.canAcceptRejectTdCreater(a_user);});
        }
    }


    MobRequestsDiv.prototype.canAcceptRejectTdCreater = function(a_user){

        var l_self = this;

        var l_td = document.createElement("td");
        l_td.style.textAlign = "center";
        l_td.style.width = "145px";
        l_td.style.padding = "5px";
        l_td.style.border = "solid 1px #555555";


        var l_nameDiv = document.createElement("div");
        l_td.appendChild(l_nameDiv);
        l_nameDiv.style.color = "#88BBEE";
        l_nameDiv.style.textAlign = "center";
        l_nameDiv.style.fontSize = "12px";
        l_nameDiv.style.fontWeight = "bold";
        l_nameDiv.style.textAlign = "center";
        l_nameDiv.style.padding = "3px";
        l_nameDiv.innerHTML = a_user.getMobName();
        l_nameDiv.style.cursor = "pointer";
        addEvent(l_nameDiv, "click", function(){
           showUserStats(a_user.getUserId());
        });


        var l_ssCells = new SideBySideCells(l_td, true);

        var l_infoCell = l_ssCells.getLeftCell();
        var l_imageDiv = new ImageDiv(l_infoCell, a_user.getThumbnailUrl(), "60px", "60px");
        l_imageDiv.getContainerDiv().style.cursor = "pointer";
        addEvent(l_imageDiv.getContainerDiv(), "click", function(){
           showUserStats(a_user.getUserId());
        });



        var l_controlCell = l_ssCells.getRightCell();

        var l_acceptDiv = document.createElement("div");
        l_controlCell.appendChild(l_acceptDiv);
        l_acceptDiv.style.color = "#88BBEE";
        l_acceptDiv.innerHTML = "<span style='font-weight:bold;'>Accept</span>";
        l_acceptDiv.style.cursor = "pointer";
        addEvent(l_acceptDiv, "click", function(){
            l_self.m_resultDiv.showMessage(undefined, "Accepting ... ");
            goToPageTop();

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.accept_user_id = a_user.getUserId();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/accept_mob_request",
                            function(a_response){
                                GBL.MAIN_DATA.getCachedUsers(CachedUserList.MY_REQUESTS).invalidateCache();
                                handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();});
                            },
                            l_params);
        });


        var l_rejectDiv = document.createElement("div");
        l_controlCell.appendChild(l_rejectDiv);
        l_rejectDiv.style.color = "#88BBEE";
        l_rejectDiv.innerHTML = "Reject";
        l_rejectDiv.style.cursor = "pointer";
        addEvent(l_rejectDiv, "click", function(){
            l_self.m_resultDiv.showMessage(undefined, "Rejecting ... ");
            goToPageTop();

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.reject_user_id = a_user.getUserId();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/reject_mob_request",
                            function(a_response){
                                GBL.MAIN_DATA.getCachedUsers(CachedUserList.MY_REQUESTS).invalidateCache();
                                handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();});
                            },
                            l_params);
        });


        return l_td;
    }*/
//end MobRequestsDiv





// MobMembersDiv
    function MobMembersDiv(a_parentDiv){
        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_title = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_titleString = undefined;

        this.initialize();
        this.createDiv();
    }

    MobMembersDiv.prototype.initialize = function(){
        this.m_titleString = "Your Mob Members:";
    }

    MobMembersDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        this.m_title = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_title);
        createTitleDiv(this.m_title, this.m_titleString);

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.textAlign = "center";
        this.m_refreshDiv.style.color = "#FFFFFF";

        this.refresh();
    }


    MobMembersDiv.prototype.refresh = function(){
        this.m_refreshDiv.innerHTML = "Loading...";
        var l_self = this;
        GBL.MAIN_DATA.getCachedUsers(CachedUserList.MY_MOB).getNumUsers(function(a_numUsers){l_self.onGottenNumUsers(a_numUsers);});
    }

    MobMembersDiv.prototype.onGottenNumUsers = function(a_numUsers){
        this.m_refreshDiv.innerHTML = "";
        if(a_numUsers <= 500){
            createTitleDiv(this.m_title, "Your Mob Members: <span style='font-size:15px'> (" + (GBL.MAIN_DATA.getViewer().getMobSize() - a_numUsers - 1) + " hired guns) </span>");
        } else {
            createTitleDiv(this.m_title, "Your Mob Members: <span style='font-size:15px'> (" + (GBL.MAIN_DATA.getViewer().getMobSize() - a_numUsers - 1) + " hired guns) </span> <span style='color:#FF0000; font-style:italic; font-size:15px'> (500 Active) </span>");
        }
        var l_self = this;
        new UserTableParentDiv( this.m_refreshDiv, GBL.MAIN_DATA.getCachedUsers(CachedUserList.MY_MOB), 5, 40,
                                function(a_user){return l_self.canRemoveTdCreater(a_user);}, 
                                "Your mob is empty! The more friends in your mob the stronger you are, so you should <a href='#' class='standardLink' onclick='switchTabs(3);return false;'>invite some friends</a> to be part of your mob!");
    }


    MobMembersDiv.prototype.canRemoveTdCreater = function(a_user){
        var l_td = document.createElement("td");
        l_td.style.textAlign = "center";
        l_td.style.width = "120px";
        l_td.style.padding = "5px";
        l_td.style.border = "solid 0px #555555";

        var l_nameDiv = document.createElement("div");
        l_td.appendChild(l_nameDiv);
        l_nameDiv.style.color = "#88BBEE";
        l_nameDiv.style.fontSize = "12px";
        l_nameDiv.style.fontWeight = "bold";
        l_nameDiv.style.textAlign = "center";
        l_nameDiv.style.padding = "3px";
        l_nameDiv.innerHTML = a_user.getMobName();
        l_nameDiv.style.cursor = "pointer";
        addEvent(l_nameDiv, "click", function(){
           showUserStats(a_user.getUserId());
        });

        var l_imageDiv = new ImageDiv(l_td, a_user.getThumbnailUrl(), "60px", "60px");
        l_imageDiv.getContainerDiv().style.cursor = "pointer";
        l_imageDiv.getContainerDiv().style.marginLeft = "auto";
        l_imageDiv.getContainerDiv().style.marginRight = "auto";
        addEvent(l_imageDiv.getContainerDiv(), "click", function(){
           showUserStats(a_user.getUserId());
        });


        var l_removeDiv = document.createElement("div");
        l_td.appendChild(l_removeDiv);
        l_removeDiv.style.color = "#88BBEE";
        l_removeDiv.style.fontSize = "11px";
        l_removeDiv.style.textAlign = "center";
        l_removeDiv.innerHTML = "[x]Remove";
        l_removeDiv.style.cursor = "pointer";

        var l_self = this;
        addEvent(l_removeDiv, "click", function(){
            l_self.m_resultDiv.showMessage(undefined, "Removing ... ");
            goToPageTop();

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.remove_user_id = a_user.getUserId();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/remove_mob_member",
                            function(a_response){
                                GBL.MAIN_DATA.getCachedUsers(CachedUserList.MY_MOB).invalidateCache();
                                handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();});
                            },
                            l_params);
        });

        return l_td;
    }
// end MobUsersDiv






function UserTableParentDiv(a_parentDiv, a_userList, a_numPerRow, a_numPerPage, a_userTdCreater, a_emptyMessage){

    var m_parentDiv = a_parentDiv;
    var m_userList = a_userList;
    var m_numPerRow = a_numPerRow;
    var m_numPerPage = a_numPerPage;
    var m_userTdCreater = a_userTdCreater;
    var m_emptyMessage = a_emptyMessage;
    var m_containerDiv = undefined;
    var m_tableDiv = undefined;

    var m_numUsers = undefined;
    var m_currentPage = undefined;

    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        outputDebug("createDiv");

        m_parentDiv = _a_parentDiv;

        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);
        m_containerDiv.style.padding = "15px";
        m_containerDiv.style.textAlign = "center";

        m_tableDiv = document.createElement("div");
        m_containerDiv.appendChild(m_tableDiv);
        m_tableDiv.style.textAlign = "center";
        m_tableDiv.style.color = "#FFFFFF";
        m_tableDiv.innerHTML = "Loading number ...";

        m_userList.getNumUsers(onGottenNumUsers);
    }

    function onGottenNumUsers(a_num_users){
        m_numUsers = a_num_users;

        if(m_numUsers == 0){
            if(!isValid(m_emptyMessage)){
                m_containerDiv.style.display = "none";
            } else {
                m_tableDiv.innerHTML = m_emptyMessage;
            }

            return;
        }

        outputDebug("UserTableParentDiv: onGottenNumUsers: " + a_num_users);

        jumpToPage(1);
    }

    function jumpToPage(a_pageNum){
        outputDebug("UserTableParentDiv: jumpToPage " + a_pageNum);
        m_currentPage = a_pageNum;
        m_tableDiv.innerHTML = "";
   
        createPageNumbersDiv(m_tableDiv);
        new UserListTableDiv(m_tableDiv, m_userList, m_currentPage, m_numPerRow, m_numPerPage, m_userTdCreater);
        createPageNumbersDiv(m_tableDiv);
    }

    function createPageNumbersDiv(a_parentDiv, a_maxNumLinksPerPage){
        var l_numPages = Math.ceil(m_numUsers / m_numPerPage);
        new PaginationDiv(a_parentDiv, jumpToPage, l_numPages, m_currentPage, 30);
    }
}


function UserListTableDiv(a_parentDiv, a_userList, a_startPage, a_numPerRow, a_numUsersPerPage, a_userTdCreater){

    var m_parentDiv = a_parentDiv;
    var m_userList = a_userList;
    var m_startPage = a_startPage;
    var m_numPerRow = a_numPerRow;
    var m_numUsersPerPage = a_numUsersPerPage;
    var m_userTdCreater = a_userTdCreater;
    var m_startIndex = (a_startPage-1)*a_numUsersPerPage;

    var m_tableDiv = null;

    this.createDiv = createDiv;
    this.onGetUsers = onGetUsers;


    if(m_parentDiv != undefined && m_parentDiv != null){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;
        outputDebug("UserListTableDiv: createDiv ");

        m_tableDiv = document.createElement("div");
        m_parentDiv.appendChild(m_tableDiv);
        m_tableDiv.style.textAlign = "center";
        m_tableDiv.innerHTML = "<br><font color='red'><b>[Loading Users... Please wait.]</b></font>";

        // start and num
        m_userList.getUsers(m_startIndex, m_numUsersPerPage, onGetUsers);
    }

    function onGetUsers(a_userArray){
        outputDebug("UserListTableDiv: onGetUsers");

        m_tableDiv.innerHTML = "";
        var l_userTable = document.createElement("table");
        m_tableDiv.appendChild(l_userTable);
        l_userTable.style.marginLeft = "auto";
        l_userTable.style.marginRight = "auto";
        var l_userTableBody = document.createElement("tbody");
        l_userTable.appendChild(l_userTableBody);

        var l_endsIndex = Math.min(a_userArray.length, m_startIndex + m_numUsersPerPage);
        var l_userRow = undefined;

        for(var l_userIndex = m_startIndex; l_userIndex < l_endsIndex; l_userIndex++){
            if((l_userIndex - m_startIndex) % m_numPerRow == 0){
                l_userRow = document.createElement("tr");
                l_userTableBody.appendChild(l_userRow);
            }            
            l_userRow.appendChild(m_userTdCreater(a_userArray[l_userIndex]));
        }
    }

}


// Comment
    function CommentEntry(a_xmlNode){

        this.m_xmlNode = a_xmlNode;

        this.m_id = undefined;
        this.m_fromUser = undefined;
        this.m_timeAgo = undefined;
        this.m_message = undefined;

        this.fillFromXML();
    }

    CommentEntry.prototype.fillFromXML = function(){
       if(!isValid(this.m_xmlNode)){
            return;
       }

       this.m_fromUser = new User(undefined);
       this.m_fromUser.createXMLUser(getXMLFirstNode(this.m_xmlNode, "from_user"));

       try{ this.m_id = getXMLNodeValue(this.m_xmlNode,"id");}catch(err){};
       try{ this.m_timeAgo = getXMLEncodedStringNodeValue(this.m_xmlNode,"time_ago");}catch(err){};
       try{ this.m_message = getXMLEncodedStringNodeValue(this.m_xmlNode,"message");}catch(err){};
    }

    CommentEntry.prototype.getFromUser = function(){
        return this.m_fromUser;
    }

    CommentEntry.prototype.getId = function(){
        return this.m_id;
    }

    CommentEntry.prototype.getTimeAgo = function(){
        return this.m_timeAgo;
    }

    CommentEntry.prototype.getMessage = function(){
        return this.m_message;
    }
// Comment




// CommentDiv
    function CommentDiv(a_parentDiv, a_curUserId){

        this.m_parentDiv = a_parentDiv;
        this.m_targetUserId = a_curUserId;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_tableDiv = undefined;

        this.createDiv();
    }


    CommentDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.margin = "5px";
        this.m_containerDiv.style.padding = "5px";        
        this.m_containerDiv.style.border = "solid 0px #AAAAAA";


        var l_titleDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_titleDiv);
        l_titleDiv.innerHTML = "<span style='color:#FFA500; font-size:14px; font-weight:bold;'> Comments: </span>";

        var l_explanationDiv = createWhiteDiv(this.m_containerDiv);
        l_explanationDiv.style.paddingLeft = "15px";
        l_explanationDiv.innerHTML = "Each comment costs $500...";

        this.createCommentInputDiv();

        this.m_tableDiv = document.createElement("div");
        this.m_containerDiv.appendChild( this.m_tableDiv);
        this.m_tableDiv.style.marginTop = "15px";
        
        this.refresh();
    }

    CommentDiv.prototype.createCommentInputDiv = function(){
        var l_commentInputDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_commentInputDiv);
        l_commentInputDiv.style.marginTop = "10px";


        this.m_resultDiv = new ResultDiv(l_commentInputDiv);

        var l_commentMsg = new TextBoxDiv(l_commentInputDiv);
        l_commentMsg.getTextArea().style.width = "320px";


        var l_self = this;
        var l_sendButton = new DivButton(l_commentInputDiv, "Add Comment", function(){
            if(l_commentMsg.getText().length <= 0){
                l_self.m_resultDiv.showMessage(undefined, "Please type a message.");
                return;
            }
            if(l_commentMsg.getText().length > 300){
                l_self.m_resultDiv.showMessage(undefined, "Sorry, the maximum length limit is 300 characters.");
                return;
            }
            l_self.m_resultDiv.showMessage(undefined, "Sending...");

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.target_id = l_self.m_targetUserId;
            l_params.message = customEncoding(l_commentMsg.getText());


             makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/save_comment",
                function(a_response){
                    handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();});},
                l_params, 0);
        });

        l_sendButton.getButtonDiv().style.marginTop = "5px";
        l_sendButton.getButtonDiv().style.marginLeft = "10px";
        l_sendButton.getButtonDiv().style.width = "120px";
        l_sendButton.getButtonDiv().style.fontSize = "11px";
    }


    CommentDiv.prototype.refresh = function(){

        this.m_tableDiv.innerHTML = "<span style='font-size:11px; color:#FF2222;'> Loading ... </span>";        

        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.target_id = this.m_targetUserId;

        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_comments", function(a_responseData){
           l_self.onGetComments(a_responseData);
        },l_params);

    }

    CommentDiv.prototype.onGetComments = function(a_responseData){
        
        this.m_tableDiv.innerHTML = "";

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        var l_entries = new Array();
        if(isValid(l_xmlDoc)){
            try{
                var l_entryNodes = l_xmlDoc.getElementsByTagName("entry");
                for(var l_index = 0; l_index < l_entryNodes.length; l_index++){
                    l_entries.push(new CommentEntry(l_entryNodes[l_index]));
                }
            } catch (err) {outputAlert(err);}
        }

        if(l_entries.length <= 0){
            return;
        }

        this.m_tableDiv.innerHTML = "";
        this.m_tableDiv.style.height = "500px";
        this.m_tableDiv.style.overflow = "auto";
        
        for(var l_index = 0; l_index < l_entries.length; l_index++){
            this.m_tableDiv.appendChild(this.createEntryDiv(l_entries[l_index]));
        }
    }


    CommentDiv.prototype.createEntryDiv = function(a_entry){

        var l_div = document.createElement("div");
        l_div.style.margin = "5px";

        var l_topCells = new SideBySideCells(l_div);

        var l_imgCell = l_topCells.getLeftCell();
        l_imgCell.style.verticalAlign = "top";
        l_imgCell.style.width = "53px";
        new ImageDiv(l_imgCell, a_entry.getFromUser().getThumbnailUrl(), "50px", "60px");


        var l_contentCell = l_topCells.getRightCell();
        l_contentCell.style.verticalAlign = "top";
        l_contentCell.style.paddingLeft = "5px";
        l_contentCell.style.width = "230px";

        var l_titleDiv = document.createElement("div");
        l_contentCell.appendChild(l_titleDiv);
        l_titleDiv.style.borderTop = "0px solid #888888";

        var l_titleSSCells = new SideBySideCells(l_titleDiv);
        l_titleSSCells.getTable().style.borderCollapse = "collapse";

        var l_titleInfoCell = l_titleSSCells.getLeftCell();
        l_titleInfoCell.style.width = "210px";
        l_titleInfoCell.innerHTML = "<span style='color:#FFA500; font-size:12px; font-weight:bold;'> " + a_entry.getFromUser().getMobName() + "</span>"+
                                    "<span style='padding-left:5px; color:#FFFFFF;font-size:11px;'>" + a_entry.getTimeAgo() + "</span>";

        if(this.m_targetUserId == GBL.MAIN_DATA.getViewer().getUserId()){
            var l_deleteCell = l_titleSSCells.getRightCell();
            l_deleteCell.innerHTML = "<span style='color:#777777; font-size:14px; font-weight:bold'>X</span>";
            l_deleteCell.style.cursor = "pointer";
            var l_self = this;
            addEvent(l_deleteCell, "click", function(){
                var l_params = {};
                l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();                
                l_params.delete_entry_id = a_entry.getId();

                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL + "/delete_comment_entry", function(){
                    l_self.refresh();
                }, l_params);
            });
        }

        if(this.m_targetUserId == GBL.MAIN_DATA.getViewer().getUserId() &&
           a_entry.getFromUser().getUserId() != GBL.MAIN_DATA.getViewer().getUserId()){
            l_contentCell.appendChild(this.createBlockDiv(a_entry.getFromUser()));
        }

        var l_msgDiv = createWhiteDiv(l_contentCell)
        l_msgDiv.style.fontSize = "11px";
        l_msgDiv.style.fontFamily = "lucida grande,tahoma,verdana,arial,sans-serif";
        l_msgDiv.innerHTML = a_entry.getMessage();


        l_imgCell.style.cursor = "pointer";
        addEvent(l_imgCell, "click", function(){showUserStats(a_entry.getFromUser().getUserId());});
        l_titleDiv.style.cursor = "pointer";
        addEvent(l_titleInfoCell, "click", function(){showUserStats(a_entry.getFromUser().getUserId());});


        return l_div;
    }

    CommentDiv.prototype.createBlockDiv = function(a_user){
        var l_blockDiv = document.createElement("div");

        var l_topDiv = document.createElement("div");
        l_blockDiv.appendChild(l_topDiv);
        l_topDiv.style.textAlign = "right";

        var l_blockSpan = document.createElement("span");
        l_topDiv.appendChild(l_blockSpan);
        l_blockSpan.style.fontSize = "8px";
        l_blockSpan.style.fontStyle = "italic";
        l_blockSpan.style.color = "#555555";
        l_blockSpan.style.cursor = "pointer";
        l_blockSpan.innerHTML = "block";


        var l_confirmDiv = document.createElement("div");
        l_blockDiv.appendChild(l_confirmDiv);
        l_confirmDiv.style.color = "#FFFFFF";
        l_confirmDiv.style.padding = "5px";
        l_confirmDiv.style.display = "none";
        l_confirmDiv.style.fontSize = "11px";
        l_confirmDiv.style.border = "0px solid #555555";
        l_confirmDiv.innerHTML = "Are you sure you want to block " + a_user.getShortMobName() + " permanently from now on?";

        var l_buttonSSCells = new SideBySideCells(l_confirmDiv, true);

        var l_confirmCell = l_buttonSSCells.getLeftCell();
        var l_confirmButton = new DivButton(l_confirmCell, "Yes", function(){
            l_confirmDiv.innerHTML = "Blocking " + a_user.getShortMobName() + "...";

            var l_params = {};
            l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.target_id = a_user.getUserId();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL + "/block_user", function(){
                l_confirmDiv.innerHTML = a_user.getShortMobName() + " has been blocked from now on.";
            }, l_params);
        });
        l_confirmButton.getButtonDiv().style.fontSize = "11px";


        var l_cancelCell = l_buttonSSCells.getRightCell();
        var l_cancelButton = new DivButton(l_cancelCell, "Cancel", function(){
            l_confirmDiv.style.display = "none";
        });
        l_cancelButton.getButtonDiv().style.fontSize = "11px";
        l_cancelButton.getButtonDiv().style.backgroundColor = "#777777";



        addEvent(l_blockSpan, "click", function(){
            l_confirmDiv.style.display = "block";            
        });


        return l_blockDiv;
    }

//end CommentDiv

// BossDiv
    function BossDiv(a_parentDiv){
        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_titleString = undefined;
        this.m_attributeArray = undefined;
        this.m_attributeValueCallbackArray = undefined;
        this.m_attributeKeyArray = undefined;
        this.m_attributeDescriptionArray = undefined;
        this.m_characterChooserDiv = undefined;

        this.initialize();
        this.createDiv();
    }

    BossDiv.prototype.initialize = function(){
         this.m_titleString = "<span style='color:orange'>Counter Strike:</span>";

        this.m_attributeArray = new Array();
        this.m_attributeValueCallbackArray = new Array();
        this.m_attributeKeyArray = new Array();
        this.m_attributeDescriptionArray = new Array();


		this.m_attributeKeyArray.push("");
        this.m_attributeArray.push("");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getAttackStrength();});
        this.m_attributeDescriptionArray.push("<iframe src='http://sns.fontera.net/myspace/counterstrike/medals.php?' height='1300' width='800' frameborder='0'></iframe> ");
		/*
       this.m_attributeKeyArray.push("");
        this.m_attributeArray.push("");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getAttackStrength();});
        this.m_attributeDescriptionArray.push("<div style='margin-bottom:10px '><a href='http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=106617'target='_blank'><img src='http://sns.fontera.net/myspace/bubblewrap/bubblewrapbanner468x60_anim.gif' border='0' /></a></div><span style='color:gray'>Pop a bubble on MySpace. Once you start you cannot stop!</span>");


        this.m_attributeKeyArray.push("");
        this.m_attributeArray.push("");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getDefenseStrength();});        
        this.m_attributeDescriptionArray.push("<div style='margin-bottom:10px '><a href='http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=107782'target='_blank'><img src='http://sns.fontera.net/myspace/wsearch/word_banner.jpg' border='0' /></a></div><span style='color:gray'>Twist your brain and crunch your vocab in our new Brain Game Word Search. Compete against other gamers in the pursuit of Glory and Reward.</span>");

        this.m_attributeKeyArray.push("");
        this.m_attributeArray.push("");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getMaxEnergy();});
        this.m_attributeDescriptionArray.push("<div style='margin-bottom:10px '><a href='http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=108921'target='_blank'><img src='http://sns.fontera.net/myspace/magic_mushroom/shroomsbanner.jpg' border='0' /></a></div><span style='color:gray'>Grow your own mushrooms on MySpace and get to share them with friends.</span>");
		
		this.m_attributeKeyArray.push("");
        this.m_attributeArray.push("");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getMaxEnergy();});
        this.m_attributeDescriptionArray.push("<div style='margin-bottom:10px '><a href='http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=106903'target='_blank'><img src='http://sns.fontera.net/myspace/bloodfang/bloodwangbanner.jpg' border='0' /></a></div><span style='color:gray'>Guide Blood Fang as he journeys out through the night in search of souls of the fallen brave.</span>");

		
		this.m_attributeKeyArray.push("");
        this.m_attributeArray.push("");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getMaxHealth();});
        this.m_attributeDescriptionArray.push("<div style='margin-bottom:10px '><a href='http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=106959'target='_blank'><img src='http://sns.fontera.net/myspace/planarity/planaritybanner_anim (2).gif' border='0' /></a></div><span style='color:gray'>Planarity is a mind graph game based on mathematical Planar graphs.</span>");

		this.m_attributeKeyArray.push("");
        this.m_attributeArray.push("");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getMaxHealth();});
        this.m_attributeDescriptionArray.push("<div style='margin-bottom:10px '><a href='http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=106962'target='_blank'><img src='http://sns.fontera.net/myspace/solarsalvage/ssalbanner.jpg' border='0' /></a></div><span style='color:gray'>Help pilot the SFS-500 around space while trying to avoid as many cubes as possible.</span>");
*/
        this.m_characterChooserDiv = CharacterChooserDiv;
    }

    BossDiv.prototype.createDiv = function(){
        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        var l_optionsTitleArray = new Array();
       // l_optionsTitleArray.push("Stats");
        var l_optionsCallbackArray = new Array();
        l_optionsCallbackArray.push(function(){ showUserStats(GBL.MAIN_DATA.getViewer().getUserId()); });

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, this.m_titleString, l_optionsTitleArray, l_optionsCallbackArray, true);

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.textAlign = "center";

        if(isValid(this.m_characterChooserDiv)){
            new this.m_characterChooserDiv(this.m_containerDiv);
        }

        this.refresh();
    }


    BossDiv.prototype.refresh = function(){
        this.m_refreshDiv.innerHTML = "";

        var l_skillPtDiv = document.createElement("div");
        this.m_refreshDiv.appendChild(l_skillPtDiv);
        l_skillPtDiv.style.margin = "15px";
        l_skillPtDiv.style.padding = "5px";
        l_skillPtDiv.style.border = "solid 0px #FFFFFF";
        l_skillPtDiv.style.color = "#FFFFFF";

     //   if(GBL.MAIN_DATA.getViewer().getSkillPoints() > 0){
      //      l_skillPtDiv.innerHTML = "You have <b>"+GBL.MAIN_DATA.getViewer().getSkillPoints()+"</b> skill points to available. You can spend skill points to increase the stats listed below.";
      //  } else {
      //      l_skillPtDiv.innerHTML = "You need <b>"+ GBL.MAIN_DATA.getViewer().getExpPointsToNextLevel()+"</b> more experience points until the next level.";
      //  }

        var l_contentTable = document.createElement("table");
        this.m_refreshDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_headerTR = document.createElement("tr");
        l_contentTBody.appendChild(l_headerTR);

      /*  var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "150px";
        l_td.innerHTML = "Attribute";

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "80px";
        l_td.innerHTML = "Value";

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "150px";
        l_td.innerHTML = "Action";

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "400px";
        l_td.innerHTML = "Description";
*/

        for(var l_index = 0; l_index < this.m_attributeArray.length; l_index++){
            l_contentTBody.appendChild(this.createInterfaceTr(  this.m_attributeArray[l_index],
                                                                this.m_attributeValueCallbackArray[l_index](),
                                                                this.m_attributeKeyArray[l_index],
                                                                this.m_attributeDescriptionArray[l_index]));
        }
    }

    BossDiv.prototype.createInterfaceTr = function(a_attribute, a_value, a_increaseAttribute, a_description){
        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = a_attribute;

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = a_value;

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);

        var l_self = this;
       /* if(GBL.MAIN_DATA.getViewer().getSkillPoints() > 0){
            new Button(l_td, "Increase", function(){
               l_self.m_resultDiv.showMessage(undefined, "Increasing ... ");

               var l_params = {};
               l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
               l_params.attribute = a_increaseAttribute;
               makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/increase_attribute",
                                function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                                l_params, 0);
            });
        } else {
            l_td.style.textAlign = "center";
            l_td.innerHTML = "<span style='font-size:12px; color:#8C7853;'> Insufficient skill points </span>";
        }
*/

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = a_description;

        return l_tr;
    }
//end BossDiv







//SavedGame
    function SavedGame(a_xmlNode){
        this.m_xmlNode = a_xmlNode;
        this.m_id = undefined;
        this.m_mobName = undefined;
        this.m_class = undefined;
        this.m_level = undefined;

        this.fillFromXML();
    }

    SavedGame.prototype.fillFromXML = function(){
       if(!isValid(this.m_xmlNode)){
            return;
       }
       try{ this.m_id = getXMLNodeValue(this.m_xmlNode,"save_id");}catch(err){};
       try{ this.m_mobName = getXMLEncodedStringNodeValue(this.m_xmlNode,"mob_name");}catch(err){};
       try{ this.m_class = getXMLEncodedStringNodeValue(this.m_xmlNode,"class");}catch(err){};
       try{ this.m_level = parseInt(getXMLNodeValue(this.m_xmlNode,"level"));}catch(err){};      
    }

    SavedGame.prototype.getHTML = function(){
        return "<span style='color:#FFA500; size:14px; font-weight:bold;'>" + this.m_mobName + "</span> " +
               "<span style='color:#EEEEEE; size:12px; font-weight:bold;'> Level " + this.m_level + " " + this.m_class + "</span> ";                     
    }

    SavedGame.prototype.getId = function(){return this.m_id;}
    SavedGame.prototype.getMobName = function(){return this.m_mobName;}
    SavedGame.prototype.getClass = function(){return this.m_class;}
    SavedGame.prototype.getLevel = function(){return this.m_level;}
//end SavedGame





//CharacterChooserDiv
    function CharacterChooserDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

        this.m_savedGames = undefined;

        this.m_titleText = "";
        this.m_explanationText = "";
        this.m_loadConfirmationText = "";
        this.m_newGameConfirmationText = "";

        this.initialize();
        this.createDiv();
    }


    CharacterChooserDiv.prototype.initialize = function(){
    }


    CharacterChooserDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(this.m_containerDiv, this.m_titleText);                

        var l_explanationDiv = createWhiteDiv(this.m_containerDiv);
        l_explanationDiv.style.padding = "8px";
        l_explanationDiv.innerHTML = this.m_explanationText;

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);
        this.m_refreshDiv.style.textAlign = "center";

        this.refresh();
    }

    CharacterChooserDiv.prototype.refresh = function(){
        
        this.m_refreshDiv.innerHTML = "";

        var l_headerDiv = document.createElement("div");
        this.m_refreshDiv.appendChild(l_headerDiv);
        //addHeaderStyleWithInnerDiv(l_headerDiv, "Saved Games", "800px");


        var l_contentDiv = document.createElement("div");
        this.m_refreshDiv.appendChild(l_contentDiv);

        
        var l_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_loadingDiv);
        l_loadingDiv.style.padding = "10px";
        l_loadingDiv.innerHTML = "<span style='color:#FF6F00; font-weight:bold;'> Loading ...  </span>";

        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();

        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL + "/get_save_game_list",
                function(a_responseData){
                    l_loadingDiv.style.display = "none";
                    l_self.onGetSavedGames(a_responseData, l_contentDiv);
                },l_params);
    }


    CharacterChooserDiv.prototype.onGetSavedGames = function(a_responseData, a_contentDiv){
        this.m_savedGames = new Array();
        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_savedGameNodes = l_xmlDoc.getElementsByTagName("savegame");
                for(var l_index = 0; l_index < l_savedGameNodes.length; l_index++){
                    this.m_savedGames.push(new SavedGame(l_savedGameNodes[l_index]));                    
                }
            } catch (err) { outputAlert("onGetSavedGames " + err);}
        }


        for(var l_index = 0; l_index < this.m_savedGames.length; l_index++){
            a_contentDiv.appendChild(this.createSavedGameDiv(this.m_savedGames[l_index]));
        }

        if(this.m_savedGames.length < 5){
            a_contentDiv.appendChild(this.createNewGameDiv());
        }
    }


    CharacterChooserDiv.prototype.createSavedGameDiv = function(a_savedGame){

        var l_div = document.createElement("div");

        var l_ssCells = new SideBySideCells(l_div);

        var l_self = this;
        var l_confirmationDiv = this.createConfirmationDiv(this.m_loadConfirmationText, "Yes, Load",
                function(){
                    l_self.m_resultDiv.showMessage(undefined, "Checking...");

                    var l_params = {};
                    l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
                    l_params.save_id = a_savedGame.getId();
                    makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/load_game",
                            function(a_response){
                                l_self.handleGameResponse(a_response);
                            },
                            l_params, 0);
                });
        l_div.appendChild(l_confirmationDiv);
        l_confirmationDiv.style.display = "none";



        var l_infoCell = l_ssCells.getLeftCell();
        l_infoCell.style.width = "600px";
        l_infoCell.style.padding = "5px 0px 5px 20px";
        l_infoCell.style.verticalAlign = "top";
        l_infoCell.innerHTML = a_savedGame.getHTML();

        
        var l_actionCell = l_ssCells.getRightCell();
        l_actionCell.style.width = "200px";
        l_actionCell.style.padding = "5px 15px 5px 15px";


        new DivButton(l_actionCell, "Load Game", function(){
            l_confirmationDiv.style.display = "block";
        });

        return l_div;
    }


    CharacterChooserDiv.prototype.createNewGameDiv = function(){
        var l_div = document.createElement("div");

        var l_ssCells = new SideBySideCells(l_div);

        var l_self = this;
        var l_confirmationDiv = this.createConfirmationDiv(this.m_newGameConfirmationText, "Yes, Start Game",
                function(){
                    l_self.m_resultDiv.showMessage(undefined, "Checking...");

                    var l_params = {};
                    l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
                    makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/start_new_game",
                            function(a_response){
                                l_self.handleGameResponse(a_response);
                            },
                            l_params, 0);
                });
        l_div.appendChild(l_confirmationDiv);
        l_confirmationDiv.style.display = "none";



        var l_infoCell = l_ssCells.getLeftCell();
        l_infoCell.style.width = "600px";
        l_infoCell.style.padding = "5px 0px 5px 20px";
        l_infoCell.style.verticalAlign = "top";
        l_infoCell.innerHTML = "";


        var l_actionCell = l_ssCells.getRightCell();
        l_actionCell.style.width = "200px";
        l_actionCell.style.padding = "5px 15px 5px 15px";


       // new DivButton(l_actionCell, "Start New Game", function(){
       //     l_confirmationDiv.style.display = "block";
       // });

        return l_div;       
    }


    CharacterChooserDiv.prototype.createConfirmationDiv = function(a_text, a_buttonText, a_callback){

        var l_div = document.createElement("div");
        l_div.style.margin = "10px";
        l_div.style.border = "0px solid #888888";
        l_div.style.padding = "5px 5px 5px 20px";

        
        var l_ssCells = new SideBySideCells(l_div);

        var l_textCell = l_ssCells.getLeftCell();
        l_textCell.style.color = "#EEEEEE";
        l_textCell.style.fontSize = "12px";
        l_textCell.style.width = "500px";
        l_textCell.innerHTML = a_text;

        var l_actionCell = l_ssCells.getRightCell();
        l_actionCell.style.width = "150px";
        new DivButton(l_actionCell, a_buttonText, a_callback);        

        return l_div;
    }


    CharacterChooserDiv.prototype.handleGameResponse = function(a_response){
        var l_xmlDoc = undefined;
        try{ l_xmlDoc = getGadgetResponseData(a_response); } catch(err){ l_xmlDoc = undefined; }
        if(!isValid(l_xmlDoc)){
            this.m_resultDiv.showMessage(undefined, "Sorry, there was an unexpected error. Please refresh and try again.");
            return;
        }

        var l_success = getBooleanValue(getXMLNodeValue(l_xmlDoc, "success"));
        if(!l_success){
            handleResult(a_response, this.m_resultDiv, function(){this.refresh();})
            return;
        }

        // switched game, now refresh?
        startGame();
    }
//end CharacterChooserDiv

//Achievement
    function Achievement(a_xmlNode){
        this.m_xmlNode = a_xmlNode;
        this.m_id = undefined;
        this.m_imageURL = undefined;
        this.m_cur_text = undefined;

        this.fillFromXML();
    }

    Achievement.prototype.fillFromXML = function(){
       if(!isValid(this.m_xmlNode)){
            return;
       }
       try{ this.m_id = getXMLNodeValue(this.m_xmlNode,"id");}catch(err){};
       try{ this.m_imageURL = getXMLEncodedStringNodeValue(this.m_xmlNode,"image_url");}catch(err){};
       try{ this.m_cur_text = getXMLEncodedStringNodeValue(this.m_xmlNode,"cur_text");}catch(err){};
       try{ this.m_next_text = getXMLEncodedStringNodeValue(this.m_xmlNode,"next_text");}catch(err){};
    }

    Achievement.prototype.getId = function(){return this.m_id;}
    Achievement.prototype.getImageURL = function(){return this.m_imageURL;}
    Achievement.prototype.getCurText = function(){return this.m_cur_text;}
    Achievement.prototype.getNextText = function(){return this.m_next_text;}
//end Achievement



// StatsData
    function StatsData(a_statsXML){
        this.m_statsData = {};

        this.createStatsFromXML(a_statsXML);
    }

    StatsData.prototype.createStatsFromXML = function(a_xmlDoc){
        if(!isValid(a_xmlDoc)){
            return;
        }
        var l_userNode = getXMLFirstNode(a_xmlDoc, "target");
        this.m_statsData.user = new User(undefined);
        this.m_statsData.user.createXMLUser(l_userNode);        

        try{
            var l_weaponsURLNode = getXMLFirstNode(a_xmlDoc, "weapon_urls");
            if(isValid(l_weaponsURLNode)){
                this.m_statsData.weaponURLsArray = new Array();
                var l_weaponURLNodes = l_weaponsURLNode.getElementsByTagName("image_url");
                for(var l_index = 0; l_index < l_weaponURLNodes.length; l_index++){
                    this.m_statsData.weaponURLsArray.push(decodeEncodedStringValue(l_weaponURLNodes[l_index].firstChild.nodeValue));
                }
            }
        }catch(err){outputDebug(err);}

        try{
            var l_vehiclesURLNode = getXMLFirstNode(a_xmlDoc, "vehicle_urls");
            if(isValid(l_vehiclesURLNode)){
                this.m_statsData.vehicleURLsArray = new Array();
                var l_vehicleURLNodes = l_vehiclesURLNode.getElementsByTagName("image_url");
                for(var l_index = 0; l_index < l_vehicleURLNodes.length; l_index++){
                    this.m_statsData.vehicleURLsArray.push(decodeEncodedStringValue(l_vehicleURLNodes[l_index].firstChild.nodeValue));
                }

            }
        }catch(err){}

        try{
            var l_propertiesURLNode = getXMLFirstNode(a_xmlDoc, "land_urls");
            if(isValid(l_propertiesURLNode)){
                this.m_statsData.propertyURLsArray = new Array();
                var l_propertyURLNodes = l_propertiesURLNode.getElementsByTagName("image_url");
                for(var l_index = 0; l_index < l_propertyURLNodes.length; l_index++){
                    this.m_statsData.propertyURLsArray.push(decodeEncodedStringValue(l_propertyURLNodes[l_index].firstChild.nodeValue));
                }
            }
        }catch(err){}

        
        try{
            var l_achievementsNode = getXMLFirstNode(a_xmlDoc, "achievements");
            if(isValid(l_achievementsNode)){
                this.m_statsData.achievementsArray = new Array();
                var l_achievementNodes = l_achievementsNode.getElementsByTagName("achievement");
                for(var l_index = 0; l_index < l_achievementNodes.length; l_index++){
                    this.m_statsData.achievementsArray.push(new Achievement(l_achievementNodes[l_index]));
                }
            }
        }catch(err){}


        try{ this.m_statsData.partOfViewerMob = getXMLNodeValue(a_xmlDoc,"part_of_viewer_mob");}catch(err){};
        try{ this.m_statsData.jobsCompleted = getXMLNodeValue(a_xmlDoc,"jobs_completed");}catch(err){};
        try{ this.m_statsData.jailed = getXMLNodeValue(a_xmlDoc,"jailed");}catch(err){};
        try{ this.m_statsData.escaped = getXMLNodeValue(a_xmlDoc,"escaped_count");}catch(err){};
        try{ this.m_statsData.bountyKills = getXMLNodeValue(a_xmlDoc,"bounty_kills");}catch(err){};
        try{ this.m_statsData.fightsWon = getXMLNodeValue(a_xmlDoc,"fights_won");}catch(err){};
        try{ this.m_statsData.fightsLost = getXMLNodeValue(a_xmlDoc,"fights_lost");}catch(err){};
        try{ this.m_statsData.deathCount = getXMLNodeValue(a_xmlDoc,"death_count");}catch(err){};
        try{ this.m_statsData.killCount = getXMLNodeValue(a_xmlDoc,"kill_count");}catch(err){};
    }

    StatsData.prototype.getData = function(){
        return this.m_statsData;
    }
//end StatsData




//StatsDiv
    function StatsDiv(a_parentDiv, a_userId){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_userId = a_userId;
        this.m_titleDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;


        this.m_attackOptionText = "Attack";
        this.m_punchActionText = "Punch in Face";
        this.m_addHitListActionText = "Add to Hit List";

        this.m_inMobLabel = undefined;
        this.m_notInMobLabel = undefined;

        this.m_weaponsTitle = undefined;
        this.m_vehiclesTitle = undefined;
        this.m_propertiesTitle = undefined;

        this.m_jobsCompletedLabel = undefined;
        this.m_jailedLabel = undefined;
        this.m_escapedLabel = undefined;
        this.m_bountyKillsLabel = undefined;
        this.m_fightsWonLabel = undefined;
        this.m_fightsLostLabel = undefined;
        this.m_deathCountLabel = undefined;
        this.m_killCountLabel = undefined;

        this.m_achievementsConstructor = AchievementDiv;

        this.m_hitListDiv = undefined;

        this.initialize();
        this.createDiv();
    }

    StatsDiv.prototype.initialize = function(){
        this.m_inMobLabel = "This person is in your mob.";
        this.m_notInMobLabel = "This person is NOT in your mob.";

        this.m_weaponsTitle = "Weapons";
        this.m_vehiclesTitle = "Vehicles";
        this.m_propertiesTitle = "Properties";

        this.m_jobsCompletedLabel = "Missions Completed";
        this.m_jailedLabel = "Jailed";
        this.m_escapedLabel = "Escaped";
        this.m_bountyKillsLabel = "Bounties Collected";
        this.m_fightsWonLabel = "Fights Won";
        this.m_fightsLostLabel = "Fights Lost";
        this.m_deathCountLabel = "Death";
        this.m_killCountLabel = "Mobsters Whacked";

        this.m_hitListDiv = HitListBountyDiv;
    }


    StatsDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        this.m_titleDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_titleDiv);
        createTitleDiv(this.m_titleDiv, "Loading ... ");

        this.m_resultDiv = new ResultDiv(this.m_containerDiv);

        this.m_refreshDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_refreshDiv);

        this.refresh();
    }

    StatsDiv.prototype.refresh = function(){
        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.target_id = this.m_userId;

        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_stats", function(a_response){l_self.OnGetStats(a_response);}, l_params);
    }


    StatsDiv.prototype.OnGetStats = function(a_response){

        var l_xmlDoc = getGadgetResponseData(a_response);
        var l_statsData = new StatsData(l_xmlDoc);

        this.m_refreshDiv.innerHTML = "";


        
        var l_targetUser = l_statsData.getData().user;
                

        var l_optionsTitleArray = new Array();
        var l_optionsCallbackArray = new Array();

        l_optionsTitleArray.push(this.m_attackOptionText);
        var l_self = this;
        l_optionsCallbackArray.push(function(){
           l_self.m_resultDiv.showMessage(undefined, "Attacking " + l_targetUser.getMobName() + " ...");
           goToPageTop();

           var l_params = {};
           l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
           l_params.target_id = l_targetUser.getUserId();
           makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/attack",
                   function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                   l_params, 0);
        });


        l_optionsTitleArray.push(this.m_punchActionText);
        l_optionsCallbackArray.push(function(){
           l_self.m_resultDiv.showMessage(undefined, "Punching " + l_targetUser.getMobName() + " in the face ...");
           goToPageTop();

           var l_params = {};
           l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
           l_params.target_id = l_targetUser.getUserId();
           l_params.punch_in_face = true;
           makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/attack",
                   function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                   l_params, 0);
        });

        if(isValid(this.m_addHitListActionText)){
            l_optionsTitleArray.push(this.m_addHitListActionText);
            l_optionsCallbackArray.push(function(){
                GBL.MAIN_TABS.switchToDynamicTab(function(a_content, a_init, a_createArgs){new l_self.m_hitListDiv(a_content, a_init, a_createArgs);},
                                                 l_targetUser);
            });
        }            


        createTitleDiv(this.m_titleDiv, "&quot;"+l_targetUser.getMobName()+"&quot;, Level " + l_targetUser.getLevel() + " " + l_targetUser.getMobClass(),
                        l_optionsTitleArray, l_optionsCallbackArray, false);



        var l_infoDiv = document.createElement("div");
        this.m_refreshDiv.appendChild(l_infoDiv);
        l_infoDiv.style.color = "#FFFFFF";        
        if(l_statsData.getData().partOfViewerMob){
            l_infoDiv.innerHTML = this.m_inMobLabel;
        } else {
            l_infoDiv.innerHTML = this.m_notInMobLabel;
        }



        var l_topSSCells = new SideBySideCells(this.m_refreshDiv, true);
        var l_leftCell = l_topSSCells.getLeftCell();
        var l_rightCell = l_topSSCells.getRightCell();


        l_leftCell.style.width = "350px";
        l_leftCell.style.verticalAlign = "top";
        this.createStatsDiv(l_leftCell, l_statsData.getData());

        new CommentDiv(l_leftCell, this.m_userId);




        l_rightCell.style.width = "450px";
        l_rightCell.style.verticalAlign = "top";

        if(isValid(this.m_achievementsConstructor)){
            new this.m_achievementsConstructor(l_rightCell, l_statsData.getData().achievementsArray);
        }        

        this.createPictureList(l_rightCell, this.m_weaponsTitle, l_statsData.getData().weaponURLsArray);
        this.createPictureList(l_rightCell, this.m_vehiclesTitle, l_statsData.getData().vehicleURLsArray);
        this.createPictureList(l_rightCell, this.m_propertiesTitle, l_statsData.getData().propertyURLsArray);
    }


    StatsDiv.prototype.createStatsDiv = function(a_parentDiv, a_statsData){

        var l_titleDiv = document.createElement("div");
        a_parentDiv.appendChild(l_titleDiv);
        createTitleDiv(l_titleDiv, "Stats");

        var l_topSSCells = new SideBySideCells(a_parentDiv, true);
        var l_careerStatsCell = l_topSSCells.getLeftCell();
        var l_fightStatsCell = l_topSSCells.getRightCell();


        var l_contentTable = document.createElement("table");
        l_careerStatsCell.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        var l_headerTR = document.createElement("tr");
        l_contentTBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "180px";
        l_td.innerHTML = "Career Stats";

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "50px";
        l_td.style.paddingLeft = "10px";
        l_td.innerHTML = "Value";

        l_contentTBody.appendChild(this.createStatTr(this.m_jobsCompletedLabel, a_statsData.jobsCompleted));
        l_contentTBody.appendChild(this.createStatTr(this.m_jailedLabel, a_statsData.jailed));
        l_contentTBody.appendChild(this.createStatTr(this.m_escapedLabel, a_statsData.escaped));
        l_contentTBody.appendChild(this.createStatTr(this.m_bountyKillsLabel, a_statsData.bountyKills));    

        l_headerTR = document.createElement("tr");
        l_contentTBody.appendChild(l_headerTR);

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "250px";
        l_td.innerHTML = "Fight Stats";

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "50px";
        l_td.innerHTML = "Value";

        l_contentTBody.appendChild(this.createStatTr(this.m_fightsWonLabel, a_statsData.fightsWon));
        l_contentTBody.appendChild(this.createStatTr(this.m_fightsLostLabel, a_statsData.fightsLost));
        l_contentTBody.appendChild(this.createStatTr(this.m_deathCountLabel, a_statsData.deathCount));
        l_contentTBody.appendChild(this.createStatTr(this.m_killCountLabel, a_statsData.killCount));
    }



    StatsDiv.prototype.createStatTr = function(a_attribute, a_value){
        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = a_attribute;

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = a_value;

        return l_tr;
    }


    StatsDiv.prototype.createPictureList = function(a_parentDiv, a_title, a_pictureURLsArray){
        if(!isValid(a_pictureURLsArray) || a_pictureURLsArray.length <= 0){
            return;
        }

        var l_titleDiv = document.createElement("div");
        a_parentDiv.appendChild(l_titleDiv);
        createTitleDiv(l_titleDiv, a_title);

        var l_pictureDiv = document.createElement("div");
        a_parentDiv.appendChild(l_pictureDiv);
        l_pictureDiv.style.textAlign = "left";
        l_pictureDiv.style.paddingLeft = "30px";

        for(var l_index = 0; l_index < a_pictureURLsArray.length; l_index++){
            var l_img = document.createElement("img");
            l_pictureDiv.appendChild(l_img);
            l_img.src = a_pictureURLsArray[l_index];
            l_img.style.margin = "8px";

        }
    }
//end StatsDiv









//AchievementDiv
    function AchievementDiv(a_parentDiv, a_achievements){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;

        this.m_achievements = a_achievements;
        this.m_achievementTDs = undefined;
        this.m_textDiv = undefined;
        this.m_curSelectedIndex = undefined;

        this.createDiv();
    }

    AchievementDiv.prototype.createDiv = function(){

        if(!isValid(this.m_achievements) || this.m_achievements.length == 0){
            return;
        }

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, "Your Achievements:");


        var l_contentDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_contentDiv);
        l_contentDiv.style.paddingLeft = "10px";
        var l_achievementTable = document.createElement("table");
        l_contentDiv.appendChild(l_achievementTable);
        var l_achievementTBody = document.createElement("tbody");
        l_achievementTable.appendChild(l_achievementTBody);


        this.m_textDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_textDiv);
        this.m_textDiv.style.textAlign = "left";
        this.m_textDiv.style.padding = "5px";        
        this.m_textDiv.style.color = "#EEEEEE";
        this.m_textDiv.style.margin = "8px";
        this.m_textDiv.style.border = "0px solid #888888";
        this.m_textDiv.style.fontSize = "11px";
        this.m_textDiv.style.fontFamily = "lucida grande,tahoma,verdana,arial,sans-serif";


        this.m_achievementTDs = new Array();
        var l_tr = undefined;
        for(var l_index = 0; l_index < this.m_achievements.length; l_index++){
            if(l_index % 6 == 0){
                l_tr = document.createElement("tr");
                l_achievementTBody.appendChild(l_tr);
            }
            l_tr.appendChild(this.createEntry(l_index));
        }

        this.selectEntry(0);
    }


    AchievementDiv.prototype.createEntry = function(a_achievementIndex){
        var l_entryTD = document.createElement("td");
        l_entryTD.style.width = "50px";

        var l_imageDiv = new ImageDiv(l_entryTD, this.m_achievements[a_achievementIndex].getImageURL(), "50px", "50px", true);

        var l_self = this;
        addEvent(l_entryTD, "mouseover", function(){
            l_self.selectEntry(a_achievementIndex);            
        });

        this.m_achievementTDs.push(l_entryTD);
        return l_entryTD;
    }


    AchievementDiv.prototype.selectEntry = function(a_achievementIndex){
       if(isValid(this.m_curSelectedIndex)){
          if(this.m_curSelectedIndex == a_achievementIndex){
              return;
          }
          this.m_achievementTDs[this.m_curSelectedIndex].style.border = "none";
       }
       this.m_curSelectedIndex = a_achievementIndex;
       this.m_achievementTDs[this.m_curSelectedIndex].style.border = "2px solid #FFA500";
       this.m_textDiv.innerHTML = this.m_achievements[this.m_curSelectedIndex].getCurText();
    }

//end AchievementDiv



// MadeMenDiv
    function MadeMenDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;

        this.m_mostDeadlyRankingDiv = undefined;
        this.m_topFightersRankingDiv = undefined;
        this.m_topBountyHuntersRankingDiv = undefined;
        this.m_topTycoonsRankingDiv = undefined;

        this.m_titleString = undefined;

        this.initialize();
        this.createDiv();
    }

    MadeMenDiv.prototype.initialize = function(){
        this.m_titleString = "<iframe src='http://sns.fontera.net/myspace/counterstrike/missions.php?buID="+UserID+"' height='1800' width='800' frameborder='0'></iframe>";
    }

    MadeMenDiv.prototype.createRankingDivs = function(a_contentTBody){
        var l_tr = document.createElement("tr");
        a_contentTBody.appendChild(l_tr);

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.width = "390px";
        l_td.style.verticalAlign = "top";
       // this.m_topFightersRankingDiv = new MobRankingDiv(l_td, "Legendary Fighters", "Win Count");

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.width = "390px";
        l_td.style.verticalAlign = "top";
        //this.m_topTycoonsRankingDiv = new MobRankingDiv(l_td, "Most Wealthy", "Bank Funds");


        l_tr = document.createElement("tr");
        a_contentTBody.appendChild(l_tr);

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.width = "390px";
        l_td.style.verticalAlign = "top";
       // this.m_mostDeadlyRankingDiv = new MobRankingDiv(l_td, "Most Deadly", "KO Count");

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.width = "390px";
        l_td.style.verticalAlign = "top";
       // this.m_topBountyHuntersRankingDiv = new MobRankingDiv(l_td, "Top Bounty Hunters", "Head Count");
    }

    MadeMenDiv.prototype.createDiv = function(){

        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.padding = "15px";
        this.m_containerDiv.style.textAlign = "center";

        var l_title = document.createElement("div");
        this.m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, this.m_titleString);



        var l_contentTable = document.createElement("table");
        this.m_containerDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        this.createRankingDivs(l_contentTBody);

        var l_params = {};
        l_params.user_id = GBL.MAIN_DATA.getViewer().getUserId();
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_made_men", function(a_responseData){l_self.onGetMadeMen(a_responseData);}, l_params);
    }


    MadeMenDiv.prototype.onGetMadeMen = function(a_responseData){
        outputDebug("onGetFightList");

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_mostDeadlyNode = getXMLFirstNode(l_xmlDoc, "most_deadly");
                this.m_mostDeadlyRankingDiv.fillFromXML(l_mostDeadlyNode);

                var l_topFightersNode = getXMLFirstNode(l_xmlDoc,"top_fighters");
                this.m_topFightersRankingDiv.fillFromXML(l_topFightersNode);

                var l_topBountyHuntersNode = getXMLFirstNode(l_xmlDoc,"top_bounty_hunters");
                this.m_topBountyHuntersRankingDiv.fillFromXML(l_topBountyHuntersNode);

                var l_topTycoonsNode = getXMLFirstNode(l_xmlDoc,"top_tycoons");
                this.m_topTycoonsRankingDiv.fillFromXML(l_topTycoonsNode);

            } catch (err) { outputDebug("onGetMadeMen " + err);}
        }
    }
//end MadeMenDiv






function MobRankingDiv(a_parentDiv, a_category, a_countTitle){

    var m_parentDiv = a_parentDiv;
    var m_category = a_category;
    var m_countTitle = a_countTitle;
    var m_containerDiv = undefined;
    var m_contentTBody = undefined;
    var m_loadingDiv = undefined;

    this.fillFromXML = fillFromXML;


    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        outputDebug("createDiv");

        m_parentDiv = _a_parentDiv;

        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);
        m_containerDiv.style.padding = "15px";
        m_containerDiv.style.textAlign = "center";

        var l_contentTable = document.createElement("table");
        m_containerDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        l_contentTable.style.borderSpacing = "6px";
        m_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(m_contentTBody);

        var l_headerTR = document.createElement("tr");
        m_contentTBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "250px";
        l_td.innerHTML = m_category;

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyle(l_td);
        l_td.style.width = "100px";
        l_td.innerHTML = a_countTitle;

        m_loadingDiv = document.createElement("div");
        m_containerDiv.appendChild(m_loadingDiv);
        m_loadingDiv.style.padding = "10px";
        m_loadingDiv.innerHTML = "<span style='color:#FF6F00; font-weight:bold;'> Loading ...  </span>";

    }

    function fillFromXML(a_xmlNode){

        m_loadingDiv.style.display = "none";

        if(isValid(a_xmlNode)){
            try{
                var l_entryNodes = a_xmlNode.getElementsByTagName("entry");
                for(var l_index = 0; l_index < l_entryNodes.length; l_index++){
                    var l_user = new User(undefined);
                    l_user.createXMLUser(getXMLFirstNode(l_entryNodes[l_index], "user"));
                    var l_count = getXMLNodeValue(l_entryNodes[l_index], "count");

                    m_contentTBody.appendChild(createContentElement(l_user, l_count));
                }

            } catch (err) { outputAlert("fillFromXML " + err);}
        }
    }



    function createContentElement(a_user, a_count){
        outputDebug("createContentElement");

        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.style.padding = "0px 10px 0px 10px";
        l_td.innerHTML = "<span style='color:#3E99C3; font-weight:bold; font-size:12px;'> " + a_user.getMobName() + " </span>";
        l_td.style.cursor = "pointer";
        addEvent(l_td, "click", function(){
            showUserStats(a_user.getUserId());
        });


        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.style.padding = "0px 10px 0px 10px";
        l_td.style.fontSize = "12px";
        l_td.innerHTML = formatNumberWithCommas(a_count);

        return l_tr;
    }
}

function ResultDiv(a_parentDiv){

    var m_parentDiv = a_parentDiv;
    var m_containerDiv = undefined;

    this.showMessage = showMessage;
    this.getContainerDiv = getContainerDiv;

    createDiv();

    function createDiv(){
        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);

        m_containerDiv.style.color = "white";
        m_containerDiv.style.margin = "10px";
        m_containerDiv.style.padding = "10px 5px 5px 20px";
        m_containerDiv.style.border = "solid 0px #CCCCCC";
        m_containerDiv.style.display = "none";
    }

    function showMessage(a_success, a_msg, a_bulletinNode){
        m_containerDiv.style.display = "block";
        m_containerDiv.innerHTML = "";

        if(isValid(a_success)){
            var l_successDiv = document.createElement("div");
            m_containerDiv.appendChild(l_successDiv);
            l_successDiv.style.color = "#FF7F00";
            l_successDiv.style.fontSize = "14px";
            l_successDiv.style.fontWeight = "bold";
            l_successDiv.style.textAlign = "left";

            if(a_success){
                l_successDiv.innerHTML = "Excellent!";
            } else {
                l_successDiv.innerHTML = "";
            }
        }

        var l_msgDiv = document.createElement("div");
        m_containerDiv.appendChild(l_msgDiv);
        l_msgDiv.style.color = "#FFFFFF";
        l_msgDiv.style.textAlign = "left";
        l_msgDiv.style.padding = "8px";
        l_msgDiv.innerHTML = a_msg;


        // handling bulletins
        try{
            if(isValid(a_bulletinNode)){
                var l_buttonText = getXMLEncodedStringNodeValue(a_bulletinNode, "button_text");
                var l_bulletinSubject = getXMLEncodedStringNodeValue(a_bulletinNode, "subject");
                var l_bulletinBody = getXMLEncodedStringNodeValue(a_bulletinNode, "body_html");

                var l_bulletinButtonDiv = document.createElement("div");
                m_containerDiv.appendChild(l_bulletinButtonDiv);
                l_bulletinButtonDiv.style.padding = "15px 10px 20px 50px";
                l_bulletinButtonDiv.style.textAlign = "left";

                new Button(l_bulletinButtonDiv, l_buttonText, function(){
                    postToBulletin(GBL.MAIN_DATA.getViewer(), l_bulletinSubject, l_bulletinBody, function(){});                    
                });
            }
        }catch(err){}
    }

    function getContainerDiv(){
        return m_containerDiv;
    }
}
function sendBulletin(){

	var target = MyOpenSpace.PostTo.Targets.BULLETINS;
	var subject = "";
	var content = "";

	subject += "Counter Strike";

	content += "<a href='" + GBL.APP_CANVAS_URL + "&track=comment_img'><img src='http://sns.fontera.net/myspace/counterstrike/CS_profile_page.gif' align='left'/></a>" + GBL.MAIN_DATA.getViewer().getName() + " wants you to join the MySpace game <a href='" + GBL.APP_CANVAS_URL + "&track=link1'>Counter Strike</a>. <p>Join the Frag Fest. Suit up, grab your weapons and prepare for war!</p><br/><a href='" + GBL.APP_CANVAS_URL + "&track=comment_link2''>Join " + GBL.MAIN_DATA.getViewer().getName() + " and other gamers Now!</a>";
	
	var message = opensocial.newMessage(content);

	message.setField(opensocial.Message.Field.TITLE, subject);

	message.setField(opensocial.Message.Field.TYPE, target);
//(MS_OS_TOKEN, l_message, a_targetUser, a_postToCallback);
	V_LIBRARY_OS_CONTAINER.postTo(MS_OS_TOKEN, message);
}

function init(){
    outputDebug("init called");
        
    gadgets.window.adjustHeight(2850);

    document.body.style.backgroundColor = "#ffffff";

    var l_headerFrame = document.getElementById("headerFrame");
    if(isValid(l_headerFrame)){
        l_headerFrame.style.backgroundColor = "#ffffff";
        l_headerFrame.style.backgroundImage = "";
        l_headerFrame.style.height = "135px";
        l_headerFrame.style.backgroundRepeat = "no-repeat";
        l_headerFrame.style.backgroundPosition = "0 0";
        l_headerFrame.style.margin = "0px";
        l_headerFrame.style.padding = "0px";
        l_headerFrame.style.border = "none";
        l_headerFrame.style.display = "block";
    }
	
	var l_footerFrame = document.getElementById("footerFrame");
    if(isValid(l_footerFrame)){
        l_footerFrame.style.backgroundColor = "#ffffff";
        l_footerFrame.style.backgroundImage = "";
        l_footerFrame.style.height = "135px";
        l_footerFrame.style.backgroundRepeat = "no-repeat";
        l_footerFrame.style.backgroundPosition = "0 0";
        l_footerFrame.style.margin = "0px";
        l_footerFrame.style.padding = "0px";
        l_footerFrame.style.border = "none";
        l_footerFrame.style.display = "block";
    }

    
    var l_mainFrame = document.getElementById("mainFrame");
    if(isValid(l_mainFrame)){
        l_mainFrame.style.paddingLeft = "50px";
        l_mainFrame.style.paddingRight = "50px";
        //l_mainFrame.style.backgroundColor = "#ffffff";
        l_mainFrame.style.backgroundImage = "";
        l_mainFrame.style.backgroundRepeat = "repeat-x";
        l_mainFrame.style.margin = "0px";
        l_mainFrame.style.padding = "10px 20px 0px 20px";
        l_mainFrame.style.overflow = "auto";
        l_mainFrame.style.border = "none";

//        if(isDebugging()){
//            l_mainFrame.style.height = "1200px";
//        } else {
            l_mainFrame.style.height = "1800px";
//        }
    }


    try{
        _uacct = "UA-4182330-8";
        urchinTracker();
    }catch(err){}

    
    var l_params = gadgets.views.getParams();
    for(var l_id in l_params){
        outputDebug(l_id + " >>> " + l_params[l_id]);
    }

    try{
        var l_installState = l_params["installState"];
        switch(l_installState){
            case "0": GBL.app_install_state = GBL.APP_NOT_INSTALLED; break;
            case "1": GBL.app_install_state = GBL.APP_INSTALLED; break;
            case "2": GBL.app_install_state = GBL.APP_JUST_INSTALLED; break;

            default: GBL.app_install_state = GBL.APP_INSTALLED; break;
        }
    } catch(err){
        GBL.app_install_state = GBL.APP_INSTALLED;
    }

    startGame();
}

/*	,
    {iframeId:'a30bde71', zoneId:46},
    {iframeId:'a42f0f1c', zoneId:47}];
*/
function startGame(){
    var l_headerFrame = document.getElementById("headerFrame");
//    l_headerFrame.innerHTML = "<iframe id='a42ed14d' name='a42ed14d' src='http://openx.textstream.co.za/www/delivery/afr.php?refresh=10&amp;zoneid=44&amp;cb=Math.floor(Math.random()*199999)' framespacing='0' frameborder='no' scrolling='no' width='800' height='64'><a href='http://openx.textstream.co.za/www/delivery/ck.php?n=af04dc89&amp;cb=Math.floor(Math.random()*199999)' target='_blank'><img src='http://openx.textstream.co.za/www/delivery/avw.php?zoneid=44&amp;cb=Math.floor(Math.random()*199999)&amp;n=af04dc89' border='0' alt='' /></a></iframe>";
	// l_headerFrame.innerHTML = "<iframe id='aa735543' name='aa735543' framespacing='0' frameborder='no' scrolling='no' width='900' height='64'></iframe><br/><iframe id='a4ff4695' name='a4ff4695' framespacing='0' frameborder='no' scrolling='no' width='900' height='64'></iframe>";
	// l_headerFrame.innerHTML +=  "<script src='http://sns.fontera.net/myspace/ads/js/textstreamAds.js'></script>";
  

   var l_mainFrame = document.getElementById("mainFrame");
    l_mainFrame.innerHTML = "";
    
    if(GBL.app_install_state == GBL.APP_NOT_INSTALLED){
        showNotInstalledMessage();
    } else {
        var l_loadStatusDiv = new CenteredTextMessageDiv(l_mainFrame, "<span style='font-weight:bold;'> Waiting for MySpace to respond... </span> <br/> <span style='font-size:10px;'> (Refreshing the page may help...) </span>", "300px");
        GBL.MAIN_DATA = new CentralData(createUI, l_loadStatusDiv);
    }
}


function showNotInstalledMessage() {
    var l_mainFrameDiv = document.getElementById("mainFrame");

    var l_arrowTop = "0px";
    var l_arrowLeft = "135px";
    var l_msgTop = "110px";
    var l_msgLeft = "80px";

//    var IE = document.all?true:false;
//    if(IE){
//        l_arrowTop = "-60px";
//        l_arrowLeft = "135px";
//        l_msgTop = "50px";
//        l_msgLeft = "80px";
//    }

    var l_arrowImg = document.createElement("img");
    document.body.appendChild(l_arrowImg);
    l_arrowImg.src = "http://sns.fontera.net/myspace/solarsalvage/arrow.jpg";
    l_arrowImg.style.position = "absolute";
    l_arrowImg.style.top = l_arrowTop;
    l_arrowImg.style.left = l_arrowLeft;
    l_arrowImg.style.zIndex = 0;


    var l_msgDiv = document.createElement("div");
    document.body.appendChild(l_msgDiv);
    l_msgDiv.style.textAlign = "center";
    l_msgDiv.style.backgroundColor = "#FFFFFF";
    l_msgDiv.style.padding = "10px";
    l_msgDiv.style.fontSize = "18px";
    l_msgDiv.style.borderColor = "black";
    l_msgDiv.style.borderStyle = "solid";
    l_msgDiv.style.borderWidth = "4px";
    l_msgDiv.style.position = "absolute";
    l_msgDiv.style.top = l_msgTop;
    l_msgDiv.style.left = l_msgLeft;
    l_msgDiv.style.zIndex = 0;

    if(screen.availHeight < 600){
        l_msgDiv.style.textAlign = "left";
        l_msgDiv.innerHTML = "1. Press <b>F11</b> for fullscreen.<br> 2. Click &quot;Add this App&quot; above to continue!";
    } else {
        l_msgDiv.innerHTML = "You must add this application to continue!";
    }



    document.body.style.backgroundColor = "#000000";
    document.body.style.backgroundImage = "";
    document.body.style.backgroundRepeat = "no-repeat";

    var l_headerFrame = document.getElementById("headerFrame");
    if(isValid(l_headerFrame)){
        l_headerFrame.style.display = "none";
    }
	var l_footerFrame = document.getElementById("footerFrame");
    if(isValid(l_footerFrame)){
        l_footerFrame.style.display = "none";
    }
    var l_mainFrame = document.getElementById("mainFrame");
    if(isValid(l_mainFrame)){
        l_mainFrame.style.display = "none";
    }

    if(isValid(getOpenSocialParameter("rsrc"))){
        abTest(-1, getOpenSocialParameter("rsrc"));
    }
    return false;
}


function createUI(){

    var l_headerFrame = document.getElementById("headerFrame");
    var l_mainFrame = document.getElementById("mainFrame");
    l_mainFrame.innerHTML = "";
    goToPageTop();

    //if(!isValid(GBL.MAIN_DATA.getViewer().getMobName()) || !isValid(GBL.MAIN_DATA.getViewer().getMobClass())){
       // new InitialChooserDiv(l_mainFrame, createUI);
    //    return;
    //}


    var l_nameArray = new Array();
    l_nameArray.push("Attack");
	l_nameArray.push("Arena");
    l_nameArray.push("Equipment");
    // l_nameArray.push("Bank");
	
    l_nameArray.push("Clans");
    l_nameArray.push("Missions");
    l_nameArray.push("Recruit");
    l_nameArray.push("How to play");
    l_nameArray.push("Avatar");
	l_nameArray.push("Leaderboard");
	// l_nameArray.push("Recruited Friends");
   l_nameArray.push("Medals");
   l_nameArray.push("CS Forum");
  


    var l_callbackArray = new Array();
    l_callbackArray.push(toMainMenuTab);
	l_callbackArray.push(toGodfatherTab);
    l_callbackArray.push(toBankTab);
   // l_callbackArray.push(toFightTab);
  
  l_callbackArray.push(toHitListTab);
    l_callbackArray.push(toMadeMenTab);
    l_callbackArray.push(toMyMobTab);
	l_callbackArray.push(toCityTab);
	l_callbackArray.push(toHospitalTab);
	 l_callbackArray.push(toJobTab);
	//l_callbackArray.push(toFAQTab);
    l_callbackArray.push(toMyBossTab);
   l_callbackArray.push(toStockpileTab);
   


    var l_alignArray = new Array();
    l_alignArray.push("left");
    l_alignArray.push("left");
    l_alignArray.push("left");
    //l_alignArray.push("left");
    //l_alignArray.push("left");
    //l_alignArray.push("left");
    //l_alignArray.push("left");
    //l_alignArray.push("left");
    //l_alignArray.push("left");
    l_alignArray.push("left");
   // l_alignArray.push("left");
    //l_alignArray.push("left");
    //l_alignArray.push("right");

    var l_defaultTabIndex = 0;

    GBL.REFRESH_STATUS = new ViewerRefreshStatus(l_headerFrame);

    GBL.STATUS_DIV = new ViewerStatusDiv(l_mainFrame);
    GBL.MAIN_TABS = new TabsDiv(l_mainFrame, l_nameArray, l_callbackArray, l_alignArray, l_defaultTabIndex, "unSelectedTab", "selectedTab");

    if(isValid(getOpenSocialParameter(GBL.SHOW_USER_ID))){
        GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
            a_contentDiv.innerHTML = "";
            new StatsDiv(a_contentDiv, getOpenSocialParameter(GBL.SHOW_USER_ID));
        });
    }

    if(GBL.app_install_state != GBL.APP_JUST_INSTALLED &&
       isValid(getOpenSocialParameter("rsrc"))){
        abTest(GBL.MAIN_DATA.getViewer().getUserId(), getOpenSocialParameter("rsrc")+"_installed");
    }

    if(GBL.MAIN_DATA.getViewer().getIsCheater()){
        var l_headerFrame = document.getElementById("headerFrame");
         if(isValid(l_headerFrame)){
            l_headerFrame.style.backgroundImage = "";
            l_headerFrame.style.padding = "5px 200px 5px 25px";
            l_headerFrame.innerHTML = "<span style='color:#FF0000; font-size:18px; font-weight:bold;'> WARNING! </span>" +
                                      "<span style='padding-left:20px; color:#FF0000; font-size:14px; font-weight:bold;'> We have detected that you are playing with an automated program!<br>" +
                                      "Your actions are ruining the experience for other players!<br>"+
                                      "If you are caught again, your characters will be removed, and your account will be BANNED!" +
                                      "</span>";
         }
    }


    try{
        var l_params = {};
        l_params.action = "prefetch";
        l_params.app = "MOBSTER";
        l_params.userId = GBL.MAIN_DATA.getViewer().getUserId();
        makeXMLNotCachedRequest("http://friend-dynamic-lb.myspacegamingapps.com/get_friend", function(a_response){}, l_params,0);
    }catch(err){};
}


function toMainMenuTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new MobMainMenuDiv(a_contentDiv);
       // new NewsFeedDiv(a_contentDiv);
    }
}

function toJobTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new JobListDiv(a_contentDiv);
    }
}

function toCityTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new CityListDiv(a_contentDiv);
    }
}

function toBankTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new BankDiv(a_contentDiv);
    }
}

function toGodfatherTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new GodfatherDiv(a_contentDiv);
    }
}

function toFightTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new FightListDiv(a_contentDiv);
    }
}

function toHitListTab(a_contentDiv, a_initialized){
    a_contentDiv.innerHTML = "";
   // new HitListDiv(a_contentDiv);
	new ViewerMobDivX(a_contentDiv);
}

function toStockpileTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new StockPileDiv(a_contentDiv);
    }
}

function toHospitalTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new HospitalDiv(a_contentDiv);
    }    
}

function toMyMobTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new ViewerMobDiv(a_contentDiv);
    }
}

function toMyBossTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new BossDiv(a_contentDiv);
    }
}

function toMadeMenTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new MadeMenDiv(a_contentDiv);
    }
}

function toFAQTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new MobFAQDiv(a_contentDiv);
    }
}


//////////////////////////////////////////////////////////////////////////////////////////////
// Simple canvas elements

function showWelcomeMessage(a_parentDiv){
    var l_welcomeDiv = document.createElement("div");
    a_parentDiv.appendChild(l_welcomeDiv);
    l_welcomeDiv.style.margin = "10px 0px 10px 0px";
    l_welcomeDiv.style.padding = "10px";
    l_welcomeDiv.style.border = "solid 0px #888888";
    l_welcomeDiv.style.fontSize = "20px";
    l_welcomeDiv.style.fontWeight = "bold";
    l_welcomeDiv.style.textAlign = "left";
    l_welcomeDiv.style.color = "#CD7F32";
    l_welcomeDiv.innerHTML = ""

    var l_messageDiv = document.createElement("div");
    l_welcomeDiv.appendChild(l_messageDiv);
    l_messageDiv.style.padding = "8px 8px 8px 20px";
    l_messageDiv.style.fontSize = "14px";
    l_messageDiv.style.fontWeight = "300";
    l_messageDiv.style.color = "#FFFFFF";
    /*l_messageDiv.innerHTML = "As a new thug on the streets, you should start making money and gaining experience by <a href='#' class='standardLink' onclick='switchTabs(1); return false;'>completing some missions.</a>"
            + "<br/>After you've made some money, you can also:<br/><ul>"
            + "<li>Control and build <a href='#' class='standardLink' onclick='switchTabs(2); return false;'>your territory</a> to earn recurring income.</li>"
            + "<li>Spend your money and <a href='#' class='standardLink' onclick='switchTabs(7); return false;'>equip your mob</a> with powerful weapons and vehicles.</li>"
            + "<li>Use your weapons to <a href='#' class='standardLink' onclick='switchTabs(5); return false;'>fight</a> against opposing mafia families.</li>"
            + "<li><b>HOT TIP: The larger your Mob family, the more powerful you are.</b> <a href='#' class='standardLink' onclick='switchTabs(9); return false;'>Click here to invite your friends</a> to join your mob family!</li>"
            + "</ul>For more information on how to play Mobsters, <a href='#' class='standardLink' onclick='switchTabs(12); return false;'>check out our FAQ!</a>";*/
}


function showNotifactionMessage(a_parentDiv){
    new HotTipDiv(a_parentDiv);
}

 function textstreamAds(){
	var ox_TEXTSTREAM_AD_DEBUGGER = true;
	var ox_adSource = 'http://openx.textstream.co.za/www/delivery/afr.php?';
	var ox_adRefresh = 'refresh=20&';
	var ox_adCacheBusting = 'cb=' + Math.floor(Math.random()*99999999999)+'&';
	var ox_zoneId = 'zoneid=';
	var ox_BannerParameters = '';
	
	
	this.getUserInformation		= getUserInformation;
	this.processUserInformation	= processUserInformation;
	this.setAllIframes			= setAllIframes;
	this.setIframe				= setIframe;
	this.isDebugging 			= isDebugging;
	this.debugOutput			= debugOutput;
	this.isValid				= isValid;
	
	debugOutput("In textstream Ads" );
	getUserInformation();

	
	function getUserInformation() {
		debugOutput("Getting User information" );
		
		var os = opensocial.Container.get();
		var dataReqObj = os.newDataRequest();

		var param = {};
		param[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.DATE_OF_BIRTH, MyOpenSpace.Person.Field.CITY, MyOpenSpace.Person.Field.GENDER, MyOpenSpace.Person.Field.REGION, MyOpenSpace.Person.Field.COUNTRY];
	
		var viewerReq = os.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER, param);
		//var viewerFriendsReq = os.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, param);

		dataReqObj.add(viewerReq);
		//dataReqObj.add(viewerFriendsReq);
		
		dataReqObj.send(processUserInformation);
	}
	
	function processUserInformation( dataResponse ) {
		debugOutput("Processing returned information" );
		
		ox_BannerParameters = "";
		
		if ( !dataResponse.hadError() ) {
			var viewerData = dataResponse.get(opensocial.DataRequest.PersonId.VIEWER).getData();
			var viewerID = viewerData.getField(opensocial.Person.Field.ID);

			var name			= viewerData.getField(opensocial.Person.Field.NAME);
			var pic_url			= viewerData.getField(opensocial.Person.Field.THUMBNAIL_URL);
			var date_of_birth	= viewerData.getField(opensocial.Person.Field.DATE_OF_BIRTH);
			var age				= viewerData.getField(MyOpenSpace.Person.Field.AGE);
			var gender			= viewerData.getField(MyOpenSpace.Person.Field.GENDER);
			var city			= viewerData.getField(MyOpenSpace.Person.Field.CITY);
			var postalcode		= viewerData.getField(MyOpenSpace.Person.Field.POSTALCODE);
			var marital_status	= viewerData.getField(MyOpenSpace.Person.Field.MARITAL_STATUS);
			var region			= viewerData.getField(MyOpenSpace.Person.Field.REGION);
			var country			= viewerData.getField(MyOpenSpace.Person.Field.COUNTRY);

			if ( viewerID )
				ox_BannerParameters += '&viewerId=' + escape(viewerID);
			else 
				ox_BannerParameters += '&viewerId';
			if ( name )
				ox_BannerParameters += '&name=' + escape(name);
			else
				ox_BannerParameters += '&name';
			if ( pic_url )
				ox_BannerParameters += '&pic_url=' + escape(pic_url);
			else
				ox_BannerParameters += '&pic_url';
			if ( age )
				ox_BannerParameters += '&age=' + escape(age);
			else
				ox_BannerParameters += '&age';
			if ( gender )
				ox_BannerParameters += '&gender=' + escape(gender);
			else
				ox_BannerParameters += '&gender';
			if ( city )
				ox_BannerParameters += '&city=' + escape(city);
			else
				ox_BannerParameters += '&city';
			if ( postalcode )
				ox_BannerParameters += '&postalcode=' + escape(postalcode);
			else
				ox_BannerParameters += '&postalcode';
			if ( marital_status )
				ox_BannerParameters += '&marital_status=' + escape(marital_status);
			else
				ox_BannerParameters += '&marital_status';
			if ( date_of_birth )
				ox_BannerParameters += '&dob=' + escape(date_of_birth);
			else
				ox_BannerParameters += '&dob';
			if ( region )
				ox_BannerParameters += '&region=' + escape(region);
			else
				ox_BannerParameters += '&region';
			if ( country )
				ox_BannerParameters += '&country=' + escape(country);
			else
				ox_BannerParameters += '&country';
		} else {
			ox_BannerParameters += '&viewerId&name&pic_url&age&gender&city&postalcode&marital_status';
		}
		
		setAllIframes();
	}
	
	function setAllIframes() {
		debugOutput("Updating all iframes" );
		
		if ( isValid( textstreamAdSettings ) ) {
			var src = ''
			for( var i in textstreamAdSettings ) {
				src = ox_adSource + ox_adRefresh + ox_adCacheBusting + ox_zoneId + textstreamAdSettings[i].zoneId + ox_BannerParameters;
				setIframe(textstreamAdSettings[i].iframeId, src)
			}
		}
	}
	
	function setIframe(iframe_id, url){
		
		debugOutput("Updating Iframe " +  iframe_id + ' with ' + url);
		var ifrm = document.getElementById( iframe_id );
		ifrm.setAttribute("src", url);
	}
	
	function isDebugging(){
		try{
			if ( isValid(ox_TEXTSTREAM_AD_DEBUGGER) && ox_TEXTSTREAM_AD_DEBUGGER ) {  
				return true;
			} else {
				return false;
			}
		}catch(err){
			return false;
		}
	}
	
	function debugOutput ( a_text ) {
		try{                        
			if(isDebugging()){
				var debugElement = document.getElementById('debugOutput');
				if(isValid(debugElement) && isValid(debugElement.style) && debugElement.style.display != "none"){
					debugElement.innerHTML += a_text + '<br>';
				}
			}
		}catch(err){};
	}
	
	function isValid(a_obj) {
		return (a_obj != undefined && a_obj != null);
	}
}



function MobMainMenuDiv(a_parentDiv){

    var m_parentDiv = a_parentDiv;
    var m_containerDiv = undefined;

    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);
        m_containerDiv.style.padding = "15px";
        m_containerDiv.style.textAlign = "center";

        if(GBL.app_install_state == GBL.APP_JUST_INSTALLED ||
           (isValid(GBL.MAIN_DATA.getViewer().getJoinedDaysAgo()) &&
            GBL.MAIN_DATA.getViewer().getJoinedDaysAgo() <= 1)){
            showWelcomeMessage(m_containerDiv);            
        } else {
            showNotifactionMessage(m_containerDiv);
        }

        var l_numRequests = GBL.MAIN_DATA.getViewer().getNumRequests();
      //  if(isValid(l_numRequests) && l_numRequests > 0){
      //      var l_resultDiv = new ResultDiv(m_containerDiv);
      //      l_resultDiv.showMessage(undefined, "You have " + l_numRequests + " request(s) to join people's mobs.");
      //      l_resultDiv.getContainerDiv().style.cursor = "pointer";
      //      addEvent(l_resultDiv.getContainerDiv(), "click", function(){
      //          GBL.MAIN_TABS.switchToTab(9);
      //      });
      //  }
	  
	 textstreamAds();
	

        var l_title = document.createElement("div");
        m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, "<span style='color:orange'>Counter Strike:<span>");   

		var app_container=document.createElement("div");
		m_containerDiv.appendChild(app_container);
		createTitleDiv(app_container,"<iframe src='http://sns.fontera.net/myspace/counterstrike/index.php?buID="+UserID+"' height='920' width='800' frameborder='0'></iframe><iframe id='a42f0f1c' name='a42f0f1c' framespacing='0' frameborder='no' scrolling='no' width='900' height='64'></iframe><iframe id='a30bde71' name='a30bde71' framespacing='0' frameborder='no' scrolling='no' width='900' height='64'></iframe><span style='color:orange; font-size: 12pt; font-family: Trebuchet MS'>The developers of this application are against the purchasing and the use of firearms. Please enjoy the game responsibly.</span>");
		/*	

        var l_contentTable = document.createElement("table");
        m_containerDiv.appendChild(l_contentTable);
        l_contentTable.style.marginLeft = "auto";
        l_contentTable.style.marginRight = "auto";
        var l_contentTBody = document.createElement("tbody");
        l_contentTable.appendChild(l_contentTBody);

        l_contentTBody.appendChild(createContentElement("Missions", "Completing missions is the quickest way to gain money and experience.", 1));
        l_contentTBody.appendChild(createContentElement("My Territory", "Buy, build, and control more territory to earn recurring income.", 2));
        l_contentTBody.appendChild(createContentElement("The Bank", "Use the bank to launder your money and keep it safe.", 3));
        l_contentTBody.appendChild(createContentElement("The Godfather", "Earn favors from The Godfather.", 4));
        l_contentTBody.appendChild(createContentElement("Fight!", "Attack rival mobsters and make money robbing them!", 5));
        l_contentTBody.appendChild(createContentElement("The Hit List", "Make hits on marked men and earn a big bounties.", 6));
        l_contentTBody.appendChild(createContentElement("My Equipment", "Buy powerful weapons, hot cars, and more.", 7));
        l_contentTBody.appendChild(createContentElement("Hospital", "Pay your doctors some clean money to heal you." , 8));
        l_contentTBody.appendChild(createContentElement("My Mob Family", "Grow your mob family to become more powerful." , 9));
        l_contentTBody.appendChild(createContentElement("My Mobster", "View and upgrade your character.", 10));
        l_contentTBody.appendChild(createContentElement("Made Men", "The most powerful mobsters of MySpace.", 11));*/
    }

    function createContentElement(a_title, a_description, a_tabIndex){
        var l_tr = document.createElement("tr");

        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.innerHTML = "";

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.style.color = "#4D87D8";
        l_td.style.fontWeight = "bold";
        l_td.innerHTML = a_title;

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.style.color = "#ffffff";
        l_td.innerHTML = "(" + a_description + ")";

        l_tr.style.cursor = "pointer";
        addEvent(l_tr, "click", function(){ GBL.MAIN_TABS.switchToTab(a_tabIndex); });

        return l_tr;
    }
}

function MobFAQDiv(a_parentDiv){

    var m_parentDiv = a_parentDiv;
    var m_containerDiv = undefined;

    if(m_parentDiv != undefined){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;

        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);
        m_containerDiv.style.color = "#000000";

        var l_faq = "<iframe src='http://sns.fontera.net/myspace/counterstrike/recruited.php?buID="+UserID+"' height='1200' width='800' frameborder='0'></iframe>";
                 
        m_containerDiv.innerHTML = l_faq;
    }
}


