var container;
var errorDiv;
var hasTaken;
var approved;
var osContainer;
var surveyImgUrl;
var PAGE=0;
var allFriends = []; 
var friendsToInvite = [];
var presentUrl = "";
var app=null;
var superBanner = "<br><br><center><a target=_blank href="+SUPER_URL+"><img src='"+IMG_URL+"sendgift.png' ></a></center>";

var popularApps = [
{id: 28, name: "Angels"},
{id: 3,  name: "Cocktail"},
{id: 25, name: "Hug"},
{id: 57, name: "Smile"},
{id: 51, name: "Disney Character"},
{id: 72, name: "Drinkings"},
{id: 47, name: "Condom"},
{id: 27, name: "Weapon"},
{id: 56, name: "Teddy bear"},
{id: 67, name: "Dogs"},
{id: 240, name: "Simpsons"},
{id: 2,   name: "Jewellery"}
];
/*
|      3 | Cocktail          |    42803 | 
|     25 | Hug               |    33076 | 
|     28 | Angels            |    26610 | 
|     27 | Weapon            |    26398 | 
|     57 | Smile             |    25186 | 
|     34 | Disney Character  |    23283 | 
|     67 | Dogs              |    13112 | 
|     47 | Condom            |    12980 | 
|     72 | Drinkings         |    12519 | 
|     70 | Love              |    11119 | 
|    240 | Simpsons          |    10937 | 
|     22 | Motorbike         |    10606 | 
|     29 | Ice Cream         |    10420 | 
|     56 | Teddy bear        |     9823 | 
|     51 | Good Morning      |     9524 | 
|     30 | Car               |     9463 | 
|      5 | Flower            |     8579 | 
|      6 | Cartoon Character |     8535 | 
|      2 | Jewellery         |     8502 | 
|     50 | Kiss              |     7607 | 
|     55 | Heart             |     7387 | 
|    422 | Roses             |     6474 | 
|     52 | Candy             |     6375 | 
|     68 | Coffee            |     6214 | 
|     54 | Chocolate         |     5564 | 
*/
 
var isAppPopular = function(id){
	for (var i=0;i<popularApps.length;i++){
		if (popularApps[i].id == id){
			return true;
		}
	}
	return false;
}

var init = function(){
	//userId = 401096326; uncomment if you want to test with Jewellery user
	req_getHTMLToDisplay("present", null, false);
	req_getRightBar();
	embedGoogleAnalitics();
	//var data = getUserPostData();
	//Request.sendPOST(SERVICE_URL+"q"+presentId+"?t=adduser&userId="+userId+"&nopromote=1&json=1", data, initApp);
}

var req_getHTMLToDisplay = function(action, params, refresh){
	selectTab(action);
	container.innerHTML = loadingImgStr;
	if ((action == "present" ||  action == "presentlist") && IS_SIMPLE_APP){
		action += "_ananim";
	}
	Request.sendGET(SERVICE_URL+"q"+presentId+"?t="+action+"&userId="+userId+(params ? params : ''), resp_getHTMLToDisplay, CONTENT_TYPE_TEXT, refresh);
}

var resp_getHTMLToDisplay = function(response){
	container.innerHTML = response.text;
	if ($("friend") && userId != null) {
		do_present(container);
		getGiftImgUrls();
		setTimeout(middleBanner, 5000);
		if (!IS_SIMPLE_APP){// $("hiscore")
			$("addgift").style.display = "";
		}
	}	
	gadgets.window.adjustHeight();
}

var do_present=function(container){
	var inviteObj = new FriendSelector("friend", [sendPresent,invite], "Send Your Gift", true,"<b>By clicking the button above you'll be given an opportunity also to send message about the sent gift.</b>");	
}

var giftImgUrls = [];
var getGiftImgUrls = function(){
	var form = $("gift_selector");
	presentUrl = form.name;
	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');
	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;
		}
	}
	var textarea=$('giftMessageArea');
	var message=textarea.value;
	postData+="&giftMessage="+encodeURIComponent(message);
	var checked = 0;
	if ($("ananimcheckbox")){
		checked = $("ananimcheckbox").checked ? 1 : 0;
	}
	var action = IS_SIMPLE_APP ? "present_ananim&isAnanim="+checked : "present";
	Request.sendPOST(SERVICE_URL+"q"+presentId+"?t="+action+"&userId="+userId, postData, doNothing);
}

var req_getRightBar = function(){
	if (IS_SIMPLE_APP && app && app.approved == "1"){
		$("rightbar").innerHTML = "<iframe src='http://s2.appotec.com/ha/gift_m/ad_intern_banner.html' scrolling='no' frameborder='0' width=160px height=550px></iframe>";		
	}else if(!IS_SIMPLE_APP){
		Request.sendGET(SERVICE_URL+"q"+presentId+"?t=rightbar&userId="+userId+"&nopromote=1", resp_getRightBar, CONTENT_TYPE_TEXT, false);
	}
}

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");
	refreshIframes();
   	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.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 = "Send "+presentName+" to your friends.";
	var imgStr = "";
	for (var i=0;i<giftImgUrls.length;i++){
		imgStr += "<a target='_blank' href='"+MP_APP.CANVAS_URL+"'><img boder='0px' style='margin:8px;' src='"+giftImgUrls[i]+"' /></a>";
	}
	var content =
	"<b>Hey!<br/>"+
	"See how nice <a target='_blank' href='"+MP_APP.CANVAS_URL+"'>"+presentName+"</a> I've got. "+
	"<br>You may also <a target='_blank' href='"+MP_APP.CANVAS_URL+"'>send "+presentName+"</a> to your friends!</b><br>"+imgStr;
	content += superBanner;
	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='"+MP_APP.CANVAS_URL+"'>"+presentName+"s.</a>"+
	"<br>You may also <a href='"+MP_APP.CANVAS_URL+"'>send "+presentName+"</a> to me and your friends!!!<br><br>";
	content += getPostContent();
	content += superBanner;
	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='"+MP_APP.CANVAS_URL+"'>"+presentName+"s.</a>"+
	"<br>You may also <a href='"+MP_APP.CANVAS_URL+"'>send "+presentName+"</a> to me and your friends!!!<br><br>";
	content += getPostContent();
	content += superBanner;
	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='"+MP_APP.CANVAS_URL+"'><img border='0px' src='"+imgs[i].src+"' >&nbsp;</a>";
				sentGifts[sentGifts.length] = imgs[i].src;
			}
		}
	}
	content += "<br><br>Send <a href='"+MP_APP.CANVAS_URL+"'>"+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='"+MP_APP.CANVAS_URL+"'><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){
		var subject = "I have just sent "+presentName+" to my friends!!!";
		var content = 
		"<b>I have sent <a href='"+MP_APP.CANVAS_URL+"'>"+presentName+"</a> to my friends."+
		"<br><br><img border='0px' style='margin:8px;' src='"+selectedPresentImg+"' />"+
		"<br><br>You may also <a href='"+MP_APP.CANVAS_URL+"'>send "+presentName+"</a> to me and your friends!!!</b>";
		var additionalGifts = "";
		for (var i=0;i<giftImgUrls.length;i++){
			additionalGifts += "<a href='"+MP_APP.CANVAS_URL+"'><img border='0px' src='"+giftImgUrls[i]+"' >&nbsp;</a>";
		}
		content += "<br><br><b>See also</b><br><br>"+additionalGifts;
		content += superBanner;
		
		var postComment = function(){
			if (selectorObj.isCommentChecked()){
				postTo_(subject, content, user, "COMMENTS");	
			}
		}
		
		if (selectorObj.isBulletinChecked()){
			postTo_(subject, content, user, "BULLETINS", postComment);	
		}else{
			postComment();
		}
	}
}
var linkToSuper = "";
var fillBody = function(){
	if (typeof IS_SIMPLE_APP == "undefined") IS_SIMPLE_APP = false;
	linkToSuper = SUPER_URL+"&appParams=%7B%22presentId%22%3A"+presentId+"%7D";
	/*if (!isAppPopular(presentId)){
		window.location.href = linkToSuper;
		return;
	}*/
	var inboxTabName = presentId==2266 ? "Your Valentines" : "Received";
	allContent = $("allContent");
	allContent.innerHTML = 
	'<div id=superlink style="display:none;border: 1px solid #eac237; background: #f8e298; padding: 5px; font-size: 12px;"><a target="_blank" href="'+linkToSuper+'" style="text-decoration: none; color: #a40f00; font-family: verdana;"><b>Super Gifts App is now Availible!</b> Send thousands of gifts from <u>ONLY ONE APP!!!!</u> <u><b>Click Here to UPGRADE NOW!</b></u></a></div>'+ 
	//"<iframe src='http://s2.appotec.com/ha/gift_m/ad_intern_horiz.html' scrolling='no' frameborder='0' width=735px height=40px></iframe>"+
	'<table><tr>'+
	'<td><table cellspacing=0 cellpadding=0>'+
		'<tr class="tabs" id="tabContainer">'+
			'<td name=present id="present"><a href="javascript:req_getHTMLToDisplay(\'present\')">Send '+presentName+'</a></td>'+
			'<td name=presentlist id="presentlist"><a href="javascript:req_getHTMLToDisplay(\'presentlist\')">'+inboxTabName+'</a></td>'+
			'<td name=sentpresent id="sentpresent"><a href="javascript:req_getHTMLToDisplay(\'sentpresent\')">Sent</a></td>'+
			//'<td name=topusers><a href="javascript:req_getHTMLToDisplay(\'topusers\')">Top Users</a></td>'+
			'<td id=newapps name=newapps><a href="javascript:req_getHTMLToDisplay(\'newapps\')">New Gifts</a></td>'+
			'<td id=simplelist name=simplelist><a href="javascript:req_getHTMLToDisplay(\'simplelist\')">Top Gifts</a></td>'+
			'<td name=addgift id="addgift" style="display:none"><a href="javascript:showAddGift()">Add New Gift</a></td>'+
			'<td name=invite id="invite"><a href="javascript:inviteViaBulletin()">Invite Friends</a></td>'+
		'</tr>'+
	'</table></td>'+
	'<td id=enableMail style="padding-left:20px;"></td>'+
	'</tr></table>'+
		
	//'<div id="top_banner" style="margin-top:5px;" ><iframe src="http://ads.socialmedia.com/myspace/monetize.php?width=645&height=60&pubid=fa49ebd62e3dd022fc7f436d4ce36494&bgcolor=FFFFFF&bordercolor=FFFFFF" border="0" width="645" height="60" name="socialmedia_ad" scrolling="no" frameborder="0"></iframe></div>'+
	'<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script><script type="text/javascript">_uacct = "UA-5234570-1";urchinTracker();</script>'+
	'<table class=container><tr>'+
		'<td width=80% valign=top>'+
			'<div id="top_banner" style="margin-top:5px;" >'+getAd(TOP)+'</div>'+
			'<div id=error style="display: none"></div>'+
			'<div id=container><div class=loading><img src="http://s2.appotec.com/ha/gift_m/images/loading.gif" /></div></div>'+
			'<div style="margin-top:10px;" id="bottom_banner"></div>'+
			'<br><br><br><br>'+
		'</td>'+
		'<td id=rightbar width=20% valign=top style="padding:0px 10px;">'+
		'</td>'+
	'</tr></table>';
	//'<div style="margin-top:20px;" id="adDiv2">'+getAd(2)+'</div>';
	if (IS_SIMPLE_APP){
		$("sentpresent").style.display="none";
		$("newapps").style.display="none";
		$("simplelist").style.display="none";
		$("superlink").style.display="none";
		$("invite").firstChild.href="javascript:postInvite()";
		$("invite").firstChild.innerHTML="Post Bulletin";
	}
	getAppInfo();
	container = $("container");
	errorDiv = $("error");
	getUser();
	setTimeout(bottomBanner, 10000);
}
var MP_APP = {};
var getAppInfo=function(){
	var mpApp = opensocial.getEnvironment().currentApplication;
	MP_APP.ICON_LARGE = mpApp.getField("ICON_LARGE");
	MP_APP.ICON_SMALL = mpApp.getField("ICON_SMALL");
	MP_APP.ID = mpApp.getField("ID");
	MP_APP.NAME = mpApp.getField("NAME");
	MP_APP.PROFILE_URL = mpApp.getField("PROFILE_URL");
	MP_APP.CANVAS_URL = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId="+MP_APP.ID;
}

var hideTabs = function(msg) {
	req_getRightBar();
	req_getHTMLToDisplay("present");
	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.style.left = (70+MP_APP.NAME.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 "+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-2";urchinTracker();';
  head[0].appendChild(script);
 }catch(ex){}
}


function bottomBanner() {
	$('bottom_banner').innerHTML = getAd(BOTTOM);
	gadgets.window.adjustHeight();
}

function middleBanner() {
	/*var rnd = Math.floor(Math.random()*100);
	if (rnd < 96){
		$('middle_banner').innerHTML = '<iframe src="http://ads.socialmedia.com/myspace/monetize.php?width=645&height=60&pubid=11359c3c7acf301dd668000ce532abe7&bgcolor=FFFFFF&bordercolor=FFFFFF" border="0" width="645" height="60" name="socialmedia_ad" scrolling="no" frameborder="0"></iframe>';
		//$('middle_banner').innerHTML = '<iframe src="http://s2.appotec.com/ha/gift_m/?t=ad&userId=400519169" border="0" width="645" height="60" name="socialmedia_ad" scrolling="no" frameborder="0"></iframe>';
	}else{
		$('middle_banner').innerHTML ='<iframe src="http://adturns.com/ad.php?c=35" width="640" height="100" style="border: none; overflow: hidden" scrolling="no" frameborder="0" />';
		//$('middle_banner').innerHTML = '<iframe src="http://www.easysurveymaker.com/surveymaker/showad.jsp" width="640" height="60" style="border: none; overflow: hidden" scrolling="no" frameborder="0" />';
		//http://adturns.com/ad.php?c=30
	}*/
	$('middle_banner').innerHTML = getAd(MIDDLE);
	gadgets.window.adjustHeight();
}


var level = 0;

function showAddGift(){
	selectTab('addgift');
	$("top_banner").style.display = "none";
	$("bottom_banner").style.display = "none";
	level = 0;
	var str = '<div id=error></div>'+
			  '<div id=giftSpace></div>'+
			  '<div><a href="javascript:addGift()">Add One More Gift</a></div>'+
			  '<input id="sendReqBut" style="float:right" type=button value="Add Gifts" onclick="req_addGift()" />';
	container.innerHTML = str;
	addGift();
}

function addGift(){
	level++;
	var str = 
	'<table id=gift'+level+'>'+
		'<tr>'+
			'<td width="30%" style="color: rgb(85, 85, 85); font-size: 11px; font-weight: bold;">Gift Name</td>'+
			'<td><input id="giftname'+level+'" type="text" name="title3" style="width: 286px;"/></td>'+
			'<td coslpan=2 valign=top><img onclick="deleteGift('+level+')" src="http://s2.appotec.com/ha/gift_m/images/delete.gif" /></td>'+
		'</tr>'+
		'<tr>'+
			'<td style="color: rgb(85, 85, 85); font-size: 11px; font-weight: bold;">Gift Picture</td>'+
			'<td>'+
				'<img id="giftimg'+level+'" width=100px height=100px src="http://s2.appotec.com/ha/gift_m/images/noimage.jpg" /><br>'+
				'<form onsubmit="return AIM.submit(this, {onStart : uploadStarted, onComplete : uploadCompleted, id:'+level+'})" enctype="multipart/form-data" action="http://s2.appotec.com/ha/gift_m/?t=upload&userId='+userId+'&level='+level+'" method="post">'+ 
					'<input id="uploadField'+level+'" type="file" id="fileUpload" name="file"/><input id="submit'+level+'" type="submit" value="Upload"/>'+
				'</form>'+
			'</td>'+
		'</tr>'+
	'</table>';
	$("giftSpace").innerHTML += str;
	gadgets.window.adjustHeight();
}

function deleteGift(level){
	$("gift"+level).parentNode.removeChild($("gift"+level));	
}

function uploadStarted(level) {
   var re_text = /\.jpg|.jpeg|.gif/i; 
   var filename = $("uploadField"+level).value;
   /* Checking file type */
   if (filename.search(re_text) == -1){
        alert("File does not have text(jpg, jpeg) extension");
        return false;
    }
	$("submit"+level).disabled = true;
    return true;
}

function uploadCompleted(level) {
	$("submit"+level).disabled = false;
	$("submit"+level).setAttribute("uploaded", "true");
	$("giftimg"+level).src = "http://s2.appotec.com/ha/gift_m/cache/img_upload/"+userId+"_"+level+"_100.jpg?v="+Math.random();
}

function req_addGift(){
	var tables = container.getElementsByTagName("table");
	var data = '';
	for (var i=0;i<tables.length;i++){
		var level = tables[i].id.substring(4,tables[i].id.length);
		if ($("submit"+level).getAttribute("uploaded") == "true"){
			var name = $('giftname'+level).value;
			if (name == ""){
				$("error").innerHTML = ("Fill in gift names.");
			}else{
				data += '&gifts[' + level + ']=' + name;
			}
		}
	}
	if (data != ''){
		$("sendReqBut").disabled = true;
		Request.sendPOST(SERVICE_URL+"q"+presentId+"?t=addgift&userId="+userId, data, resp_addGift);
	}else{
		$("error").innerHTML = ("You haven't uploaded any gift.");
	}
}

function resp_addGift(response){
	$("sendReqBut").disabled = false;
	container.innerHTML = "<div class='heading'>Thank you for uploading new gifts. <br>We will review and publish them to our gallery in order they are compatable with the application.</div>";
}