////////////////////////////////////////////////////
/// MWF TWITTER ////////////////////////////////////
////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

TW = {};

TW.popup = null;
TW.isShown = false;
TW.ajax = null;

TW.action = '';
TW.username = '';
TW.pw = '';
TW.img = '';
TW.landUrl = '';
TW.app = '';
TW.tweetUpdateSent = false;
TW.twitterPostMsg = '';

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/// UI Functions

TW.init = function()
{
	TW.setForm();
	
	// use this line to set the TD as anchor. just set an id to the relevant td... :) 
	TW.popup = new Popup.Popup('twitterRegistrationDiv', 'twitterDivAnchor', {type: Popup.PositionType.SCREEN_CENTER_MIDDLE}, false);
}

TW.hide = function()
{
	//~ TW.isShown = false;
	TW.img = '';
	TW.popup.hide();
	
	TW.setForm();
}

TW.setForm = function()
{
	if (!document.forms['twitterForm']) 
	{
		var html = new Array();
		html.push("<form name='twitterForm' id='twitterForm' method='post' >");
		html.push("<table border=0 cellpadding='0px' cellspacing='0px'>");
			html.push("<tr><td  id='twitterDivAnchor' width='330px' height='50px' colspan=3><div style='position:absolute; top:16px; left:298px'><a href='javascript:TW.hide()' onclick=\"TW.sendStat('/GAS/Twitter/close')\"><img border=0 src='/images/twitter/xclose.gif'></a></div></td></tr>");
			html.push("<tr>");
				html.push("<td width='30px'></td>");
				html.push("<td width='270px'>");
					html.push("<div style='position:relative; top:0px; left:0px; z-index:0'>");
						// anchor title
						html.push("<div style='position:absolute; top:0px; left:0px'><span class='twitterH3'>Sign in with your Twitter account</span><br/><span id='twitterRegistrationMsg'></span></div>");
						// form element
						html.push("<div style='position:absolute; top:40px; left:0px'>");
						html.push("<span class='twitterDefText'>Username:<br/></span><input class='twitterInput' type='text' name='username' value=''/><span class='twitterDefText'><br/></span>");
						html.push("<span class='twitterDefText' style='margin-top: 5px;'>Password:<br/></span><input class='twitterInput' type='password' name='password' value=''/><span class='twitterDefText'><br/></span>");
						html.push("<span class='twitterDefText' style='margin-top: 5px;'>Message:<br/></span><textarea id='twitterPostMsg' class='twitterTextarea' rows='3' cols='45'></textarea>");
						html.push("</div>");
						// buttons
						html.push("<div style='position:absolute; top:230px; left:0px'>");
						html.push("<a id='twitterRefUpdate' href='javascript:TW.Post()' onclick='TW.setUpdateStat()'><img border=0 src='/images/twitter/update.gif'></a>");
						html.push("<span style='width:5px'>&nbsp;</span>");
						html.push("<a href='javascript:TW.hide()' onclick=\"TW.sendStat('/GAS/Twitter/close')\"><img border=0 src='/images/twitter/cancel.gif'></a>");
						html.push("</div>");
						// preloader image
						html.push("<div id='twitterPreloader' style='position:absolute; top:0px; left:0px; width:270px; height:280px; background:url(/images/twitter/preloader.gif) center center no-repeat #ffffff; z-index:1; display:none;'></div>");
					html.push("</div>");
				html.push("</td>");
				html.push("<td width='30px'></td>");
			html.push("</tr>");
		html.push("</table>");
		html.push("</form>");
		
		var regDiv = General.$('twitterRegistrationDiv') || null;
		if (regDiv) 
		{
			regDiv.innerHTML = html.join("");
		}
	}
	
	// zero details
	TW.pw = TW.username = '';
}

TW.setMsgDiv = function(msg)
{
	var _msg = msg || "";
	//_msg = "<a class='twitterMsgRef' href='http://twitter.com/"+TW.username+"' onclick='javascript:TW.hide()' target='_blank'>"+_msg+"</a>";
	_msg = "<span class='twitterMsg'>"+_msg+"</span>";
	
	var html = new Array();
	html.push("<table border=0 cellpadding='0px' cellspacing='0px'>");
		html.push("<tr><td  id='twitterDivAnchor' width='330px' height='50px'><div style='position:absolute; top:16px; left:298px'><a href='javascript:TW.hide()'><img border=0 src='/images/twitter/xclose.gif'></a></div></td></tr>");
		html.push("<tr><td  width='330px' height='50px' align='center' valign='top'></td></tr>");
		html.push("<tr><td  width='330px' height='170px' align='center' valign='top'><img border=0 src='/images/twitter/bird.gif'><br/>"+_msg+"</td></tr>");
		html.push("<tr><td  width='330px' height='80px' align='center' valign='top'><a href='javascript:TW.hide()'><img border=0 src='/images/twitter/close.gif'></a></td></tr>");
	html.push("</table>");
	
	var regDiv = General.$('twitterRegistrationDiv');
	regDiv.innerHTML = html.join("");
}

TW.getLandUrl = function(imgSrc)
{
	var urlArr = imgSrc.split("/");
	var imgName = urlArr[urlArr.length-1];
	imgName = imgName.split(".")[0];
	
	var landUrl = "http://home.mywebface.com/land.pl?id=" + imgName;
	
	if (TW.app === 'myWebFace' || TW.app === 'myWebFaceGallery') {
		landUrl += "app=mwf";
	}
	else if (TW.app === 'photoFX' || TW.app === 'myPhotoFxGallery') {
		landUrl += "app=pfx";
	}
	else if (TW.app === 'photoMIX' || TW.app === 'photoMIXGallery') {
		landUrl += "app=pm";
	}
	
	return landUrl;
}

TW.setSyncImg = function(action)
{
	var _action = action || 'hide';
	var _tp = General.$('twitterPreloader') || null;
	if (_tp) {
		_tp.style.display = (_action == "hide")? "none" : "block";
	}
}

TW.setUpdateStat = function()
{
	var _gas = (TW.tweetUpdateSent)? '/GAS/Twitter/tweetUpdate' : '/GAS/Twitter/tweetUpdateUnique';
	TW.sendStat(_gas);
	
	// set the 'click on update button' status in order to seperate the stats of 1st update Vs other updates
	TW.tweetUpdateSent = true;
}

TW.sendStat = function(gas)
{
	var _gas = gas || '/GAS/Twitter/empty';
	
	//~ if (registered === '1') {
		//~ alert("sending - " + _gas);
	//~ }
	
	GAStats.send(_gas);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//  Start

TW.tweet = function(imgSrc)
{
	TW.go(imgSrc, "update")
}

TW.uploadProfileImg = function(imgSrc)
{
	TW.go(imgSrc, "update_profile_image")
}


TW.go = function(imgSrc, action, app)
{
	// set the current action
	TW.action = action || "update_profile_image";
	
	// set the app param
	TW.app = app || "";
	
	// clean the image url 
	var qmIndex = imgSrc.indexOf("?");
	if (qmIndex > -1) {
		imgSrc = imgSrc.substring(0, qmIndex);
	}

	// set the image source and the its landing page
	TW.img = imgSrc;
	TW.landUrl = TW.getLandUrl(imgSrc);
	
	// set the relevant message to tweet about 
	var str = '';
	if (TW.action === 'update') {
		str = "Check out what i just made on myWebFace.com ";
	}
	else if (TW.action === 'update_profile_image') {
		str = "I just uploaded my new profile image created on myWebFace.com ";
	}
	else if (TW.action === 'update_profile_background_image') {
		str = "I just created a new background image on myWebFace.com ";
	}
	TW.twitterPostMsg = document.forms['twitterForm'].twitterPostMsg.value = str + TW.landUrl;
	
	// open the reg div
	TW.popup.show();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/// Ajax Functions

TW.Post = function()
{
	TW.username = document.forms['twitterForm'].username.value.replace(/^\s+|\s+$/g,"");
	TW.pw = document.forms['twitterForm'].password.value.replace(/^\s+|\s+$/g,"");

	if (TW.username === '' || TW.pw === '')
	{
		if (TW.username === '')
		{
			TW.sendStat('/GAS/Twitter/alert/usernameMissing');
			alert('Please supply your twitter username');
			return;	
		}
		
		if (TW.pw === '')
		{
			TW.sendStat('/GAS/Twitter/alert/passMissing');
			alert('Please supply your twitter password');
			return;	
		}
	}
	//~ if (TW.username.indexOf('@') != -1)
	//~ {
		//~ TW.sendStat('/GAS/Twitter/alert/emailError');
		//~ alert('This feature currently works with user name only.');
		//~ return;	
	//~ }
	
	
	if (TW.ajax === null)	
	{
		TW.ajax = new AJAX.request("http://home.mywebface.com/twitterAPI.pl", AJAX.Method.POST, AJAX.Type.ASYNC);
		TW.ajax.onFailFunction = TW.updateFail;
		TW.ajax.onTimeoutFunction = TW.updateFail;
		TW.ajax.onSuccessFunction = TW.PostOk;
	}
	else
	{
		TW.ajax.onSuccessFunction = TW.PostOk;
	}
	
	// show sync image
	TW.setSyncImg('show');


	// start the ajax
	if (TW.action === 'update') {
		TW.ajax.start("action=" + TW.action + "&username=" + TW.username + "&password=" +  TW.pw  + "&status=" + TW.twitterPostMsg);
	}
	else if (TW.action === 'update_profile_image') {
		TW.ajax.start("action=" + TW.action + "&username=" + TW.username + "&password=" +  TW.pw  + "&image=" + TW.img + "&status=" + TW.twitterPostMsg);
	}
	else if (TW.action === 'update_profile_background_image') {
		TW.ajax.start("action=" + TW.action + "&username=" + TW.username + "&password=" +  TW.pw  + "&image=" + TW.img + "&status=" + TW.twitterPostMsg);
	}
}

TW.PostOk = function(request)
{
	if (request.responseText === "error")
	{
		// send a succees stats event
		TW.sendStat('/GAS/Twitter/tweetWrongLogin');
	
		var regMsg = General.$('twitterRegistrationMsg');
		regMsg.innerHTML = "Wrong login credentials.<br/>";
		TW.setSyncImg('hide');
	}
	else if (request.responseText === "success")
	{
		// send a succees stats event
		TW.sendStat('/GAS/Twitter/tweetSuccess');

		// Zero the 'click on update button' status in order to init the stats of 1st update
		TW.tweetUpdateSent = false;

		// show the relevant message by the relevant action
		if (TW.action === 'update') {
			TW.setMsgDiv("Your Tweet has been posted!");
		}
		else if (TW.action === 'update_profile_image') {
			TW.setMsgDiv("Your Twitter profile image<br/>has been updated!");
		}
		else if (TW.action === 'update_profile_background_image') {
			TW.setMsgDiv("Your Twitter background image<br/>has been updated!");
		}
	}
}

TW.updateFail = function(request)
{
	TW.sendStat('/GAS/Twitter/tweetFailure');
	alert('Server failure. Please try again later...');
	TW.setSyncImg('hide');
	TW.hide();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


