var SERVER_URL = "http://gt.doflirt.com/textGenerator/";
var IMG_URL = SERVER_URL+"images/";
var HEART_URL = SERVER_URL+"hearts/";
var Request = new Object();
var user;
var userId = null;
var ownerId = null;
var allContent;
var container;
var osContainer;
var global_style = "font_vibrato";
var selectedTab = "";
var text = "";
var height = "";
var width = "";
var fontName = "28DaysLater";
var fontColor = "#9E4285";
var shadowColor = "#685a68";
var backgroundColor = "#fdfdfc"; 
var fontSize = "36";
var images = ["28DaysLater", "20thfaux", "BTTF", "batmfa__", "BLADRMF_", "X_BAMBI", "ARGOS", "AARDC___", "abaddon", "AC______", "Arggotsc", "Ayuma2yk", "Bastarda-K", "Cardinal-Alternate", "chp-fire", "CuxhavenTimes", "SEAWFA__", "BlackCastleMF", "Bosox", "CAPTH___", "athena_u"];
var styles = ["font_vibrato", "font_wavy", "font_colourful", "font_fuzzy", "font_slewed", "font_extrude", "font_upsidedown", "font_beveled", "font_tile", "font_gradient" ];
var canvas_url = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=121836";
var hearts_canvas_url = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=121192";
var glitter_canvas_url = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=120054";
var tease_canvas_url = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=123842";
var funny_canvas_url = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=123711";
var message_img_url = "";
var appParams;
var senderId = null, appId, appName, giftType, senderThumbnail, senderProfile, senderTypeId, senderName, giftTypeId;
var recievers = [];
var isIE    =  window.ActiveXObject ? true : false;
var isShared = false;
var lastSharedImgUrl = "";

function getUser() {
	osContainer = opensocial.Container.get();
    var req = opensocial.newDataRequest();
    var paramViewer = {};
    paramViewer[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
    [MyOpenSpace.Person.Field.COUNTRY,
     MyOpenSpace.Person.Field.CITY];

    var paramOwner = {};
     paramOwner[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
    [MyOpenSpace.Person.Field.NAME];
     
    req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER, paramViewer), "viewer");
    req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER, paramOwner), "owner");
    req.send(resp_getUser);
}

function resp_getUser(data) {
    try{
        user = data.get("viewer").getData();
        userId = user.getId();

	var owner = data.get("owner").getData(); 
	ownerId = owner.getId();	

        if (userId == null || userId=="null"){
     	   showMask();
        }else{
        	  fill();
        }
    }catch(ex){
    	showMask();
    }
}

function showMask(){
	 var bodyMask = document.createElement("div");
	var title = "Cool Text Graphics Generator";
	 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.style.left = (75+title.length*10)+"px";
	 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 <b>Cool Text Graphics Generator</b></div>";
	 document.body.appendChild(wizardBox);
}

Request.sendPOST = function(url, data, responseHandler) {
	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);
}

Request.sendGET = function(url, responseHandler) {
	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);
}

var _$ = function(id){
	return document.getElementById(id);
}
var openTextStyles = function(obj) {
	var div = _$("openedStyles");
	var display = div.style.display;
	if(display == "none") {
		var top = findPosY(obj);
		var left = findPosX(obj);
	   	div.style.top = top + 35 + "px";
	   	div.style.left = left + "px";
	   	div.style.display = "";
	} else {
		div.style.display = "none";
	}
}

var openFonts = function(obj) {
	var div = _$("openedFonts");
	var display = div.style.display;
	if(display == "none") {
		var top = findPosY(obj);
		var left = findPosX(obj);
	   	div.style.top = top + 35 + "px";
	   	div.style.left = left + "px";
	   	div.style.display = "";
	} else {
		div.style.display = "none";
	}
	
}

var openSizes = function(obj) {
	var div = _$("openedSizes");
	var display = div.style.display;
	if(display == "none") {
		var top = findPosY(obj);
		var left = findPosX(obj);
	   	div.style.top = top + 30 + "px";
	   	div.style.left = left + "px";
	   	div.style.display = "";
	} else {
		div.style.display = "none";
	}
	
}

var selectFont = function(obj, font_name) {
	fontName = font_name;
	_$("tr_0").innerHTML = obj.innerHTML;
	_$("openedFonts").style.display = "none";
	req_generateText();
}

var selectStyle = function(obj, style) {
	global_style = style;
	_$("s_0").innerHTML = obj.innerHTML;
	_$("openedStyles").style.display = "none";
	req_generateText();
}

var selectSize = function(obj, size) {
	fontSize = size;
	_$("td_0").innerHTML = obj.innerHTML;
	_$("openedSizes").style.display = "none";
	req_generateText();
}

var selectFontColor = function(id) {
	$('#'+id).farbtastic('#color1', selectFontColorCallback);
	_$(id).style.display = "";
}

var selectFontColorCallback = function() {
	fontColor = _$("color1").value;
	_$('colorpicker1').style.display = "none";
	req_generateText();
}

var selectBackgroundColor = function(id) {
	$('#'+id).farbtastic('#color2', selectBackgroundColorCallback);
	_$(id).style.display = "";
}

var selectBackgroundColorCallback = function() {
	backgroundColor = _$("color2").value;
	_$('colorpicker2').style.display = "none";
	req_generateText();
}

var selectShadowColor = function(id) {
	$('#'+id).farbtastic('#color3', selectShadowColorCallback);
	_$(id).style.display = "";
}

var selectShadowColorCallback = function() {
	shadowColor = _$("color3").value;
	_$('colorpicker3').style.display = "none";
	req_generateText();
}

var req_generateText = function() {
	_$("error").innerHTML = "";
	text = _$("text").value;
	height = _$("height").value;
	width = _$("width").value;
	
	if(text == "") {
		errorDiv.innerHTML = "<b style='color: red'> Text can not be empty ! </b>";
	} else if(parseInt(height) > 900 || parseInt(width) > 950) {
		errorDiv.innerHTML = "<b style='color: red'>Height or Width can not have length larger than 950. </b>";
	}else {
		_$("genHeart").innerHTML = "Generating...";
		var data = 	"fontName=" + fontName + "&fontSize=" + fontSize + 
					"&text=" + text + "&userId=" + userId +"&fontColor=" + fontColor +
					"&backgroungColor=" + backgroundColor + "&height=" + height + 
					"&width=" + width + "&shadowColor=" + shadowColor +"&style=" + global_style;
		
		Request.sendPOST(SERVER_URL+"index.php", data, resp_generateText);
	}
}

var resp_generateText = function(response) {
	var img_url = response.text.substring(1, response.text.length-1);
	var t = new Date();
	t = t.getTime();
	_$("genHeart").innerHTML = '<img style="padding-left: 15px;" src="'+SERVER_URL+img_url+'?t='+t+'">';
	_$("genHeart").style.height = parseInt(height)+"px";
	_$("forSave").style.display = "";
	setTimeout("gadgets.window.adjustHeight()", 2000);
}

document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

var findPosX = function(obj) {
	var curleft = 0;
	try{
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				curleft += obj.offsetLeft;
				obj = obj.offsetParent;
			}
		} else if (obj.x) curleft += obj.x;
	}catch(ex){}
	return curleft;
}

var findPosY = function(obj) {
	var curtop = 0;
	try {
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				curtop += obj.offsetTop;
				obj = obj.offsetParent;
			}
		} else
		 if (obj.y) curtop += obj.y;
	}catch(ex){}
	return curtop;
}

var selectTab = function(tabName){
	var tabDivs = _$("tabContainer").getElementsByTagName("td");	
	for (var i=0;i<tabDivs.length;i++){
		if (tabDivs[i].getAttribute("name") == tabName){
			tabDivs[i].className = "selected";
		}else{
			tabDivs[i].className = "";
		}
	}
	selectedTab = tabName;
}

var showInvite = function(imgUrl, shared){
	if(shared == "shared") {
		isShared = true;
	} else {
		isShared = false;
		selectTab("images");
		_$("forMail").style.display = "none";
		_$("forProfile").style.display = "none";
		_$("forSendMessage").style.display = "";
		_$("imagesTable").style.border = "1px solid #9e4285";
	}
	message_img_url = imgUrl; 
	
	var str =
		"<div>"+
		"<h1 style='font-size:16px; color: #9e4285'>Send Your selected Generated Text to your friends.<span style='font-size:16px; color: #9e4285;position:relative; float: left; padding-right: 10px;'><b> Send As: </b></span><div id='targets'></div></h1>"+//
		"<div id=friend>Loading...</div>"+
		"</div>";
	_$("friendsDiv").innerHTML = str;
	loadSupportedTargets();
	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);
		gadgets.window.adjustHeight();
	},

	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);
		gadgets.window.adjustHeight();
	},

	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 width="+(100/cellCount)+"% >"+
						"<table valign=top width=100%>"+
							"<tr>"+
								"<td class=smallFont_ title='"+name+"'>"+name.substring(0,20)+"</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='margin-right:10px;font-size:16px;font-weight:bold;'>Previous</a>";
				if(available)
				str+=
					"<a href='javascript:Invite.next()' style='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;
		
		cont.innerHTML = "<div id="+containerId+"_1></div>";
		cont.setAttribute("curPage", 1);
		
		Invite.req_getFriends(curPage);
	}
};
}();

function inviteFriend(id, callback){
    var target_is_supported = false;
    var target = _$("target").value;
	var imgsrc = "";
	if(isShared) {
		imgsrc = SERVER_URL+"shared/" + message_img_url;
	} else {
		imgsrc = SERVER_URL+"genimg/"+userId+"/"+message_img_url;
	}
    var subject = "Generate your own Text as Image";
    var content = 	"<a href='"+canvas_url+"'><img src='"+IMG_URL+"/logo_32.png' /></a><br />"+ 	
					"<img style='padding-left: 10px;' src='"+imgsrc+"' /><br />"+
					"<span style='color: #3B5998; font-size: 13px;'><br />Generate Your Text using <a href='"+canvas_url+"'> Text Generator </a> !</span><br />";
   
    // make sure that the selected target is enabled
    for (var i = 0; i < supported.length; i++) {
          if (supported[ i ] == target) {
                target_is_supported = true;
                break;
          }
    }

    if (target_is_supported) {
    	postTo_(subject, content, getFriendById(id), target, callback);
    }
}

var postTo_ = function(subject, content, receiver, postWhere, ptCallback){
	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, ptCallback);
}

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

var postInvite = function(){
	var gameTitle = "Cool Text Graphics Generator!";
	var content =	"<a href='"+canvas_url+"'><img src='"+IMG_URL+"/logo_32.png' /></a><br />"+
					"<img src='"+SERVER_URL+"genimg/tmp/"+ownerId+".jpg />"+
					"<span style='color: #3B5998; font-size: 13px;'> Heeey see I have generated Text !!!<br /> Use <a href='"+canvas_url+"'> Cool Text Graphics Generator </a> to generate your own Text ! It's so easy, everyone can use it . </span><br />";
					
	postTo_(gameTitle, content, user, "BULLETINS", null);
}

var postInvite_ = function(img_url){
	var gameTitle = "Cool Text Graphics Generator!";
	var content =	"<a href='"+canvas_url+"'><img src='"+IMG_URL+"/logo_32.png' /></a><br />"+
					"<img src='"+SERVER_URL+"genimg/"+ownerId+"/"+img_url+"' /><br>"+
					"<span style='color: #3B5998; font-size: 13px;'> Heeey see I have generated Text !!!<br /> Use <a href='"+canvas_url+"'> Text Generator </a> to generate your own Text ! It's so easy, everyone can use it . </span><br />";
	postTo_(gameTitle, content, user, "BULLETINS", null);
}

var shareBulletin = function(img_url) {
	var gameTitle = "Cool Text Graphics Generator!";
	var content =	"<a href='"+canvas_url+"'><img src='"+IMG_URL+"/logo_32.png' /></a><br />"+
					"<img src='"+SERVER_URL+"shared/"+img_url+"' /><br>"+
					"<span style='color: #3B5998; font-size: 13px;'> Heeey see this cool generated Text !!!<br /> Use <a href='"+canvas_url+"'> Text Generator </a> to generate your own Text !</span><br />";
	postTo_(gameTitle, content, user, "BULLETINS", null);
}

function loadSupportedTargets() {
	supported = osContainer.getMySpaceEnvironment().getSupportedPostToTargets();
    var temp = "<select id=\"target\">";
    for (var i = 0; i < supported.length; i++){
          temp += "<option value=\"" + supported[ i ] + "\">" + supported[ i ] + "</option>";
    }
    temp += "</select>";
    document.getElementById("targets").innerHTML = temp;
}

////////////////////////  start promotion
$(document).ready(function(){
		// 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"];
		 
		 if(actionRedirect != null && actionRedirect .length > 0) {
				var url = "http://adturns.com/channelStatistics.php?act_own=32&socialType=myspace&appId=text_generator&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