/**
 * @author killer10: Georgiy Chipunov
 * 
 * 
 * Gnome Game : for opensocial applications on myspace
 * 
 * 
 */



var os;
var dataReqObj;

var html = '';
var heading = '';

var REQUEST_DESTINATION_URL = "http://crime.servegame.com/gnomewars/WebService.asmx";
var paramSHOW_USER_ID = "ShowUserProfile";
 
 
    var g_UserID = '';
	var g_UserDisplayName = '';
	var g_UserTN = '';
	var g_UserAge = '';
	var g_UserGender = '';
	var g_UserProfile = '';
	var appURLAT = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=117812"
	/*
	 * Timers
	 * 
	 */
	var g_secHealth=0; 
	var g_secStamina=0;
	var g_secEnergy=0;
	var	g_constsecHealth = 30;
	var g_constsecStamina = 45;
	var g_constsecEnergy = 60;
	
	var g_playSeconds = false;
	
	 var gUserClass_nameArray = new Array();
	 var gUserClass_descArray = new Array();
	 var gUserClass_idArray = new Array();
	 
	 
	 var g_DivMainTabs = undefined;
	 var g_DivViewerStatus = undefined;
	 
	 var g_app_install_state = undefined;
	 
	 
	 var GBL = {};

    GBL.APP_CANVAS_URL = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=117812&";
    GBL.APP_ERROR_MSG = "Sorry, Some Eror has occurred please refresh<BR><iframe frameborder='0' scrolling='no' marginheight='0' marginwidth='0' width='300' height='250' src='http://www.adparlor.com/serveIFrameAd.aspx?appId=1663706&adtype=7&age=<>&gender=<>&maritalStatus=<>&adTBG=000000&adTColor=FFFFFF&adCntColor=000000&adBG=FFFFFF' id='AdParlorAd'></iframe><BR>";

	     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 = "ShowUserProfile";
	GBL.SHOW_MASTERMIND ="ShowMastermind";
	GBL.SHOW_ORGANIZATION ="ShowOrganization";
	
	     function customEncoding(a_text) {
        return "cstm_" + encodeURIComponent(a_text).replace(/%/g, "@");
	 //  return encodeURIComponent(a_text).replace(/%/g, "@");
    }
	 
	// CSS Code
		function setCSSStyle(obj,style,value){
		getRef(obj).style[style]= value;
	}
	
		function getRef(obj){
		return (typeof obj == "string") ?
			 document.getElementById(obj) : obj;
	}
	
	
	
	


    function customEncoding(a_text) {
        return "cstm_" + encodeURIComponent(a_text).replace(/%/g, "@");
    }

    function makePostRequest(a_url, a_callback, a_param) {
        makeXMLNotCachedRequest(a_url, a_callback, a_param, true);
    }


    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";
            }
        }

       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);
    }

    var XML_REQUEST_QUEUE = new XMLRequestQueue();
    XMLRequestQueue.DO_POST = 1;
    XMLRequestQueue.DO_GET = 2;
    XMLRequestQueue.MAX_RETRIES = 1;
    XMLRequestQueue.MAX_TIMEOUT = 200000;
    XMLRequestQueue.PREEMPT_REQUESTS = false;

    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))
                    l_tempCallback(undefined);
               makeNewRequest();

           } else {
               doRequest();
           }
        }

        function retryRequest(){
           m_cur_retries += 1;
           outputDebug("retrying " + m_cur_url + " " + 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);
            }

            if(!isValid(a_response.data) && !isValid(a_response.text)){
                outputDebug(" response is not valid");
                retryRequest();

            } else{
                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){
            outputAlert("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 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 addEvent2(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(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 + "..";
        }
    }




     // 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;
    }









var V_LIBRARY_OS_CONTAINER = opensocial.Container.get();
var MS_OS_TOKEN = MyOpenSpace.MySpaceContainer.OSToken;


/////////////////////////////////////////////////////////
// utility functions
/////////////////////////////////////////////////////////

function isPostToTargetLive(){
    var supported = V_LIBRARY_OS_CONTAINER.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_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();
    V_LIBRARY_OS_CONTAINER.postTo(MS_OS_TOKEN, l_message, a_targetUser, a_postToCallback);
}


function sendComment(a_targetUser, a_content, a_postToCallback){

    var l_message;
	l_message = opensocial.newMessage(a_content);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.COMMENTS);

    goToPageTop();
    V_LIBRARY_OS_CONTAINER.postTo(MS_OS_TOKEN, l_message, a_targetUser, a_postToCallback);
}


function sendCommentWOGoToPageTop(a_targetUser, a_content, a_postToCallback){

    var l_message;
	l_message = opensocial.newMessage(a_content);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.COMMENTS);

    V_LIBRARY_OS_CONTAINER.postTo(MS_OS_TOKEN, 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_message;
	l_message = opensocial.newMessage(a_content);
    l_message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.PROFILE);

    goToPageTop();
    V_LIBRARY_OS_CONTAINER.postTo(MS_OS_TOKEN, l_message, a_targetUser, a_postToCallback);
}

function postToBlog(a_targetUser, a_subject, a_content, a_postToCallback){

    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();
    V_LIBRARY_OS_CONTAINER.postTo(MS_OS_TOKEN, l_message, a_targetUser);
}

function postToBulletin(a_targetUser, a_subject, a_content, a_postToCallback){

    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();
    V_LIBRARY_OS_CONTAINER.postTo(MS_OS_TOKEN, l_message, a_targetUser, a_postToCallback);
}

function postToBulletinWOGoToPageTop(a_targetUser, a_subject, a_content, a_postToCallback){
    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);

    V_LIBRARY_OS_CONTAINER.postTo(MS_OS_TOKEN, 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;
		this.m_city = undefined;
		this.m_region = undefined;
		this.m_country = undefined;
		this.m_zipcode = undefined;
		
        // specific to crime
        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_adrenaline = undefined;
		this.m_maxAdrenaline = 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;

        // 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_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);
		this.m_city = a_osUserData.getField("CITY");
		this.m_region = a_osUserData.getField("REGION");
		this.m_zipcode = a_osUserData.getField("POSTALCODE") ;
		this.m_country = a_osUserData.getField("COUNTRY") ;
		
		
    }

    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){};
      
	  try{this.m_city = getXMLEncodedStringNodeValue(a_userInfoNode, "city"); }catch(err){};
	  try{this.m_region = getXMLEncodedStringNodeValue(a_userInfoNode, "region"); }catch(err){};
	  try{this.m_zipcode = getXMLEncodedStringNodeValue(a_userInfoNode, "postalcode"); }catch(err){};
	  try{this.m_country = getXMLEncodedStringNodeValue(a_userInfoNode, "country"); }catch(err){};
	  
	  
	  
	   this.fillSpecificInfoFromXML(a_userInfoNode);
    }


    User.prototype.constructParamForReq = function() {
        var l_params = {};
		outputDebug("User.prototype.constructParamForReq");
		
        l_params.NetworkID = this.m_userId;
		l_params.City = "";
		
           
       l_params.gender = "";;
        l_params.thumbnail_url = "";;
        l_params.ProfileURL = "";;
         l_params.displayname ="";;
		
		//if (isValid(this.m_city))
		
		 l_params.region = "";
		 l_params.zipcode = "";
		 l_params.country ="";
	
	
		l_params.NetworkType = 2;
		
		l_params.City = "Wtf";
		
		
        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.ProfileURL = this.m_profile_url;
      //  if (isValid(this.m_name)) l_params.displayname = customEncoding(this.m_name);
		
		//if (isValid(this.m_city))
		
		if (isValid(this.m_region)) l_params.region = this.m_region;
		if (isValid(this.m_zipcode)) l_params.zipcode = this.m_zipcode;
		if (isValid(this.m_country)) l_params.country = this.m_country;
		//l_params.countrya = "eyg3";
	//	 l_params.wtf ="wtf";  
		//		this.m_city =a_osUserData.getField(opensocial.Person.Field.CITY);
	//	this.m_region = a_osUserData.getField(opensocial.Person.Field.REGION);
	//	this.m_zipcode = a_osUserData.getField(opensocial.Person.Field.POSTALCODE);
	//	this.m_country = a_osUserData.getField(opensocial.Person.Field.COUNTRY);
		
        return l_params;
    }

    User.prototype.signInViewer = function(onFinishCallback) {
       if (isValid(this.m_userId)) {
           var l_params = this.constructParamForReq();
           l_params.sign_in = "true";
		  // User.prototype.constructParamForReq
		  
		  // http://www.bigideastech.com/crime/WebService.asmx//sign_in?user_id=152564710&age=24&gender=Male&thumbnail_url=http://a198.ac-images.myspacecdn.com/images01/30/s_34cae79d2c8824b5bca0d22dcab4f45d.jpg&profile_url=http://www.myspace.com/captchacrack&display_name=cstm_killer10&sign_in=true&session_id=ecc79e00cb10b5be627e5d87c3466e363f2e3ba1&nocache=1220907364247

		  
		   outputDebug("makeXMLNotCachedRequest("+REQUEST_DESTINATION_URL+"/CheckUserID");
           makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/CheckUserID", 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(){
        if(this.m_name.length < 12){
            return this.m_name;
        }
        return this.m_name.substring(0, 11)+"..";
    }

    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{ if(isValid(getXMLNodeValue(a_xmlNode,"userjailed"))) this.m_userjailed = getXMLNodeValue(a_xmlNode,"userjailed"); }catch(err){};
// m_userjailed

       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.getJailed = function(){
        return this.m_userjailed;
    }
	
    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.getRequestedByUser = function(){
        return getBooleanValue(this.m_requestedByUser);
    }

    ////////////////////////////////////////////////////////////
    // 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;
			case opensocial.Person.Field.CITY: return this.m_city;
			case opensocial.Person.Field.REGION: return this.m_region;
			case opensocial.Person.Field.POSTALCODE: return this.m_zipcode;
			case opensocial.Person.Field.COUNTRY: return this.m_country; 
			
	
		
        }
        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_owner){

    var m_owner = a_owner;
    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(isValid(l_queryIdString) && l_queryIdString.length > 0){
                var l_params = {};
                l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
				 l_params.NetworkType = "2";
                l_params.query_ids= l_queryIdString;
				
 makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetGameUsers",
           //     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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = "2";
        l_params.action = getActionURI(m_type);
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetNumUsers", 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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = "2";
		
        l_params.action = getActionURI(m_type);
        l_params.start = l_startIndex;
        l_params.num = l_numToFetch;

        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetOrgUsers", 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 init() {
     outputDebug("init called");
// var page = opensocial.getEnvironment().getParams()["page"];
// http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=XXXXX&appParams=%7B%22page%22%3A%22about%22%7D
/*
 * if (page == "about") {
    renderAboutPage();
  } else {
    renderNormalPage();
  }
  
  
  UA-5544836-1
  
 */
document.title="MySpace - Gnome Wars"
//document.title("MySpace - Crime");

gadgets.window.adjustHeight(5000);

    document.body.style.backgroundColor = "#000000";

    var l_headerFrame = document.getElementById("heading");
    if(isValid(l_headerFrame)){
        l_headerFrame.style.backgroundColor = "#000000";
        l_headerFrame.style.backgroundImage = "url(http://g.laasex.com/gnomeswars/images/UI/logo.jpg)";
        l_headerFrame.style.height = "70px";
        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_mainFrame = document.getElementById("main");
    if(isValid(l_mainFrame)){
        l_mainFrame.style.paddingLeft = "0px";
        l_mainFrame.style.paddingRight = "0px";
        l_mainFrame.style.backgroundColor = "#000000";
        l_mainFrame.style.backgroundImage = "url(http://g.laasex.com/gnomeswars/images/UI/logo2.jpg)";
      //  l_mainFrame.style.backgroundRepeat = "repeat-y";
      l_mainFrame.style.backgroundRepeat = "no-repeat";
        l_mainFrame.style.margin = "0px";
        l_mainFrame.style.padding = "10px 20px 0px 20px";
        l_mainFrame.style.height = "15000px";
        l_mainFrame.style.overflow = "auto";
        l_mainFrame.style.border = "none";
	//	l_mainFrame.innerHTML ="<iframe frameborder='0' scrolling='no' marginheight='0' marginwidth='0' width='645' height='75' src='http://www.adparlor.com/serveIFrameAd.aspx?appId=1251552&adtype=6&age=<>&gender=<>&maritalStatus=<>&adTBG=000000&adTColor=FFFFFF&adCntColor=000000&adBG=FFFFFF' id='AdParlorAd'></iframe>";
    }


    try{
        _uacct = "UA-5544836-1";
        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;
    }
	
   // document.getElementById('heading').innerHTML = 'Loading...';
   // document.getElementById('main').innerHTML = 'Loading...';
/*
    os = opensocial.Container.get();
    dataReqObj = os.newDataRequest();
	
	var param = {};
    param[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [MyOpenSpace.Person.Field.CITY, MyOpenSpace.Person.Field.MOOD, MyOpenSpace.Person.Field.GENDER];
	
	
    var viewerReq = os.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER,param);
	
	
	
    dataReqObj.add(viewerReq);
      
    dataReqObj.send(viewerResponse);
	*/
startGame();
}

function startGame(){
	outputDebug("startGame");
    var l_headerFrame = document.getElementById("heading");
    l_headerFrame.innerHTML = "";
    var l_mainFrame = document.getElementById("main");
    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>", "400px");
        GBL.MAIN_DATA = new CentralData(createGUI, l_loadStatusDiv);
    }
}


    function isValid(a_obj) {
        return (a_obj != undefined && a_obj != null);
    }

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://www.bigideastech.com/crime/images/UI/up_arrow2.gif";
    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 = "#000000";
    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;
    l_msgDiv.innerHTML = "You must add this application to continue!";



    document.body.style.backgroundColor = "#000000";
    document.body.style.backgroundImage = "url(http://g.laasex.com/gnomeswars/images/UI/gnome-wars-ss.jpg)";
    document.body.style.backgroundRepeat = "no-repeat";

    var l_headerFrame = document.getElementById("headerFrame");
    if(isValid(l_headerFrame)){
        l_headerFrame.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 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 = "1px";
        m_textDiv.style.borderColor = "#7f93bc";


		m_textDiv.style.backgroundImage = "url(http://www.bigideastech.com/crime/images/UI/carburn.jpg)";
		
        m_textDiv.innerHTML = m_messageText;
    }

    function getTextDiv(){
        return m_textDiv;
    }
}


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 = "#E7E610";
        m_buttonDiv.style.color = "black";
        m_buttonDiv.style.fontSize = "14px";
        m_buttonDiv.style.fontWeight = "bold";

        m_buttonDiv.style.borderLeft = "solid 1px #27A527";        
        m_buttonDiv.style.borderTop = "solid 1px #27A527";
        m_buttonDiv.style.borderRight = "solid 2px #27A527";
        m_buttonDiv.style.borderBottom = "solid 2px #27A527";

        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 0px 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<<"));
	  l_prevA.innerHTML = '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"));
	   l_numA.innerHTML = '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));
	      l_numA.innerHTML = l_pageNum.toString();
                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));
	       l_curNumSpan.innerHTML = l_pageNum.toString();
            }
        }


        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;
    }
}


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 = "1px";
        m_textDiv.style.borderColor = "#e2c822";

        m_textDiv.innerHTML = m_messageText;
    }

    function getContainerDiv(){
        return m_textDiv;
    }
}

function switchTabs(a_index){
    g_DivMainTabs.switchToTab(a_index);
}

function clickRefresh(){
	// refreshbutton
	setCSSStyle('refreshbutton','color','red');
	setCSSStyle('refreshbutton','background-color','rgb(85, 65, 79)');
	
	
	document.getElementById('refreshbutton').innerHTML = 'refreshing ...';
	GameRefresh();
}



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 = "#FFFFFF";
    l_div.style.textAlign = "left";
    return l_div;
}


function addHeaderStyle(a_element){
    a_element.style.borderLeft = "solid 1px #AAAAAA";
    a_element.style.borderTop = "solid 1px #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 1px #AAAAAA";
    l_div.style.borderTop = "solid 1px #AAAAAA";
    l_div.style.borderRight = "solid 2px #454545";
    l_div.style.borderBottom = "solid 2px #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 1px #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 1px #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_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);
            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";
        l_numTd.innerHTML = "<span style='font-weight:bold;'>" + l_itemData.number + " x </span>";


        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_div = createWhiteDiv(l_itemTd);
        l_div.style.fontSize = "11px";
        l_div.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 Gnome Name";
        this.m_chooseNameExplanation = "Choose your Gnome name (please be creative):";
        this.m_warningText = "<span style='color:#FF0000; fot-weight:bold;'> Warning! Please change your Gnome name. </span> <br> Users have complained that your player 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 Gnome Class";
        this.m_chooseClassExplanation = "Choose your gnome class:";

        this.m_classNameArray = new Array();
        this.m_classDescriptionsArray = new Array();

        this.m_classNameArray.push("Murderer");
        this.m_classDescriptionsArray.push("Murderer (Take More People out)");

        this.m_classNameArray.push("Paladin");
        this.m_classDescriptionsArray.push("Paladin (Can steal from other players)");

        this.m_classNameArray.push("Smith");
        this.m_classDescriptionsArray.push("Smith (Makes Weapons faster, and uses better)");
		
		this.m_classNameArray.push("Rage Roader");
        this.m_classDescriptionsArray.push("Rage Roader (Gets more damage from cars, and allows clans to do Car Quests)");

        this.m_classNameArray.push("Papa");
        this.m_classDescriptionsArray.push("Papa (Increases clan friends max size by 5)");
		
		
		
		this.m_classNameArray.push("Crazy");
        this.m_classDescriptionsArray.push("Crazy (Stamina Recreases faster)");

        this.m_classNameArray.push("Warrior");
        this.m_classDescriptionsArray.push("Warrior (Increased Weapon Skills)");
		
		this.m_classNameArray.push("Blinger");
        this.m_classDescriptionsArray.push("Blinger (Income is 10 Percent more.)");

        this.m_classNameArray.push("Healer");
        this.m_classDescriptionsArray.push("Healer (Increases health 2x faster)");
		
		this.m_classNameArray.push("Adverturer");
        this.m_classDescriptionsArray.push("Adverturer (Energy increases 10 faster, do more quests)");

     
    }

    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 DivButton(l_td, "Choose Name", function(){
            l_self.m_resultDiv.showMessage(undefined, "Checking ... ");

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			 l_params.NetworkType = "2"; 
            l_params.Name =encodeURIComponent(l_nameField.value);

          //  makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/choose_name",
		  makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/ChooseCrimeName",
                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 DivButton(l_td, "Choose", function(){
            l_self.m_resultDiv.showMessage(undefined, "Checking ... ");

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			 l_params.NetworkType ="2";
            for(var l_index = 0; l_index < l_options.length; l_index++){
                if(l_options[l_index].selected){
                    l_params.Class = l_options[l_index].value;
                    break;
                }
            }

        //    makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/choose_class",
		makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/ChooseCrimeClass",
                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 goToPageTop(){
   location.href = "#mainFrameTop";
}
function MobDoRefresh(){
    var l_params = {};
    l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
	l_params.NetworkType = "2";
    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.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(12) + "</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 = "#5556F7";
	//	l_statsTD.style.f
      //  l_statsTD.style.textDecoration = "underline";        
        l_statsTD.innerHTML = "My Profile";
l_statsTD.style.fontWeight="bold";


        
        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 1px #181ACD";
        this.m_refreshButtonDiv.style.border = "solid 1px #555565";
        this.m_refreshButtonDiv.style.backgroundColor = "#181ACD"
        this.m_refreshButtonDiv.style.paddingTop = "4px";
        this.m_refreshButtonDiv.style.paddingBottom = "4px";
        this.m_refreshButtonDiv.style.paddingLeft = "11px";
        this.m_refreshButtonDiv.style.paddingRight = "11px";
        this.m_refreshButtonDiv.style.color = "black";
        this.m_refreshButtonDiv.style.fontSize = "11px";
		this.m_refreshButtonDiv.style.fontWeight ="bold";
        this.m_refreshButtonDiv.innerHTML = "RELOAD";
        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 = "#555565"
                l_self.m_refreshButtonDiv.innerHTML = "reloading...";

                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 = "#181ACD"
		this.m_refreshButtonDiv.style.fontWeight ="bold";
        this.m_refreshButtonDiv.innerHTML = "RELOAD";

    }

    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 1px #AAAAAA";
        a_td.style.borderTop = "solid 1px #AAAAAA";
        a_td.style.borderRight = "solid 1px #000000";
        a_td.style.borderBottom = "solid 1px #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


//AdDiv
    function AdDiv(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.initialize();
        this.createDiv();
    }

    AdDiv.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();
    }


    AdDiv.prototype.createDiv = function(){
        this.m_containerDiv = document.createElement("div");
        this.m_parentDiv.appendChild(this.m_containerDiv);
        this.m_containerDiv.style.textAlign  = "center";

        this.refreshStatus();
    }


    AdDiv.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 = "<iframe frameborder='0' scrolling='no' marginheight='0' marginwidth='0' width='300' height='250' src='http://www.adparlor.com/serveIFrameAd.aspx?appId=1663706&adtype=7&age=<>&gender=<>&maritalStatus=<>&adTBG=000000&adTColor=FFFFFF&adCntColor=000000&adBG=FFFFFF' id='AdParlorAd'></iframe>";        
/*
        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 = "#5556F7";
	//	l_statsTD.style.f
      //  l_statsTD.style.textDecoration = "underline";        
        l_statsTD.innerHTML = "My Profile";
l_statsTD.style.fontWeight="bold";


        
        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 1px #181ACD";
        this.m_refreshButtonDiv.style.border = "solid 1px #555565";
        this.m_refreshButtonDiv.style.backgroundColor = "#181ACD"
        this.m_refreshButtonDiv.style.paddingTop = "4px";
        this.m_refreshButtonDiv.style.paddingBottom = "4px";
        this.m_refreshButtonDiv.style.paddingLeft = "11px";
        this.m_refreshButtonDiv.style.paddingRight = "11px";
        this.m_refreshButtonDiv.style.color = "black";
        this.m_refreshButtonDiv.style.fontSize = "11px";
		this.m_refreshButtonDiv.style.fontWeight ="bold";
        this.m_refreshButtonDiv.innerHTML = "RELOAD";
        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 = "#555565"
                l_self.m_refreshButtonDiv.innerHTML = "reloading...";

                window.setTimeout("GBL.STATUS_DIV.enableRefreshButton()", 1000);
                MobDoRefresh();
            }
        });  
        */
    }

    AdDiv.prototype.enableRefreshButton = function(){
        this.m_refreshButtonEnabled = true;
        this.m_refreshButtonDiv.style.cursor = "pointer";
        this.m_refreshButtonDiv.style.backgroundColor = "#181ACD"
		this.m_refreshButtonDiv.style.fontWeight ="bold";
        this.m_refreshButtonDiv.innerHTML = "RELOAD";

    }

    AdDiv.prototype.addLinkToMyMob = function(a_td){
        a_td.style.cursor = "pointer";
        addEvent(a_td, "click", function(){
            GBL.MAIN_TABS.switchToTab(9);
        });
    }


    AdDiv.prototype.addLinkToMyBoss = function(a_td){
        a_td.style.cursor = "pointer";
        addEvent(a_td, "click", function(){
            GBL.MAIN_TABS.switchToTab(10);
        });
    }


    AdDiv.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());
                    }
            );
        });
    }

    AdDiv.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";
    }


    AdDiv.prototype.addStandardStyle = function(a_td){
        a_td.style.borderLeft = "solid 1px #AAAAAA";
        a_td.style.borderTop = "solid 1px #AAAAAA";
        a_td.style.borderRight = "solid 1px #000000";
        a_td.style.borderBottom = "solid 1px #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";        
    }

    AdDiv.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 = "800";
        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) ;}
        if(isValid(this.m_secondsToHealth)){ this.m_secondsToHealth = parseInt(this.m_secondsToHealth) ;}
        if(isValid(this.m_secondsToStamina)){ this.m_secondsToStamina = parseInt(this.m_secondsToStamina) ;}


        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;
		 m_secondsToHealth = 50;
            }
            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;
		m_secondsToEnergy = 100;
            }
            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;
		m_secondsToStamina =80;
            }
            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.m_FromUserID = 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){};
   try{ this.m_FromUserID = getXMLEncodedStringNodeValue(this.m_xmlNode,"user_idfrom");}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;
    }
	   NewsFeedEntry.prototype.getUserIDFrom = function(){
        return this.m_FromUserID;
    }
	// 
//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 clan!";
    }

    NewsFeedDiv.prototype.createBulletinSubject = function(){
        return  "A broadcast to my Gnome Clan!";
    }

    NewsFeedDiv.prototype.createBulletin = function(a_msg){
        return  a_msg +
                "<br><br>------------------------------------------------------<br>" +
                "<a href='"+GBL.APP_CANVAS_URL+"track=command'>This message sent from: Gnome Wars. Start a gnome clan with your friends. Rise from a petty gnome to a gnome maniac. 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(100*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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
            l_params.message = customEncoding(l_commentMsg.getText());
			
            l_params.cost = (100*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+"/BroadCastMessage",
                                    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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType ="2";
		
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetNewsFeed", 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.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 = "Quests:";

        this.m_rewardHeader = "Description / Payout";
        this.m_requirementHeader = "Job Requires";
        this.m_actionHeader = "Do Job";

        this.m_nextLevelText = "Unlock more Quests when you reach level";

        this.m_doButtonText = "Do Quests";
        this.m_doingText = "Doing Quests... ";
    }

    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 1px #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 1px #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 1px #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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
            l_params.MissionID = a_job.getJobId();
			
			
            //makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/do_job",
			makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/DoMission",
                    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 = "Friends: "+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


// JobOrgListDiv
    function JobOrgListDiv(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);
    }

    JobOrgListDiv.prototype.initialize = function(){
        this.m_titleDiv = "Jobs:";

        this.m_rewardHeader = "Description / Payout";
        this.m_requirementHeader = "Job Requires";
        this.m_actionHeader = "Do Job";

        this.m_nextLevelText = "Unlock more jobs when you reach level";

        this.m_doButtonText = "Do Job";
        this.m_doingText = "Doing Job... ";
    }

    JobOrgListDiv.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();
    }

    JobOrgListDiv.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);
    }


    JobOrgListDiv.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);}
        }
    }


    JobOrgListDiv.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 1px #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 1px #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 1px #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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
            l_params.MissionID = a_job.getJobId();
			
			
            //makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/do_job",
			makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/DoMission",
                    function(a_response){
                        handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();});},
                    l_params, 0);
        });

        return l_tr;
    }

    JobOrgListDiv.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;
    }

    JobOrgListDiv.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 = "Friends: "+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 JobOrgListDiv




// JobClassListDiv
    function JobClassListDiv(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);
    }

    JobClassListDiv.prototype.initialize = function(){
        this.m_titleDiv = "Class Jobs:";

        this.m_rewardHeader = "Description / Payout";
        this.m_requirementHeader = "Job Requires";
        this.m_actionHeader = "Do Job";

        this.m_nextLevelText = "Unlock more jobs when you reach level";

        this.m_doButtonText = "Do Job";
        this.m_doingText = "Doing Job... ";
    }

    JobClassListDiv.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();
    }

    JobClassListDiv.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);
    }


    JobClassListDiv.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);}
        }
    }


    JobClassListDiv.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 1px #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 1px #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 1px #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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
            l_params.MissionID = a_job.getJobId();
			
			
            //makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/do_job",
			makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/DoMission",
                    function(a_response){
                        handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();});},
                    l_params, 0);
        });

        return l_tr;
    }

    JobClassListDiv.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;
    }

    JobClassListDiv.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 = "Friends: "+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 JobClassListDiv


// 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_ResidentialTitle = undefined;
		this.m_MilitaryTitle = undefined;
		
	//	this.m_MilitaryTitle = undefined;
		
        this.m_explanationText = undefined;
        this.m_cashFlowText = "Cash Flow";

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }


    CityListDiv.prototype.initialize = function(){                
      
		
		 this.m_undevelopedLandTitle = "Undeveloped";
		 this.m_IndustrialLandTitle = "Industrial";
		   this.m_ResidentialLandTitle = "Residential";
        this.m_CommercialsTitle = "Commercial";
		this.m_MilitaryTitle = "Military";
		// Military, 
		
        this.m_explanationText = "Buy up new territory to earn hourly income! First, purchase undeveloped land, then build on your land to earn even more. Once developed, a unit of land will be converted permanently to the establishment you build on it. Need more cash? <a class='standardLink' href='#' onclick='switchTabs(1);return false;'>Complete some Jobs</a>.";
    }

    CityListDiv.prototype.createTitle = function(a_optionTitles, a_optionCallbacks){
        createTitleDiv(this.m_titleDiv, "Your Land: <span style='font-size:14px'> (Income <span style='color:#00FF00'>$"+formatNumberWithCommas(GBL.MAIN_DATA.getViewer().getIncome())+"</span>, Upkeep From Equipment: <span style='color:#FF0000'>$"+formatNumberWithCommas(GBL.MAIN_DATA.getViewer().getUpkeep())+"</span> ) </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_ResidentialList = new PropertyListDiv(this.m_tableDiv, this.m_ResidentialLandTitle,   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_IndustrialList = new PropertyListDiv(this.m_tableDiv, this.m_IndustrialLandTitle,   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_CommercialsList = new PropertyListDiv(this.m_tableDiv, this.m_CommercialsTitle,   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_MilitaryList = new PropertyListDiv(this.m_tableDiv, this.m_MilitaryTitle,   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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = "2"; 
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetRealEstate", 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, "Residential_lands");
                var l_establishmentNodes = l_establishmentsNode.getElementsByTagName("land");
                for(var l_index = 0; l_index < l_establishmentNodes.length; l_index++){
                    this.m_ResidentialList.addProperty(new Property(l_establishmentNodes[l_index]));
                }
				// Industrial
				
		                var l_establishmentsNode = getXMLFirstNode(l_xmlDoc, "Industrial_lands");
                var l_establishmentNodes = l_establishmentsNode.getElementsByTagName("land");
                for(var l_index = 0; l_index < l_establishmentNodes.length; l_index++){
                    this.m_IndustrialList.addProperty(new Property(l_establishmentNodes[l_index]));
                }		
				
				
				var l_establishmentsNode = getXMLFirstNode(l_xmlDoc, "Commercial_lands");
                var l_establishmentNodes = l_establishmentsNode.getElementsByTagName("land");
                for(var l_index = 0; l_index < l_establishmentNodes.length; l_index++){
                    this.m_CommercialsList.addProperty(new Property(l_establishmentNodes[l_index]));
                }
				
				
				var l_establishmentsNode = getXMLFirstNode(l_xmlDoc, "Military_lands");
                var l_establishmentNodes = l_establishmentsNode.getElementsByTagName("land");
                for(var l_index = 0; l_index < l_establishmentNodes.length; l_index++){
                    this.m_MilitaryList.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; font-size:26px;'> Unlock more Real Estate 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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		 l_params.NetworkType = "2";
        l_params.LandID = a_buyId;
        l_params.amount = a_amount;

        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyRealEstate",
                        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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
	    l_params.NetworkType = "2";
       l_params.LandID = a_sellId;
	   
       l_params.amount = -a_amount;

       var l_self = this;
       makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyRealEstate",
                        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 1px #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 1px #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, 25, "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, 25, "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_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_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, "The "+this.m_bankName+" (Open an Account)");

        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 = "Open an account with: ";


        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 DivButton(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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
            l_params.amount = l_amountField.value;
			
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/DepositBank",
                    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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
            l_params.amount = l_amountField.value;
			
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/DepositBank",*/
                var l_params = {};
                l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
                l_params.NetworkType = "2";
				l_params.amount = -l_amountField.value;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/DepositBank",
                        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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
                l_params.NetworkType = "2";
				l_params.amount = l_amountField.value;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/DepositBank",
                        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 = "Papa Gnomes's Offer";

        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 = "Buy offers below to earn gnome points from Papa Gnome. In return for gnome points, The Papa Gnome will offer you various rewards such as cash, items, territory, and more gnome clan members.*<br/><br/><font size='2'>*Gnome 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 Papa Gnome offers you $" + formatNumberWithCommas(10000*GBL.MAIN_DATA.getViewer().getLevel()) + " for 10 gnome points.");
        this.m_offerCosts.push(10);

        this.m_offerKeys.push("maxfriends");
        this.m_offerDescriptions.push("The Papa Gnome offers you 1 hired gnome expert for 20 gnome points.");
        this.m_offerCosts.push(20);

        this.m_offerKeys.push("energy");
        this.m_offerDescriptions.push( "The Papa Gnome offers you full energy (refill) for 10 gnome points.");
        this.m_offerCosts.push(10);

        this.m_offerpalConstructor = OfferPalDiv;
    }

    GodfatherDiv.prototype.createTitle = function(a_title){
   
	  var l_snuid = GBL.MAIN_DATA.getViewer().getUserId();
	  
        var l_offerPalCS = "<span onclick='window.open(\"http://pub.myofferpal.com/c30afa6b9a7d0cc4753a4d25a908280c/userstatus.action?snuid="+l_snuid+"\",'_self'); return false;' style='text-decoration:underline; cursor:pointer; font-size:13px; color:#EEEEEE;'> Missing Gnome Points, click here! </span>";
     //   createTitleDiv(a_title, "The Papa Gnome: <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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
			
            l_params.reward = a_offerStr;
			
			
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/AcceptMasterMind",
                    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 = "Buy Gnome Points";

        this.m_offerPalLink = undefined;

        this.initialize();
        this.createDiv();
    }

    OfferPalDiv.prototype.initialize = function(){
 
	    var l_snuid = GBL.MAIN_DATA.getViewer().getUserId();
		
       var l_offerPalCS = "<span onclick='window.open(\"http://pub.myofferpal.com/c30afa6b9a7d0cc4753a4d25a908280c/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 Gnome points and help sponsor this application by completing offers! <br> "  ;
        this.m_offerPalLink = "http://pub.myofferpal.com/c30afa6b9a7d0cc4753a4d25a908280c/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());

        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='http://www.bigideastech.com/crime/iframepaypal.aspx?NetworkID="+ GBL.MAIN_DATA.getViewer().getUserId() +"'>";
		
        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 Other Gnomes!";
        this.m_mobNameLabel = "Gnome";
        this.m_mobSizeLabel = "Clan Size";
        this.m_mobActionLabel = "Action";
        this.m_emptyMessage = "There are no other gnomes around your level to fight. You should check the gnome land again in a couple minutes. Why not <a class='standardLink' href='#' onclick='switchTabs(1);return false;'>complete some Quests</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 Gnome list... please wait  </span>";


        var l_params = {};
        l_params.attacteruserid = GBL.MAIN_DATA.getViewer().getUserId();
        var l_self = this;
    //    makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/get_fight_list", function(a_responseData){
	 makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetFightList", 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 = "<a target=\"_blank\" href=\""+ GBL.APP_CANVAS_URL + "appParams=%7B%22"+GBL.SHOW_USER_ID+"%22%3A%22"+a_targetUser.getUserId()+"%22%7D\" >" + "<span style='color:#3E99C3; font-weight:bold;'> <img width=\"50\" height=\"50\" src=\'" + a_targetUser.getThumbnailUrl() + "\'/>" + a_targetUser.getMobName() + " </span>, Level " + a_targetUser.getLevel() + " " + a_targetUser.getMobClass() + "</span></a>";
        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.attacteruserid = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.attackeduserid = a_targetUser.getUserId();
					   l_params.attacteruseridNetwork ="2";
		   l_params.attackeduseridNetwork="2";
		   
            l_params.level = GBL.MAIN_DATA.getViewer().getLevel();
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetAttackFight",
                    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 gnome 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 = "You won the fight"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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = 2;
        l_params.TargetNetworkID = this.m_targetUser.getUserId();
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetHitlistMinPay",
                function(a_response){ l_self.createBountyInterface(a_response, true);},
                l_params);

    }

    HitListBountyDiv.prototype.refresh = function(){
        this.m_refreshDiv.innerHTML = "";

        var l_params = {};
           l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = 2;
        l_params.TargetNetworkID = this.m_targetUser.getUserId();
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetHitlistMinPay",
                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;
		
		var l_minCostOneday = undefined;
var l_minCostSevenday = undefined;

        try{
            l_minCost = getXMLNodeValue(l_xmlDoc, "min_cost");
			l_minCostOneday =  getXMLNodeValue(l_xmlDoc, "min_1_day_cost");
			l_minCostSevenday =  getXMLNodeValue(l_xmlDoc, "min_7_day_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 $"+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 $"+ l_minCost + " to put " + this.m_targetUser.getMobName() + " on the bad 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_tr2 = document.createElement("tr");
        l_contentTBody.appendChild(l_tr2);
		
        var l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.color = "#FFFFFF";
        l_td.innerHTML = "Bad 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_td2 = document.createElement("td");
        l_tr2.appendChild(l_td2);
        l_td2.style.color = "#FFFFFF";
		/*
		 *   var l_minCost = undefined;
var l_minCostSevenday = undefined;
		 
        l_td2.innerHTML = "<b>Hit List 1 Day Listing 50 kill limit count Amount: " + l_minCostOneday;
l_td2.innerHTML += "<BR>Hit List 7 Day Listing 200 kill limit count  Amount: " + l_minCostSevenday + "</b>";
*/
        var l_self = this;
        new DivButton(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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType ="2";
            l_params.TargetNetworkID = l_self.m_targetUser.getUserId();
            l_params.amount = l_amountField.value;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/AddHitList",
                    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 = "The Bad List";
        this.m_explanationText = "Make a hit on a gnome 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 gnome to the bad list below by clicking &quot;Add To Bad List&quot; on their gnome profile page.";
        this.m_emptyMessage = "The bad list is currently empty. Check back often for marked men that you can earn a bounty on!";
        this.m_targetLabel = "The Bad Gnome";
        this.m_actionLabel = "Attack Gnome";
    }

    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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType ="2";
        l_params.level = GBL.MAIN_DATA.getViewer().getLevel();
		
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetHitList", 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 = "<a target=\"_blank\" href=\""+ GBL.APP_CANVAS_URL + "appParams=%7B%22"+GBL.SHOW_USER_ID+"%22%3A%22"+a_targetUser.getUserId()+"%22%7D\" >" + "<span style='color:#3E99C3; font-weight:bold;'> " + a_targetUser.getMobName() + " </span></a>";
        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 target=\"_blank\" href=\""+ GBL.APP_CANVAS_URL + "appParams=%7B%22"+GBL.SHOW_USER_ID+"%22%3A%22"+a_paidUser.getUserId()+"%22%7D\" >" +"<span style='color:#3E99C3; font-weight:bold;'> " + a_paidUser.getMobName() + " </span></a>";
        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.attacteruserid = GBL.MAIN_DATA.getViewer().getUserId();
            l_params.attackeduserid = a_targetUser.getUserId();
					   l_params.attacteruseridNetwork ="2";
		   l_params.attackeduseridNetwork="2";
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetAttackFight",
                    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_itemtype = 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_itemtype = getXMLNodeValue(this.m_xmlNode,"itemtype");}catch(err){};
       try{ this.m_imageURL = getXMLEncodedStringNodeValue(this.m_xmlNode,"image_url");}catch(err){};
	   
	    try{ this.m_imageURLOver = getXMLEncodedStringNodeValue(this.m_xmlNode,"imageover_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.getItemType = function(){
        return this.m_itemtype;
    }
	
    RPGItem.prototype.getImageURL = function(){
        return this.m_imageURL;
    }
    RPGItem.prototype.getImageOverURL = function(){
        return this.m_imageURLOver;
    }
	
    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;

      var s_nameelement ="weapon";

        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();},s_nameelement);

        
        var l_params = {};
        l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = '2';
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetMyStuff",
                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");
				
		       // var l_inventoryNode2 = getXMLFirstNode(l_xmlDoc, "weapon");
				
                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


//MobStockPileDiv
  //MobStockPileDiv
    function StockPileNewDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;
	this.Wimg = undefined;
	this.Aimg = undefined;
	this.Bimg = undefined;
	this.Cimg = undefined;
	this.Dimg = undefined;
	this.Fimg = undefined;
this.Gimg = undefined;

        this.m_mobInventoryDiv = undefined;
        this.m_mobItemsDiv = undefined;

        this.m_mobInventoryConstructor = InventoryDiv;
        this.m_mobItemsConstructor = ItemsDiv;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    StockPileNewDiv.prototype.initialize = function(_a_parentDiv){
    }

    StockPileNewDiv.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 = "left";
	
	
	 this.Wimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Wimg);
	 this.Wimg.style.textAlign = "left";
	
	
		 this.Aimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Aimg);
	 this.Aimg.style.textAlign = "left";
	 
	 	 this.Bimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Bimg);
	 this.Bimg.style.textAlign = "left";
	 
	 	 this.Cimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Cimg);
	 this.Cimg.style.textAlign = "left";
	 
	 	 this.Dimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Dimg);
	 this.Dimg.style.textAlign = "left";
	 
	 	 this.Eimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Eimg);
	 this.Eimg.style.textAlign = "left";
	 
	//this.Wimg = document.createElement("img");
	//this.Wimg.src="http://www.bigideastech.com/crime/images/UI/weapons2.jpg");
	
	
	// "<img style='margin-left:auto; margin-right:auto;' src='"+a_item.getImageURL()+"'/>";
	
	// this.m_refreshDiv.appendChild(this.Wimg);
	
	 this.m_refreshDiv.innerHTML = "<h2>Choose Shops Category</h2> ";
 
  this.Wimg.innerHTML = "<BR><BR><h3>Weapons</h3><BR><img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/weapons3.jpg'/>  ";
 
 this.Aimg.innerHTML = "<h3>Armor</h3><BR><img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/armor2.jpg'/> ";

this.Bimg.innerHTML = "<h3>Vehicles</h3><BR><img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/vehicles2.jpg'/> ";

this.Cimg.innerHTML = "<h3>Items</h3><BR><img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/items2.jpg'/> ";




addEvent(this.Wimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivWeapons(a_contentDiv);
		});; });

addEvent(this.Aimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivArmor(a_contentDiv);
		});; });

addEvent(this.Bimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivVehicles(a_contentDiv);
		});; });

addEvent(this.Cimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = ""; 
			new StockPileDivItems(a_contentDiv);
		});; });
       // this.refresh();
    }

    StockPileNewDiv.prototype.refresh = function(){

        var l_self = this;

      var s_nameelement ="weapon";

        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();},s_nameelement);

        
        var l_params = {};
        l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = '2';
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetMyStuff",
                function(a_responseData){
                    l_self.onGetStockpile(a_responseData);
                },l_params);
    }


    StockPileNewDiv.prototype.onGetStockpile = function(a_responseData){

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_inventoryNode = getXMLFirstNode(l_xmlDoc, "inventory");
				
		       // var l_inventoryNode2 = getXMLFirstNode(l_xmlDoc, "weapon");
				
                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 StockPileNewDiv


//MobStockPileDiv
    function StockPileDivVehicles(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

	this.Wimg = undefined;
	this.Aimg = undefined;
	this.Bimg = undefined;
	this.Cimg = undefined;
	this.Dimg = undefined;
	this.Fimg = undefined;
this.Gimg = undefined;

this.m_contentTequimentMenuBody  = undefined;



        this.m_mobInventoryDiv = undefined;
        this.m_mobItemsDiv = undefined;

        this.m_mobInventoryConstructor = InventoryDiv;
        this.m_mobItemsConstructor = ItemsVehicleDiv;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    StockPileDivVehicles.prototype.initialize = function(_a_parentDiv){
    }

    StockPileDivVehicles.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";

    var l_contentTableEquipmentMenu = document.createElement("table");
		
		
		
		
		
         this.m_containerDiv.appendChild(l_contentTableEquipmentMenu);
        l_contentTableEquipmentMenu.style.marginLeft = "auto";
        l_contentTableEquipmentMenu.style.marginRight = "auto";
        l_contentTableEquipmentMenu.style.marginTop = "5px";
        l_contentTableEquipmentMenu.style.cellSpacing = "0px";
        l_contentTableEquipmentMenu.style.borderCollapse = "collapse";
        this.m_contentTequimentMenuBody = document.createElement("tbody");
        l_contentTableEquipmentMenu.appendChild(this.m_contentTequimentMenuBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTequimentMenuBody.appendChild(l_headerTR);

       // var l_td = document.createElement("td");
      //  l_headerTR.appendChild(l_td);
       // addHeaderStyleWithInnerDiv(l_td, "Weapons", "500px");




	 this.Wimg = document.createElement("td");
         l_headerTR.appendChild(this.Wimg);
	// this.m_containerDiv.appendChild(this.Wimg);
	 this.Wimg.style.textAlign = "center";
	this.Wimg.style.cursor = "pointer";
	
		 this.Aimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Aimg);
	 this.Aimg.style.textAlign = "center";
	 this.Aimg.style.cursor = "pointer";
          this.Bimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Bimg);
	 this.Bimg.style.textAlign = "center";
         this.Bimg.style.cursor = "pointer";
          this.Cimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Cimg);
	 this.Cimg.style.textAlign = "center";
         this.Cimg.style.cursor = "pointer";
          this.Dimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Dimg);
	 this.Dimg.style.textAlign = "center";
         this.Dimg.style.cursor = "pointer";
         
         /*
	 	 this.Bimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Bimg);
	 this.Bimg.style.textAlign = "left";
	 
	 	 this.Cimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Cimg);
	 this.Cimg.style.textAlign = "left";
	 
	 	 this.Dimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Dimg);
	 this.Dimg.style.textAlign = "left";
	 
	 	 this.Eimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Eimg);
	 this.Eimg.style.textAlign = "left";
         */
	//this.Wimg = document.createElement("img");
	//this.Wimg.src="http://www.bigideastech.com/crime/images/UI/weapons2.jpg");
	
	
	// "<img style='margin-left:auto; margin-right:auto;' src='"+a_item.getImageURL()+"'/>";
	
	// this.m_refreshDiv.appendChild(this.Wimg);
	
	// this.m_refreshDiv.innerHTML = "<h2>Choose Shops Category</h2> ";
 
  this.Wimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/weapons.jpg'/>  ";
 
 this.Aimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/armor.jpg'/> ";

this.Bimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/vehicles.jpg'/> ";

this.Cimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/items.jpg'/> ";




addEvent(this.Wimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivWeapons(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Aimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivArmor(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Bimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivVehicles(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Cimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = ""; 
			new StockPileDivItems(a_contentDiv); new AdDiv2(a_contentDiv);
});; });




        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();
    }

    StockPileDivVehicles.prototype.refresh = function(){

        var l_self = this;
var s_nameelement ="vehicle";

        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();},s_nameelement);

        
        var l_params = {};
        l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = '2';
		l_params.Type = '2';
        var l_self = this;
	
	
	
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetMyStuff2",
                function(a_responseData){
                    l_self.onGetStockpile(a_responseData);
                },l_params);
    }


    StockPileDivVehicles.prototype.onGetStockpile = function(a_responseData){

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_inventoryNode = getXMLFirstNode(l_xmlDoc, "inventory");
				
		       // var l_inventoryNode2 = getXMLFirstNode(l_xmlDoc, "weapon");
				
                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


// ItemsArmorDiv
//StockPileDivArmor
    function StockPileDivArmor(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;


	this.Wimg = undefined;
	this.Aimg = undefined;
	this.Bimg = undefined;
	this.Cimg = undefined;
	this.Dimg = undefined;
	this.Fimg = undefined;
this.Gimg = undefined;

this.m_contentTequimentMenuBody  = undefined;


        this.m_mobInventoryDiv = undefined;
        this.m_mobItemsDiv = undefined;

        this.m_mobInventoryConstructor = InventoryDiv;
        this.m_mobItemsConstructor = ItemsArmorDiv;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    StockPileDivArmor.prototype.initialize = function(_a_parentDiv){
    }

    StockPileDivArmor.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";

    var l_contentTableEquipmentMenu = document.createElement("table");
		
		
		
		
		
         this.m_containerDiv.appendChild(l_contentTableEquipmentMenu);
        l_contentTableEquipmentMenu.style.marginLeft = "auto";
        l_contentTableEquipmentMenu.style.marginRight = "auto";
        l_contentTableEquipmentMenu.style.marginTop = "5px";
        l_contentTableEquipmentMenu.style.cellSpacing = "0px";
        l_contentTableEquipmentMenu.style.borderCollapse = "collapse";
        this.m_contentTequimentMenuBody = document.createElement("tbody");
        l_contentTableEquipmentMenu.appendChild(this.m_contentTequimentMenuBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTequimentMenuBody.appendChild(l_headerTR);

       // var l_td = document.createElement("td");
      //  l_headerTR.appendChild(l_td);
       // addHeaderStyleWithInnerDiv(l_td, "Weapons", "500px");




	 this.Wimg = document.createElement("td");
         l_headerTR.appendChild(this.Wimg);
	// this.m_containerDiv.appendChild(this.Wimg);
	 this.Wimg.style.textAlign = "center";
	this.Wimg.style.cursor = "pointer";
	
		 this.Aimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Aimg);
	 this.Aimg.style.textAlign = "center";
	 this.Aimg.style.cursor = "pointer";
          this.Bimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Bimg);
	 this.Bimg.style.textAlign = "center";
         this.Bimg.style.cursor = "pointer";
          this.Cimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Cimg);
	 this.Cimg.style.textAlign = "center";
         this.Cimg.style.cursor = "pointer";
          this.Dimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Dimg);
	 this.Dimg.style.textAlign = "center";
         this.Dimg.style.cursor = "pointer";
         
         /*
	 	 this.Bimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Bimg);
	 this.Bimg.style.textAlign = "left";
	 
	 	 this.Cimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Cimg);
	 this.Cimg.style.textAlign = "left";
	 
	 	 this.Dimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Dimg);
	 this.Dimg.style.textAlign = "left";
	 
	 	 this.Eimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Eimg);
	 this.Eimg.style.textAlign = "left";
         */
	//this.Wimg = document.createElement("img");
	//this.Wimg.src="http://www.bigideastech.com/crime/images/UI/weapons2.jpg");
	
	
	// "<img style='margin-left:auto; margin-right:auto;' src='"+a_item.getImageURL()+"'/>";
	
	// this.m_refreshDiv.appendChild(this.Wimg);
	
	// this.m_refreshDiv.innerHTML = "<h2>Choose Shops Category</h2> ";
 
  this.Wimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/weapons.jpg'/>  ";
 
 this.Aimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/armor.jpg'/> ";

this.Bimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/vehicles.jpg'/> ";

this.Cimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/items.jpg'/> ";




addEvent(this.Wimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivWeapons(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Aimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivArmor(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Bimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivVehicles(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Cimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = ""; 
			new StockPileDivItems(a_contentDiv); new AdDiv2(a_contentDiv);
});; });



        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();
    }

    StockPileDivArmor.prototype.refresh = function(){

        var l_self = this;
var s_nameelement ="vehicle";

        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();},s_nameelement);

        
        var l_params = {};
        l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = '2';
		l_params.Type = '3';
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetMyStuff2",
                function(a_responseData){
                    l_self.onGetStockpile(a_responseData);
                },l_params);
    }


    StockPileDivArmor.prototype.onGetStockpile = function(a_responseData){

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_inventoryNode = getXMLFirstNode(l_xmlDoc, "inventory");
				
		       // var l_inventoryNode2 = getXMLFirstNode(l_xmlDoc, "weapon");
				
                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


//StockPileDivWeapons
    function StockPileDivWeapons(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;

	this.Wimg = undefined;
	this.Aimg = undefined;
	this.Bimg = undefined;
	this.Cimg = undefined;
	this.Dimg = undefined;
	this.Fimg = undefined;
this.Gimg = undefined;

this.m_contentTequimentMenuBody  = undefined;

        this.m_mobInventoryDiv = undefined;
        this.m_mobItemsDiv = undefined;

        this.m_mobInventoryConstructor = InventoryDiv;
        this.m_mobItemsConstructor = ItemsWeaponsDiv;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    StockPileDivWeapons.prototype.initialize = function(_a_parentDiv){
    }

    StockPileDivWeapons.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";



        var l_contentTableEquipmentMenu = document.createElement("table");
		
		
		
		
		
         this.m_containerDiv.appendChild(l_contentTableEquipmentMenu);
        l_contentTableEquipmentMenu.style.marginLeft = "auto";
        l_contentTableEquipmentMenu.style.marginRight = "auto";
        l_contentTableEquipmentMenu.style.marginTop = "5px";
        l_contentTableEquipmentMenu.style.cellSpacing = "0px";
        l_contentTableEquipmentMenu.style.borderCollapse = "collapse";
        this.m_contentTequimentMenuBody = document.createElement("tbody");
        l_contentTableEquipmentMenu.appendChild(this.m_contentTequimentMenuBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTequimentMenuBody.appendChild(l_headerTR);

       // var l_td = document.createElement("td");
      //  l_headerTR.appendChild(l_td);
       // addHeaderStyleWithInnerDiv(l_td, "Weapons", "500px");




	 this.Wimg = document.createElement("td");
         l_headerTR.appendChild(this.Wimg);
	// this.m_containerDiv.appendChild(this.Wimg);
	 this.Wimg.style.textAlign = "center";
	this.Wimg.style.cursor = "pointer";
	
		 this.Aimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Aimg);
	 this.Aimg.style.textAlign = "center";
	 this.Aimg.style.cursor = "pointer";
          this.Bimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Bimg);
	 this.Bimg.style.textAlign = "center";
         this.Bimg.style.cursor = "pointer";
          this.Cimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Cimg);
	 this.Cimg.style.textAlign = "center";
         this.Cimg.style.cursor = "pointer";
          this.Dimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Dimg);
	 this.Dimg.style.textAlign = "center";
         this.Dimg.style.cursor = "pointer";
         
         /*
	 	 this.Bimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Bimg);
	 this.Bimg.style.textAlign = "left";
	 
	 	 this.Cimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Cimg);
	 this.Cimg.style.textAlign = "left";
	 
	 	 this.Dimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Dimg);
	 this.Dimg.style.textAlign = "left";
	 
	 	 this.Eimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Eimg);
	 this.Eimg.style.textAlign = "left";
         */
	//this.Wimg = document.createElement("img");
	//this.Wimg.src="http://www.bigideastech.com/crime/images/UI/weapons2.jpg");
	
	
	// "<img style='margin-left:auto; margin-right:auto;' src='"+a_item.getImageURL()+"'/>";
	
	// this.m_refreshDiv.appendChild(this.Wimg);
	
	// this.m_refreshDiv.innerHTML = "<h2>Choose Shops Category</h2> ";
 
  this.Wimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/weapons.jpg'/>  ";
 
 this.Aimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/armor.jpg'/> ";

this.Bimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/vehicles.jpg'/> ";

this.Cimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/items.jpg'/> ";




addEvent(this.Wimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivWeapons(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Aimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivArmor(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Bimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivVehicles(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Cimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = ""; 
			new StockPileDivItems(a_contentDiv); new AdDiv2(a_contentDiv);
});; });

        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();
}

    StockPileDivWeapons.prototype.refresh = function(){

        var l_self = this;
var s_nameelement ="vehicle";

        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();},s_nameelement);

        
        var l_params = {};
        l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = '2';
                l_params.Type = '1';
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetMyStuff2",
                function(a_responseData){
                    l_self.onGetStockpile(a_responseData);
                },l_params);
    }


    StockPileDivWeapons.prototype.onGetStockpile = function(a_responseData){

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_inventoryNode = getXMLFirstNode(l_xmlDoc, "inventory");
				
		       // var l_inventoryNode2 = getXMLFirstNode(l_xmlDoc, "weapon");
				
                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


//StockPileDivWeapons
    function StockPileDivItems(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_refreshDiv = undefined;


	this.Wimg = undefined;
	this.Aimg = undefined;
	this.Bimg = undefined;
	this.Cimg = undefined;
	this.Dimg = undefined;
	this.Fimg = undefined;
this.Gimg = undefined;

this.m_contentTequimentMenuBody  = undefined;

        this.m_mobInventoryDiv = undefined;
        this.m_mobItemsDiv = undefined;

        this.m_mobInventoryConstructor = InventoryDiv;
        this.m_mobItemsConstructor = ItemsItemsDiv;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    StockPileDivItems.prototype.initialize = function(_a_parentDiv){
    }

    StockPileDivItems.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";



    var l_contentTableEquipmentMenu = document.createElement("table");
		
		
		
		
		
         this.m_containerDiv.appendChild(l_contentTableEquipmentMenu);
        l_contentTableEquipmentMenu.style.marginLeft = "auto";
        l_contentTableEquipmentMenu.style.marginRight = "auto";
        l_contentTableEquipmentMenu.style.marginTop = "5px";
        l_contentTableEquipmentMenu.style.cellSpacing = "0px";
        l_contentTableEquipmentMenu.style.borderCollapse = "collapse";
        this.m_contentTequimentMenuBody = document.createElement("tbody");
        l_contentTableEquipmentMenu.appendChild(this.m_contentTequimentMenuBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTequimentMenuBody.appendChild(l_headerTR);

       // var l_td = document.createElement("td");
      //  l_headerTR.appendChild(l_td);
       // addHeaderStyleWithInnerDiv(l_td, "Weapons", "500px");




	 this.Wimg = document.createElement("td");
         l_headerTR.appendChild(this.Wimg);
	// this.m_containerDiv.appendChild(this.Wimg);
	 this.Wimg.style.textAlign = "center";
	this.Wimg.style.cursor = "pointer";
	
		 this.Aimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Aimg);
	 this.Aimg.style.textAlign = "center";
	 this.Aimg.style.cursor = "pointer";
          this.Bimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Bimg);
	 this.Bimg.style.textAlign = "center";
         this.Bimg.style.cursor = "pointer";
          this.Cimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Cimg);
	 this.Cimg.style.textAlign = "center";
         this.Cimg.style.cursor = "pointer";
          this.Dimg = document.createElement("td");
	// this.m_containerDiv.appendChild(this.Aimg);
         l_headerTR.appendChild(this.Dimg);
	 this.Dimg.style.textAlign = "center";
         this.Dimg.style.cursor = "pointer";
         
         /*
	 	 this.Bimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Bimg);
	 this.Bimg.style.textAlign = "left";
	 
	 	 this.Cimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Cimg);
	 this.Cimg.style.textAlign = "left";
	 
	 	 this.Dimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Dimg);
	 this.Dimg.style.textAlign = "left";
	 
	 	 this.Eimg = document.createElement("div");
	 this.m_containerDiv.appendChild(this.Eimg);
	 this.Eimg.style.textAlign = "left";
         */
	//this.Wimg = document.createElement("img");
	//this.Wimg.src="http://www.bigideastech.com/crime/images/UI/weapons2.jpg");
	
	
	// "<img style='margin-left:auto; margin-right:auto;' src='"+a_item.getImageURL()+"'/>";
	
	// this.m_refreshDiv.appendChild(this.Wimg);
	
	// this.m_refreshDiv.innerHTML = "<h2>Choose Shops Category</h2> ";
 
  this.Wimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/weapons.jpg'/>  ";
 
 this.Aimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/armor.jpg'/> ";

this.Bimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/vehicles.jpg'/> ";

this.Cimg.innerHTML = "<img style='margin-left:auto; margin-right:auto;' src='http://www.bigideastech.com/crime/images/UI/buttons/items.jpg'/> ";




addEvent(this.Wimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivWeapons(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Aimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivArmor(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Bimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new StockPileDivVehicles(a_contentDiv); new AdDiv2(a_contentDiv);
		});; });

addEvent(this.Cimg, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = ""; 
			new StockPileDivItems(a_contentDiv); new AdDiv2(a_contentDiv);
});; });




        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();
    }

    StockPileDivItems.prototype.refresh = function(){

        var l_self = this;
var s_nameelement ="vehicle";

        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();},s_nameelement);

        
        var l_params = {};
        l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = '2';
		l_params.Type = '4';
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetMyStuff2",
                function(a_responseData){
                    l_self.onGetStockpile(a_responseData);
                },l_params);
    }


    StockPileDivItems.prototype.onGetStockpile = function(a_responseData){

        var l_xmlDoc = getGadgetResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_inventoryNode = getXMLFirstNode(l_xmlDoc, "inventory");
				
		       // var l_inventoryNode2 = getXMLFirstNode(l_xmlDoc, "weapon");
				
                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 StockPileDivItems



//MobItemsDiv
    function ItemsDiv(a_parentDiv, a_resultDiv, a_refreshCallback, s_nameelement){

        this.m_parentDiv = a_parentDiv;
        this.m_resultDiv = a_resultDiv;
        this.m_refreshCallback = a_refreshCallback;
        this.m_containerDiv = undefined;
        this.m_contentTBody = undefined;
        this.m_loadingDiv = undefined;

        this.m_titleText = "Your Stuff";
        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;
        }

        var l_contentTableWeapons = document.createElement("table");
		
		
		
		
		
        this.m_containerDiv.appendChild(l_contentTableWeapons);
        l_contentTableWeapons.style.marginLeft = "auto";
        l_contentTableWeapons.style.marginRight = "auto";
        l_contentTableWeapons.style.marginTop = "5px";
        l_contentTableWeapons.style.cellSpacing = "0px";
        l_contentTableWeapons.style.borderCollapse = "collapse";
        this.m_contentTWeaponsBody = document.createElement("tbody");
        l_contentTableWeapons.appendChild(this.m_contentTWeaponsBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTWeaponsBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Weapons", "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");



		var l_contentTableArmor = document.createElement("table");
	
		
        this.m_containerDiv.appendChild(l_contentTableArmor);
        l_contentTableArmor.style.marginLeft = "auto";
        l_contentTableArmor.style.marginRight = "auto";
        l_contentTableArmor.style.marginTop = "5px";
        l_contentTableArmor.style.cellSpacing = "0px";
        l_contentTableArmor.style.borderCollapse = "collapse";
        this.m_contentTArmorBody = document.createElement("tbody");
        l_contentTableArmor.appendChild(this.m_contentTArmorBody);

         l_headerTR = document.createElement("tr");
        this.m_contentTArmorBody.appendChild(l_headerTR);

         l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Weapons", "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");
		

		
		
			var l_contentTableVehicles = document.createElement("table");
	
		
        this.m_containerDiv.appendChild(l_contentTableVehicles);
        l_contentTableVehicles.style.marginLeft = "auto";
        l_contentTableVehicles.style.marginRight = "auto";
        l_contentTableVehicles.style.marginTop = "5px";
        l_contentTableVehicles.style.cellSpacing = "0px";
        l_contentTableVehicles.style.borderCollapse = "collapse";
        this.m_contentTVehiclesBody = document.createElement("tbody");
        l_contentTableArmor.appendChild(this.m_contentTVehiclesBody);

         l_headerTR = document.createElement("tr");
        this.m_contentTVehiclesBody.appendChild(l_headerTR);

         l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Vehicles", "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");
		
	

			var l_contentTableItems = document.createElement("table");
	
		
        this.m_containerDiv.appendChild(l_contentTableItems);
        l_contentTableItems.style.marginLeft = "auto";
        l_contentTableItems.style.marginRight = "auto";
        l_contentTableItems.style.marginTop = "5px";
        l_contentTableItems.style.cellSpacing = "0px";
        l_contentTableItems.style.borderCollapse = "collapse";
        this.m_contentTItemsBody = document.createElement("tbody");
        l_contentTableItems.appendChild(this.m_contentTItemsBody);

         l_headerTR = document.createElement("tr");
        this.m_contentTItemsBody.appendChild(l_headerTR);

         l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Items", "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");
		
		

        this.m_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_loadingDiv);
        this.m_loadingDiv.style.padding = "20px";
        this.m_loadingDiv.innerHTML = "<span style='color:#FF6F27; font-weight:bold; font-size: 18px'> Loading ...  </span>";

    }

    ItemsDiv.prototype.fillFromXML = function(a_xmlNode){ //"inventory"

        this.m_loadingDiv.style.display = "none";

        if(isValid(a_xmlNode)){
            try{
				
				var l_weaponNode = a_xmlNode.getElementsByTagName("weapon");
				var l_weaponNodesItems = l_weaponNode[0].getElementsByTagName("item");
				
				var l_armorNode = a_xmlNode.getElementsByTagName("armor");
				var l_armorNodesItems = l_armorNode[0].getElementsByTagName("item");
					
					
				var l_carsNode = a_xmlNode.getElementsByTagName("vehicle");
				var l_carsNodesItems = l_carsNode[0].getElementsByTagName("item");
				
				
				var l_itemsNode = a_xmlNode.getElementsByTagName("items");
				var l_itemsNodesItems = l_itemsNode[0].getElementsByTagName("item");
					
					
					/*
					var l_carsNode = a_xmlNode.getElementsByTagName("vehicle");
				
					var l_carsNodesItems = l_carsNode[0].getElementsByTagName("item");	
					*/
            //    var l_itemNodes = a_xmlNode.getElementsByTagName("item");
				
				//	a_xmlNode.get
                for(var l_index = 0; l_index < l_weaponNodesItems.length; l_index++){
					 this.m_contentTWeaponsBody.appendChild(this.createContentElement(new RPGItem(l_weaponNodesItems[l_index])));
                }
				
				 for(var l_index = 0; l_index < l_armorNodesItems.length; l_index++){
					 this.m_contentTArmorBody.appendChild(this.createContentElement(new RPGItem(l_armorNodesItems[l_index])));
                }
				 for(var l_index = 0; l_index < l_carsNodesItems.length; l_index++){
					 this.m_contentTVehiclesBody.appendChild(this.createContentElement(new RPGItem(l_carsNodesItems[l_index])));
                }
				
				
				for(var l_index = 0; l_index < l_itemsNodesItems.length; l_index++){
					 this.m_contentTItemsBody.appendChild(this.createContentElement(new RPGItem(l_itemsNodesItems[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 1px #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 1px #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, 25, "Buy", function(a_numToBuy){
            l_self.m_resultDiv.showMessage(undefined, "Buying ... ");
            goToPageTop();

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();
			
			l_params.item_type = a_item.getItemType();
			
            l_params.amount = a_numToBuy;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    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, 25, "Sell", function(a_numToSell){
                l_self.m_resultDiv.showMessage(undefined, "Selling ... ");
                goToPageTop();

                var l_params = {};
                l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();;
				l_params.item_type = a_item.getItemType();
				
                l_params.amount = -a_numToSell;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();})},
                    l_params, 0);
            }, "#656565");
        }

        return l_tr;
    }
//end MobItemsDiv






//MobItemsDiv
    function ItemsNewDiv(a_parentDiv, a_resultDiv, a_refreshCallback, s_nameelement){

        this.m_parentDiv = a_parentDiv;
        this.m_resultDiv = a_resultDiv;
        this.m_refreshCallback = a_refreshCallback;
        this.m_containerDiv = undefined;
        this.m_contentTBody = undefined;
        this.m_loadingDiv = undefined;

        this.m_titleText = "Your Stuff";
        this.m_explanationText = undefined;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    ItemsNewDiv.prototype.initialize = function(_a_parentDiv){
    }


    ItemsNewDiv.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;
        }

        var l_contentTableWeapons = document.createElement("table");
		
		
		
		
		
        this.m_containerDiv.appendChild(l_contentTableWeapons);
        l_contentTableWeapons.style.marginLeft = "auto";
        l_contentTableWeapons.style.marginRight = "auto";
        l_contentTableWeapons.style.marginTop = "5px";
        l_contentTableWeapons.style.cellSpacing = "0px";
        l_contentTableWeapons.style.borderCollapse = "collapse";
        this.m_contentTWeaponsBody = document.createElement("tbody");
        l_contentTableWeapons.appendChild(this.m_contentTWeaponsBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTWeaponsBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Weapons", "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");



		

        this.m_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_loadingDiv);
        this.m_loadingDiv.style.padding = "20px";
        this.m_loadingDiv.innerHTML = "<span style='color:#FF6F27; font-weight:bold; font-size: 18px'> Loading ...  </span>";

    }

    ItemsNewDiv.prototype.fillFromXML = function(a_xmlNode){ //"inventory"

        this.m_loadingDiv.style.display = "none";

        if(isValid(a_xmlNode)){
            try{
				
				var l_weaponNode = a_xmlNode.getElementsByTagName("weapon");
				var l_weaponNodesItems = l_weaponNode[0].getElementsByTagName("item");
			
                for(var l_index = 0; l_index < l_weaponNodesItems.length; l_index++){
					 this.m_contentTWeaponsBody.appendChild(this.createContentElement(new RPGItem(l_weaponNodesItems[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);}
        }        
    }



    ItemsNewDiv.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 1px #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 1px #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, 25, "Buy", function(a_numToBuy){
            l_self.m_resultDiv.showMessage(undefined, "Buying ... ");
            goToPageTop();

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();
			
			l_params.item_type = a_item.getItemType();
			
            l_params.amount = a_numToBuy;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    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, 25, "Sell", function(a_numToSell){
                l_self.m_resultDiv.showMessage(undefined, "Selling ... ");
                goToPageTop();

                var l_params = {};
                l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();;
				l_params.item_type = a_item.getItemType();
				
                l_params.amount = -a_numToSell;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();})},
                    l_params, 0);
            }, "#656565");
        }

        return l_tr;
    }
//end MobItemsDiv


//ItemsArmorDiv
    function ItemsArmorDiv(a_parentDiv, a_resultDiv, a_refreshCallback, s_nameelement){

        this.m_parentDiv = a_parentDiv;
        this.m_resultDiv = a_resultDiv;
        this.m_refreshCallback = a_refreshCallback;
        this.m_containerDiv = undefined;
        this.m_contentTBody = undefined;
        this.m_loadingDiv = undefined;

        this.m_titleText = "Your Stuff";
        this.m_explanationText = undefined;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    ItemsArmorDiv.prototype.initialize = function(_a_parentDiv){
    }


    ItemsArmorDiv.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;
        }

        var l_contentTableWeapons = document.createElement("table");
		
		
		
		
		
        this.m_containerDiv.appendChild(l_contentTableWeapons);
        l_contentTableWeapons.style.marginLeft = "auto";
        l_contentTableWeapons.style.marginRight = "auto";
        l_contentTableWeapons.style.marginTop = "5px";
        l_contentTableWeapons.style.cellSpacing = "0px";
        l_contentTableWeapons.style.borderCollapse = "collapse";
        this.m_contentTWeaponsBody = document.createElement("tbody");
        l_contentTableWeapons.appendChild(this.m_contentTWeaponsBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTWeaponsBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Armor", "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");



		

        this.m_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_loadingDiv);
        this.m_loadingDiv.style.padding = "20px";
        this.m_loadingDiv.innerHTML = "<span style='color:#FF6F27; font-weight:bold; font-size: 18px'> Loading ...  </span>";

    }

    ItemsArmorDiv.prototype.fillFromXML = function(a_xmlNode){ //"inventory"

        this.m_loadingDiv.style.display = "none";

        if(isValid(a_xmlNode)){
            try{
				
				var l_weaponNode = a_xmlNode.getElementsByTagName("armor");
				var l_weaponNodesItems = l_weaponNode[0].getElementsByTagName("item");
			
                for(var l_index = 0; l_index < l_weaponNodesItems.length; l_index++){
					 this.m_contentTWeaponsBody.appendChild(this.createContentElement(new RPGItem(l_weaponNodesItems[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);}
        }        
    }



    ItemsArmorDiv.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 1px #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 1px #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, 25, "Buy", function(a_numToBuy){
            l_self.m_resultDiv.showMessage(undefined, "Buying ... ");
            goToPageTop();

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();
			
			l_params.item_type = a_item.getItemType();
			
            l_params.amount = a_numToBuy;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    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, 25, "Sell", function(a_numToSell){
                l_self.m_resultDiv.showMessage(undefined, "Selling ... ");
                goToPageTop();

                var l_params = {};
                l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();;
				l_params.item_type = a_item.getItemType();
				
                l_params.amount = -a_numToSell;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();})},
                    l_params, 0);
            }, "#656565");
        }

        return l_tr;
    }
//end ItemsArmorDiv



//ItemsVehicleDiv
    function ItemsVehicleDiv(a_parentDiv, a_resultDiv, a_refreshCallback, s_nameelement){

        this.m_parentDiv = a_parentDiv;
        this.m_resultDiv = a_resultDiv;
        this.m_refreshCallback = a_refreshCallback;
        this.m_containerDiv = undefined;
        this.m_contentTBody = undefined;
        this.m_loadingDiv = undefined;

        this.m_titleText = "Your Stuff";
        this.m_explanationText = undefined;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    ItemsVehicleDiv.prototype.initialize = function(_a_parentDiv){
    }


    ItemsVehicleDiv.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;
        }

        var l_contentTableWeapons = document.createElement("table");
		
		
		
		
		
        this.m_containerDiv.appendChild(l_contentTableWeapons);
        l_contentTableWeapons.style.marginLeft = "auto";
        l_contentTableWeapons.style.marginRight = "auto";
        l_contentTableWeapons.style.marginTop = "5px";
        l_contentTableWeapons.style.cellSpacing = "0px";
        l_contentTableWeapons.style.borderCollapse = "collapse";
        this.m_contentTWeaponsBody = document.createElement("tbody");
        l_contentTableWeapons.appendChild(this.m_contentTWeaponsBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTWeaponsBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Vehicles", "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");



		

        this.m_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_loadingDiv);
        this.m_loadingDiv.style.padding = "20px";
        this.m_loadingDiv.innerHTML = "<span style='color:#FF6F27; font-weight:bold; font-size: 18px'> Loading ...  </span>";

    }

    ItemsVehicleDiv.prototype.fillFromXML = function(a_xmlNode){ //"inventory"

        this.m_loadingDiv.style.display = "none";

        if(isValid(a_xmlNode)){
            try{
				
				var l_weaponNode = a_xmlNode.getElementsByTagName("vehicle");
				var l_weaponNodesItems = l_weaponNode[0].getElementsByTagName("item");
			
                for(var l_index = 0; l_index < l_weaponNodesItems.length; l_index++){
					 this.m_contentTWeaponsBody.appendChild(this.createContentElement(new RPGItem(l_weaponNodesItems[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);}
        }        
    }



    ItemsVehicleDiv.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 1px #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 1px #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, 25, "Buy", function(a_numToBuy){
            l_self.m_resultDiv.showMessage(undefined, "Buying ... ");
            goToPageTop();

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();
			
			l_params.item_type = a_item.getItemType();
			
            l_params.amount = a_numToBuy;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    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, 25, "Sell", function(a_numToSell){
                l_self.m_resultDiv.showMessage(undefined, "Selling ... ");
                goToPageTop();

                var l_params = {};
                l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();;
				l_params.item_type = a_item.getItemType();
				
                l_params.amount = -a_numToSell;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();})},
                    l_params, 0);
            }, "#656565");
        }

        return l_tr;
    }
//end ItemsVehicleDiv



//ItemsWeaponsDiv
    function ItemsWeaponsDiv(a_parentDiv, a_resultDiv, a_refreshCallback, s_nameelement){

        this.m_parentDiv = a_parentDiv;
        this.m_resultDiv = a_resultDiv;
        this.m_refreshCallback = a_refreshCallback;
        this.m_containerDiv = undefined;
        this.m_contentTBody = undefined;
        this.m_loadingDiv = undefined;

        this.m_titleText = "Your Stuff";
        this.m_explanationText = undefined;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    ItemsWeaponsDiv.prototype.initialize = function(_a_parentDiv){
    }


    ItemsWeaponsDiv.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;
        }

        var l_contentTableWeapons = document.createElement("table");
		
		
		
		
		
        this.m_containerDiv.appendChild(l_contentTableWeapons);
        l_contentTableWeapons.style.marginLeft = "auto";
        l_contentTableWeapons.style.marginRight = "auto";
        l_contentTableWeapons.style.marginTop = "5px";
        l_contentTableWeapons.style.cellSpacing = "0px";
        l_contentTableWeapons.style.borderCollapse = "collapse";
        this.m_contentTWeaponsBody = document.createElement("tbody");
        l_contentTableWeapons.appendChild(this.m_contentTWeaponsBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTWeaponsBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Weapons", "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");



		

        this.m_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_loadingDiv);
        this.m_loadingDiv.style.padding = "20px";
        this.m_loadingDiv.innerHTML = "<span style='color:#FF6F27; font-weight:bold; font-size: 18px'> Loading ...  </span>";

    }

    ItemsWeaponsDiv.prototype.fillFromXML = function(a_xmlNode){ //"inventory"

        this.m_loadingDiv.style.display = "none";

        if(isValid(a_xmlNode)){
            try{
				
				var l_weaponNode = a_xmlNode.getElementsByTagName("weapon");
				var l_weaponNodesItems = l_weaponNode[0].getElementsByTagName("item");
			
                for(var l_index = 0; l_index < l_weaponNodesItems.length; l_index++){
					 this.m_contentTWeaponsBody.appendChild(this.createContentElement(new RPGItem(l_weaponNodesItems[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);}
        }        
    }



    ItemsWeaponsDiv.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 1px #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 1px #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, 25, "Buy", function(a_numToBuy){
            l_self.m_resultDiv.showMessage(undefined, "Buying ... ");
            goToPageTop();

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();
			
			l_params.item_type = a_item.getItemType();
			
            l_params.amount = a_numToBuy;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    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, 25, "Sell", function(a_numToSell){
                l_self.m_resultDiv.showMessage(undefined, "Selling ... ");
                goToPageTop();

                var l_params = {};
                l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();;
				l_params.item_type = a_item.getItemType();
				
                l_params.amount = -a_numToSell;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();})},
                    l_params, 0);
            }, "#656565");
        }

        return l_tr;
    }
//end ItemsWeaponsDiv


//ItemsWeaponsDiv
    function ItemsItemsDiv(a_parentDiv, a_resultDiv, a_refreshCallback, s_nameelement){

        this.m_parentDiv = a_parentDiv;
        this.m_resultDiv = a_resultDiv;
        this.m_refreshCallback = a_refreshCallback;
        this.m_containerDiv = undefined;
        this.m_contentTBody = undefined;
        this.m_loadingDiv = undefined;

        this.m_titleText = "Your Stuff";
        this.m_explanationText = undefined;

        this.initialize();
        this.createDiv(this.m_parentDiv);
    }

    ItemsItemsDiv.prototype.initialize = function(_a_parentDiv){
    }


    ItemsItemsDiv.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;
        }

        var l_contentTableWeapons = document.createElement("table");
		
		
		
		
		
        this.m_containerDiv.appendChild(l_contentTableWeapons);
        l_contentTableWeapons.style.marginLeft = "auto";
        l_contentTableWeapons.style.marginRight = "auto";
        l_contentTableWeapons.style.marginTop = "5px";
        l_contentTableWeapons.style.cellSpacing = "0px";
        l_contentTableWeapons.style.borderCollapse = "collapse";
        this.m_contentTWeaponsBody = document.createElement("tbody");
        l_contentTableWeapons.appendChild(this.m_contentTWeaponsBody);

        var l_headerTR = document.createElement("tr");
        this.m_contentTWeaponsBody.appendChild(l_headerTR);

        var l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Items", "500px");

        l_td = document.createElement("td");
        l_headerTR.appendChild(l_td);
        addHeaderStyleWithInnerDiv(l_td, "Buy / Sell", "300px");



		

        this.m_loadingDiv = document.createElement("div");
        this.m_containerDiv.appendChild(this.m_loadingDiv);
        this.m_loadingDiv.style.padding = "20px";
        this.m_loadingDiv.innerHTML = "<span style='color:#FF6F27; font-weight:bold; font-size: 18px'> Loading ...  </span>";

    }

    ItemsItemsDiv.prototype.fillFromXML = function(a_xmlNode){ //"inventory"

        this.m_loadingDiv.style.display = "none";

        if(isValid(a_xmlNode)){
            try{
				
				var l_weaponNode = a_xmlNode.getElementsByTagName("items");
				var l_weaponNodesItems = l_weaponNode[0].getElementsByTagName("item");
			
                for(var l_index = 0; l_index < l_weaponNodesItems.length; l_index++){
					 this.m_contentTWeaponsBody.appendChild(this.createContentElement(new RPGItem(l_weaponNodesItems[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);}
        }        
    }



    ItemsItemsDiv.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 1px #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 1px #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, 25, "Buy", function(a_numToBuy){
            l_self.m_resultDiv.showMessage(undefined, "Buying ... ");
            goToPageTop();

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();
			
			l_params.item_type = a_item.getItemType();
			
            l_params.amount = a_numToBuy;
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    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, 25, "Sell", function(a_numToSell){
                l_self.m_resultDiv.showMessage(undefined, "Selling ... ");
                goToPageTop();

                var l_params = {};
                l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType =  "2";
            l_params.item_id = a_item.getId();;
				l_params.item_type = a_item.getItemType();
				
                l_params.amount = -a_numToSell;
                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BuyItem",
                    function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.m_refreshCallback();})},
                    l_params, 0);
            }, "#656565");
        }

        return l_tr;
    }
//end ItemsWeaponsDiv

//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


//JailDiv
    function JailDiv(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();
    }

    JailDiv.prototype.initialize = function(){
        this.m_titleText = "Jail";
        this.m_explanationMsg = "You can pay a bail to get out of Jail. Cops 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_explanationMsg += "<BR> You can also Invite 5 friends to play gnome wars to get bail. <a href='#' class='standardLink' onclick='switchTabs(9); return false;'>the clan</a>";
	  
	    this.m_cantBailText = "You cannot bail your out.";
        this.m_healPrefix = "Bail yourself out for";
        this.m_healProcessText = "Bailing...";        
    }

    JailDiv.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();
    }


    JailDiv.prototype.refresh = function(){        
        this.m_refreshDiv.innerHTML = "";

        var l_viewer = GBL.MAIN_DATA.getViewer();
        var l_cost = l_viewer.getLevel() * 2000;
        if(l_viewer.getJailed() == "False"){
            this.m_refreshDiv.textAlign = "left";
            this.m_refreshDiv.innerHTML = this.m_cantBailText;
			
            return;
        }

      //  this.m_refreshDiv.innerHTML = this.m_explanationMsg;
		this.m_refreshDiv.innerHTML = "You can pay a bail to get out of Jail. Cops must be paid with clean money from <a href='#' class='standardLink' onclick='switchTabs(3); return false;'>the bank</a>.<BR> You currently have <span style='color:#32CD32'>$" + formatNumberWithCommas(GBL.MAIN_DATA.getViewer().getCashInBank()) + "</span> in the bank.";
        this.m_refreshDiv.innerHTML += "<BR><BR> You can also Invite 5 friends to play gnome wars to get bail. <a href='#' class='standardLink' onclick='switchTabs(9); return false;'>the clan</a>";
	//	this.m_refreshDiv.innerHTML += "<BR>l_viewer.getJailed():" + l_viewer.getJailed(); 
		
		
		var l_buttonDiv = document.createElement("div");
        this.m_refreshDiv.appendChild(l_buttonDiv);
        l_buttonDiv.style.padding = "10px";                

        var l_self = this;
        new DivButton(l_buttonDiv, this.m_healPrefix + " $" + formatNumberWithCommas(l_cost), function(){
            l_self.m_resultDiv.showMessage(undefined, l_self.m_healProcessText + " ... ");

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
       //     l_params.level = GBL.MAIN_DATA.getViewer().getLevel();
			
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/BailSelf",
                function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                l_params, 0);
        });
    }
//end JailDiv


//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() * 200;
        if(l_viewer.getHealth() >= 0.80*l_viewer.getMaxHealth()){
            this.m_refreshDiv.textAlign = "left";
            this.m_refreshDiv.innerHTML = this.m_cantHealText;
			
            return;
        }

      //  this.m_refreshDiv.innerHTML = this.m_explanationMsg;
		this.m_refreshDiv.innerHTML = "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.";
        var l_buttonDiv = document.createElement("div");
        this.m_refreshDiv.appendChild(l_buttonDiv);
        l_buttonDiv.style.padding = "10px";                

        var l_self = this;
        new DivButton(l_buttonDiv, this.m_healPrefix + " $" + formatNumberWithCommas(l_cost), function(){
            l_self.m_resultDiv.showMessage(undefined, l_self.m_healProcessText + " ... ");

            var l_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
       //     l_params.level = GBL.MAIN_DATA.getViewer().getLevel();
			
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/HealSelf",
                function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
                l_params, 0);
        });
    }
//end HospitalDiv

//MobInviteDiv
    function InviteDiv(a_parentDiv){

        this.m_parentDiv = a_parentDiv;
        this.m_containerDiv = undefined;
        this.m_resultDiv = undefined;
        this.m_friendPicker = undefined;
        this.m_sentFriends = undefined;

        this.m_sendInvite = false;
        this.m_explanationMsg = undefined;

        this.initialize();
        this.createDiv();
    }

    InviteDiv.prototype.initialize = function(){
        this.m_explanationMsg = "";// "<span style='font-size:18px; color:#00FF00;'>If MySpace Inviting Gets Error, Please Click Here, it should fix the problem.</span><BR><BR>Select your friends below to recruit them. <b>The larger your gnome clan, the more gnomer you can do when attacking and completing Quests!</b> ";
 
 
    }

    InviteDiv.prototype.generateComment = function(){
        var l_random = Math.random();
        if(l_random < 0.8){
            return "<a href='" + GBL.APP_CANVAS_URL + "&track=comment_img_v1'><img src='http://g.laasex.com/gnomeswars/images/UI/gnome-wars-ss1.jpg'/></a><br/><br/>" + GBL.MAIN_DATA.getViewer().getName() + " wants you to join their Gnome Clan in <a href='" + GBL.APP_CANVAS_URL + "&track=comment_link1_v1'>Gnome Wars</a>, a Mafia-style combat game played on MySpace. Start out as a petty gnome and work your way up to become a Number 1 Gnome on Myspace!<br/><br/><a href='" + GBL.APP_CANVAS_URL + "&track=comment_link2_v1''>Join " + GBL.MAIN_DATA.getViewer().getName() + "'s Gnome Clan!</a>";
        } else {

            return "<a href='" + GBL.APP_CANVAS_URL + "&track=comment_img_v2'><img src='http://g.laasex.com/gnomeswars/images/UI/gnome-wars-ss1.jpg'/></a><br/><br/>" + GBL.MAIN_DATA.getViewer().getName() + " wants you to join their Gnome Clan in <a href='" + GBL.APP_CANVAS_URL + "&track=comment_link1_v2'>Gnome Wars</a>, a Mafia-style combat game played on MySpace. Start out as a petty gnome and work your way up to become a Number 1 Gnome on Myspace!<br/><br/><a href='" + GBL.APP_CANVAS_URL + "&track=comment_link2_v2''>Join " + GBL.MAIN_DATA.getViewer().getName() + "'s Gnome Clan!</a>";;
        }
    }

    InviteDiv.prototype.generateInvite = function(){
        return  "[sender] wants you to join their Clan in [app], a Mafia-style combat game played on MySpace. Start out as a petty thief and work your way up to become a Number 1 Criminal on Myspace!";
    }

    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;


 
 	//	function(a_contentDiv){
	addEvent(l_noteDiv, "click", function(e) { GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
			a_contentDiv.innerHTML = "";
			new ViewerMobDiv(a_contentDiv);
		});; });

	      addEvent(l_noteDiv, "mouseover", function(){
		  	l_noteDiv.style.backgroundcolor ="#FFFFFF";
           // l_self.selectEntry(a_achievementIndex);            
        });
		
	this.selectRandom10=selectRandom10;
	
	function selectRandom10(){
		
		unselectFriends();
		
		var gT=getRandomNumbers(bw.length-1,10);
		
		eP=gT.length;for(var l=0;l<gT.length;l++){
			
			var dY=gT[l];var dL=eH[dY].value;bw[dY].checked=true;bw[dY].selected=true;bw[dY].style.backgroundColor="#3b5998";
			
			bw[dY].style.color="white";eH[dY].checked=true;gI[dL]=dL;}
			
			};

        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 DivButton(l_buttonDiv, "Send Invites & Comments", function(){l_self.send();});
	
 var l_AselectAll = document.createElement("a");
  l_AselectAll.innerHTML = 'Send All';
  addEvent(l_AselectAll,"click",function(){
    l_self.sendAll();
    /*
    var checkboxes = document.getElementsByName('pickFriend');
	   for(var i = 0; i<checkboxes.length; i++)
	   {
	    checkboxes[i].checked = true;
	    
	   }*/
	   });
   this.m_containerDiv.appendChild(l_AselectAll);
        this.m_friendPicker = new FriendPicker(this.m_containerDiv, 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 DivButton(l_buttonDiv, "Send Invites & Comments", function(){l_self.send();});
		
		/*
		var lh=makeElement("span",fl,{fontSize:"12px",textDecoration:"underline",color:"#3b5998",cursor:"pointer"});
		lh.innerHTML="Select Random 10";
		addEvent(lh,"click",function(){
			clearSelectedUserIdMap();
		if(isValid(eV)){eV.selectRandom10();
		}
		});
		
		var pk=makeElement("span",fl,{fontSize:"15px",color:"#000000",padding:"0px 10px 0px 10px"});
		
		pk.innerHTML="|";
		
		var lk=makeElement("span",fl,{fontSize:"12px",textDecoration:"underline",color:"#3b5998",cursor:"pointer"});lk.innerHTML="Clear Selected";
		
		addEvent(lk,"click",function(){clearSelectedUserIdMap();
		if(isValid(eV)){
			eV.unselectFriends();}});;
                */
		
    }


    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.sendComment(l_selectedFriends, 0);
    }
    
 InviteDiv.prototype.sendAll = function() {
     
	 var l_self = this;
	 
	GBL.MAIN_DATA.getViewerFriends().getNumUsers(function (numusers){
	    
	    GBL.MAIN_DATA.getViewerFriends().getUsers(0,numusers,function (l_selectedFriends)
						      {
							
							
						  if (!isValid(l_selectedFriends) || l_selectedFriends.length == 0) {
            l_self.m_resultDiv.showMessage(false, "Please select at least one friend to invite");
            return;
        }

        l_self.m_resultDiv.showMessage(undefined, "Sending...");
        l_self.m_sentFriends = new Array();
        l_self.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){

            if(a_postStatus > 0){
                l_self.m_sentFriends.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(); 
            }
        }
        
        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(){
        if(this.m_sentFriends.length > 0){
            this.m_resultDiv.showMessage(true, "You have sent requests to " + this.m_sentFriends.length + " friends!");
            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_params = {};
            l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
            l_params.ToNetworkID = l_userIdsStr;
			
            var l_self = this;

            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL + "/SendRequests",
                    function(a_response){
                        GBL.MAIN_DATA.getViewerFriends().invalidateCache();
                        handleResult(a_response, l_self.m_resultDiv, undefined);
                    },
                    l_params);

        } else {
            this.m_resultDiv.showMessage(false, "You didn't send any invites!");
        }
    }
//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;


    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 = "#FFFFFF";
        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){
        outputDebug("UserListDiv: jumpToPage " + a_pageNum);
        m_currentPage = a_pageNum;
        m_containerDiv.innerHTML = "";

        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);
            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 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 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;


    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;'> Member </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;'> Requested </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 unselectFriends() {
        for(var i = 0; i < m_friendTdArray.length; i++){
            m_friendTdArray[i].checked = 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 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;
    }
}


//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 = "Your Clan:";
        this.m_maxExplanation = "Note: Your current max gnome clan size limit is: <b>"+1000+"</b>";
        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 = "Invite ALL your friends to play Gnome Wars with a bulletin!";

        var l_buttonCell = l_ssCells.getRightCell();
        var l_button = new DivButton(l_buttonCell, "Send Gnome Wars Bulletin", function(){
            postToBulletin(GBL.MAIN_DATA.getViewer(),
                           "Want to get into Gnome Wars?",
                           "<a href='" + GBL.APP_CANVAS_URL + "&track=bulletin_img'><img src='http://g.laasex.com/gnomeswars/images/UI/gnome-wars-ss1.jpg'/></a><br/><br/>Come play <a href='" + GBL.APP_CANVAS_URL + "appParams=%7B%22rsrc%22%3A%22bulletin_link1%22%7D&track=bulletin_link1'>Gnome Wars</a>, a Mafia-style combat game played on MySpace. Start out as a petty thief and work your way up to become a Top Gnome on MySpace!<br/><br/><a href='" + GBL.APP_CANVAS_URL + "appParams=%7B%22rsrc%22%3A%22bulletin_link2%22%7D&track=bulletin_link2'>Play Gnome Wars!</a>",
                            function(a_postResult){
                                //if(a_postResult > 0){
                                l_buttonCell.innerHTML = "<span style='color:#FF7F00; font-weight:bold; font-size:12px;'> Now more Gnomes will die! </span>";
                                //}
                            });
        });
    }

// end ViewerMobDiv





// 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 gnome clan. If you accept, they will also become a member of your gnome clan and you will be able to pull off more difficult missions, as well as become more powerful when attacking other criminals.";
    }

    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 target=\"_blank\" href=\""+ GBL.APP_CANVAS_URL + "appParams=%7B%22"+GBL.SHOW_USER_ID+"%22%3A%22"+a_user.getUserId()+"%22%7D\" >" + a_user.getMobName() + ' Level ' +  a_user.getLevel()+"</a>";
        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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType ="2";
            l_params.AcceptNetworkID = a_user.getUserId();
			
			
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/AcceptOrgRequest",
                            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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType ="2";
            l_params.RejectNetworkID = a_user.getUserId();
			
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/RejectOrgRequest",
                            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 Clan 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 <= 1000){
            createTitleDiv(this.m_title, "Your Clan Members: <span style='font-size:15px'> (" + (GBL.MAIN_DATA.getViewer().getMobSize() - a_numUsers ) + " hired criminals) </span>");
        } else {
            createTitleDiv(this.m_title, "Your Clan Members: <span style='font-size:15px'> (" + (GBL.MAIN_DATA.getViewer().getMobSize() - a_numUsers ) + " hired criminals) </span> <span style='color:#FF0000; font-style:italic; font-size:15px'> (1000 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 Clan is empty! The more friends in your Clan the stronger you are, so you should <a href='#' class='standardLink' onclick='switchTabs(9);return false;'>invite some friends</a> to be part of your clan!");
    }


    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 1px #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 target=\"_blank\" href=\""+ GBL.APP_CANVAS_URL + "appParams=%7B%22"+GBL.SHOW_USER_ID+"%22%3A%22"+a_user.getUserId()+"%22%7D\" >" +a_user.getMobName()+ "</a>";
        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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType ="2";
            l_params.ToNetworkID = a_user.getUserId();
			
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/RemoveOrgUser",
                            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 1px #AAAAAA";


        var l_titleDiv = document.createElement("div");
        this.m_containerDiv.appendChild(l_titleDiv);
        l_titleDiv.innerHTML = "<span style='color:#FFA500; font-size:16px; font-weight:bold;'> Comments: </span>";

        var l_explanationDiv = createWhiteDiv(this.m_containerDiv);
        l_explanationDiv.style.paddingLeft = "15px";
        l_explanationDiv.innerHTML = "Costs $100";

        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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
            l_params.TargetNetworkID = l_self.m_targetUserId;
            l_params.message = customEncoding(l_commentMsg.getText());
				//  l_params.message = l_commentMsg.getText();

         //    makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/save_comment",
		 makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/SaveProfileComment",
                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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
		l_params.NetworkType = "2";
        l_params.TargetNetworkID = this.m_targetUserId;

        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetProfileComments", 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 = "330px";

        var l_titleDiv = document.createElement("div");
        l_contentCell.appendChild(l_titleDiv);
        l_titleDiv.style.borderTop = "1px 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 = "310px";
        l_titleInfoCell.innerHTML = "<a target=\"_blank\" href=\""+ GBL.APP_CANVAS_URL + "appParams=%7B%22"+GBL.SHOW_USER_ID+"%22%3A%22"+a_entry.getFromUser().getUserId()+"%22%7D\" ><span style='color:#FFA500; font-size:12px; font-weight:bold;'> " + a_entry.getFromUser().getMobName() + "</span></a>"+
                                    "<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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();                
                l_params.ProfileCommentID = a_entry.getId();

                makeXMLNotCachedRequest(REQUEST_DESTINATION_URL + "/DeleteProfileComment", function(){
                    l_self.refresh();
                }, l_params);
            });
        }

        if(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 = "13px";
        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 = "1px 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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
             l_params.NetworkIDType = "2";
            l_params.TargetNetworkID = a_user.getUserId();
              l_params.TargetNetworkIDType = "2";
            
	    
            makeXMLNotCachedRequest(REQUEST_DESTINATION_URL + "/BlockUser", 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 = "Your Gnome";

        this.m_attributeArray = new Array();
        this.m_attributeValueCallbackArray = new Array();
        this.m_attributeKeyArray = new Array();
        this.m_attributeDescriptionArray = new Array();


        this.m_attributeKeyArray.push("attack_strength");
        this.m_attributeArray.push("Attack Strength");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getAttackStrength();});
        this.m_attributeDescriptionArray.push("Increase your attack strength to attack rival mobs more effectively.");


        this.m_attributeKeyArray.push("defense_strength");
        this.m_attributeArray.push("Defense Power");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getDefenseStrength();});
        this.m_attributeDescriptionArray.push("Increase your defense strength to defend against rival gnomes more effectively.");

        this.m_attributeKeyArray.push("max_energy");
        this.m_attributeArray.push("Max Energy");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getMaxEnergy();});
        this.m_attributeDescriptionArray.push("Increase your max energy to complete more Quests and perform special attacks later in the game.");

        this.m_attributeKeyArray.push("max_health");
        this.m_attributeArray.push("Max Health");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getMaxHealth();});
        this.m_attributeDescriptionArray.push("Increase your max health to survive and fight longer during extended battles. <span style='color:gray'>[<b>1</b> skill point increases your maximum health by <b>10</b>.]</span>");

        this.m_attributeKeyArray.push("max_stamina");
        this.m_attributeArray.push("Max Stamina");
        this.m_attributeValueCallbackArray.push(function(){return GBL.MAIN_DATA.getViewer().getMaxStamina();});
        this.m_attributeDescriptionArray.push("Increase your stamina to attack, punch, and bad list your opponents more quickly. ");


        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 1px #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 DivButton(l_td, "Increase", function(){
               l_self.m_resultDiv.showMessage(undefined, "Increasing ... ");

               var l_params = {};
               l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			   l_params.NetworkType = "2";
               l_params.attribute = a_increaseAttribute;
               makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/IncreaseAttr",
                                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 = "Switch Mobsters/Start New Mobster (beta)";
        this.m_explanationText = "I've been getting a lot of requests from you guys to change your name and/or restart with a new character. Here's the answer to those requests! You can now create up to 3 Mobsters under the same account. Each of these Mobsters will share: favor points, mob members, and achievements. Inactive (saved) characters do not regenerate or make money, but also cannot be attacked. Let me know if you have any questions/concerns regarding this feature. Thanks!";
        this.m_loadConfirmationText = "Are you sure you want to load this game? Your current game will be saved, but your current mobster will not regenerate or make money while it is inactive.";
        this.m_newGameConfirmationText = "Are you sure you want to start a new game? Your current game will be saved, but your current mobster will not regenerate or make money while it is inactive.";

        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 = "<span style='color:#eeeeee; font-style:italic; font-size:12px;'> Start new game...</span>";


        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 = "1px 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 Bad 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_hitListDiv = undefined;

        this.initialize();
        this.createDiv();
    }

    StatsDiv.prototype.initialize = function(){
        this.m_inMobLabel = "This person is in your clan.";
        this.m_notInMobLabel = "This person is NOT in your clan.";

        this.m_weaponsTitle = "Weapons";
        this.m_vehiclesTitle = "Vehicles";
        this.m_propertiesTitle = "Properties";

        this.m_jobsCompletedLabel = "Quests 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 = "Criminals 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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.TargetNetworkID = this.m_userId;
		l_params.NetworkType = "2";
		l_params.TargetNetworkType = "2";
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetUserStats", 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.attacteruserid = GBL.MAIN_DATA.getViewer().getUserId();
           l_params.attackeduserid = l_targetUser.getUserId();
		   l_params.attacteruseridNetwork ="2";
		   l_params.attackeduseridNetwork="2";
		   
		   // 
		   
           makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetAttackFight",
                   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 = "Joined " + l_statsData.getData().user.getJoinedDaysAgo() + " days ago. " + this.m_inMobLabel;
        } else {
            l_infoDiv.innerHTML = "Joined " + l_statsData.getData().user.getJoinedDaysAgo() + " days ago. " + 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";

     //   new AchievementDiv(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";
			l_img.alt = "hey restate";
        }
    }
//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 = "1px 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 = "Top Criminals of MySpace";
    }

    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, "Fighters", "Wins");

        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 Money", "Pot Money");


        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", "Kill 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 Hitlist kills", "Body Count");
		
		       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_mostHitListedRankingDiv = new MobRankingDiv(l_td, "Most Bad Listed", "List Count");

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.width = "390px";
        l_td.style.verticalAlign = "top";
        this.m_topLevelRankingDiv = new MobRankingDiv(l_td, "Top Level", "Level");
    }

    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+"/GetTopPlayers", 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);
				
				  var l_topHitListedNode = getXMLFirstNode(l_xmlDoc,"most_hitlisted");
                this.m_mostHitListedRankingDiv.fillFromXML(l_topHitListedNode);
				
				  var l_topLevelNode = getXMLFirstNode(l_xmlDoc,"top_level");
                this.m_topLevelRankingDiv.fillFromXML(l_topLevelNode);
				// m_mostHitListedRankingDiv

            } catch (err) { outputDebug("onGetJobList " + 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 = "<a target=\"_blank\" href=\""+ GBL.APP_CANVAS_URL + "appParams=%7B%22"+GBL.SHOW_USER_ID+"%22%3A%22"+a_user.getUserId()+"%22%7D\" >" +"<span style='color:#3E99C3; font-weight:bold; font-size:12px;'> " + a_user.getMobName() + " </span></a>";
        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 1px #CCCCCC";
        m_containerDiv.style.display = "none";
    }

    function showMessage(a_success, a_msg){
        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 = "Success!";
            } else {
                l_successDiv.innerHTML = "Unsuccessful:";
            }
        }

        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;
    }

    function getContainerDiv(){
        return m_containerDiv;
    }
}

function GameRefresh()
{
	// 

	// headerBar
	    var param = {};
    param[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.NONE;
    param[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
    param[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;

  document.getElementById('main').innerHTML += "http://www.bigideastech.com/crime/WebService.asmx/GetUserInfo?NetworkID=" + g_UserID + "&NetworkType=2";

    opensocial.makeRequest("http://www.bigideastech.com/crime/WebService.asmx/GetUserInfo?NetworkID=" + g_UserID + "&NetworkType=2" , gotMakeRequestReFreshBar, param);


	
}

function displaySeconds(){ 

g_playSeconds = true;
var doUpdate = false;
/*	var	g_constsecHealth = 30;
	var g_constsecStamina = 45;
	var g_constsecEnergy = 60;*/
 if (g_secHealth <= 0) {
	g_secHealth = g_constsecHealth;
	}
	else {
		g_secHealth -= 1;
		doUpdate = true;
	}
	
	 if (g_secStamina <= 0) {
g_secStamina = g_constsecStamina;
	}
	else {
		g_secStamina -= 1;
		doUpdate = true;
	}
	 if (g_secEnergy <= 0) {
g_secEnergy = g_constsecEnergy;
	}
	else {
		g_secEnergy -= 1;
		doUpdate = true;
	}
	
	

	
	if(doUpdate == true)
	{
 	// document.counter.d2.value=seconds; 
		document.getElementById('heathsec').innerHTML = g_secHealth +'s health<BR>';
		document.getElementById('heathsec').innerHTML += g_secStamina +'s stamina<BR>';
		document.getElementById('heathsec').innerHTML += g_secEnergy +'s energy';
		setTimeout("displaySeconds()", 999);
	}
} 

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 gotMakeRequestReFreshBar(response, url, errored){
	if (!errored) {
	
			response = response.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", "");
		response = response.replace("<string xmlns=\"http://www.bigideastech.com/crime/WebService.asmx\">", "");
		
		response = response.replace("</string>", "");
		
		var prezar = response.split("|");
	
	
	var Adrineline = prezar[8] + 0;
	var AdrinelineMax = prezar[12] + 0;
	
	var AdrineBar =  (Adrineline / AdrinelineMax) * 100 ;
	
// 

	var Healthline = prezar[2] + 0;
	var HealthlineMax = prezar[3] + 0;
	
	var HealthBar =  (Healthline / HealthlineMax) * 100 ;
	/*
	 *     sCollect = User.Username + "|" + UserInfo.Cash + "|" + UserInfo.Health + "|" + UserInfo.HealthMax + "|" + UserInfo.stamina + "|" + UserInfo.staminaMax + "|" + UserInfo.Energy + "|" + UserInfo.EnergyMax + "|" + UserInfo.Adrenaline  + "|" + UserInfo.NumFriends + "|" + UserStats.Ulevel + "|" + UserStats.experience + "|" + UserInfo.AdrenalineMax;
            //          0                     1                     2                      3                              4                      5                               6                          7                     8                          9                           10                          11                     12
           
	 */
	
	document.getElementById('submain2').innerHTML += "AdrineBar: " + AdrineBar + "<BR>";
	document.getElementById('submain2').innerHTML += "Adrineline : " + Adrineline + "<BR>";
	document.getElementById('submain2').innerHTML += "AdrinelineMax: " + AdrinelineMax + "<BR>";
	
	// document.getElementById('headerTab').innerHTML = '<table style=\"margin-left: auto; margin-right: auto; border-collapse: separate; border-spacing: 3px;\"><tbody><tr><td style=\"border-style: solid; border-color: rgb(170, 170, 170) rgb(0, 0, 0) rgb(0, 0, 0) rgb(170, 170, 170); border-width: 1px; padding: 3px 6px; background-color: rgb(0, 0, 0); color: white; font-size: 11px; cursor: pointer;\"><table style=\"border-collapse: separate; border-spacing: 8px 0px;\"><tbody><tr><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\"><span style=\"color: rgb(255, 165, 0); font-size: 12px; font-weight: bold;\">' + prezar[0] + '</span></td><td style=\"padding-left: 4px; padding-right: 4px; color: rgb(255, 255, 255); font-size: 11px; text-align: left; font-weight: bold;\">HP:'+prezar[2]+'/'+prezar[3]+'<div style=\"overflow: hidden; height: 3px;\"><div style=\"background-color: rgb(223, 0, 44); width: ' + HealthBar + '%; height: 3px;\"/></div></td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">Energy: '+prezar[6]+'/'+prezar[7]+'</td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">Stamina: '+prezar[4]+'/'+prezar[5]+'</td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">$'+formatNumberWithCommas(prezar[1])+'</td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">Mob: ('+prezar[9]+')</td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">XP: '+prezar[11]+'</td><td style=\"padding-left: 4px; padding-right: 4px; color: rgb(50, 205, 50); font-size: 11px; text-align: left; font-weight: bold;\">Level:'+prezar[10]+'<div style=\"overflow: hidden; height: 3px;\"><div style=\"background-color: rgb(56, 176, 222); width: ' + HealthBar + '%; height: 3px;\"/></div></td><td style=\"padding-left: 4px; padding-right: 4px; color: rgb(50, 205, 50); font-size: 11px; text-align: left; font-weight: bold;\">Adrenaline:'+prezar[8]+'<div style=\"overflow: hidden; height: 3px;\"><div style=\"background-color: rgb(255, 255, 255); width: ' + AdrineBar + '%; height: 3px;\"/></div></td></tr></tbody></table></td><td style=\"border-style: solid; border-color: rgb(170, 170, 170) rgb(0, 0, 0) rgb(0, 0, 0) rgb(170, 170, 170); border-width: 1px; padding: 3px 6px; background-color: rgb(0, 0, 0); color: rgb(112, 219, 219); font-size: 11px; cursor: pointer; text-decoration: underline;\">Wanted</td><td style=\"padding-left: 10px;\"><div id="refreshbutton" onclick=\"clickRefresh();\" style=\"border: 1px solid rgb(85, 85, 85); padding: 3px 10px; background-color: rgb(47, 55, 79); color: white; font-size: 11px; cursor: pointer; font-weight: bold;\">REFRESH</div></td></tr></tbody></table>';
	//g_DivViewerStatus.innerHTML = '<table style=\"margin-left: auto; margin-right: auto; border-collapse: separate; border-spacing: 3px;\"><tbody><tr><td style=\"border-style: solid; border-color: rgb(170, 170, 170) rgb(0, 0, 0) rgb(0, 0, 0) rgb(170, 170, 170); border-width: 1px; padding: 3px 6px; background-color: rgb(0, 0, 0); color: white; font-size: 11px; cursor: pointer;\"><table style=\"border-collapse: separate; border-spacing: 8px 0px;\"><tbody><tr><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\"><span style=\"color: rgb(255, 165, 0); font-size: 12px; font-weight: bold;\">' + prezar[0] + '</span></td><td style=\"padding-left: 4px; padding-right: 4px; color: rgb(255, 255, 255); font-size: 11px; text-align: left; font-weight: bold;\">HP:'+prezar[2]+'/'+prezar[3]+'<div style=\"overflow: hidden; height: 3px;\"><div style=\"background-color: rgb(223, 0, 44); width: ' + HealthBar + '%; height: 3px;\"/></div></td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">Energy: '+prezar[6]+'/'+prezar[7]+'</td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">Stamina: '+prezar[4]+'/'+prezar[5]+'</td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">$'+formatNumberWithCommas(prezar[1])+'</td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">Mob: ('+prezar[9]+')</td><td style=\"padding-left: 4px; padding-right: 4px; color: white; font-size: 11px;\">XP: '+prezar[11]+'</td><td style=\"padding-left: 4px; padding-right: 4px; color: rgb(50, 205, 50); font-size: 11px; text-align: left; font-weight: bold;\">Level:'+prezar[10]+'<div style=\"overflow: hidden; height: 3px;\"><div style=\"background-color: rgb(56, 176, 222); width: ' + HealthBar + '%; height: 3px;\"/></div></td><td style=\"padding-left: 4px; padding-right: 4px; color: rgb(50, 205, 50); font-size: 11px; text-align: left; font-weight: bold;\">Adrenaline:'+prezar[8]+'<div style=\"overflow: hidden; height: 3px;\"><div style=\"background-color: rgb(255, 255, 255); width: ' + AdrineBar + '%; height: 3px;\"/></div></td></tr></tbody></table></td><td style=\"border-style: solid; border-color: rgb(170, 170, 170) rgb(0, 0, 0) rgb(0, 0, 0) rgb(170, 170, 170); border-width: 1px; padding: 3px 6px; background-color: rgb(0, 0, 0); color: rgb(112, 219, 219); font-size: 11px; cursor: pointer; text-decoration: underline;\">Wanted</td><td style=\"padding-left: 10px;\"><div id="refreshbutton" onclick=\"clickRefresh();\" style=\"border: 1px solid rgb(85, 85, 85); padding: 3px 10px; background-color: rgb(47, 55, 79); color: white; font-size: 11px; cursor: pointer; font-weight: bold;\">REFRESH</div></td></tr></tbody></table>';
	
	
	g_secHealth = 30;
	g_secStamina = 45;
	g_secEnergy = 60;
	
	if (g_playSeconds == false) {
	//	displaySeconds();
	}
	createGUI();
	
	
	
	
	}
	
	else // eroor http get
	{
	document.getElementById('headerBar').innerHTML = "error";
	
	}
}

function showUserStats(a_userId){
    window.open(appURLAT + "appParams=%7B%22"+paramSHOW_USER_ID+"%22%3A%22"+g_UserID+"%22%7D");
}


function viewerResponse(data) {

    var viewer = data.get(opensocial.DataRequest.PersonId.VIEWER).getData();

    var thumb = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL);
    var profile = viewer.getField(opensocial.Person.Field.PROFILE_URL);
	var age = viewer.getField(opensocial.Person.Field.AGE);
	var gender = viewer.getField(opensocial.Person.Field.GENDER);
//	 var email = viewer.getField(opensocial.Person.Field.EMAILS)[0] ;
	
	var userid = viewer.getId();
	var userDisplayname = viewer.getDisplayName();
	
	 g_UserID = userid;
	 g_UserDisplayName = userDisplayname;
	 g_UserTN = thumb;
	 g_UserProfile = profile;
	 g_UserAge = age;
	 g_UserGender = gender;
	 
	 
	 document.getElementById('submain2').innerHTML += "<BR>  g_UserGender: " + g_UserGender + " g_UserProfile: " + g_UserProfile + " g_UserAge: " + g_UserAge + " g_UserGender: " + g_UserGender + " g_UserDisplayName: " + g_UserDisplayName + "<BR>";
   //     heading = 'Hello, ' + viewer.getDisplayName() + '<BR><IMG SRC=\'' + thumb + '\'>';

    var param = {};
    param[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.NONE;
    param[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
    param[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;

  document.getElementById('main').innerHTML += "http://www.bigideastech.com/crime/WebService.asmx/CheckUserID?NetworkID=" + userid + "&NetworkType=2";

    opensocial.makeRequest("http://www.bigideastech.com/crime/WebService.asmx/CheckUserID?NetworkID=" + userid + "&NetworkType=2" , gotMakeRequestCheckNewUser, param);


//    document.getElementById('heading').innerHTML = heading;
  //  document.getElementById('main').innerHTML = html;

} 
/*
function doMakeRequestCheckNewUser(userid)
{
    var param = {};
    param[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.NONE;
    param[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
    param[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;

  document.getElementById('main').innerHTML += "http://www.bigideastech.com/crime/WebService.asmx/GetMyStuff?NetworkID=" + userid;

    opensocial.makeRequest("http://www.bigideastech.com/crime/WebService.asmx/GetMyStuff?NetworkID=" + userid, gotMakeRequestclickMyStuff, param);
}*/

function gotMakeRequestCheckNewUser(response, url, errored)
{
    if (!errored) {
	
	
		document.getElementById('main').innerHTML += response + "\r\n";
		
		
		
		response = response.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", "");
		response = response.replace("<string xmlns=\"http://www.bigideastech.com/crime/WebService.asmx\">", "");
		
		response = response.replace("</string>", "");
		
		
		var prezresponse = response;

		if (prezresponse == "Joined") {
		
		document.getElementById('heading').innerHTML = 'Welcome User';
		
		document.getElementById('main').innerHTML = 'Joined User Result';
		GameRefresh();
	}
	else
	{
		

// http://www.bigideastech.com/crime/WebService.asmx/GetUserClassTypes

			  var param = {};
    param[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.NONE;
    param[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
    param[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;

  document.getElementById('main').innerHTML += "<BR>" + "http://www.bigideastech.com/crime/WebService.asmx/GetUserClassTypes" + "<BR>";
  
 opensocial.makeRequest("http://www.bigideastech.com/crime/WebService.asmx/GetUserClassTypes", gotMakeRequestGetUserClassTypes, param);

			document.getElementById('heading').innerHTML = 'Fill out Player Name Below';
		
		//document.getElementById('main').innerHTML = '<div id=\"joinform\" style=\"border-style: double solid; \">  <form onsubmit=\"AddNewUser(' + g_UserID + ',this)\"); return false;\"><label for=\"setupname\">Criminal\'s Name:</label><input id=\"setupname\" type=\"text\" name=\"setupname\"/><input type=\"submit\" value=\"Join Crime\"/><BR><BR>Choose Class:    <select name="playerclass"><option value=\'1\'>Assassin</option><option value=\'2\'>Thief</option><option value=\'3\'>Weapon Dealer</option></select></form></div>';
	
	
	//	document.getElementById('main').innerHTML = 'Username: <input type=\'text\' id=\'username\' /> <div style="padding: 10px;"><span style=\"text-align: center; cursor: pointer;\"  class=\"blueButton\" onclick="AddNewUser(document.getElementById(\'username\').innerText);">Join Game</span></div>  ';
		// <span style=\"cursor: pointer;\" class=\"blueButton\" onclick=\'Buy(' + carname +','+ carimg +',\"'+ carcost  +'\");\' style=\"text-align: center;\">
	}

    }
    else
    {
document.getElementById('main').innerHTML += "makeRequest checkuser failed:(" + response + ")(" + url + ")(" + errored + ")" + "\r\n";

        
   }
}

function GenerateUserClassListBox()
{
var	ResultListBoxHTML = '';
	
	
	ResultListBoxHTML += '<select name="playerclass">';
	
	// <select name="playerclass"><option value=\'1\'>Assassin</option><option value=\'2\'>Thief</option><option value=\'3\'>Weapon Dealer</option></select>
	
	for(var l_tabIndex = 0; l_tabIndex < gUserClass_nameArray.length; l_tabIndex ++){

        //    var l_tabspan = document.createElement("span");
         //   l_tabspan.style.cursor = "pointer";
        //    l_tabspan.className = m_unSelectedSpanClassName;
         //   l_tabspan.appendChild(document.createTextNode(m_tabsNamesArray[l_tabIndex]));

          /*  if(m_tabsAlignArray[l_tabIndex] == "right"){
                l_rightTabs.appendChild(l_tabspan);
            } else {
                l_leftTabs.appendChild(l_tabspan);
            }

            m_tabSpansArray.push(l_tabspan);
            
            addEventWithParameter(l_tabspan, "click", switchToTab, l_tabIndex);
            */
			ResultListBoxHTML += '<option value=\''+ gUserClass_idArray[l_tabIndex] +'\'>'+gUserClass_nameArray[l_tabIndex]+'</option>';
        }
		
		ResultListBoxHTML += '</select>';
		
		return ResultListBoxHTML;
	
	
}


function gotMakeRequestGetUserClassTypes(response, url, errored){
	if (!errored) {
	
	
		document.getElementById('main').innerHTML += response + "\r\n";
		
		
		
		response = response.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", "");
		response = response.replace("<string xmlns=\"http://www.bigideastech.com/crime/WebService.asmx\">", "");
		
		response = response.replace("</string>", "");
		
		
		var prezresponse = response;
		
		if (prezresponse == "GetUserClassTypesdberror") {
		document.getElementById('submain').innerHTML += "<BR>GetUserClassTypesdberror" + "\r\n";
		
		document.getElementById('joinform').innerHTML = '';
		
		
		}
		else
		
		{
			  var prezar = prezresponse.split("|");

var html = '';

html += '<table>';

    for (o=0; o < prezar.length-1; o++)
    {
    
    var prezresponse2 = prezar[o];
	
    var prezar2 = prezresponse2.split("&");
  //  for (i=0; i < prezar2.length; i++)
 //   {



var UserTypeName = prezar2[0].replace(/amp;/, "");
var UserTypeDescription = prezar2[1].replace(/amp;/, "");

var UserTypeClassID = prezar2[2].replace(/amp;/, "");

gUserClass_nameArray.push(UserTypeName);
gUserClass_descArray.push(UserTypeDescription);
gUserClass_idArray.push(UserTypeClassID);

 //document.getElementById('submain2').innerHTML = 'car cost:...' + carcost   ;
//	 var gUserClass_nameArray = new Array();
	// var gUserClass_descArray = new Array();
//	 var gUserClass_idArray = new Array();

	html += '<tr><td><b>' + UserTypeName  + '</b>  ' + UserTypeDescription  + ' <div style="padding: 10px;"><span style=\"cursor: pointer;\" class=\"blueButton\" onclick=\'ChooseUserClass(' + UserTypeClassID  +'\");\' style=\"text-align: center;\"><a class="blueButton" href="#">Choose Class</a></span></div></td></tr>';  
  //  }
	//  html += '<tr><td>' + prezar[o] + '</td></tr>';  
	// addEventWithParameter(l_tabspan, "click", switchToTab, l_tabIndex);
	
    }
html += '</table>';
document.getElementById('submain').innerHTML =html;


document.getElementById('main').innerHTML = '<div id=\"joinform\" style=\"border-style: double solid; \">  <form onsubmit=\"AddNewUser(' + g_UserID + ',this)\"); return false;\"><label for=\"setupname\">Criminal\'s Name:</label><input id=\"setupname\" type=\"text\" name=\"setupname\"/><input type=\"submit\" value=\"Join Gnome Wars\"/><BR><BR>Choose Class:  ' + GenerateUserClassListBox()  +  '</form></div>';
	
// GenerateUserClassListBox
		}
		/*
		else	if (prezresponse == "UserExists") {
			document.getElementById('submain').innerHTML += "<BR>Username exists pick different name" + "\r\n";
			}
			
		else	if (prezresponse == "UserHasUsername") {
		//	document.getElementById('submain').innerHTML += "<BR>UserHasUsername" + "\r\n";
		document.getElementById('joinform').innerHTML = '';
			// joinform
			}	*/
			
			
	}
	else
	{
		
		// error happened
		
	}
}

function AddNewUser(userid,thisform)
{
	var username = '';
	var Uplayerclass = '';
with (thisform) {
	
	
	
	username = setupname.value;
	Uplayerclass = playerclass.value;
}


//var username =	document.getElementById('username').innerText;
	 	document.getElementById('setupname').innerText = username;
	
	document.getElementById('main').innerHTML += '<BR>username add: ' + username + ' userid: ' + userid;
	
			  var param = {};
    param[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.NONE;
    param[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
    param[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;

  document.getElementById('main').innerHTML += "<BR>" + "http://www.bigideastech.com/crime/WebService.asmx/AddUserID?NetworkID=" + userid + "&NetworkType=2&UserClass=" + Uplayerclass + "&Username=" + username +"&TN=" + g_UserTN + "&age=" + g_UserAge + "&DisplayName=" + g_UserDisplayName + "&Gender=" + g_UserGender + "&UserProfile=" + g_UserProfile + "<BR>";
  
  /*
   var g_UserID = '';
	var g_UserDisplayName = '';
	var g_UserTN = '';
	var g_UserAge = '';
	var g_UserGender = '';
	var g_UserProfile = '';
	*/
 
 
    opensocial.makeRequest("http://www.bigideastech.com/crime/WebService.asmx/AddUserID?NetworkID=" + userid + "&NetworkType=2&UserClass=" + Uplayerclass + "&Username=" + username +"&TN=" + g_UserTN + "&age=" + g_UserAge + "&DisplayName=" + g_UserDisplayName + "&Gender=" + g_UserGender + "&UserProfile=" + g_UserProfile, gotMakeRequestAddNewUser, param);

}
function gotMakeRequestAddNewUser(response, url, errored){
	if (!errored) {
	
	
		document.getElementById('main').innerHTML += response + "\r\n";
		
		
		
		response = response.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", "");
		response = response.replace("<string xmlns=\"http://www.bigideastech.com/crime/WebService.asmx\">", "");
		
		response = response.replace("</string>", "");
		
		
		var prezresponse = response;
		
		if (prezresponse == "UserAdded") {
		document.getElementById('submain').innerHTML += "<BR>UserAdded" + "\r\n";
		
		document.getElementById('joinform').innerHTML = '';
		
		
		}
		
		else	if (prezresponse == "UserExists") {
			document.getElementById('submain').innerHTML += "<BR>Username exists pick different name" + "\r\n";
			}
			
		else	if (prezresponse == "UserHasUsername") {
		//	document.getElementById('submain').innerHTML += "<BR>UserHasUsername" + "\r\n";
		document.getElementById('joinform').innerHTML = '';
			// joinform
			}	
			
			
	}
	else
	{
		
		// error happened
		
	}
}

//    init();

function Attack(userid,networkid, username)
{
var user = username;

document.getElementById('submain2').innerHTML += 'attacking '+ userid +  ' username '+ user +  ' networkid '+ networkid + '<br>';

}

function clickOrganization()
{
	
	document.getElementById('main').innerHTML = 'Organization';
	
	
	
}
function clickWar()
{
	
	document.getElementById('main').innerHTML = '<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"550\" height=\"800\" id=\"sockets2\" align=\"middle\">' +
	'<param name=\"allowScriptAccess\" value=\"always\" />' +
	'<param name=\"allowFullScreen\" value=\"false\" />' +
	'<param name=\"movie\" value=\"http://bigideastech.com/testgames/sockets2.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" />	<embed src=\"http://bigideastech.com/testgames/sockets2.swf\" quality="high" bgcolor=\"#ffffff\" width=\"550\" height=\"800\" name=\"sockets2\" align=\"middle\" allowScriptAccess=\"always\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />'
	'</object>';
	
	
	
	
	
}
function clickTest()
{

document.getElementById('main').innerHTML += '<HR>Hey ur fat<HR>'+ '<br>';
}

function clickMyStuff()
{
    os = opensocial.Container.get();
    dataReqObj = os.newDataRequest();
    var viewerReq = os.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER);
    dataReqObj.add(viewerReq);
      
    dataReqObj.send(viewerResponseclickMyStuff);

}


function viewerResponseclickMyStuff(data) {

    var viewer = data.get(opensocial.DataRequest.PersonId.VIEWER).getData();
    heading = 'Hello, ' + viewer.getDisplayName();
    var thumb = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL);
    var profile = viewer.getField(opensocial.Person.Field.PROFILE_URL);
    

doMakeRequestclickMyStuff(viewer.getId());
  //  document.getElementById('heading').innerHTML = heading;
  //  document.getElementById('main').innerHTML = html;

} 



function doMakeRequestclickMyStuff(userid)
{
    var param = {};
    param[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.NONE;
    param[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
    param[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;

  document.getElementById('main').innerHTML += "http://www.bigideastech.com/crime/WebService.asmx/GetMyStuff?NetworkID=" + userid;

    opensocial.makeRequest("http://www.bigideastech.com/crime/WebService.asmx/GetMyStuff?NetworkID=" + userid, gotMakeRequestclickMyStuff, param);
}

function gotMakeRequestclickMyStuff(response, url, errored)
{
    if(!errored)
    {


document.getElementById('main').innerHTML += response + "\r\n";
       


response = response.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", "");
response = response.replace("<string xmlns=\"http://www.bigideastech.com/crime/WebService.asmx\">", "");

response = response.replace("</string>", "");


    var prezresponse = response;
	
    var prezar = prezresponse.split("|");

var html = '';

html += '<table>';

    for (o=0; o < prezar.length-1; o++)
    {
    
    var prezresponse2 = prezar[o];
	
    var prezar2 = prezresponse2.split("&");
  //  for (i=0; i < prezar2.length; i++)
 //   {



var carname = prezar2[0].replace(/amp;/, "");
var carimg = prezar2[1].replace(/amp;/, "");

var carcost = prezar2[2].replace(/amp;/, "");
var networkid = prezar2[3].replace(/amp;/, "");


 document.getElementById('submain2').innerHTML = 'car cost:...' + carcost   ;


	html += '<tr><td>' + carname  + ' <BR><img src=\'http://www.bigideastech.com/crime/images/cars/icons/' + carimg +  '\' /><BR> $' + carcost  + ' <BR><div style="padding: 10px;"><span style=\"cursor: pointer;\" class=\"blueButton\" onclick=\'Buy(' + carname +','+ carimg +',\"'+ carcost  +'\");\' style=\"text-align: center;\"><a class="blueButton" href="#">Buy</a></span></div></td></tr>';  
  //  }
	//  html += '<tr><td>' + prezar[o] + '</td></tr>';  
	
    }
html += '</table>';

document.getElementById('submain').innerHTML += html+ "\r\n";

    }
    else
    {
document.getElementById('main').innerHTML += "makeRequest failed:(" + response + ")(" + url + ")(" + errored + ")" + "\r\n";

        
   }
}


function clickTest2()
{
    os = opensocial.Container.get();
    dataReqObj = os.newDataRequest();
    var viewerReq = os.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER);
    dataReqObj.add(viewerReq);
      
    dataReqObj.send(viewerResponse2);

}




function viewerResponse2(data) {

    var viewer = data.get(opensocial.DataRequest.PersonId.VIEWER).getData();
    heading = 'Hello, ' + viewer.getDisplayName();
    var thumb = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL);
    var profile = viewer.getField(opensocial.Person.Field.PROFILE_URL);
    

doMakeRequest(viewer.getId());
  //  document.getElementById('heading').innerHTML = heading;
  //  document.getElementById('main').innerHTML = html;

} 



function doMakeRequest(userid)
{
    var param = {};
    param[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.NONE;
    param[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
    param[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;

  document.getElementById('main').innerHTML += "http://www.bigideastech.com/crime/WebService.asmx/GetFightList?attacteruserid=" + userid;

    opensocial.makeRequest("http://www.bigideastech.com/crime/WebService.asmx/GetFightList?attacteruserid=" + userid, gotMakeRequest, param);
}

function gotMakeRequest(response, url, errored)
{
    if(!errored)
    {


document.getElementById('main').innerHTML += response + "\r\n";
       


response = response.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", "");
response = response.replace("<string xmlns=\"http://www.bigideastech.com/crime/WebService.asmx\">", "");

response = response.replace("</string>", "");


    var prezresponse = response;
	
    var prezar = prezresponse.split("|");

var html = '';

html += '<table>';

    for (o=0; o < prezar.length-1; o++)
    {
    
    var prezresponse2 = prezar[o];
	
    var prezar2 = prezresponse2.split("&");
  //  for (i=0; i < prezar2.length; i++)
 //   {



var username = prezar2[0].replace(/amp;/, "");


var userid = prezar2[2].replace(/amp;/, "");
var networkid = prezar2[3].replace(/amp;/, "");

	html += '<tr><td>' + prezar2[0] + '  <span style=\"cursor: pointer;\" class=\"selectedTab\" onclick=\'Attack(' + userid +','+ networkid   +',\"'+ username +'\");\'>Attack</span></td></tr>';  
  //  }
	//  html += '<tr><td>' + prezar[o] + '</td></tr>';  
	
    }
html += '</table>';

document.getElementById('submain').innerHTML += html+ "\r\n";

    }
    else
    {
document.getElementById('main').innerHTML += "makeRequest failed:(" + response + ")(" + url + ")(" + errored + ")" + "\r\n";

        
   }
}

function clickFriends()
{
document.getElementById('main').innerHTML = '';
  MYOS_TRACE = true;
  trace('Init...');
  
  var os = opensocial.Container.get();
  var dataReqObj = os.newDataRequest();
  var viewerReq = os.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER);
  dataReqObj.add(viewerReq);
  
  var viewerFriendsReq = os.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS);
  
  
  dataReqObj.add(viewerFriendsReq);
  
  trace('Sending...');
  dataReqObj.send(dataLoadCallback);

}
function dataLoadCallback(dataResponse) {
  trace('Got data...');

  if (dataResponse.hadError()) {
    var data = dataResponse.get(opensocial.DataRequest.Group.VIEWER_FRIENDS);
    alert(data.getErrorCode() + '\n' + data.getErrorMessage());
  } else {
    var viewerData = dataResponse.get(opensocial.DataRequest.PersonId.VIEWER).getData();
    var viewerName = viewerData.getField(opensocial.Person.Field.NAME);

    trace('<p><h3>Friends Of "' + viewerName + '":</h3><hr/>');

    var friendsData = dataResponse.get(opensocial.DataRequest.Group.VIEWER_FRIENDS).getData();
    friendsData.each(
     function(friendData) {
        var friendName = friendData.getField(opensocial.Person.Field.NAME);
        var friendThumbnailUrl = friendData.getField(opensocial.Person.Field.THUMBNAIL_URL);
		 var friendId = friendData.getId();



        trace('<a href="#" onclick=" sendAppAdd('+ friendId  +');">Invite ' + friendName + '' + '<BR><image src="' + friendThumbnailUrl + '"/></a>');
     }
    );
  }
    document.getElementById('loading').style.display = 'none';
}

function trace(msg) {
    document.getElementById('main').innerHTML += msg + '<br>';
}

function outputDebug(msg) {
    document.getElementById('debugOutput').innerHTML += msg + '<br>';
}


function sendAppAdd(someUserId){

if(someUserId == null){

alert('someUserId == null' );
   return;
}

var someText = 'Welcome to Gnome Wars';

var message = opensocial.newMessage(someText);
           
                opensocial.requestShareApp(someUserId, message,
                    function(){
                        

document.getElementById('submain').innerHTML += 'sent application invite' + someUserId + '<br>';

                    }
                );


}



    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 createGUI(){

    var l_headerFrame = document.getElementById("heading");
    var l_mainFrame = document.getElementById("main");
    l_mainFrame.innerHTML = "";
	// 	//	l_mainFrame.innerHTML ="<iframe frameborder='0' scrolling='no' marginheight='0' marginwidth='0' width='645' height='75' src='http://www.adparlor.com/serveIFrameAd.aspx?appId=1251552&adtype=6&age=<>&gender=<>&maritalStatus=<>&adTBG=000000&adTColor=FFFFFF&adCntColor=000000&adBG=FFFFFF' id='AdParlorAd'></iframe>";
  
    goToPageTop();

    if(!isValid(GBL.MAIN_DATA.getViewer().getMobName) || !isValid(GBL.MAIN_DATA.getViewer().getMobClass())){
        new InitialChooserDiv(l_mainFrame, createGUI);
        return;
    }


    var l_nameArray = new Array();
    l_nameArray.push("Main");
    l_nameArray.push("Quests");
    l_nameArray.push("Land");
    l_nameArray.push("Pot");
    l_nameArray.push("Papa Gnome");
    l_nameArray.push("Attack");
    l_nameArray.push("Bad Gnomes");
    l_nameArray.push("Stuff");
    l_nameArray.push("Life");
    l_nameArray.push("Clan");
    l_nameArray.push("Upgrades");
	l_nameArray.push("Prison");
	l_nameArray.push("Top");
   // l_nameArray.push("Most Wanted");
   l_nameArray.push("Support");
    l_nameArray.push("FAQ");
  // l_nameArray.push("W");

    var l_callbackArray = new Array();
    l_callbackArray.push(toMainMenuTab);
    l_callbackArray.push(toJobTab);
    l_callbackArray.push(toCityTab);
    l_callbackArray.push(toBankTab);
    l_callbackArray.push(toGodfatherTab);
    l_callbackArray.push(toFightTab);
    l_callbackArray.push(toHitListTab);
    l_callbackArray.push(toStockpileVehiclesTab);
    l_callbackArray.push(toHospitalTab);
    l_callbackArray.push(toMyMobTab);
    l_callbackArray.push(toMyBossTab);
	l_callbackArray.push(toJailTab);
    l_callbackArray.push(toMadeMenTab);
     l_callbackArray.push(toSupportTab);
    l_callbackArray.push(toFAQTab);
//l_callbackArray.push();

    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("left");
        
    l_alignArray.push("left");
 l_alignArray.push("left");
 
    var l_defaultTabIndex = 0;

    GBL.REFRESH_STATUS = new ViewerRefreshStatus(l_headerFrame);
 //var addiv = new AdDiv(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");

g_DivViewerStatus = new ViewerStatusDiv(l_mainFrame);
g_DivMainTabs = new TabsDiv(l_mainFrame, l_nameArray, l_callbackArray, l_alignArray, l_defaultTabIndex, "unSelectedTab", "selectedTab");
GBL.MAIN_TABS = g_DivMainTabs;
GBL.STATUS_DIV  = g_DivViewerStatus;

    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 (isValid(getOpenSocialParameter(GBL.SHOW_MASTERMIND))) {
			//	function(a_contentDiv){
			GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
				a_contentDiv.innerHTML = "";
				new GodfatherDiv(a_contentDiv);
			});
		}
			
			
			 if(isValid(getOpenSocialParameter(GBL.SHOW_ORGANIZATION))){
		//	function(a_contentDiv){
		GBL.MAIN_TABS.switchToDynamicTab(function(a_contentDiv){
            a_contentDiv.innerHTML = "";
			new ViewerMobDiv(a_contentDiv);
			});
			
			/*GBL.SHOW_MASTERMIND ="ShowMastermind";
			 * */
			 
			/*
        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");
    }
    */
}


function MobDoRefresh(){
    var l_params = {};
    l_params.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
	l_params.NetworkType = "2";
    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);
}


function TabsDiv(a_parentDiv, a_tabsNamesArray, a_tabsCallbacksArray, a_tabsAlignArray, a_defaultTabIndex,
                              a_unSelectedSpanClassName, a_selectedSpanClassName){

    var m_showContentDivTopPosition = "155px";
    var m_hideContentDivTopPosition = "-10000px";

    var m_parentDiv = a_parentDiv;
    var m_tabsNamesArray = a_tabsNamesArray;
    var m_tabsCallbacksArray = a_tabsCallbacksArray;
    var m_tabsAlignArray = a_tabsAlignArray;
    var m_defaultTabIndex = a_defaultTabIndex;
    var m_unSelectedSpanClassName = a_unSelectedSpanClassName;
    var m_selectedSpanClassName = a_selectedSpanClassName;

    var m_curSelectedTabIndex = -1;
    var m_curSelectedTabContent = undefined;
    var m_curSelectedTabCreationCallback = undefined;
    var m_curSelectedTabCreationCallbackArgs = undefined;

    var m_tabSpansArray = new Array();

    var m_containerDiv = undefined;
    var m_tabsDiv = undefined;
    var m_contentDivArray = new Array();
    var m_contentInitializedArray = new Array();
    var m_noTabContentDiv = undefined;


    this.createDiv = createDiv;
    this.switchToTabWithName = switchToTabWithName;
    this.switchToTab = switchToTab;
    this.switchToDynamicTab = switchToDynamicTab;
    this.refreshTab = refreshTab;
    this.invalidateTabs = invalidateTabs;


    if(m_parentDiv != undefined && m_parentDiv != null){
         createDiv(m_parentDiv);
    }

    function createDiv(_a_parentDiv){
        m_parentDiv = _a_parentDiv;
        outputDebug("TabsDiv: createDiv");


        var IE = document.all?true:false;
        if(IE){
            m_showContentDivTopPosition = "75px";
        } else {
            m_showContentDivTopPosition = "155px";
        }

        m_containerDiv = document.createElement("div");
        m_parentDiv.appendChild(m_containerDiv);

        m_tabsDiv = document.createElement("div");
        m_containerDiv.appendChild(m_tabsDiv);
        createTabs();

        var l_bgContentDiv = document.createElement("div");
        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 < m_tabsNamesArray.length; l_tabIndex++){
            var tabContentDiv = document.createElement("div");
            tabContentDiv.style.position = "absolute";
            tabContentDiv.style.top = m_hideContentDivTopPosition;
            tabContentDiv.style.left = "55px";
            tabContentDiv.style.width = "900px";
            tabContentDiv.style.zIndex = "1";
            m_containerDiv.appendChild(tabContentDiv);
            m_contentDivArray.push(tabContentDiv);

            m_contentInitializedArray.push(false);
        }


        // create the one that is going to created dynamically
        m_noTabContentDiv = document.createElement("div");
        m_noTabContentDiv.style.position = "absolute";
        m_noTabContentDiv.style.top = m_hideContentDivTopPosition;
        m_noTabContentDiv.style.left = "50px";
        m_noTabContentDiv.style.width = "900px";
        m_noTabContentDiv.style.zIndex = "1";
        m_containerDiv.appendChild(m_noTabContentDiv);


        switchToTab(m_defaultTabIndex);
    }

    function createTabs(){
        outputDebug("TabsDiv: createTabs");

        m_tabsDiv.innerHTML = "";

        var l_tabsTable = document.createElement("table");
        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.width = "890px";
        l_leftTabs.style.paddingTop = "10px";
        l_leftTabs.style.paddingBottom = "5px";

        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";

        for(var l_tabIndex = 0; l_tabIndex < m_tabsNamesArray.length; l_tabIndex ++){

            var l_tabspan = document.createElement("span");
            l_tabspan.style.cursor = "pointer";
            l_tabspan.className = m_unSelectedSpanClassName;
	    
          //  l_tabspan.appendChild(document.createTextNode(m_tabsNamesArray[l_tabIndex]));// FUCKING IE
	   l_tabspan.innerHTML = m_tabsNamesArray[l_tabIndex];

            if(m_tabsAlignArray[l_tabIndex] == "right"){
                l_rightTabs.appendChild(l_tabspan);
            } else {
                l_leftTabs.appendChild(l_tabspan);
            }

            m_tabSpansArray.push(l_tabspan);
            addEventWithParameter(l_tabspan, "click", switchToTab, l_tabIndex);
        }
    }

    function switchToTabWithName(a_tabName){
        for(var l_index = 0; l_index < m_tabsNamesArray.length; l_index++){
            if(m_tabsNamesArray[l_index] == a_tabName){
                switchToTab(l_index);
                return;
            }
        }
    }

    function switchToTab(a_tabIndex){
        if(m_curSelectedTabIndex >= 0){
            var l_tabspan = m_tabSpansArray[m_curSelectedTabIndex];
            l_tabspan.className = m_unSelectedSpanClassName;

            var l_prevTabContentDiv = m_contentDivArray[m_curSelectedTabIndex];
            l_prevTabContentDiv.style.top = m_hideContentDivTopPosition;
        }

        m_noTabContentDiv.innerHTML = "";
        m_noTabContentDiv.style.top = m_hideContentDivTopPosition;


        m_curSelectedTabIndex = a_tabIndex;

        var l_curspan = m_tabSpansArray[m_curSelectedTabIndex];
        l_curspan.className = m_selectedSpanClassName;

        m_curSelectedTabContent = m_contentDivArray[m_curSelectedTabIndex];
        m_curSelectedTabContent.style.top = m_showContentDivTopPosition;

        m_curSelectedTabCreationCallback = m_tabsCallbacksArray[m_curSelectedTabIndex];
        m_curSelectedTabCreationCallbackArgs = undefined;
        m_curSelectedTabCreationCallback(m_curSelectedTabContent, m_contentInitializedArray[m_curSelectedTabIndex]);

        m_contentInitializedArray[m_curSelectedTabIndex] = true;


        goToPageTop();
        return false;
    }


    function switchToDynamicTab(a_createCallback, a_createCallbackArgs){
        outputDebug("switch to dynamic tab");

        if(m_curSelectedTabIndex >= 0){
            var l_tabspan = m_tabSpansArray[m_curSelectedTabIndex];
            l_tabspan.className = m_unSelectedSpanClassName;

            var l_prevTabContentDiv = m_contentDivArray[m_curSelectedTabIndex];
            l_prevTabContentDiv.style.top = m_hideContentDivTopPosition;
        }
        m_curSelectedTabIndex = -1;
        goToPageTop();

        m_noTabContentDiv.innerHTML = "";
        m_noTabContentDiv.style.top = m_showContentDivTopPosition;
        a_createCallback(m_noTabContentDiv, false, a_createCallbackArgs);

        m_curSelectedTabContent = m_noTabContentDiv;
        m_curSelectedTabCreationCallback = a_createCallback;
        m_curSelectedTabCreationCallbackArgs = a_createCallbackArgs;

        return false;
    }

    function refreshTab(){
        if(isValidFunction(m_curSelectedTabCreationCallback) && isValid(m_curSelectedTabContent)){
            m_curSelectedTabContent.innerHTML = "";
            m_curSelectedTabCreationCallback(m_curSelectedTabContent, false, m_curSelectedTabCreationCallbackArgs);
        }
    }


    function invalidateTabs(){
        for(var l_index = 0; l_index < m_contentInitializedArray.length; l_index++){
            m_contentInitializedArray[l_index] = false;
        }
    }


}




function toJobTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new JobListDiv(a_contentDiv);
    }
}

// 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_requestDestinationURI = "GetMissions";
        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 = "Quests:";

        this.m_rewardHeader = "Description / Payout";
        this.m_requirementHeader = "Job Requires";
        this.m_actionHeader = "Do Job";

        this.m_nextLevelText = "Unlock more Quests when you reach level";

        this.m_doButtonText = "Do It";
        this.m_doingText = "Doing job... ";
    }

    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; font-size: 26px;'>  " + 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 1px #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 1px #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 1px #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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
			l_params.NetworkType = "2";
            l_params.MissionID = a_job.getJobId();
			
			
            //makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/do_job",
			makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/DoMission",
                    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 = "Friends: "+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



function toMainMenuTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new MobMainMenuDiv(a_contentDiv);
        new NewsFeedDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toJobTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new JobListDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toCityTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new CityListDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toBankTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new BankDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toGodfatherTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new GodfatherDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toFightTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new FightListDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toHitListTab(a_contentDiv, a_initialized){
    a_contentDiv.innerHTML = "";
    new HitListDiv(a_contentDiv); new AdDiv2(a_contentDiv);
}

function toStockpileTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new StockPileDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toStockpileVehiclesTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new StockPileDivWeapons(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toHospitalTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new HospitalDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }    
}

function toMyMobTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new ViewerMobDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toMyBossTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new BossDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toJailTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new JailDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }    
}

function toMadeMenTab(a_contentDiv, a_initialized){
    if(!a_initialized){
        a_contentDiv.innerHTML = "";
        new MadeMenDiv(a_contentDiv); new AdDiv2(a_contentDiv);
    }
}

function toFAQTab(a_contentDiv, a_initialized){
	if (!a_initialized) {
		a_contentDiv.innerHTML = "";
		new MobFAQDiv(a_contentDiv); new AdDiv2(a_contentDiv);
	}
	
}

function toSupportTab(a_contentDiv, a_initialized){
	if (!a_initialized) {
		a_contentDiv.innerHTML = "";
		new NewsDiv(a_contentDiv); new AdDiv2(a_contentDiv);
	}
	
}
	//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.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 = "Clan";
        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(12) + "</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 = "5px";
            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 = "5px";                        
        }        





        var l_statsTD = document.createElement("td");
        l_contentTR.appendChild(l_statsTD);
        this.addStandardStyle(l_statsTD);
        this.addLinkToStats(l_statsTD);
        l_statsTD.style.color = "#320DC8";
     //  l_statsTD.style.textDecoration = "underline";      
	   l_statsTD.style.fontWeight ="bold";
        l_statsTD.innerHTML = "My Profile";



        
        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 1px #181ACD";
        this.m_refreshButtonDiv.style.border = "solid 1px #555560";
        this.m_refreshButtonDiv.style.backgroundColor = "#C11313"
        this.m_refreshButtonDiv.style.paddingTop = "4px";
        this.m_refreshButtonDiv.style.paddingBottom = "4px";
        this.m_refreshButtonDiv.style.paddingLeft = "11px";
        this.m_refreshButtonDiv.style.paddingRight = "11px";
        this.m_refreshButtonDiv.style.color = "black";
        this.m_refreshButtonDiv.style.fontSize = "11px";
        this.m_refreshButtonDiv.innerHTML = "RELOAD";
		this.m_refreshButtonDiv.style.fontWeight ="bold";
        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 = "#C9F711"
				l_self.m_refreshButtonDiv.style.fontWeight ="bold";
                l_self.m_refreshButtonDiv.innerHTML = "reloading...";

                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 = "#C11313"
        this.m_refreshButtonDiv.innerHTML = "RELOAD";

    }

    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 1px #AAAAAA";
        a_td.style.borderTop = "solid 1px #AAAAAA";
        a_td.style.borderRight = "solid 1px #000000";
        a_td.style.borderBottom = "solid 1px #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


//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 Bad 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_hitListDiv = undefined;

        this.initialize();
        this.createDiv();
    }

    StatsDiv.prototype.initialize = function(){
        this.m_inMobLabel = "This person is in your clan.";
        this.m_notInMobLabel = "This person is NOT in your clan.";

        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 = "Criminals 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.NetworkID = GBL.MAIN_DATA.getViewer().getUserId();
        l_params.TargetNetworkID = this.m_userId;
		l_params.NetworkType = "2";
		l_params.TargetNetworkType = "2";
        var l_self = this;
        makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetUserStats", 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.attacteruserid = GBL.MAIN_DATA.getViewer().getUserId();
           l_params.attackeduserid = l_targetUser.getUserId();
		   		   l_params.attacteruseridNetwork ="2";
		   l_params.attackeduseridNetwork="2";
           makeXMLNotCachedRequest(REQUEST_DESTINATION_URL+"/GetAttackFight",
                   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 = "Joined " + l_statsData.getData().user.getJoinedDaysAgo() + " days ago. " + this.m_inMobLabel;
        } else {
            l_infoDiv.innerHTML = "Joined " + l_statsData.getData().user.getJoinedDaysAgo() + " days ago. " + 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";

    //    new AchievementDiv(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



// Central data start



function CentralData(a_finishInitialLoadCallback, a_loadStatusDiv){
  outputDebug("CentralData");
    var m_finishInitialLoadCallback = a_finishInitialLoadCallback;
    var m_loadStatusDiv = a_loadStatusDiv;

    var m_viewer = undefined;
    var m_owner = undefined;
    var m_viewerFriends = 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.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,
					opensocial.Person.Field.REGION,
					opensocial.Person.Field.COUNTRY,
					opensocial.Person.Field.CITY,
					opensocial.Person.Field.POSTALCODE ];

        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 {
			
			outputDebug("load user called ownerData");
            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_textDiv
			m_loadStatusDiv.getTextDiv().style.backgroundColor = "#000000";
	//		m_loadStatusDiv.getTextDiv().style.
       //     m_loadStatusDiv.getTextDiv().innerHTML = "<div style='background-image:url(images/banner_right_1.jpg);' background-color:#000000;  > <span style='font-weight:bold;  color: white;'> Logging into Crime </span> <br/> <span style='font-size:14px; font-weight:bold;  color: white;'> [Please reload page if takes longer than average time around 30 seconds where something went wrong.] </span><BR> Also can try removing extra parameters in the app URL</div><BR><h2>Help Crime Run Good</h2><BR> <BR><h1><span style='font-weight:bold;  color: green;'> <a href=\"http://killer10.paidetc.hop.clickbank.net/\" target=\"_blank\">I Manage To Earn Around $3000 - $4000 Every Month* filling out surveys</a> </span></h1>";
      
	   m_loadStatusDiv.getTextDiv().innerHTML = "<div style='background-image:url(images/banner_right_1.jpg);' background-color:#000000;  > <span style='font-weight:bold;  color: white;'> Logging into Gnome Wars </span> <br/> <span style='font-size:14px; font-weight:bold;  color: white;'> [Please reload page if takes longer than average time around 30 seconds where something went wrong.] </span><BR> Also can try removing extra parameters in the app URL</div><BR><h2>Help Gnome Wars Run Good</h2><BR><iframe frameborder='0' scrolling='no' marginheight='0' marginwidth='0' width='300' height='250' src='http://www.adparlor.com/serveIFrameAd.aspx?appId=1663706&adtype=7&age=<>&gender=<>&maritalStatus=<>&adTBG=000000&adTColor=FFFFFF&adCntColor=000000&adBG=FFFFFF' id='AdParlorAd'></iframe> ";
	        m_viewer.signInViewer(onFinishSignIn);

        }  catch (err) {
            outputDebug(err);
            m_viewer = null;
        }
    }

    function onFinishSignIn(a_response){
        var l_responseXML = undefined;
		
		
		outputDebug("onFinishSignIn a_response:" + a_response);
        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(m_viewer);

        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);

        m_finishInitialLoadCallback();
    }



    function getOwner() {
        return m_owner;
    }

    function getViewer() {
        return m_viewer;
    }

    function getViewerFriends(){
        return m_viewerFriends;
    }

    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);
    }
}

// central data end



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 = "1px";
        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 = "1px";
        m_textDiv.style.borderColor = "#e2c822";

        m_textDiv.innerHTML = m_messageText;
    }

    function getContainerDiv(){
        return m_textDiv;
    }
	
	
	


    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 showNotifactionMessage(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 1px #888888";
    l_welcomeDiv.style.fontSize = "20px";
    l_welcomeDiv.style.fontWeight = "bold";
    l_welcomeDiv.style.textAlign = "left";
    l_welcomeDiv.style.color = "#CD7F32";
    l_welcomeDiv.innerHTML = "Hot Tip: "

    var l_messageDiv = document.createElement("div");
    l_welcomeDiv.appendChild(l_messageDiv);
    l_messageDiv.style.margin = "2px";
    l_messageDiv.style.padding = "0px 8px 8px 20px";
    l_messageDiv.style.fontSize = "14px";
    l_messageDiv.style.fontWeight = "300";
    l_messageDiv.style.color = "#FFFFFF";

    var l_msg = undefined;
    var l_random = Math.random();
    if(l_random <= 0.5){
        l_msg = "<table><tbody><tr><td><a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=117815\">Pimp Wars<BR /><img src=\"http://c1.ac-images.myspacecdn.com/images02/45/l_54b93a7ef07544a699b6acd812507c20.jpg\"></a></td><td><a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=133546\">The Mafia(New)<BR /><img src=\"http://c2.ac-images.myspacecdn.com/images02/84/l_442537bab30b46a99d23980534a47b5d.jpg\"></a></td><td><a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=114009\">Ghetto Wars <BR /><img src=\"http://c3.ac-images.myspacecdn.com/images02/27/l_5061213fef1d410598613556b11615f2.jpg\"></a></td><td><a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=123998\">Terror Strike(New)<BR /><img src=\"http://c4.ac-images.myspacecdn.com/images02/21/l_6436eda7843149ae842bb2e39f0c0e03.jpg\"></a></td><td> <a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=112773\">Crime<BR /><img src=\"http://c2.ac-images.myspacecdn.com/images01/47/l_64c5bd1a7b8b3ff83cede5873fdc7e39.jpg\"></a></td></tr></tbody></table><span style='color: #CD7F32; font-size:16px; font-weight:bold;'> The Bigger the clan, the gnomer! </span> <br>A bigger clan will make you more <b>powerful in attacks</b> and give you access to <b>more Gnome Quests. You can also do Quests with your clan, and attack other clans. </b>. <a href='#' class='standardLink' onclick='switchTabs(9); return false;'>Click here to invite more friends</a> to join your gnome family!";
//    } else if(l_random < 0.7){
//        l_msg = "<span style='color: #CD7F32; font-size:16px; font-weight:bold;'> New way to earn Favor Points! (experimental feature) </span> <br>The Mastermind will now reward you with favor points as you reach career achievements. <a href='#' class='standardLink' onclick='showViewerStats(); return false;'>Click here</a> to see your current achievements and find out how to unlock more!";
    }
	// else if(l_random < 0.8){
    //    l_msg = "<span style='color: #CD7F32; font-size:16px; font-weight:bold;'> Dust yourself off and try again. </span> <br>Want to try again with a different Crime class? With our new save/load game feature you can create up to 3 criminals characters under one MySpace account which will share crime points and crime members. <a href='#' class='standardLink' onclick='switchTabs(10); return false;'>Click here</a> to check it out!";
  //  } 
	else {
        l_msg = "<table><tbody><tr><td><a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=117815\">Pimp Wars<BR /><img src=\"http://c1.ac-images.myspacecdn.com/images02/45/l_54b93a7ef07544a699b6acd812507c20.jpg\"></a></td><td><a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=133546\">The Mafia(New)<BR /><img src=\"http://c2.ac-images.myspacecdn.com/images02/84/l_442537bab30b46a99d23980534a47b5d.jpg\"></a></td><td><a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=114009\">Ghetto Wars <BR /><img src=\"http://c3.ac-images.myspacecdn.com/images02/27/l_5061213fef1d410598613556b11615f2.jpg\"></a></td><td><a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=123998\">Terror Strike(New)<BR /><img src=\"http://c4.ac-images.myspacecdn.com/images02/21/l_6436eda7843149ae842bb2e39f0c0e03.jpg\"></a></td><td> <a href=\"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=112773\">Crime<BR /><img src=\"http://c2.ac-images.myspacecdn.com/images01/47/l_64c5bd1a7b8b3ff83cede5873fdc7e39.jpg\"></a></td></tr></tbody></table><span style='color: #CD7F32; font-size:16px; font-weight:bold;'> The Bigger the clan, the deadlier! </span> <br>A bigger clan will make you more <b>powerful in fights</b> and give you access to <b>more gnome quests. You can also do missions with your clan, and attack other clans. </b>. <a href='#' class='standardLink' onclick='switchTabs(9); return false;'>Click here to invite more friends</a> to join your gnome family!";
    }
	//opensocial.hasPermission(MyOpenSpace.Permission.VIEWER_PERMISSION);
	if(opensocial.hasPermission(MyOpenSpace.Permission.VIEWER_DISPLAY_ON_PROFILE )){
	//l_msg += "VIEWER_SHOW_UPDATES_FROM_FRIENDS ";
	}
		else
	{
			opensocial.requestPermission([MyOpenSpace.Permission.VIEWER_DISPLAY_ON_PROFILE], "Access to your profile is required!", function(){});
	}
	
		if(opensocial.hasPermission(MyOpenSpace.Permission.VIEWER_DISPLAY_ON_HOME )){
	//l_msg += "VIEWER_SHOW_UPDATES_FROM_FRIENDS ";
	}
		else
	{
			opensocial.requestPermission([MyOpenSpace.Permission.VIEWER_DISPLAY_ON_HOME], "Access to your home is required!", function(){});
	}
	/*
	if(opensocial.hasPermission(MyOpenSpace.Permission.VIEWER_UPDATE_MOOD_STATUS )){
	//l_msg += "VIEWER_UPDATE_MOOD_STATUS ";
	}
	else
	{
			opensocial.requestPermission([MyOpenSpace.Permission.VIEWER_UPDATE_MOOD_STATUS], "Access to your updates is required!", function(){});
	}
	
	if(opensocial.hasPermission(MyOpenSpace.Permission.VIEWER_SHOW_UPDATES_FROM_FRIENDS )){
	//l_msg += "VIEWER_SHOW_UPDATES_FROM_FRIENDS ";
	}
		else
	{
			opensocial.requestPermission([MyOpenSpace.Permission.VIEWER_SHOW_UPDATES_FROM_FRIENDS], "Access to your updates from friends is required!", function(){});
	}
	
	
	
	if(opensocial.hasPermission(MyOpenSpace.Permission.VIEWER_SEND_UPDATES_TO_FRIENDS )){
	//l_msg += "VIEWER_SEND_UPDATES_TO_FRIENDS ";
	}
		else
	{
			opensocial.requestPermission([MyOpenSpace.Permission.VIEWER_SEND_UPDATES_TO_FRIENDS], "Access to your updates to friends is required!", function(){});
	}*/
    l_messageDiv.innerHTML = "<ul><li>"+l_msg+"</li></ul>";
}


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){
            showWelcomeMessage(m_containerDiv);            
        } else {
            showNotifactionMessage(m_containerDiv);
        }*/
 showNotifactionMessage(m_containerDiv); // just do this without inst new install
 
 
        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 clans.");
            l_resultDiv.getContainerDiv().style.cursor = "pointer";
            addEvent(l_resultDiv.getContainerDiv(), "click", function(){
                GBL.MAIN_TABS.switchToTab(9);
            });
        }


        var l_title = document.createElement("div");
        m_containerDiv.appendChild(l_title);
        createTitleDiv(l_title, "Main Menu:");        

        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("Quests", "Completing missions is the quickest way to gain money and experience.", 1));
        l_contentTBody.appendChild(createContentElement("My Land", "Buy, build, and control more territory to earn recurring income.", 2));
        l_contentTBody.appendChild(createContentElement("The Pot", "Use the bank to launder your money and keep it safe, good for paying off cops and doctors.", 3));
        l_contentTBody.appendChild(createContentElement("Papa Gnome", "Earn gnome points from The Papa Gnome.", 4));
        l_contentTBody.appendChild(createContentElement("Attack", "Attack rival gnomes and make money robbing them!", 5));
        l_contentTBody.appendChild(createContentElement("Bad Gnomes", "Make hits on marked men and earn a big bounties.", 6));
        l_contentTBody.appendChild(createContentElement("My Stuff", "Buy powerful weapons, hot cars, items and armor.", 7));
        l_contentTBody.appendChild(createContentElement("Life", "Pay your doctors some clean money to heal you." , 8));
        l_contentTBody.appendChild(createContentElement("My Clan", "Grow your gnome clan to become more powerful." , 9));
        l_contentTBody.appendChild(createContentElement("My Gnome", "View and upgrade your character.", 10));
		l_contentTBody.appendChild(createContentElement("The Prison", "Gnomes Doing Time", 11));
        l_contentTBody.appendChild(createContentElement("Top Players", "The most powerful gnomes of MySpace.", 12));
         l_contentTBody.appendChild(createContentElement("Support", "Get Help.", 13));
		// l_contentTBody.appendChild(createContentElement("Vehicles", "The most powerful criminals of MySpace.", 14));
		 //l_contentTBody.appendChild(createContentElement("Top Players", "The most powerful criminals of MySpace.", 12));
		// toStockpileVehiclesTab
    }

    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 = "<img src='http://g.laasex.com/gnomeswars/images/UI/skull-ring-50x50.jpg'/>";

        l_td = document.createElement("td");
        l_tr.appendChild(l_td);
        l_td.style.padding = "5px 10px 5px 10px";
        l_td.style.color = "#DC0A0A";
        l_td.style.fontWeight = "bold";
		l_td.style.fontSize ="18px";
        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 = "#FFFFFF";

        var l_faq = "<center><h1>Gnome Wars FAQ</h1></center>";
                 l_faq += "<br>";
                 l_faq += "<b>Frequently Asked Questions</b>";
                 l_faq += "<br/>Here you can quickly learn the basics of Gnome Wars. Expect updates to this page as I become aware of, and then answer, your common questions.";
                 l_faq += "<br><br>";
                 l_faq += "<ol>";
                 l_faq += "<li><b>Quests</b>";
                 l_faq += "<br> Complete Quests to earn quick cash and gain experience. Each mission has certain requirements like energy, weapons, clan size, etc. New Quests become unlocked for higher level players.</li><br>";
                 l_faq += "<li><b>Your Land</b>";
                 l_faq += "<br> Buy undeveloped land and then build on it to increase your income. Once a piece of undeveloped land is built on, it cannot be built upon again. Selling any property gives you back half of what you paid. The more territory you control, the more money and power you'll have! </li><br>";
                 l_faq += "<li><b>The Bad List</b>";
                 l_faq += "<br> Check here to find \"hits\" that have been placed on other players. A successful hit will earn you a bounty, but it won't be easy. Hundreds of other players will be able to view the same hit.  You can place a hit on most people near your level from their Gnome profile, if you have enough money and stamina.</li><br>";
                 l_faq += "<li><b>The Pot</b>";
                 l_faq += "<br> For a $10,000 minimum deposit, you can open a bank account to protect your money from being stolen from an attack by another criminal. The bank does charge a slight fee for laundering your money, however... You can withdraw money at your leisure, but be careful! The bank requires you to have at least $2,000 in your account at all times! Only money from the bank can be used to pay the hospital, so make sure you keep some there in case you get hurt.</li><br>";
                 l_faq += "<li><b>How Fighting Works</b>";
                 l_faq += "<br> You can attack gnomes at or above your level. The fight results are calculated based on how many people are in your clan and what they are armed with. You should try to have at least one weapon for each of your gnome clan member to fight with, or else some will have to fight bare knuckled.  Each clan member may hold 1 weapon, drive 1 vehicle, and be equipped with 1 special item (e.g. a bulletproof vest). The number of criminals</li><br>";
                 l_faq += "<li><b>Your Stuff</b>";
                 l_fa