var container;
var errorDiv;
var hasTaken;
var approved;
var osContainer;
var surveyImgUrl;
var PAGE=0;
var allFriends = []; 
var friendsToInvite = [];
var presentUrl = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=119740";
var app=null;

var init = function(){
	req_getHTMLToDisplay("weaponhome");
	embedGoogleAnalitics();
	var data = getUserPostData();
	Request.sendPOST(SERVICE_URL+"q"+presentId+"?t=adduser&userId="+userId+"&nopromote=1&json=1&ajax=1", data, doNothing); 
}

var req_getHTMLToDisplay = function(action, params){
	selectTab(action);
	container.innerHTML = loadingImgStr;
	var randomP = Math.random();
	Request.sendGET(SERVICE_URL+"q"+presentId+"/?ajax=1&t="+action+"&userId="+userId+"&randomP="+randomP+(params ? params : ''), resp_getHTMLToDisplay, CONTENT_TYPE_TEXT);
}

var resp_getHTMLToDisplay = function(response){
	container.innerHTML = response.text;
	if ($("friend")) {
		do_present(container);
		getGiftImgUrls();
	}
	if($("moodcanvas")){
		
	}
	gadgets.window.adjustHeight();
}

var do_present=function(container){
	var inviteObj = new FriendSelector("friend", [sendPresent,invite], "Send Gift", true, "By clicking Attack you'll be given an apportunity also to comment about attack on selected friends' profile.");	
}

var giftImgUrls = [];
var getGiftImgUrls = function(){
	var form = $("gift_selector");
	var imgs = form.getElementsByTagName("img");
	for (var i=0;i<imgs.length;i++){
		giftImgUrls[giftImgUrls.length] = imgs[i].src;
	}
}

var selectedPresentImg;
var sendPresent=function(friends){
	var postData="";
	for(var i=0; i<friends.length; i++){
		postData+="ids[]="+friends[i].id+"&";
		postData+="names[]="+friends[i].name+"&";
		postData+="profiles[]="+friends[i].profile+"&";
		postData+="pictures[]="+friends[i].thumbnail+"&";
	}
	var form=$('gift_selector');
	selectedPresentImg = null;
	var inputs=form.getElementsByTagName("input");
	for(var i=0; i<inputs.length; i++){
		if(inputs[i].type=="radio" && inputs[i].checked==true){
			postData+="&gift_selector="+inputs[i].value;
			selectedPresentImg = $("giftimg_"+inputs[i].value).src;
			break;
		}
	}
	if (selectedPresentImg){
		//var textarea=$('giftMessageArea');
		var message=" ";
		postData+="&giftMessage="+message;
		Request.sendPOST(SERVICE_URL+"q"+presentId+"/?t=weaponhome&userId="+userId, postData, resp_afterAtack, CONTENT_TYPE_JSON);
		$("selectWeaponError_top").innerHTML = "";
		$("selectWeaponError_bottom").innerHTML = "";
	}else{
		$("selectWeaponError_top").innerHTML = "Please, select a weapon.";
		$("selectWeaponError_bottom").innerHTML = "Please, select a weapon above.";
	}
}

var resp_afterAtack = function(response){
	var message = response.data.message;
	var money = response.data.money;
	var count = response.data.count;
	var lvl = response.data.lvl;
	$('money_block').innerHTML = money;
	$('weapon_count_'+lvl).innerHTML = count;
	$('attack_msg').innerHTML = message;
	$('attack_msg').style.display = 'block'; 
}

var req_getRightBar = function(){
	Request.sendGET(SERVICE_URL+"q"+presentId+"/?t=rightbar&userId="+userId+"&nopromote=1", resp_getRightBar, CONTENT_TYPE_TEXT);
}

var resp_getRightBar = function(response){
	$("rightbar").innerHTML = response.text;
	gadgets.window.adjustHeight();
}

var friendIndex = 0;
var defaultInviteMessage = opensocial.newMessage("Hey I'm sending you [app]. Take it.");

var inviteViaBulletin = function(forwardToResultsPage){
	selectTab("invite");
   	var str = "<center><h1 style='font-size:19px'>Invite Your Friends to have more fun!!!<br/></h1>"+
   			"<img style='cursor:pointer' src='"+IMG_URL+"bulletin_red.png' onclick='postInvite()' ></center>";
	str += "<div style='margin: 30px 0px;'><div id=friend><div></div>";
    container.innerHTML = str;
    var inviteObj = new FriendSelector("friend", [sendOnlyInvitation], "Invite", false);
}


var postInvite = function(){
	var subject = "Attack your friends.";
	var imgStr = "";
	for (var i=0;i<giftImgUrls.length;i++){
		imgStr += "<a target='_blank' href='"+presentUrl+"'><img boder='0px' style='margin:8px;' src='"+giftImgUrls[i]+"' /></a>";
	}
	var content =
	"<b><a target='_blank' href='"+presentUrl+"'>Attack your friends. Become Marshall</a><br><br>"+imgStr;
	postTo_(subject, content, user, "BULLETINS");
}

var postWhatWasReceived = function(count, placeToPost){
	var subject = "I have received "+count+" "+presentName+"s!!!";
	var content = 
	"<b>I have received "+count+" <a href='"+presentUrl+"'>"+presentName+"s.</a>"+
	"<br>You may also <a href='"+presentUrl+"'>send "+presentName+"</a> to me and your friends!!!<br><br>";
	content += getPostContent();
	placeToPost = placeToPost ? placeToPost : "BULLETINS";
	postTo_(subject, content, user, placeToPost);
}

var postWhatWasSent = function(count, placeToPost){
	var subject = "I have sent "+count+" "+presentName+"s!!!";
	var content = 
	"<b>I have sent "+count+" <a href='"+presentUrl+"'>"+presentName+"s.</a>"+
	"<br>You may also <a href='"+presentUrl+"'>send "+presentName+"</a> to me and your friends!!!<br><br>";
	content += getPostContent();
	placeToPost = placeToPost ? placeToPost : "COMMENTS";
	postTo_(subject, content, user, placeToPost);
}

var getPostContent = function(){
	var content = "";
	var imgs = container.getElementsByTagName("img");
	var sentGifts = [];
	for (var i=0;i<imgs.length;i++){
		if (imgs[i].name == 'gift'){
			var isSent = false;
			for (var j=0;j<sentGifts.length;j++){
				if (imgs[i].src == sentGifts[j]){
					isSent = true; break;
				}
			}
			if (!isSent){
				content += "<a href='"+presentUrl+"'><img border='0px' src='"+imgs[i].src+"' >&nbsp;</a>";
				sentGifts[sentGifts.length] = imgs[i].src;
			}
		}
	}
	content += "<br><br>Send <a href='"+presentUrl+"'>"+presentName+"</a> to your friends!!!</b>";
	
	var additionalGifts = "";
	for (var i=0;i<giftImgUrls.length;i++){
		var isSent = false;
		for (var j=0;j<sentGifts.length;j++){
			if (giftImgUrls[i] == sentGifts[j]){
				isSent = true; break;
			}
		}	
		if (!isSent){
			additionalGifts += "<a href='"+presentUrl+"'><img border='0px' src='"+giftImgUrls[i]+"' >&nbsp;</a>";
		}
	}
	if (additionalGifts != ""){
		content += "<br><br><b>See also</b><br><br>"+additionalGifts;
	}
	return content;
}

var postWhatWasJustSent = function(friends, selectorObj){
	if (app!=null && app.approved && app.approved==1 || userId == ADMIN_USER){
		var subject = "I have just attacked my friends with "+presentName+"!!!";
		var content = 
		"<b>I have just attacked my friends with <a href='"+presentUrl+"'>"+presentName+"</a>."+
		"<br><br><img border='0px' style='margin:8px;' src='"+selectedPresentImg+"' />"+
		"<br><a href='"+presentUrl+"'>Let's see what you can do!!!</a>";
		
		var postComment = function(){
			if (selectorObj.isCommentChecked()){
				postTo_(subject, content, user, "COMMENTS");	
			}
		}
		
		if (selectorObj.isBulletinChecked()){
			postTo_(subject, content, user, "BULLETINS", postComment);	
		}else{
			postComment();
		}
	}
}

var fillBody = function(){
	allContent = $("allContent");
	allContent.innerHTML = 	'<div style="background: black;padding: 10px; color: #e8280a; font-family: verdana">'+
	'<img src="http://s2.appotec.com/ha/gift_m/images/weapons_logo.jpg" />'+
	'<div style="margin: 6px; padding: 5px; border: 1px solid #be8809; color: #9b210e; position: relative; background: black; font-weight: bold;">'+
	'<a style="cursor: pointer; margin: 10px; color: #fcc906;" onclick="req_getHTMLToDisplay(\'weaponhome\')">Home</a>'+
	'<a style="cursor: pointer; margin: 10px; color: #fcc906;" onclick="req_getHTMLToDisplay(\'buyweapon\')">Buy Weapons</a>'+
	'<a style="cursor: pointer; margin: 10px; color: #fcc906;" onclick="req_getHTMLToDisplay(\'recentattacks\')">Recent Attacks</a>'+
	'<a style="cursor: pointer; margin: 10px; color: #fcc906;" onclick="req_getHTMLToDisplay(\'weapontop\')">Top Attackers!!!</a>'+
	'<a style="cursor: pointer; margin: 10px; color: #fcc906;" onclick="inviteViaBulletin()">Challenge Friends</a>'+
	'</div>'+
	'<div>'+getAd()+'</div>'+
	'<div id=container>'+
		'<div class=loading><img src="http://s2.appotec.com/ha/gift_m/images/weapons_loading.gif" /></div>'+
	'</div>'+
	'<div id="bottom_banner"></div><br>'+
	'<div style="color:#9B210E;font-weight:bold;">Contact us at appotec@gmail.com</div>'+
	'<br><br><br>';
	
	container = $("container");
	errorDiv = $("error");
	getUser();
	setTimeout(bottomBanner, 10000);
}

function bottomBanner() {
	if (userId == null) return;
	$('bottom_banner').innerHTML = getAd(BOTTOM);
	gadgets.window.adjustHeight();
	setTimeout(bottomBanner, 30000);
}

var hideTabs = function(msg) {
	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.className = "wizardBox-dlg";
	wizardBox.id = "wizardBox-dlg";
	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 "+presentName+"</div>";
	document.body.appendChild(wizardBox);
}

function embedGoogleAnalitics(){
 try{
  var head = document.getElementsByTagName("head");
  var script = document.createElement("script");
  script.setAttribute('src', 'http://www.google-analytics.com/urchin.js');
  script.setAttribute('type', 'text/javascript');
  head[0].appendChild(script);
  
  var script = document.createElement("script");
  script.setAttribute('type', 'text/javascript');
  script.text = '_uacct = "UA-5234570-8";urchinTracker();';
  head[0].appendChild(script);
 }catch(ex){}
}


