var container;
var tabContainer;
var errorDiv;
var super_mpAppId = 456726125;
var super_appId =  129779;
var serverURL = "http://mp.playgamesite.com/fungames/";
//var serverURL = "http://127.0.0.1:8081/fungames/";
var serviceURL = serverURL+"GameService";
var reportURL = serverURL+"ReportService";
var GAME_IMG_URL="http://www.playgamesite.com/arcade/img/";
var IMG_URL = serverURL+"img/";
var MENU_IMG_URL = IMG_URL + "menu_icon/";
//var MP_IMG_URL = serverURL+"mp_img/";
var MP_IMG_URL = serverURL+"mp_img/";
var SWF_URL = serverURL +"swf/";
var COMMENT_COUNT = 5;
var HOME_APP_COUNT = 9;
var osContainer;
var allContent;
var APP_COUNT = 16;
var PLAYERS_COUNT= 25;
var GALLERY_APP_COUNT = 20;
var Request = new Object();
var user = null;
var userId = null;
var userThumbnail, userName, userProfile, userCountry, userCity,
	userRegion, userPostalCode, userAge, userGender;
var CANVAS_URL = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=";
var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

var IS_LIVE = true;
var isUploaded = false;

var isAdmin = false;
var adminIds = new Array("368183653","425703872","423369260","423855305","440346060","434386067");  //Ani,Vahe,Serine, Karen, Kritina,Hovik


var SUPER_URL = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=129779";  //456726125  //hovhannes.safaryan@gmail.com   //pluton0

var currentAdIndex = 0;  
var currentDuration = 0;  
var gameMaskDuration  = 25000;   

/*var GAME_MASK_ADS = [{name:"GOOGLE_AD",src:'<iframe src="'+serverURL+'google_ad_300x250.html" scrolling="no" frameborder="0"  width="300" height="250" ></iframe>'},
                     {name:"SOCIAL_AD",src: getSocialAd()}
                    ];
*/
var GAME_MASK_ADS = ['<iframe src="'+serverURL+'google_ad_300x250.html" scrolling="no" frameborder="0"  width="300" height="250" ></iframe>',
                     getSocialAd()
                     ];

var overDiv = "0";
var showDiv = "0";
var SMALL_AD = {height:60, width:645};
var LARGE_AD = {height:90, width:728};
var PUBLIC_APPS;
var CONFIG = null;
var request_URL="";
var _$ = function(id){
	return document.getElementById(id);
}

var fillAds = function(){
	for (adName in CONFIG.AD_CONFIG){
		if (_$("ad_"+adName) && CONFIG.AD_CONFIG[adName].show){
			var code = CONFIG.AD_CONFIG[adName].code;
			if (CONFIG.AD_CONFIG[adName].id){
				code = ADS[CONFIG.AD_CONFIG[adName].id].code;
			} 
			if (code.indexOf("recommendations.jsp")>0){
				var colorStr =
						"?borderColor="+CONFIG.TAB_CONFIG.borderColor.substring(1,7)+
						"&headerBgColor="+CONFIG.TAB_CONFIG.selectedBgColor.substring(1,7)+
						"&headerColor="+CONFIG.TAB_CONFIG.selectedColor.substring(1,7)+
						"&color="+CONFIG.textColor.substring(1,7)+
						"&strongColor="+CONFIG.highLightedTextColor.substring(1,7)+
						"&bgColor="+CONFIG.bgColor.substring(1,7)+
						"&count="+(CONFIG.height-34)/53;
				code = code.replace("recommendations.jsp", "recommendations.jsp"+colorStr+"&is_super="+is_super);
			
				
			}else{
			
				if (code.indexOf("bgcolor") > 0){
					var bgcolor = code.substr(code.indexOf("bgcolor")+8, 6);
					var newColor = CONFIG.bgColor.replace("#", "");
					code = replaceAll(code, bgcolor, newColor);
				}
				if (code.indexOf("bgColor") > 0){
					var bgcolor = code.substr(code.indexOf("bgColor")+8, 6);
					var newColor = CONFIG.bgColor.replace("#", "");
					code = replaceAll(code, bgcolor, newColor);
				}
				if (code.indexOf("bordercolor") > 0){
					var bgcolor = code.substr(code.indexOf("bordercolor")+12, 6);
					var newColor = CONFIG.bgColor.replace("#", "");
					code = replaceAll(code, bgcolor, newColor);
				}
			
				var ind = code.indexOf("&color");
				if (ind < 0){
					ind = code.indexOf("?color");
				}
				if (ind > 0){
					var bgcolor = code.substr(ind+7, 6);
					var newColor = CONFIG.TAB_CONFIG.selectedBgColor.replace("#", "");
					code = replaceAll(code, bgcolor, newColor);
				}
			}

	          if (code.indexOf("canvas_randomApps.jsp") > 0){
					/*
					var sufix = code.substr(code.lastIndexOf("?"),1);
					code = replaceAll(code,sufix,"&");
					if(is_super) 	code = replaceAll(code,"canvas_randomApps.jsp", "canvas_randomApps.jsp?is_super="+is_super);
					*/
			 }
			if(_$("ad_"+adName))   _$("ad_"+adName).innerHTML = code;
		}
	}
}


function applyAds(adDiv, adHolderDiv){
    var adTop = document.getElementById(adDiv);
        adTop.parentNode.removeChild(adTop);
	    var adHolder = document.getElementById(adHolderDiv);
	    adHolder.appendChild(adTop);
	    adTop.style.display='block';
    
}


var applyMiddleAd = function(adDiv, adHolderDiv){
   var adMiddle = document.getElementById(adDiv);
   if(adMiddle == null || adMiddle == "null" || typeof adMiddle == "undefined"){
       var adStr = "<iframe frameborder='0' src = 'http://adturns.com/ad.php?c=67' width = '728' height = '90' border='0' style = 'border: none; overflow: hidden' frameborder='0'  scrolling='no' ></iframe>";
        document.getElementById(adHolderDiv).innerHTML = adStr;
   }else{
    	var middleAdText = adMiddle.innerHTML;
	    if(document.getElementById(adHolderDiv)) document.getElementById(adHolderDiv).innerHTML = middleAdText;
   }	
}





var getAd = function(size){
	if (!size){
		size = SMALL_AD;
	}
    return '<iframe src="http://ads.socialmedia.com/myspace/monetize.php?width='+size.width+'&height='+size.height+'&pubid=54d306cd0a4dd0086cac15df9dcecbaf&bgcolor=FFFFFF&bordercolor=FFFFFF"  border="0" width="'+size.width+'" height="'+size.height+'" name="socialmedia_ad" scrolling="no" frameborder="0"></iframe>';
}

function storeDuration(){
	if (userId == null || userId == "null" || typeof window.startTime == "undefined") return;
	var duration=Math.ceil(((new Date()).getTime()-window.startTime.getTime())/1000);
	var data="query=durationUpdate&userId="+userId+"&appId="+gameId+"&duration="+duration;
	Request.sendPOST(serviceURL, data, resp_duration);
}

/*
function storeCurrentDuration(){
	if (userId == null || userId == "null") return;
	var duration=Math.ceil(((new Date()).getTime()-window.startTime.getTime())/1000);
	var data="query=durationUpdate&userId="+userId+"&appId="+gameId+"&duration="+duration;
	Request.sendPOST(serviceURL, data, resp_duration);
}
*/

var resp_duration=function(response){}

var fillBody = function(){
    
    if(typeof is_super == "undefined") is_super = false;
    if(typeof preview == "undefined") preview = false;
	if (typeof gadgets == "undefined"){
		window.gadgets = {
			window : {
				adjustHeight: function(){}
			 }
		}
		IS_LIVE = false;
		if (window.opener){
			CONFIG = window.opener.CONFIG;
			gameTitle = window.opener.gameTitle;
			gameId = window.opener.gameId;
		    gameURL = window.opener.gameURL;
		    gameImgUrl= window.opener.gameImgUrl;
		    swf = window.opener.swf;
		    is_super = window.opener.is_super;
		}
	}
	
	Request.sendGET(serviceURL+"/version/"+gameId+"/"+Math.random(), resp_getVersion);
	
}

var ADS;
var VERSION_ID;
var resp_getVersion = function(response){
	if (response.errorCode){
		showDefault();
	}else{
		if (window.opener && !IS_LIVE){
			VERSION_ID = window.opener.VERSION_ID;
		}else{
			CONFIG = eval("("+response.data.configJson+")");
			VERSION_ID = response.data.versionId;
		}
		ADS = {};
		var respAds = response.data.ads;
		for (var i=0;i<respAds.length;i++){
			ADS[respAds[i].id] = respAds[i];
		}
		validateConfig();
		
		if(preview || !is_super){
		    fillBody2();
         }else{
                getUser();  
	       /////// getCanvasRandomApps();
                setDefaultApp();
         }
	   
	}

}

var validateConfig = function(){
	if (!CONFIG.highLightedTextColor){
		CONFIG.highLightedTextColor = "#3B5998";
	}
	if (!CONFIG.textColor){
		CONFIG.textColor = "#787376";
	}
}

var showDefault = function(){
   var str = '<center>';
   str+='<iframe src="'+serverURL+'app_to_promote_myspace.html" style="border:0px;" width="840" height="110" scrolling="no" frameborder="0"></iframe>';
   if(!is_super) str + '<div><img style="cursor:pointer; margin:7px 0px;" src="'+IMG_URL+'sharegame.png" onclick="postInvite()"></div>';
   str+='<div>'+getAd()+'</div>'+
		'<div><iframe id=gameframe src="'+swf.url+'"width="'+swf.width+'" height="'+swf.height+'" name="game" scrolling="no" frameborder="0" ></iframe></div>'+
		'<div>'+getAd()+'</div>'+
		'</center>';
	allContent = _$("allContent");
	allContent.innerHTML = str;
	
}

var showFavorite = true;

var fillBody2 = function(){

  
	//window.startTime = new Date();
	//window.onbeforeunload=storeDuration;
		
	if (CONFIG.width && VERSION_ID != 0) swf.width = CONFIG.width;
	if (CONFIG.height && VERSION_ID != 0) swf.height = CONFIG.height;
	
  	allContent = _$("allContent");
  	var header = '<table cellspacing=0 cellpadding=0><tr><td><div id="curGame" style="margin-bottom: 10px;margin-top:10px;"/></td></tr></table>';
	var tabs = 
        '<table cellspacing=0 cellpadding=0>'+
	    '<tr class="tabs" id="tabContainer">';
    var _class = "";  
    if(is_super){
        tabs += '<td class="lastTab ui-widget-content ui-corner-all" style="border-color:'+CONFIG.TAB_CONFIG.borderColor+';background:'+CONFIG.TAB_CONFIG.bgColor+'" name="home" >'+
	    	    '<a style="color:'+CONFIG.TAB_CONFIG.color+';" href="javascript:showHome()">Home</a></td>';
	    var _class = "lastTab ui-widget-content ui-corner-all";
	}
	    var items = CONFIG.TAB_CONFIG.items;
	    for (var i=0;i<items.length;i++){
	    	if (items[i].name == "favorites"){
	    		showFavorite = items[i].show;
	    	}
	    	if (!items[i].show) continue;
	    	tabs += '<td class="'+_class+'" style="border-color:'+CONFIG.TAB_CONFIG.borderColor+';background:'+CONFIG.TAB_CONFIG.bgColor+'" name="'+items[i].name+'" >'+
	    	'<a style="color:'+CONFIG.TAB_CONFIG.color+';" href="'+items[i].link+'">'+getTabDisplayName(items[i])+'</a></td>';
	    }
	tabs += '</tr></table>';
  	var topBanner ='<div align=center style="font-size:15px;font-weight:bold;">';
	if(!is_super)
		topBanner+='<div><img style="cursor:pointer; margin:7px 0px;" src="'+IMG_URL+'sharegame.png" onclick="javascript:postInvite()"></div>';
		topBanner+='<div style="margin:30px 7px 0px;" class=menu id=menuTop>'+getMenu()+'</div>'+
		 		   '<div id=topAd></div><br/>'+
		 		   '<div style="font-size:11px;color:#999999;" >Click to play  inside "Mario, Tetris, Pacman and 10,000 games"</div>'+
	               '</div>';
  	var cont =
  		'<div id=error style="display: none"></div>'+
		         '<div id=container style="margin-top: 20px;"><div class=loading>Loading...</div></div>';
	var botomBanner =
		'<div align=center style="font-size:15px;font-weight:bold;">'+ 
	      ///////  '<div id=ad_bottom></div>'+
	        '<div style="margin:7px 0px;" class=menu id=menuBottom>'+getMenu()+'</div></div>'+
			    '<br/><div align=center id=bottomAd></div>'+
                '<br/><br/><div align=center id=canvas_randomApps></div><br/>';
       if(!is_super)
       botomBanner+='<div align=center><img style="cursor:pointer; margin:7px 0px;" src="'+IMG_URL+'sharegame.png" onclick="javascript:postInvite()" /></div>';
      
	
	if (CONFIG.bgImage && gameId){
		document.body.style.backgroundImage = "url("+MP_IMG_URL+gameId+"_bg.png)";
	}
	if (CONFIG.bgColor){
		document.body.style.backgroundColor = CONFIG.bgColor;
	}

	var  str ='<iframe src="'+serverURL+'app_to_promote_myspace.html" style="border:0px;" width="840" height="110" scrolling="no" frameborder="0"></iframe>';
    str += header + tabs +topBanner + cont + botomBanner;
	if (CONFIG.commentsWithGame){
		str += "<div id='commentContainer'></div>"; 	
	}
	// str+="<div align=center >"+getBottomAd()+"</div>";
	str += "<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>";
	allContent.innerHTML = str;
	container = _$("container");
	errorDiv = _$("error");
	tabContainer = _$("tabContainer");
    if(!is_super)	tabContainer.lastChild.className = "lastTab";
	fillAds();
	
	getCanvasRandomApps();
    getUser();  
     
    try{
    	applyAds('adDivTop', 'topAd');
		applyAds('adDivBottom', 'bottomAd');
	    sr_gof();
    }catch(ex){
        showTopAd();
        showBottomAd();
    }
}

function getBottomAd(){
 return "<iframe frameborder='0' src = 'http://adturns.com/ad.php?c=46' width = '700' height = '65' border='0' style = 'border: none; overflow: hidden' frameborder='0'  scrolling='no' />";
}

var defaultFlag = false;
var setDefaultApp = function(){

    if(defaultFlag == false){
      Request.sendGET(serviceURL+"/randApp", resp_setDefaultApp); 	    
    }

}

var resp_setDefaultApp = function(response){

    defaultFlag =true;
  //  var json = eval("("+response.data.app+")");
     var json = response.data;
	gameTitle = json.title;
	gameId = json.id;
    gameDesc = json.description;
    swf = new Object();
    swf.url = "http://www.playgamesite.com/arcade/"+json.flashUrl;
    swf.width = json.width;
    swf.height = json.height;
    gameURL = "http://www.myspace.com"+json.mpAppId;
    gameImgUrl= "http://www.playgamesite.com/arcade/img/"+json.imgLargeUrl;
    canvas_url = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId="+json.url;

   fillBody2();
}

var getTabDisplayName = function(tabItem){
	switch(tabItem.name){
		case "invite" : return "Spread Game";
		default: return tabItem.displayName;
	}
}

var showTopAd = function(){
   _$("topAd").innerHTML = '<iframe frameborder="0" src = "http://adturns.com/ad.php?c=65" width = "728" height = "90" border="0" style = "border: none; overflow: hidden" frameborder="0"  scrolling="no" />';
}
var showBottomAd = function (){
	//_$("bottomAd2").innerHTML = "<br><br><div align=center><iframe src='http://playgamesite.com/bottomads.html' scrolling='no' frameborder='0' width=728px height=80px></iframe></div>";
    _$("bottomAd").innerHTML =  '<iframe frameborder="0" src = "http://adturns.com/ad.php?c=66" width = "728" height = "90" border="0" style = "border: none; overflow: hidden" frameborder="0"  scrolling="no" />';
}

var getUserPostData = function(){
	var str = "userName="+encodeURIComponent(userName)+
			  "&thumbnail="+userThumbnail+
			  "&country="+encodeURIComponent(userCountry)+
			  "&city="+encodeURIComponent(userCity)+
			  "&region="+encodeURIComponent(userRegion)+
	    	  "&postalCode="+encodeURIComponent(userPostalCode)+
    		  "&profile="+userProfile+
    		  "&gender="+userGender+
    		  "&age="+userAge+
	    	  "&userId="+userId;
	return str;
}

function getUser() {
	 if (!IS_LIVE){
	   	user = {};
		userId = 425703872;
		userAge = 23;
	    userGender = 1;
		userThumbnail = "http://c3.ac-images.myspacecdn.com/images02/38/s_46501398ca054779b59bb59db90f045a.jpg";
		userName = "Ani";
		userProfile = "http://www.myspace.com/425703872";
	    userCountry = "AM";
	    userCity = "yerevan";
	    userRegion = "yerevan";
	    userPostalCode = "374";

		if(defaultFlag || preview || !is_super)  _startGame();
	}else{
		 osContainer = opensocial.Container.get();
	    var req = opensocial.newDataRequest();
		var paramViewer = {};
	    paramViewer[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
	    [MyOpenSpace.Person.Field.COUNTRY,
	     MyOpenSpace.Person.Field.CITY,
	     MyOpenSpace.Person.Field.POSTALCODE,
	     MyOpenSpace.Person.Field.REGION, 
	     MyOpenSpace.Person.Field.THUMBNAIL_URL, 
	     MyOpenSpace.Person.Field.NAME, 
	     MyOpenSpace.Person.Field.AGE,
	     MyOpenSpace.Person.Field.GENDER,
	     MyOpenSpace.Person.Field.PROFILE_URL];
	    req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER, paramViewer), "viewer");
	    //req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), "owner");
	    req.send(resp_getUser);
	}
checkPromotion();
};

var resp_addUser=function(response){
	
}

function resp_getUser(data) {
	try{
		//data.get("owner").getData().getId();
		user = data.get("viewer").getData();
		userId = user.getId();
		userThumbnail = user.getField(opensocial.Person.Field.THUMBNAIL_URL);
		userName = user.getField(opensocial.Person.Field.NAME);
		userProfile = user.getField(opensocial.Person.Field.PROFILE_URL);
		userCountry = user.getField(MyOpenSpace.Person.Field.COUNTRY);
		userCity = user.getField(MyOpenSpace.Person.Field.CITY);
		userRegion = user.getField(MyOpenSpace.Person.Field.REGION);
		userPostalCode = user.getField(MyOpenSpace.Person.Field.POSTALCODE);
		userAge = user.getField(MyOpenSpace.Person.Field.AGE);
		userGender = user.getField(MyOpenSpace.Person.Field.GENDER); 
	    
		if (typeof userAge == "undefined"){
			userAge = 0;
		}
		if (typeof userGender == "undefined"){
			userGender = 0;
		}else{
			userGender = userGender == "Male" ? 0 : 1;
		}
		
     }
	catch(ex){
		showMask();
		
  	}
  	
	if (userId == null || userId=="null"){
			showMask();
    }else{
		   if(defaultFlag || preview  || !is_super){   
			   _startGame();
		    }
     }	
  		
}


function  _startGame(){
	var data="query=adduser&"+getUserPostData()+"&appId="+gameId;
	Request.sendPOST(serviceURL, data, resp_addUser);
    if(is_super)    initSuper();
    else            play();

	
	for(var i in adminIds)
	  if(adminIds[i] == userId)
	     isAdmin = true;
	
	if (CONFIG.commentsWithGame){
		request_getComments(1);
	}	
}


function showMask(){
/*
	var bodyMask = document.createElement("div");
	bodyMask.className = "body-mask";
	bodyMask.id = "body-mask";
	bodyMask.onclick = function(ev){
		if (window.event) ev = window.event;
		ev.cancelBubble = true;
		return false;
	}
	document.body.appendChild(bodyMask);
	
	var wizardBox = document.createElement("div");
	wizardBox.id = "wizardBox-dlg";
	wizardBox.innerHTML = "<img src='"+IMG_URL+"add_app.jpg'/>";
	
	wizardBox.className = "wizardBox-dlg";
	wizardBox.style.left = (75+gameTitle.length*10)+"px";
	wizardBox.innerHTML = 
	"<center><img src='"+IMG_URL+"arrow_jump.gif'></center>"+
	"<div style='border: 3px solid red; padding:13px'>"+
	"Add / Install this App to start using "+gameTitle+"</div>";
	
	document.body.appendChild(wizardBox);
	
	showAllGames();
	*/
	_$("allContent").innerHTML = "<img src='"+IMG_URL+"add_app.jpg'/>";
}

function getFullScreenURL() {
	var myWidth = 0, myHeight = 0;
    if (window.screen){
    	myWidth = window.screen.width;
    	myHeight = window.screen.height;
    }else if( typeof( window.innerWidth ) == 'number' ) {
          myWidth = window.innerWidth;
          myHeight = window.innerHeight;
    }else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
          myWidth = document.documentElement.clientWidth;
          myHeight = document.documentElement.clientHeight;
    }else if(document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
         myWidth = document.body.clientWidth;
         myHeight = document.body.clientHeight;
   	}
   	var url=swf.url;
	if(gameId){
   		url = "http://www.playgamesite.com/playgame1.php?getgame="+gameId+"&width=" + myWidth + "&height=" + myHeight;	 
	}	
   	return url;
}
access_to_play = false;
function showGameMask(games_str){
	 // return false;
	 	    
	access_to_play = true;                    
	var gameMask = document.createElement("div");
	gameMask.className = "game-mask";
	gameMask.setAttribute("text-align","center");
	/////gameMask.style.left = "55px";
	////////gameMask.style.top = "350px";
	
	gameMask.id = "game-mask";
	gameMask.onclick = function(ev){
		if (window.event) ev = window.event;
		ev.cancelBubble = true;
		return false;
	}
	_$("game_container").appendChild(gameMask);	
	var  preloadingBox_width = parseInt(swf.width) - 50;
	var  preloadingBox_height = parseInt(swf.height);
	
	var preloadingBox  = document.createElement("div");
	preloadingBox.className = "preloading-dlg";
	preloadingBox.style.width = preloadingBox_width+100+"px"; 
	preloadingBox.style.height  = preloadingBox_height+"px";

	preloadingBox.id = "preloading-dlg";
	preloadingBox.innerHTML  ='<center>'+games_str +'<div id="preloading_ad"></div><br/>'+
	                     '<p style="font-size:12px;font-weight:bold;">Please wait...<img style="border:none;" src="'+serverURL+'img/loading.png"/></p>'+
	                    '</center>';
 
	 gameMask.appendChild(preloadingBox);
	 _$("game_container").appendChild(gameMask);

	 _$("preloading_ad").innerHTML = GAME_MASK_ADS[ Math.round(Math.random())];  
	/*_$("preloading_ad").innerHTML = GAME_MASK_ADS[1]; */
	
	
	///// changeAdTimer = setTimeout('showPreloadingAds("GOOGLE_AD")',500);
	 setTimeout('removeMask()',gameMaskDuration);
	
}


function showPreloadingAds(name){

 currentDuration +=5000;
 for(var i in GAME_MASK_ADS){
   if(name == GAME_MASK_ADS[i].name){
      currentAdIndex = i;
     _$("preloading_ad").innerHTML = GAME_MASK_ADS[i].src;   
   }
 }
 if(currentAdIndex != GAME_MASK_ADS.length - 1)  currentAdIndex++;
 else  currentAdIndex = 0;
 
 if(currentDuration >= gameMaskDuration)
    clearTimeout(changeAdTimer);
  else 
   setTimeout('showPreloadingAds("'+GAME_MASK_ADS[currentAdIndex].name+'");',5000);  //gameMaskDuration/GAME_MASK_ADS.length


 
}
function removeMask() {
	var n = document.getElementById("preloading-dlg");
	n.parentNode.removeChild(n);
	var n = document.getElementById("game-mask");
	n.parentNode.removeChild(n);
}

var req_newApps = function(){
	request_URL = serviceURL+"/publicgame/6/All/1";
	Request.sendGET(request_URL, resp_newApps);
}

var resp_newApps = function(response){
    var data = response.data;
	var str = "<table  cellspacing='0' style='margin-top:10px;margin-left:10px;width:100%;'>";
	for(var i = 0;i<data.app.length;i++){
	    var title = data.app[i].gamename;
	    if(title.length > 20) title = title.substring(0,20);
	    
	   ////// var link  = "http://www.myspace.com/"+data.app[i].mpAppId;
	    var link  = SUPER_URL+"&appParams=%7B%22gameId%22%3A"+data.app[i].id+"%7D";
	    var target = "_blank";
	
	    if(is_super){
	        link   = "javascript:loadGame("+data.app[i].id+")";
	        target = "";
	    }
	    
	    var img_src = GAME_IMG_URL+data.app[i].imgLarge;    
		str+="<td style='width:50px;height:50px' valign=top>"+
				"<a style='color:"+CONFIG.textColor+";font-size:8px;' href='"+link+"' target='"+target+"'>"+
				"<img  border='none' width='50px' height='50px'  src='"+img_src+"' ></img>";
		str+="<div style='width:55px; overflow:hidden'>"+title+"</div></a></td>";
	
	}
	str += "</table>";
	showGameMask(str);
}


var initSuper = function(){

 if(IS_LIVE){
  	var params = opensocial.getEnvironment().getParams();
	if (params["gameId"]){
	 loadGame(params["gameId"]);
	}else{
	 showHome();
	}
 }else{
    showHome();
 }
  
}
var gameObj;
var loadGame = function(gameId){
	
	if (typeof gadgets == "undefined"){
		window.gadgets = {
			window : {
				adjustHeight: function(){}
			 }
		}
	 IS_LIVE =false;
	}
   isUploaded = false;
   if(gameId){
     access_to_play = false;
     Request.sendGET(serviceURL+"/getApp/"+gameId, resp_loadGame);
    }
}

var resp_loadGame = function(response){

    if (response.errorCode){
		return;
	}else{
	   var json = response.data;

	   gameTitle = json.title;
	   gameId = json.id;
	   gameDesc = json.description;
	   gameImgUrl= "http://www.playgamesite.com/arcade/img/"+json.imgLargeUrl;
	   gameRate = json.rate;
	   swf = new Object();
	   swf.url = "http://www.playgamesite.com/arcade/"+json.flashUrl;
	   swf.width = json.width;
	   swf.height = json.height;
	     
	  if(swf.width == 0 || swf.width == null) swf.width = 640;
	  if(swf.height == 0 || swf.height == null) swf.height = 480;
	   canvas_url = 'http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId='+json.url;
	   gameURL = 'http://www.myspace.com/'+json.mpAppId;
	   
	   play();
	  
	}

}
var play = function(){
	if (userId == null || userId=="null") return;
	selectTab("play");
         getFlash();
	if(!access_to_play)   	req_newApps();
	fillAds();

	    if(is_super){
		 var str ="<table>"+
					 "<tr>"+
					  "<td>"+
					  "<img class='ui-widget-content ui-corner-all' src='"+gameImgUrl+"'  width='120px' height='90px'>"+  
					  "</td>"+
					  "<td>"+
					    "<h1>"+gameTitle+"</h1>";
				 if(typeof gameRate != "undefined")
	              str+= showRate(gameRate,13)+"<br/>";
				  str+=	"<div style='color: #999999;overflow:hidden;height:30px;width:250px;'>"+gameDesc+"</div>"+   
				    "</td>"+
					 "</tr>"+
				    "</table>";

	      _$("curGame").innerHTML = str;
	    }
	   
		gadgets.window.adjustHeight();	
		Request.sendGET(serviceURL+"/checkForFavorite/"+userId+"/"+gameId, resp_checkForFavorite); 	
}

var getFlash = function(){

	swf.height = parseInt(swf.height);
	var h = swf.height > 600 ? 50 : (600-swf.height);

	var gameStr = '<center>';
	if (CONFIG.flashWithAd){
  	  	gameStr += 
		'<div id=ad_left style="display:inline;vertical-align: top"></div>'+
	  	'<div id="game_container"><iframe id=gameframe src="'+getFullScreenURL()+'"width="100%" height="'+(parseInt(swf.height)+h)+'" name="game" scrolling="no" frameborder="0" ></iframe></div>'+
	  	'<div id=ad_right style="display:inline;vertical-align: top"></div>';
	}else{
		gameStr +=
		'<table><tr>'+
		'<td id=ad_left></td>'+
		'<td><div id="game_container"><embed  wmode="transparent" id=gameframe src="'+swf.url+'"width="'+swf.width+'" height="'+swf.height+'" name="game" scrolling="no" frameborder="0" ></embed></div></td>'+
	  	'<td id=ad_right></td>'+
	  	'</tr></table>';
	}
	gameStr +='</center>';
	container.innerHTML = gameStr;
}

var resp_checkForFavorite=function(response){
	var json=response.data;
	if(json.totalCount==0 && showFavorite){
  		_$("favorite").innerHTML = '[ <img  src="'+MENU_IMG_URL+'favorite.png" class="icon" /><a style="color:'+CONFIG.highLightedTextColor+'" href="javascript:req_addToFavorites()" />Add to Favorites</a> ]';
	}
  	gadgets.window.adjustHeight();
  	
   Request.sendGET(serviceURL+"/checkForRecommend/"+userId+"/"+gameId, resp_checkForRecommand);
}

var resp_checkForRecommand=function(response){

	var json=response.data;
	if(json.totalCount==0){
	    // if(is_super)
	      var icon_str = '<img  src="'+MENU_IMG_URL+'recommend.png" class=icon />';
	   //  else		  var icon_str = '<img  src="'+IMG_URL+'recommend.png" />';
  		_$("recommend").innerHTML = '[<a style="color:'+CONFIG.highLightedTextColor+'" href="javascript:req_addToRecommend()">'+icon_str+'Recommend</a>]';
	}
	
  	gadgets.window.adjustHeight();
}
var req_addToRecommend=function(){
	var data="query=addRecommend&userId="+userId+"&appId="+gameId;
    Request.sendPOST(serviceURL,data, resp_addToRecommend);
}


var resp_addToRecommend=function(response){
   	if (response.text == "ok")
	   _$("recommend").innerHTML="";
	
}



var getMenu = function(){
  var menuStr = 
  '<span ><a style="color:'+CONFIG.highLightedTextColor+'" target="_blank" href="http://www.playgamesite.com"><img  src="'+MENU_IMG_URL+'playgamesite.png" class=icon />PlayGameSite</a></span>'+
 // '<span><a style="color:'+CONFIG.highLightedTextColor+'" target="_blank" href="'+getFullScreenURL()+'" ><img src="'+MENU_IMG_URL+'fullScreen.png" /> FullScreen</a></span>'+
  '<span ><a style="color:'+CONFIG.highLightedTextColor+'" href="javascript:postInvite()"><img  src="'+MENU_IMG_URL+'post_bulletin.png" class=icon /> Post Bulletin </a></span>' +
  '<span id=favorite></span>'+
  '<span id=recommend></span>';
  return menuStr;
}

var showAllGames = function(){
	selectTab("allgames");
	
	Request.sendGET(serviceURL+"/getCategories", resp_getCategories);
	container.innerHTML ="<table width='100%'><tr>"+
	 "<td valign='top'><div id='leftBox'><div class=loading>Loading...</div></div></td>"+
	 "<td valign='top'>"+
	 "<table><tr><td>"+
	 "<table id='gameTypes' style='font-size:14px;'><tr><td name='new'>"+
	 "<a style='color:"+CONFIG.highLightedTextColor+"' href=javascript:selectType('new'); >New Games</a></td>"+
	 "<td> | </td><td name='RandomGames'>"+
	 "<a style='color:"+CONFIG.highLightedTextColor+"' href=javascript:selectType('RandomGames'); >Random Games</a></td>"+
	 "<td> | </td><td name='popular'>"+
	 "<a style='color:"+CONFIG.highLightedTextColor+"' href=javascript:selectType('popular'); >Popular Games </a></td>"+
	 "<td> | </td><td name='active'>"+
	 "<a style='color:"+CONFIG.highLightedTextColor+"' href=javascript:selectType('active'); >Active Today</a></td>"+
	 "<td><div id='search_form'></div></td></tr></table></td></tr>"+
	 "<tr>"+
	 "<td valign='top'><div id='categoryGames'></div>"+
	 "</td></tr></table></td>"+
   	 
	 "<td valign='top'><div style='width:180px'>"+
	   "<div style='height:20px;font-size:14px;padding-top:5px;border:1px solid "+CONFIG.TAB_CONFIG.borderColor+";color:"+CONFIG.TAB_CONFIG.selectedColor+";background:"+CONFIG.TAB_CONFIG.selectedBgColor+";font-weight:bold;padding-left:10px;	'>Recommendations</div>"+
	   "<div id=recommendation style='padding-bottom:0px;'><div class=loading>Loading...</div></div>"+
	   "</div>"+
	 "</td></tr></table>";	
	 
	 Request.sendGET(serviceURL+"/getRecommendedGames/8",resp_getReccomended);
  	 search_button();
}


var resp_getReccomended = function(response){

   	var recommend =  _$("recommendation"); 
   	var dataList = response.data;
   	var str = "<table width=100% cellspacing='2' style='border:1px solid "+CONFIG.TAB_CONFIG.borderColor+";'>";
    for (var i=0;i<dataList.length;i++){
  		var data = dataList[i];
  		
  		////////var  link = CANVAS_URL + data.appUrl;
  	   var link  = SUPER_URL+"&appParams=%7B%22gameId%22%3A"+data.id+"%7D";
		var  target  = '_blank';
		if(is_super) {
		  link = 'javascript:loadGame('+data.id+')';
		  target = ''; 
		}

		str += "<tr>"+
		           '<td style="cursor:pointer;color:'+CONFIG.TAB_CONFIG.color+'; background:'+CONFIG.bgColor+';">'+
		              "<div style='height:13px;overflow:hidden;'><a style='color:"+CONFIG.textColor+";' target=_blank href='"+data.userProfile+"'>"+data.name+"</b></a></div>"+
		              "<table cellspacing=0>"+
		                 "<tr>"+
		                     "<td>"+
		                       "<div><a target=_blank href='"+data.userProfile+"'><img  style='width:35px;height:35px;' src='"+data.thumbnail+"' /></a></div>"+
		                  	 "</td>"+
		                  	 "<td style='padding-left:5px;'>"+
		                     	"<div style='color:"+CONFIG.textColor+"'>recommended:</div>"+
		                     	"<div style='height:30px;width:90px;overflow:hidden;'><a target='"+target+"'   href='"+link+"' style='color:"+CONFIG.highLightedTextColor+";font-weight:bold;'>"+data.gamename+"</a></div>"+
			                 "</td>"+
		               	"</tr>"+
		             "</table>";
		str+="</td></tr>";
	}
 	str += "</table>";
  	recommend.innerHTML = str;
}



var selectType =function(tabName)
{
   var catName = selectedCategory;
   selectTypeStyle(tabName);
   if(tabName == 'new')
   {
   req_getNewApps2(1,catName);
   }
   else if( tabName == 'RandomGames' )
   {
    req_getOtherApps();
   }
   else if(tabName == 'popular')
   {
    req_getPopularApps(1,catName);
   }
   else if(tabName =='active')
   {
      req_getActiveApps(1,catName);
   }
   
}
var resp_getCategories = function(response){
	var json=response.data.categories;
	selectedType='new';
	if(is_super)  var _class = 'ui-widget-content ui-corner-all';
	else          var _class = '';
	str='<div class="categoryTitle" style="color:'+CONFIG.highLightedTextColor+'">Categories</div>'+
	    '<table  class="'+_class+'" id="CategoryContainer" cellspacing="2" style="border:1px solid '+CONFIG.TAB_CONFIG.borderColor+'";>'+
		'<tr><td class="'+_class+'"  onclick="selectCategoryStyle(\'All\')" onmouseover="changeCategoryStyle(\'All\')" onmouseout="changeCategoryStyle(\'\')" name="All" style="cursor:pointer;color:'+CONFIG.TAB_CONFIG.color+'; background:'+CONFIG.TAB_CONFIG.bgColor+';">'+
		'<a href=# style="color:'+CONFIG.TAB_CONFIG.color+';"><b>All</b></a></td></tr>';  
	for(var i=0;i<json.length;i++){
	   if(json[i] != "")
    	str+='<tr><td class="'+_class+'" onclick="selectCategoryStyle(\''+json[i]+'\')" onmouseover="changeCategoryStyle(\''+json[i]+'\')" onmouseout="changeCategoryStyle(\'\')" name="'+json[i]+'" style="cursor:pointer;color:'+CONFIG.TAB_CONFIG.color+'; background:'+CONFIG.TAB_CONFIG.bgColor+';">'+
    	'<a href=# style="color:'+CONFIG.TAB_CONFIG.color+';"><b>'+json[i]+"</b></a></td></tr>";
   	}
   	str+="</table></div>";
    _$("leftBox").innerHTML=str;
    selectCategory("All");
    selectType('new');
    	
}
var changeCategoryStyle = function(catName)
{
    var tabDivs = _$("CategoryContainer").getElementsByTagName("td");
    for (var i=0;i<tabDivs.length;i++){
		if (tabDivs[i].getAttribute("name") == catName){
			tabDivs[i].firstChild.style.color = CONFIG.TAB_CONFIG.selectedColor;
			tabDivs[i].style.background = CONFIG.TAB_CONFIG.selectedBgColor;
		}else{
			tabDivs[i].style.color = CONFIG.TAB_CONFIG.color;
			tabDivs[i].firstChild.style.color = CONFIG.TAB_CONFIG.color;
			if(tabDivs[i].getAttribute("name") == selectedCategory)
			{
			tabDivs[i].style.background =CONFIG.TAB_CONFIG.selectedBgColor;
			}
			else 
			{
			tabDivs[i].style.background = CONFIG.TAB_CONFIG.bgColor;
			}
		}
		
}
}
var selectCategoryStyle = function(catName)
{
  var type = selectedType;
      selectCategory(catName);
      selectType(type);
}
var req_getOtherApps = function(){

    var url = serverURL+"otherApps.jsp?color="+CONFIG.textColor.substring(1,7);
    if(is_super) url+="&is_super="+is_super;
	Request.sendGET(url, resp_getOtherApps);
}
var req_getNewApps2 = function(page,categoryName){
    selectCategory(categoryName);
    request_URL = serviceURL+"/publicgame/"+GALLERY_APP_COUNT+"/"+categoryName+"/";
	Request.sendGET(request_URL+page, resp_getNewApps2);
}

var req_getNewApps = function(page){
    var url = serverURL+"publicApps.jsp?page="+page;
    if(is_super)  url+="&is_super="+is_super;
	Request.sendGET(url, resp_getNewApps);
}
var req_getPopularApps = function (page,categoryName){
    selectCategory(categoryName);
    request_URL = serviceURL+"/populargame/"+GALLERY_APP_COUNT+"/"+categoryName+"/";
    Request.sendGET(request_URL+page,resp_getNewApps2);
}
req_getActiveApps =function(page,categoryName){
   selectCategory(categoryName);
   request_URL = serviceURL+"/activegame/"+GALLERY_APP_COUNT+"/"+categoryName+"/";
   Request.sendGET(request_URL+page,resp_getNewApps2);
}

var resp_getNewApps = function(response){
	_$("newApps").innerHTML = response.text; 
	gadgets.window.adjustHeight();
}
var resp_getNewApps2 = function(response){
	PUBLIC_APPS = response.data;
	var str = getAppsHTML(PUBLIC_APPS);
	if(is_super)   var style = "border:1px solid "+CONFIG.TAB_CONFIG.selectedBgColor+";background:"+CONFIG.bgColor+";"; 
	else           var style = "border:1px solid "+CONFIG.TAB_CONFIG.borderColor+";background:"+CONFIG.TAB_CONFIG.selectedBgColor+";"; 
	_$("categoryGames").innerHTML = "<div id='aboutDiv' onmouseout='divmouseout()' onmouseover='divmouseover()' class='aboutDiv ui-widget-content ui-corner-all' style='display:none;"+style+"'></div>"+str; 
	gadgets.window.adjustHeight();
}


var	divmouseover = function(){
	overDiv = "1";
}

var	divmouseout = function(){
	overDiv = "0";
	setTimeout('hideDiv();',500);
}
var global_request = function(page)
 {
 Request.sendGET(request_URL+page,resp_getNewApps2);
 }

var getAppsHTML = function(data){
	var colCount = 5;
	var currentPage = data.page;
	var arguments="";
	var str = "<table id='tableimages' cellspacing='0' width='100%'>";
	for(var i = 0;i<data.app.length;i++){
	 
	    var rate=0; 
	    if(data.app[i].rate != 'null') rate = data.app[i].rate;

		if(i%colCount==0){
			str+="<tr>";
		}
		/////////var  link = 'http://www.myspace.com/'+data.app[i].mpAppId;
		var link  = SUPER_URL+"&appParams=%7B%22gameId%22%3A"+data.app[i].id+"%7D";
		var  target  = '_blank';
		if(is_super) {
		  link = 'javascript:loadGame('+data.app[i].id+')';
		  target = ''; 
		}
		
		var img_src = '';
		if(typeof data.app[i].imgLarge == "undefined") img_src = MP_IMG_URL+data.app[i].id+"_64.png";
		else                                           img_src =GAME_IMG_URL+data.app[i].imgLarge;
		
		str+="<td style='width:200' valign=top>"+
				"<a style='color:"+CONFIG.textColor+";font-size:10px;' href='"+link+"' target='"+target+"'>"+
				"<img src='"+img_src+"' onmouseover = 'popupDiv(event,"+i+")' onmouseout='closeDiv()' id='"+data.app[i].id+"' index='"+i+"' border='none' style='margin-right:8px'  width='64px' height='64px'></img>";
				
		str+=showRate(rate,10);
		str+="<div style='width:100px; overflow:hidden'>"+data.app[i].gamename+"</div></a></td>";
		if(i%colCount == colCount-1){
			str+="</tr>";
		}
	}
	
	var pageCount = Math.ceil(data.totalCount / GALLERY_APP_COUNT);
	str += getPagingHTML(colCount, pageCount, currentPage, "global_request");
	str += "</table>";
	return str;
}

var getPagingHTML = function(colCount, pageCount, currentPage, handler){
	var str = "";
	if (pageCount > 1){
		str += "<tr><td colspan="+colCount+" align=right>";
		for (var p = currentPage-2; p<currentPage+2;p++){
			if (p > 0 && p <= pageCount){
				var font = p == currentPage ? "bold" : "normal";
				str += "<a style='margin: 0px 7px;color:"+CONFIG.highLightedTextColor+";font-weight:"+font+"' href=javascript:"+handler+"("+p+"); >"+p+"</a>";
			}
		}
		if (currentPage < pageCount){
			str += "<a style='margin: 0px 7px;color:"+CONFIG.highLightedTextColor+"' href='javascript:"+handler+"("+(currentPage+1)+")'>Next</a>";
		}
		str += "</td><tr>";
	}
	return str;
}

var divHtml = function(index){
	var data = PUBLIC_APPS;
	
	var str = "<table><tr>"+
				"<td valign=top>"+
					"<a href='http://www.myspace.com/"+data.app[index].mpAppId+"' target='_blank'><img src='http://mp.playgamesite.com/fungames/mp_img/"+data.app[index].id+"_64.png' ></a>"+
				"</td>"+
				"<td>"+
					"<font size='2px' color='"+CONFIG.TAB_CONFIG.selectedColor+"'>";
					if (data.app[index].category != "Other"){
						str += "<div style='margin-bottom:8px;color:"+CONFIG.textColor+"'>Category: <i><b style='color:"+CONFIG.TAB_CONFIG.selectedBgColor+"'>"+data.app[index].category+"</b></i></div>";
					}
					str+=
					"<i>"+data.app[index].desc+"</i></font>"+
				"</td></tr>"+
				"<tr><td colspan='2' align='center'>"+
					"<a style='font-size:14px;color:"+CONFIG.TAB_CONFIG.selectedBgColor+"' href='http://www.myspace.com/"+data.app[index].mpAppId+"' target='_blank'><b>Play Game</b></a></td></tr>"+
				"</table>";	
	_$("aboutDiv").innerHTML = str;
}

var popupDiv=function(e,index)
{
    e||(e=window.event);
    var x=e.clientX;
    var y=e.clientY;
   setTimeout("render("+x+","+y+","+index+")",500);

}
var render=function(x,y,index)
{
    var div=_$("aboutDiv");
	var index = index;

    if(document.documentElement.clientWidth && document.documentElement.clientWidth-x<250)
       x=x-250;
    else
        x=x+15;
         
    if(document.documentElement.clientHeight && document.documentElement.clientHeight-y<130)
        y=y-130;

    if(document.documentElement.scrollLeft)
        x=x+document.documentElement.scrollLeft;
    else if(document.body.scrollLeft)
        x=x+document.body.scrollLeft;

    if(document.documentElement.scrollTop)
        y=y+document.documentElement.scrollTop;
    else if(document.body.scrollTop)  
        y=y+document.body.scrollTop;

		div.style.position = "absolute";
        div.style.left=x+"px";
        div.style.top=y+"px";
    	div.style.display = "";
    	showDiv = "1";
    	divHtml(index);
}
var closeDiv = function(){

		setTimeout('hideDiv();',500);
}
var hideDiv = function(){

	if(overDiv == "0"){
		var aboutDiv = _$("aboutDiv");
		aboutDiv.style.display = "none";
		showDiv="0";
		}		
}

var resp_getOtherApps = function(response){
	_$("categoryGames").innerHTML = response.text; 
	gadgets.window.adjustHeight();
}

//////////////////////////////////////////
var req_addToFavorites=function(){
	if (userId == null || userId == "null") return;
	var data="query=addFavorite&userId="+userId+"&appId="+gameId;
    Request.sendPOST(serviceURL,data, resp_addToFavorites);
}
var resp_addToFavorites=function(response){
    var favDiv=_$("favorite"); 
   	if (response.text == "ok"){
	   favDiv.innerHTML="";
	}
}

var showUserFavorites=function(page){
	if (userId == null || userId=="null") return;
   	selectTab("favorites");
   	Request.sendGET(serviceURL+"/getFavorites/"+userId+"/"+APP_COUNT+"/"+page, resp_showUserFavorites);
}

var resp_showUserFavorites=function(response)
{
  var json=response.data;
  var userFavorites = json.favorites;
  var currentPage=json.page;
  var str="";
     if(json.totalCount!=0)
     {
       str+="<div align='center' style='margin-top:20px' id='removeConfirm'></div>";
       str+="<table cellspacing=12>";
       for (var i=0;i<userFavorites.length;i++){
			fav = userFavorites[i];
			
			//var  link = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId="+fav.appUrl;
			var link  = SUPER_URL+"&appParams=%7B%22gameId%22%3A"+fav.gameId+"%7D";
			var  target  = '_blank';
			if(is_super) {
			  link = 'javascript:loadGame('+fav.gameId+')';
			  target = ''; 
			}
		    
			if ( i % 4 == 0) str += "<tr>";
			str += "<td><table><tr>"+
					"<td>"+
						"<div><a target='"+target+"' href='"+link+"' style='color: rgb(59,89,152); font-size: 10px;' >"+
						"<img width=64px height=64px border='medium none' style='margin-right:8px;' src='"+GAME_IMG_URL+fav.imageUrl+"' /></a></div>"+
					"</td>"+	
					"<td valign='top' style='overflow: hidden; width: 100px;'>"+
						"<a style='color:"+CONFIG.highLightedTextColor+"' target='"+target+"' href='"+link+"'><b>"+fav.gameName+"</b></a>";
			str += showRate(fav.rate,10);
			str +="<div style='margin:3px 0px;color:"+CONFIG.textColor+";'>"+fav.gameCat+"</div>"+
						"<br><div class='remove' style='color:"+CONFIG.textColor+"' onclick='showDeleteFavorite("+fav.gameId+", \""+encodeURIComponent(fav.gameName)+"\")'>Delete</div>"+
					"</td>"+
				  "</tr></table></td>";
		  	if ( i % 4 == 3) str += "</tr>";
		}
      
       var pageCount = Math.ceil(json.totalCount / GALLERY_APP_COUNT);
		str += getPagingHTML(4, pageCount, currentPage, "showUserFavorites");
		str += "</table>";
     }
     else 
     {
     str+="<center><div style='height:50px; padding-top:25px; font-size:15px;font-weight:bold; color:"+CONFIG.TAB_CONFIG.color+"'>You have no favorite game.</center>";
     }
      container.innerHTML=str;
}

var showDeleteFavorite = function(gameId, gameName){
   var confirmBox = _$('removeConfirm');
   var content="";
       content += "<div align='center' class='confirmBox' style='background:"+CONFIG.TAB_CONFIG.bgColor+";color:"+CONFIG.TAB_CONFIG.color+";border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"; '>"+
                       "Are you sure you want to remove "+decodeURIComponent(gameName)+" from favorites?"+
                       "<div class='buttonlist' style='margin-top:10px;'>"+
                       "<a style='color:"+CONFIG.TAB_CONFIG.selectedColor+";background:"+CONFIG.TAB_CONFIG.selectedBgColor+"' href='javascript:deleteFavorite("+gameId+")'>Yes</a>"+
                       "<a style='color:"+CONFIG.TAB_CONFIG.selectedColor+";background:"+CONFIG.TAB_CONFIG.selectedBgColor+"' href='javascript:removeConfirmBox()'>No</a></div>"
                 "</div>"; 
   confirmBox.innerHTML=content;
  
}

var removeConfirmBox = function(){
	var confirmBox = _$('removeConfirm');
    confirmBox.innerHTML = "";
}

var deleteFavorite = function(gameId){
     var confirmBox = _$('removeConfirm');
     confirmBox.innerHTML = "<img src='"+IMG_URL+"loading.png' >";
     var  data = "query=deleteFavorite&appId="+gameId+"&userId="+userId;
	 Request.sendPOST(serviceURL, data, resp_deleteFavorite);
}

var resp_deleteFavorite = function(response){
	  if(response.text == "ok")
	    showUserFavorites(1);
}
///////////////////////////////////////////2

var showPlayers=function(){
	selectTab("players");
    if(is_super) var _class = ' ui-widget-content ui-corner-all';
    else         var _class = '';   
	container.innerHTML = 
	 "<div class='title "+_class+"' style='color:"+CONFIG.TAB_CONFIG.selectedColor+";background:"+CONFIG.TAB_CONFIG.selectedBgColor+";border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"' >Recent Players</div>"+
	 "<div class='content "+_class+"' id=recentUsers style='border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"'><div class=loading>Loading...</div></div>"+
	 "<div id='middleAd' style='text-align:center;margin-left:20px;' ></div>"+
	 
	 "<div class='title "+_class+"' style='color:"+CONFIG.TAB_CONFIG.selectedColor+";background:"+CONFIG.TAB_CONFIG.selectedBgColor+";border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"'>Active Players</div>"+
	 "<div class='content "+_class+"' id=activeUsers style='border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"'></div>";	
	req_getRecentUsers();
	req_getActiveUsers(1);
	
	applyMiddleAd('topAd', 'middleAd');
}
var req_getActiveUsers=function(page){
	_$("activeUsers").innerHTML = "<div class=loading>Loading...</div>";
	Request.sendGET(serviceURL+"/getMostPlayed/"+PLAYERS_COUNT+"/"+page, resp_getActiveUsers);
}
var resp_getActiveUsers=function(response){
	var hours,minutes,seconds,remainder; 
  	var json=response.data;
 	var userList = json.users;
  	var currentPage=json.page;
  	var str="<table width=100%>";
  	var colCount = 5;

  	for (var i=0;i<userList.length;i++){
		var user = userList[i];
		if ( i % colCount == 0) str += "<tr>";
		 hours=(user.duration-user.duration%3600)/3600;
		 hours = hours == 0 ? "" : hours+"h ";
     	 remainder=user.duration%3600;
      	 minutes=(remainder-((remainder)%60))/60;
		 str += "<td><table><tr>"+
				"<td><a target=_blank href='"+user.profileUrl+"' ><img class='smallImg' src='"+user.thumbnailUrl+"' /></a></td>"+	
				"<td valign='top'>"+
					"<div style='color:"+CONFIG.textColor+"' class=fixedText><a style='color:"+CONFIG.highLightedTextColor+"' target=_blank href='"+user.profileUrl+"'><b>"+user.userName+"</b></a>"+
					" played <b>"+hours+minutes+"min</b></div>"+
				"</td>"+
			  "</tr></table></td>";
	  	if ( i % colCount == (colCount - 1) ) str += "</tr>";
	} 
    var pageCount = Math.ceil(json.totalCount / PLAYERS_COUNT);
    str += getPagingHTML(colCount, pageCount, currentPage, "req_getActiveUsers");
	str += "</table>";
   	_$("activeUsers").innerHTML=str;
   	gadgets.window.adjustHeight();
}

var req_getRecentUsers=function(){
	Request.sendGET(serviceURL+"/recentusers", resp_getRecentUsers);
}

var resp_getRecentUsers=function(response){
	var userList = response.data;
	var str = "<table width=100%>";
	var colCount = 5;
	for (var i=0;i<userList.length && i<colCount*5;i++){
  		var user = userList[i].user;
		var app = userList[i].app;
		
		//////var link = CANVAS_URL+app.url;
		var link  = SUPER_URL+"&appParams=%7B%22gameId%22%3A"+app.id+"%7D";
		var target = "_blank";
		if(is_super){
		   link = "javascript:loadGame("+app.id+")";
		   target = ""; 
		 
		}
		
		if ( i % colCount == 0) str += "<tr>";		
		str += "<td><table><tr>"+
			"<td><a target=_blank href='"+user.profile+"'><img class=smallImg src='"+user.thumbnail+"' /></a></td>"+	
			"<td valign='top'>"+
				"<div class=fixedText style='color:"+CONFIG.textColor+"' ><a style='color:"+CONFIG.textColor+";font-weight:bold;' target=_blank href='"+user.profile+"'>"+user.name+"</b></a>"+
				" played <a target='"+target+"' href='"+link+"' style='color:"+CONFIG.highLightedTextColor+";font-weight:bold;'>"+app.title+"</a></div>"+
			"</td>"+
		  "</tr></table></td>";
  		if ( i % colCount == (colCount -1) ) str += "</tr>";
	}
    str += "</table>";
    _$("recentUsers").innerHTML=str;
    gadgets.window.adjustHeight();
}

var search_button=function(response)
 {
    var search_div = _$("search_form"); 
    var str='<form name="search" onsubmit="return false"><table >'+
        	"<tr>"+
        		"<td ><input type='text' name='gameName'/></td>"+
        		"<td colspan=3 align='right'><input style='color:"+CONFIG.TAB_CONFIG.selectedColor+"; background:"+CONFIG.TAB_CONFIG.selectedBgColor+"; border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"' type='submit' value='Search' onclick='getCategoryGames(1)' /></td>"+
          "</tr></table></form>";
    str+="<div id='searchResult' ></div>";      
          
     search_div.innerHTML=str;
 }
 
var getCategoryGames=function(page)
  {
  var category = selectedCategory; 
  var type = selectedType;
  if (type == "RandomGames") type = "popular";
  var gameName = document.search.gameName.value;
  var result=_$("categoryGames");
  if(gameName=="" || category=="")
   {
    return;
   }
   else 
   {
    result.innerHTML = "<div  id=catGames></div>";
    request_URL = serviceURL+"/getCategoryGames/"+category+"/"+gameName+"/"+GALLERY_APP_COUNT+"/"+type+"/";
    Request.sendGET(request_URL+page, resp_getNewApps2);
   }
    
  }

//-------------------------------------- invite --------------------------------------
	
var showInvite = function(){
    selectTab("invite");
   	var str =
   	"<div style='margin: 30px 0px;'>"+
	  	"<h1 style='font-size:19px;color:"+CONFIG.textColor+"'>Send Comments to your friends.</h1>"+
	  	"<div id=friend>Loading...</div>"+
	"</div>";
    _$("container").innerHTML = str;
    Invite.show();
}

var Invite = function(){
	var curPage = 1;
	var containerId = "friend";
	var receivedFriendsCount = 0;
	var friendsTotalCount = 0;
	var cellCount=8;
	
	return {
		prev: function(){
			_$(containerId+"_"+curPage).style.display = "none";
			_$(containerId+"_"+(curPage-1)).style.display = "";
			curPage--;
			_$(containerId).setAttribute("curPage", curPage);
		},
			
		next: function(){
			var nextPage = curPage + 1;
			if (_$(containerId+"_"+nextPage)){
				_$(containerId+"_"+nextPage).style.display = "";
				_$(containerId+"_"+(nextPage-1)).style.display = "none";
			}else{
				var height = _$(containerId+"_"+curPage).offsetHeight;
				_$(containerId+"_"+curPage).style.display = "none";
				_$(containerId).innerHTML += "<div id="+containerId+"_"+nextPage+"><div class=loading style='height:"+height+"px;'>Loading...</div></div>";
				Invite.req_getFriends(nextPage);
			}
			curPage++;
			_$(containerId).setAttribute("curPage", curPage);
		},
		
		req_getFriends: function(page){
			var req = opensocial.newDataRequest();
			MyOpenSpace.DefaultPageSize = cellCount*4;
			var params = {}; 
	   		params[opensocial.DataRequest.PeopleRequestFields.FIRST] = (page-1)*MyOpenSpace.DefaultPageSize;
			req.add(req.newFetchPeopleRequest("VIEWER_FRIENDS", params), "friends");
			req.send(Invite.resp_getFriends);
		},
		
		resp_getFriends: function(response){
			var friends = response.get("friends").getData().asArray();
			allFriends = allFriends.concat(friends);
			receivedFriendsCount += friends.length;
			friendsTotalCount = response.get('friends').getData().getTotalSize();
			var str = "<table width=100%>";
			for(var i=0; i<friends.length;i++) {
				if (i % cellCount == 0) str+= "<tr>";
				var friendId = friends[i].getField(opensocial.Person.Field.ID);
			    var name = friends[i].getField(opensocial.Person.Field.NAME);
			    var thumbnail = friends[i].getField(opensocial.Person.Field.THUMBNAIL_URL);
			    var profile = friends[i].getField(opensocial.Person.Field.PROFILE_URL);
			    str += "<td name=userCell style='cursor:pointer;border:1px solid "+CONFIG.bgColor+"' onmouseover='this.style.border=\"1px solid "+CONFIG.highLightedTextColor+"\"' onmouseout='this.style.border=\"1px solid "+CONFIG.bgColor+"\"' width="+(100/cellCount)+"% >"+
							"<table valign=top width=100%>"+
								"<tr>"+
		        					"<td style='color:"+CONFIG.textColor+"' title='"+name+"'><div class=smallFont_>"+name+"</div></td>"+
			        				"<td style='display:none' align=right><input checked type=checkbox name='checkBox' id='"+friendId+"' /></td>"+
	           					"</tr>"+
	           					"<tr>"+    
									"<td><img style='cursor:pointer' onclick='inviteFriend("+friendId+")' class=smallImg src='"+thumbnail+"' /></td>"+
								"</tr>"+
							"</table>"+
						"</td>";
				if (i % cellCount == cellCount-1) str += "</tr>";
			}
			var available = receivedFriendsCount < friendsTotalCount;
			if (available || curPage>1){
				str += "<tr><td colspan="+cellCount+" align=right>";
							if (curPage>1)
							str+=
							"<a href='javascript:Invite.prev()' style='color:"+CONFIG.highLightedTextColor+";margin-right:10px;font-size:16px;font-weight:bold;'>Previous</a>";
							if (available)
							str+=
							"<a href='javascript:Invite.next()' style='color:"+CONFIG.highLightedTextColor+";margin-right:10px;font-size:16px;font-weight:bold;'>Next</a>"+
						"</td></tr>";
			}
			str += "</table>";
			_$(containerId+"_"+curPage).innerHTML = str;
			gadgets.window.adjustHeight();
		},
		
		getSelectedFriends:  function(){
			var friends = [];
			var pg = _$("friend").getAttribute("curPage");
			var inputs = _$("friend_"+pg).getElementsByTagName("input");
			for (var i=0;i<inputs.length;i++){
				if (inputs[i].checked && inputs[i].getAttribute("hasTaken")!="true"){
					var id = inputs[i].id;
					if (id != 6221){
						friends[friends.length] = id;
					}
				}
			}
			return friends;
		},
		
		show: function(id, title, img){
			var cont = _$(containerId);
			allFriends = [];
			curPage = 1;
			receivedFriendsCount = 0;
			friendsTotalCount = 0;
			var table = document.createElement("table");
			table.width="100%";
			var sendCont = document.createElement("tbody");
			var row2 = document.createElement("tr");
			sendCont.appendChild(row2);
			var cell2 = document.createElement("td");
			cell2.align = "center";
			row2.appendChild(cell2);
				
			/*var imgInvite = document.createElement("img");
			imgInvite.className = "sendButtonInvite";
			imgInvite.src = IMG_URL+"sendfriends.png";
			imgInvite.onclick = function(){
				inviteAll(id, title, img);
			};
			
			cell2.appendChild(imgInvite);*/
			table.appendChild(sendCont);
			cont.parentNode.appendChild(table);
			
			cont.innerHTML = "<div id="+containerId+"_1></div>";
			cont.setAttribute("curPage", 1);
			
			Invite.req_getFriends(curPage);
		}
	};
}();

var inviteAll = function(id, title, img) {
	var friendIndex = 0;
	var friends = Invite.getSelectedFriends();
	
	var inviteAllCallback = function(result){
		var finished = true;
		if (result == MyOpenSpace.PostTo.Result.SUCCESS) {
			friendIndex++;
			if(friendIndex < friends.length){
				finished = false;
				inviteFriend(friends[friendIndex], inviteAllCallback);
			}
		}
	}
	
	if (friends.length > 0){
		inviteFriend(friends[friendIndex], inviteAllCallback);
	}
}

var inviteFriend = function(id, callback){

    var  link = is_super ? SUPER_URL+"&appParams=%7B%22gameId%22%3A"+gameId+"%7D" : canvas_url;
    var  gameLink = is_super ? SUPER_URL+"&appParams=%7B%22gameId%22%3A"+gameId+"%7D" : gameURL;
    
	var content = "I've found this cool game. ADIIIIIICTIVE! <br><br>"+
	"<a href='"+link+"'><img src='"+gameImgUrl+"'></a><br><br>"+
	"<a href='"+gameLink+"'>Play now!</a><br>"+
	"<a target='_blank' href='"+link+"'><img src='"+IMG_URL+"/playgame.png'/></a>";

	postTo_("OMG! Check this out!", content, getFriendById(id), "COMMENTS", callback);
}

var _ptCallback = null;
var _postWhere  = null;

var postTo_ = function(subject, content, receiver, postWhere, ptCallback){

    _ptCallback = ptCallback;
    _postWhere = postWhere;
    
	var postType = MyOpenSpace.PostTo.Targets[postWhere];
	var os_token = MyOpenSpace.MySpaceContainer.OSToken;
	var message = opensocial.newMessage(content);
	message.setField(opensocial.Message.Field.TITLE, subject);
	message.setField(opensocial.Message.Field.TYPE, postType);

	osContainer.postTo(os_token, message, receiver, callback);

} 
var callback = function(result){
		if (result == MyOpenSpace.PostTo.Result.SUCCESS) {
			Request.sendPOST(reportURL, "query="+_postWhere+"&appId="+gameId, doNothing);
		}
		if (_ptCallback)  _ptCallback();
}

var doNothing = function(response){
	
}

var getFriendById = function(id){
	for (var i=0;i<allFriends.length;i++){
		if (allFriends[i].getId() == id) return allFriends[i];		
	}
}

var postInvite = function(){

    var  link = is_super ? SUPER_URL+"&appParams=%7B%22gameId%22%3A"+gameId+"%7D" : canvas_url;
    var  gameLink = is_super ? SUPER_URL+"&appParams=%7B%22gameId%22%3A"+gameId+"%7D" : gameURL;
	var content = "I've found this cool game. ADIIIIIICTIVE! <br><br>"+
		"<a target='_blank' href='"+link+"'><img src='"+gameImgUrl+"'></a><br><br>"+
		"<a target='_blank' href='"+gameLink+"'>Play now!</a><br>"+
		"<a target='_blank' href='"+link+"'><img src='"+IMG_URL+"/playgame.png'/></a>";
	
	postTo_(gameTitle, content, user, "BULLETINS", null);
	
}

var selectedTab = "";
var selectTab = function(tabName){
    if(tabName == "play"){
        window.startTime = new Date();
    }else{
	  storeDuration();
    }
	var tabDivs = _$("tabContainer").getElementsByTagName("td");	
	for (var i=0;i<tabDivs.length;i++){
		if (tabDivs[i].getAttribute("name") == tabName){
			tabDivs[i].firstChild.style.color = CONFIG.TAB_CONFIG.selectedColor;
			tabDivs[i].style.background = CONFIG.TAB_CONFIG.selectedBgColor;
		}else{
			tabDivs[i].firstChild.style.color = CONFIG.TAB_CONFIG.color;
			tabDivs[i].style.background = CONFIG.TAB_CONFIG.bgColor;
		}
	}
	//////if(tabName != "play")   access_to_play = false;
	selectedTab = tabName;
}
var selectedCategory = "";
var selectCategory = function(catName){
    var tabDivs = _$("CategoryContainer").getElementsByTagName("td");
    for (var i=0;i<tabDivs.length;i++){
		if (tabDivs[i].getAttribute("name") == catName){
		    tabDivs[i].firstChild.style.fontStyle = "italic";
			tabDivs[i].style.background = CONFIG.TAB_CONFIG.selectedBgColor;
		}else{
			tabDivs[i].firstChild.style.fontStyle = "normal";
			tabDivs[i].style.background = CONFIG.TAB_CONFIG.bgColor;
		}
		
}
    selectedCategory = catName;
}
var selectedType ="";
var selectTypeStyle = function(tabName){
    var links = _$("gameTypes").getElementsByTagName("a");
    for (var i=0;i<links.length;i++){
		links[i].style.fontWeight = links[i].parentNode.getAttribute("name") == tabName ? "bold" : "normal"; 
	}
 	selectedType = tabName;
}

var selectContainer = function(id){
	if (id == "container"){
		_$(id).style.display = "";
		_$("flashContainer").style.display = "none";
	}else
	  if( id == "flashContainer"){
		_$("container").style.display = "none";
		_$(id).style.display = "";
	}
}

var showLoading = function(){
	container.innerHTML = "<div style='border: none;'>  Loading...</div>";
	showError("");
}

var showError = function(str){
	if (str == ""){
		errorDiv.style.display = "none";
	}else{
		errorDiv.style.display = "";
		errorDiv.innerHTML = str;
	}
}

var getCanvasRandomApps = function(){
    var url = serverURL+"canvas_randomApps.jsp";
    if(is_super) url+="?is_super="+is_super;
	Request.sendGET(url, resp_getCanvasRandomApps);
}

var resp_getCanvasRandomApps = function(response){
    if(response && _$("canvas_randomApps")!=null)
     _$("canvas_randomApps").innerHTML = response.text; 

}
   
var getRandomApps = function(){
    var url = serverURL+"randomApps.jsp";
    if(typeof is_super == "undefined") is_super = false;
    
    if(is_super) url+="?is_super="+is_super;
	Request.sendGET(url, resp_getRandomApps);
}

var resp_getRandomApps = function(response){
  	_$("randomApps").innerHTML = response.text; 
  	
}

var showComments = function(){
	selectTab("comments");

	container.innerHTML = "<div  id='commentContainer'></div>";
	request_getComments(1);
}

function resp_addComment(response){
	if (response.text == "ok"){
		request_getComments(1);
	}
}

function request_getComments(page){
	//_$("commentContainer").innerHTML = "Loading...";
	Request.sendGET(serviceURL+"/getcomment/"+gameId+"/"+page+"/"+COMMENT_COUNT,response_getComments);
}

function addComment(){
	if (userId == null || userId=="null") return;

	var rate=5;
	var form = document.commentAndRate["rate"];
    for (i=0; i < form.length; i++ ){
   	     if ( form[i].checked) 
   	        rate = form[i].value;
    }
    
	var tObj = document.getElementById("textArea");
	var textValue = tObj.value;	
	if (textValue != ""){
		data = "comment="+encodeURIComponent(textValue)+"&appId="+gameId+"&query=addcomment&userId="+userId+"&rate="+rate;
		Request.sendPOST(serviceURL, data, resp_addComment);
	}
}

var replaceAll = function(oldStr,findStr,repStr) {
	var srchNdx = 0;
 	var newStr = "";
 	while (oldStr.indexOf(findStr,srchNdx) != -1) {
  		newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
		newStr += repStr;
		srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
 	}
	newStr += oldStr.substring(srchNdx,oldStr.length);
	return newStr;
}

function response_getComments(response){
	var json = response.data;
	var jsonArray = json.comments;
	
    var str =
	 '<form name="commentAndRate">'+
	 '<div class="commentDiv">'+
	    '<table class="commentTable" style="background:'+CONFIG.TAB_CONFIG.bgColor+';">'+
	         '<tr><td style="color:'+CONFIG.TAB_CONFIG.color+'"><b>Add Comment and Rate this game:</b></td></tr>'+    
	         '<tr><td>'+
	             '<table style="color:'+CONFIG.TAB_CONFIG.color+'">'+
	                '<tr>'+
	                   '<td><b>Rate: </b></td>'+
	                   '<td><input type="radio" name="rate" value="1">1</td>'+
	                   '<td><input type="radio" name="rate" value="2">2</td>'+
	                   '<td><input type="radio" name="rate" value="3">3</td>'+
	                   '<td><input type="radio" name="rate" value="4">4</td>'+
	                   '<td><input type="radio" name="rate" value="5" checked>5</td>'+
	                 '</tr>'+
	             '</table>'+   
	         '</td></tr>'+
	         '<tr><td><textarea id="textArea" style="font-size: 15px;width: 600px;  border: 1px solid '+CONFIG.TAB_CONFIG.borderColor+';"></textarea></td></tr>'+
	       // '<tr><td style="float:right;cursor:pointer;"><img style="height:30px" src="'+IMG_URL+'addComment.png" onclick="javascript:addComment()"/></td></tr>'+
	       '<tr><td><input class="sumbitComment" type="button" style="background:'+CONFIG.TAB_CONFIG.selectedBgColor+';border-color:'+CONFIG.TAB_CONFIG.borderColor+';color:'+CONFIG.TAB_CONFIG.selectedColor+';margin-left: 500px;" value="Add Comment" onclick="javascript:addComment()"/></td></tr>'+
	       
	       //  '<tr id="emptyComment"/>'+
	         '<tr><td style="color:'+CONFIG.TAB_CONFIG.color+'">For  reporting abuse go <a style="color:'+CONFIG.TAB_CONFIG.color+'" target="_blank" href="http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=440346060"><b>here</b></a></td></tr>'+
	      '</table>'+
	 '</div>'+
	'</form>';
    str += "<table width=100%>";
	  
	var jsonObj = null;
	var currentPage = json.page;
	for(var i = 0; i < jsonArray.length ; i++){
		jsonObj = jsonArray[i];
		var date = new Date(jsonObj.date);
		var hours = date.getHours();
		var minutes=date.getMinutes();
		minutes=((minutes < 10) ? "0" : "") + minutes;
		var dateStr = monthname[date.getMonth()] + " " + date.getDate() + " , " +
					  date.getFullYear() + " " + hours + ":" + minutes;
	
		var rate=0;
		if(rate != 'null') rate  = jsonObj.rate;
		str += 
		"<tr style='1px solid black'>"+
			"<td valign=top width=120px align=center>";
		str+= showRate(rate,13);
		str+='<a target=_blank href="'+jsonObj.profileUrl+'"><img class="imgStyle" src="'+jsonObj.thumbnailUrl+'"/></a>'+
			    '<div style="overflow: hidden; width: 120px;"><a style="color:'+CONFIG.highLightedTextColor+';font-size: 12px;" target=_blank href="'+jsonObj.profileUrl+'">'+jsonObj.name+'</a></div>'+
		    "</td>"+
		    "<td valign=top class=curlycontainer style='color:"+CONFIG.textColor+"'>"+
				replaceAll(jsonObj.comment, "\n", "<br/>")+
				'<div class="date" style="color:'+CONFIG.highLightedTextColor+'">'+dateStr+'</div>'+
			"</td>";
		
	    if(isAdmin)	
		    str+="<td valign=top  width=70 hwight=30>"+
				'<input type=button value="Delete" onclick="req_deleteComment('+jsonObj.id+')" />'+
			"</td>";
		
		str+="</tr>"+
		"<tr><td colspan=2><hr style='border:0.5px solid #EEEEEE;' /></td></tr>";
	}
	
	
	var pageCount = Math.ceil(json.total / COMMENT_COUNT);
	str += getPagingHTML(2, pageCount, currentPage, "request_getComments");		
	str += "</table>";

	_$("commentContainer").innerHTML = str;
	gadgets.window.adjustHeight();
}

var req_deleteComment=function(commentId){
	var data = "query=deleteComment&commentId="+commentId;
	Request.sendPOST(serviceURL, data, resp_deleteComment);
}

var resp_deleteComment = function(response){
	if(response.text == "ok"){
		request_getComments(1);
	}
}

function showRockyouAd(){
	try{
 		_ryadConfig = new Object();
		_ryadConfig.placeguid='653E624036';
		_ryadConfig.type='Leaderboard';
		
  		_$("bottomAd2").innerHTML = "<div id='_ryad_653E624036'></div>"; 
  		
		var head = document.getElementsByTagName("head");
		var script = document.createElement("script");
		script.setAttribute('src', 'http://cdn.rockyou.com/apps/ams/tag_os.js');
  		script.setAttribute('type', 'text/javascript');
  		head[0].appendChild(script);
  		
	 }catch(ex){
	 	;
	 }
}


var showRate = function(rate,h){
    var str="";
    str ="<div style='width:90px'>";
    for(var j=0;j<5;j++){
       if(j<rate)
          str += '<span><img src="'+IMG_URL+'star.png" style="height:'+h+'px"></span>';
       else  
         str += '<span><img src="'+IMG_URL+'blankstar.png" style="height:'+h+'px"></span>';
    }
	str += "</div>"; 
 	return str;
}
//--============================== Home =============================

var showHome = function(){
  selectTab("home");
  showLoading();
    if(is_super) var _class = ' ui-widget-content ui-corner-all';
    else         var _class = '';   
	container.innerHTML = 
	 "<div class='title "+_class+"'  id=newestGamesTitle style='color:"+CONFIG.TAB_CONFIG.selectedColor+";background:"+CONFIG.textColor+";border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"' >Newest Games *</div>"+
	 "<div class='content "+_class+"' id=newestGames style='border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"'><div class=loading>Loading...</div></div>"+
	 "<div id='middleAd1' style='text-align:center;'></div>"+
	 
	 "<div class='title "+_class+"' id=recentlyPopularTitle  style='color:"+CONFIG.TAB_CONFIG.selectedColor+";background:"+CONFIG.textColor+";border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"'>Recently Popular </div>"+
	 "<div class='content "+_class+"' id=recentlyPopular style='border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"'><div class=loading>Loading...</div></div>"+
	 "<div id='middleAd2' style='text-align:center;'></div>"+
	  
	 "<div class='title "+_class+"' id=mostPopularTitle style='color:"+CONFIG.TAB_CONFIG.selectedColor+";background:"+CONFIG.textColor+";border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"'>Most Popular </div>"+
	 "<div class='content "+_class+"' id=mostPopular style='border:1px solid "+CONFIG.TAB_CONFIG.borderColor+"'><div class=loading>Loading...</div></div>";
  showNewestGames();
  
  //setTimeout(" showRecentlyPopular()",2000);
  //setTimeout(" showMostPopular()",2500);
   showRecentlyPopular();
   showMostPopular();
  
  
	applyMiddleAd('topAd', 'middleAd1');
	applyMiddleAd('topAd', 'middleAd2');
  
}
// request
var showNewestGames = function(){
  var request_URL = serviceURL+"/publicgame/"+HOME_APP_COUNT+"/All/";
  var page = 1;
  Request.sendGET(request_URL+page, resp_showNewestGames);
}

var showRecentlyPopular = function(){
   var request_URL = serviceURL+"/activegame/"+HOME_APP_COUNT+"/All/";
   var page = 1;
   Request.sendGET(request_URL+page,resp_showRecentlyPopular);
}

var showMostPopular = function(){
   var request_URL = serviceURL+"/populargame/"+HOME_APP_COUNT+"/All/";
   var page = 1;
   Request.sendGET(request_URL+page,resp_showMostPopular);
}
//- ======  response
var resp_showNewestGames = function(response){
    if(response)
      _$("newestGames").innerHTML=getHomeHTML(response.data,"newestGames");
    gadgets.window.adjustHeight();
}
var resp_showRecentlyPopular = function(response){
    if(response)
      _$("recentlyPopular").innerHTML=getHomeHTML(response.data,"recentlyPopular");
    gadgets.window.adjustHeight();
}
var resp_showMostPopular = function(response){
    if(response)
      _$("mostPopular").innerHTML=getHomeHTML(response.data,"mostPopular");
    gadgets.window.adjustHeight();
}


var getHomeHTML = function(data,divID){

	if(data == null || data.totalCount == 0 ){
	 _$(divID).parentNode.removeChild( _$(divID));
	 _$(divID+"Title").parentNode.removeChild( _$(divID+"Title"));
	}
	var colCount = 3;
	var arguments="";
	var str = "<table id='tableimages' cellspacing='0' width='100%'>";
	for(var i = 0;i<data.app.length;i++){
	   
	//-==- rate	   
	    var rate=0; 
	    if(data.app[i].rate != 'null') rate = data.app[i].rate;
		if(i%colCount==0){
			str+="<tr>";
		}
    //-==- link,target
		///////var  link = 'http://www.myspace.com/'+data.app[i].mpAppId;
		var link  = SUPER_URL+"&appParams=%7B%22gameId%22%3A"+data.app[i].id+"%7D";
		var  target  = '_blank';
		if(is_super) {
		  link = 'javascript:loadGame('+data.app[i].id+')';
		  target = ''; 
		}
	//-==- img	
		var img_src = '';
		if(divID == "newestUploaded"){
		  img_src = MP_IMG_URL + data.app[i].imgLarge;		
		}else{
			if(typeof data.app[i].imgLarge == "undefined") img_src = MP_IMG_URL+data.app[i].id+"_64.png";
			else                                           img_src = GAME_IMG_URL+data.app[i].imgLarge;
		}	
   //-==- totalplays
		if(data.app[i].totalplays == null  || typeof data.app[i].totalplays == "undefined") data.app[i].totalplays = 0;
   //-==- creator
        var creatorStr = "";
        if(data.app[i].creatorId != null  || typeof data.app[i].creatorId != "undefined"){
	        var date = new Date(data.app[i].createdOn);
			var hours = date.getHours();
			var minutes=date.getMinutes();
			    minutes=((minutes < 10) ? "0" : "") + minutes;
			var dateStr = monthname[date.getMonth()] + " " + date.getDate() + " , " +
						  date.getFullYear() + " " + hours + ":" + minutes;
			 if( data.app[i].creatorName.length > 20) data.app[i].creatorName = data.app[i].creatorName.substring(0,20);
	         creatorStr = '<tr><td><b>Creator:    </b><div class=userDiv><a target="_blank" href="'+data.app[i].creatorProfile+'">'+'<img src="'+data.app[i].creatorImg+'" class=userImg /><label class=userText>'+ data.app[i].creatorName+'</label></a><div>'+'</td></tr>'+ 
						  '<tr><td><b>Created On: </b>'+dateStr+'</td></tr>'; 
   	   }
   	//-==- description,gamename
         if(data.app[i].desc.length > 150) data.app[i].desc = data.app[i].desc.substring(0,150);
         if( data.app[i].gamename.length > 20) data.app[i].gamename = data.app[i].gamename.substring(0,20);
        
   	
		str+='<td>'+
				//"<a style='color:"+CONFIG.highLightedTextColor+";font-size:10px;' href='"+link+"' target='"+target+"'>"+
				//"<img src='"+img_src+"' id='"+data.app[i].id+"' index='"+i+"' border='none' style='margin-right:8px'  width='64px' height='64px'></img>";	
		//str+=showRate(rate,10);
		//str+="<div style='width:100px; overflow:hidden'>"+data.app[i].gamename+"</div></a>  "+data.app[i].totalplays+"</td>";
		
	        '<div class="box_row" style="width: 95%;" >'+
			'<div class="tr" style="background-image: url('+IMG_URL+'tr.gif);"></div>'+
			'<div class="tl" style="background-image: url('+IMG_URL+'tl.gif);"></div>'+
			'<div class="br" style="background-image: url('+IMG_URL+'br.gif);"></div>'+
			'<div class="bl" style="background-image: url('+IMG_URL+'bl.gif);"></div>'+
			'<div class="border" >'+
				'<table cellspacing="0" cellpadding="0" style="margin-left: 5px; margin-right: 5px;">'+
				  '<tr>'+
					   '<td>'+
					    '<a style="color:'+CONFIG.highLightedTextColor+';font-size:10px;" href="'+link+'" target="'+target+'">'+
					     '<img src="'+img_src+'" id="'+data.app[i].id+'" index="'+i+'" border="1px solid gray" style="margin-right:8px"  width="80px" height="80px"></img>'+
					     showRate(rate,10)+
					    '</a>'+
					   '</td>'+
					   '<td>'+
					    // '<div class=homeText width="110px">'+'<b>'+data.app[i].gamename+'</b><br/><br/>'+data.app[i].desc+'</b><br/><br/>'+creatorStr+
					       '<table class=homeText><tr><td>'+'<b>'+data.app[i].gamename+'</b>'+'</td></tr>'+
					              '<tr><td>'+data.app[i].desc+'</td></tr>'+  
                                   creatorStr+
					       '</table>'+       
					   '</td>'+
				   '</tr>'+
				   '<tr>'+
				 	   '<td>'+
	                     '<div style="margin-top: 2px; font-size: 11px; color: gray;">Played: '+data.app[i].totalplays+'</div>'+
					   '</td>'+
					   '<td>'+
					     '<a style="border: medium none ;" href="'+link+'" target="'+target+'">'+
	                       '<img src="'+IMG_URL+'play_now.png" class="playnow_btn" />'+
	                     '</a>'+
					   '</td>'+      
				   '</tr>'+
				 '</table>'+
			  '</div>'+
			'</div>';		  
			     
		if(i%colCount == colCount){
			str+="</tr>";
		}
	}
	str += "</table>";
	return str;
}

//--=================================================================================


//---==========================================
function getGoogleAd(){
	return "<div align=center><iframe src='"+serverURL+"google_ad.html' scrolling='no' frameborder='0' width=728px height=90px></iframe></div>";   		
}
function getSocialAd(){                                                                                                
	//return '<script type="text/javascript" src="http://www.socialmedia.com/network/opensocial/js/smms.js?pop=1&pubid=561bb26204d0a44f438b4d7c3885fdc6"></script>'+
    //       '<iframe name="socialmedia_ad" id="socialmedia_ad"  style="border:0px;" width="300" height="250" scrollig="no" frameborder="0"></iframe>';
   
    return '<iframe height="250" frameborder="0" width="300" scrolling="no" name="socialmedia_ad" border="0" src="http://ads.socialmedia.com/myspace/monetize.php?width=300&height=250&pubid=561bb26204d0a44f438b4d7c3885fdc6&amp;bgcolor=FFFFFF&bordercolor=FFFFFF" id="ad1"/>';
}
function getSocialLarge(){

   return '<iframe src="http://ads.socialmedia.com/myspace/monetize.php?width=728&height=90&pubid=54d306cd0a4dd0086cac15df9dcecbaf&bgcolor=FFFFFF&bordercolor=FFFFFF" border="0" width="728" height="90" name="socialmedia_ad" scrolling="no" frameborder="0"></iframe>';
}


Request.send = function(url, method, responseHandler, data, urlencoded) {

	var req;	
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	req.onreadystatechange = function() {
		if (req.readyState == 4) {// only if req shows "loaded"
			if (req.status < 400) {// only if "OK"
				 try{
				 	req.data = eval("("+req.responseText+")"); 
				 }catch(ex){
				 	
				 }
				 req.text = req.responseText;
				 responseHandler(req);
			}
		}
	}
	if (method=="POST") {
		req.open("POST", url, true);
		if (urlencoded) req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send("" + data);
	}else{
		req.open("GET", url, true);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send(null);
	}
	
	return req;
}

Request.sendPOST = function(url, data, responseHandler) {
	if (IS_LIVE){
		var os_params = {};
		os_params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		os_params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
		os_params[gadgets.io.RequestParameters.POST_DATA] = data;
		gadgets.io.makeRequest(url, responseHandler, os_params);
	}else{
		if(undefined == data) data = '';
		Request.send(url, "POST", responseHandler, data, true);
	}
}

Request.sendGET = function(url, responseHandler) {
	if (IS_LIVE){
		var os_params = {};
		os_params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
		os_params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
		gadgets.io.makeRequest(url, responseHandler, os_params);
	}else{
		Request.send(url, "GET", responseHandler);
	}
}




////////////////////////start promotion
function checkPromotion(){
  // determine if app is installed
  var global_viewerId = 'non';
  if(opensocial.hasPermission(opensocial.Permission.VIEWER)) {
   global_viewerId = gadgets.views.getParams().viewerId;
  }
 

   var actionRedirect = gadgets.views.getParams()["goto"];
   var destination = gadgets.views.getParams()["appname"];
   var landingPage = gadgets.views.getParams()["landpage"];
   var channelName = "games";
   
   if(actionRedirect != null && actionRedirect .length > 0) {
	if(gameId  != "undefined" && gameId  != null ) channelName = "game_"+gameId ;
    var url = "http://adturns.com/channelStatistics.php?act_own=32&socialType=myspace&appId="+channelName+"&userId="+global_viewerId+"&channel=goto_"+destination;
    var os_params = {};
    os_params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
    os_params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    gadgets.io.makeRequest(url, dummyResponseHandler, os_params);
     
    if(typeof landingPage == 'undefined' || landingPage==null){
     window.location = 'http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId='+actionRedirect;
    } else {
     window.location = 'http://www.myspace.com/'+actionRedirect;
    }
   }
 };

function dummyResponseHandler(response){
 //nothing here
}
////////////////////////  end promotion