//Last updated Aug 01, 2009 , 11:00 AM
GANGSTERS = {};
GANGSTERS.APP_DOWN_FOR_MAINTENANCE = false;
GANGSTERS.APP_URL = "http://myspace.com/428927689";
GANGSTERS.BASE_URL = "http://www.slickflash.net/WorldAtWarII";
GANGSTERS.CANVAS_URL = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=120549&";
GANGSTERS.one_troy_ounce = 31.1034768; // grams
GANGSTERS.APP_NOT_INSTALLED = 0;
GANGSTERS.APP_INSTALLED = 1;
GANGSTERS.APP_JUST_INSTALLED = 2;
GANGSTERS.MY_REQUESTS = 1;
GANGSTERS.MY_GANG = 2;
GANGSTERS.NEW_USERS = 3;
GANGSTERS.MY_FRIENDS = 4;
GANGSTERS.NON_BACKED_FRIENDS = 5;
GANGSTERS.MY_GANG_MEMBERS = 6;
GANGSTERS.install_state = undefined;
GANGSTERS.statusDiv = undefined;
GANGSTERS.mainDiv = undefined;
GANGSTERS.refreshDiv = undefined;
GANGSTERS.SHOW_USER_ID = "show_user_id";
GANGSTERS.headerDiv = undefined;
GANGSTERS.mainDiv = undefined;
GANGSTERS.VIEWER = undefined;
GANGSTERS.OWNER = undefined;
GANGSTERS.VIEWER_REQUESTS = undefined;
GANGSTERS.VIEWER_GANG = undefined;
GANGSTERS.GANG_MEMBERS = undefined;
GANGSTERS.NEW_GANGSTERS = undefined;
GANGSTERS.VIEWER_FRIENDS = undefined;
GANGSTERS.VIEWER_NON_BACKED_FRIENDS = undefined;
GANGSTERS.OS_CONTAINER = opensocial.Container.get();
GANGSTERS.OS_TOKEN = MyOpenSpace.MySpaceContainer.OSToken;
GANGSTERS.ERROR_MSG = "<img src='"+GANGSTERS.BASE_URL+"/images/logo.jpg' /><br/><div class='outerTextDiv'><div class='innerTextDiv'>Sorry, Myspace is having some issue. Please refresh this page...<br/> If you're bored, try <a target='_blank' href='http://myspace.com/mobwarsapp'> Mob Wars </a> the Mafia game!</div></div>";
GANGSTERS.LOADING_MSG = "<img src='"+GANGSTERS.BASE_URL+"/images/logo.jpg' /><br/><div class='outerTextDiv'><div class='innerTextDiv'><span style='font-weight:bold;'> Loading World At War II... </span> <br/> <span style='font-size:12px;'> (Please refresh if app doesn't load in 30 seconds.) </span></div></div>";
GANGSTERS.MYSPACE_WAITING_MSG = "<img src='"+GANGSTERS.BASE_URL+"/images/logo.jpg' /><br/><div class='outerTextDiv'><div class='innerTextDiv'><span style='font-weight:bold;'> Waiting for MySpace to respond... </span> <br/> <span style='font-size:10px;'> (Refreshing the page may help...) </span></div></div>";
GANGSTERS.APP_DOWN_MSG = "<img src='"+GANGSTERS.BASE_URL+"/images/logo.jpg' /><br/><div class='outerTextDiv'><div class='innerTextDiv'><span style='font-weight:bold;'> World At War II is down for maintenance.</span> <br/> <span style='font-size:10px;'> (Please come back later...) </span></div></div>";
GANGSTERS.MYSPACE_ERROR_MSG = "Sorry, Myspace is having some issue. Please refresh this page...";

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 addslashes( str ) {
    return (str+'').replace("'","*.*apostrophe*.*");
}

//Alliance_Stat
    function Alliance_Stat(a_parentDiv, a_type){
		this.m_parentDiv = a_parentDiv;
		
		this.m_menuDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_menuDiv);
		this.m_menuDiv.innerHTML = '' +
		'<div id="feedMenu"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(10)">Top 25</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Alliance_Stat\',\'Alliance_Stat\')">Alliance Stats</a></div>';
		
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);
		this.m_infoDiv.innerHTML = '<h1>Alliance Stats</h1><div>All stats below are updated once a day only.</div>';
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_contentDiv);
		
		this.refresh();
    }
	
	Alliance_Stat.prototype.refresh = function(){
		var l_self = this;
		var l_param = {};
        l_param.user_id = GANGSTERS.VIEWER.getUserId();
		makeRequest("get_allies_info",function(a_responseData){l_self.onGetAlliesStat(a_responseData);},l_param,l_self);
	}
	
    Alliance_Stat.prototype.onGetAlliesStat = function(a_responseData){
        var l_xmlNode = getResponseData(a_responseData);
		
        if(isValid(l_xmlNode)){
            try{
                var l_northNodes = l_xmlNode.getElementsByTagName("north");
                 var l_north_population = number_format(getXMLNodeValue(l_northNodes[0], "population"));
                var l_north_cash_in_bank = number_format(getXMLNodeValue(l_northNodes[0], "cash_in_bank"));
                var l_north_cash = number_format(getXMLNodeValue(l_northNodes[0], "cash"));
                var l_north_total = number_format(getXMLNodeValue(l_northNodes[0], "total"));
                var l_north_fights_won = number_format(getXMLNodeValue(l_northNodes[0], "fights_won"));
                var l_north_fights_lost = number_format(getXMLNodeValue(l_northNodes[0], "fights_lost"));
                var l_north_death_count = number_format(getXMLNodeValue(l_northNodes[0], "death_count"));
                var l_north_kill_count = number_format(getXMLNodeValue(l_northNodes[0], "kill_count"));
                var l_north_t_gold = getXMLNodeValue(l_northNodes[0], "gold");
				if(l_north_t_gold>GANGSTERS.one_troy_ounce){
					l_north_t_gold = number_format(Math.floor(l_north_t_gold / GANGSTERS.one_troy_ounce)) + ' troy ounces';
				}
				else{
					l_north_t_gold = number_format(Math.floor(l_north_t_gold)) + ' grams';
				}
				
                var l_north_jobs_completed = number_format(getXMLNodeValue(l_northNodes[0], "jobs_completed"));
                var l_north_attack_strength = number_format(getXMLNodeValue(l_northNodes[0], "attack_strength"));
                var l_north_defense_strength = number_format(getXMLNodeValue(l_northNodes[0], "defense_strength"));
                var l_north_land_income = number_format(getXMLNodeValue(l_northNodes[0], "land_income"));
                var l_north_item_upkeep = number_format(getXMLNodeValue(l_northNodes[0], "item_upkeep"));
				
                var l_southNodes = l_xmlNode.getElementsByTagName("south");
				var l_south_population = number_format(getXMLNodeValue(l_southNodes[0], "population"));
                var l_south_cash_in_bank = number_format(getXMLNodeValue(l_southNodes[0], "cash_in_bank"));
                var l_south_cash = number_format(getXMLNodeValue(l_southNodes[0], "cash"));
                var l_south_total = number_format(getXMLNodeValue(l_southNodes[0], "total"));
                var l_south_fights_won = number_format(getXMLNodeValue(l_southNodes[0], "fights_won"));
                var l_south_fights_lost = number_format(getXMLNodeValue(l_southNodes[0], "fights_lost"));
                var l_south_death_count = number_format(getXMLNodeValue(l_southNodes[0], "death_count"));
                var l_south_kill_count = number_format(getXMLNodeValue(l_southNodes[0], "kill_count"));  
				var l_south_t_gold = getXMLNodeValue(l_southNodes[0], "gold");
				if(l_south_t_gold>GANGSTERS.one_troy_ounce){
					l_south_t_gold = number_format(Math.floor(l_south_t_gold / GANGSTERS.one_troy_ounce)) + ' troy ounces';
				}
				else{
					l_south_t_gold = number_format(Math.floor(l_south_t_gold)) + ' grams';
				}
                var l_south_jobs_completed = number_format(getXMLNodeValue(l_southNodes[0], "jobs_completed"));
                var l_south_attack_strength = number_format(getXMLNodeValue(l_southNodes[0], "attack_strength"));
                var l_south_defense_strength = number_format(getXMLNodeValue(l_southNodes[0], "defense_strength"));
                var l_south_land_income = number_format(getXMLNodeValue(l_southNodes[0], "land_income"));
                var l_south_item_upkeep = number_format(getXMLNodeValue(l_southNodes[0], "item_upkeep"));
				
				var l_table = '<br/><br/>' +
				'<div id="alliance">' +
					'<table align="center">' +
						'<tr>' +
							'<td><span class="tableTitle">Stats</span></td>' +
							'<td><span class="tableTitle">Northern Alliance</span></td>' +
							'<td><span class="tableTitle">Southern Alliance</span></td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Population</div></td>' +
							'<td>' + l_north_population + '</td>' +
							'<td>' + l_south_population + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Money in hand</div></td>' +
							'<td>' + l_north_cash + '</td>' +
							'<td>' + l_south_cash + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Treasury</div></td>' +
							'<td>' + l_north_cash_in_bank + '</td>' +
							'<td>' + l_south_cash_in_bank + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Total Money</div></td>' +
							'<td>' + l_north_total + '</td>' +
							'<td>' + l_south_total + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Won Battles</div></td>' +
							'<td>' + l_north_fights_won + '</td>' +
							'<td>' + l_south_fights_won + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Lost Battles</div></td>' +
							'<td>' + l_north_fights_lost + '</td>' +
							'<td>' + l_south_fights_lost + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Kill Count</div></td>' +
							'<td>' + l_north_kill_count + '</td>' +
							'<td>' + l_south_kill_count + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Death Count</div></td>' +
							'<td>' + l_north_death_count + '</td>' +
							'<td>' + l_south_death_count + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Total Gold</div></td>' +
							'<td>' + l_north_t_gold + '</td>' +
							'<td>' + l_south_t_gold + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Missions Accomplished</div></td>' +
							'<td>' + l_north_jobs_completed + '</td>' +
							'<td>' + l_south_jobs_completed + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Attack Strength</div></td>' +
							'<td>' + l_north_attack_strength + '</td>' +
							'<td>' + l_south_attack_strength + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Defense Strength</div></td>' +
							'<td>' + l_north_defense_strength + '</td>' +
							'<td>' + l_south_defense_strength + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Income</div></td>' +
							'<td>' + l_north_land_income + '</td>' +
							'<td>' + l_south_land_income + '</td>' +
						'</tr>' +
						'<tr>' +
							'<td><div class="allianceTitle">Expenses</div></td>' +
							'<td>' + l_north_item_upkeep + '</td>' +
							'<td>' + l_south_item_upkeep + '</td>' +
						'</tr>' +
					'</table>' +
				'</div>';

				this.m_contentDiv.innerHTML = l_table;
            } catch (err) {}
        }	
    }
//end Alliance_Stat

//Allies
	function Allies(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		
		this.m_menuDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_menuDiv);
		this.m_menuDiv.innerHTML = '' +
		'<div id="feedMenu"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(8)">Invite Friends</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ManageGang\',\'ManageGang\')">Manage Allies</a> | <a href="#top" onClick="showFamilyTree()">War Cabinet</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ChooseSide\',\'ChooseSide\')">Choose a side</a></div>';
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_requestDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_requestDiv);
		
        var l_self = this;
        GANGSTERS.VIEWER_REQUESTS.getNumUsers(function(a_numUsers){l_self.onGottenNumUsers(a_numUsers);});
		
		this.m_bulletinDiv = document.createElement("div");
		this.m_bulletinDiv.id = "newUsers";
		
		this.m_parentDiv.appendChild(this.m_bulletinDiv);
		this.m_bulletinDiv.innerHTML = '<div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.Allies.sendBulletin()">Send War Bulletin</a></div></div>' +
		'<br/><p style="text-align:justify; font-size:12pt; padding: 5px;">Select your friends below to recruit them. <b>The more Allies you have, the more powerful your Nation will become when attacking and completing missions!</b> In order to build a successful Nation, you should choose all friends from below who are most likely to join, and invite them.</p> <br /><br><br><p>ATTN: Getting friend Lists with the myspace api seem to be down for version 0.7 of the api version. We are waiting on Myspace to fix this. Hopefully this will not take long. We will look for a workaround if they dont fix it soon! Sorry for the inconvenience.</p>';
		
		this.m_inviteButton1 = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_inviteButton1);
		this.m_inviteButton1.innerHTML = '<center><table><tr><td><div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.Allies.send(1)">Send Invite!</a></div></div></td><td><div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.Allies.send(2)">Send Message!</a></div></div></td><td><div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.Allies.send(3)">Send Comments!</a></div></div></td></tr></table></center>';

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

        this.m_friendPicker = new FriendPicker(this.m_friendPickerDiv, GANGSTERS.VIEWER_FRIENDS, function(){l_self.send();});

		this.m_inviteButton2 = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_inviteButton2);
		this.m_inviteButton2.innerHTML = '<center><table><tr><td><div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.Allies.send(1)">Send Invite!</a></div></div></td><td><div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.Allies.send(2)">Send Message!</a></div></div></td><td><div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.Allies.send(3)">Send Comments!</a></div></div></td></tr></table></center>';
	}
	
    Allies.prototype.onGottenNumUsers = function(a_numUsers){
        if(a_numUsers > 0){
		
            this.m_requestDiv.innerHTML = "The following people have requested that you unite with them and become an ally. If you accept, they will both be allies and you will be able to complete more challenging missions. Also, you will be more powerful when attacking other Nations.";

            var l_self = this;
            new UserTableParentDiv(this.m_requestDiv,
                                    GANGSTERS.VIEWER_REQUESTS,
                                    4, 12,
                                    function(a_user){return l_self.canAcceptRejectTdCreater(a_user);});
        }
    }
	
    Allies.prototype.canAcceptRejectTdCreater = function(a_user){

        var l_self = this;

        var l_td = document.createElement("td");
		l_td.className = "requestTd";
		l_td.innerHTML = '<a href="#top" onClick="viewProfile('+a_user.getUserId()+')"><img src="'+a_user.getThumbnailUrl()+'" width="60" height="60" border="0" /><br/>'+a_user.getGangName()+'</a><br /><span style="color:#66FF00; cursor:pointer" onClick="GANGSTERS.Allies.acceptRequest('+a_user.getUserId()+')">Accept</span> | <span style="color:red; cursor:pointer" onClick="GANGSTERS.Allies.denyRequest('+a_user.getUserId()+')">Reject</span>';
		
        return l_td;
    }
	
	Allies.prototype.acceptRequest =  function(a_userId){
		var l_self = this;
		l_self.m_resultDiv.innerHTML = "Accepting ... ";
		goToPageTop();

		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.accept_user_id = a_userId;
		makeRequest("accept_gang_request",
			function(a_response){
				GANGSTERS.VIEWER_REQUESTS.invalidateCache();
				handleResult(a_response, l_self.m_resultDiv, function(){DoRefresh();});
			},
			l_params,l_self);
	}
	
	Allies.prototype.denyRequest =  function(a_userId){
		var l_self = this;
		l_self.m_resultDiv.innerHTML = "Denying ... ";
		goToPageTop();

		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.reject_user_id = a_userId;
		makeRequest("reject_gang_request",
			function(a_response){
				GANGSTERS.VIEWER_REQUESTS.invalidateCache();
				handleResult(a_response, l_self.m_resultDiv, function(){DoRefresh();});
			},
			l_params,l_self);
	}
	
	Allies.prototype.sendBulletin = function(){
		var l_subject ="Want to build your own Army and conquer the World??";
		var l_body = "<a href='" + GANGSTERS.CANVAS_URL + "'><img src='http://i149.photobucket.com/albums/s48/glittervault2/comment.jpg'/></a><br/><br/>Come play <a href='" + GANGSTERS.CANVAS_URL + "'>World At War II</a>, a World Domination game where you and your friends can conquer and rule the world and battle against others on Myspace!<br/><br/><a href='" + GANGSTERS.CANVAS_URL + "appParams=%7B%22rsrc%22%3A%22bulletin_link2%22%7D&track=bulletin'>Play World at War II!</a>";
		
		postBulletin(GANGSTERS.VIEWER, l_subject, l_body, function(){});
	}
	
    Allies.prototype.send = function(a_isInvite) {
        var l_selectedFriends = this.m_friendPicker.getSelectedFriends();

        if (!isValid(l_selectedFriends) || l_selectedFriends.length == 0) {
            this.m_resultDiv.innerHTML = "Please select at least one friend to invite";
            return;
        }

        this.m_resultDiv.innerHTML = "Sending...";
        this.m_sentFriends = new Array();
		if(a_isInvite==1){
			this.sendInvite(l_selectedFriends, 0);
		}
		else if(a_isInvite==2){
			this.sendMessage(l_selectedFriends, 0);
		}
		else{
			this.sendComment(l_selectedFriends, 0);
		}
    }
	
    Allies.prototype.sendInvite = function(a_targetUsers, a_currentIndex){
        var l_user = a_targetUsers[a_currentIndex];
        var l_self = this;

        var onSentInvite = function(a_postStatus){

            if(a_postStatus > 0){
				for(var i=0; i<20; i++){
					if(!isValid(a_targetUsers[i]))
						break;
					l_user = a_targetUsers[i];
	                l_user.setRequestedByUser(true);
	                l_self.m_sentFriends.push(l_user);
				}
            }
            l_self.finishSending(); 
        }
        
        var l_message = GANGSTERS.VIEWER.getName() + " wants you to join their Army in [app], Click \"Add World At War II\" to play! Help your friend out in this great WAR themed application.";
		
		var usrArr = new Array();
		for(var i=0; i<20; i++){
			if(!isValid(a_targetUsers[i]))
				break;
			l_user = a_targetUsers[i];
			usrArr.push(l_user.getUserId());
		}
        sendMultipleInvite(usrArr, l_message, onSentInvite);
    }
	
    Allies.prototype.sendComment = function(a_targetUsers, a_currentIndex){
        var l_user = a_targetUsers[a_currentIndex];
        var l_self = this;

        var onSentComment = function(a_postStatus){

            if(a_postStatus > 0){
                l_user.setRequestedByUser(true);
                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(); 
            }
        }

		var l_message = "<a href='" + GANGSTERS.CANVAS_URL + "'><img src='http://i149.photobucket.com/albums/s48/glittervault2/comment.jpg'/></a><br/><br/>Come play <a href='" + GANGSTERS.CANVAS_URL + "'>World At War II</a>, a World Domination game where you can build your own Army and conquer the world with your friends!<br/><br/><a href='" + GANGSTERS.CANVAS_URL + "appParams=%7B%22rsrc%22%3A%22bulletin_link2%22%7D&track=comment'>Play World At War II!</a>";
        sendComment(l_user, l_message, onSentComment);
    }
	
    Allies.prototype.sendMessage = function(a_targetUsers, a_currentIndex){
        var l_user = a_targetUsers[a_currentIndex];
        var l_self = this;

        var onSentMessage = function(a_postStatus){

            if(a_postStatus > 0){
                l_user.setRequestedByUser(true);
                l_self.m_sentFriends.push(l_user);
            }

            var l_nextIndex = a_currentIndex + 1;
            if(l_nextIndex < a_targetUsers.length){
                l_self.sendMessage(a_targetUsers, l_nextIndex);
            } else {
                l_self.finishSending(); 
            }
        }

		var l_message = "<a href='" + GANGSTERS.CANVAS_URL + "'><img src='http://i149.photobucket.com/albums/s48/glittervault2/comment.jpg'/></a><br/><br/>Come play <a href='" + GANGSTERS.CANVAS_URL + "'>World At War II</a>, a World Domination game where you can build your own Army and conquer the world with your friends!<br/><br/><a href='" + GANGSTERS.CANVAS_URL + "appParams=%7B%22rsrc%22%3A%22bulletin_link2%22%7D&track=sendmessage'>Play World At War II!</a>";
		
		var l_subject = "I want you in my army";
		
        sendMessage(l_user, l_subject, l_message, onSentMessage);
    }
	
    Allies.prototype.finishSending = function(){
        if(this.m_sentFriends.length > 0){
            this.m_resultDiv.innerHTML = "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.user_id = GANGSTERS.VIEWER.getUserId();
            l_params.to_user_ids = l_userIdsStr;
            var l_self = this;

            makeRequest("send_requests",
                    function(a_response){
                        handleResult(a_response, l_self.m_resultDiv, function(){});
                    },
                    l_params,l_self);

        } else {
            this.m_resultDiv.innerHTML = "You didn't send any invites!";
            this.m_friendPicker.unselectFriends();
        }
    }
//end Allies

//Assets
	function Assets(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_titleDiv = document.createElement('div');
		this.m_parentDiv.appendChild(this.m_titleDiv);

		this.m_landContentDiv = document.createElement("div");
		this.m_landContentDiv.className = "categoryTableTitle";
		this.m_parentDiv.appendChild(this.m_landContentDiv);
		
		this.m_infoDiv = document.createElement('div');
		this.m_parentDiv.appendChild(this.m_infoDiv);
		
		this.m_titleDiv.innerHTML = '' +	
		'<div id="newUsers">' +
			'<h1>National Assets</h1>' +
			'<div class="tips">' +
				'Completing Missions is a great way to earn funds to strengthen your Army, but everyone knows there you can earn recurring income by raising money and colonizing weaker nations. These options are great investments to generate the funds to help you build a stronger, more powerful Army. <br /><h2>You will be charged more tax as you owned more assets. You will save money if you buy in bulk quantity.</h2>' +
			'</div>' +
		'</div>	';
		this.getAssetList();
		this.getIncome();
	}
	
    Assets.prototype.getAssetList = function(){

        this.m_landContentDiv.innerHTML = "Loading Assets...";
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        l_params.level = GANGSTERS.VIEWER.getLevel();
        
        var l_self = this;
        makeRequest("get_city_list", function(a_responseData){
           l_self.onGetAssetList(a_responseData);
        },l_params,l_self);
    }

    Assets.prototype.onGetAssetList = function(a_responseData){
        var l_xmlDoc = getResponseData(a_responseData);
		var l_table = '';
		var l_maxProperty = GANGSTERS.VIEWER.getMaxProperty();
		
        if(isValid(l_xmlDoc)){
            try{
				l_table = '' +
						'<table align="center">' +
							'<tr>' +
								'<th>Description</th>' +
								'<th>Assets</th>' +
								'<th>Buy / Sell</th>' +
							'</tr>';
                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++){

					l_table += '<tr>';
					
			        try{ 
						var l_landId = getXMLNodeValue(l_landNodes[l_index],"id");
						var l_title = getXMLEncodedStringNodeValue(l_landNodes[l_index],"title");
						
						l_table += '<td width="20%"><span class="description">' + l_title + '</span></td>';
						var l_image_url = getXMLNodeValue(l_landNodes[l_index],"image_url");

						l_table += '<td width="20%"><img src="' + l_image_url + '" /></td>';
						
						var l_income = getXMLNodeValue(l_landNodes[l_index],"income");
						var l_owned = getXMLNodeValue(l_landNodes[l_index],"num_owned");
						var l_cost = getXMLNodeValue(l_landNodes[l_index],"cost");
						var l_tax = getXMLNodeValue(l_landNodes[l_index],"tax");
						var l_total = getXMLNodeValue(l_landNodes[l_index],"total");
						var l_allies_size = getXMLNodeValue(l_landNodes[l_index],"gang_size");

						l_table += '' +
						'<td width="40%">' +
							'<span class="money">Cost: $' + number_format(l_total) + '</span><br/><span class="redText">Allies Size: '+ number_format(l_allies_size) + '</span><br/><span class="money">Income: $' + number_format(l_income) + '</span> <br /><br />' +
							'<select id="buy_qty' + l_landId + '">' +
								'<option value="1">1</option>' +
								'<option value="2">2</option>' +
								'<option value="3">3</option>' +
								'<option value="4">4</option>' +
								'<option value="5">5</option>' +
								'<option value="6">6</option>' +
								'<option value="7">7</option>' +
								'<option value="8">8</option>' +
								'<option value="9">9</option>' +
								'<option value="10">10</option>' +
							'</select>'+
							'<input type="submit" value="Buy" onClick="GANGSTERS.Assets.buy(' + l_landId + ')" /> ';
							
						if(isValid(l_owned) && l_owned>0){
						l_table += '<select id="sell_qty' + l_landId + '">' +
								'<option value="1">1</option>' +
								'<option value="2">2</option>' +
								'<option value="3">3</option>' +
								'<option value="4">4</option>' +
								'<option value="5">5</option>' +
								'<option value="6">6</option>' +
								'<option value="7">7</option>' +
								'<option value="8">8</option>' +
								'<option value="9">9</option>' +
								'<option value="10">10</option>' +
							'</select>' +
						' <input type="submit" value="Sell" onClick="GANGSTERS.Assets.sell(' + l_landId + ')" /> ';

							l_table += '<br />Owned: ' + l_owned;
						}
						l_table += '</td>';

					}catch(err){};
					l_table += '</tr>';
                }

				l_table += '</table>';

                var l_nextLevel = getXMLNodeValue(l_xmlDoc, "next_level");
                if(isValid(l_nextLevel)){
					l_table += '<div class="levelMsg">Unlock more items when you reach level ' + l_nextLevel + ' ...</div>';
                }

				this.m_landContentDiv.innerHTML = l_table;
				
            } catch (err) {}
        }
    }
	
	Assets.prototype.buy = function(a_landId){
		goToPageTop();
		var l_self = this;
		var l_amount = document.getElementById("buy_qty" + a_landId);
		var l_qty = 0;
        for(var l_index = 0; l_index < l_amount.length; l_index++){
            if(l_amount[l_index].selected){
                l_qty = l_amount[l_index].value;
            }
        }
		this.m_resultDiv.innerHTML = "Buying ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.land_id = a_landId;
		l_params.amount = l_qty;
		
		makeRequest("buy_land",
				function(a_response){
					handleResult(a_response, l_self.m_resultDiv, function(){l_self.getAssetList()});},
				l_params,l_self);
	}
	
	Assets.prototype.sell = function(a_landId){
		goToPageTop();
		var l_self = this;
		var l_amount = document.getElementById("sell_qty" + a_landId);
		var l_qty = 0;
        for(var l_index = 0; l_index < l_amount.length; l_index++){
            if(l_amount[l_index].selected){
                l_qty = l_amount[l_index].value;
            }
        }
		this.m_resultDiv.innerHTML = "Selling ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.land_id = a_landId;
		l_params.amount = l_qty;
		
		makeRequest("sell_land",
				function(a_response){
					handleResult(a_response, l_self.m_resultDiv, function(){l_self.getAssetList()});},
				l_params,l_self);
	}

	Assets.prototype.getIncome = function(){
		this.m_infoDiv.innerHTML = "Loading income...";
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        var l_self = this;
        makeRequest("get_income", function(a_responseData){
           l_self.onGetIncome(a_responseData);
        },l_params,l_self);
	}
	
	Assets.prototype.onGetIncome = function(a_responseData){
        var l_xmlDoc = getResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
                var l_updatePeriod = getXMLNodeValue(l_xmlDoc, "update_period");
                var l_minutesToUpdate = getXMLNodeValue(l_xmlDoc, "minutes_to_update");

				this.m_infoDiv.innerHTML = '' +
				'<div id="invite">' +
					'<h1>Total Income Generated</h1>' +
					'<div class="tips">' +
						'You are generating a total of, <span class="money"> $'+ number_format(GANGSTERS.VIEWER.getIncome()) +'</span> every ' + l_updatePeriod + ' minutes. You will get income in <span class="experience">'+ l_minutesToUpdate +' Minutes.</span>' +
					'</div>' +
				'</div>';
            } catch (err) {}
        }
	}
//end Assets

//Ask
	function Ask(a_parentDiv, a_type){
		this.m_parentDiv = a_parentDiv;
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_weapon = "New Weapon";
		
		this.m_promoDiv = document.createElement("div");
		this.m_promoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_promoDiv);
		this.getPromoItem();
		
		this.m_inviteButton1 = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_inviteButton1);
		this.m_inviteButton1.innerHTML = '<center><table><tr><td><div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.Ask.send(1)">Ask & Send Invite!</a></div></div></td></tr></table></center>';

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

        this.m_friendPicker = new FriendPicker(this.m_friendPickerDiv, GANGSTERS.VIEWER_FRIENDS, function(){l_self.send();});

		this.m_inviteButton2 = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_inviteButton2);
		this.m_inviteButton2.innerHTML = '<center><table><tr><td><div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.Ask.send(1)">Ask & Send Invite!</a></div></div></td></tr></table></center>';
	}
		
    Ask.prototype.getPromoItem = function() {		
		var l_self = this;
		var l_param = {};
		this.m_promoDiv.innerHTML = "Loading Offers...";
        l_param.invite_count = Math.ceil((GANGSTERS.VIEWER.getInviteCount()+1) / 20) * 20;
		makeRequest("get_promo_item",
				function(a_responseData){l_self.onGetPromoItem(a_responseData);},
				l_param,l_self);
	}
	
    Ask.prototype.onGetPromoItem = function(a_responseData){
        var l_xmlNode = getResponseData(a_responseData);
		this.m_promoDiv.innerHTML = "";
		
        if(isValid(l_xmlNode)){
            try{
                var l_promoNode = l_xmlNode.getElementsByTagName("promo");
                this.m_weapon = getXMLEncodedStringNodeValue(l_promoNode[0],"title");
                var l_url = getXMLEncodedStringNodeValue(l_promoNode[0],"image_url");
                var l_invite_count = number_format(getXMLNodeValue(l_promoNode[0], "invite_count"));
                var l_attack = number_format(getXMLNodeValue(l_promoNode[0], "attack"));
                var l_defense = number_format(getXMLNodeValue(l_promoNode[0], "defense"));
                var l_upkeep = number_format(getXMLNodeValue(l_promoNode[0], "upkeep"));
				
				l_invite_count -= GANGSTERS.VIEWER.getInviteCount();
				var l_table = '<h1>Bonus Offers</h1>' +
				'<table class="category" style="border: 1px solid red">' +
					'<tr>' +
						'<td width="15%">' +
							'<img src="' + l_url + ' "/>' +
						'</td>' +
						'<td width="15%" style="text-align:left; font-size:10pt;">' +
							'Attack:  &nbsp; ' + l_attack + '<br/>' + 
							'Defense: ' + l_defense + '<br/>' + 
							'Upkeep: &nbsp;' + l_upkeep +
						'</td>' +
						'<td width="70%" style="text-align:left; font-size:10pt;">Foreign Aid offers you 1 ' + this.m_weapon + ' for free. However, you can claim it after inviting ' + l_invite_count + ' friends by <a href="#" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Ask\',\'Ask\')">sending invites</a> feel free to accept this offer if you like...' +
						'</td>' +
					'</tr>' +
				'</table>';

				this.m_promoDiv.innerHTML = l_table;
            } catch (err) {}
        }
    }
	
    Ask.prototype.send = function(a_isInvite) {
        var l_selectedFriends = this.m_friendPicker.getSelectedFriends();

        if (!isValid(l_selectedFriends) || l_selectedFriends.length == 0) {
            this.m_resultDiv.innerHTML = "Please select at least one friend to invite";
            return;
        }

        this.m_resultDiv.innerHTML = "Sending...";
        this.m_sentFriends = new Array();
		if(a_isInvite==1){
			this.sendInvite(l_selectedFriends, 0);
		}
    }
	
    Ask.prototype.sendInvite = function(a_targetUsers, a_currentIndex){
        var l_user = a_targetUsers[a_currentIndex];
        var l_self = this;

        var onSentInvite = function(a_postStatus){

            if(a_postStatus > 0){
                l_user.setRequestedByUser(true);
                l_self.m_sentFriends.push(l_user);
            }
			

            var l_nextIndex = a_currentIndex + 1;
            if(l_nextIndex < a_targetUsers.length){
                l_self.sendInvite(a_targetUsers, l_nextIndex);
            } else {
                l_self.finishSending(); 
            }
        }
        
        var l_message = GANGSTERS.VIEWER.getName() + " has asked you for a favour to get them a " + this.m_weapon + " in [app], a Mafia themed combat game played with you friends on MySpace. Click \"Add World At War II \" and help them!";
		
        sendInvite(l_user, l_message, onSentInvite);
    }
	
    Ask.prototype.finishSending = function(){
        if(this.m_sentFriends.length > 0){
            this.m_resultDiv.innerHTML = "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.user_id = GANGSTERS.VIEWER.getUserId();
            l_params.to_user_ids = l_userIdsStr;
            var l_self = this;

            makeRequest("send_requests",
                    function(a_response){
                        handleResult(a_response, l_self.m_resultDiv, function(){});
                    },
                    l_params,l_self);

        } else {
            this.m_resultDiv.innerHTML = "You didn't send any invites!";
            this.m_friendPicker.unselectFriends();
        }
    }
//end Ask

// Attack
    function Attack(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);

		this.m_infoDiv.innerHTML = '' +
		'<div id="newUsers">' +
			'<h1>Attack Hostile Nations</h1>' +
			'<div class="tips">' +
				'You may attack Nations to gain experience and pillage their vaults. Any monetary items not secured in their Treasury can be confiscated or lost in an attack, so make sure your funds are protected in the Treasury at all times!' +
				' <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(2)">Click here</a> to go to bank.' +
			'</div>' +
		'</div>';
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.className = "categoryTableTitle";
		this.m_parentDiv.appendChild(this.m_contentDiv);
				
		this.m_generalDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_generalDiv);
		
		this.m_generalDiv.innerHTML = '' +
		'<div class="general">' +
		'Better Weaponary and the number of Allies you have, makes you a more powerful force when attacking hostile Nations. Keep these two things in mind before attacking. You can check which nations have attacked you while you were gone, in your feeds!' +
		'</div>';
		
		this.getAttackList();
    }

    Attack.prototype.getAttackList = function(){

        this.m_contentDiv.innerHTML = "Loading Attack List...";
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        l_params.level = GANGSTERS.VIEWER.getLevel();
        
        var l_self = this;
        makeRequest("get_fight_list", function(a_responseData){
           l_self.onGetAttackList(a_responseData);
        },l_params,l_self);
    }

    Attack.prototype.onGetAttackList = function(a_responseData){
        var l_xmlDoc = getResponseData(a_responseData);
		var l_table = '';
		
        var l_xmlDoc = getResponseData(a_responseData);
        var l_numTargets = undefined;
        if(isValid(l_xmlDoc)){
            try{
                var l_numTargets = parseInt(getXMLNodeValue(l_xmlDoc, "num_targets"));
				l_table = '' +
				'<table align="center">' +
					'<tr>' +
						'<th>Name</th>' +
						'<th>Status</th>' +
						'<th>Allies</th>' +
						'<th>Attack!</th>' +
					'</tr>';

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

					l_table += '<tr>';
					
			        try{ 
	                    var l_targetUser = new User(undefined);
	                    l_targetUser.createXMLUser(l_userNodes[l_index]);
						
						l_table += '<td width="20%"><div class="thumbTable"><table><tr><td width="5%"><a href="#top" onClick="viewProfile('+l_targetUser.getUserId()+')"><img src="'+l_targetUser.getThumbnailUrl()+'" width="35px" height="35px" border="0"></a></td><td> <a href="#top" onClick="viewProfile('+l_targetUser.getUserId()+')">'+l_targetUser.getGangName()+'</a></td></tr></table></div></td>' +
						'<td width="20%">Level '+l_targetUser.getLevel()+', '+l_targetUser.getGangClass()+'</td>' +
						'<td width="20%">'+l_targetUser.getGangSize()+'</td>' +
						'<td width="40%">' +
						'<input type="submit" value="Attack!" onClick="GANGSTERS.Attack.attack('+l_targetUser.getUserId()+')">' +						
						'</td>';
					
					}catch(err){};
					l_table += '</tr>';
                }
				
				l_table += '</table>';

				this.m_contentDiv.innerHTML = l_table;

		        if(!isValid(l_numTargets) || l_numTargets <= 0){
					this.m_contentDiv.innerHTML = "<div class=\"general\">There are no other Nations available to wage WAR on. Why don't you <a href='#top' onClick='GANGSTERS.menuDiv.navigateTo(1);'>complete some missions</a> in the meantime?</div>";
		        }
            } catch (err) {}
        }
    }
	
	Attack.prototype.attack = function(a_targetId){
		goToPageTop();
		var l_self = this;
		this.m_resultDiv.innerHTML = "Attacking ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.target_id = a_targetId;
		
		makeRequest("attack",
				function(a_response){
					handleResult(a_response, l_self.m_resultDiv, function(){l_self.getAttackList()});},
				l_params,l_self);
	}
// end Attack


// BrowseDiv
    function BrowseDiv(a_parentDiv, a_type){
        this.m_parentDiv = a_parentDiv;
        
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);
        
		this.m_contentDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_contentDiv);
		this.m_contentDiv.style.textAlign = "center";
		
		this.m_total = 0;
        this.m_infoDiv.innerHTML = "Loading Nations...";
        var l_self = this;
        GANGSTERS.NEW_GANGSTERS.getNumUsers(function(a_numUsers){l_self.onGottenNumUsers(a_numUsers);});
    }

    BrowseDiv.prototype.onGottenNumUsers = function(a_numUsers){
		this.m_total = a_numUsers;
        this.m_infoDiv.innerHTML = '<h1>Browse Users (' + a_numUsers + ' User)</h1>';
		this.loadGangsters(1);
    }

    BrowseDiv.prototype.onGetGangsters = function(a_responseData){
		var l_self = this;
        var l_xmlDoc = getResponseText(a_responseData);
		
        if(isValid(l_xmlDoc)){
            try{
				this.m_contentDiv.innerHTML = l_xmlDoc;
			}
			catch(err){}
		}
    }
	
	BrowseDiv.prototype.loadGangsters = function(a_page){
        var l_self = this;
		this.m_contentDiv.innerHTML = "Loading New Users...";
		var l_params = {};
		l_params.total = this.m_total;
		l_params.page = a_page;
		
		makeRequest("browse_gangsters", function(a_responseData){l_self.onGetGangsters(a_responseData);}, l_params,l_self);
    }
// end BrowseDiv


//ChooseSide
	function ChooseSide(a_parentDiv, a_type){
		this.m_parentDiv = a_parentDiv;
		
		this.m_menuDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_menuDiv);
		this.m_menuDiv.innerHTML = '' +
		'<div id="feedMenu"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(8)">Invite Friends</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ManageGang\',\'ManageGang\')">Manage Allies</a> | <a href="#top" onClick="showFamilyTree()">War Cabinet</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ChooseSide\',\'ChooseSide\')">Choose a side</a></div>';
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_contentDiv);
	
		this.m_contentDiv.innerHTML = '' +
			'<h1>Choose an Alliance</h1>' +
			'<div class="tips">' +
				'There are two sides you can choose to fight under. The Northern Alliance and the Southern Alliance are in perpetual War. Who will you support? Choose an Alliance to fight under. Pick your side carefully, the best bet is to pick the sides in which your friends fight under. Please note there is a <span class="money">$5,000,000</span> charge for changing sides once you have choose one for the first time!<br/><br/><div class="button"><a href="#top" onClick="GANGSTERS.ChooseSide.choose(1)">I pick the North Side</a></div><div class="button"><a href="#top" onClick="GANGSTERS.ChooseSide.choose(2)">I pick the South side</a></div>' +
			'</div>';
	}
	
	ChooseSide.prototype.choose = function(a_side){	
		var l_self = this;
		this.m_resultDiv.innerHTML = "Saving ... ";
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.side = a_side;
		makeRequest("choose_side",
			function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){})},
			l_params,l_self);
	}
//end ChooseSide

function createUI(){

    GANGSTERS.mainDiv.innerHTML = "";
    goToPageTop();

    if(!isValid(GANGSTERS.VIEWER.getGangName()) || !isValid(GANGSTERS.VIEWER.getGangClass())){
        GANGSTERS.GameSetup = new GameSetup(GANGSTERS.mainDiv, createUI);
        return;
    }

    GANGSTERS.mainDiv.innerHTML = "";
	var l_containerDiv = document.createElement("div");
	l_containerDiv.id = "container";
	GANGSTERS.mainDiv.appendChild(l_containerDiv);
	
	var l_footerDiv = document.createElement("div");
	//l_footerDiv.id = "footer";
	l_footerDiv.innerHTML = '<iframe src="'+GANGSTERS.BASE_URL+'/google-analytics.html" scrolling="no" frameborder="0" width="0" height="0"></iframe>';
	GANGSTERS.mainDiv.appendChild(l_footerDiv);
	
	var l_headerDiv = document.createElement("div");
	l_headerDiv.id = "header";
	l_containerDiv.appendChild(l_headerDiv);
	l_headerDiv.innerHTML = '<img src="'+GANGSTERS.BASE_URL+'/images/logo.jpg" />';
	
	var l_refreshDiv = document.createElement("div");
	l_refreshDiv.id = "refreshDiv";
	l_containerDiv.appendChild(l_refreshDiv);	
	var l_statusDiv = document.createElement("div");
	l_statusDiv.id = "status";
	l_containerDiv.appendChild(l_statusDiv);
	var l_menuDiv = document.createElement("div");
	l_menuDiv.id = "menu";
	l_containerDiv.appendChild(l_menuDiv);
	
	var l_reportDiv = document.createElement("div");
	l_reportDiv.style.textAlign = "right";
	l_containerDiv.appendChild(l_reportDiv);
	l_reportDiv.innerHTML = '<a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ReportAbuse\',\'ReportAbuse\')" style="color:#FF0000">REPORT ABUSE</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'NewsUpdate\',\'NewsUpdate\')" style="color:#FF0000">NEWS UPDATES</a> | <a href="http://slickflash.net/tos.html" target="_blank" style="color:#FF0000">TOS</a>';

	var l_menu = new Array("Home","Missions","Treasury","Weapons","Assets","Attack","Threat List","Medic","Allies","Profile","Top 25","Foreign Aid","Upgrade","Help");
	
    GANGSTERS.refreshDiv = new RefreshDiv(l_refreshDiv);
    GANGSTERS.statusDiv = new StatusDiv(l_statusDiv);
    GANGSTERS.menuDiv = new MenuDiv(l_menuDiv,l_menu,l_containerDiv);
	
    if(isValid(getOSparam(GANGSTERS.SHOW_USER_ID))){
        GANGSTERS.menuDiv.navigateTo(9);
    }
	
    if(isValid(getOSparam("show_family_tree"))){
		GANGSTERS.menuDiv.navigateToDynamicTab('FamilyTree','FamilyTree');
	}
	
    if(isValid(getOSparam("OE"))){
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		makeRequest("creditOE", function(a_response){},	l_params);
    }
	
    if(isValid(getOSparam("MOBWARS"))){
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		makeRequest("credit_mobwars", function(a_response){},	l_params);
    }
}

function customEncoding(a_text) {		
		var txt = "enco_" + encodeURIComponent(a_text).replace(/%/g, "@");
        return addslashes(txt);
}
	
function decodeEncodedStringValue(a_value){
        if (a_value == undefined){
            return undefined;
        } else {
            return decodeURIComponent(a_value);
        }
    }
	
function DoRefresh(){
    var l_params = {};
    l_params.user_id = GANGSTERS.VIEWER.getUserId();
    makeRequest("refresh_stat",
            function(a_response){
                var l_xmlDoc = getResponseData(a_response);
                var l_updatedInfoNode = getXMLFirstNode(l_xmlDoc, "viewer");
                GANGSTERS.VIEWER.fillSpecificInfoFromXML(l_updatedInfoNode);
				
				GANGSTERS.VIEWER_REQUESTS.invalidateCache();
				GANGSTERS.VIEWER_GANG.invalidateCache();
				GANGSTERS.NEW_GANGSTERS.invalidateCache();				
				GANGSTERS.GANG_MEMBERS.invalidateCache();
				GANGSTERS.statusDiv.refresh();
				GANGSTERS.refreshDiv.refresh();
				GANGSTERS.menuDiv.refresh();
            },
            l_params);
}

// Custom drop action for the Family boxes
function dropItems(idOfDraggedItem,targetId,x,y){
	var targetObj = document.getElementById(targetId);	// Creating reference to target obj
	var subDivs = targetObj.getElementsByTagName('div');	// Number of subdivs
	if(subDivs.length>=2 && targetId!='members')
	{
		return;
	}
	else if(subDivs.length==1)
	{
		var id = subDivs[0].id.replace(/[^0-9]/gi,'')/1;
		if(id>5000)
		{
			return;
		}
		//var y=targetObj.getElementsByTagName("DIV")[0];
		//x=targetObj.removeChild(y);
	}
	else if(subDivs.length>0 && targetId!='members')
	{
		return;	// Sub divs exists on target, i.e. element already dragged on it. => return from function without doing anything
	}
	else
	{
	}
	var sourceObj = document.getElementById(idOfDraggedItem);	// Creating reference to source, i.e. dragged object
	if(targetId=='members'){	// Target is the capital box - append the dragged item as child of first sub div, i.e. as child of <div id="dropContent">
		targetObj = targetObj.getElementsByTagName('div')[0];	
	}
	targetObj.appendChild(sourceObj);	// Append	
}


// FamilyTree
    function FamilyTree(a_parentDiv, a_type){
		
		this.dragDropObj = undefined;
		
		this.m_parentDiv = a_parentDiv;
		
		this.m_menuDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_menuDiv);
		this.m_menuDiv.innerHTML = '' +
		'<div id="feedMenu"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(8)">Invite Friends</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ManageGang\',\'ManageGang\')">Manage Allies</a> | <a href="#top" onClick="showFamilyTree()">War Cabinet</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ChooseSide\',\'ChooseSide\')">Choose a side</a></div>';
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_contentDiv);
				
		this.m_table = document.createElement("table");
		this.m_parentDiv.appendChild(this.m_table);
		
		this.m_tbody = document.createElement("tbody");
		this.m_table.appendChild(this.m_tbody);
		
		this.m_tableTr = document.createElement("tr");
		this.m_tbody.appendChild(this.m_tableTr);
		
		this.m_leftTd = document.createElement("td");
		this.m_tableTr.appendChild(this.m_leftTd);
		
		this.m_rightTd = document.createElement("td");
		this.m_tableTr.appendChild(this.m_rightTd );		
		
		this.m_buttonDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_buttonDiv);
		
		this.refresh();
	}

    FamilyTree.prototype.refresh = function(){
		this.m_leftTd.innerHTML = "";
		this.m_rightTd.innerHTML = "";
		this.m_resultDiv.innerHTML = "";
        var l_self = this;
		
		//tree code
		this.dragDropObj = new DHTMLgoodies_dragDrop();	// Creating drag and drop object
		//

        new MemberTreeTableParentDiv( this.m_leftTd, GANGSTERS.GANG_MEMBERS, 3, 30,
                                function(a_user){return l_self.TdCreater(a_user);}, 
                                "<a href='#' onclick='GANGSTERS.menuDiv.navigateTo(8)'>Invite your friends to be your Allies!",this.dragDropObj);
		
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        l_params.thumbnail_url = GANGSTERS.VIEWER.getThumbnailUrl();
        makeRequest("get_family_tree", function(a_responseData){l_self.onGetFamilyTree(a_responseData);}, l_params,l_self);

		this.m_buttonDiv.innerHTML = '<div align="center"><div class="button"><a href="#top" onClick="GANGSTERS.FamilyTree.saveTree()">Save War Cabinet</a></div></div>';
		//this.dragDropObj.init();	// Initizlizing drag and drop object

		//tree code end
    }
	
	FamilyTree.prototype.onGetFamilyTree = function(a_responseData){
		var l_self = this;
        var l_xmlDoc = getResponseText(a_responseData);
		
        if(isValid(l_xmlDoc)){
            try{
				this.m_rightTd.innerHTML = l_xmlDoc;
				
				// Assigning drop events on the family
				this.dragDropObj.addTarget('box1','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box2','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box3','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box4','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box5','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box6','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box7','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box8','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box9','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box10','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box11','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box12','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box13','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('box14','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop
				this.dragDropObj.addTarget('members','dropItems'); // Set <div id="leftColumn"> as a drop target. Call function dropItems on drop

				for(var i=1; i<=14; i++)
				{
					var targetId = 'box'+i;
					var targetObj = document.getElementById(targetId);	// Creating reference to target obj
					var subDivs = targetObj.getElementsByTagName('div');	// Number of subdivs
					if(subDivs.length>0)
					{
						this.dragDropObj.addSource(subDivs[0].id,true);	// Make <div id="box1"> dragable. slide item back into original position after drop						
					}
				}

				this.dragDropObj.init();
				
            } catch (err) {}
        }
	}
	
	FamilyTree.prototype.saveTree = function(){
		var l_params = {};
		var l_self = this;
		this.m_resultDiv.innerHTML = "Saving ...";
		
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		var output = '';
		for(var i=1; i<=14; i++)
		{
			var targetId = 'box'+i;
			var targetObj = document.getElementById(targetId);	// Creating reference to target obj
			var subDivs = targetObj.getElementsByTagName('div');	// Number of subdivs
			if(subDivs.length>0)
			{
				var id=subDivs[subDivs.length-1].id.replace(/[^0-9]/gi,'')/1;
				if(id>5000)
				{
					output += i + ":" + id +",";
				}
			}
		}
		l_params.family_tree = output;
		makeRequest("save_family_tree",
			function(a_response){
				handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();});},
			l_params,l_self);
	}

    FamilyTree.prototype.TdCreater = function(a_user){
        var l_div = document.createElement("div");
		l_div.className = "dragableBox";
		l_div.id = 'box'+a_user.getUserId();
		l_div.innerHTML = '<img src="'+a_user.getThumbnailUrl()+'" height="50" width="50" />';
        return l_div;
    }
// end FamilyTree

//Foreign_Aid
	function Foreign_Aid(a_parentDiv){
		this.m_parentDiv = a_parentDiv;

		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);

		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_contentDiv);
		
        this.offerPalURL =  "http://pub.myofferpal.com/50a4a6b00fdadaab71521619a9996517/showoffers.action?snuid=" + (GANGSTERS.VIEWER.getUserId());

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

        if(isValid(GANGSTERS.VIEWER.getGender())){
            this.offerPalURL += "&gender="+GANGSTERS.VIEWER.getGender();
        }
		
		this.refresh();
	}
	
	Foreign_Aid.prototype.refresh = function(){
		this.m_contentDiv.innerHTML = '' +
		'<div id="newUsers">' +
			'<h1>Foreign Aid (You have '+GANGSTERS.VIEWER.getOfferPoints()+' offer points) <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ReportAbuse\',\'ReportAbuse\')" style="color:#FF0000">Missing Offer Points? E-Mail Us</a></h1>' +
			'<div class="tips">' +
				'Get offer points from rich Foreign Nations by completing offers below. You can trade offer points for various rewards, such as money, allies, territory, weapons and more. Offer points are not required to play the game; however, they can give you a quick boost/advantage.<br/><br/><font size="1"></font>' +
			'</div>' +
		'</div>' +
		'<div class="categoryTableTitle">' +
				'<table align="center">' +
					'<tr>' +
						'<th>Description</th>' +
						'<th>Requirement</th>' +
						'<th>Reward</th>' +
						'<th>Accept</th>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Extra Funds $10,000</span></td>' +
						'<td>10 Offer Points</td>' +
						'<td><span class="money">$10,000</span></span></td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'cash10\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Extra Funds $25,000</span></td>' +
						'<td>15 Offer Points</td>' +
						'<td><span class="money">$25,000</span></span></td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'cash15\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Extra Funds $35,000</span></td>' +
						'<td>20 Offer Points</td>' +
						'<td><span class="money">$35,000</span></span></td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'cash20\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Extra Funds $50,000</span></td>' +
						'<td>30 Offer Points</td>' +
						'<td><span class="money">$50,000</span></span></td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'cash30\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Buy 1 new allies</span></td>' +
						'<td>10 Offer Points</td>' +
						'<td>acquire 1 new allies</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'hire10\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Buy 5 new allies</span></td>' +
						'<td>15 Offer Points</td>' +
						'<td>acquire 5 new allies</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'hire15\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Buy 10 new allies</span></td>' +
						'<td>25 Offer Points</td>' +
						'<td>acquire 10 new allies</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'hire25\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Buy 15 new allies</span></td>' +
						'<td>35 Offer Points</td>' +
						'<td>acquire 15 new allies</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'hire35\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Get 1 Research point</span></td>' +
						'<td>10 Offer Points</td>' +
						'<td>1 Research points</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'skillpoints10\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Get 5 Research point</span></td>' +
						'<td>15 Offer Points</td>' +
						'<td>5 Research points</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'skillpoints15\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Get 10 Research point</span></td>' +
						'<td>25 Offer Points</td>' +
						'<td>10 Research points</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'skillpoints25\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Courage refill</span></td>' +
						'<td>10 Offer Points</td>' +
						'<td>Full Courage Refill</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'adrenaline\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Health refill</span></td>' +
						'<td>10 Offer Points</td>' +
						'<td>Full Health Refill</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'health\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Stamina refill</span></td>' +
						'<td>10 Offer Points</td>' +
						'<td>Full Stamina Refill</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'stamina\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Resupply all weapons</span></td>' +
						'<td>50 Offer Points</td>' +
						'<td>Resupply all units</td>' +
						'<td><input type="submit" value="Accept" onClick="GANGSTERS.Foreign_Aid.accept(\'reload\')"></td>' +
					'</tr>' +
				'</table>' +
		'</div>' +
		'<div id="newUsers">' +
			'<h1>Buy Offer Points using PayPal</h1>' +
			'<div class="tips">' +
				'Buy offer points using your paypal account or credit card. <br/><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ReportAbuse\',\'ReportAbuse\')" style="color:#FF0000">Missing Offer Points? E-Mail Us</a>' +
			'</div>' +
			'<form action="http://www.slickflash.net/secure/paypalsubmit.php" target="_blank" name="paypal_form" method="post">' +
				'<input type="hidden" name="cmd" value="_xclick">' +
				'<input type="hidden" name="item_name" value="Buy offer points for World At War II"> ' +
				'<input type="hidden" name="shipping" value="0.00"/>' +
				'<input type="hidden" name="no_shipping" value="1"/>					' +
				'<input type="hidden" name="no_note" value="1">' +
				'<input type="hidden" name="currency_code" value="USD"> ' +
				'Buy Offer Points ' +
				'<select name="amount">' +
				'<option value="2.0">10 offer points for $2.00</option>' +
				'<option value="3.00">15 offer points for $3.00</option>' +
				'<option value="4.00">20 offer points for $4.00</option>' +
				'<option value="5.00">25 offer points for $5.00</option>' +
				'<option value="10.00">50 offer points for $10.00</option>' +
				'<option value="20.00">100 offer points for $20.00</option>' +
				'<option value="35.00">175 offer points for $35.00</option>' +
				'<option value="50.00">250 offer points for $50.00</option>' +
				'<option value="75.00">375 offer points for $75.00</option>' +
				'<option value="100.00">500 offer points for $100.00</option>' +
				'</select>' +
				'<input type="hidden" name="custom" value="' + GANGSTERS.VIEWER.getUserId() + '">' +
				'<br/><br/>'+
				'<input type="image" border="0" alt="Make payments with PayPal - it\'s fast, free and secure!" name="submit" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" /> ' +
				'<input type="hidden" name="return" value="http://apps.myspace.com/120549">' +
				'<input type="hidden" name="cancel_return" value="http://apps.myspace.com/120549">' +
				'<input type="hidden" name="notify_url" value="http://www.slickflash.net/WorldAtWarII/paypal.php">' +
			'</form>' +
		'</div>';
        /* +
		'<div id="newUsers">' +
			'<h1>Earn Offer Points</h1>' +
			'<div class="tips">' +
				'Earn favor points and help sponsor this application by completing offers!<br/>' +
				'<a href="http://pub.myofferpal.com/50a4a6b00fdadaab71521619a9996517/userstatus.action?snuid='+GANGSTERS.VIEWER.getUserId()+'" target="_blank">Missing Favor Points, click here!</a>' +
			'</div>' +
		'</div>' +
		'<div align="center">' +
		'<iframe style="width:650px; height: 2300px; margin-left:auto; margin-right:auto; overflow:auto; border:none;" src="'+this.offerPalURL+'">' +
		'</iframe>' +
		'</div>';
        */
        /* +	
		'<div align="center">' +
			'<h1>Earn Offer Points</h1>' +
			'<iframe style="width:650px; height: 1400px; margin-left:auto; margin-right:auto; overflow:auto; border:none;" src="' + GANGSTERS.BASE_URL + '/clickbank_offers.php?user_id=' + GANGSTERS.VIEWER.getUserId() + '"></iframe>' +
		'</div>' +	
		'<div id="newUsers">' +
			'<h1>Subscribe Offer Points</h1>' +
			'<div class="tips">' +
				'You will get 75 and 100 offer points weekly with $15 and $20 subscription monthly fee respectively. Buy offer points using your paypal account or credit card. <br/><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ReportAbuse\',\'ReportAbuse\')" style="color:#FF0000">Missing Offer Points? E-Mail Us</a>' +
			'</div>' +
			'<iframe src="'+GANGSTERS.BASE_URL+'/terms.html" width="800" height="150"></iframe><br/><br/> ' +
			'<form id="paypalSubscribeForm" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"> ' +
				'<input type="hidden" name="cmd" value="_xclick-subscriptions"> ' +
				'<input type="hidden" name="lc" value="US"> ' +
				'<input type="hidden" name="item_name" value="Monthly Subscription for World At War II"> ' +
				'<input type="hidden" name="no_note" value="1"> ' +
				'<input type="hidden" name="no_shipping" value="1"> ' +
				'<input type="hidden" name="rm" value="1"> ' +
				'<input type="hidden" name="return" value="http://apps.myspace.com/worldwarapp"> ' +
				'<input type="hidden" name="cancel_return" value="http://apps.myspace.com/worldwarapp"> ' +
				'<input type="hidden" name="custom" value="' + GANGSTERS.VIEWER.getUserId() + '"> ' +
				'Buy Offer Points  ' +
				'<select name="a3"> ' +
					'<option value="15.00">Get 75 offer points weekly with $15 monthly subscription</option> ' +
					'<option value="20.00">Get 100 offer points weekly with $20 monthly subscription</option> ' +
				'</select> ' +
				'<input type="hidden" name="currency_code" value="USD"> ' +
				'<input type="hidden" name="src" value="1"> ' +
				'<input type="hidden" name="p3" value="1"> ' +
				'<input type="hidden" name="t3" value="M"> ' +
				'<input type="hidden" name="bn" value="PP-SubscriptionsBF:btn_subscribeCC_LG.gif:NonHostedGuest"> ' +
				'<input type="hidden" name="notify_url" value="http://www.owneveryone.com/WorldAtWarII/paypalsubscription.php"> ' +
				'<br/> ' +
				'<input type="checkbox" name="iagreeChk" id="iagreeChk" />I agree, terms of service' +
				'<div id="iagreeErrorDiv" style="color:#FF0000"></div><br/> ' +
				'<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="" onClick="return GANGSTERS.Foreign_Aid.checkPaypalForm();"> ' +
				'<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"> ' +
			'</form> ' +
		'</div>' +
		'<div id="newUsers">' +
			'<h1>Buy Offer Points using your Mobile Phone</h1>' +
			'<div class="tips">' +
				'Don\'t have credit card? No problem use your mobile phone to buy offer points. You will be billed by your mobile operator. However your mobile carrier network must be located within USA. All transactions are processed by zong.com <br/>' +
				'Step 1: Select payment amount and enter your mobile number<br/>' +
				'Step 2: Enter the PIN code that you received in your mobile<br/>' +
				'Step 3: Transaction completed. You will get transaction notification in your mobile.' +
				'<br/><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ReportAbuse\',\'ReportAbuse\')" style="color:#FF0000">Missing Offer Points? E-Mail Us</a>' +
			'</div>' +
				'<form action="http://www.owneveryone.com/WorldAtWarII/zong/step2.php" method="post" target="_blank">' +
				'<input type="hidden" name="user_id" value="' + GANGSTERS.VIEWER.getUserId() + '">' +
				'<table>' +
					'<tr>' +
						'<td>Buy Offer Points</td>' +
						'<td>' +
							'<select name="market_id">' +
							'<option value="2994">1 offer points for $0.25</option>' +
							'<option value="2995">2 offer points for $0.50</option>' +
							'<option value="2984">5 offer points for $1.00</option>' +
							'<option value="2996">15 offer points for $2.99</option>' +
							'</select>' +
						'</td>' +
						'<td>' +
					'</tr>' +
					'<tr>' +
						'<td>Your mobile number</td>' +
						'<td>' +
							'<input type="text" name="phone1" maxlength="3" size="3" /> - ' +
							'<input type="text" name="phone2" maxlength="3" size="3" /> - ' +
							'<input type="text" name="phone3" maxlength="4" size="4" />' +
						'</td>'+
					'</tr>' +
					'<tr>' +
						'<td>&nbsp;</td>' +
						'<td><input type="submit" value="submit"/></td>' +
					'</tr>' +
				'</table>' +
				'</form>' +
		'</div>';*/
	}
	
	Foreign_Aid.prototype.checkPaypalForm = function(){
		if(document.getElementById('iagreeChk').checked == true){
			document.getElementById('iagreeErrorDiv').innerHTML = '';
			document.getElementById('paypalSubscribeForm').submit();
			return true;
		}
		else{
			document.getElementById('iagreeErrorDiv').innerHTML = '<br/>You must agree our Terms of Service';
			return false;
		}
	}
	
	Foreign_Aid.prototype.accept = function(a_reward){
		goToPageTop();
		var l_self = this;
		l_self.m_resultDiv.innerHTML = "Checking.....";

		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.reward = a_reward;
		makeRequest("accept_godfather",
				function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
				l_params,l_self);
	}
//end Foreign_Aid

function FriendPicker(a_parentDiv, a_cachedFriendList, a_numCheckCallback){

    var m_parentDiv = a_parentDiv;
    var m_cachedFriendList = a_cachedFriendList;
    var m_numCheckCallback = a_numCheckCallback;
    var m_containerDiv = undefined;
    var m_selectedUserIdMap = new Object();
    var m_numUsers = undefined;
    var m_currentPage = undefined;

    var m_friendPickerContentDiv = undefined;

    this.getSelectedFriends = getSelectedFriends;
    this.unselectFriends = unselectFriends;

	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){

        m_numUsers = a_num_users;
        jumpToPage(1);
    }

    function jumpToPage(a_pageNum){
        m_currentPage = a_pageNum;
        m_containerDiv.innerHTML = "";

        createSelectDiv(m_containerDiv);

        if (!isValid(m_numUsers) || m_numUsers == 0) {
            var l_noUsersInstructionsDiv = document.createElement("div");
            m_containerDiv.appendChild(l_noUsersInstructionsDiv);
            l_noUsersInstructionsDiv.style.color = "#AAAAAA";
            l_noUsersInstructionsDiv.innerHTML = "Sorry, an error has occured! Please try again.";
        } else {
            createPageNumbersDiv(m_containerDiv);
			
            m_friendPickerContentDiv = new  FriendPickerContentDiv(m_containerDiv, m_cachedFriendList, m_currentPage, m_selectedUserIdMap, getNumSelected(), m_numCheckCallback);
			
            createPageNumbersDiv(m_containerDiv);
        }
    }

    function getNumSelected(){
        var l_num_selected = 0;
        for(var id in m_selectedUserIdMap){
            if(isValid(m_selectedUserIdMap[id])){
                l_num_selected += 1;
            }
        }
        return l_num_selected;
    }

    function createSelectDiv(a_parentDiv){

        var l_selectDiv = document.createElement("div");
        a_parentDiv.appendChild(l_selectDiv);
        l_selectDiv.style.textAlign = "center";
		/*
        var l_selectAllSpan = makeElement("span", l_selectDiv, {fontSize:"12px", textDecoration:"underline", color:"#FFFFFF", cursor:"pointer"});
        l_selectAllSpan.innerHTML = "Select All";

        addEvent(l_selectAllSpan, "click", function(){
            clearSelectedUserIdMap();
            if(isValid(m_friendPickerContentDiv)){
                m_friendPickerContentDiv.selectAll();
            }
        });
		
		var l_middleSpan1 = makeElement("span", l_selectDiv, {fontSize:"15px", color:"#FFFFFF", padding:"0px 10px 0px 10px"});
        l_middleSpan1.innerHTML = "|";
		*/
        var l_selectRandom10Span = makeElement("span", l_selectDiv, {fontSize:"12px", textDecoration:"underline", color:"#FFFFFF", cursor:"pointer"});
        l_selectRandom10Span.innerHTML = "Select Random 20";

        addEvent(l_selectRandom10Span, "click", function(){
            clearSelectedUserIdMap();
            if(isValid(m_friendPickerContentDiv)){
                m_friendPickerContentDiv.selectRandom10();
            }
        });

        var l_middleSpan2 = makeElement("span", l_selectDiv, {fontSize:"15px", color:"#FFFFFF", padding:"0px 10px 0px 10px"});
        l_middleSpan2.innerHTML = "|";

        var l_clearSelectionSpan = makeElement("span", l_selectDiv, {fontSize:"12px", textDecoration:"underline", color:"#FFFFFF", cursor:"pointer"});
        l_clearSelectionSpan.innerHTML = "Clear Selected";

        addEvent(l_clearSelectionSpan, "click", function(){
            clearSelectedUserIdMap();
            if(isValid(m_friendPickerContentDiv)){
                m_friendPickerContentDiv.unselectFriends();
            }
        });
    }

    function createPageNumbersDiv(a_parentDiv){
        var l_numPages = Math.ceil(m_numUsers / 40);
        new PaginationDiv(a_parentDiv, jumpToPage, l_numPages, m_currentPage, 20);
    }

    function getSelectedFriends(){
        var l_selectedFriends = new Array();
        for(var id in m_selectedUserIdMap){
            if(isValid(m_selectedUserIdMap[id])){
                l_selectedFriends.push(m_cachedFriendList.getUserById(id));
            }
        }
        return l_selectedFriends;
    }

    function unselectFriends(){
        m_selectedUserIdMap = new Object();
        jumpToPage(m_currentPage);
    }

    function clearSelectedUserIdMap(){
        for(var id in m_selectedUserIdMap){
            m_selectedUserIdMap[id] = undefined;
        }
    }

}

function FriendPickerContentDiv(a_parentDiv, a_cachedUserList, a_currentPage, a_selectedFriendMap, a_numChecked, a_numCheckCallback){
    var m_parentDiv = a_parentDiv;
    var m_cachedUserList = a_cachedUserList;
    var m_numChecked = a_numChecked;
    var m_currentPage = a_currentPage;
    var m_selectedFriendIdMap = a_selectedFriendMap;
    var m_numCheckCallback = a_numCheckCallback;

    var m_containerDiv = undefined;
    var m_pickForm = undefined;

    var m_friendTdArray = new Array();
    var m_checkboxArray = new Array();

    this.getSelectedFriendIds = getSelectedFriendIds;
    this.unselectFriends = unselectFriends;
    this.selectRandom10 = selectRandom10;
    this.selectAll = selectAll;

	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 Friends...";

	m_cachedUserList.getUsers((m_currentPage-1)*40, 40, onLoadedFriends);

    function onLoadedFriends(a_friends){

        if(a_friends == undefined){
            m_containerDiv.innerHTML = "Unfortunately, we could not locate 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";
        l_friendsTable.style.textAlign = "center";
        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 >= 6){
                l_currentRow = document.createElement("tr");
                l_friendsTBody.appendChild(l_currentRow);
                l_numInCurrentRow = 0;
            }
	        if(l_friend.getpartOfViewerGang() || l_friend.getRequestedByUser()){
	            continue;
	        }
			else{
				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 = "#000000";
        l_td.selected = false;
        l_td.onmouseover = function() { if (!l_td.selected) { l_td.style.backgroundColor = "#FF0000";}};
        l_td.onmouseout = function() { if (!l_td.selected) { l_td.style.backgroundColor = "#000000";}};
        l_td.style.cursor = "pointer";

        if(a_friend.getpartOfViewerGang()){
            var l_noteDiv = document.createElement("div");
            l_td.appendChild(l_noteDiv);
            l_noteDiv.innerHTML = "<span style='font-weight:bold; color:#00FF00; text-align:center;'> 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:#FFFFFF; text-align:center;'> Requested </span>";
        }

        var imageDiv = document.createElement("div");
		imageDiv.style.textAlign = "center";
        l_td.appendChild(imageDiv);
		imageDiv.innerHTML = '<img src="'+a_friend.getThumbnailUrl()+'" width="70" height="70" />';
		
        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_nameTd = document.createElement("td");
        imageCheckRow.appendChild(l_nameTd);

        if(isValid(a_friend)){
          l_nameTd.innerHTML = shortenedStringKeepEscapedCharacters(a_friend.getName(), 12);
        }

       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="#FF0000";
            checkboxTd.style.color = "white";
        }
        checkboxTd.appendChild(l_friendCheckbox);
		
        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++;
        }

        return false;
    }

    function setBackground(a_td) {
        a_td.selected = !a_td.selected;

        if (a_td.selected) {
            a_td.style.backgroundColor="#FF0000";
            a_td.style.color = "white";
        } else {
            a_td.style.backgroundColor="#000000";
            a_td.style.color = "white";
        }
    }

    function getSelectedFriendIds(){
        var selectedFriendsIds = new Array();
        for(var i = 0; i < m_pickForm.pickFriend.length; i++){
            if(m_pickForm.pickFriend[i].checked){
                selectedFriendsIds.push(m_pickForm.pickFriend[i].value);
            }
        }
        return selectedFriendsIds;
    }

    function unselectFriends() {
        for(var i = 0; i < m_friendTdArray.length; i++){
            m_friendTdArray[i].checked = false;
            m_friendTdArray[i].selected = false;
            m_friendTdArray[i].style.backgroundColor="black";
            m_friendTdArray[i].style.color = "white";
        }

        for(var i = 0; i < m_checkboxArray.length; i++) {
            m_checkboxArray[i].checked = false;
            m_numChecked = 0;
        }
    }

    function selectRandom10(){
        unselectFriends();

        var l_randomIndices = getRandomNumbers(m_friendTdArray.length-1, 20);
        m_numChecked = l_randomIndices.length;

        for(var l_index = 0; l_index < l_randomIndices.length; l_index++){
            var l_randomIndex = l_randomIndices[l_index];
            var l_userId = m_checkboxArray[l_randomIndex].value;

            m_friendTdArray[l_randomIndex].checked = true;
            m_friendTdArray[l_randomIndex].selected = true;
            m_friendTdArray[l_randomIndex].style.backgroundColor="#FF0000";
            m_friendTdArray[l_randomIndex].style.color = "white";
            m_checkboxArray[l_randomIndex].checked = true;

            m_selectedFriendIdMap[l_userId] = l_userId;
        }
    }
	
    function selectAll(){
        unselectFriends();

        m_numChecked = m_friendTdArray.length;

        for(var l_index = 0; l_index < m_friendTdArray.length; l_index++){
            var l_userId = m_checkboxArray[l_index].value;

            m_friendTdArray[l_index].checked = true;
            m_friendTdArray[l_index].selected = true;
            m_friendTdArray[l_index].style.backgroundColor="#FF0000";
            m_friendTdArray[l_index].style.color = "white";
            m_checkboxArray[l_index].checked = true;

            m_selectedFriendIdMap[l_userId] = l_userId;
        }
    }
}


//GameSetup
    function GameSetup(a_parentDiv, a_finish_callback){
        this.m_parentDiv = a_parentDiv;
        this.m_finishCallback = a_finish_callback;
		
		this.m_imageDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_imageDiv);		
		this.m_imageDiv.innerHTML = '<img src="'+GANGSTERS.BASE_URL+'/images/logo.jpg" /><br/>';
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_contentDiv);

		this.refresh();
    }

    GameSetup.prototype.refresh = function(){
        this.m_contentDiv.innerHTML = "";

        if(!isValid(GANGSTERS.VIEWER.getGangName())){
            this.chooseNameUI();
        } else if(!isValid(GANGSTERS.VIEWER.getGangClass())){
            this.chooseStyleUI();
        } else {
            this.m_finishCallback();
        }
    }

    GameSetup.prototype.chooseNameUI = function(){
		this.m_contentDiv.innerHTML = '' +
		'<h1>Choose the name of your Nation\'s ruler</h1>' +
		'Choose your Leader\'s name (ex. George W. Bush):' +
		'<input type="text" id="gangName" max_length="50" /> ' +
		'<input type="button" value="Choose Name" onClick="GANGSTERS.GameSetup.saveName()" />' +
		'<br/><br/>Name can contain underscore ( _ ) but no other special characters';
	}

	GameSetup.prototype.saveName = function(){
        var l_self = this;
        this.m_resultDiv.innerHTML = "Checking ... ";

		var l_name = document.getElementById('gangName');
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.gang_name =customEncoding(l_name.value);

		makeRequest("choose_name",
			function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
			l_params,l_self);
    }

    GameSetup.prototype.chooseStyleUI = function(){
        this.m_contentDiv.innerHTML = '' +
		'<h1>Choose Ruling Style</h1>' +
		'<table align="center">' +
			'<tr>' +
			'<td valign="top">Choose your style:</td>' +
			'<td>' +
				'<input type="radio" name="gangStyle" id="Adrenaline_Junkie" value="Fascist" />Fascist (get courage faster)<br/>' +
				'<input type="radio" name="gangStyle" id="Health_Freak" value="Marxist" />Marxist (get health faster)<br/>' +
				'<input type="radio" name="gangStyle" id="Big_Earner" value="Capitalist" />Capitalist (get money faster)' +
			'</td>' +
			'<tr><td></td><td><input type="button" value="Choose Style" onClick="GANGSTERS.GameSetup.saveStyle()" /></td></tr>' +
		'</table>';
	}

	GameSetup.prototype.saveStyle = function(){

        var l_self = this;

		var l_gangStyle = undefined;
		
		var l_style = document.getElementById('Adrenaline_Junkie');
		if(l_style.checked){
			l_gangStyle = l_style.value;
		}
		var l_style = document.getElementById('Health_Freak');
		if(l_style.checked){
			l_gangStyle = l_style.value;
		}
		var l_style = document.getElementById('Big_Earner');
		if(l_style.checked){
			l_gangStyle = l_style.value;
		}
		
		if(l_gangStyle == undefined){
			this.m_resultDiv.innerHTML = "Please Select your Ruling Style";
			return;
		}
		
        this.m_resultDiv.innerHTML = "Checking ... ";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.gang_class = l_gangStyle;

		makeRequest("choose_class",
			function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
			l_params,l_self);
    }
//end GameSetup

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 getOSparam(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){
        }
    }

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

function getResponseData(a_response){
        if(a_response.data == null || a_response.data == undefined){
            return undefined;
        }
        return a_response.data;
    }

function getResponseText(a_response){
        if(a_response.text == null || a_response.text == undefined){
            return undefined;
        }
        return a_response.text;
    }

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 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 goToPageTop(){
   location.href = "#top";
}


// Gold_Shop
    function Gold_Shop(a_parentDiv, a_category){
		this.m_parentDiv = a_parentDiv;
		this.m_category = a_category;
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);
		
		this.m_infoDiv.innerHTML = '' +
			'<h1>Gold Shop</h1>' +
			'<div class="tips">' +
				'Buy and Sell Gold on the open market for profit. Buy gold when the price is low and sell when the price is high. Prices fluctuate depending on real world gold prices! If you don\'t need to be here then, ' +
				' <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(2)">Click here</a> to go back.' +

			'</div>';
		
		this.m_contentDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_contentDiv);
		
		this.refresh();
    }

	Gold_Shop.prototype.refresh = function(){
        this.m_contentDiv.innerHTML = "Loading your stats...";
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        
        var l_self = this;
        makeRequest("get_gold_stats", function(a_responseData){
           l_self.onGetData(a_responseData);
        },l_params,l_self);
	}
	
    Gold_Shop.prototype.onGetData = function(a_responseData){
		
        var l_xmlDoc = getResponseData(a_responseData);
		var l_table = '';
		
        if(isValid(l_xmlDoc)){
            try{
                var gold_per_ounce = parseFloat(getXMLNodeValue(l_xmlDoc, "gold_per_ounce"));
                var last_updated = getXMLNodeValue(l_xmlDoc, "last_updated");
				
				if(isValid(gold_per_ounce)){
					var l_gold = GANGSTERS.VIEWER.getGold();
					
					if(l_gold > GANGSTERS.one_troy_ounce){
						var l_totalGold = number_format(l_gold / GANGSTERS.one_troy_ounce) + ' ounces';
					}
					else{
						var l_totalGold = number_format(l_gold) + ' grams';
					}
					var goldPerGram = gold_per_ounce / GANGSTERS.one_troy_ounce;
					
					l_table = '' +
					'<br /><br /><div id="status">' +
						'<table>' +
							'<tr>' +
								'<td><div class="statusTitle">Your Total Gold</div> <div>' + l_totalGold + '</div></td>' +
								'<td><div class="cashTitle">Value</div> <div>$' + (number_format(l_gold * goldPerGram)) + '</div></td>' +
								'<td><div class="statusTitle">Exchange Rate</div> <div> 1 ounce = $' + (number_format(gold_per_ounce)) + '</div></td>' +
								'<td><div class="statusTitle">Rates last updated</div> <div>' + last_updated + '</div></td>' +
								
							'</tr>' +
						'</table>' +
					'</div>' +
					'<div class="general">' +
						'<table> ' +
							'<tr>' +
								'<td> Buy Gold Worth: $</td>' +
								'<td> <input type="text" id="buy_amount" value="' + GANGSTERS.VIEWER.getCash() + '"/> </td>' +
								'<td> <input type="submit" value="Buy Gold" onClick="GANGSTERS.Gold_Shop.buy()" /> </td>' +
							'</tr>' +
							'<tr>' +
								'<td> Sell Gold Worth: $</td>' +
								'<td> <input type="text" id="sell_amount" value="' + Math.floor( l_gold * goldPerGram ) + '" /> </td>' +
								'<td> <input type="submit" value="Sell Gold" onClick="GANGSTERS.Gold_Shop.sell()" /> </td>' +
							'</tr>' +
						'</table>' +
					'</div>';
				}
				else{
					this.m_resultDiv.innerHTML = 'Could not acquire gold stats. Please refresh this page.';
				}
            } catch (err) {}
        }
		
		this.m_contentDiv.innerHTML = l_table;
    }
	
	Gold_Shop.prototype.buy = function(){
		var l_self = this;
		var l_amount = document.getElementById("buy_amount");
		if(!validateAmount(l_amount.value)){
			this.m_resultDiv.innerHTML = "Please specify a valid amount to buy!";
			return;
		}

		this.m_resultDiv.innerHTML = "Buying Gold ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.amount = l_amount.value;
		makeRequest("buy_gold",
				function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
				l_params,l_self);
	}
	
	Gold_Shop.prototype.sell = function(){
		var l_self = this;
		var l_amount = document.getElementById("sell_amount");
		if(!validateAmount(l_amount.value)){
			this.m_resultDiv.innerHTML = "Please specify a valid amount to sell!";
			return;
		}

		this.m_resultDiv.innerHTML = "Selling Gold ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.amount = l_amount.value;
		makeRequest("sell_gold",
				function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
				l_params,l_self);
	}
// end Gold_Shop


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

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

    if(!isValid(l_xmlDoc)){
        a_resultDiv.innerHTML = "Oopsie, 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 = GANGSTERS.VIEWER.getLevel();

    if(isValid(l_success)){
		a_resultDiv.innerHTML = l_msg;
				
		GANGSTERS.VIEWER.fillSpecificInfoFromXML(l_updatedInfoNode);
		if(isValid(GANGSTERS.statusDiv) && isValid(GANGSTERS.refreshDiv)){
			GANGSTERS.statusDiv.refresh();
			GANGSTERS.refreshDiv.refresh();
		}
		if(isValidFunction(a_refreshCallback)){
			a_refreshCallback();
		}
    } else {
        a_resultDiv.innerHTML = "Oopsie, unexpected error. Please refresh and try again.";
    }
}

//Help
	function Help(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		
		this.m_parentDiv.innerHTML = '' +
        '<center><h1>World At War II Help Section</h1></center>' +
                 '<br>' +
                 '<br/>This section gives you a general idea of how things work in the World At War II application. Please check back for updates.' +
                 '<br><br>' +
                 '<ol>' +
                 '<li><b>Missions</b>' +
                 '<br> Complete missions to collect monetary rewards. To complete a mission, make sure you have the required items as shown in the requirements section. The higher you advance in the game, the more lucrative missions are revealed. Units get damaged while doing missions. Make sure you repair them or they render useless!</li><br>' +
                 '<li><b>The Treasury</b>' +
                 '<br> The Treasury protects your money in times of war. It is a very secure place to store your national treasures safely in the events of an attack from your enemies. 10% deposit fee is taken.</li><br>' +
                 '<li><b>Weapons</b>' +
                 '<br> You can purchase weapons in this section. You can buy only 1 weapon of each type for each allies. So, each type of weapon you can buy = size of your allies. Units get damaged while doing missions. Make sure you repair them or they render useless!</li><br>' +
                 '<li><b>Assets</b>' +
                 '<br> You can earn recurring income in the game if you hire unemployed staff land and make them work your campaigns or buildings. The price of assets increases in successive buying attempts. So you will save more money if you buy in bulk quantity. </li><br>' +
                 '<li><b>Attacking Nations</b>' +
                 '<br> You can attack any Nations ranked 1 level lower than you and 1 level higher than you. If you attack other nations then your most offensive weapons are used. Somebody attacks you then your most defensive weapons are used. You need to be well equipped to win in an attack, so make sure you have the proper weapons before you pick a fight and defend. Also remember that having more allies greatly increases the chances of your attack being successful. Number of allies that can take part in a fight = 5 X your current rank</li><br>' +
                 '<li><b>The Threat List</b>' +
                 '<br> This section lists all players that are considered threat nations and have had war waged on them. Attack these nations and receive bounties from their enemies. If you have an enemy you want to put on the threat list, navigate to their profile and click on the \"Add to Threat List\" link. You will get 80% of the bounty amount if you kill the nation in threat list otherwise you will not gain any cash.</li><br>' +
                 '<li><b>Medic</b>' +
                 '<br> You will be in medic center when your health goes down below 20% of your max health. The Medic Center will heal the injured soldiers in your Army after attacks and increase their health attribute by 20% - 30%. A maintenance fee required for each visit = $250 X your current rank</li><br>' +
                 '<li><b>Your Allies</b>' +
                 '<br> Add, delete and manage all your allies in this section. This section also contains a link to the War Cabinet where you can promote your closest allies by displaying them on the rank tree. Just drag and drop your friend\'\s pictures to the blank spots on the tree.</li><br>' +
                 '<li><b>Foreign Aid</b>' +
                 '<br> You can complete our sponsors offers to earn offer points or you can use paypal to buy offer points. Offer points can be exchanged with extra hired guns, extra cash, health refill, courage refill,  exchange for research points and resupply all weapons.</li><br>' +
                 '<li><b>Upgrade</b>' +
                 '<br> Everytime you advance a level you receive Research points. You can use these Research points to improve the attributes of your Nation. The attributes you can improve are the following: Attack Strength, Defense Power, Courage,  Health and Stamina. You can also start over your game character from this section.</li><br>' +
				 '<li><b>What is the War Cabinet?</b>' +
                 '<br> The Excutive tree lets you arrange the members in your Allied Army  by the order of importance. In short it is like a "top friends" section for your friends. People will be able to see your War Cabinet by visiting World at War II profile and even your myspace profile.</li><br>' +  
				 '<li><b>How can I see the other players playing the game?</b>' +
                 '<br> On the Main page, there is a link, \"Browse More...\" this link will give you a list of the other players in the application. </li><br>' +
                 '</li>' +
                 '</ol>';
	}
//end Help

//Home
	function Home(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		this.m_hasNewRequest = undefined;
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);		
		
		this.m_promoDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_promoDiv);

		this.m_newUsersDiv = document.createElement("div");
		this.m_newUsersDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_newUsersDiv);
		
		this.m_inviteDiv = document.createElement("div");
		this.m_inviteDiv.id = "invite";
		this.m_parentDiv.appendChild(this.m_inviteDiv);
		
		this.m_skillPointDiv = document.createElement("div");
		this.m_skillPointDiv.id = "skillpoints";
		this.m_parentDiv.appendChild(this.m_skillPointDiv);
		this.m_skillPointDiv.innerHTML = '<strong>You have, ' + GANGSTERS.VIEWER.getSkillPoints() + ' Research point(s) that you can use to <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(12)">upgrade</a></strong>';
		
		this.m_DetailMenuDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_DetailMenuDiv);
		this.m_DetailMenuDiv.innerHTML = '<h1>Quick Menu Links</h1>'+
		'<table align="center" width="85%"> ' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(1)">Missions</a></td><td class="quickmenu"> Complete Missions to earn the funds to grow your Army. </td> </tr>' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(2)">Treasury</a></td><td class="quickmenu"> Deposit your earnings into the Treasury to protect your funds from attacks.</td> </tr>' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(3)">Weapons</a></td><td class="quickmenu"> Purchase powerful weapons and Military units. </td> </tr>' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(4)">Assets</a></td><td class="quickmenu"> Purchase installations that generate you recurring income.</td> </tr> ' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(5)">Attack</a></td><td class="quickmenu"> Attack Enemy Nations and Conquer your Foes.</td> </tr>' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(6)">Threat List</a></td><td class="quickmenu"> Collect Rewards for destroying enemies on the Threat List.</td> </tr> ' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(7)">Medic</a></td><td class="quickmenu"> Heal your units by visiting the Medic Center.</td> </tr>' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(8)">Allies</a></td><td class="quickmenu"> Recruit and manage your Allies. Invite your friends to join!</td> </tr> ' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(9)">Profile</a></td><td class="quickmenu"> Check your Battle Statistics and view your Profile.</td> </tr> ' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(10)">Top 25</a></td><td class="quickmenu"> Top 25 Most Powerful Leaders & Nations.</td> </tr> ' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(11)">Foreign Aid</a></td><td class="quickmenu"> Low on Funds or Allies? Get them from Foreign Aid.</td> </tr> ' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(12)">Upgrade</a></td><td class="quickmenu"> Upgrade your Research points and make yourself more powerful.</td> </tr> ' +
		'<tr><td class="quicklinks"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(13)">Help</a></td><td class="quickmenu"> Help Section.</td> </tr>' +
		'</table>' ;
				
		this.m_bulletinDiv = document.createElement("div");
		this.m_bulletinDiv.id = "bulletin";
		this.m_parentDiv.appendChild(this.m_bulletinDiv);
		this.m_bulletinDiv.innerHTML = ''+
			'<div id="bulletin">' +
				'<h1>Send a Message</h1>' +
				'<div class="tips">Broadcast messages to your Allies. Each message costs you $50, but that\'s a small price to pay for staying well connected with your allies.</div>' +	
				'<div class="bulletinBox">' +
				'<textarea id="msg"></textarea>' +
				'<br />' +
					'<input type="button" value="Post a Bulletin to your Allies" onClick="GANGSTERS.Home.broadcast()" /></div>' +
			'</div>';
				
		this.m_newsFeedsDiv = document.createElement("div");
		this.m_newsFeedsDiv.id = "newsFeeds";
		this.m_parentDiv.appendChild(this.m_newsFeedsDiv);

		this.m_inviteUsers = new Array();
		
		this.m_message_feedDiv = undefined;
		this.m_comment_feedDiv = undefined;
		this.m_attack_feedDiv = undefined;
		this.m_hitlist_feedDiv = undefined;
		
		this.m_newsFeedsDivArr = new Array();
		
		this.checkNewRequests();
		this.getNewUsers();
		this.getInviteFrens();
		this.getNewsFeeds();
		this.getAlliesInfo();
		this.getPromoItem();
	}

	Home.prototype.checkNewRequests = function(){
		var l_numRequests = GANGSTERS.VIEWER.getNumRequests();
		if(isValid(l_numRequests) && l_numRequests > 0){
			this.m_hasNewRequest = '<a style="font-size:18px; font-weight: bold; color: blue; text-decoration:underline; padding-left:10px" href="#top" onClick="GANGSTERS.menuDiv.navigateTo(8)">Attention: You have ' + l_numRequests + ' request(s) to be your Ally.</a><br/>';
		}
	}
	
	Home.prototype.getNewUsers = function(){
		this.m_newUsersDiv.innerHTML = "Loading new Users...";
		var l_self = this;
		var l_param = {};
        l_param.user_id = GANGSTERS.VIEWER.getUserId();
		makeRequest("get_new_people",function(a_responseData){l_self.onGetNewUsers(a_responseData);},l_param,l_self);
	}
	
	Home.prototype.onGetNewUsers = function(a_responseData){
		this.m_newUsersDiv.innerHTML = '<h1>New Users (<a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'BrowseDiv\', \'BrowseDiv\')">Browse More</a>)</h1>';
        var l_xmlNode = getResponseData(a_responseData);
		
        if(isValid(l_xmlNode)){
            try{
                var l_entryNodes = l_xmlNode.getElementsByTagName("entry");
                for(var i = 0; i < l_entryNodes.length; i++){
                    var l_user = new User(undefined);
                    l_user.createXMLUser(getXMLFirstNode(l_entryNodes[i], "user"));

                    this.m_newUsersDiv.innerHTML += "<a href=\"#\" onClick=\"viewProfile("+l_user.getUserId()+")\"><img src=\""+ l_user.getThumbnailUrl() +"\" width=\"50\" height=\"50\" style=\"border: 2px solid red\"/></a> ";
                }
            } catch (err) {}
        }
	}

	Home.prototype.getInviteFrens = function(){
		this.m_inviteDiv.innerHTML = "Loading Friends...";
        var l_self = this;
        GANGSTERS.VIEWER_NON_BACKED_FRIENDS.getNumUsers(
                function(a_numUsers){
                    l_self.onGetNumUsers(a_numUsers);
                });
	}
	
    Home.prototype.onGetNumUsers = function(a_numUsers){
		
        var l_numFullPages = Math.max(Math.floor(a_numUsers / 40), 1);
        var l_start = Math.min( Math.floor(Math.random() * l_numFullPages), l_numFullPages-1) * 40;

        var l_self = this;
        GANGSTERS.VIEWER_NON_BACKED_FRIENDS.getUsers(l_start, 40, function(a_users){
            l_self.onGetRandomFriends(a_users);
        });
    }

    Home.prototype.onGetRandomFriends = function(a_users){
		
        var l_numQueryUsers = 0;
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        l_params.query_ids = "";
        for(var l_index = 0; l_index < a_users.length && l_numQueryUsers <= 40; l_index++){
            if(isValid(a_users[l_index])){
                l_params.query_ids += a_users[l_index].getUserId() + ",";
                l_numQueryUsers += 1;
            }
        }

        var l_self = this;
        makeRequest("get_app_users_for_invite",
                function(a_responseData){
                        l_self.onGetInviteUsers(a_responseData);
                }, l_params,l_self);
    }

    Home.prototype.onGetInviteUsers = function(a_responseData){

        this.m_inviteUsers = new Array();

        try{
            var l_viewerFriends = GANGSTERS.VIEWER_NON_BACKED_FRIENDS;
            var l_xmlDoc = getResponseData(a_responseData);

            if(l_xmlDoc != undefined){
                var l_invite_ids = l_xmlDoc.getElementsByTagName("invite_id");
                if(isValid(l_invite_ids) && l_invite_ids.length > 0){
                    for(var l_index = 0; l_index < l_invite_ids.length; l_index++){
                        var l_userId = l_invite_ids[l_index].firstChild.nodeValue;
                        this.m_inviteUsers.push(l_viewerFriends.getUserById(l_userId));
                    }
                }
            }
        }catch(err){};

        if(this.m_inviteUsers.length <= 0){
			this.m_inviteDiv.innerHTML = "";
            return;
        }

        var l_self = this;
		
		this.m_inviteDiv.innerHTML = '' +
		'<h1>Allies Recruitment</h1>' +
		'<div class="tips"> A large team of Allies is crutial to be run a powerful Nation and to complete higher level missions. Invite your friends to join your cause, or destroy them if they refuse!</div>';
		
		var l_table = '' +
		'<table align="center">' + 
			'<tr>';
		for(var i=1; i<=3; i++){
			var l_showIndex = Math.min(Math.floor(Math.random() * this.m_inviteUsers.length), this.m_inviteUsers.length-1);
			var l_showUser = this.m_inviteUsers[l_showIndex];
			l_table += '' +
				'<td>' +
					'<table>' +
						'<tr>' +
						'</tr>' +					
						'<tr>' +
							'<td>' +
								'<img src="' + l_showUser.getThumbnailUrl() + '" width="50" height="50" style="border: 2px solid red">' +
							'</td>' +
							'<td>' +
								'<div class="button"><a href="#top" onClick="GANGSTERS.Home.inviteShowUser('+ l_showIndex +')">Invite ' + l_showUser.getShortName() + '</a></div>' +
								'<div class="button"><a href="#top" onClick="GANGSTERS.Home.invite10Friends()">Invite 20 Friends</a></div>' +
								'<div class="button"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(8)">Invite Others</a></div>' +
							'</td>' +
						'</tr>' +
						'<tr>' +
							'<td colspan="2">is not one of your Allies...</td>' +
						'</tr>' +
					'</table>' +
				'</td>';
		}
		l_table += '' +
			'</tr>'+
		'</table>';
		this.m_inviteDiv.innerHTML += l_table;
    }

	Home.prototype.inviteShowUser = function(a_showIndex){
			var l_self = this;
            var l_targetUsers = new Array();
            l_targetUsers.push(this.m_inviteUsers[a_showIndex]);

            l_self.m_sentFriends = new Array();
            l_self.m_failedFriends = new Array();
            l_self.sendInvite(l_targetUsers, 0);
    }
	
	Home.prototype.invite10Friends = function(){
			var l_self = this;
            var l_targetUsers = new Array();
            var l_inviteIndices = getRandomNumbers(this.m_inviteUsers.length-1, 20);
            for(var l_index = 0; l_index < l_inviteIndices.length; l_index++){
                l_targetUsers.push(this.m_inviteUsers[l_inviteIndices[l_index]]);
            }

            l_self.m_sentFriends = new Array();
            l_self.m_failedFriends = new Array();
            l_self.sendInvite(l_targetUsers, 0);
    }
	
    Home.prototype.generateInvite = function(){
        return  GANGSTERS.VIEWER.getName() + " wants you to join their Army in [app], Click \"Add World At War II\" to play! Help your friend out in this great WAR themed application.";
    }

    Home.prototype.sendInvite = function(a_targetUsers, a_currentIndex){
        var l_user = a_targetUsers[a_currentIndex];
        var l_self = this;

        var l_onSentInvite = function(a_postStatus){	
            if(a_postStatus > 0){
				for(var i=0; i<20; i++){
					if(!isValid(a_targetUsers[i]))
						break;
					l_user = a_targetUsers[i];
	                l_user.setRequestedByUser(true);
	                l_self.m_sentFriends.push(l_user);
				}
            }
            l_self.finishSending(); 
        }
        
		var usrArr = new Array();
		for(var i=0; i<20; i++){
			if(!isValid(a_targetUsers[i]))
				break;
			l_user = a_targetUsers[i];
			usrArr.push(l_user.getUserId());
		}
        sendMultipleInvite(usrArr, this.generateInvite(), l_onSentInvite);		
    }

    Home.prototype.finishSending = function(){
        if(this.m_sentFriends.length > 0){
            this.m_resultDiv.innerHTML = "You have sent requests to " + this.m_sentFriends.length + " friends!";
        } else {
            this.m_resultDiv.innerHTML = "You didn't send any invites!";
        }

        var l_sendSuccessUserIdsStr = "";
        for(var l_index = 0; l_index < this.m_sentFriends.length; l_index++){
            if(l_index > 0){
                l_sendSuccessUserIdsStr += ",";
            }
            l_sendSuccessUserIdsStr += this.m_sentFriends[l_index].getUserId();
        }

        var l_failedUserIdsStr = "";
        for(var l_index = 0; l_index < this.m_failedFriends.length; l_index++){
            if(l_index > 0){
                l_failedUserIdsStr += ",";
            }
            l_failedUserIdsStr += this.m_failedFriends[l_index].getUserId();
        }

        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        l_params.to_user_ids = l_sendSuccessUserIdsStr;
        l_params.failed_user_ids = l_failedUserIdsStr;
        var l_self = this;

        makeRequest("send_requests",
                function(a_response){
                    handleResult(a_response, l_self.m_resultDiv, function(){});
                },
                l_params,l_self);
    }
		
	Home.prototype.broadcast = function(){
		var l_self = this;
		var l_commentMsg = document.getElementById('msg');
		if(l_commentMsg.value.length <= 0){
			this.m_resultDiv.innerHTML = "Please type a message.";
			return;
		}
		if(l_commentMsg.value.length > 300){
			this.m_resultDiv.innerHTML = "Sorry, the maximum length limit is 300 characters.";
			return;
		}

		var l_subject = "A message to my Army!";
		var l_body = l_commentMsg.value +
                "<br><br>--------------------------------------------------------<br>" +
                "<a href='"+GANGSTERS.CANVAS_URL+"track=command'>This message sent from: World At War II. Build your own Powerful Nation and conquer the world!</a>";
		postBulletin(GANGSTERS.VIEWER,
						l_subject,
						l_body,
						function(a_status){l_self.onSentBulletin(a_status);});		
    }
	
	Home.prototype.onSentBulletin = function(a_status){	
        if(a_status > 0){
			var l_self = this;
			var l_commentMsg = document.getElementById('msg');
			var l_params = {};
			l_params.user_id = GANGSTERS.VIEWER.getUserId();
			l_params.message = customEncoding(l_commentMsg.value);
			l_params.cost = (100);
			
			makeRequest("broadcast",
						function(a_response){l_self.getNewsFeeds();},
						l_params,l_self);
		}
		else{
            this.m_resultDiv.innerHTML = 'You didn\'t send any message to your Army';
		}
	}
	
	Home.prototype.getNewsFeeds = function(){
		this.m_newsFeedsDiv.innerHTML = "Loading News Feeds...";
        var l_self = this;
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        makeRequest("get_newsfeeds", function(a_responseData){
           l_self.onGetNewsfeeds(a_responseData);
        },l_params,l_self);
	}
	
    Home.prototype.onGetNewsfeeds = function(a_responseData){
		this.m_newsFeedsDiv.innerHTML = '' + 
		'<h1>News Feeds (<a href="#top" onClick="GANGSTERS.Home.deleteAllFeeds()">Delete Feeds</a>)</h1>' +
		'<div id="feedMenu"><a href="#top" onClick="GANGSTERS.Home.showNewsFeed(0)">Message Feeds</a> | <a href="#top" onClick="GANGSTERS.Home.showNewsFeed(1)">Comment Feeds</a> | <a href="#top" onClick="GANGSTERS.Home.showNewsFeed(2)">Attack/Defend Feeds</a> | <a href="#top" onClick="GANGSTERS.Home.showNewsFeed(3)">Threat List/Rewards Feeds</a></div>';
		
		this.m_message_feedDiv = document.createElement("div");
		this.m_message_feedDiv.style.display = "none";
		this.m_message_feedDiv.id = "feedsDiv";
		this.m_comment_feedDiv = document.createElement("div");
		this.m_comment_feedDiv.style.display = "none";
		this.m_comment_feedDiv.id = "feedsDiv";
		this.m_attack_feedDiv = document.createElement("div");
		this.m_attack_feedDiv.style.display = "block";
		this.m_attack_feedDiv.id = "feedsDiv";
		this.m_hitlist_feedDiv = document.createElement("div");
		this.m_hitlist_feedDiv.style.display = "none";
		this.m_hitlist_feedDiv.id = "feedsDiv";
		
		this.m_newsFeedsDiv.appendChild(this.m_message_feedDiv);
		this.m_newsFeedsDiv.appendChild(this.m_comment_feedDiv);
		this.m_newsFeedsDiv.appendChild(this.m_attack_feedDiv);
		this.m_newsFeedsDiv.appendChild(this.m_hitlist_feedDiv);
		
		this.m_newsFeedsDivArr = new Array();
		this.m_newsFeedsDivArr.push(this.m_message_feedDiv);
		this.m_newsFeedsDivArr.push(this.m_comment_feedDiv);
		this.m_newsFeedsDivArr.push(this.m_attack_feedDiv);
		this.m_newsFeedsDivArr.push(this.m_hitlist_feedDiv);
		
        var l_xmlDoc = getResponseData(a_responseData);
        if(isValid(l_xmlDoc)){
            try{
				var id = undefined;
				var timeAgo = undefined;
				var messageHTML = undefined;
				
				var message_feedNodes = getXMLFirstNode(l_xmlDoc,"message_feedNodes");
				var l_entryNodes = message_feedNodes.getElementsByTagName("entry");
				for(var l_index = 0; l_index < l_entryNodes.length; l_index++){
				   try{ id = getXMLNodeValue(l_entryNodes[l_index],"id");}catch(err){};
				   try{ timeAgo = getXMLEncodedStringNodeValue(l_entryNodes[l_index],"time_ago");}catch(err){};
				   try{ messageHTML = getXMLEncodedStringNodeValue(l_entryNodes[l_index],"message_html");}catch(err){};
				   this.m_message_feedDiv.innerHTML += '' +
					'<div class="feeds">' +
						messageHTML + ' <span class="delete">(<a href="#top" onClick="GANGSTERS.Home.deleteFeed(' + id + ')">delete</a>)</span><br />' +
						'<span class="date">Posted ' + timeAgo + '</span>' +
					'</div>';
				}
				
				var comment_feedNodes = getXMLFirstNode(l_xmlDoc,"comment_feedNodes");
				var l_entryNodes = comment_feedNodes.getElementsByTagName("entry");
				for(var l_index = 0; l_index < l_entryNodes.length; l_index++){
				   try{ id = getXMLNodeValue(l_entryNodes[l_index],"id");}catch(err){};
				   try{ timeAgo = getXMLEncodedStringNodeValue(l_entryNodes[l_index],"time_ago");}catch(err){};
				   try{ messageHTML = getXMLEncodedStringNodeValue(l_entryNodes[l_index],"message_html");}catch(err){};
				   this.m_comment_feedDiv.innerHTML += '' +
					'<div class="feeds">' +
						messageHTML + ' <span class="delete">(<a href="#top" onClick="GANGSTERS.Home.deleteFeed(' + id + ')">delete</a>)</span><br />' +
						'<span class="date">Posted ' + timeAgo + '</span>' +
					'</div>';
				}
				
				var attack_feedNodes = getXMLFirstNode(l_xmlDoc,"attack_feedNodes");
				var l_entryNodes = attack_feedNodes.getElementsByTagName("entry");
				for(var l_index = 0; l_index < l_entryNodes.length; l_index++){
				   try{ id = getXMLNodeValue(l_entryNodes[l_index],"id");}catch(err){};
				   try{ timeAgo = getXMLEncodedStringNodeValue(l_entryNodes[l_index],"time_ago");}catch(err){};
				   try{ messageHTML = getXMLEncodedStringNodeValue(l_entryNodes[l_index],"message_html");}catch(err){};
				   this.m_attack_feedDiv.innerHTML += '' +
					'<div class="feeds">' +
						messageHTML + ' <span class="delete">(<a href="#top" onClick="GANGSTERS.Home.deleteFeed(' + id + ')">delete</a>)</span><br />' +
						'<span class="date">Posted ' + timeAgo + '</span>' +
					'</div>';
				}
				
				var hitlist_feedNodes = getXMLFirstNode(l_xmlDoc,"hitlist_feedNodes");
				var l_entryNodes = hitlist_feedNodes.getElementsByTagName("entry");
				for(var l_index = 0; l_index < l_entryNodes.length; l_index++){
				   try{ id = getXMLNodeValue(l_entryNodes[l_index],"id");}catch(err){};
				   try{ timeAgo = getXMLEncodedStringNodeValue(l_entryNodes[l_index],"time_ago");}catch(err){};
				   try{ messageHTML = getXMLEncodedStringNodeValue(l_entryNodes[l_index],"message_html");}catch(err){};
				   this.m_hitlist_feedDiv.innerHTML += '' +
					'<div class="feeds">' +
						messageHTML + ' <span class="delete">(<a href="#top" onClick="GANGSTERS.Home.deleteFeed(' + id + ')">delete</a>)</span><br />' +
						'<span class="date">Posted ' + timeAgo + '</span>' +
					'</div>';
				}
            } catch (err) {}
        }
    }
	
	Home.prototype.showNewsFeed = function(a_index){
		for(var i=0; i<this.m_newsFeedsDivArr.length; i++){
			this.m_newsFeedsDivArr[i].style.display = "none";
		}
		this.m_newsFeedsDivArr[a_index].style.display = "block";
	}
	
	Home.prototype.deleteFeed = function(a_id){
		this.m_resultDiv.innerHTML = "Deleting news feed...";
		var l_self = this;
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.delete_entry_id = a_id;
		makeRequest("delete_newsfeed_entry",
			   function(a_response){l_self.m_resultDiv.innerHTML = ""; l_self.getNewsFeeds();},
			   l_params,l_self);
	}
	
	Home.prototype.deleteAllFeeds = function(){
		this.m_newsFeedsDiv.innerHTML = "Deleting all feeds...";
		var l_self = this;
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		makeRequest("delete_all_newsfeeds",
				function(a_response){l_self.getNewsFeeds();},
				l_params,l_self);
	}

	Home.prototype.getAlliesInfo = function(){
		this.m_resultDiv.innerHTML = "Loading Allies stat...";
		var l_self = this;
		var l_param = {};
        l_param.user_id = GANGSTERS.VIEWER.getUserId();
		makeRequest("get_allies_info",function(a_responseData){l_self.onGetAlliesInfo(a_responseData);},l_param,l_self);
	}
	
	Home.prototype.onGetAlliesInfo = function(a_responseData){
        var l_xmlNode = getResponseData(a_responseData);
		
        if(isValid(l_xmlNode)){
            try{
                var l_northNodes = l_xmlNode.getElementsByTagName("north");
                var l_northPopulation = number_format(getXMLNodeValue(l_northNodes[0], "population"));
                var l_northTotal = getXMLNodeValue(l_northNodes[0], "total");
				
                var l_southNodes = l_xmlNode.getElementsByTagName("south");
                var l_southPopulation = number_format(getXMLNodeValue(l_southNodes[0], "population"));
                var l_southTotal = getXMLNodeValue(l_southNodes[0], "total");

                if(l_northTotal>l_southTotal){
					var msg = 'Northern Alliance is richer than Southern Alliance.';
				}
				else if(l_northTotal<l_southTotal){
					var msg = 'Southern Alliance is richer than Northern Alliance.';
				}
				else
				{
					var msg = 'Northern Alliance and Southern Alliance have equal cash.';
				}
				
				if(isValid(this.m_hasNewRequest))
				{
					var txt = this.m_hasNewRequest;
				}
				else
				{
					var txt ='';
				}
				this.m_resultDiv.innerHTML = txt + "As of the last update, the Northern Alliance Population: <b>" + l_northPopulation + "</b> Vs. Southern Alliance Population: <b>" + l_southPopulation + "</b> (<a href=\"#\" onClick=\"GANGSTERS.menuDiv.navigateToDynamicTab('Alliance_Stat', 'Alliance_Stat')\">More Stats</a>) Currently, the " + msg + " <a href=\"#\" onClick=\"GANGSTERS.menuDiv.navigateToDynamicTab('ChooseSide', 'ChooseSide')\">Have you chosen a side yet?</a> <br /><br /><center>";
				
            } catch (err) {}
        }
		//this.m_resultDiv.innerHTML += '<br/><h2>Current Updates</h2> - We are in the process of making updates. Please check the <b>NEWS UPDATE</b> tab for more info. <br />- What are Respect Points? You can receive respect points by killing members on an enemies tree. Respect points will be tradeable for cool gear, real soon! So help us out and start testing the Respect points system!';
	}	

    Home.prototype.getPromoItem = function() {		
		var l_self = this;
		var l_param = {};
		this.m_promoDiv.innerHTML = "Loading Offers...";
        l_param.invite_count = Math.ceil((GANGSTERS.VIEWER.getInviteCount()+1) / 20) * 20;
		makeRequest("get_promo_item",
				function(a_responseData){l_self.onGetPromoItem(a_responseData);},
				l_param,l_self);
	}
	
    Home.prototype.onGetPromoItem = function(a_responseData){
        var l_xmlNode = getResponseData(a_responseData);
		this.m_promoDiv.innerHTML = "";
        if(isValid(l_xmlNode)){
            try{
                var l_promoNode = l_xmlNode.getElementsByTagName("promo");
                var l_weapon = getXMLEncodedStringNodeValue(l_promoNode[0],"title");
                var l_url = getXMLEncodedStringNodeValue(l_promoNode[0],"image_url");
                var l_invite_count = number_format(getXMLNodeValue(l_promoNode[0], "invite_count"));
                var l_attack = number_format(getXMLNodeValue(l_promoNode[0], "attack"));
                var l_defense = number_format(getXMLNodeValue(l_promoNode[0], "defense"));
                var l_upkeep = number_format(getXMLNodeValue(l_promoNode[0], "upkeep"));
				
				l_invite_count -= GANGSTERS.VIEWER.getInviteCount();
				var l_table = '<h2>Bonus Offers</h2>' +
				'<table class="category" style="border: 1px solid red">' +
					'<tr>' +
						'<td width="15%">' +
							'<img src="' + l_url + ' "/>' +
						'</td>' +
						'<td width="15%" style="font-size:10pt; text-align: left;">' +
							'Attack: &nbsp;  '  + l_attack + '<br/>' + 
							'Defense: ' + l_defense + '<br/>' + 
							'Upkeep:  &nbsp;'  + l_upkeep +
						'</td>' +
						'<td width="70%" style="font-size:10pt; text-align: left;">Foreign Aid offers you 1 ' + l_weapon + ' for free. However, you can claim it after inviting ' + l_invite_count + ' friends by <a href="#" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Ask\',\'Ask\')">sending invites</a>. Feel free to accept this offer if you like...' +
						'</td>' +
					'</tr>' +
				'</table>';

				//this.m_promoDiv.id = "resultDiv";
				this.m_promoDiv.innerHTML = l_table;
            } catch (err) {}
        }
    }
	
//end Home


function init(){
    //set height of app
    gadgets.window.adjustHeight(5000);
	
	//Get parameters
    var l_params = gadgets.views.getParams();
	
    try{
        GANGSTERS.app_install_state = l_params["installState"];
		
		if(GANGSTERS.app_install_state == undefined)
		{
			GANGSTERS.app_install_state = GANGSTERS.APP_INSTALLED;
        }
    } catch(err){
        GANGSTERS.app_install_state = GANGSTERS.APP_INSTALLED;
    }

    main();
}

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

function isValidFunction(a_obj){
        return isValid(a_obj) && (typeof(a_obj) == 'function');
    }
	
	
function main(){
    
	this.onLoadUser = onLoadUser;
	this.onLoggedIn = onLoggedIn;
	
    if(GANGSTERS.app_install_state == GANGSTERS.APP_NOT_INSTALLED){
	    var l_arrowImg = document.createElement("img");
	    document.body.appendChild(l_arrowImg);
	    l_arrowImg.src = "http://i149.photobucket.com/albums/s48/glittervault2/arrow-1.gif";
	    l_arrowImg.style.position = "absolute";
	    l_arrowImg.style.top = "0px";
	    l_arrowImg.style.left = "345px";
	    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 = "#FF0000";
	    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.color = "#FFFFFF";
	    l_msgDiv.style.top = "110px";
	    l_msgDiv.style.left = "190px";
	    l_msgDiv.style.zIndex = 0;
	    l_msgDiv.innerHTML = "You must add this application to continue!";
    } else {
	    GANGSTERS.mainDiv = document.getElementById("mainDiv");
	    GANGSTERS.mainDiv.innerHTML = GANGSTERS.MYSPACE_WAITING_MSG;		

        var request = opensocial.newDataRequest();

        var param = {};
        param[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
                   [opensocial.Person.Field.ID,
                    opensocial.Person.Field.NAME,
                    opensocial.Person.Field.THUMBNAIL_URL,
					opensocial.Person.Field.PROFILE_URL];

        request.add(request.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER, param), 'owner');
        request.add(request.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER, param), 'viewer');
        request.send(onLoadUser);
    }
	
	function onLoadUser(dataResponse) {
	
        try {
            var ownerData = dataResponse.get('owner').getData();
            GANGSTERS.OWNER = new User(ownerData);
        }  catch (err) {
            GANGSTERS.OWNER = null;
        }

        try {
            var viewerData = dataResponse.get('viewer').getData();
            GANGSTERS.VIEWER = new User(viewerData);
            GANGSTERS.mainDiv.innerHTML = GANGSTERS.LOADING_MSG;
            GANGSTERS.VIEWER.signIn(onLoggedIn);

        }  catch (err) {
            GANGSTERS.VIEWER = null;
        }
    }
	
	function onLoggedIn(a_response){
        var l_responseXML = undefined;
        try{
            l_responseXML = getResponseData(a_response);
        }catch(err){};

        if(!isValid(l_responseXML)){
            GANGSTERS.mainDiv.innerHTML = GANGSTERS.APP_ERROR_MSG;
            return;
        }

        GANGSTERS.VIEWER_FRIENDS = new UsersCache(GANGSTERS.MY_FRIENDS);
        GANGSTERS.VIEWER_NON_BACKED_FRIENDS = new UsersCache(GANGSTERS.NON_BACKED_FRIENDS);

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

        GANGSTERS.VIEWER_REQUESTS = new UsersCache(GANGSTERS.MY_REQUESTS);
        GANGSTERS.VIEWER_GANG = new UsersCache(GANGSTERS.MY_GANG);
        GANGSTERS.NEW_GANGSTERS = new UsersCache(GANGSTERS.NEW_USERS);
        GANGSTERS.GANG_MEMBERS = new UsersCache(GANGSTERS.MY_GANG_MEMBERS);		
        
        createUI();
    }
}

function makeRequest(url, callback, params, obj){
	if(GANGSTERS.APP_DOWN_FOR_MAINTENANCE == true){
        GANGSTERS.mainDiv.innerHTML = GANGSTERS.APP_DOWN_MSG;
		return;
	}
	
	if(isValid(params)){
		var l_param_str = "";
		for(var l_id in params){
				l_param_str += l_id + "=" + params[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);
		}
		var l_request_url = GANGSTERS.BASE_URL + '/index.php?action=' + url + '&' + l_param_str;
		
		var l_ts = new Date().getTime();
		l_request_url += "&nocache=" + l_ts;

		params['METHOD'] = 'GET';
		params['CONTENT_TYPE'] = gadgets.io.ContentType.DOM;
		params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;

		gadgets.io.makeRequest(l_request_url, 
			function(a_response){
				if(isValid(a_response.data) || isValid(a_response.text)){
					callback(a_response);
				}
				else{
					if(!isValid(obj)){
						GANGSTERS.mainDiv.innerHTML = GANGSTERS.ERROR_MSG;
					}
					else if(isValid(obj.m_resultDiv)){
						obj.m_resultDiv.innerHTML = GANGSTERS.MYSPACE_ERROR_MSG;
					}
					else{
						GANGSTERS.mainDiv.innerHTML = GANGSTERS.ERROR_MSG;
					}
				}
			}
			, params);
	}
}

function makeElement(a_tag, a_parent, a_style) {
    var l_result = document.createElement(a_tag);
    a_parent.appendChild(l_result);
    return setStyle(l_result, a_style);
}

// ManageGang
    function ManageGang(a_parentDiv, a_type){
		this.m_parentDiv = a_parentDiv;
		
		this.m_menuDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_menuDiv);
		this.m_menuDiv.innerHTML = '' +
		'<div id="feedMenu"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(8)">Invite Friends</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ManageGang\',\'ManageGang\')">Manage Allies</a> | <a href="#top" onClick="showFamilyTree()">War Cabinet</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'ChooseSide\',\'ChooseSide\')">Choose a side</a></div>';
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_contentDiv);
		
		this.refresh();
    }
	
	ManageGang.prototype.refresh = function(){
        var l_self = this;
		this.m_resultDiv.innerHTML = "";
        this.m_contentDiv.innerHTML = "Loading...";
        GANGSTERS.VIEWER_GANG.getNumUsers(function(a_numUsers){l_self.onGottenNumUsers(a_numUsers);});
	}
	
    ManageGang.prototype.onGottenNumUsers = function(a_numUsers){
        this.m_contentDiv.innerHTML = "<h1>Your Allies: (" + (GANGSTERS.VIEWER.getGangSize() - a_numUsers - 1) + " Bought Allies)</h1>";
		
        var l_self = this;
        new UserTableParentDiv( this.m_contentDiv, GANGSTERS.VIEWER_GANG, 5, 40,
                                function(a_user){return l_self.canRemoveTdCreater(a_user);}, 
                                "You have no Allies! The more Allies you have the stronger you are, so you should <a href='#top' onclick='GANGSTERS.menuDiv.navigateTo(8)'>invite some friends</a> to be part of your Allied strike force!");
    }

    ManageGang.prototype.canRemoveTdCreater = function(a_user){
        var l_td = document.createElement("td");
		l_td.className = "userTableTd";		
		l_td.innerHTML ='<a href="#top" onClick="viewProfile('+a_user.getUserId()+')"<img src="'+a_user.getThumbnailUrl()+'" border="0" width="60" height="60" /><br/>'+a_user.getGangName()+'</a>' +
		'<div style="color:red; cursor:pointer" onClick="GANGSTERS.ManageGang.removeUser('+a_user.getUserId()+')">[X] Remove</div>';
		
        return l_td;
    }
	
	ManageGang.prototype.removeUser = function(a_userId){
        var l_self = this;
		l_self.m_resultDiv.innerHTML = "Removing ... ";
		goToPageTop();

		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.remove_user_id = a_userId;
		makeRequest("remove_gang_member",
			function(a_response){
				GANGSTERS.VIEWER_GANG.invalidateCache();
				handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();});
			},
			l_params,l_self);
	}
// end ManageGang

//Medic
	function Medic(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);
		
		this.refresh();
	}
	
	Medic.prototype.refresh = function(){
        var l_cost = GANGSTERS.VIEWER.getLevel() * 250;
        if(GANGSTERS.VIEWER.getHealth() >= 0.67 * GANGSTERS.VIEWER.getMaxHealth()){
            this.m_infoDiv.innerHTML = "You are at Full Health!";
            return;
        }
		
		this.m_infoDiv.innerHTML = '' +
		'<div id="newUsers">' +
			'<h1>Medic Center</h1>' +
			'<div class="tips">' +
				'The Medic Center will heal the injured soldiers in your Army after attacks and increase their health attribute. A maintenance fee is required for each visit.' +
			'</div>' +
			'<div class="general">' +
				'<div class="button"> <a href="#top" onClick="GANGSTERS.Medic.heal()">Heal Soldiers</a></div>' +
			    '<br />' +
				'<br />' +
			'</div>' +
		'</div>'; 
	}
	
	Medic.prototype.heal = function(){
        var l_self = this;
		this.m_resultDiv.innerHTML = "Healing ... ";

		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.level = GANGSTERS.VIEWER.getLevel();
		makeRequest("heal",
			function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
			l_params,l_self);
	}	
//end Medic

function MemberTreeTableParentDiv(a_parentDiv, a_userList, a_numPerRow, a_numPerPage, a_userTdCreater, a_emptyMessage, a_dragDropObj){

    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_dropContentDiv = undefined;
	var m_dragDropObj = a_dragDropObj;
	
    var m_numUsers = undefined;
    var m_currentPage = undefined;

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

    function createDiv(_a_parentDiv){

        m_parentDiv = _a_parentDiv;

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

        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_containerDiv.innerHTML = m_emptyMessage;
            }

            return;
        }

        jumpToPage(1);
    }

    function jumpToPage(a_pageNum){
        m_currentPage = a_pageNum;
		m_containerDiv.innerHTML = "";
		
        createPageNumbersDiv(m_containerDiv);
		
        m_dropContentDiv = document.createElement("div");
		m_dropContentDiv.id = "dropContent";
        m_containerDiv.appendChild(m_dropContentDiv);
        m_dropContentDiv.style.textAlign = "center";
        m_dropContentDiv.style.color = "#FFFFFF";
   
        new MemberTreeListTableDiv(m_dropContentDiv, m_userList, m_currentPage, m_numPerRow, m_numPerPage, m_userTdCreater, m_dragDropObj);
        createPageNumbersDiv(m_containerDiv);
    }

    function createPageNumbersDiv(a_parentDiv, a_maxNumLinksPerPage){
        var l_numPages = Math.ceil(m_numUsers / m_numPerPage);
        new PaginationDiv(a_parentDiv, jumpToPage, l_numPages, m_currentPage, 7);
    }
}

function MemberTreeListTableDiv(a_parentDiv, a_userList, a_startPage, a_numPerRow, a_numUsersPerPage, a_userTdCreater, a_dragDropObj){

    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_dragDropObj = a_dragDropObj;

    var m_dropContentDiv = 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;

        m_parentDiv.style.textAlign = "center";
        m_parentDiv.innerHTML = "<br><font color='white'><b>[Loading Users... Please wait.]</b></font>";

        // start and num
        m_userList.getUsers(m_startIndex, m_numUsersPerPage, onGetUsers);
    }

    function onGetUsers(a_userArray){
        m_parentDiv.innerHTML = "";
		var l_div = undefined;
        var l_endsIndex = Math.min(a_userArray.length, m_startIndex + m_numUsersPerPage);

        for(var l_userIndex = m_startIndex; l_userIndex < l_endsIndex; l_userIndex++){
			
	        l_div = document.createElement("div");
			l_div.className = "dragableBox";
			l_div.id = "box" + a_userArray[l_userIndex].getUserId();
			l_div.innerHTML = '<img src="'+a_userArray[l_userIndex].getThumbnailUrl()+'" height="50" width="50" />';
            m_parentDiv.appendChild(l_div);
			m_dragDropObj.addSource(l_div.id,true);	// Make <div id="box1"> dragable. slide item back into original position after drop
			m_dragDropObj.init();	// Initizlizing drag and drop object
        }
    }
}

//MenuDiv
	function MenuDiv(a_parentDiv,a_menu,a_contentDiv){
		this.m_contentDiv = a_contentDiv;
		this.m_parentDiv = a_parentDiv;
		this.m_menu = a_menu;
		this.m_selectedMenu = 0;
		this.m_menuCategoryArr = new Array();
		this.m_containerDivArr = new Array();
		this.m_isLoadedArr = new Array();
		this.createMenu();
		this.navigateTo(this.m_selectedMenu);
		
	}

	MenuDiv.prototype.createMenu = function(){
		for(var i=0; i<this.m_menu.length; i++){
			this.m_parentDiv.innerHTML += '<a href="#top" onClick="GANGSTERS.menuDiv.navigateTo('+ i +')">' + this.m_menu[i] + '</a>';
			if(i<this.m_menu.length-1){
				this.m_parentDiv.innerHTML += ' | ';
			}
			var l_containerDiv = document.createElement("div");
			l_containerDiv.id = "containerDiv";
			this.m_menuCategoryArr.push(undefined);
			this.m_containerDivArr.push(l_containerDiv);
			this.m_contentDiv.appendChild(l_containerDiv);
			this.m_isLoadedArr.push(false);
		}
	}
	
	MenuDiv.prototype.navigateTo = function(a_index){
		this.m_selectedMenu = a_index;
		for(var i=0; i<this.m_menu.length; i++){
				this.m_containerDivArr[i].style.display = "none";
		}
		this.m_containerDivArr[this.m_selectedMenu].style.display = "block";
		var l_callback = this.m_menu[this.m_selectedMenu].replace(' ','_');
		if(this.m_isLoadedArr[this.m_selectedMenu] == false){
			this.m_isLoadedArr[this.m_selectedMenu] = true;
			this.m_containerDivArr[this.m_selectedMenu].innerHTML = "";
			if(isValid(this.m_menuCategoryArr[this.m_selectedMenu])){
				eval ("GANGSTERS."+l_callback+" = new " + this.m_menuCategoryArr[this.m_selectedMenu] + "(this.m_containerDivArr[this.m_selectedMenu], l_callback);");
			}
			else{
				eval ("GANGSTERS."+l_callback+" = new " + l_callback + "(this.m_containerDivArr[this.m_selectedMenu]);");
			}
		}
	}
	
	MenuDiv.prototype.refresh = function(){
		this.m_isLoadedArr[this.m_selectedMenu] = false;
		this.navigateTo(this.m_selectedMenu);
	}
	
	MenuDiv.prototype.invalidate = function(){
		this.m_isLoadedArr[this.m_selectedMenu] = false;
	}
	
	MenuDiv.prototype.navigateToDynamicTab = function(a_menu, a_category){
		var l_isExists = false;
		var l_index = 0;
		for(var i=0; i<this.m_menu.length; i++){
			if(this.m_menu[i] == a_category){
				l_isExists = true;
				l_index = i;
				break;
			}
		}
		if(!l_isExists){
			this.m_menu.push(a_category);
			this.m_menuCategoryArr.push(a_menu);
			var l_containerDiv = document.createElement("div");
			l_containerDiv.id = "containerDiv";
			this.m_containerDivArr.push(l_containerDiv);
			this.m_contentDiv.appendChild(l_containerDiv);
			this.m_isLoadedArr.push(false);
			l_index = this.m_menu.length - 1;
		}
		this.navigateTo(l_index);
	}
//end MenuDiv

//Missions
	function Missions(a_parentDiv){
		this.m_parentDiv = a_parentDiv;

		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.className = "categoryTableTitle";
		this.m_parentDiv.appendChild(this.m_contentDiv);
		
		this.m_infoDiv.innerHTML = '' +
		'<div id="newUsers">' +
			'<h1>Missions</h1>' +
			'<div class="tips">' +
				'Complete missions to obtain the necessary funds to increase your wealth. Use your wealth to build a powerful army and conquer all Nations that stand in your way!<br/><br />' +
				'Some Missions require Allies to be completed. If you need more Allies for completing higher level missions for more money, why not try inviting some of your trusted friends, <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(8)">Click here</a> to get started now.' +
			'</div>' +
		'</div>';
		
		this.getJobList();
	}
	
    Missions.prototype.getJobList = function(){

        this.m_contentDiv.innerHTML = "Loading Jobs...";
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        l_params.level = GANGSTERS.VIEWER.getLevel();
        
        var l_self = this;
        makeRequest("get_job_list", function(a_responseData){
           l_self.onGetJobList(a_responseData);
        },l_params,l_self);
    }

    Missions.prototype.onGetJobList = function(a_responseData){
        var l_xmlDoc = getResponseData(a_responseData);
		var l_table = '';
		
        if(isValid(l_xmlDoc)){
            try{
				l_table = '<div style="height:4000px;overflow:auto">' +
						'<table align="center">' +
							'<tr>' +
								'<th>Description</th>' +
								'<th>Items Required</th>' +
								'<th>Rewards</th>' +
								'<th>Execute!</th>' +
							'</tr>';

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

					l_table += '<tr>';
					
			        try{ 
						var l_jobId = getXMLNodeValue(l_jobNodes[l_index],"id");
					}catch(err){};
					
			        try{ 
						var l_title = getXMLEncodedStringNodeValue(l_jobNodes[l_index],"title");
						
						l_table += '<td width="20%"><span class="description">' + l_title + '</span></td>';
					}catch(err){};
					
			        try{ 
						var l_requirementNode = getXMLFirstNode(l_jobNodes[l_index],"requirement");

						l_table += '<td width="45%">';
						
				        try{
				            var l_itemNodes = l_requirementNode.getElementsByTagName("item");
				            if(isValid(l_itemNodes) && l_itemNodes.length > 0){
				                for(var i = 0; i < l_itemNodes.length; i++){
				                    l_number = getXMLNodeValue(l_itemNodes[i], "number");
				                    l_image_url = getXMLEncodedStringNodeValue(l_itemNodes[i], "image_url");
									
									l_table += '<img src="'+l_image_url+'" /> x '+ l_number;
				                }
				            }
				        } catch(err){};
						
						l_table += '<span class="gangReq">';
						
				        try{ 
							var l_gangster = getXMLNodeValue(l_requirementNode,"gangster");
							if(l_gangster > 0){
								l_table += 'Allies: ' + l_gangster + ' / ';
							}
						}catch(err){};
						
				        try{ 
							var l_adrenaline = getXMLNodeValue(l_requirementNode,"adrenaline");
							if(l_adrenaline > 0){
								l_table += 'Courage: ' + l_adrenaline;
							}
						}catch(err){};

				        try{ 
							var l_cash = getXMLNodeValue(l_requirementNode,"cash");
							if(l_cash > 0){
								l_table += ' / Cash: $' + number_format(l_cash);
							}
						}catch(err){};
						
				        try{ 
							var l_bullet = getXMLNodeValue(l_requirementNode,"bullet");
							if(l_bullet > 0){
								l_table += ' / Supplies used: ' + number_format(l_bullet);
							}
						}catch(err){};
						
						l_table +='</span></td>';
						
					}catch(err){};
					
			        try{ 
						var l_rewardNode = getXMLFirstNode(l_jobNodes[l_index],"reward");
						var l_min = getXMLNodeValue(l_rewardNode,"min");
						var l_max = getXMLNodeValue(l_rewardNode,"max");
						var l_exp = getXMLNodeValue(l_rewardNode,"experience");
						
						l_table += '<td><span class="money">$' + number_format(l_min) + '-$' + number_format(l_max) + '</span> <br /> Experience: <span class="experience">+' + number_format(l_exp) + '</span> </td>';
				    }catch(err){};
					
						l_table += '<td><input type="submit" value="Do Job!" onClick="GANGSTERS.Missions.doJob('+l_jobId+')"></td>';
					l_table += '</tr>';
                }
				
				l_table += '</table>';
				
                var l_nextLevel = getXMLNodeValue(l_xmlDoc, "next_level");
                if(isValid(l_nextLevel)){
					l_table += '<div class="levelMsg">Unlock more missions when you reach ' + l_nextLevel + ' ...</div></div>';
                }

            } catch (err) {}
        }
		
		this.m_contentDiv.innerHTML = l_table;
    }
	
	Missions.prototype.doJob = function(a_jobId){
		goToPageTop();
		
		var l_self = this;
		this.m_resultDiv.innerHTML = "Attempting Mission...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.job_id = a_jobId;
		makeRequest("do_job",
				function(a_response){
					handleResult(a_response, l_self.m_resultDiv, function(){});},
				l_params,l_self);
	}
//end Missions


//NewsUpdate
    function NewsUpdate(a_parentDiv, a_type){
				
		this.m_parentDiv = a_parentDiv;
		this.m_appNewsDiv = document.createElement("div");
		this.m_appNewsDiv.id = "newsDiv";
		this.m_parentDiv.appendChild(this.m_appNewsDiv);
		this.m_appNewsDiv.innerHTML = '<h1>NEWS UPDATES</h1>' +
				'<div style="text-align:left; margin-left:10px">' +


'<p><b>4/15/2009</b> Gold trading is temporarily offline because e-gold.com is down for maintenance. e-gold.com is the server we use to return daily gold prices. Once e-gold.com goes back online, your gold amounts and gold trading will work as normal.</p>'+
				  				    '<p><b>2/26/2009</b>: :::ATTENTION::: Everyone was given 3 days of income (72 hours) for the downtime for waw1 and waw2. It was deposited in your bank so happy spending!</p>' +

				  '02/26/09: Many are not pleased with the missing income for the days the app was down. We will try to give you back those hours of missing income as soon as we can. Check back here for an annoucement.<br /><br />' +
				  '02/26/09: Dear Users, I apologize for the 2 day downtime for World At War II. We had to take down the app for some emergency bug fixes and did not have time to issue notice. The app is currently back up and should it go down again, please check the app profile by clicking the "more info" link above for an updated status. Thank you for playing and I am sorry if I did not get a chance to reply to all the messages in my myspace inbox during this crisis. We are working on a support ticket system to provide you with better communications  with us! Thank you once again for playing. '+
				'</div>';
	}
//end NewsUpdate

function number_format(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 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;

	var adjacents = 2;
	
	/* Setup page vars for display. */
	var prev = m_currentPage - 1;                            //previous page is page - 1
	var next = m_currentPage + 1;                            //next page is page + 1
	var lastpage = m_numPages;        //lastpage is = total pages / items per page, rounded up.
	var lpm1 = lastpage - 1;                        //last page minus 1
	
	m_pageNumDiv = document.createElement('div');
	//m_pageNumDiv.style.textAlign = "center";
	m_pageNumDiv.className = "pagination";
	m_parentDiv.appendChild(m_pageNumDiv);
	
	/* 
		Now we apply our rules and draw the pagination object. 
		We're actually saving the code to a variable in case we want to draw it more than once.
	*/
					
	if(lastpage > 1){
		if(m_currentPage){
			//anterior button
			if(m_currentPage > 1){
				var l_prevA = document.createElement("a");
				l_prevA.className = "prev";
				l_prevA.href = "#";
				//l_prevA.appendChild(document.createTextNode("<<Previous"));
				l_prevA.innerHTML = "Previous";
				m_pageNumDiv.appendChild(l_prevA);
		
				addEventWithParameter(l_prevA, "click", m_pageCallback, prev);
			}
			else{
				var l_prevA = document.createElement("span");
				l_prevA.className = "disabled";
				l_prevA.innerHTML = "Previous";
				m_pageNumDiv.appendChild(l_prevA);				
			}
		}
		//pages	
		if (lastpage < 7 + (adjacents * 2)){//not enough pages to bother breaking it up
			for (counter = 1; counter <= lastpage; counter++){
				if (counter == m_currentPage){
					var l_curr = document.createElement("span");
					l_curr.className = "current";
					l_curr.innerHTML = counter;
					m_pageNumDiv.appendChild(l_curr);
				}
				else{
					var l_curr = document.createElement("a");
					l_curr.href = "#";
					l_curr.innerHTML = counter;
					m_pageNumDiv.appendChild(l_curr);
			
					addEventWithParameter(l_curr, "click", m_pageCallback, counter);
				}
			}
		}
		else if(lastpage > 5 + (adjacents * 2)){//enough pages to hide some
			//close to beginning; only hide later pages
			if(m_currentPage < 1 + (adjacents * 2)){
				for (counter = 1; counter < 4 + (adjacents * 2); counter++){
					if (counter == m_currentPage){
						var l_curr = document.createElement("span");
						l_curr.className = "current";
						l_curr.innerHTML = counter;
						m_pageNumDiv.appendChild(l_curr);
					}
					else{
						var l_curr = document.createElement("a");
						l_curr.href = "#";
						l_curr.innerHTML = counter;
						m_pageNumDiv.appendChild(l_curr);
				
						addEventWithParameter(l_curr, "click", m_pageCallback, counter);
					}
				}				
				
				var l_sep = document.createElement("span");
				l_sep.innerHTML = "...";
				m_pageNumDiv.appendChild(l_sep);
				
				var l_curr = document.createElement("a");
				l_curr.href = "#";
				l_curr.innerHTML = lpm1;
				m_pageNumDiv.appendChild(l_curr);

				addEventWithParameter(l_curr, "click", m_pageCallback, lpm1);

				var l_curr = document.createElement("a");
				l_curr.href = "#";
				l_curr.innerHTML = lastpage;
				m_pageNumDiv.appendChild(l_curr);
		
				addEventWithParameter(l_curr, "click", m_pageCallback, lastpage);					
			}
			//in middle; hide some front and some back
			else if(lastpage - (adjacents * 2) > m_currentPage && m_currentPage > (adjacents * 2)){
				var l_curr = document.createElement("a");
				l_curr.href = "#";
				l_curr.innerHTML = "1";
				m_pageNumDiv.appendChild(l_curr);
		
				addEventWithParameter(l_curr, "click", m_pageCallback, 1);
				
				var l_curr = document.createElement("a");
				l_curr.href = "#";
				l_curr.innerHTML = "2";
				m_pageNumDiv.appendChild(l_curr);
		
				addEventWithParameter(l_curr, "click", m_pageCallback, 2);
				
				
				var l_sep = document.createElement("span");
				l_sep.innerHTML = "...";
				m_pageNumDiv.appendChild(l_sep);
				
				for (counter = m_currentPage - adjacents; counter <= m_currentPage + adjacents; counter++){
					if (counter == m_currentPage){
						var l_curr = document.createElement("span");
						l_curr.className = "current";
						l_curr.innerHTML = counter;
						m_pageNumDiv.appendChild(l_curr);
					}
					else{
						var l_curr = document.createElement("a");
						l_curr.href = "#";
						l_curr.innerHTML = counter;
						m_pageNumDiv.appendChild(l_curr);
				
						addEventWithParameter(l_curr, "click", m_pageCallback, counter);
					}
				}
				
				var l_sep = document.createElement("span");
				l_sep.innerHTML = "...";
				m_pageNumDiv.appendChild(l_sep);
				
				var l_curr = document.createElement("a");
				l_curr.href = "#";
				l_curr.innerHTML = lpm1;
				m_pageNumDiv.appendChild(l_curr);

				addEventWithParameter(l_curr, "click", m_pageCallback, lpm1);

				var l_curr = document.createElement("a");
				l_curr.href = "#";
				l_curr.innerHTML = lastpage;
				m_pageNumDiv.appendChild(l_curr);
		
				addEventWithParameter(l_curr, "click", m_pageCallback, lastpage);
			}
			//close to end; only hide early pages
			else{
				var l_curr = document.createElement("a");
				l_curr.href = "#";
				l_curr.innerHTML = "1";
				m_pageNumDiv.appendChild(l_curr);
		
				addEventWithParameter(l_curr, "click", m_pageCallback, 1);
				
				var l_curr = document.createElement("a");
				l_curr.href = "#";
				l_curr.innerHTML = "2";
				m_pageNumDiv.appendChild(l_curr);
		
				addEventWithParameter(l_curr, "click", m_pageCallback, 2);
				
				
				var l_sep = document.createElement("span");
				l_sep.innerHTML = "...";
				m_pageNumDiv.appendChild(l_sep);
				
				for (counter = lastpage - (2 + (adjacents * 2)); counter <= lastpage; counter++){
					if (counter == m_currentPage){
						var l_curr = document.createElement("span");
						l_curr.className = "current";
						l_curr.innerHTML = counter;
						m_pageNumDiv.appendChild(l_curr);
					}
					else{
						var l_curr = document.createElement("a");
						l_curr.href = "#";
						l_curr.innerHTML = counter;
						m_pageNumDiv.appendChild(l_curr);
				
						addEventWithParameter(l_curr, "click", m_pageCallback, counter);									
					}
				}
			}
		}
		if(m_currentPage){
			//siguiente button
			if (m_currentPage < counter - 1){
					var l_nextA = document.createElement("a");
					l_nextA.href = "#";
					l_nextA.className = "next";					
					l_nextA.innerHTML = "Next";
					m_pageNumDiv.appendChild(l_nextA);
			
					addEventWithParameter(l_nextA, "click", m_pageCallback, next);							
			}
			else{
				var l_nextA = document.createElement("span");
				l_nextA.className = "disabled";
				l_nextA.innerHTML = "Next";
				m_pageNumDiv.appendChild(l_nextA);
			}
		}
	}
}

function postBulletin(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();
    GANGSTERS.OS_CONTAINER.postTo(GANGSTERS.OS_TOKEN, l_message, a_targetUser, a_postToCallback);
}

// Profile
    function Profile(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);				
		
		this.m_profileTable = document.createElement("table");
		this.m_profileTable.className = "profileTable";
		this.m_parentDiv.appendChild(this.m_profileTable);
		
		this.m_tbody = document.createElement("tbody");
		this.m_profileTable.appendChild(this.m_tbody);
		
		this.m_profileTableTr = document.createElement("tr");
		this.m_tbody.appendChild(this.m_profileTableTr);
		
		this.m_profileTableLeftTd = document.createElement("td");
		this.m_profileTableTr.appendChild(this.m_profileTableLeftTd);
		this.m_profileTableLeftTd.style.width = "500px";
		
		this.m_profileTableRightTd = document.createElement("td");
		this.m_profileTableTr.appendChild(this.m_profileTableRightTd);
		this.m_profileTableRightTd.style.width = "50%";
		
		this.m_treeDiv = document.createElement("div");
		this.m_treeDiv.className = "treeDiv";
		this.m_profileTableLeftTd.appendChild(this.m_treeDiv);
		
		this.m_commentDiv = document.createElement("div");
		this.m_profileTableLeftTd.appendChild(this.m_commentDiv);		
		
	    if(isValid(getOSparam(GANGSTERS.SHOW_USER_ID)) && !isValid(GANGSTERS.user_id)){	            
			this.m_targetId = getOSparam(GANGSTERS.SHOW_USER_ID);
			GANGSTERS.user_id = GANGSTERS.VIEWER.getUserId();
			GANGSTERS.menuDiv.invalidate();
	    }
		else{
			this.m_targetId = GANGSTERS.VIEWER.getUserId();
		}

		this.getProfile();
		this.getFamilyTree();
		this.getComments();
    }

    Profile.prototype.getProfile = function(){

        this.m_resultDiv.innerHTML = "Loading ...";
        var l_params = {};
		
		l_params.target_id = this.m_targetId;

        l_params.user_id = GANGSTERS.VIEWER.getUserId();

        var l_self = this;
        makeRequest("get_profile", function(a_responseData){
           l_self.onGetProfile(a_responseData);
        },l_params,l_self);
    }

    Profile.prototype.onGetProfile = function(a_responseData){
        this.m_resultDiv.innerHTML = "";
				
        var l_xmlDoc = getResponseData(a_responseData);
		var l_table = '';
		
        if(isValid(l_xmlDoc)){
            try{
				var l_targetNode = getXMLFirstNode(l_xmlDoc, "user");
				var l_targetUser = new User(undefined);
				l_targetUser.createXMLUser(l_targetNode);
				this.m_infoDiv.innerHTML = '' +
				'<div id="userProfile">' +
					'<table>' +
						'<tr>' +
							'<td width="10%"><a href="'+l_targetUser.getProfileUrl()+'" target="_blank"><img src="'+l_targetUser.getThumbnailUrl()+'" width="70px" height="70px" border="0"></a></td>' +
							'<td>' +
							'<div class="profileInfo">Name: '+l_targetUser.getGangName()+'</div>' +
							'<div class="profileInfo">Style: '+l_targetUser.getGangClass()+'</div>' +
							'<div class="profileInfo">Level: '+l_targetUser.getLevel()+'</div>' +
							'<div class="profileInfo">Alliance: '+l_targetUser.getSide()+'</div>' +
							'<div><a href="http://friends.myspace.com/index.cfm?fuseaction=invite.addfriend_verify&friendID='+l_targetUser.getUserId()+'" target="_blank"><img src="http://x.myspace.com/images/profile/friend_1.gif" border="0"/></a></div>' +
							'</td>' +
						'</tr>' +
					'</table>' +
				'</div>';
			}catch(err){}

			try{
				var l_statsNode = getXMLFirstNode(l_xmlDoc, "stat");
				var l_jobs_completed = getXMLNodeValue(l_statsNode,"jobs_completed");
				var l_jailed = getXMLNodeValue(l_statsNode,"jailed");
				var l_escaped_count = getXMLNodeValue(l_statsNode,"escaped_count");
				var l_escaped = getXMLNodeValue(l_statsNode,"escaped");
				var l_bounty_kills = getXMLNodeValue(l_statsNode,"bounty_kills");
				var l_fights_won = getXMLNodeValue(l_statsNode,"fights_won");
				var l_fights_lost = getXMLNodeValue(l_statsNode,"fights_lost");
				var l_death_count = getXMLNodeValue(l_statsNode,"death_count");
				var l_kill_count = getXMLNodeValue(l_statsNode,"kill_count");
				var l_respect_points = getXMLNodeValue(l_statsNode,"respect_points");
				
				var gold_per_ounce = parseFloat(getXMLNodeValue(l_xmlDoc, "gold_per_ounce"));
	
				var l_gold = l_targetUser.getGold();
				
				if(l_gold > GANGSTERS.one_troy_ounce){
					var l_totalGold = number_format(Math.floor(l_gold / GANGSTERS.one_troy_ounce)) + ' oz';
				}
				else{
					var l_totalGold = number_format(Math.floor(l_gold)) + ' g';
				}

				if(isValid(gold_per_ounce)){
					var goldPerGram = gold_per_ounce / GANGSTERS.one_troy_ounce;
					var l_goldValue = number_format(Math.floor(l_gold * goldPerGram));
				}
				else
				{
					var l_goldValue = 'Data unavailable';
				}
				
				l_table = '' +
				'<div id="userProfile2">' +
					'<table>' +	
							'<tr>' +
								'<th>Your Stats</th><th>&nbsp;</th><th>&nbsp;</th><th>&nbsp;</th>' +
							'</tr>' +
							'</tr>' +
								'<td>Total Gold</td><td>' + l_totalGold + '</td>' +
								'<td>Gold Value</td><td>$' + l_goldValue + '</td>' +
							'</tr>' +
							'<tr>' +
								'<td>Money in hand</td><td>$'+number_format(l_targetUser.getCash())+'</td>' +
								'<td>Missions</td><td>'+number_format(l_jobs_completed)+'</td>' +
							'</tr>' +
							'<tr>' +
								'<td>Treasury</td><td>$'+number_format(l_targetUser.getCashInBank())+'</td>' +
								'<td>Kill Count</td><td>'+number_format(l_kill_count)+'</td>' +
							'</tr>' +
							'<tr>' +
								'<td>Allies</td><td>'+number_format(l_targetUser.getGangSize())+'</td>' +
								'<td>Threats Eliminated</td><td>'+number_format(l_bounty_kills)+'</td>' +
							'</tr>' +
							'<tr>' +
								'<td>Income</td><td>$'+number_format(l_targetUser.getIncome())+'</td>' +
								'<td>Won Battles</td><td>'+number_format(l_fights_won)+'</td>' +
							'</tr>' +
							'<tr>' +
								'<td>Upkeep</td><td>$'+number_format(l_targetUser.getUpkeep())+'</td>' +
								'<td>Lost Battles</td><td>'+number_format(l_fights_lost)+'</td>' +
							'</tr>'+
								'<td>Attack </td><td>'+number_format(l_targetUser.getAttackStrength())+'</td>' +
								'<td>Defense</td><td>'+number_format(l_targetUser.getDefenseStrength())+'</td>' +
							'</tr>' +
							'<tr>'+
								'<td>Respect Points </td><td>'+number_format(l_respect_points)+'</td>' +
								'<td></td><td></td>' +
							'</tr>';

				var l_assetsNode = getXMLFirstNode(l_xmlDoc, "land_urls");
				l_table += '' +
					'<tr>' +
						'<td colspan="4">' +
							'<h2>National Assets</h2>'; 
				var l_imageNodes = l_assetsNode.getElementsByTagName("image_url");
                for(var l_index = 0; l_index < l_imageNodes.length; l_index++){
					var l_image_url = decodeEncodedStringValue(l_imageNodes[l_index].firstChild.nodeValue);
					l_table += '' +
							'<img src="'+l_image_url+'"/> ';
				}				
				l_table += '</td>' +
					'</tr>';

				var l_infantryNode = getXMLFirstNode(l_xmlDoc, "infantry_units");
				l_table += '' +
					'<tr>' +
						'<td colspan="4">' +
							'<h2>Infantry Units</h2>'; 
				var l_imageNodes = l_infantryNode.getElementsByTagName("image_url");
                for(var l_index = 0; l_index < l_imageNodes.length; l_index++){
					var l_image_url = decodeEncodedStringValue(l_imageNodes[l_index].firstChild.nodeValue);
					l_table += '' +
							'<img src="'+l_image_url+'"/> ';
				}

				l_table += '</td>' +
					'</tr>';

				var l_landNode = getXMLFirstNode(l_xmlDoc, "land_units");
				l_table += '' +
					'<tr>' +
						'<td colspan="4">' +
							'<h2>Land Units</h2>'; 
				var l_imageNodes = l_landNode.getElementsByTagName("image_url");
                for(var l_index = 0; l_index < l_imageNodes.length; l_index++){
					var l_image_url = decodeEncodedStringValue(l_imageNodes[l_index].firstChild.nodeValue);
					l_table += '' +
							'<img src="'+l_image_url+'"/> ';
				}

				l_table += '</td>' +
					'</tr>';

				var l_navalNode = getXMLFirstNode(l_xmlDoc, "naval_units");
				l_table += '' +
					'<tr>' +
						'<td colspan="4">' +
							'<h2>Naval Units</h2>'; 
				var l_imageNodes = l_navalNode.getElementsByTagName("image_url");
                for(var l_index = 0; l_index < l_imageNodes.length; l_index++){
					var l_image_url = decodeEncodedStringValue(l_imageNodes[l_index].firstChild.nodeValue);
					l_table += '' +
							'<img src="'+l_image_url+'"/> ';
				}

				l_table += '</td>' +
					'</tr>';

				var l_airforceNode = getXMLFirstNode(l_xmlDoc, "airforce_units");
				l_table += '' +
					'<tr>' +
						'<td colspan="4">' +
							'<h2>Airforce Units</h2>';
				var l_imageNodes = l_airforceNode.getElementsByTagName("image_url");
                for(var l_index = 0; l_index < l_imageNodes.length; l_index++){
					var l_image_url = decodeEncodedStringValue(l_imageNodes[l_index].firstChild.nodeValue);
					l_table += '' +
							'<img src="'+l_image_url+'"/> ';
				}

				l_table += '</td>' +
						  '</tr>';
						  
				var l_tacticalNode = getXMLFirstNode(l_xmlDoc, "tactical_weapons");
				l_table += '' +
					'<tr>' +
						'<td colspan="4">' +
							'<h2>Tactical Weapons</h2>'; 
				var l_imageNodes = l_tacticalNode.getElementsByTagName("image_url");
                for(var l_index = 0; l_index < l_imageNodes.length; l_index++){
					var l_image_url = decodeEncodedStringValue(l_imageNodes[l_index].firstChild.nodeValue);
					l_table += '' +
							'<img src="'+l_image_url+'"/> ';
				}

				l_table += '</td>' +
						'</tr>' +
						'</table>' +
					'</div>';

            } catch (err) {}
        }
		this.m_profileTableRightTd.innerHTML = l_table;
    }

	Profile.prototype.attack = function(a_punch,a_captcha){
		var l_self = this;
		if(a_punch){			
			l_self.m_resultDiv.innerHTML = "Threaten...";
		}
		else{
			l_self.m_resultDiv.innerHTML = "Attacking ...";
		}
		
	   goToPageTop();

	   var l_params = {};
	   l_params.user_id = GANGSTERS.VIEWER.getUserId();
	   l_params.target_id = this.m_targetId;
	   try{
			l_params.captcha = a_captcha.value;
	   }
	   catch(ex){}
	   
	   l_params.punch_in_face = a_punch;
	   makeRequest("attack",
			   function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){})},
			   l_params,l_self);
	}

	Profile.prototype.attackForRespectPoint = function(a_bossId, a_targetId){
		var l_self = this;
		l_self.m_resultDiv.innerHTML = "Attacking war cabinet...";
	
	   goToPageTop();

	   var l_params = {};
	   l_params.user_id = GANGSTERS.VIEWER.getUserId();
	   l_params.target_id = a_targetId;
	   l_params.boss_id = a_bossId;
	   makeRequest("attack_for_respect_point",
			   function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){})},
			   l_params,l_self);
	}

	Profile.prototype.block = function(a_targetId){
		var l_self = this;
		l_self.m_resultDiv.innerHTML = "Blocking user...";
	
	   goToPageTop();

	   var l_params = {};
	   l_params.user_id = GANGSTERS.VIEWER.getUserId();
	   l_params.target_id = this.m_targetId;
	   makeRequest("block_user",
			   function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){})},
			   l_params,l_self);
	}

	Profile.prototype.getComments =  function(){
	   var l_self = this;
	   var l_params = {};
	   l_params.target_id = this.m_targetId;
	   makeRequest("get_comments",
			   function(a_responseData){l_self.onGetComments(a_responseData)},
			   l_params,l_self);
	}
	
	Profile.prototype.onGetComments = function(a_responseData){
        var l_xmlDoc = getResponseData(a_responseData);
		
		var l_table = '' +
				'<h2> User Comments </h2>' +
				'<table>' +
					'<tr>' +
						'<td>Comment:</td>' +
						'<td><textarea id="comment_msg"></textarea></td>' +
					'</tr>'	+
					'<tr>' +
						'<td></td>' +
						'<td><input type="submit" value="Post Comment" onClick="GANGSTERS.Profile.postComment()" /></td>' +
					'</tr>' +
				'</table>'+						
				'<div style="width:450px;height:1000px;overflow:auto">' +
				'<table width="100%">';

        if(isValid(l_xmlDoc)){
            try{
                var l_entryNodes = l_xmlDoc.getElementsByTagName("entry");

                for(var l_index = 0; l_index < l_entryNodes.length; l_index++){
					var l_id = getXMLNodeValue(l_entryNodes[l_index], "id");
					var l_message = getXMLEncodedStringNodeValue(l_entryNodes[l_index], "message");
					var l_time_ago = getXMLNodeValue(l_entryNodes[l_index], "time_ago");

					var l_fromUserNodes = getXMLFirstNode(l_entryNodes[l_index],"from_user");
					var l_user_id = getXMLNodeValue(l_fromUserNodes, "user_id");
					var l_gang_name = getXMLNodeValue(l_fromUserNodes, "gang_name");
					var l_thumbnail_url = getXMLNodeValue(l_fromUserNodes, "thumbnail_url");

					l_table += '<tr>' +
						'<td width="15%" valign="top" class="separator"><a href="#top" onClick="viewProfile('+l_user_id+')"><img src="'+l_thumbnail_url+'" width="50px" height="50px" border="0" /></a></td>' +
						'<td class="separator">'+ 
							'<span class="name" valign="top"><a href="#top" onClick="viewProfile('+l_user_id+')">'+l_gang_name+'</a></span> <span class="date">'+l_time_ago+'</span>' +
							'<div class="comment">'+l_message+'</div>' +
						'</td>' +
						'<td class="separator"><span class="date" valign="top"><a href="#top" onClick="GANGSTERS.Profile.deleteComment('+l_id+')">X</a></span></td>' +
					'</tr>';
				}
			}
			catch(ex){}
		}
		l_table += '</table></div>';
		
		this.m_commentDiv.innerHTML = l_table;
	}
	
	Profile.prototype.deleteComment = function(a_id){
	   var l_self = this;
	   l_self.m_resultDiv.innerHTML = "Deleting...";
	   goToPageTop();

	   var l_params = {};
	   l_params.user_id = GANGSTERS.VIEWER.getUserId();
	   l_params.delete_entry_id = a_id;
	   makeRequest("delete_comment_entry",
		   function(a_response){l_self.m_resultDiv.innerHTML = ""; l_self.getComments();},
		   l_params,l_self);		
	}
	
	Profile.prototype.postComment = function(){
	   var l_self = this;
	   l_self.m_resultDiv.innerHTML = "Posting...";
	   goToPageTop();

	   var l_message = document.getElementById("comment_msg");
	   var l_params = {};
	   l_params.user_id = GANGSTERS.VIEWER.getUserId();
	   l_params.target_id = this.m_targetId;
	   l_params.message = customEncoding(l_message.value);
	   makeRequest("save_comment",
		   function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.getComments();})},
		   l_params,l_self);				
	}
	
	Profile.prototype.getFamilyTree = function(){	
		var l_self = this;
        var l_params = {};
        l_params.user_id = this.m_targetId;
        makeRequest("get_family_tree_profile", function(a_responseData){l_self.onGetFamilyTree(a_responseData);}, l_params,l_self);
    }
	
	Profile.prototype.onGetFamilyTree = function(a_responseData){
		this.m_treeDiv.innerHTML = '<h1>War Cabinet:<a href="#top" onClick="GANGSTERS.Profile.attack(false)">Attack</a> | <a href="#top" onClick="GANGSTERS.Profile.attack(true)">Bomb</a> | <a href="#top" onClick="GANGSTERS.Profile.calcMinBounty()">Add to Threat List</a> | <a href="#top" onClick="GANGSTERS.Profile.block()">Block|Unblock</a></h1>';
		var l_self = this;
        var l_xmlDoc = getResponseText(a_responseData);
		
        if(isValid(l_xmlDoc)){
            try{
				this.m_treeDiv.innerHTML += l_xmlDoc;
            } catch (err) {}
        }
	}	

	Profile.prototype.calcMinBounty = function(){
		this.m_resultDiv.innerHTML = 'Loading...';

        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        l_params.target_id = this.m_targetId;
        var l_self = this;
        makeRequest("get_min_hit_list_bounty",
                function(a_response){ l_self.onGetMinBounty(a_response, true);},
                l_params,l_self);

    }

    Profile.prototype.onGetMinBounty = function(a_response, a_showError){
        var l_xmlDoc = getResponseData(a_response);
        var l_minCost = undefined;

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

        if(!isValid(l_minCost)){
            this.m_resultDiv.innerHTML = "Oopsie, there was an error, please refresh";
            return;
        }

        l_minCost = parseInt(l_minCost);
        this.m_resultDiv.innerHTML = '' +
		'<h1>Place on Threat List (Minimum of $'+number_format(l_minCost)+')</h1>' +
		'Once your Threat is posted, this user will be publicly listed for attack by other Nations. The reward will be given to whoever accomplishes the task. <b> It costs 1 stamina point to place a user on the Threat List.</b><br/>';

        if(a_showError){
            var l_totalUserCash = GANGSTERS.VIEWER.getCash() + GANGSTERS.VIEWER.getCashInBank();
            if(l_minCost > l_totalUserCash){
                this.m_resultDiv.innerHTML = "Sorry, you need at least $"+ number_format(l_minCost) + " to put this Nation on the Threat list.";
                return;
            }
        }
		
		var l_table = '' +
		'<table>' +
			'<tr>' +
				'<td>' +
				'Threat List Reward Amount: ' +
				'</td>' +
				'<td>' +
				'<input type="text" id="bountyAmount" value="'+l_minCost+'"/>' +
				'</td>' +
				'<td>' +
				'<input type="submit" value="Add To Threat List" onClick="GANGSTERS.Profile.addToHitList()" />' +
				'</td>' +
			'</tr>' +
		'</table>';
		this.m_resultDiv.innerHTML += l_table;
	}

	Profile.prototype.addToHitList = function(){
        var l_self = this;
		var l_amount = document.getElementById('bountyAmount');
		if(!validateAmount(l_amount.value)){
			l_self.m_resultDiv.innerHTML = "Please specify a valid amount!";
			return;
		}

		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.target_id = l_self.m_targetId;
		l_params.bounty = l_amount.value;
		makeRequest("add_hit_list",
				function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){})},
				l_params,l_self);
	}
// end Profile


//Refresh Div
	function RefreshDiv(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		
		this.m_containerDiv = document.createElement("div");
		this.m_containerDiv.id = "refresh";
		this.m_parentDiv.appendChild(this.m_containerDiv);
		this.m_refreshBtn = document.createElement("div");
		this.m_refreshBtn.className = "refreshButton";
		this.m_parentDiv.appendChild(this.m_refreshBtn);
		this.m_refreshBtn.innerHTML = '<br/><a href="#top" onClick="DoRefresh()">REFRESH</a>';
		
		this.m_secondsToHealth = undefined;
		this.m_secondsToAdrenaline = undefined;
		this.m_secondsToStamina = undefined;
		
		this.timer = undefined;
		this.refresh();	
	}
	
	RefreshDiv.prototype.refresh = function(){
		this.m_containerDiv.innerHTML = "";

        this.m_secondsToHealth = GANGSTERS.VIEWER.getSecondsToHealthRefresh();
        this.m_secondsToAdrenaline = GANGSTERS.VIEWER.getSecondsToAdrenalineRefresh();
        this.m_secondsToStamina = GANGSTERS.VIEWER.getSecondsToStaminaRefresh();

        if(isValid(this.m_secondsToAdrenaline)){ this.m_secondsToAdrenaline = parseInt(this.m_secondsToAdrenaline) + 2;}
        if(isValid(this.m_secondsToHealth)){ this.m_secondsToHealth = parseInt(this.m_secondsToHealth) + 2;}
        if(isValid(this.m_secondsToStamina)){ this.m_secondsToStamina = parseInt(this.m_secondsToStamina) + 2;}
		
		if(isValid(this.timer)){
			clearInterval(this.timer);
		}
		this.timer = setInterval(function(){GANGSTERS.refreshDiv.onTick()},1000);
    }

    RefreshDiv.prototype.onTick = function(){
        if(!isValid(GANGSTERS.VIEWER)){
            return;
        }

        this.m_containerDiv.innerHTML = "";

        if(!isValid(GANGSTERS.VIEWER.getSecondsToHealthRefresh()) &&
           !isValid(GANGSTERS.VIEWER.getSecondsToAdrenalineRefresh()) &&
           !isValid(GANGSTERS.VIEWER.getSecondsToStaminaRefresh())) {

            this.m_containerDiv.innerHTML = "<span style='color:red'>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 + " sec until more health.<br>";
            } else {
               l_needsRefresh = true;
            }
            this.m_secondsToHealth -= 1;
        }

        if(isValid(this.m_secondsToAdrenaline)){
            if(this.m_secondsToAdrenaline >= 1) {
                this.m_containerDiv.innerHTML += this.m_secondsToAdrenaline + " sec until more courage.<br>";			
            } else {
               l_needsRefresh = true;
            }
            this.m_secondsToAdrenaline -= 1;
        }

        if(isValid(this.m_secondsToStamina)){
            if(this.m_secondsToStamina >= 1) {
                this.m_containerDiv.innerHTML += this.m_secondsToStamina + " sec until more stamina.<br>";
            } else {
               l_needsRefresh = true;
            }
            this.m_secondsToStamina -= 1;
        }

        if(l_needsRefresh){
            this.m_containerDiv.innerHTML = "<a href='#top' onclick='DoRefresh()'>Please refresh page</a>";        }
	}
//end RefreshDiv

//ReportAbuse
    function ReportAbuse(a_parentDiv, a_type){
				
		this.m_parentDiv = a_parentDiv;
	
		this.m_parentDiv.innerHTML = '<i>Thank you for playing World At War II,<br/><br/>'+ 
		'If you have any questions, concerns or would like to report abuse. Please e-mail the abuse team at <a href="mailto:abuse@layoutvault.com">abuse@layoutvault.com</a>. All your concerns will be fully investigated. If you are missing offerpoints or have issues with paypal transactions contact us at <a href="mailto:points@layoutvault.com">points@layoutvault.com</a></i>';
	}
//end ReportAbuse

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();
    GANGSTERS.OS_CONTAINER.postTo(GANGSTERS.OS_TOKEN, l_message, a_targetUser, a_postToCallback);
}

function sendInvite(a_targetUser, a_content, a_postToCallback){	
    var l_message = opensocial.newMessage(a_content);
	l_message.setField(opensocial.Message.Field.TITLE, "Join my gang");
    opensocial.requestShareApp(a_targetUser.getUserId(), l_message, a_postToCallback);
}

function sendMultipleInvite(a_targetUser, a_content, a_postToCallback){	
    var l_message = opensocial.newMessage(a_content);
	l_message.setField(opensocial.Message.Field.TITLE, "Join my gang");
    opensocial.requestShareApp(a_targetUser, l_message, a_postToCallback);
}

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();
    GANGSTERS.OS_CONTAINER.postTo(GANGSTERS.OS_TOKEN, l_message, a_targetUser, a_postToCallback);
}

function setStyle(a_node, a_style) {
    if(isValid(a_style))        {
        for(var i in a_style) {
            a_node.style[i] = a_style[i];
        }
    }
    return a_node;
}

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(";");
        
        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 + "..";
        }
    }

// Shops_Category
    function Shops_Category(a_parentDiv, a_category){
		this.m_parentDiv = a_parentDiv;
		this.m_category = a_category;
		
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);
		
		this.Melee_Weapons = '' +
		'<div id="newUsers">' +
			'<h1>Infantry</h1>' +
			'<div class="tips">' +
				'The infantry is usually the first in and last out in many historical battles. Invest in skilled infantry to defend your nation and complete complex missions. Make sure you have a good number of foot soldiers in your Armed Forces at all times!' +
				' <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(3)">Click here</a> to go back. <br/> <h2 style="font-size:8pt">* The maximum amount of weapons you can own is related to your RANK, the higher your RANK the more you can buy of a certain type of unit. Rising in RANK means you can purchase more weapons and become stronger!</h2> <h2 style="font-size:8pt"> ** Units get damaged while doing missions. Make sure you repair them or they render useless!</h2>' +
			'</div>' +
		'</div>';
		
		this.Guns_Ammo = '' +
		'<div id="newUsers">' +
			'<h1>Land Warfare Units</h1>' +
			'<div class="tips">' +
				'Outfit your armored and mobile units with state-of-the-art armored units and vechicles. These units are great support for your infantry units during attacks and missions. There is nothing more fearful than the noise of tank treads on asphalt.' + 
				' <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(3)">Click here</a> to go back. <br /> <h2  style="font-size:8pt">* The maximum amount of weapons you can own is related to your RANK, the higher your RANK the more you can buy of a certain type of unit. Rising in RANK means you can purchase more weapons and become stronger!</h2> <h2 style="font-size:8pt"> ** Units get damaged while doing missions. Make sure you repair them or they render useless!</h2>' +
			'</div>' +
		'</div>';
		
		this.Armor_Store = '' +
		'<div id="newUsers">' +
			'<h1>Sea Units</h1>' +
			'<div class="tips">' +
				'Wars aren\'t fought on land alone. Build a fearful Navy to dominate the seas. Commission all sea units in this area. Your Naval force should be feared on the open seas, so choose your units wisely.' +
				' <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(3)"> Click here</a> to go back. <br /> <h2  style="font-size:8pt">* The maximum amount of weapons you can own is related to your RANK, the higher your RANK the more you can buy of a certain type of unit. Rising in RANK means you can purchase more weapons and become stronger!</h2> <h2 style="font-size:8pt"> ** Units get damaged while doing missions. Make sure you repair them or they render useless!</h2>' +
			'</div>' +
		'</div>';
		
		this.Auto_Dealers = '' +
		'<div id="newUsers">' +
			'<h1>Air Units</h1>' +
			'<div class="tips">' +
				'Air superiority is crutial in any battle. Upgrade your Air Force with the best planes and helicopters in this section. The more powerful and stealthy units are unlocked at higher levels ' +
				' <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(3)"> Click here</a> to go back. <br /><h2  style="font-size:8pt">* The maximum amount of weapons you can own is related to your RANK, the higher your RANK the more you can buy of a certain type of unit. Rising in RANK means you can purchase more weapons and become stronger!</h2> <h2 style="font-size:8pt"> ** Units get damaged while doing missions. Make sure you repair them or they render useless!</h2>' +
			'</div>' +
		'</div>';
		
		this.Pet_Store = '' +
		'<div id="newUsers">' +
			'<h1>Special Operations</h1>' +
			'<div class="tips">' +
				'This is a Classified Area. Utilize Special Ops Units to infiltrate the enemy and destroy them from all angles. Special Ops units are not displayed on your profile, so nobody will know the strength of this division. You may want to use this information to plan your strategies.' +
				' <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(3)">Click here</a> to go back. <br/> <h2  style="font-size:8pt">* The maximum amount of weapons you can own is related to your RANK, the higher your RANK the more you can buy of a certain type of unit. Rising in RANK means you can purchase more weapons and become stronger!</h2> <h2 style="font-size:8pt"> ** Units get damaged while doing missions. Make sure you repair them or they render useless!</h2>' +
			'</div>' +
		'</div>';
		
		this.General_Store = '' +
		'<div id="newUsers">' +
			'<h1>Tactical Weapons</h1>' +
			'<div class="tips">' +
				'Both conventional and unconventional weapons can be found here. Please be reasonable before using Weapons of Mass Destruction, especially nuclear weapons that you will unlock when you reach higher ranks. These weapons can be devastating to your enemy. ' +
				' <a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(3)"> Click here</a> to go back. <br/> <h2  style="font-size:8pt">* The maximum amount of weapons you can own is related to your RANK, the higher your RANK the more you can buy of a certain type of unit. Rising in RANK means you can purchase more weapons and become stronger!</h2> <h2 style="font-size:8pt"> ** Units get damaged while doing missions. Make sure you repair them or they render useless!</h2>' +
			'</div>' +
		'</div>';
				
		switch(this.m_category){	
			case 'Melee_Weapons':
				if(GANGSTERS.VIEWER.getLevel()<1){					
					this.m_infoDiv.innerHTML = 'You must reach level 1 to unlock weapons in this shop';
					return;
				}
				break;
			case 'Guns_Ammo':
				if(GANGSTERS.VIEWER.getLevel()<55){					
					this.m_infoDiv.innerHTML = 'You must reach level 55 to unlock weapons in this shop';
					return;
				}
				break;
			case 'Auto_Dealers':
				if(GANGSTERS.VIEWER.getLevel()<115){
					this.m_infoDiv.innerHTML = 'You must reach level 115 to unlock weapons in this shop';
					return;
				}
				break;
			case 'Armor_Store':
				if(GANGSTERS.VIEWER.getLevel()<220){
					this.m_infoDiv.innerHTML = 'You must reach level 220 to unlock weapons in this shop';
					return;
				}
				break;
			case 'Pet_Store':
				if(GANGSTERS.VIEWER.getLevel()<260){
					this.m_infoDiv.innerHTML = 'You must reach level 260 to unlock weapons in this shop';
					return;
				}
				break;
			case 'General_Store':
				if(GANGSTERS.VIEWER.getLevel()<295){
					this.m_infoDiv.innerHTML = 'You must reach level 295 to unlock weapons in this shop';
					return;
				}
				break;
		}
		
		this.m_infoDiv.innerHTML = eval('this.'+this.m_category);
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.className = "categoryTableTitle";
		this.m_parentDiv.appendChild(this.m_contentDiv);
		
		this.getItemList();
    }

    Shops_Category.prototype.getItemList = function(){

        this.m_contentDiv.innerHTML = "Loading Items...";
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        l_params.level = GANGSTERS.VIEWER.getLevel();
		l_params.category = this.m_category;
        
        var l_self = this;
        makeRequest("get_item_list", function(a_responseData){
           l_self.onGetItemList(a_responseData);
        },l_params,l_self);
    }

    Shops_Category.prototype.onGetItemList = function(a_responseData){
        var l_xmlDoc = getResponseData(a_responseData);
		var l_table = '';
		
        if(isValid(l_xmlDoc)){
            try{
				l_table = '' +
						'<table align="center">' +
							'<tr>' +
								'<th>Description</th>' +
								'<th>Picture</th>' +
								'<th>Stats</th>' +
								'<th>Buy / Sell / Resupply</th>' +
							'</tr>';

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

					l_table += '<tr>';

			        try{ 
						var l_itemId = getXMLNodeValue(l_itemNodes[l_index],"id");
						var l_title = getXMLEncodedStringNodeValue(l_itemNodes[l_index],"title");

						l_table += '<td width="20%"><span class="description">' + l_title + '</span></td>';
						var l_image_url = getXMLEncodedStringNodeValue(l_itemNodes[l_index],"image_url");

						l_table += '<td width="20%"><img src="' + l_image_url + '" /></td>';												
						var l_attack = getXMLNodeValue(l_itemNodes[l_index],"attack");
						var l_defense = getXMLNodeValue(l_itemNodes[l_index],"defense");
						var l_upkeep = getXMLNodeValue(l_itemNodes[l_index],"upkeep");
						
						var l_loaded = getXMLNodeValue(l_itemNodes[l_index],"loaded");

						var l_cost = getXMLNodeValue(l_itemNodes[l_index],"cost");
						var l_owned = getXMLNodeValue(l_itemNodes[l_index],"num_owned");
						var l_allies_size = getXMLNodeValue(l_itemNodes[l_index],"gang_size");
						
						l_table += '<td width="20%">';
						if(isValid(l_attack) && l_attack>0){
							l_table += 'Attack:' + l_attack;
						}
						if(isValid(l_defense) && l_defense>0){
							l_table += ' / Defense:' + l_defense;
						}
						if(isValid(l_upkeep) && l_upkeep>0){
							l_table += ' <br /> Upkeep: $' + number_format(l_upkeep);
						}
						
						l_table += ' <br/><span class="redText">Allies Size: '+ number_format(l_allies_size) + '</span>';
						
						if(isValid(l_loaded) && isValid(l_owned)){
							l_table += ' <br /><br/>Unit(s) Health: ' + number_format(l_loaded)/number_format(l_owned) * 100 + '%';
						}
						l_table += '</td>' +
						'<td width="40%">' +
							'<span class="money">Cost: $' + number_format(l_cost) + '</span> <br /><br />' +
							'<select id="buy_qty' + l_itemId + '">' +
								'<option value="1">1</option>' +
								'<option value="2">2</option>' +
								'<option value="3">3</option>' +
								'<option value="4">4</option>' +
								'<option value="5">5</option>' +
								'<option value="10">10</option>' +
								'<option value="20">20</option>' +
								'<option value="50">50</option>' +
								'<option value="100">100</option>' +
								'<option value="1000">1000</option>' +
								'<option value="10000">10000</option>' +
							'</select>' +
							'<input type="submit" value="Buy" onClick="GANGSTERS.'+this.m_category+'.buy(' + l_itemId + ')" /> ';

						if(isValid(l_owned) && l_owned>0){
						l_table += '<select id="sell_qty' + l_itemId + '">' +
								'<option value="1">1</option>' +
								'<option value="2">2</option>' +
								'<option value="3">3</option>' +
								'<option value="4">4</option>' +
								'<option value="5">5</option>' +
								'<option value="10">10</option>' +
								'<option value="20">20</option>' +
								'<option value="50">50</option>' +
								'<option value="100">100</option>' +
								'<option value="1000">1000</option>' +
								'<option value="10000">10000</option>' +
							'</select>' +
						' <input type="submit" value="Sell" onClick="GANGSTERS.'+this.m_category+'.sell(' + l_itemId + ')" /> ' +
							'<select id="reload_qty' + l_itemId + '">' +
								'<option value="1">1</option>' +
								'<option value="2">2</option>' +
								'<option value="3">3</option>' +
								'<option value="4">4</option>' +
								'<option value="5">5</option>' +
								'<option value="10">10</option>' +
								'<option value="20">20</option>' +
								'<option value="50">50</option>' +
								'<option value="100">100</option>' +
								'<option value="1000">1000</option>' +
								'<option value="10000">10000</option>' +
							'</select>' +
						' <input type="submit" value="Repair" onClick="GANGSTERS.'+this.m_category+'.reload(' + l_itemId + ')" />';
						
							l_table += '<br />Owned / Limit: ' + l_owned + ' / ' + GANGSTERS.VIEWER.getGangSize();
						}
						else{
							l_table += '<br/>Owned / Limit: 0 / ' + GANGSTERS.VIEWER.getGangSize();
						}
						
						l_table += '</td>';
					
					}catch(err){};
					l_table += '</tr>';
                }
				
				l_table += '</table>';
				
                var l_nextLevel = getXMLNodeValue(l_xmlDoc, "next_level");
                if(isValid(l_nextLevel)){
					l_table += '<div class="levelMsg">Unlock more items when you reach ' + l_nextLevel + ' ...';
                }

            } catch (err) {}
        }
		
		this.m_contentDiv.innerHTML = l_table;
    }
	
	Shops_Category.prototype.buy = function(a_itemId){
		goToPageTop();
		var l_self = this;
		var l_amount = document.getElementById("buy_qty" + a_itemId);
		var l_qty = 0;
        for(var l_index = 0; l_index < l_amount.length; l_index++){
            if(l_amount[l_index].selected){
                l_qty = l_amount[l_index].value;
            }
        }
		this.m_resultDiv.innerHTML = "Buying ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.item_id = a_itemId;
		l_params.amount = l_qty;
		
		makeRequest("buy_item",
				function(a_response){
					handleResult(a_response, l_self.m_resultDiv, function(){l_self.getItemList()});},
				l_params,l_self);
	}
	
	Shops_Category.prototype.sell = function(a_itemId){
		goToPageTop();
		var l_self = this;
		var l_amount = document.getElementById("sell_qty" + a_itemId);
		var l_qty = 0;
        for(var l_index = 0; l_index < l_amount.length; l_index++){
            if(l_amount[l_index].selected){
                l_qty = l_amount[l_index].value;
            }
        }
		this.m_resultDiv.innerHTML = "Selling ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.item_id = a_itemId;
		l_params.amount = l_qty;
		
		makeRequest("sell_item",
				function(a_response){
					handleResult(a_response, l_self.m_resultDiv, function(){l_self.getItemList()});},
				l_params,l_self);
	}
	
	Shops_Category.prototype.reload = function(a_itemId){
		goToPageTop();
		var l_self = this;
		var l_amount = document.getElementById("reload_qty" + a_itemId);
		var l_qty = 0;
        for(var l_index = 0; l_index < l_amount.length; l_index++){
            if(l_amount[l_index].selected){
                l_qty = l_amount[l_index].value;
            }
        }
		this.m_resultDiv.innerHTML = "Resupplying ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.item_id = a_itemId;
		l_params.amount = l_qty;
		
		makeRequest("reload_item",
				function(a_response){
					handleResult(a_response, l_self.m_resultDiv, function(){l_self.getItemList()});},
				l_params,l_self);
	}
// end Shops_Category

function showFamilyTree(){
	window.open(GANGSTERS.CANVAS_URL + "appParams=%7B%22show_family_tree%22%3A%22true%22%7D");
}

//StatusDiv
	function StatusDiv(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		this.refresh();	
	}

	StatusDiv.prototype.refresh = function(){
		this.m_parentDiv.innerHTML = ''+
		'<table>' +
			'<tr>' +
				'<td><div class="statusTitle">HEALTH</div> <div>' + GANGSTERS.VIEWER.getHealth() + '/' + GANGSTERS.VIEWER.getMaxHealth() + '</div></td>' +
				'<td><div class="statusTitle">COURAGE</div> <div>' + GANGSTERS.VIEWER.getAdrenaline() + '/' + GANGSTERS.VIEWER.getMaxAdrenaline() + '</div></td>' +
				'<td><div class="statusTitle">STAMINA</div> <div>' + GANGSTERS.VIEWER.getStamina() + '/' + GANGSTERS.VIEWER.getMaxStamina() + '</div></td>' +
				'<td><div class="statusTitle">ALLIES</div> <div>' + GANGSTERS.VIEWER.getGangSize() + '</div></td>' +
				'<td><div class="statusTitle">EXPERIENCE</div> <div>' + GANGSTERS.VIEWER.getExperience() + '/' + (GANGSTERS.VIEWER.getExpPointsToNextLevel() + GANGSTERS.VIEWER.getExperience()) + '</div></td>' +
				'<td><div class="cashTitle">FINANCES</div> <div>$' + number_format(GANGSTERS.VIEWER.getCash()) + '</div></td>' +
				'<td><div class="statusTitle">RANK</div> <div>' + GANGSTERS.VIEWER.getLevel() + '</div></td>' +
			'</tr>'+
		'</table>';
	}
//end StatusDiv

// Threat_List
    function Threat_List(a_parentDiv){
		this.m_parentDiv = a_parentDiv;

		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);

		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);

		this.m_infoDiv.innerHTML = '' +
		'<div id="newUsers">' +
			'<div class="tips">' +
			    ' <span style="color:yellow; font-size:14px; font-weight:bold"><span style="color:red"> WARNING! </span> There is an ADMIN bot placed on the hitlist to catch users trying to use automated programs. This bot is clearly labelled as, "<span style="color:red">ADMIN THREAT LIST ENFORCER BOT DO NOT ATTACK</span>,"and will have maximum attack and defense power. Please DO NOT attack this bot, it is there to catch those that cheat. Be careful, your losses from the bot will not be removed</span>'+
			'</div>';
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.className = "categoryTableTitle";
		this.m_parentDiv.appendChild(this.m_contentDiv);
				
		this.m_generalDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_generalDiv);
		
		this.m_generalDiv.innerHTML = '' +
		'<div class="general">' +
		'Make sure you have a large amount of Allies supporting you and have purchased the most powerful and efficient Army before attacking others. You have been warned!' +
		'</div>';
		
		this.getHitList();
    }
	
    Threat_List.prototype.getHitList = function(){

        this.m_contentDiv.innerHTML = "Loading Threat List...";
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
        l_params.level = GANGSTERS.VIEWER.getLevel();
        
        var l_self = this;
        makeRequest("get_hit_list", function(a_responseData){
           l_self.onGetHitList(a_responseData);
        },l_params,l_self);
    }
	
    Threat_List.prototype.onGetHitList = function(a_responseData){
        var l_xmlDoc = getResponseData(a_responseData);
		var l_table = '';
		
        var l_xmlDoc = getResponseData(a_responseData);
        var l_numTargets = undefined;
        if(isValid(l_xmlDoc)){
            try{
                var l_numTargets = parseInt(getXMLNodeValue(l_xmlDoc, "num_targets"));
				l_table = '' +
				'<table align="center">' +
					'<tr>' +
						'<th>Name</th>' +
						'<th>Status</th>' +
						'<th>Allies</th>' +
						'<th>Attack!</th>' +
					'</tr>';

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

					l_table += '<tr>';
					
			        try{ 
	                    var l_targetUser = new User(undefined);
	                    l_targetUser.createXMLUser(l_userNodes[l_index]);
						
						l_table += '<td width="20%"><div class="thumbTable"><table><tr><td width="5%"><a href="#top" onClick="viewProfile('+l_targetUser.getUserId()+')"><img src="'+l_targetUser.getThumbnailUrl()+'" width="35px" height="35px" border="0"></a></td><td> <a href="#top" onClick="viewProfile('+l_targetUser.getUserId()+')">'+l_targetUser.getGangName()+'</a></td></tr></table></div></td>' +
						'<td width="20%">Level '+l_targetUser.getLevel()+', '+l_targetUser.getGangClass()+'</td>' +
						'<td width="20%">'+l_targetUser.getGangSize()+'</td>' +
						'<td width="40%">' +
						'<span class="money">Reward: $'+number_format(l_targetUser.getReward())+'</span> <br /><br />' +
						'<input type="submit" value="Attack!" onClick="GANGSTERS.Threat_List.attack('+l_targetUser.getUserId()+')">' +						
						'</td>';
					
					}catch(err){};
					l_table += '</tr>';
                }
				
				l_table += '</table>';

				this.m_contentDiv.innerHTML = l_table;

		        if(!isValid(l_numTargets) || l_numTargets <= 0){
					this.m_contentDiv.innerHTML = "The Threat List is currently empty. Check back often for marked Nations that you can earn rewards on!";
		        }
            } catch (err) {}
        }
    }
	
	Threat_List.prototype.attack = function(a_targetId){
		goToPageTop();
		var l_self = this;
		this.m_resultDiv.innerHTML = "Attacking ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.target_id = a_targetId;
		
		makeRequest("hitlist_attack",
				function(a_response){
					handleResult(a_response, l_self.m_resultDiv, function(){l_self.getHitList()});},
				l_params,l_self);
	}
// end Threat_List

// Top_25
    function Top_25(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
				
		this.m_menuDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_menuDiv);
		this.m_menuDiv.innerHTML = '' +
		'<div id="feedMenu"><a href="#top" onClick="GANGSTERS.menuDiv.navigateTo(10)">Top 25</a> | <a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Alliance_Stat\',\'Alliance_Stat\')">Alliance Stats</a></div>';
		
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);
				
		this.m_infoDiv.innerHTML = '' +
		'<div id="newUsers">' +
			'<h1>Notorious Nations</h1>' +
			'<div class="tips">' +
				'The richest, most powerful and feared Nations are listed here. Maybe one day you will make in the History books as a mighty Nation. Try harder if you aren\'t already up in the ranks. Sort list by, ' + 
				'<select id="sort_by" onChange="GANGSTERS.Top_25.handleOnChange()">' +
					'<option value="gang_size">Largest Population</option>' +
					'<option value="respect_points">Most respectable</option>' +
					'<option value="richest">Richest Nations</option>' +
					'<option value="level">Top Level</option>' +
					'<option value="gold">Top Gold Traders</option>' +
					'<option value="most_kills">Most Battle Kills</option>' +
					'<option value="most_wins">Most Battle Wins</option>' +
					'<option value="most_hits">Most Threats Eliminated</option>' +
				'</select>' +
			'</div>'+
		'</div>';
		
		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.className = "rankTable";
		this.m_parentDiv.appendChild(this.m_contentDiv);

		this.m_generalDiv = document.createElement("div");
		this.m_parentDiv.appendChild(this.m_generalDiv);
		this.m_generalDiv.innerHTML = '' +
		'<div class="general">' +
		'Make sure you have a large amount of Allies supporting you and have purchased the most powerful and efficient Army before attacking others. You have been warned!' +
		'</div>';
		
		this.getLeaderList('gang_size');
    }

    Top_25.prototype.getLeaderList = function(a_sortby){

        this.m_contentDiv.innerHTML = "Loading "+a_sortby.replace('_',' ')+" Nations...";
        var l_params = {};
        l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.sort_by = a_sortby;
        
        var l_self = this;
        makeRequest("get_leaders", function(a_responseData){
           l_self.onGetLeaderList(a_responseData);
        },l_params,l_self);
    }

    Top_25.prototype.onGetLeaderList = function(a_responseData){
        var l_xmlDoc = getResponseData(a_responseData);
		var l_table = '';
		
        if(isValid(l_xmlDoc)){
            try{
				l_table = '' +
						'<table align="center">' +
							'<tr>' +
								'<th>Rank</th>' +
								'<th>Name</th>' +
								'<th>Accomplishment</th>' +
							'</tr>';	

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

					l_table += '<tr>';
					
					try{ 
						var l_targetUser = new User(undefined);
						l_targetUser.createXMLUser(l_userNodes[l_index]);
						
						l_table += '<td width="10%">'+(l_index+1)+'</td><td width="45%"><span class="thumbTable"><table><tr><td width="5%"><a href="#top" onClick="viewProfile('+l_targetUser.getUserId()+')"><img src="'+l_targetUser.getThumbnailUrl()+'" width="35px" height="35px" border="0"></a></td><td> <a href="#top" onClick="viewProfile('+l_targetUser.getUserId()+')">'+l_targetUser.getGangName()+'</a></td></tr></table></span></td>' +
						'<td width="45%">'+l_targetUser.getReward()+'</td>';
					
					}catch(err){};
					l_table += '</tr>';
				}
				
				l_table += '</table>';

				this.m_contentDiv.innerHTML = l_table;

            } catch (err) {}
        }
    }
	
	Top_25.prototype.handleOnChange = function(){
		goToPageTop();
		var l_sortByRank = 'richest';
		var l_sortby = document.getElementById("sort_by");
        for(var l_index = 0; l_index < l_sortby.length; l_index++){
            if(l_sortby[l_index].selected){
                l_sortByRank = l_sortby[l_index].value;
            }
        }
		this.getLeaderList(l_sortByRank);
	}
// end Top_25

//Treasury
	function Treasury(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);
		
		this.m_infoDiv = document.createElement("div");
		this.m_infoDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_infoDiv);
		
		this.refresh();
	}
	
	Treasury.prototype.refresh = function(){
		
		var htmlContent = '' +
			'<div id="newUsers">' +
			'<h1>National Treasury</h1>' +
			'<div class="tips">' +
				'Deposit your Funds in the Treasury for safety. Money in the Treasury cannot be stolen by rival Nations in the event of an attack. You can only use Treasury money to pay mainteance fees at Medic Stations so please keep a reasonable amount in your Treasury at all times. Also, you must keep a minimum of <span class="money">$2,000</span> in the Treasury as a reserve, but you may withdraw or deposit Funds at any time. All deposits are charged a 10% fee.' +
			'</div>' +
			'<div class="general">' +
				'Treasury Balance: <span class="money">$' + ( number_format(GANGSTERS.VIEWER.getCashInBank()) ) + '</span>' +
			'</div>' +
			'<div class="general">' +
				'<table> ' +
					'<tr>' +
						'<td> Withdraw Funds: </td>' +
						'<td> <input type="text" id="withdraw_amount" value="' + ( Math.min(1000, GANGSTERS.VIEWER.getCashInBank()) ) + '"/> </td>' +
						'<td> <input type="submit" value="Withdraw" onClick="GANGSTERS.Treasury.withdraw()" style="width:100px;" /> </td>' +
					'</tr>' +
					'<tr>' +
						'<td> Deposit Funds: </td>' +
						'<td> <input type="text" id="deposit_amount" value="' + ( GANGSTERS.VIEWER.getCash() ) + '" /> </td>' +
						'<td> <input type="submit" value="Deposit" onClick="GANGSTERS.Treasury.deposit()" style="width:100px;"/> </td>' +
					'</tr>' +
				'</table>' +
			'</div>' +
			'<div id="newUsers">' +
			'<h1>Automatic Deposit Service';
		
		if(GANGSTERS.VIEWER.isPlanActive() == 1){
			htmlContent += ' (<span style="color:#00FF00">Plan ' + GANGSTERS.VIEWER.getDepositPlan() + ' is active</span>)';
		}
		
		htmlContent += '</h1>' +
			'<div class="tips">' +
				'Auto deposit your assets\' income into your bank account. This helps you protect your money from attackers while you are away from the game. Subscription is valid for 24hr only. All auto deposits are charged a 10% fee. ' +
			'</div>' +
			'<div class="general">' +
				'<table> ' +
					'<tr>' +
						'<td> Plan 1: Auto deposits 15% of your income</td>' +
						'<td> <input type="submit" value="Subscribe for   $3,000" onClick="GANGSTERS.Treasury.subscribe(1)" /> </td>' +
					'</tr>' +
					'<tr>' +
						'<td> Plan 2: Auto deposits 25% of your income</td>' +
						'<td> <input type="submit" value="Subscribe for   $5,000" onClick="GANGSTERS.Treasury.subscribe(2)" /> </td>' +
					'</tr>' +
					'<tr>' +
						'<td> Plan 3: Auto deposits 50% of your income</td>' +
						'<td> <input type="submit" value="Subscribe for $10,000" onClick="GANGSTERS.Treasury.subscribe(3)" /> </td>' +
					'</tr>' +
				'</table>' +
			'</div>' +
			'<h1>Gold Shop</h1>' +
			'<div class="tips">' +
				'Buy and Sell Gold on the open market for profit. Buy gold when the price is low and sell when the price is high. Prices fluctuate depending on real world gold prices, so keep your eye on the daily news! ' +
				'<H1>****ATTENTION: Gold Shop functions are down temporarily due to the server that returns Gold prices being down. It will be back as soon as possible!****</H2>' +
		
		'</div>' +
			'<div align="center">' +
					'<a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Gold_Shop\', \'Gold Shop\')"><img src="'+GANGSTERS.BASE_URL+'/images/goldshop.jpg"></a><br/>' +
					'<a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Gold_Shop\', \'Gold Shop\')">Enter Gold Shop</a>' +
			'</div>';
		this.m_infoDiv.innerHTML = htmlContent;
	}
	
	Treasury.prototype.subscribe = function(a_plan){
		var l_self = this;
		
		this.m_resultDiv.innerHTML = "Subscribing ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.plan = a_plan;
		makeRequest("auto_deposit",
				function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
				l_params,l_self);
	}
	
	Treasury.prototype.deposit = function(){
		var l_self = this;
		var l_amount = document.getElementById("deposit_amount");
		if(!validateAmount(l_amount.value)){
			this.m_resultDiv.innerHTML = "Please specify a valid amount to deposit!";
			return;
		}

		this.m_resultDiv.innerHTML = "Depositing ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.amount = l_amount.value;
		makeRequest("deposit",
				function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
				l_params,l_self);
	}
	
	Treasury.prototype.withdraw = function(){
		var l_self = this;
		var l_amount = document.getElementById("withdraw_amount");
		if(!validateAmount(l_amount.value)){
			this.m_resultDiv.innerHTML = "Please specify a valid amount to withdraw!";
			return;
		}

		this.m_resultDiv.innerHTML = "Withdrawing ...";
		
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		l_params.amount = l_amount.value;
		makeRequest("withdraw",
				function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
				l_params,l_self);
	}
//end Treasury


// User
    function User(a_userData) {
        // opensocial data
        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_is_owner = false;
        this.m_is_viewer = false;

        // gangsters data
        this.m_gangName = undefined;
        this.m_gangClass = undefined;
        this.m_gangSize = undefined;
        this.m_cash = undefined;
        this.m_cashInBank = undefined;
        this.m_attackStrength = undefined;
        this.m_defenseStrength = undefined;
        this.m_maxProperty = undefined;
        this.m_health = undefined;
        this.m_maxHealth = undefined;
        this.m_adrenaline = undefined;
        this.m_maxAdrenaline = undefined;
        this.m_stamina = undefined;
        this.m_maxStamina = undefined;
        this.m_experience = undefined;
        this.m_percentToNextLevel = undefined;
        this.m_expPointsToNextLevel = undefined;
        this.m_level = undefined;
        this.m_skillPoints = undefined;
        this.m_offerPoints = undefined;
        this.m_secondsToHealthRefresh = undefined;
        this.m_secondsToAdrenalineRefresh = undefined;
        this.m_secondsToStaminaRefresh = undefined;
        this.m_numRequests = undefined;
        this.m_joinedDaysAgo = undefined;
        this.m_income = undefined;
        this.m_upkeep = undefined;
        this.m_partOfViewerGang = undefined;
        this.m_requestedByUser = undefined;
		this.m_reward = undefined;
		this.m_gold = undefined;
		this.m_side = undefined;
		this.m_depositPlan = undefined;
		this.m_isPlanActive = undefined;
		this.m_inviteCount = undefined;

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

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

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

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

    User.prototype.signIn = function(onFinishCallback) {
       if (isValid(this.m_userId)) {
           var l_params = this.constructParamForReq();
           l_params.sign_in = "true";
           makeRequest("sign_in", onFinishCallback, l_params);
       }
    }

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

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

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

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

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

    User.prototype.getShortName = function(){
        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.getField = function(a_key){
        switch(a_key){
            case opensocial.Person.Field.ID: return this.m_userId;
            case opensocial.Person.Field.NAME: return this.m_name;
            case opensocial.Person.Field.AGE: return this.m_age;
            case opensocial.Person.Field.GENDER: return this.m_gender;
            case opensocial.Person.Field.THUMBNAIL_URL: return this.m_thumbnail_url;
            case opensocial.Person.Field.PROFILE_URL: return this.m_profile_url;
        }
        return undefined;
    }

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

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

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

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

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

    User.prototype.setIsViewer = function(a_is_viewer){
        this.m_is_viewer = a_is_viewer;
    }
	
    // gangsters method
    User.prototype.fillSpecificInfoFromXML = function(a_xmlNode){
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"gang_name"))) this.m_gangName = getXMLEncodedStringNodeValue(a_xmlNode,"gang_name"); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"gang_class"))) this.m_gangClass = getXMLEncodedStringNodeValue(a_xmlNode,"gang_class"); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"side"))) this.m_side = getXMLNodeValue(a_xmlNode,"side"); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"plan"))) this.m_depositPlan = getXMLNodeValue(a_xmlNode,"plan"); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"isPlanActive"))) this.m_isPlanActive = getXMLNodeValue(a_xmlNode,"isPlanActive"); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"gang_size"))) this.m_gangSize = parseInt(getXMLNodeValue(a_xmlNode,"gang_size")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"cash"))) this.m_cash = Math.floor(parseFloat(getXMLNodeValue(a_xmlNode,"cash"))); }catch(err){};
	   try{ if(isValid(getXMLNodeValue(a_xmlNode,"gold"))) this.m_gold = parseFloat(getXMLNodeValue(a_xmlNode,"gold")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"cash_in_bank"))) this.m_cashInBank = Math.floor(parseFloat(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,"max_property"))) this.m_maxProperty = parseInt(getXMLNodeValue(a_xmlNode,"max_property")); }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,"adrenaline"))) this.m_adrenaline = parseInt(getXMLNodeValue(a_xmlNode,"adrenaline")); }catch(err){};
       try{ if(isValid(getXMLNodeValue(a_xmlNode,"max_adrenaline"))) this.m_maxAdrenaline = parseInt(getXMLNodeValue(a_xmlNode,"max_adrenaline")); }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_offerPoints = parseInt(getXMLNodeValue(a_xmlNode,"favor_points")); }catch(err){};

       try{ if(isValid(getXMLNodeValue(a_xmlNode,"invite_count"))) this.m_inviteCount = parseInt(getXMLNodeValue(a_xmlNode,"invite_count")); }catch(err){};
	   
       try{ this.m_secondsToHealthRefresh = undefined; if(isValid(getXMLNodeValue(a_xmlNode,"seconds_to_health_refresh"))) this.m_secondsToHealthRefresh = parseInt(getXMLNodeValue(a_xmlNode,"seconds_to_health_refresh")); }catch(err){};
       try{ this.m_secondsToAdrenalineRefresh = undefined; if(isValid(getXMLNodeValue(a_xmlNode,"seconds_to_adrenaline_refresh"))) this.m_secondsToAdrenalineRefresh = parseInt(getXMLNodeValue(a_xmlNode,"seconds_to_adrenaline_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_partOfViewerGang = getXMLNodeValue(a_xmlNode,"part_of_viewer_gang"); }catch(err){};
       try{ this.m_requestedByUser = getXMLNodeValue(a_xmlNode,"requested_by_viewer"); }catch(err){};
	   try{ this.m_reward = getXMLNodeValue(a_xmlNode,"reward"); }catch(err){};
	   
    }

    User.prototype.getGangName = function(){
        return this.m_gangName;
    }

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

    User.prototype.getGangClass = function(){
        return this.m_gangClass;
    }
	
    User.prototype.getSide = function(){
        return this.m_side;
    }

    User.prototype.getGangSize = function(){
        return this.m_gangSize;
    }

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

    User.prototype.getGold = function(){
        return this.m_gold;
    }
	
    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.getMaxProperty = function(){
        return this.m_maxProperty;
    }

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

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

    User.prototype.getAdrenaline = function(){
        return this.m_adrenaline;
    }

    User.prototype.getMaxAdrenaline = function(){
        return this.m_maxAdrenaline;
    }

    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.getOfferPoints = function(){
        return this.m_offerPoints;
    }

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

    User.prototype.getSecondsToAdrenalineRefresh = function(){
        return this.m_secondsToAdrenalineRefresh;
    }

    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.getpartOfViewerGang = function(){
        return getBooleanValue(this.m_partOfViewerGang); 
    }

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

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

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

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

    User.prototype.getReward = function(){
        return this.m_reward;
    }

    User.prototype.getDepositPlan = function(){
        return this.m_depositPlan;
    }
	
    User.prototype.isPlanActive = function(){
        return this.m_isPlanActive;
    }

    User.prototype.getInviteCount = function(){
        return this.m_inviteCount;
    }
	
// end user

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

    this.invalidateCache = invalidateCache;

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

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

    function invalidateCache(){
        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 = {};
		
        switch(m_type){
            case GANGSTERS.MY_REQUESTS: 
            case GANGSTERS.MY_GANG: 
			case GANGSTERS.NEW_USERS:
			case GANGSTERS.MY_GANG_MEMBERS:
			        l_params.user_id = GANGSTERS.VIEWER.getUserId();
			        l_params.cmd = getActionURI(m_type);
			        makeRequest("get_num_users", onGetNumUsers, l_params);
					break;
					
			case GANGSTERS.MY_FRIENDS:
			case GANGSTERS.NON_BACKED_FRIENDS:
			        // just get the number of friends
			        l_params[opensocial.DataRequest.PeopleRequestFields.FIRST] = 0;
			        l_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 0;
			        var l_req = opensocial.newDataRequest();
			        l_req.add(l_req.newFetchPeopleRequest('VIEWER_FRIENDS', l_params), 'numFriends');
			        l_req.send(onGetNumUsers);
					break;
        }
    }

    function onGetNumUsers(a_requestData){
        switch(m_type){
            case GANGSTERS.MY_REQUESTS: 
            case GANGSTERS.MY_GANG: 
			case GANGSTERS.NEW_USERS:
			case GANGSTERS.MY_GANG_MEMBERS:
			        var l_xmlDoc = getResponseData(a_requestData);
			        if(l_xmlDoc != undefined){
			            try{
			                m_totalNumUsers = getXMLNodeValue(l_xmlDoc, "num");
			            }catch(err){}
			        }
					break;
					
			case GANGSTERS.MY_FRIENDS:
			case GANGSTERS.NON_BACKED_FRIENDS:
			        try{
			            m_totalNumUsers = parseInt(a_requestData.get('numFriends').getData().getTotalSize())
			        }catch (err) {
			            m_totalNumUsers = undefined;
			        }

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

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

    function getUsers(a_requiredStart, a_requiredNum, a_finishFetchCallback){

        switch(m_type){
            case GANGSTERS.MY_REQUESTS: 
            case GANGSTERS.MY_GANG: 
			case GANGSTERS.MY_GANG_MEMBERS:
			case GANGSTERS.NEW_USERS:
			        if(m_cachedUsers.length >= m_totalNumUsers || m_cachedUsers.length >= (a_requiredStart + a_requiredNum-1)){
			            a_finishFetchCallback(m_cachedUsers);
			            return;
			        }

			        var l_startIndex = Math.min(m_cachedUsers.length, a_requiredStart);
			        var l_numToFetch = (a_requiredStart + a_requiredNum) - l_startIndex;
			        m_usersFinishCallback = a_finishFetchCallback;

			        var l_params = {};
			        l_params.user_id = GANGSTERS.VIEWER.getUserId();
			        l_params.cmd = getActionURI(m_type);
			        l_params.start = l_startIndex;
			        l_params.num = l_numToFetch;

			        makeRequest("get_users", onLoadUsers, l_params);
					break;
					
			case GANGSTERS.MY_FRIENDS:
			case GANGSTERS.NON_BACKED_FRIENDS:
			        if(a_requiredNum % 40 != 0){
			            //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);

			        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]);
			            }
			        }


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

				        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);
				        });
					}
					break;
        }
    }

    function onLoadFriends(a_startIndex, a_dataResponse){

        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;
        }

        
        if(m_type == GANGSTERS.MY_FRIENDS && isValid(l_queryIdString) && l_queryIdString.length > 0){
            var l_params = {};
            l_params.user_id = GANGSTERS.VIEWER.getUserId();
            l_params.query_ids= l_queryIdString;

            makeRequest("get_app_users",
                    onLoadUsers,
                    l_params);
            return;
        }

        if(isValidFunction(m_usersFinishCallback)){
            var l_tempCallback = m_usersFinishCallback;
            m_usersFinishCallback = undefined;
            l_tempCallback(m_cachedUsers);
        }
    }
	
    function onLoadUsers(a_requestData){
        var l_xmlDoc = getResponseData(a_requestData);
        switch(m_type){
            case GANGSTERS.MY_REQUESTS: 
            case GANGSTERS.MY_GANG: 
			case GANGSTERS.NEW_USERS:
			case GANGSTERS.MY_GANG_MEMBERS:
			        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;
			                }
			            }
			        }
					break;
					
			case GANGSTERS.MY_FRIENDS:
			case GANGSTERS.NON_BACKED_FRIENDS:
			        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){
			                    }
			                }
			            }
			        }
					break;
        }

        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 GANGSTERS.MY_REQUESTS:
                return "request";
            case GANGSTERS.MY_GANG:
                return "my_gang";
            case GANGSTERS.NEW_USERS:
                return "new_gangsters";
            case GANGSTERS.MY_GANG_MEMBERS:
                return "gang_members";
            default:                
                return undefined;
        }
    }
}

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;

        m_tableDiv = document.createElement("div");
        m_parentDiv.appendChild(m_tableDiv);
        m_tableDiv.style.textAlign = "center";
        m_tableDiv.innerHTML = "<br><font color='white'><b>[Loading Users... Please wait.]</b></font>";

        // start and num
        m_userList.getUsers(m_startIndex, m_numUsersPerPage, onGetUsers);
    }

    function onGetUsers(a_userArray){
        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]));
        }
    }
}

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){

        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;
        }

        jumpToPage(1);
    }

    function 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, 4);
    }
}

//Upgrade
	function Upgrade(a_parentDiv){
		this.m_parentDiv = a_parentDiv;

		this.m_resultDiv = document.createElement("div");
		this.m_resultDiv.id = "resultDiv";
		this.m_parentDiv.appendChild(this.m_resultDiv);

		this.m_contentDiv = document.createElement("div");
		this.m_contentDiv.id = "newUsers";
		this.m_parentDiv.appendChild(this.m_contentDiv);		
		
		this.refresh();
	}
	
	Upgrade.prototype.refresh = function(){
		
		this.m_contentDiv.innerHTML = '' +
		'<div id="newUsers">' +
			'<h1>Upgrade (You have '+GANGSTERS.VIEWER.getSkillPoints()+' Research points)</h1>' +
			'<div class="tips">' +
				'Use your Research points to upgrade Defense Power, Attack Strength, Max Courage, Max Health and Max Stamina' +
			'</div>' +
		'</div>' +
		'<div class="categoryTableTitle">' +
				'<table align="center">' +
					'<tr>' +
						'<th>Description</th>' +
						'<th>Requirement</th>' +
						'<th>Reward</th>' +
						'<th>Upgrade</th>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Upgrade Defense Power</span></td>' +
						'<td>1 Research points</td>' +
						'<td>+1 Defense Strength</td>' +
						'<td><input type="submit" value="Upgrade" onClick="GANGSTERS.Upgrade.upgrade(\'defense_strength\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Upgrade Attack Strength</span></td>' +
						'<td>1 Research points</td>' +
						'<td>+1 Attack Strength</td>' +
						'<td><input type="submit" value="Upgrade" onClick="GANGSTERS.Upgrade.upgrade(\'attack_strength\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Upgrade Max Courage</span></td>' +
						'<td>1 Research points</td>' +
						'<td>+1 Max Courage</td>' +
						'<td><input type="submit" value="Upgrade" onClick="GANGSTERS.Upgrade.upgrade(\'max_adrenaline\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Upgrade Max Health</span></td>' +
						'<td>1 Research points</td>' +
						'<td>+10 Max Health</td>' +
						'<td><input type="submit" value="Upgrade" onClick="GANGSTERS.Upgrade.upgrade(\'max_health\')"></td>' +
					'</tr>' +
					'<tr>' +
						'<td><span class="description">Upgrade Max Stamina</span></td>' +
						'<td>2 Research points</td>' +
						'<td>+1 Max Stamina</td>' +
						'<td><input type="submit" value="Upgrade" onClick="GANGSTERS.Upgrade.upgrade(\'max_stamina\')"></td>' +
					'</tr>' +
				'</table>' +
		'</div>' +
		'<div id="newUsers">' +
			'<h1>Start Over</h1>' +
			'<div class="tips">' +
				'Do you want to start over?<br/>Warning! All your stats, cash, assets and equipment will be reset except your Allies and unused Offer Points. Be very sure before you click on the button!<br/><div class="startover"><a href="#top" onClick="GANGSTERS.Upgrade.startOver()">Start Over</a></div>' +
			'</div>' +
		'</div>';
	}
	
	Upgrade.prototype.startOver = function() {
		this.m_resultDiv.innerHTML = 'Are you sure to reset the game?<br/>You will loose all your assets, money, weapons and stats.<br/><div class="button"><a href="#top" onClick="GANGSTERS.Upgrade.doStartOver()">Yes</a><br/></div><div class="button"><a href="#top" onClick="GANGSTERS.Upgrade.cancel()">No</a></div>';
	}
	
	Upgrade.prototype.cancel = function() {
		this.m_resultDiv.innerHTML = '';
	}
	
	Upgrade.prototype.doStartOver = function(){	
		var l_self = this;
		this.m_resultDiv.innerHTML = "Starting over ... ";
		var l_params = {};
		l_params.user_id = GANGSTERS.VIEWER.getUserId();
		makeRequest("start_over",
		function(a_response){main();},
		l_params,l_self);
	}
	
	Upgrade.prototype.upgrade = function(a_attribute){	
        var l_self = this;
        if(GANGSTERS.VIEWER.getSkillPoints() > 0){
		   l_self.m_resultDiv.innerHTML = "Upgrading ... ";
		   var l_params = {};
		   l_params.user_id = GANGSTERS.VIEWER.getUserId();
		   l_params.attribute = a_attribute;
		   makeRequest("increase_attribute",
			function(a_response){handleResult(a_response, l_self.m_resultDiv, function(){l_self.refresh();})},
			l_params,l_self);
        } else {
			l_self.m_resultDiv.innerHTML = "Insufficent Research points";
        }
	}
//end Upgrade

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 viewProfile(a_userId){
    window.open(GANGSTERS.CANVAS_URL + "appParams=%7B%22"+GANGSTERS.SHOW_USER_ID+"%22%3A%22"+a_userId+"%22%7D");
}


//Weapons
	function Weapons(a_parentDiv){
		this.m_parentDiv = a_parentDiv;
		this.m_parentDiv.innerHTML = '' +	
		'<div id="newUsers">' +
			'<h1>Weapons Factories</h1>' +
			'<div class="tips">' +
				'Browse the various factories to purchase weapons for your Army. Land, Sea, Air and Special Operations units crutial to attack and defend against rival Nations. The best combination of weapons can make it or break it in a battle. <br /><h2>More advanced Weapon factories are unlocked at higher RANKS! So, to access more powerful weapons, increase your RANK.</h2>' +
			'</div>' +
			'<div class="category">' +
			'<table align="center">' +
				'<tr>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Melee Weapons\')"><img src="'+GANGSTERS.BASE_URL+'/images/infantry.jpg"></a></td>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Guns Ammo\')"><img src="'+GANGSTERS.BASE_URL+'/images/land.jpg"></a></td>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Auto Dealers\')"><img src="'+GANGSTERS.BASE_URL+'/images/air.jpg"></a></td>' +
				'</tr>' +
				'<tr>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Melee Weapons\')">Infantry</td>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Guns Ammo\')">Land Units</a></td>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Auto Dealers\')">Air Units</td>' +
				'</tr>' +
				'<tr>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Armor Store\')"><img src="'+GANGSTERS.BASE_URL+'/images/sea.jpg"></a></td>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Pet Store\')"><img src="'+GANGSTERS.BASE_URL+'/images/special.jpg"></a></td>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'General Store\')"><img src="'+GANGSTERS.BASE_URL+'/images/tactical.jpg"></a></td>' +
				'</tr>' +
					'<tr>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Armor Store\')">Sea Units</a></td>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'Pet Store\')">Special Forces</a></td>' +
					'<td><a href="#top" onClick="GANGSTERS.menuDiv.navigateToDynamicTab(\'Shops_Category\', \'General Store\')">Tactical Weapons</a></td>' +
				'</tr>' +
			'</table>' +
			'</div>' +
		'</div>' +
		'<div id="invite">' +
			'<h1>Total Upkeep for Armed Forces!</h1>' +
			'<div class="tips">' +
				'You are spending a total of, <span class="redText"> $' + number_format(GANGSTERS.VIEWER.getUpkeep()) + '</span> every 60 minutes.</span> That\'s just the cost of maintaining the quality of your Armed Forces.' +
			'</div>' +
		'</div>';
	}
//end Weapons

