var postReady
	, tweetReady
	, dailyCreditReady
	, hasTasks
	, isFirstUiUpdate = true;

// Initialize
//---
$(function() {

	if (isAuthenticated == 0) {
		winnla.showMessage('/fb/help/Welcome', {}, false);

		$('.task_fan').click(winnla.authenticate);
		$('.task_bookmark').click(winnla.authenticate);
		$('.task_fan_other').click(winnla.authenticate);
	}
	else {
		if (showWelcomeBack == 1) {
			winnla.showMessage('/fb/help/WelcomeBack', {}, false);
		}

		$('.task_fan').click(winnla.earnFan);
		$('.task_bookmark').click(winnla.earnBookmark);
		$('.task_fan_other').click(winnla.earnFanOther);
		$('.task_demo_1').click(winnla.earnDemo1);
		$('.task_demo_2').click(winnla.earnDemo2);
		$('.task_email').click(winnla.earnEmail);
	}

	$('#taskPlay').click(function() {
		winnla.changeLocation('/Fb/Pages/Games');
	});

	$('#taskOxfam').click(function() {
		winnla.changeLocation('/Fb/Pages/Charity');
	});

	// load entries for member initially
	$.post('/API/EntriesForMember/' + '?' + winnla.fbQueries()
		, {}
		, winnla.updateUi
	);

	if (secondsUntilNextPost == 0) {
		if (isAuthenticated == 0) {
			$('#referWall').click(winnla.authenticate);
		}
		else {
			$('#referWall').click(winnla.referWall);
		}
	} else {
		winnla.updatePostTimer();
	}

	if (secondsUntilNextTweet == 0) {
		$('#referTweet').click(winnla.referTweet);
	} else {
		winnla.updateTwitterTimer();
	}

	if (secondsUntilNextDailyCredit != 0) {

		dailyCreditReady = new Date();
		dailyCreditReady.setSeconds(dailyCreditReady.getSeconds() + secondsUntilNextDailyCredit);

		$(document).everyTime(1000, 'dailyCreditPoller', winnla.countdownDailyCredit);
	}

	//	enter competition button click
	$('.enterCompetition').click(winnla.enterCompetition);

	//	earn entries
	$('.referInvite').click(winnla.referInvite);

	// add faq message click handlers
	//---
	$("#faqShare").click(function() {
		winnla.showMessage('/fb/help/Refer');
	});

	$("#faqTickets").click(function() {
		winnla.showMessage('/fb/help/Tickets');
	});

	$('.tooltip').hover(winnla.toolTipOn, winnla.toolTipOff);

	winnla.toggleTaskView();
});

//	toggle the task view
winnla.toggleTaskView = function() {

	var taskCount = $('.task_node').size();

	if (taskCount == 0) {
		$("#tasksFull").hide();
		$("#tasksEmpty").show();
		hasTasks = false;
	}
	else {
		$("#tasksEmpty").hide();
		$("#tasksFull").show();
		hasTasks = true;
	}
}

//	when you have finished entering a competition
winnla.earnComplete = function(d, s) {

	if (typeof d == 'string')
		d = eval('(' + d + ')');

	switch (d.ConfirmationType) {
		case "Comment":
			winnla.checkPostability();
			break;

		case "DirectComment":
			winnla.checkPostability();
			break;

		case "Tweet":
			winnla.updateTwitterTimer();
			break;

		case "SetupEmail":
			$('.task_email').hide();
			break;

		case "Demographic_1":
			$('.task_demo_1').hide();
			break;

		case "Demographic_2":
			$('.task_demo_2').hide();
			break;

		default:
			break;
	}

	winnla.hideLoader();

	if (d.ReturnCode == 2) {
		//	task was not valid

		winnla.showLoader();

		$('#closeNiceOverlay').live('click', winnla.closeOverlay);
		
		$('#overlayContent').load('/fb/Help/Oops'
			, ''
			, function() {
				$("#ooooops").fadeIn('fast');
				if (!$.browser.msie) {
					$('.no_click_overlay').fadeTo('slow', 0.6);
				}
				winnla.hideLoader();
				winnla.parseFbml();
			}
		);
		
	} else {

		winnla.showMessage("/fb/Help/EarnComplete/"
			, { earnType: d.ConfirmationType, tickets: d.NumberOfEntries }
			, false
		);

		_gaq.push(['_trackPageview', '/tasks/' + d.ConfirmationType + '.completed']);
	}

	var currentTickets = $('#counterAvailableTickets').html().replace(' tickets', '');

	if (isNaN(currentTickets)) {
		currentTickets = 0;
	}

	winnla.changeAvailableTickets((parseInt(currentTickets) + d.NumberOfEntries));

	//isFirstUiUpdate = false;
}

winnla.checkPostability = function() {
	$.post('/API/NextMemberToInvite/' + '?' + winnla.fbQueries()
		, {}
		, winnla.nextMemberCallback
	);
}

winnla.nextMemberCallback = function(d, s) {

	if (typeof d == 'string')
		d = eval('(' + d + ')');

	nextPostUid = d.NextPostUid;
	shareStoryAttachment = eval('(' + d.Story + ')');

	winnla.updatePostTimer();
}

winnla.updatePostTimer = function() {

	if (nextPostUid > 0) {
		//	nothing, we can do it again!
		winnla.enableElement('#referWall');
	} else {

		$('#referWall').unbind('click');

		if (secondsUntilNextPost == 0)
			secondsUntilNextPost = postDelayInHours * 60 * 60;

		postReady = new Date();
		postReady.setSeconds(postReady.getSeconds() + secondsUntilNextPost);

		$(document).everyTime(1000, 'postPoller', winnla.countdownPosts);
	}
}
// test

winnla.updateTwitterTimer = function() {

	if (secondsUntilNextTweet == 0)
		secondsUntilNextTweet = twitterPostDelayInHours * 60 * 60;

	tweetReady = new Date();
	tweetReady.setSeconds(tweetReady.getSeconds() + secondsUntilNextTweet);

	$(document).everyTime(1000, 'tweetPoller', winnla.countdownTweets);
}

var gCompId = 0;

winnla.enterCompetition = function() {
	var hasPreReq = $(this).hasClass('preReq');

	var competitionId = $(this).parent().children(".entryCounter").attr("id").replace('entryCounter_', '');

	if (!hasPreReq) {
		$.post('/API/EnterCompetition/' + competitionId + '?' + winnla.fbQueries()
			, { n: 1 }
			, winnla.updateUi
		);
	} else {
		profilePageId = $(this).attr('uid');

		if (isAuthenticated == 0) {
			winnla.authenticate();
			return;
		}

		//	if ! fan then become fan + enter
		//	else must send direct message to enter
		gCompId = competitionId;

		FB.Facebook.apiClient.pages_isFan(profilePageId
			, FB.Facebook.apiClient.get_session().uid
			, function(data) {
				if (data) {
					//alert('show message');
					winnla.showAMessage(profilePageId);
				} else {
					winnla.doAFan(profilePageId, winnla.preReqFanEnter);
				}
			}
		);
	}
}

var __t = '';

winnla.preReqFanEnter = function() {
	__t = 'fan';
	winnla.preReqEnter('fan', 'InAppFan' + profilePageId);
}

winnla.preReqPostEnter = function(postId) {
	__t = 'post';
	winnla.preReqEnter(postId, 'InAppPost' + profilePageId);
}

winnla.preReqEnter = function(postId, type) {
	if (postId) {
		$.post('/API/EnterCompetition/' + gCompId + '?' + winnla.fbQueries()
			, { n: 1, postId: postId, type: type, profilePageId: profilePageId }
			, winnla.updateUi
		);
	}
}

winnla.showAMessage = function(pageUid) {
	//	create message
	var attachment = {};
	for (var i in attachments) {
		if (attachments[i]['uid'] == pageUid) {
			attachment = attachments[i];
			break;
		}
	}

	//	display
	var action_links = attachment['action_links'];
	attachment = attachment['attachment'];

	FB.ensureInit(function() {
		FB.Connect.requireSession(function() {
			FB.Connect.streamPublish('', attachment, action_links, null, 'Tell your friends to join in with a personal note!', winnla.preReqPostEnter);
		});
	});
}

//	refresh display current entries
winnla.updateUi = function(d, s) {

	if (typeof d == 'string')
		d = eval('(' + d + ')');

	//	no data, quit
	if (!d.Competitions) {
		return;
	}

	for (var a in d.Competitions) {
		var h = $('#entryCounter_' + d.Competitions[a].CompetitionId).html();
		var n = d.Competitions[a].EntryCount;

		//	only update if changed to avoid client side flicker
		if (h != n) {
			$('#entryCounter_' + d.Competitions[a].CompetitionId)
				.hide()
				.html(n)
				.fadeIn();
		}
	}

	winnla.changeAvailableTickets(d.RemainingEntries, d.ThirdPartyDisabled);
	setTimeout(function() { winnla.changeScore(d.Score) }, 2000);

	// TODO
	if (isFirstUiUpdate) {
		if (isInvite) {
			winnla.showMessage("/fb/Help/EarnComplete/"
				, { earnType: "Invite" }
				, false);
		}
	}

	if (__t == 'fan') {

		$("#overlay").fadeOut('fast'
			, function() {
				$('#overlayContent').html('');
				$("#page").fadeIn('slow');
			}
		);
		
		winnla.fanCheckCancel();
	}

	isFirstUiUpdate = false;
}


// increments / decrements the available tickets count and changes the ui accordingly
winnla.changeAvailableTickets = function(count, thirdPartyDisabled) {

	$('#counterAvailableTickets').html(count);

	if (count == 0) {
		$('.enterCompetition').attr("disabled", "disabled");
		$('.enterCompetition').addClass("disabled");

		winnla.showEarnMore();
	}
	else {
		$('.enterCompetition').removeAttr("disabled");
		$('.enterCompetition').removeClass("disabled");

		for (var i in thirdPartyDisabled) {
			$('#competition_' + thirdPartyDisabled[i] + ' .enterCompetition').attr("disabled", "disabled").addClass("disabled");
		}
	}
}

winnla.changeScore = function(totalScore) {

	var o = new Object();
	o.lowerThreshold = 0;
	o.upperThreshold = 0;

	var currentLevel = winnla.calculateLevel(totalScore, o);

	var myLevelPoints = Math.round(totalScore - o.lowerThreshold);
	var levelPointsRequired = Math.round(o.upperThreshold - o.lowerThreshold);

	var progressFraction = myLevelPoints / levelPointsRequired;
	var progressPercentage = Math.round(myLevelPoints / levelPointsRequired * 100);

	// is lelvel up
	if (currentLevel > parseInt($('#counterLevel').html())) {
		$("#dailyCreditCounter").html(parseInt($('#dailyCreditCounter').html()) + 2);
	}

	$('#counterLevel').html(currentLevel);
	$('#counterProgress').html(progressPercentage + "%");  //myLevelPoints + " / " + levelPointsRequired);

	$('#barProgress').css('width', progressFraction * 154);

}

winnla.calculateLevel = function(totalScore, o) {

	var c = 1;
	for (var i = 10; i < 100000; i *= 1.5) {
		if (totalScore < i) {
			o.upperThreshold = i;
			return c;
		}
		o.lowerThreshold = i;
		c++;
	}

	return 0;
}




winnla.showEarnMore = function() {

	// TODO:
	// Add earn by task - show this if tasks list not empty
	var earnType = "Refer";

	if (hasTasks)
		earnType = "Tasks";

	// TODO:
	// Alternate message between earn by reffer and earn by task.
	// Or maybe show which is ever is most relevant first.
	// Also, surpress afte each is show once in this session
	if (!isFirstUiUpdate) {
		if (isFan) {
			winnla.showMessage('/Fb/Help/AllGone', { earnType: earnType });
		}
		else {
			winnla.showMessage('/Fb/Help/AllGone', { earnType: earnType });
		}
	}
}


// messgaes
//-----------------------------------------------------------------------------------------------------

// message popup
winnla.showMessage = function(msgLocation, formData, showClose) {

	$('#messageContent').load(msgLocation, formData, winnla.messageLoadComplete);
	$("#messagePanel").fadeIn('slow');

	$("#popmeOk").click(winnla.hideMessage);
	$("#popmeOk").show();
}
winnla.messageLoadComplete = function() {

	$("#messageContent").fadeIn('slow').animate({ opacity: 1.0 }, 2000);
}

winnla.hideMessage = function() {

	$("#messagePanel").fadeOut();
	$("#messageContent").html("");

	$("#popmeOk").unbind('click');
}

// small message panel
winnla.showSmallMessage = function(messageId, hideAutomatically) {

	if (hideAutomatically == true) {
		setTimeout(winnla.hideMessageSmall, 6000);
	}

	$('.msg').hide();
	$(messageId).show();
	$("#smallMessage").show();
}
winnla.hideMessageSmall = function() {

	$("#smallMessage").fadeOut(2000);
}

// hover tooltip
winnla.toolTipOn = function() {

	var $this = $(this);

	//get the position of the placeholder element
	var pos = $this.offset();

	var title = $this.attr('title');
	$this.data('title', title);
	$this.removeAttr('title');

	//show the menu directly over the placeholder
	$("#tooltip").html(title);
	//$("#tooltip").css({ "left": (pos.left - 30) + "px", "top": (pos.top + 50) + "px" });
	$("#tooltip").css({ "top": (pos.top + 80) + "px" });
	$("#tooltip").show();
}
winnla.toolTipOff = function() {

	$(this).attr('title', $(this).data('title'));

	$("#tooltip").html();
	$("#tooltip").hide();
}


winnla.referInvite = function() {

	winnla.changeLocation('/Fb/Pages/Invite');
}



//	post
//------------------------------------------------------------------------------------------------------
winnla.referWall = function() {

	window.frames.postFrame.showPublishDialog("", nextPostUid);

	$("#overlayPost").show();
}

winnla.postComplete = function(postId) {

	$(document).stopTime('postedPoller');

	$("#overlayPost").hide();

	if (!postId || postId == "null") {

		winnla.checkPostability();

		return;
	}

	winnla.disableElement('#referWall');

	var taskType = (nextPostUid > 0) ? "DirectComment" : "Comment";

	// submit entry to server
	$.post('/API/SubmitTask' + '?' + winnla.fbQueries()
		, { confirmationType: taskType, postId: postId, targetUid: nextPostUid }
		, winnla.earnComplete
	);
}




winnla.referWallOld = function() {

	winnla.showPublishDialog(''
		, shareStoryAttachment
		, shareStoryActionLinks
		, null
		, "Earn tickets by sharing Winnla with your friends"
		, winnla.publishComplete
		, false
		, ""
	);
}

//	displays publish dialog for user
winnla.showPublishDialog = function(userMessage, attachment, actionLinks, targetId, userMessagePrompt, callback, autoPublish, actorId) {

	FB.ensureInit(function() {
		FB.Connect.requireSession(function() {
			FB.Connect.streamPublish(userMessage
				, eval(attachment)
				, eval(actionLinks)
				, targetId
				, userMessagePrompt
				, callback
				, autoPublish
				, actorId
			);
		});
	});
}

//	callback once story is published (or not)
winnla.publishComplete = function(postId, exception, data) {

	if (!postId || postId == "null") {
		return;
	}

	// disable publish for x hours (server requires code for this)
	$('#referWall').attr("disabled", "disabled");
	$('#referWall').addClass("disabled");
	$('#referWall').unbind('click');

	// TODO:
	// Replace "Wall Post" with countdown

	// submit entry to server
	$.post('/API/SubmitTask' + '?' + winnla.fbQueries()
		, { confirmationType: "Comment", postId: postId }
		, winnla.earnComplete
	);
}









// tasks
//----------------------------------------------------------------------------------------------

winnla.earnDemo1 = function() {
	winnla.earnDemo('', winnla.demoValidate);
}

winnla.earnDemo2 = function() {
	winnla.earnDemo('2', winnla.demoValidate2);
}

winnla.earnDemo = function(demoId, validator) {

	$('#closeDemoWindow').live('click', winnla.closeOverlay);
	$('#demoSave').live('click', validator);

	winnla.showLoader();

	$('#overlayContent').load('/fb/Tasks/Demo' + demoId
		, ''
		, function() {
			if (demoId == '') {
				winnla.demoPopulate();
			}
			$('#overlay').fadeIn('fast');
			if (!$.browser.msie) {
				$('.no_click_overlay').fadeTo('slow', 0.6);
			}
			winnla.hideLoader();
			winnla.parseFbml();
		}
	);

	winnla.hideMessage();

}

winnla.earnBookmark = function() {

	$('#messageContent').load('/fb/Tasks/Bookmark'
        , ''
        , function() {
        	$("#messageContent").fadeIn('slow').animate({ opacity: 1.0 }, 2000);
        	winnla.parseFbml();
        }
    );

	$("#messagePanel").fadeIn('slow');
}

winnla.earnEmail = function() {

	$('#closeEmailWindow').live('click', winnla.closeOverlay);
	$('#emailPrompt').live('click', winnla.promptForEmail);

	winnla.showLoader();

	$('#overlayContent').load("/fb/Tasks/Email"
		, ''
		, function() {
			$('#overlay').fadeIn('fast');
			if (!$.browser.msie) {
				$('.no_click_overlay').fadeTo('slow', 0.6);
			}
			winnla.hideLoader();
			winnla.parseFbml();
		}
	);

	winnla.hideMessage();
}

winnla.promptForEmail = function() {
	winnla.closeOverlay();
	FB.Connect.showPermissionDialog("email", winnla.emailPermissionComplete);
}

winnla.emailPermissionComplete = function(perms) {

	if (perms) {

		winnla.showLoader('saving...');

		$.post('/API/SubmitTask' + '?' + winnla.fbQueries()
			, { confirmationType: "SetupEmail" }
			, winnla.earnComplete
		);
	}
}

winnla.demoPopulate = function() {

	var fields = new Array();

	fields.push('birthday_date', 'sex', 'meeting_sex', 'meeting_for', 'relationship_status');

	FB.Facebook.apiClient.users_getInfo(FB.Facebook.apiClient.get_session().uid, fields, winnla.loadDemoData);
}

winnla.loadDemoData = function(d, ex) {

	var fsl = d[0]['sex'];
	if (fsl.length > 0) {
		fsl = fsl[0];
		$('select[name="demo1_sex"] option[value="' + fsl + '"]').attr('selected', 'selected');
	}
	fsl = d[0]['birthday_date'];
	if (fsl.length > 0) {
		var a = new Date(fsl);
		var m = a.getMonth() + 1;

		$('select[name="demo1_bday_day"]').val(a.getDate());
		$('select[name="demo1_bday_month"]').val((m < 9 ? "0" : "") + (a.getMonth() + 1));
		$('select[name="demo1_bday_year"] option[value="' + a.getFullYear() + '"]').attr('selected', 'selected');
	}
	fsl = d[0]['relationship_status'];
	$('select[name="demo1_relationship_status"]').val(fsl);

	fsl = d[0]['meeting_for'];
	for (var i in fsl) {
		$('input[name="demo1_meeting_for"][value="' + fsl[i] + '"]').attr('checked', 'checked');
	}
	fsl = d[0]['meeting_sex'];
	for (var i in fsl) {
		$('input[name="demo1_meeting_sex"][value="' + fsl[i] + '"]').attr('checked', 'checked');
	}
}

winnla.demoValidate = function() {

	var day = $('select[name="demo1_bday_day"]')[0]
		, month = $('select[name="demo1_bday_month"]')[0]
		, year = $('select[name="demo1_bday_year"]')[0];

	day = day.options[day.selectedIndex].value;
	month = month.options[month.selectedIndex].value;
	year = year.options[year.selectedIndex].value;

	var bd = new Date(year, month - 1, day);

	if (winnla.isValidDate(day, month, year)) {

		winnla.showLoader('saving...');

		var s = $('select[name="demo1_sex"] option:selected').val()
			, rs = $('select[name="demo1_relationship_status"] option:selected').val()
			, mf = []
			, ms = [];

		$('input[name="demo1_meeting_for"]:checked').each(function() {
			mf.push(this.value);
		});

		$('input[name="demo1_meeting_sex"]:checked').each(function() {
			ms.push(this.value);
		});

		mf = mf.join(',');
		ms = ms.join(',');

		winnla.closeOverlay();

		$.post('/API/SubmitTask' + '?' + winnla.fbQueries()
			, { confirmationType: "Demographic_1"
				, birthday_date: bd
				, sex: s
				, relationship_status: rs
				, meeting_for: mf
				, meeting_sex: ms
			}
			, winnla.earnComplete
		);

	} else {
		$('.demo1_bday_error').html('Please enter a valid date');
	}
}

winnla.demoValidate2 = function() {

	winnla.showLoader('saving...');

	var formData = 'confirmationType=Demographic_2&' + $('#demographicInfo form').serialize();

	winnla.closeOverlay();

	$.post('/API/SubmitTask' + '?' + winnla.fbQueries()
		, formData
		, winnla.earnComplete
	);
}

winnla.isValidDate = function(day, month, year) {

	var leap = 0;
	
	if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
		leap = 1;
	}
	
	if ((month == "02") && (leap == 1) && (day > 29)) {
		return false;
	}
	
	if ((month == "02") && (leap != 1) && (day > 28)) {
		return false;
	}
	
	if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
		return false;
	}
	
	if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
		return false;
	}
	
	return true;
}


// fan task
//----------------------------------------------------------------------------------------------

winnla.earnFan = function() {

	// global for use in other methods
	profilePageId = $(this).attr('id').replace('li', '');

	$('#closeFanWinnla').live('click', winnla.closeFanWindow);
	
	winnla.showLoader();

	$('#messageContent').load('/fb/Tasks/FanWinnla'
		, ''
		, function() {
			$("#messagePanel").fadeIn('slow');
			$("#popmeOk").hide();
			winnla.parseFbml();
			winnla.hideLoader();
		}
	);

	var fanPollerId = "Fan" + profilePageId;

	$(document).everyTime(2000
		, 'fanCheckPoller'
		, function() {
			winnla.isFanCheck(profilePageId, fanPollerId, winnla.fanComplete);
		}
	);
}

winnla.earnFanOther = function() {
	// global for use in other methods
	profilePageId = $(this).attr('id').replace('li', '');

	winnla.doAFan(profilePageId, winnla.fanOtherComplete);
}

winnla.doAFan = function(profilePageId, onComplete) {

	$('#btnCloseFanWindow').live('click', winnla.closeFanOtherWindow);

	winnla.showLoader();

	$('#overlayContent').load("/fb/Tasks/FanOther/" + profilePageId
		, ''
		, function() {
			$("#page").hide();
			$("#overlay").fadeIn('slow');
			winnla.parseFbml();
			winnla.hideLoader();
			winnla.hideMessage();
		}
	);

	var fanPollerId = "Fan" + profilePageId;

	$(document).everyTime(2000
		, 'fanCheckPoller'
		, function() {
			winnla.isFanCheck(profilePageId, fanPollerId, onComplete);
		}
	);
}

winnla.isFanCheck = function(profileId, confirmationType, onComplete) {

	FB.Facebook.apiClient.pages_isFan(profileId
		, FB.Facebook.apiClient.get_session().uid
		, function(data) {
			if (data) {
				winnla.fanCheckComplete(confirmationType, onComplete);
			}
		}
	);
	/*
	$.post('/API/IsFan/' + '?' + winnla.fbQueries()
		, { profileId: profileId }
		, function(data, textStatus) {
			if (data.toString() == "true") {
				winnla.fanCheckComplete(confirmationType, onComplete);
			}
		}
	);*/
}

winnla.fanCheckComplete = function(confirmationType, onComplete) {

	winnla.fanCheckCancel();

	//	submit entry to server
	$.post('/API/SubmitTask' + '?' + winnla.fbQueries()
		, { confirmationType: confirmationType }
		, onComplete
	);
}

winnla.fanComplete = function(d, s) {

	winnla.fanOtherComplete(d, s);

	winnla.closeFanWindow();
}

winnla.fanOtherComplete = function(d, s) {

	// Update points earnt
	winnla.earnComplete(d, s);

	var nodeId = "#li" + profilePageId;
	$(nodeId).remove();

	profilePageId = '';

	winnla.toggleTaskView();
	winnla.closeFanOtherWindow();
}

winnla.closeFanWindow = function(event) {

	winnla.hideMessage();
	winnla.fanCheckCancel();
	//event.preventDefault();
}

winnla.closeFanOtherWindow = function() {

	$("#overlay").fadeOut('fast'
		, function() {
			$('#overlayContent').html('');
			$("#page").fadeIn('slow');
		}
	);
	winnla.fanCheckCancel();
}

winnla.closeOverlay = function() {

	$('.no_click_overlay').fadeTo('fast'
		, 0.0
		, function() {
			$('.nice_overlay').fadeOut('fast');
			$("#overlay").fadeOut('fast'
				, function() {
					$('#overlayContent').html('');
					$("#page").fadeIn('slow');
				}
			);
		}
	);
}

winnla.fanCheckCancel = function() {

	$(document).stopTime('fanCheckPoller');
}

















// tweet
//----------------------------------------------------------------------------------------------
winnla.referTweet = function() {

	var twitterAppAddedAndActiveSession = false; // Set via checking process
	if (twitterAppAddedAndActiveSession) {
		winnla.referTweetConfirmed();
	}
	else {
		var w = window.open("http://" + host + "/Twitter/Connect", "twcWindow", "width=800,height=400,left=150,top=100,scrollbar=no,resize=no");

		//	w.onbeforeunload = winnla.checkTweetAuthentication;
		//	$(w).bind('unload', winnla.checkTweetAuthentication); ;
		//	alert($('twcWindow').html());
	}
}
winnla.checkTweetAuthentication = function() {

	$.post('/Twitter/IsAuthenticated'
		, {}
		, winnla.checkTweetAuthenticationFinished
	);
}
winnla.checkTweetAuthenticationFinished = function (d, s) {
	if (typeof d == 'string')
		d = eval('(' + d + ')');

	if (d.IsAuthenticated == 1) {
		winnla.referTweetConfirmed();
	}
}
winnla.referTweetConfirmed = function() {

	var toLoad = "/Twitter/Tweet/";

	$('#overlayContent').load(toLoad, '', winnla.initTwitter);
	$("#page").fadeOut('slow');
	$("#overlay").fadeIn('slow');

	winnla.hideMessage();

}
winnla.tweetComplete = function (d, s) {
	if (typeof d == 'string')
		d = eval('(' + d + ')');

	winnla.disableElement("#referTweet");

	winnla.closeTweetWindow();

	$('#referTweet').attr("disabled", "disabled");
	$('#referTweet').addClass("disabled");
	$('#referTweet').unbind('click');

	if (d.Response != 'NO_MESSAGE') {
		//	submit entry to server
		$.post('/API/SubmitTask' + '?' + winnla.fbQueries()
			, { confirmationType: "Tweet" }
			, winnla.earnComplete
		);
	}
}
winnla.closeTweetWindow = function() {

	$("#overlay").fadeOut('slow');
	$("#page").fadeIn('slow');
}
winnla.initTwitter = function() {

	$('#tweet')
		.change(winnla.updateTwitterCharacterCount)
		.keypress(winnla.updateTwitterCharacterCount)
		.keyup(winnla.updateTwitterCharacterCount)
		.click(winnla.updateTwitterCharacterCount);

	$.post('/API/GenerateTwitterStory/0'
		, {}
		, winnla.loadTwitterStory
	);

	$("#btnCloseTweetWindow").click(function(event) {

		event.preventDefault();
		winnla.closeTweetWindow();
	});

	$("#btnPostTweet").click(function(event) {

		event.preventDefault();

		var tweet = $('#tweet').val();

		if (tweet.length == 0) {
			alert('Please enter a message');
		} else {
			var autoFollow = $('#autoFollow').val();
			$.post('/Twitter/SubmitTweet/' + '?' + winnla.fbQueries()
				, { tweet: tweet, autoFollow: autoFollow }
				, winnla.tweetComplete
			);
		}
	});
}
winnla.loadTwitterStory = function (d, s) {

	var r;
	if (typeof d == 'string')
		r = eval('(' + d + ')');
	else
		r = d;

	$('#tweet').val(r.TwitterStory);

	winnla.updateTwitterCharacterCount();
}
winnla.updateTwitterCharacterCount = function() {

	var remaining = 140 - $("#tweet").val().length;
	var tcc = $("#twitterCharacterCount");
	tcc.html(remaining);

	//	alert($("#tweet").html());
	if (remaining < 0) {
		tcc.addClass("overlimit");
	}
	else {
		tcc.removeClass("overlimit");
	}
}





// countdown stuff
winnla.countdownTweets = function() {

	var dateDiffMilliseconds = tweetReady.valueOf() - new Date().valueOf();

	var secondsLeft = parseInt(dateDiffMilliseconds / 1000);

	if (secondsLeft <= 0) {
		$(document).stopTime('tweetCounter');
		$('#referTweet')
			.removeClass('disabled')
			.attr('disabled', '')
			.click(winnla.referTweet);
		$('#referTweet>.refer_name').html('Twitter');
		return;
	}

	var displayable = winnla.parseTime(tweetReady);

	$('#referTweet>.refer_name').html(displayable);
}

winnla.countdownPosts = function() {

	var now = new Date();

	var dateDiffMilliseconds = postReady.valueOf() - now.valueOf();

	var secondsLeft = parseInt(dateDiffMilliseconds / 1000);

	if (secondsLeft <= 0) {
		$(document).stopTime('postPoller');
		$('#referWall')
			.removeClass('disabled')
			.attr('disabled', '')
			.click(winnla.referWall)
		$('#referWall>.refer_name').html('Wall Post');
		return;
	}

	var displayable = winnla.parseTime(postReady);

	$('#referWall>.refer_name').html(displayable);
}

winnla.countdownDailyCredit = function() {

	var now = new Date();

	var dateDiffMilliseconds = dailyCreditReady.valueOf() - now.valueOf();

	var secondsLeft = parseInt(dateDiffMilliseconds / 1000);

	var displayable = winnla.parseTime(dailyCreditReady);

	$('#dailyCreditTime').html(displayable);
}

