$(document).ready(function(){
	TwitterPost.createTwitterModals();
})

/**
 * This is going to be used for posting items to twitter. the basic flow is as
 * follows:
 *		1. Look at cookie, is the user logged in?
 *			yes - go to 6
 *			no - goto 2.
 *		2. call out to the authorization URL 
 *		~~~~~~~magic~~~~~~~
 *		3. jared's stuff will call back to original pop up and populate a JS object
 *		4. Send the user object back to the main window and set cookie
 *		5. close the pop up window
 *		6. Dow whatever you are supposed to do (update image, etc);
 *		7. show modal with suggested text 
 *		8. pending on users interaction:
 *			yes, post -  post to twitter, then show a new pop up window that will go to twitter 
 *			no - close modal
 *		9. profit.
 **/
var TwitterPost = {
	twitterAuthWindow: 			null,
	twitterCookieName:			"twitterUserObj",
	/*
		twitterAuthenticatedObj should look like this:
			oauth_token: 'someVal',
			oauth_token_secret: 'someVal',
			user_id: 'someVal',
			screen_name: 'someVal'
	*/
	twitterAuthenticatedObj: 	"",
	url1:		 				"",
	url2:		 				"",
	requestedAction:			"",
	
	setBackground: function( a_id ){
		if(document.location.href.indexOf('local.') != -1)
			this.launchTwitterShare("http://imgfarm.com/images/fwp/wf/assets/layouts/"+$("#assetUrl_"+a_id).val(), TwitterActions.POST_BACKGROUND);
		else
			this.launchTwitterShare("http://ak.webfetti.com/assets/layouts/"+$("#assetUrl_"+a_id).val(), TwitterActions.POST_BACKGROUND);
	},
	setOverlay: function( a_id ){
		if(document.location.href.indexOf('local.') != -1)
			this.launchTwitterShare("http://imgfarm.com/images/fwp/wf/assets/layouts/"+$("#assetUrl_"+a_id).val(), TwitterActions.ADD_OVERLAY_TO_PROFILE);
		else
			this.launchTwitterShare("http://ak.webfetti.com/assets/layouts/"+$("#assetUrl_"+a_id).val(), TwitterActions.ADD_OVERLAY_TO_PROFILE);
	},
	/**
	 * this function will take the ID of an asset then determin if the user has a  
	 * cookie set with the oauth things that we need.  If they do, then just share 
	 * it.  Else, go to the oAuth page, and begin authorization.
	 * 
	 * @author luly 
	 **/
	launchTwitterShare:function( a_url1, a_action, a_url2 ){
		this.url1 = a_url1;
		this.url2 = a_url2;
 		this.requestedAction = a_action;
		var cookieObj = this.checkTwitterCookie();
		if( typeof(cookieObj) == 'undefined' ){
			document.domain="webfetti.com";
			this.twitterAuthWindow = window.open(sTwitterAuth ,"Twitter", "toolbar=1,menubar=1,width=1000,height=400");
		}
		else{
			this.twitterAuthenticatedObj = eval(cookieObj);
			switch(this.requestedAction){
				case TwitterActions.POST_BACKGROUND:
					this.startDialog(TwitterPost.getBGHTML, function(){
						TwitterPost.initTwitterAPI(TwitterPost.actuallySetBackground);
					});
				break;
				case TwitterActions.POST_NEW_PROFILE_PICTURE:
					
				break;
				case TwitterActions.ADD_OVERLAY_TO_PROFILE:
					this.startDialog(TwitterPost.getProfilePicOverlayHTML, function(){
						TwitterPost.initTwitterAPI(TwitterPost.actuallySetProfilePicOverlay);
					});
				break;
			}
		}
	}, 
	
	/**
	 * Begin the initialization of TwitterAPI
	 */
	initTwitterAPI: function (a_callback){
		TwitterAPI.init(this.getTwitterAPIConfig(),a_callback, null, null, this.createSwfCont);
	},
	
	/**
	 * This will create the SWF container that will be inserted in to the modal that has been popped
	 **/
	createSwfCont: function (a_swfID){
		$("#libHolder").html("<span id='"+a_swfID+"'></span>");
		return {element:$("#"+a_swfID), height:'24', width:'179',extraParams:{}}
	},
	
	/**
	 * This will construct a config object that can be passed in to the twitter 
	 * API
	 **/ 
	getTwitterAPIConfig:function(){
		var serverProxyURL = "" 
		var tempObj = {
			user: {
				accessToken: 	this.twitterAuthenticatedObj.oauth_token,
				accessSecret:	this.twitterAuthenticatedObj.oauth_token_secret,
				usersSN:		this.twitterAuthenticatedObj.user_id,
				usersID:		this.twitterAuthenticatedObj.screen_name
			},
			urls:{
				proxy:			"",	//Used to go through domains
				serverProxy:	sTwitterLibProxy			//used instead of twitter.com
			},
			throughServer:	 	true,
			format: 			"json"
		};
		return tempObj;
	},
	
	/**
	 * This will show the background modal.
	 **/
	startDialog: function(a_functionForHTML, a_callback){
		this.openDialog('twitterModal');
		ckTrk("/clicks/twittermodal/open");		
		setTimeout(function(){
				$("#twitterModalContent").html(a_functionForHTML());
				a_callback();
			},400);
	},
	
	/**
	 * creates the html for the modal
	 **/
	getBGHTML: function(){
		return '<div style="float:right;width:80px;  margin:25px 0px 0px 0px;">'+
		'	<img src="' + TwitterPost.url1 + '" id="twitterModalBG" width="75" align="right" alt="Right-click here and choose Save As..."></div> ' +
		'	<div style="font-family:Georgia;font-weight:bold; font-size:18pt; color:#9d0658;padding:0px 0px 5px 0px;">Please Confirm</div>' +
		'	<div style="font-family: Georgia; font-weight: bold; font-size: 12pt;width:300px; color:#9d0658;padding:0px 0px 10px 0px;">Click on the button below to make this your Twitter background</div>' +
		'	<div style="font-family:Arial;font-size:12pt; color:#4d4d4d; padding:0px 0px 10px 10px"><input type="checkbox" checked="yes" id="postMessageCheck_BG"/> Tell your friends by Tweeting it!</div>' +
		'	<div style="border:1px solid #dfdfdf; font-family:Arial;font-size:12pt; color:#333333;padding:10px;">' +
		'		I just updated my Twitter background using Webfetti' +
		'		<p style="padding:10px 0px 0px;">' +
		'			Check it out!' +
		'			<br/>' +
		'			<div style="padding: 0px 0px; text-decoration:underline;">' +
		'				http://www.webfetti.com/webfetti/Twitter/Layouts/Twitter-Backgrounds.jhtml' +
		'			</div>' +
		'		</p>' +
		'	</div>' +
		'	<div style="width:250px;margin:10px auto; overflow:hidden; " id="ButtonBayTwitterModal">' +
		'		<span id="libHolder" style="float:left; "></span>' +
		'		<a href="#" onclick="TwitterPost.closeDialog(\'twitterModal\');return false;" style="display:block;float:right;margin:2px 0px 0px 0px; overflow:hidden">' +
		'			<img src="http://ak.webfetti.com/v3/cancel_btn.gif" width="62" height="20">' +
		'		</a>' +
		'	</div>';
	},
	
	/**
	 * creates the html for the modal
	 **/
	getProfilePicOverlayHTML: function(){
		return '<div style="float:right;width:80px; margin:25px 0px 0px 0px;position:relative;">'+
		'		<img style="float:right" src="http://ak.imgfarm.com/images/spacer.gif" id="twitterModalProfilePic" width="75" align="right" />'+
		'		<img style="float:left;position:absolute;top:0px; left:0px; " src="' + TwitterPost.url1 + '" id="twitterModalProfilePicOverlay" width="75" align="right" />'+
		'	</div> ' +
		'	<div style="font-family:Georgia;font-weight:bold; font-size:18pt; color:#9d0658;padding:0px 0px 5px 0px;">Please Confirm</div>' +						
		'	<div style="font-family:Georgia; font-weight: bold; font-size: 12pt;width:300px; color:#9d0658;padding:0px 0px 10px 0px;">Click on the button below to change your Twitter Profile Picture</div>' +
		'	<div style="font-family:Arial;font-size:12pt; color:#4d4d4d; padding:0px 0px 10px 10px"><input type="checkbox" checked="yes" id="postMessageCheck_picOverlay"/> Tell your friends by Tweeting it!</div>' +
		'	<div style="border:1px solid #dfdfdf; font-family:Arial;font-size:12pt; color:#333333;padding:10px;">' +
		'		I just updated my Twitter profile pic using Webfetti' +
		'		<p style="padding:10px 0px 0px;">' +
		'			Check it out!' +
		'			<br/>' +
		'			<div style="padding: 0px 0px; text-decoration:underline;">' +
		'				http://local.webfetti.com/webfetti/Twitter/Layouts/Profile-Pics.jhtml' +
		'			</div>' +
		'		</p>' +
		'	</div>' +
		'	<div style="width:250px;margin:10px auto; overflow:hidden;" id="ButtonBayTwitterModal">' +
		'		<span id="libHolder" style="float:left;"></span>' +
		'		<a href="#" onclick="TwitterPost.closeDialog(\'twitterModal\');return false;" style="display:block;float:right;margin:2px 0px 0px 0px; overflow:hidden">' +
		'			<img src="http://ak.webfetti.com/v3/cancel_btn.gif" width="62" height="20">' +
		'		</a>' +
		'	</div>';
	},
	
	/**
	 * this is what _actuall_ sends off the command to the API
	 **/
	actuallySetBackground:function(){
		TwitterAPI.setBackgroundImage(TwitterPost.handleCompletionSetBG, TwitterPost.url1)
	},
	
	/**
	 * this is what _actuall_ sends off the command to the API
	 **/
	actuallySetProfilePicOverlay: function(){
		TwitterAPI.MultiStepActions.addProfileOverlay(TwitterPost.handleCompletionPicOverlay, TwitterPost.url1, function(a_json){
			var response = eval(unescape('('+a_json+')'));
			var imageURL = response.profile_image_url;
			$("#twitterModalProfilePic").attr("src",imageURL);
		});
	},
	
	toggleLoadingScreen: function(a_bHide){
		if(a_bHide)
			$("#WFLoadingTwitterContainer").hide();
		else
			$("#WFLoadingTwitterContainer").show();
	},
	handleCompletionSetBG: function(a_json){
		if($("#postMessageCheck_BG").attr("checked")){
			var s = "I just updated my twitter background using Webfetti Check it out! http://www.webfetti.com/Twitter/Layouts/Twitter-Backgrounds.jhtml?vr=" + Math.random();
			setShortenedStatus(s, function(){
					window.open("http://www.twitter.com","Twitter");
					TwitterPost.closeDialog('twitterModal');
				})
		}
		else{
			window.open("http://www.twitter.com","Twitter");
			TwitterPost.closeDialog('twitterModal');
		}
	},
	
	/**
	 * 
	 * 
	 **/
	handleCompletionPicOverlay: function(a_json){
		if($("#postMessageCheck_picOverlay").attr("checked")){
			var s = "I just updated my Twitter profile pic using Webfetti Check it out! http://www.webfetti.com/Twitter/Layouts/Twitter-Backgrounds.jhtml?vr=" + Math.random();
			setShortenedStatus(s, function(){
					window.open("http://www.twitter.com","Twitter");
					TwitterPost.closeDialog('twitterModal');
				})
		}
		else{
			window.open("http://www.twitter.com","Twitter");
			TwitterPost.closeDialog('twitterModal');
		}
	},
	
	/**
	 * get the cookie, and return it
	 **/
	checkTwitterCookie:function(){
		return getCookie(this.twitterCookieName);
	},
	
	/**
	 * sets the cookie to the data sent in with an expiration date of a year
	 **/
	setTwitterCookie:function( a_someData ){
		var expiration=new Date();
		expiration.setDate(expiration.getDate()+365);
		setCookie( this.twitterCookieName, a_someData, expiration,"/",null,null );
	},
	
	/**
	 * this will check to see if 'this.twitterAuthenticatedObj is set, if it is 
	 * return that.  If not then check the cookie and see if that is set. if the
	 * cookie is not set return null, else, assign the eval-ed value to the 
	 * twitterAuthenticatedObj, then return that.
	 **/
	getAuthenticatedUserConfig:function(){
		if(this.twitterAuthenticatedObj == "" || this.twitterAuthenticatedObj == null){
			var tempCookie = this.checkTwitterCookie();
			if(typeof(tempCookie)== 'undefined')
				return null;
			else
				this.twitterAuthenticatedObj = eval(tempCookie);
		}
		return this.twitterAuthenticatedObj;
	},
	
	/**
	 * This i called from the opening window, it sets the information that is 
	 * needed for ust o act on behalf of the user. then sets the cookie
	 **/
	setAuthenticatedUserObj:function(a_tempObj){
		this.closeOAuthWin();
		this.twitterAuthenticatedObj = {};
		this.twitterAuthenticatedObj.oauth_token 		= a_tempObj.oauth_token;
		this.twitterAuthenticatedObj.oauth_token_secret = a_tempObj.oauth_token_secret;
		this.twitterAuthenticatedObj.user_id 			= a_tempObj.user_id;
		this.twitterAuthenticatedObj.screen_name 		= a_tempObj.screen_name;
		this.setTwitterCookie(convertObjectToString(TwitterPost.twitterAuthenticatedObj));
//		TwitterAPI.setConfig(this.getTwitterAPIConfig());
//		TwitterAPI.getSWF(TwitterAPI.SWF_ID).refreshConfig();
		this.launchTwitterShare(this.url1, this.requestedAction, this.url2);
	},
	
	/**
	 * Used to close the window that is opened from the oAuth call 
	 **/
	closeOAuthWin:function(){
		this.twitterAuthWindow.close();
	},
	
	twitterDown:function(){
		alert("Sorry, Twitter is currently down. Please try back later");
	},
	
	openDialog: function(a_dialogID){
		this.toggleLoadingScreen(false);
		$("#"+a_dialogID).dialog("open");
	},
	closeDialog: function(a_dialogID){
		$("#libHolder").html("");
		$("#"+a_dialogID).dialog("close");
	},
	
	createTwitterModals: function(){
		$("#twitterModal").dialog({
			autoOpen:false,
			draggable:true,
			resizable:false,
			modal:true,
			overlay:{opacity:0.4,background:"black"},
			position:"center",
			height:330,
			width:440,
			show:{effect:"fade",speed:500},
			hide:{effect:"fade",speed:250}
		}).show();
	}
};

/**
 * this is used with the TwitterPost object, this is more like a constants
 * object
 **/
var TwitterActions={
	POST_BACKGROUND:			"POST_BACKGROUND",
	POST_NEW_PROFILE_PICTURE:	"POST_NEW_PROFILE_PICTURE",
	ADD_OVERLAY_TO_PROFILE:		"ADD_OVERLAY_TO_PROFILE"
}

function setShortenedStatus(a_str, a_callback){
	BitlyAPI.setConfig(getBitlyConfig());
	BitlyHelper.findAndReplaceLinks(a_str, function(a_str_response){
		TwitterAPI.setStatus(a_callback, a_str_response);
	});
}

function getBitlyConfig(){
	return {
			bitlyConfig:{
				login: 		"bulldog",
				apiKey: 	"R_38562e6c99903b937119cb4bad551819",
				version:	"2.0.1",
				format:		"json"
			}
		};
}