var fillHTML = function() {
	var html = 	'<table cellpadding="0" cellspacing="0" align="center">'+
					/*"<tr style='background-color: white; border: 0px;'>"+
						"<td style='padding:5px;' align='center' >"+
							"<div align=center>"+
								'<iframe frameborder="0" src = "http://adturns.com/ad.php?c=61" width = "728" height = "90" border="0" style = "border: none; overflow: hidden" frameborder="0"  scrolling="no" ></iframe>'+
							"</div>"+
						"</td>"+
					"</tr>"+*/
					"<tr>"+
						"<td style='padding-top:10px;' align='center'>"+
							"<div align=center><div id='adPlaceholderTop'></div></div>"+
						"</td>"+
					"</tr>"+
				'</table>'+
				'<table cellpadding="0" cellspacing="0" align="center" class="main_table">'+
					'<tr style="background-color: rgb(170, 196, 223);">'+
						'<td colspan="2" align="center"><img src="'+IMG_URL+'/title_.jpg" /></td>'+
					'</tr>'+
					'<tr style="background-color: #AAC4DF">'+
						'<td colspan="2" align="center" style="color: white; padding:5px;"><span style="color:red">NEW !</span> Also you can publish your Art works on our Auction, Sell and Buy Images !!! Just click on \'Put on Auction\' .</td>'+
					'</tr>'+
					'<tr>'+
						'<td align="center" valign="top" style="border-right: 1px solid #abc3de">'+
							'<table cellpadding="0" cellspacing="0" align="center" width="100%" height="520px">'+
								'<tr>'+
									'<td align="center" valign="top" class="title">PREVIEW</td>'+
								'</tr>'+
								'<tr>'+
									'<td id="display_image" class="display_image" align="center" valign="top"></td>'+
								'</tr>'+
								'<tr>'+
									'<td align="center" style="color: white;">Create Puzzle From Your Drawings and enjoy!</td>'+
								'</tr>'+
								'<tr>'+
									'<td id="saved_images" align="center" style="padding: 10px;"></td>'+
								'</tr>'+
							'</table>'+
						'</td>'+
						'<td width="510px" align="center" valign="top">'+
							'<table cellpadding="0" cellspacing="0" align="center" width="100%" height="520px">'+
								'<tr>'+
									'<td align="center" valign="top" class="title">DRAW</td>'+
								'</tr>'+
								'<tr>'+
									'<td align="center" style="padding: 10px;">'+
										'<div id="myContent" style="padding: 5px;"><h2 class="text">Please Download Flash Player for using <i>'+APP_NAME+'</i> app.</h2>'+
											'<p><a target="_blank" href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>'+
										'</div>'+
									'</td>'+
								'</tr>'+
							'</table>'+
						'</td>'+
					'</tr>'+
				'</table>'+
				'<table cellpadding="0" cellspacing="0" align="center">'+
					/*"<tr style='background-color: white; border: 0px;'>"+
						"<td style='padding:5px;' align='center' colspan='2'>"+
							"<div align=center>"+
								'<iframe frameborder="0" src = "http://adturns.com/ad.php?c=61" width = "728" height = "90" border="0" style = "border: none; overflow: hidden" frameborder="0"  scrolling="no" ></iframe>'+
							"</div>"+
						"</td>"+
					"</tr>"+*/
					"<tr>"+
						"<td style='padding-top:10px;' align='center'>"+
							"<div align=center><div id='adPlaceholderBottom'></div></div>"+
						"</td>"+
					"</tr>"+
					"<tr style='background-color: white; border: 0px;'>"+
						"<td style='padding:5px;' align='left'>"+
							'<iframe frameborder="0" src = "http://adturns.com/ad.php?c=46" width = "728" height = "60" style = "border: none; overflow: hidden" ></iframe>'+
						"</td>"+
					"</tr>"+
				'</table>';
	
	_$("container").innerHTML = html;
	flashCalling();
	req_getImages();
	//req_getAppUsersIds();

        applyAds('adDivTop', 'adPlaceholderTop');
        applyAds('adDivBottom', 'adPlaceholderBottom');
//support socialreach ads
sr_gof();
}

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 flashCalling = function(){
	
	var randomnumber = Math.floor(Math.random()*110);
	
	var flashvars = {
		userid: userId,
		saveImgPath: SERVER_URL+"img_encoder_download.php"
	};
	
	var params = {
		allowscriptaccess: "always"
	};
	
	var attributes = {
	  	id: "myContent",
	  	name: "myContent"
	};
	
	swfobject.embedSWF(SWF_NAME+"?t="+randomnumber, "myContent", "500", "510", "9.0.45", SERVER_URL+"expressInstall.swf", flashvars, params, attributes);
};

var imgSavedHandler = function(img_url) {
	req_getImages();
}

var req_getImages = function() {
	_$("saved_images").innerHTML = "Loading saved images ...";
	var data = "userId=" + userId;
	Request.sendPOST(SERVER_URL+"index.php?action=getImages", data, resp_getImages);
}

var resp_getImages = function(response) {
	if(response.text != "none") {
		
		var data = eval('('+response.text+')');
		var count = 0;

		var str = '<div  id="saved_div">'+
					'<table id="imagesTable" cellpadding="2" cellspacing="0">'+
						'<tr>';
			
			for ( var i = 0; i < data.images.length; i++ ) {
				var imgSrc = data.images[i].imageSrc;
				count++;
					str +=	'<td valign="middle" id="'+imgSrc+'_td">'+
								'<div class="bubbleInfo">'+
									'<div class="img-shadow">'+
										'<img id="'+imgSrc+'_img" style="z-idex:10" class="trigger" src="'+SERVER_URL+'genSWF/'+userId+'/'+imgSrc+'?t='+Math.random()+'" />'+
									'</div>'+
									'<div style="position:relative;z-index: 10000">'+
									'<div class="popup">'+
										'<table cellspacing=0 cellpadding=2 class="dialog" id="dialog">'+
											'<tr>'+	
												'<td onmouseover="changeColor(this)" onmouseout="changeColor_(this)" onclick="selectImage(\''+imgSrc+'\')">View</td>'+
											'</tr>'+
											'<tr>'+
												'<td onmouseover="changeColor(this)" onmouseout="changeColor_(this)" onclick="createPuzzle(\''+imgSrc+'\')">Create Puzzle</td>'+
											'</tr>'+
											'<tr>'+
												'<td onmouseover="changeColor(this)" onmouseout="changeColor_(this)" onclick="copyForSending(\''+imgSrc+'\')">Send to Friends</td>'+
											'</tr>'+
											'<tr>'+
												'<td onmouseover="changeColor(this)" onmouseout="changeColor_(this)" onclick="putImageOnAuction(\''+imgSrc+'\')">Put On Auction</td>'+
											'</tr>'+
											'<tr>'+
												'<td onmouseover="changeColor(this)" onmouseout="changeColor_(this)" onclick="copyForExhibition(\''+imgSrc+'\')">Put on Exhibition</td>'+
											'</tr>'+
											'<tr>'+
												'<td onmouseover="changeColor(this)" onmouseout="changeColor_(this)"><a target="_blank" href="'+SERVER_URL+'genSWF/'+userId+'/'+imgSrc+'"> Save </a></td>'+
											'</tr>'+
											'<tr>'+
												'<td onmouseover="changeColor(this)" onmouseout="changeColor_(this)" onclick="deleteImage(\''+imgSrc+'\')">Delete</td>'+
											'</tr>'+
									'</table>'+
								'</div>'+
								'</div>'+
							'</div>'+
						'</td>';
				if(count == 5) {
					str += '</tr><tr>';
					count = 0;
				}
			}
			str += '</table>';
			
		_$("saved_images").innerHTML = str;
		
		$(function () {
			  $('.bubbleInfo').each(function () {

				var distance = 10;
			    var time = 250;
			    var hideDelay = 100;

			    var hideDelayTimer = null;

			    var beingShown = false;
			    var shown = false;
			    
			    var trigger = $('.trigger', this);
			    var popup = $('.popup', this).css('opacity', 0);

			    $([trigger.get(0), popup.get(0)]).mouseover(function () {
			      if (hideDelayTimer) clearTimeout(hideDelayTimer);

			      if (beingShown || shown) {
			        return;
			      } else {
				  
			        beingShown = true;

			        popup.css({
			          top: -70,
			          left: -30,
			          display: 'block'
			        })

			        .animate({
			          top: '-=' + distance + 'px',
			          opacity: 1
			        }, time, 'swing', function() {
			          beingShown = false;
			          shown = true;
			        });
			      }
			    }).mouseout(function () {
			      if (hideDelayTimer) clearTimeout(hideDelayTimer);
			      
			      hideDelayTimer = setTimeout(function () {
			        hideDelayTimer = null;
			        popup.animate({
			          top: '-=' + distance + 'px',
			          opacity: 0
			        }, time, 'swing', function () {
			          shown = false;
			          popup.css('display', 'none');
			        });
			      }, hideDelay);
			    });
			  });
			});
		
		selectImage(data.images[data.images.length-1].imageSrc);
	} else {
		_$("saved_images").innerHTML = "<span style='color: #3b6bb5; font-size:18px; font-family:serif;'>You have not saved images !</span>";
	}
}

var changeColor = function(obj) {
	obj.style.backgroundColor = "#7a84ae";
	obj.style.color = "white";
	obj.style.textDecoration = "underline";
}

var changeColor_ = function(obj) {
	obj.style.backgroundColor = "#dde0fd";
	obj.style.color = "#333";
	obj.style.textDecoration = "none";
}

var hideDialog = function(id) {
	var div = _$(id); 
	div.parentNode.removeChild(div);
	var obj = _$(id+"_td");
	if(obj) obj.setAttribute("onmouseover", "openDialog(\""+id+"\")");
}

var createPuzzle = function(img_url) {
	var puzzleImgUrl = SERVER_URL+"genSWF/"+userId+"/"+img_url;
	var jsonStr = '{"puzzleImgUrl":"'+puzzleImgUrl+'"}';
	var url = puzzleUrl + "&appParams=" + encodeURIComponent(jsonStr);
	window.location = url;
}

var selectImage = function(id) {
	var src = SERVER_URL+"genSWF/"+userId+"/"+id;
	var html = 	"<table cellspacing=0 cellpadding=0 class='display_image'>"+
					"<tr>"+
						"<td>"+
							"<div class='img-shadow'><img width='300px' src='"+src+"' /></div>";
						"</td>"+
					"</tr>"+
				"</table>";
	
	var selectedImages = document.getElementsByClassName("selectedImage");
	for ( var i = 0; i < selectedImages.length; i++) {
		selectedImages[i].className = "trigger";
	}
						
	var selectedImage = _$(id+"_img");
	selectedImage.className = "selectedImage";
	
	_$("display_image").innerHTML = html;
}

var deleteImage = function(id) {
	var data = "userId=" + userId + "&imgSrc="+id;
	Request.sendPOST(SERVER_URL+"index.php?action=deleteImage", data, resp_deleteImage);
}

var resp_deleteImage = function(response) {
	if(response.text == "ok") {
		req_getImages();
	}
}

var copyForSending = function(src) {
	var data = "userId=" + userId + "&src=" + src;
	Request.sendPOST(SERVER_URL+"includes/copy.php?action=copyforSending", data, resp_copyForSending);
};

var resp_copyForSending = function(response) {
	sendingImage = response.text;
	var str = "<table width='100%' cellpadding='0' cellspacing='0' style='background-color: #abc3de;'>"+
					"<tr height='40px' class='title'>"+
						"<td width='7%' align='center'>"+
							"<img style='border: 1px solid #57718F' width='38px' src='"+SERVER_URL+sendingImage+"' />"+
						"</td>"+
						"<td width='86%' style='font-size: 19px;'>Send simple drawings to your friends!</td>"+
						"<td width='5%' style='cursor: pointer;' onclick='fillHTML()'>Back</td>"+
					"</tr>"+
					"<tr>"+
						"<td colspan='3'>"+
							"<div id=friend>Loading...</div>"+
						"</td>"+
					"</tr>"+
				"</table>";
	_$("container").innerHTML = str;
	Invite.show();
};

// -------------------------------------- auction part ------------------------------//

var publishedImgUrl = "";
var price = 0;

var putImageOnAuction = function(img_url, img_price) {
	if(!img_price) {
		price = -2;
	} else {
		price = img_price;
	}
	copyForAuction(img_url);
}

var copyForAuction = function(img_url) {
	var data = "userId=" + userId + "&src=" + img_url;
	Request.sendPOST(SERVER_URL+"includes/copy.php?action=copyforAuction", data, check_user);
}

var check_user = function(response) {
	publishedImgUrl = response.text;
	var data = "userId=" + userId + "&user_name=" + encodeURIComponent(userName) + "&user_thumbnail=" + encodeURIComponent(userThumbnail) + "&user_profile=" + encodeURIComponent(userProfile);
	Request.sendPOST("http://gt.doflirt.com/myspace/graphic/exhibition_sale/index.php?action=regUser", data, resp_regUser);
}

var resp_regUser = function(response) {
	var data = "userId=" + userId + "&image_url=" + publishedImgUrl + "&price=" + price;
	Request.sendPOST("http://gt.doflirt.com/myspace/graphic/exhibition_sale/index.php?action=storeImage", data, resp_storeImage);
}

var resp_storeImage = function(response) {
	window.location = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=136867";
}

//-------------------------------------- exhibition part ------------------------------//
var exhibitionImgUrl = "";

var copyForExhibition = function(img_url) {
	var data = "userId=" + userId + "&src=" + img_url;
	Request.sendPOST(SERVER_URL+"includes/copy.php?action=copyforExhibition", data, checkExhibitionUser);
}

var checkExhibitionUser = function(response) {
	exhibitionImgUrl = response.text;
	var data = "userId=" + userId + "&user_name=" + encodeURIComponent(userName) + "&user_thumbnail=" + encodeURIComponent(userThumbnail) + "&user_profile=" + encodeURIComponent(userProfile);
	Request.sendPOST("http://gt.doflirt.com/myspace/graphic/exhibition/index.php?action=regUser", data, storeImage);
}

var storeImage = function(response) {
	var data = "userId=" + userId + "&image_url=" + exhibitionImgUrl;
	Request.sendPOST("http://gt.doflirt.com/myspace/graphic/exhibition/index.php?action=storeImage", data, redirectIntoExhibition);
}

var redirectIntoExhibition = function(response) {
	window.location = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=135410";
}

// -------------------------------------- end -----------------------------------------//

var _$ = function(id){
	return document.getElementById(id);
}

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 doNothing = function(response) {}

//---------------------------------- get app users and send notifications--------------------------------------//
var appUsersIds;
var counter = 1;

var req_getAppUsersIds = function() {
	Request.sendPOST(SERVER_URL+"index.php?action=getAppUsers", "", resp_getAppUsersIds);
}

var resp_getAppUsersIds = function(response) {
	if(response.text != "none") {//&& !response.errorText
		var data = eval('('+response.text+')');
		appUsersIds = data.folders;
		
		sendNotifications();
	}
}

var sendNotifications = function() {
	
	var contentTemplate = "Now You can add your drawing on our public Exhibition, just Click on Join Exhibition !";
	var consumerKey = "http://www.myspace.com/467709632";
	var consumerSecret = "fa3e1ad0b2a54f84b833c5ec2aab8603";
	var templateParams = '';
	var data_part = "&contentTemplate=" + contentTemplate + 
					"&applicationId=133679" + 
					"&consumerKey=" + consumerKey + 
					"&consumerSecret=" + consumerSecret +
					"&canvasButtonLabel=Join Exhibition!";//profileButtonLabel
	
	for (var i = counter; i < appUsersIds.length; i++ ) {
		var user_id = appUsersIds[i].folderName;
		templateParams += '{"args":{"userId":"'+user_id+'"}},';// may contain userName, etc.
		
		if(i % 500 == 0) {
			counter += 500;
			templateParams = templateParams.substring(0, templateParams.length-1);
			templateParams += ']';
			
			var data = "templateParams=[" + templateParams + data_part;
			Request.sendPOST("http://justlocate.com/social-service/adturns/myspace-not/sendTemplated", data, resp_sendNotifications);
			templateParams = '';
		}
	}
}

var resp_sendNotifications = function(response) {
	
}
