var os_token = MyOpenSpace.MySpaceContainer.OSToken;
var os = opensocial.Container.get();
window.osContainer = opensocial.Container.get();
gadgets.util.registerOnLoadHandler(init);

//VARIABLES
var loaded		= false;
var pageId		= 0;
var showOnly	= -1;
var commentId	= new Array(0,0,0,0,0);
commentId[-1]	= 0;
var replyId		= 0;
var Refreshing	= 0;
//USER CACHED INFO!!!!
var fid			= 0;
var picture		= "";
var gender		= -1;
var money		= 0;
var owner		= undefined;
var tickets		= 0;
var rides		= 0;
var totalrides	= 0;
var adds		= new Array();
var addsCnt		= 0;
var totalfriends= 100;
var interests	= "";
var name 		= "";
//HTML
var trainHTML	= "";
var homeHTML	= "";
var topHTML		= "<h1>Loading... Please Wait</h1><br><img src='http://i19.photobucket.com/albums/b190/erb2011/ajax-loader.gif'/>";
var topTodayHTML= "<h1>Loading... Please Wait</h1><br><img src='http://i19.photobucket.com/albums/b190/erb2011/ajax-loader.gif'/>";
var siteName	= "FriendTrain";
var Message		= "<center><a href='http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=418399031'><img src='http://friendtrainapp.com/image/friendtrain.gif'/></a><br>[sender] would like you to install the application [app]. It's the best way to expand your friends list and meet cool new people!<br><br><a href='http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=418399031'><img src='http://friendtrainapp.com/image/friendtrain.gif'/></a></center>";

var People		= new Array();
var comments	= new Array();

function init() {
	//if(top.location == document.location){
	//	document.location = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=117798";
	//	return;
	//}
	setTimeout('timeout()', 25000);
	try{
		var req = os.newDataRequest()
		var param = {};
		param[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
				opensocial.Person.Field.ID,
				MyOpenSpace.Person.Field.GENDER,
				opensocial.Person.Field.THUMBNAIL_URL ];
		var dReq = os.newFetchPersonRequest(
				opensocial.DataRequest.PersonId.VIEWER, param);
		var profileDetails = [MyOpenSpace.Person.Field.ID, MyOpenSpace.Person.Field.POSTALCODE]; 
		var allFriends = {};
		allFriends[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = profileDetails;
		allFriends[opensocial.DataRequest.PeopleRequestFields.FIRST] = 1;   
		allFriends[opensocial.DataRequest.PeopleRequestFields.MAX] = 36;
	
		req.add(os.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, allFriends), "group1");
		req.add(dReq);
		req.send(load);
	}
	catch(e)
	{
		showError(e);
	}
}
function timeout() {
	if(loaded == false)
	{
		document.getElementById('right').innerHTML = "";
		showError("The remote server could not be reached... usually this error appears during peak times when the server is slow. You can close this error and wait a little longer.");
	}
}
function load(response) {
	try{
		if(response.hadError()){
			loaded = true;
			
			if(response.get(opensocial.DataRequest.PersonId.VIEWER).getErrorMessage() == "Invalid Opensocial token. Invalid length for a Base-64 char array.")
			{	
				showRefresh();
				return;
			}
			
			showAddApp();
			return;
		}
		totalfriends = response.get("group1").getData().getTotalSize();
		owner = response.get(opensocial.DataRequest.PersonId.VIEWER).getData();
		fid = owner.getField(opensocial.Person.Field.ID);
		switch(owner.getField(MyOpenSpace.Person.Field.GENDER))
		{
			case "Male":
				gender = 0;
				break;
			case "Female":
				gender = 1;
				break;		
		}
		picture = owner.getField(opensocial.Person.Field.THUMBNAIL_URL);
		name = owner.getDisplayName();
		doRequest(1);
		document.getElementById("menu").innerHTML = '<ul>	<li><a href="#" onclick="showPage(2,1)">Home </a></li>	<li><a href="#" onclick="showPage(3,1)">The Train </a></li>	<li><a href="#" onclick="showPage(12,1)">Send Photo Comments </a></li>	<li><a href="#" onclick="showPage(15)">Shop </a></li><li><a href="#" onclick="showPage(4,1)">Invite Friends </a></li>	<li><a href="#" onclick="showPage(5,1)">Get Extra Tickets </a></li>	<li><a href="#" onclick="showPage(7,1)">Top Users</a></li> <li><a href="#" onclick="showPage(8,1)">Faq </a></li>	<li><a href="#" onclick="showPage(9,1)">Interests </a></li></ul>';
	}
	catch(e)
	{
		showError(e);
	}
}

function sendBulletin(){
    var target = MyOpenSpace.PostTo.Targets.BULLETINS;
    var message = opensocial.newMessage("<center><a href='http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=418399031'><img src='http://friendtrainapp.com/image/friendtrain.gif'/></a><br>I'm inviting you to add the application "+siteName+"!<br>It's the best way to expand your friends list and meet cool new people!<br><br><a href='http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=418399031'><b>Click Here To Join!</b><br><img src='http://friendtrainapp.com/image/friendtrain.gif'/></a></center>");
    message.setField(opensocial.Message.Field.TITLE, "New Myspace App! The Best way to get Friends Fast!");
    message.setField(opensocial.Message.Field.TYPE, target);
    os.postTo(os_token, message, owner, BulletinInviteCallback);
}
function sendAppAdd(friend_id){
	invite_id = friend_id;
	var message = opensocial.newMessage(Message);
	opensocial.requestShareApp(friend_id, message, FriendInviteCallback);
}
function FriendInviteCallback(responseCode){	 
	if(responseCode==MyOpenSpace.PostTo.Result.ERROR){
		setStatus("Sorry an unexpected error occured.");
	}
	else if(responseCode==MyOpenSpace.PostTo.Result.CANCELLED){
		setStatus("Sorry an unexpected error occured.");
	}
	else if(responseCode ==MyOpenSpace.PostTo.Result.SUCCESS){
		setStatus("You have successfully invited 1 friend!");
		doRequest(6, invite_id);
	}
}
function BulletinInviteCallback(responseCode){	 
	if(responseCode==MyOpenSpace.PostTo.Result.ERROR){
		setStatus("Sorry an unexpected error occured.");
	}
	else if(responseCode==MyOpenSpace.PostTo.Result.CANCELLED){
		setStatus("Sorry an unexpected error occured.");
	}
	else if(responseCode ==MyOpenSpace.PostTo.Result.SUCCESS){
		setStatus("You have successfully posted the bulletin!");
		doRequest(7);
	}
}
function install(step,installing) {
	setStatus('');
	switch(step){
		case 1:
			showPage(9);
			document.getElementById('stats').innerHTML = "";
			break;
		case 2:
			interests = "";
			for(var x = 1; x < 12; x++) {
				if(document.getElementById(x).checked == true){
					interests += "-"+x+"-";
				}
			}
			if(interests == ""){
				setStatus('Sorry, you must select your interests!');
				return;
			}
			else
				doRequest(8);
			if(installing != false){
				showPage(10);
			} else{
				setStatus('You have successfully selected your interests!');
				doRequest(1);
			}
			break;
		case 3:
			showPage(11);
			break;
		case 4:
			showPage(14);
			break;
		case 5:
			show();
			break;
	}
}
function show() {
	if(interests == ""){
		install(1);
	}
	else if(Refreshing == 0){
		showPage(1);
		showPage(2);
	}
	else{
		showPage(1);
		showPage(3);
	}
}
function showPage(id,id2,id3) {
	if((interests == "" && id2 == 1) || (loaded == false && id2 == 1))
		return;
	try{
		//if(document.getElementById('left').style.visibility == "hidden"){
		//	document.getElementById('right').style.width = "580px";
		//	document.getElementById('left').style.visibility = "visible";
		//}
		switch(id){
			//showStats
			case 1:
				document.getElementById('stats').innerHTML = "<center><br><img src='" + picture.replace("s_", "m_") + "'/><table width='80%' id='settings'><tr><td>Tickets Left: </td><td>"+tickets+"</td></tr><tr onmouseover=\"tooltip.show('<strong>Cash:</strong><br>Cash can be obtained by sending other users photo comments. The link is in the Navigation bar above.');\" onmouseout=\"tooltip.hide();\"><td>Cash: </td><td>"+addCommas(money)+"</td></tr><tr><td>Rides Today: </td><td>"+rides+"</td></tr><tr><td>Total Rides: </td><td>"+totalrides+"</td></tr></table><br><h3><a href='#' onclick='doRequest(2);'><span>Ride The Train</a></h3><h3><span id='refreshL'><a href='#' onclick='doRequest(1);'>Refresh</a></span></h3></center>";
				break;
			//showHome
			case 2:
				homeHTML = "<center><h2>News</h2>";
				homeHTML += "<b>Monday, January 5th, 2009</b><br>I think I have solved the Unexpected errors on loading. It seems that showing each user's comments on the Myspace homepage took up WAY to many resources. For now I have removed them. After Myspace OK's my latest changes to the Home Canvas, you will notice a \"Click Here To Load Your Comments\" link. This link will load your comments only when requested saving a lot of work for the servers. Although your comments will not show instantly, your stats will load automaticly.<br>I Hope you all understand!<br><a href='http://forum.myspace.com/index.cfm?fuseaction=messageboard.viewThread&entryID=7714038&categoryID=0&type=friendForum&friendID=418399031&IsSticky=0' target='_blank'>Read More</a><br><br>";
				homeHTML += "<b>Sunday, January 4th, 2009</b><br>I have hopefully fixed the errors which caused the server to load extremely slow. I have also added a notification when you receive your daily tickets. <br>PLEASE NOTE: YOU CAN ONLY GET DAILY TICKETS IF YOU HAVE LESS THEN 10 TICKETS ALREADY!<br><a href='http://forum.myspace.com/index.cfm?fuseaction=messageboard.viewThread&entryID=7623171&categoryID=0&type=friendForum&friendID=418399031&IsSticky=0&Mytoken=E9A2DA74-4652-47E1-ABE2A93F8BE7797E906426990' target='_blank'>Read More</a><br><br>";
				homeHTML += "<b>Tuesday, December 9th, 2008</b><br>I have fixed the bug with newlines in comments. If you had received a comment and someone typed enter in the box, it caused the script to error out. This has since been fixed. Thanks to everyone who reported it!<br><a href='http://forum.myspace.com/index.cfm?fuseaction=messageboard.viewThread&entryID=6042179&categoryID=0&type=friendForum&friendID=418399031&IsSticky=0&Mytoken=1234C65A-0DB5-4E00-9E27819CB42A3DA125309646' target='_blank'>Read More</a><br><br>";
				//homeHTML += "<b>Monday, December 8th, 2008</b><br>I have added quite a bit today xD<br>1. You can now view only Male/Female on the Photo comments.<br>2. You can recieve up to $100 a day by sending photo comments.<br>3. I have added the shop, where you can buy tickets for $100 each. (More items to come).<br>4. I have added the code to Warn users who are about to be banned.<br>5. I have combined the Top users into 1 Page.<br><a href='http://forum.myspace.com/index.cfm?fuseaction=messageboard.viewThread&entryID=6001810&categoryID=0&type=friendForum&friendID=418399031&IsSticky=0' target='_blank'>Read More</a><br><br>";
				//homeHTML += "<b>Monday, December 8th, 2008</b><br>I have fixed the bug that prevented some users from logging in. This was caused by them receiving a comment with an Apostrophe or Quote. I had to delete maybe 100 comments, but this bug will no longer occur!<br><a href='http://forum.myspace.com/index.cfm?fuseaction=messageboard.viewThread&entryID=5983187&categoryID=0&type=friendForum&friendID=418399031&IsSticky=0' target='_blank'>Read More</a><br><br><h2>Comments</h2><div id='commentsBox'>";
				homeHTML += "<h2>Comments</h2><div id='commentsBox'><table width='80%' class='comments'><tr><td><b>Time</b></td><td><b>From</b></a></td><td><b>Comment</b></td><td><b>Rating</b></td><td><b>Etc</b></td></tr>";
				for(var x = 0; x < comments.length; x++){
					homeHTML += "<tr><td>"+comments[x].time+"</td><td><a href='http://myspace.com/"+comments[x].from+"' target='_blank'><img src='"+comments[x].picture+"' width=60px height=60px><br>"+comments[x].name+"</a></td><td>"+comments[x].comment+"</td><td>Rating: "+comments[x].rating+"/10</td><td><a href='#' onclick='showPage(13,"+comments[x].from+",\""+comments[x].picture+"\");'>Reply</a><br><a href='#' onclick='doRequest(12,"+comments[x].id+");'>Delete</a><br><a href='#' onclick='doRequest(9,"+comments[x].id+","+comments[x].from+");'>Report</a></td></tr>";
				}
				homeHTML += "</table></div></center>";
				document.getElementById('right').innerHTML = homeHTML;
				break;
			//showTrain
			case 3:
				var x = 0;
				trainHTML = "";
				for(var y = 0; y < 90; y++){
					trainHTML += "<a href='http://friends.myspace.com/index.cfm?fuseaction=invite.addfriend_verify&friendID="+People[y].Id+"' target='_blank'><img class='friend' src='"+People[y].Picture+"' width=60 height=60 border='0' " +(People[y].Id == fid ? "style='border-style:solid;border-width: 2px;'" : "") + "></a>";
					if (x == 8) {
						trainHTML += "<br>";
						x = 0;
					} else {
						x++;
					}
				}
				document.getElementById('right').innerHTML = "<center><h2>Add Some Friends With Similar Interests!</h2><br>" + trainHTML + "<br><br><input value='Post The Bulletin!' type='button' class='button2' onclick='sendBulletin();'></center>";
				break;	
			//showTickets
			case 4:
				document.getElementById('right').innerHTML = "<center><h2>Invite Friends.</h2><br><div id='FriendSelect'></div><div id='FriendNav'><a href='#' onclick='loadFriends(2);'>-- Next -></a></div></center>";
				loadFriends(1);	
				break;
			//showVendor
			case 5:
				//document.getElementById('right').style.width = "870px";
				//document.getElementById('left').style.visibility = "hidden";
				document.getElementById('right').innerHTML = "<center><h2>Complete offers below to earn Tickets from the Ticket Vendor.</h2>(Extra Tickets From this page are NOT necessary for game play or game advancement)<br><br>The fastest and easiest offers are under the \"Free\" Section.<br>They require the least amount of effort. Get free Tickets in seconds!<br><iframe src='http://pub.myofferpal.com/8515aabf2ef9c20667c6b317baa34c42/showoffers.action?snuid="+fid+"' frameborder='0' width='600' height='2200' scrolling='no'></iframe>";
				break;
			//showTop
			case 7:
				document.getElementById('right').innerHTML = "<center><h2>Top Riders Overall</h2>(<a href='#' onclick='doRequest(4);'>Refresh</a>)<br>"+topHTML+"</center>";
				if(topHTML == "<h1>Loading... Please Wait</h1><br><img src='http://i19.photobucket.com/albums/b190/erb2011/ajax-loader.gif'/>")
					doRequest(4);
				break;
			//showFAQ
			case 8:
				document.getElementById('right').innerHTML = "<center><h2>Faq</h2><a href='#1'>What are Tickets?</a><BR><a href='#2'>How do I get Tickets?</a><BR><a href='#3'>How many Tickets can I get?</a><BR><a href='#4'>What is the Train?</a><BR><a href='#5'>How do I ride the Train?</a><BR><a href='#6'>How long does the ride last?</a><BR><a href='#7'>What is the point in riding?</a><BR><a href='#8'>What is the Ticket Vendor?</a><BR><a href='#9'>How are the Top determined?</a><BR><a href='#10'>I should be on the Top and I'm not?</a><BR><a href='#11'>Missing Points From a Completed Offer?</a><BR><a href='#12'>When do I get my 5 tickets per day?</a><BR><a href='#13'>My question is not listed here.</a><BR><br><br></center><p class='heading_blue'><a name='1'><b>What are Tickets?</b></p></a><p style='padding-left: 15px'>Tickets allow you to ride the train. Each ride consumes 1 Ticket.</p><p class='heading_blue'><a name='2'><b>How do I get Tickets?</b></p></a><p style='padding-left: 15px'>You get 5 free tickets every day at 12 AM EST and for completing offers.</p><p class='heading_blue'><a name='3'><b>How many Tickets can I get?</b></p></a><p style='padding-left: 15px'>You can theoretically get 5 Tickets per day 5 free every night plus any you may get from completing offers.</p><p class='heading_blue'><a name='4'><b>What is the Train?</b></p></a><p style='padding-left: 15px'>The Train is a list of users who have recently spent a Ticket.</p><p class='heading_blue'><a name='5'><b>How do I ride the Train?</b></p></a><p style='padding-left: 15px'>Click the 'Ride The Train' link under your stats.</p><p class='heading_blue'><a name='6'><b>How long does the ride last?</b></p></a><p style='padding-left: 15px'>This depends on how many people are spending tickets. The more people, the faster the ride. You should still receive a similar amount of requests, but at a faster rate.</p><p class='heading_blue'><a name='7'><b>What is the point in riding?</b></p></a><p style='padding-left: 15px'>The point in riding is being featured in order to get more friend requests.</p><p class='heading_blue'><a name='8'><b>What is the Ticket Vendor?</b></p></a><p style='padding-left: 15px'>The Ticket Vendor is a list of offers you can complete in order to receive extra tickets.</p><p class='heading_blue'><a name='9'><b>How are the Top determined?</b></p></a><p style='padding-left: 15px'>The top are determined based on the amount of rides they have. Both Today (Top Today) and in total (Top Overall).</p><p class='heading_blue'><a name='10'><b>I should be on the Top and I'm not?</b></p></a><p style='padding-left: 15px'>Make sure you are looking at the right list. And verify the amount of rides.</p><p class='heading_blue'><a name='11'><b>Missing Points From a Completed Offer?</b></p></a><p style='padding-left: 15px'>To access the customer support page <a href='http://74.86.165.130/pending_s.php?h=cfctypxlikndripi.49315608551&uid="+fid+"&gender=Male&age=20' target='_blank'>Click Here</a></p><p class='heading_blue'><a name='12'><b>When do I get my 5 tickets per day?</b></p></a><p style='padding-left: 15px'>The site awards the free tickets everyday at 12AM EST. This is also when the 5 invites resets so you can invite more people.</p><p class='heading_blue'><a name='13'><b>My question is not listed here.</b></p></a><p style='padding-left: 15px'>If your question was not answered, ask <a href='http://forum.myspace.com/index.cfm?fuseaction=messageboard.viewcategory&type=friendForum&friendID=418399031&MyToken=fd07002b-3a5e-47de-ad0d-43a5371964b8' target='_blank'>here</a></p></center>";			break;		
				break;
			//showInterests
			case 9:
				var html =	"";
				if(interests == ""){
					html	+=	"<center><h2>Step 1: Select Your Interests</h2>FriendTrain will give you targeted results and only show friends who have similar interests! This is useful when only wanting a few friends for certain purposes such as applications!";				
				}
				else
					html	+=	"<center><h2>Select Your Interests</h2>FriendTrain will give you targeted results and only show friends who have similar interests! This is useful when only wanting a few friends for certain purposes such as applications!";
				html	+=	'<table border="0" width="80%" id="interests" align="center"><tr><td><INPUT TYPE=CHECKBOX ID="1"'+(interests.contains("-1-") ? ' checked value="true"' : '')+'></td><td>Apps</td>';
				html	+=	'<td><INPUT TYPE=CHECKBOX ID="2"'+(interests.contains("-2-") ? ' checked value="true"' : '')+'></td><td>Auto</td>';
				html	+=	'<td><INPUT TYPE=CHECKBOX ID="3"'+(interests.contains("-3-") ? ' checked value="true"' : '')+'></td><td>Books</td></tr>';
				html	+=	'<tr><td><INPUT TYPE=CHECKBOX ID="4"'+(interests.contains("-4-") ? ' checked value="true"' : '')+'></td><td>Fashion</td>';
				html	+=	'<td><INPUT TYPE=CHECKBOX ID="5"'+(interests.contains("-5-") ? ' checked value="true"' : '')+'></td><td>Health + Exercise</td>';
				html	+=	'<td><INPUT TYPE=CHECKBOX ID="6"'+(interests.contains("-6-") ? ' checked value="true"' : '')+'></td><td>Miscellaneous</td></tr>';
				html	+=	'<tr><td><INPUT TYPE=CHECKBOX ID="7"'+(interests.contains("-7-") ? ' checked value="true"' : '')+'></td><td>Movies</td>';
				html	+=	'<td><INPUT TYPE=CHECKBOX ID="8"'+(interests.contains("-8-") ? ' checked value="true"' : '')+'></td><td>Music</td>';
				html	+=	'<td><INPUT TYPE=CHECKBOX ID="9"'+(interests.contains("-9-") ? ' checked value="true"' : '')+'></td><td>Sports</td></tr>';
				html	+=	'<tr><td><INPUT TYPE=CHECKBOX ID="10"'+(interests.contains("-10-") ? ' checked value="true"' : '')+'></td><td>Television</td>';
				html	+=	'<td><INPUT TYPE=CHECKBOX ID="11"'+(interests.contains("-11-") ? ' checked value="true"' : '')+'></td><td>Video Games</td>';
				if(interests == "")
					html	+=	'<td></td></tr></table><br><input value="Next" type="button" class="button" onclick="install(2);"></h1>';
				else
					html	+=	'<td></td></tr></table><br><input value="Submit" type="button" class="button" onclick="install(2,false);"></h1>';				
				html	+=	"</center>";
				document.getElementById('right').innerHTML = html;
				break;
			//showAddus
			case 10:
				var html =	"<center><h2>Step 2: Add us!</h2><br><br>";
				html	+=	'<h1><a href="http://friends.myspace.com/index.cfm?fuseaction=invite.addfriend_verify&friendID=418399031" target="_blank" onclick="install(3);">Click Here To Add Us!</a></h1>';
				html	+=	'<br><br><input value="Skip" type="button" class="button" onclick="install(3);">';
				html	+=	"</center>";
				document.getElementById('right').innerHTML = html;
				break;
			//showSettingsCheck
			case 11:
				var html =	"<center><h2>Step 3: Check your account settings!</h2><br>Please double check the following settings to ensure you get the maximum amount of friend requests possible!<br><table width='85%' class='settings'>";
				html	+=	'<tr><td>1.</td><td>Go to <a href="http://profileedit.myspace.com/index.cfm?fuseaction=accountSettings.spam" target="_blank">http://profileedit.myspace.com/index.cfm?fuseaction=accountSettings.spam</a>.</td></tr>';
				html	+=	'<tr><td>2.</td><td>Under "Friend Requests" uncheck the box that says "Require last name or email address".</td></tr>';
				html	+=	'<tr><td>3.</td><td>Under "Friend Requests" uncheck the box that says "Require CAPTCHA".</td></tr>';
				html	+=	'<tr><td>4.</td><td>Under "Friend Requests" check the box that says "Allow bands to send friend requests".</td></tr>';
				html	+=	'<tr><td>5.</td><td>Under "Friend Requests" check the box that says "Allow filmmakers to send friend requests".</td></tr>';
				html	+=	'<tr><td>6.</td><td>Under "Friend Requests" check the box that says "Allow comedians to send friend requests".</td></tr>';
				html	+=	'</table><br>When you are done, it should like like this:<br><img src="http://i19.photobucket.com/albums/b190/erb2011/friendtrain/CAPTCHAsettings.gif"></img>';
				html	+=	'<br><br><input value="Done" type="button" class="button" onclick="install(4);">';
				html	+=	"</center>";
				document.getElementById('right').innerHTML = html;
				break;
			//PhotoComments
			case 12:
				if(People[commentId[showOnly]].Id == fid)
					commentId[showOnly]++;
				if(showOnly != -1)
				{
					while(People[commentId[showOnly]].Gender != showOnly)
					{
						commentId[showOnly]++;
						if(commentId[showOnly] > 88)
						{
							var html =	"<center><h2>Send Some Photocomments!</h2>";
							html	+=	"There are no more people left to comment! Try to refresh the train.";
							document.getElementById('right').innerHTML = html;
							return;
						}
					}
				}
				if(commentId[showOnly] > 88)
				{
					var html =	"<center><h2>Send Photo Comments!</h2>";
					html	+=	"There are no more people left to comment! Try to refresh the train.";
					document.getElementById('right').innerHTML = html;
					return;
				}
				var html =	"<center><h2>Send Some Photocomments!</h2>";
				html	+=	"<div width='100%' align='right'>Show <select onchange='clicker(this)'><option value='-1'"+(showOnly == -1 ? " selected" : "")+">Everyone</option><option value='0'"+(showOnly == 0 ? " selected" : "")+">Men</option><option value='1'"+(showOnly == 1 ? " selected" : "")+">Women</option></select></div>";
				html	+=	"<img src='"+People[commentId[showOnly]].Picture.replace("s_", "l_")+"'></img><br><input value='Report' type='button' class='button' onclick='doRequest(11,"+People[commentId[showOnly]].Id+");'></input><input value='Skip' type='button' class='button' onclick='commentId[showOnly]++;showPage(12);'></input><input value='Add' type='button' class='button' onclick='window.open(\"http://friends.myspace.com/index.cfm?fuseaction=invite.addfriend_verify&friendID=\"+"+People[commentId[showOnly]].Id+",\"_blank\",\"\")'><br>";
				html	+=	"<form name='myform' action='#'><table width='80%'><tr><td>Comment: </td><td><textarea id='commentText' cols='45' rows='4'></textarea><br><small>Sending Spam in the post will result in a ban from this application.</small></td></tr>";
				html	+=	"<tr><td>Rating</td><td><Input type='radio' Name='commentRating' Value='1'>1 <Input type='radio' Name='commentRating' Value='2'>2 <Input type='radio' Name='commentRating' Value='3'>3 <Input type='radio' Name='commentRating' Value='4'>4 <Input type='radio' Name='commentRating' Value='5'>5 <Input type='radio' Name='commentRating' Value='6'>6 <Input type='radio' Name='commentRating' Value='7'>7 <Input type='radio' Name='commentRating' Value='8'>8 <Input type='radio' Name='commentRating' Value='9'>9 <Input type='radio' Name='commentRating' Value='10'>10 </td></tr>";
				html	+=	"<tr><td></td><td><input value='Submit' type='button' class='button' onclick='submitComment();'></td></tr></table></form></center>";
				document.getElementById('right').innerHTML = html;
				break;
			//Reply
			case 13:
				replyId = id2;
				var html =	"<center><h2>Reply</h2>";
				html	+=	"<img src='"+id3.replace("s_", "l_")+"' id='commentImg'></img><br>";
				html	+=	"<form name='myform' action='#'><table width='80%'><tr><td>Comment: </td><td><textarea id='commentText' cols='45' rows='4'></textarea></td></tr>";
				html	+=	"<tr><td>Rating</td><td><Input type='radio' Name='commentRating' Value='1'>1 <Input type='radio' Name='commentRating' Value='2'>2 <Input type='radio' Name='commentRating' Value='3'>3 <Input type='radio' Name='commentRating' Value='4'>4 <Input type='radio' Name='commentRating' Value='5'>5 <Input type='radio' Name='commentRating' Value='6'>6 <Input type='radio' Name='commentRating' Value='7'>7 <Input type='radio' Name='commentRating' Value='8'>8 <Input type='radio' Name='commentRating' Value='9'>9 <Input type='radio' Name='commentRating' Value='10'>10 </td></tr>";
				html	+=	"<tr><td></td><td><input value='Submit' type='button' class='button' onclick='submitComment2();'></td></tr></table></form></center>";
				document.getElementById('right').innerHTML = html;
				break;
			//sendBulletin
			case 14:
				var html =	"<center><h2>Step 4: Post the Bulletin!</h2><br>Do us a favor, Tell all of your friends about this awesome new app!<br>More users means more friend requests for everyone.<br><br>";
				html	+=	"<input value='Post The Bulletin!' type='button' class='button2' onclick='sendBulletin();install(5);'>";
				html	+=	'<br><br><input value="Skip" type="button" class="button" onclick="install(5);">';
				html	+=	"</center>";
				document.getElementById('right').innerHTML = html;
				break;
			case 15:
				var html =	"<center><h2>Shop</h2>";
				html	+=	"<table width='575px' id='shop' class='shop'><tr>";
				html	+=	"<td><b>Item</b></td><td><b>Cost</b></td><td><b>Buy</b></td></tr>";
				html	+=	"<tr><td>1 Ticket</td><td><font color='green'>$100</font></td><td><input type='button' value='Buy' class='button' onclick='doRequest(14,1);'></td></tr>";
				html	+=	"</table>";
				document.getElementById('right').innerHTML = html;
     			break;
		}
	}
	catch(e)
	{
		showError(e+ "<br>ErrorType: 1");
	}
}
document.write = function(text)
{
	document.getElementById('right').innerHTML = text;
}
function submitComment() {
	commentCache = document.getElementById('commentText').value;
	if(commentCache == ""){
		setStatus('Please enter a comment!');	
		return;
	}
	if(commentCache.length < 6){
		setStatus('Please enter an actual comment!');
		return;
	}
	if(commentCache.length > 250){
		setStatus('Your comment is too long!');
		return;
	}
	chosen = "";
	len = document.myform.commentRating.length;

	for (i = 0; i <len; i++) {
		if (document.myform.commentRating[i].checked) {
		chosen = document.myform.commentRating[i].value;
		}
	}
	
	if (chosen == "") {
		setStatus('No rating chosen');
		return;
	}
	doRequest(10,People[commentId[showOnly]].Id,chosen);
	commentId[showOnly]++;
	showPage(12,commentId[showOnly]);
}
function submitComment2() {
	commentCache = document.getElementById('commentText').value;
	if(commentCache == ""){
		setStatus('Please enter a comment!');	
		return;
	}
	if(commentCache.length > 250){
		setStatus('Your comment is too long!');
		return;
	}
	chosen = "";
	len = document.myform.commentRating.length;

	for (i = 0; i <len; i++) {
		if (document.myform.commentRating[i].checked) {
		chosen = document.myform.commentRating[i].value;
		}
	}
	
	if (chosen == "") {
		setStatus('No rating chosen');
		return;
	}
	doRequest(10,replyId,chosen);
	showPage(2);
}
function setRefresh(state) {
	try{
		if(state == 0)
			document.getElementById('refreshL').innerHTML = "<a href='#' onclick='doRequest(1);'>Refresh</a>";
		else{
			document.getElementById('refreshL').innerHTML = "Refreshing...";
			commentId	= new Array(0,0,0,0,0);
			commentId[-1]	= 0;
			Refreshing++;
		}
	}catch(e){}
}
function setStatus(status) {
	document.getElementById('status').innerHTML = "<center>"+status+"</center>";
}
function setStatus2(status) {
	document.getElementById('status').innerHTML = "<center>"+status+"</center>";
}
function showError(e) {
	document.getElementById('light').style.display='block';
	document.getElementById('fade').style.display='block';		
	document.getElementById('light').innerHTML="<table><tr><td><img src='http://i19.photobucket.com/albums/b190/erb2011/friendtrain/error.jpg' width='100px'></td><td><h2>Sorry, an unexpected error has occurred!</h2>If this error persists, please post the error code <a href='http://forum.myspace.com/index.cfm?fuseaction=messageboard.viewcategory&type=friendForum&friendID=418399031&MyToken=167e05ed-ccc5-4698-93e9-9bf0000212f8' target='_blank'>here</a>.<br>Error: "+e+"</td></tr></table><br><input value='Close' type='button' class='button' onclick='document.getElementById(\"light\").style.display=\"none\";document.getElementById(\"fade\").style.display=\"none\";'><input value='Reload' type='button' class='button' onclick='top.location = \"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=117798\";'>";
}
function showRefresh(){
	document.getElementById('light').style.display='block';
	document.getElementById('fade').style.display='block';		
	document.getElementById('light').innerHTML="<table><tr><td><img src='http://i19.photobucket.com/albums/b190/erb2011/friendtrain/error.jpg' width='100px'></td><td><h2>Sorry, an unexpected error has occurred!</h2>You MUST refresh whole window in order to load FriendTrain, would like to do it now?</td></tr></table><br><input value='Close' type='button' class='button' onclick='document.getElementById(\"light\").style.display=\"none\";document.getElementById(\"fade\").style.display=\"none\";'><input value='Reload' type='button' class='button' onclick='top.location = \"http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=117798\";'>";
}
function showAddApp(){
	document.getElementById('light').style.display='block';
	document.getElementById('fade').style.display='block';		
	document.getElementById('light').innerHTML="<table><tr><td><img src='http://i19.photobucket.com/albums/b190/erb2011/friendtrain/error.jpg' width='100px'></td><td><h2>Sorry, an unexpected error has occurred!</h2><br><br>You MUST Install the application to continue!";
}
function showWarning(text){
	document.getElementById('light').style.display='block';
	document.getElementById('fade').style.display='block';		
	document.getElementById('light').innerHTML="<table><tr><td><img src='http://i19.photobucket.com/albums/b190/erb2011/friendtrain/error.jpg' width='100px'></td><td><h2>You have been given a Warning!</h2>"+text+"</td></tr></table><br><input value='Close' type='button' class='button' onclick='doRequest(15);document.getElementById(\"light\").style.display=\"none\";document.getElementById(\"fade\").style.display=\"none\";'>";
}
function showDailyTickets(text){
	document.getElementById('light').style.display='block';
	document.getElementById('fade').style.display='block';		
	document.getElementById('light').innerHTML="<table><tr><td width='200px'><img src='http://i19.photobucket.com/albums/b190/erb2011/friendtrain/notify.png' width='100px'></td><td><h2>You have recieved your Daily Tickets!</h2>You have recieved "+text+" free tickets since you last logged in!</td></tr></table><br><input value='Close' type='button' class='button' onclick='doRequest(15);document.getElementById(\"light\").style.display=\"none\";document.getElementById(\"fade\").style.display=\"none\";'>";
}
function showBan(text){
	document.getElementById('light').style.display='block';
	document.getElementById('fade').style.display='block';		
	document.getElementById('light').innerHTML="<table><tr><td><img src='http://i19.photobucket.com/albums/b190/erb2011/friendtrain/error.jpg' width='100px'></td><td><h2>You have been banned!</h2>"+text+"</td></tr></table>";
}
function doRequest(id, id2, id3) {
	try{
		var params = {};
	    params[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
	    params[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;
	    params[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.SIGNED;
	    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
		switch (id) {
			case 1:
				var url = "http://friendtrainapp.com/login.php?fid=" + fid + "&pic=" + picture + "&gender=" + gender + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				setRefresh(1);
				break;
			case 2:
				var url = "http://friendtrainapp.com/ride.php?fid=" + fid + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				break;
			case 3:
				var url = "http://friendtrainapp.com/added.php?fid=" + fid + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				break;	
			case 4:
				var url = "http://friendtrainapp.com/topriders.php?fid=" + fid + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				break;
			case 6:
				var url = "http://friendtrainapp.com/invite.php?fid="	+ fid + "&invite_id=" + id2 + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				return;
			case 7:
				var url = "http://friendtrainapp.com/bulletin.php?fid="	+ fid + "&invite_id=" + id2 + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				return;
			case 8:
				var url = "http://friendtrainapp.com/selectinterests.php?fid=" + fid + "&interests=" + interests + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				break;
			case 9:
				var url = "http://friendtrainapp.com/report.php?fid=" + fid + "&fid2=" +id3+ "&comid=" + id2 + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				break;
			case 10:
				params[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.POST;
				params[opensocial.ContentRequestParameters.POST_DATA] = "fid=" + fid + "&pic=" + picture + "&cmt=" + commentCache + "&rtn=" + id3 + "&to=" + id2 + "&name=" + name + "&rnd=" + rand(9999);
				var url = "http://friendtrainapp.com/comment.php";
				gadgets.io.makeRequest(url, evalResponse, params);
				break;
			case 11:
				var url = "http://friendtrainapp.com/report2.php?fid=" + fid + "&picid=" + id2 + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				break;
			case 12:
				var url = "http://friendtrainapp.com/deletecomment.php?fid=" + fid + "&comid=" + id2 + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				break;
			case 13:
				var url = "http://auction.noobzor.com/time.php";
				gadgets.io.makeRequest(url, evalResponse, params);
				break;
			case 14:
				var url = "http://friendtrainapp.com/purchase.php?fid=" + fid + "&itemid=" + id2 + "&rnd=" + rand(9999);
				gadgets.io.makeRequest(url, evalResponse, params);
				break;
			case 15:
				var url = "http://friendtrainapp.com/clearwarning.php?fid=" + fid;
				gadgets.io.makeRequest(url, evalResponse, params);
				break;

		}
	}
	catch(e)
	{
		showError(e);
	}
}

function evalResponse(data) {
	loaded = true;
	//try{
		eval(data.text);
	//}
	//catch(e)
	//{
	//	showError(e);
	//}
}

function add(id) {
	try{
		if(!adds.contains(id)){
			adds[addsCnt] = id;
			addsCnt++;
			if(90-addsCnt != 0)
				setStatus(90-addsCnt+" adds left until you get a free ticket!");
		}
		if(addsCnt == 89){
			doRequest(3);
		}
		if(90-addsCnt < 0)
			setStatus("You can only earn 1 ticket a day by adding friends!");
	}
	catch(e){
		showError(e);
	}
}

function loadFriends(pageId){
	//Get Friends
	var req= os.newDataRequest();
	var profileDetails = [MyOpenSpace.Person.Field.ID, MyOpenSpace.Person.Field.POSTALCODE]; 
	var param = {};
	var randomnum = rand(totalfriends);
	while(randomnum > 25000)
		randomnum = rand(totalfriends);
	//Request first group parameter
	var allFriends = {};
	allFriends[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = profileDetails;
	allFriends[opensocial.DataRequest.PeopleRequestFields.FIRST] = ((pageId-1)*36);   
	allFriends[opensocial.DataRequest.PeopleRequestFields.MAX] = 36;
	var rndFriends = {};
	rndFriends[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = profileDetails;
	rndFriends[opensocial.DataRequest.PeopleRequestFields.FIRST] = randomnum;   
	rndFriends[opensocial.DataRequest.PeopleRequestFields.MAX] = 36;
	req.add(os.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, allFriends), "group1");
	req.add(os.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, rndFriends), "group2");
	req.send(FriendRespose);
	try{
		var html = "";
		if(pageId > 1){
			html += "<a href='#' onclick='loadFriends("+(pageId-1)+");'><- Previous --</a>     ";
		}
		var x = pageId-5;
		for(var y = 0; y < 10; y++)
		{
			if(x > 0)
			{
				if(pageId == x)
					html += " <u>"+x+"</u>";
				else
					html += " <a href='#' onclick='loadFriends("+(x)+");'>"+x+"</a>";
					
			}
			else
			{
				y--;
			}
			x++;
		}
		html += "     <a href='#' onclick='loadFriends("+(pageId+1)+");'>-- Next -></a>";
		
		document.getElementById('FriendNav').innerHTML = html;
	}catch(e){}
}

function FriendRespose(respondsData) {
	totalfriends = respondsData.get("group1").getData().getTotalSize();
	var html = "";
	var VIEWER_FRIENDS = respondsData.get("group2").getData();
	
	var friendData = new Object;
	var x = 1;
 	for(var i=1; i < VIEWER_FRIENDS.size(); i++){
		var friendData = new Object;
		friendData.ProfileURL = VIEWER_FRIENDS.asArray()[i].getField(opensocial.Person.Field.PROFILE_URL);
		friendData.ThumbnailURL = VIEWER_FRIENDS.asArray()[i].getField(opensocial.Person.Field.THUMBNAIL_URL);
		friendData.Id = VIEWER_FRIENDS.asArray()[i].getField(opensocial.Person.Field.ID);
		if(friendData.ThumbnailURL != 'http://x.myspacecdn.com/images/no_pic.gif'){
			html += "<img src='"+friendData.ThumbnailURL+"' height='120px' width='120px' onclick='sendAppAdd("+friendData.Id+");loadFriends("+pageId+");'/><br><h2>Random Friend</h2>";
			break;
		}
		
	}


	VIEWER_FRIENDS = respondsData.get("group1").getData();
	html += "<table><tr>";
	friendsData = {};
 	x = 1;
 	for(var i=1; i < VIEWER_FRIENDS.size(); i++){
		var friendData = new Object;
		friendData.ProfileURL = VIEWER_FRIENDS.asArray()[i].getField(opensocial.Person.Field.PROFILE_URL);
		friendData.ThumbnailURL = VIEWER_FRIENDS.asArray()[i].getField(opensocial.Person.Field.THUMBNAIL_URL);
		friendData.Id = VIEWER_FRIENDS.asArray()[i].getField(opensocial.Person.Field.ID);
		html += "<td width='100' height='100'><img src='"+friendData.ThumbnailURL+"' height='80px' width='80px' onclick='sendAppAdd("+friendData.Id+")'/></td>";
		if(x == 5){
			x=0;
			html += "</tr><tr>";
		}
		x++;
 	}
 	html += "</table>";
 	try{
 	document.getElementById('FriendSelect').innerHTML = html;
 	}catch(e){}
}

Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

String.prototype.contains = function(searchString){
return (this.indexOf(searchString) != -1);
}

function rand(max) {
	return (Math.floor(Math.random()*max))+1;
}

function clicker(that) {
	var pick = that.options[that.selectedIndex].value;
	//showError(pick);
	if(showOnly != pick)
		showOnly = pick; showPage(12);
}

function addCommas(nStr) {
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return "<font color='green'>$"+ x1 + x2 + "</font>";
}

var tooltip=function(){
	var id = 'tt';
	var top = 3;
	var left = 3;
	var maxw = 300;
	var speed = 10;
	var timer = 20;
	var endalpha = 95;
	var alpha = 0;
	var tt,t,c,b,h;
	var ie = document.all ? true : false;
	return{
		show:function(v,w){
			if(tt == null){
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				t = document.createElement('div');
				t.setAttribute('id',id + 'top');
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				b = document.createElement('div');
				b.setAttribute('id',id + 'bot');
				tt.appendChild(t);
				tt.appendChild(c);
				tt.appendChild(b);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				document.onmousemove = this.pos;
			}
			tt.style.display = 'block';
			c.innerHTML = v;
			tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie){
				t.style.display = 'none';
				b.style.display = 'none';
				tt.style.width = tt.offsetWidth;
				t.style.display = 'block';
				b.style.display = 'block';
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer);
		},
		pos:function(e){
			var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
			var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
			tt.style.top = (u - h) + 'px';
			tt.style.left = (l + left) + 'px';
		},
		fade:function(d){
			var a = alpha;
			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
				var i = speed;
				if(endalpha - a < speed && d == 1){
					i = endalpha - a;
				}else if(alpha < speed && d == -1){
					i = a;
				}
				alpha = a + (i * d);
				tt.style.opacity = alpha * .01;
				tt.style.filter = 'alpha(opacity=' + alpha + ')';
			}else{
				clearInterval(tt.timer);
				if(d == -1){tt.style.display = 'none'}
			}
		},
		hide:function(){
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
		}
	};
}();