﻿var winnla = {};

if (typeof console == "undefined" || typeof console.log == "undefined")
	var console = { log: function() { } };

var _isLoading = false;

jQuery.query = function(s) {
	var r = {};
	if (s) {
		var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
		q = q.replace(/\&$/, ''); // remove the trailing &
		jQuery.each(q.split('&'), function() {
			var splitted = this.split('=');
			var key = splitted[0];
			var val = splitted[1];

			// convert numbers
			if (/^[0-9.]+$/.test(val))
				val = parseFloat(val);
			// convert booleans
			if (val == 'true')
				val = true;
			if (val == 'false')
				val = false;
			// ignore empty values
			if (val && (typeof val == 'number' || typeof val == 'boolean' || val.length > 0)) r[key] = val;
		});
	}
	return r;
};

jQuery.extend({
	utils: {
		decodeHTML: function(str) {
			return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
		},
		encodeHTML: function(str) {
			return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
		}
	}
});

winnla.fbQueries = function() {
	var d = document.location.toString();
	var q = (d.indexOf('?') > -1) ? d.substring(d.indexOf('?') + 1) : d;
	var r = '';

	jQuery.each(q.split('&'), function() {
		var splitted = this.split('=');
		var key = splitted[0];
		var val = splitted[1];

		if (key.length > 3 && key.substring(0, 3) == "fb_") {
			r += key + "=" + val + "&";
		}
	});

	return r;
}

winnla.changeLocation = function(url) {

	if ((url.indexOf('?') == -1)) {
		url += "?";
	} else {
		if (url.substring(url.length - 1) != "&") {
			url += "&";
		}
	}

	url += winnla.fbQueries();

	window.location = url;
}

winnla.changeCampaign = function(campaignId) {
    
    winnla.changeLocation("/Fb/Campaigns/" + campaignId);
}


winnla.trackOpen = function( url ) {

    //TODO: Implement tracking here, to know how many (and by who) sponsors links opened
    
    //window.open(url, 'name','attributes');
    window.open(url, '_wnlaPopup');
}

winnla.loadFriends = function() {
    $.post('/API/AppFriends'
		, {}
		, function(data, status) {

		    //	let's build our data
		    data = eval('(' + data + ')');

		    for (var i = 0; i < data.Friends.length; i++) {

		        if (i >= 4) {
		            break;
		        }

		        var asd = '<fb:profile-pic uid="' + data.Friends[i] + '" size="square"></fb:profile-pic><br />'
							+ '<fb:name uid="' + data.Friends[i] + '" capitalize="true"></fb:name><br />';

		        $("ul.mutualFriends li.empty:first").replaceWith('<li>' + asd + '</li>');
		    }

		    winnla.parseFbml();
		}
	);
}


winnla.loadWinners = function() {
	//	load past winners
	$.post('/API/Winners/'
		, { competitionId: 0 }
		, function(data, status) {

			//	let's build our data

			if (typeof data == 'string')
				data = eval('(' + data + ')');

			for (var i = 0; i < data.length; i++) {

				if (i >= 5) {
					break;
				}

				var asd = '<fb:profile-pic uid="' + data[i].FacebookUid + '" size="square"></fb:profile-pic><br />'
					+ '<fb:name uid="' + data[i].FacebookUid + '" capitalize="true"></fb:name><br />'
					+ '<span class="prize">' + data[i].PrizeTitle + '</span><br />'
					+ ((data[i].EntryLimit > 0) ? '<span class="odds">1 in ' + data[i].EntryLimit + ' chance</span><br />' : '<br />');

				$("ul.winners li.empty:first").replaceWith('<li>' + asd + '</li>');
			}

		}
	);
}

winnla.inviteFriends = function(isCompetitionInvite) {

    var id = (isCompetitionInvite) ? "#inviteTaskRequestFormContainer" : "#inviteRequestFormContainer"
    var placement = (isCompetitionInvite) ? FB.UI.PopupPlacement.topCenter : FB.UI.PopupPlacement.center;

    var dialog = new FB.UI.FBMLPopupDialog('Invite your friends to Winnla', '');
    var fbml = $(id).html();

    dialog.setFBMLContent(fbml);
    dialog.setContentWidth(740);
    dialog.setContentHeight(550);
    dialog.set_placement(placement);

    dialog.show();

}


winnla.publishCompetitionStory = function(userMessagePromt, callback, actorId) {

	if (userMessagePromt == "")
		userMessagePromt = 'Add a comment (optional)';

	winnla.publishStory('', competitionStoryAttachment, competitionStoryActionLinks, null, userMessagePromt, callback, false, actorId)
}

winnla.publishWinnerStory = function(userMessagePromt, callback, actorId) {

	winnla.publishStory('', winnerStoryAttachment, winnerStoryActionLinks, null, userMessagePromt, null, false, actorId);
}


winnla.publishStory = function(userMessage, attachment, actionLinks, targetId, userMessagePromt, callback, autoPublish, actorId) {
    
    FB.ensureInit(function() {
        FB.Connect.requireSession(function() {
            FB.Connect.streamPublish(userMessage, eval(attachment), eval(actionLinks), targetId, userMessagePromt, callback, autoPublish, actorId);
        });
    });
    //streamPublish(user_message, attachment, action_links, target_id, user_message_prompt, callback, auto_publish, actor_id);
}



winnla.parseFbml = function() {
	if (FB.XFBML.Host.parseDomTree) {
		setTimeout(FB.XFBML.Host.parseDomTree, 0);
	}
}


winnla.checkUtcOffset = function() {

	var d = new Date().getTimezoneOffset() / 60 * -1;

	//	keep cookie for two weeks from now
	var date = new Date();
	date.setTime(date.getTime() + (14 * 24 * 60 * 60 * 1000));

	var domain = null;
	var e = date.toGMTString();
	var p = "/";

	document.cookie = "utcOffset=" + escape(d)
				+ ((e) ? "; expires=" + e : "")
				+ ((p) ? "; path=" + escape(p) : "")
				+ ((domain) ? "; domain=" + domain : "");

}

winnla.authenticate = function() {

	FB.ensureInit(function() {
		FB.Connect.requireSession(function() {
			var url = "http://" + host + "/fb/DoubleHack/";
			
			if (parent != self) {
				top.location.href = url;
			} else {
				self.location.href = url + 'standalone';
			}
		});
	});
}


winnla.reloadCurent = function() {

	//	reload current page (easy way out :))
	window.location.reload();
}



winnla.enableElement = function(elementId) {

	$(elementId).removeAttr("disabled")
		.removeClass("disabled");
}

winnla.disableElement = function(elementId) {

	$(elementId).attr("disabled", "disabled")
		.addClass("disabled");
}

winnla.parseTime = function(targetTime) {

	var now = new Date();

	var dateDiffMilliseconds = targetTime.valueOf() - now.valueOf();

	var secondsLeft = parseInt(dateDiffMilliseconds / 1000);

	var minutesLeft = parseInt(secondsLeft / 60);
	var hoursLeft = parseInt(minutesLeft / 60);

	secondsLeft = secondsLeft % 60;

	var displayable;

	if (secondsLeft > 0) {
		displayable = secondsLeft.toString();
	}

	if (minutesLeft > 0) {
		displayable = minutesLeft + ":" + (secondsLeft < 10 ? "0" : "") + secondsLeft;
	}

	if (hoursLeft > 0) {
		minutesLeft = minutesLeft % 60;
		//displayable = hoursLeft + (secondsLeft % 2 == 0 ? ":" : " ") + (minutesLeft < 10 ? "0" : "") + minutesLeft;
		displayable = hoursLeft + ":" + (minutesLeft < 10 ? "0" : "") + minutesLeft + ":" + (secondsLeft < 10 ? "0" : "") + secondsLeft;
	}

	return displayable;
}



$(function() {
	//	needs argument param passed $('.mainNavItem').click(function() { winnla.changeCampaign(); });
	$('.inviteFriends').click(function() { winnla.inviteFriends(); });

	//winnla.loadWinners();
	//winnla.loadFriends();

	winnla.checkUtcOffset();

	setTimeout(winnla.parseFbml, 1000);

	if (isConnect == 0) {
		$('a').each(function() {

			var href = this.href;

			if (href.indexOf(host) > -1 && href.indexOf('fb_') == -1) {
				if ((href.indexOf('?') == -1)) {
					href += "?";
				} else {
					if (href.substring(url.length - 1) != "&") {
						href += "&";
					}
				}

				href += winnla.fbQueries();

				this.href = href;
			}

		});

		//	any external links should move the entire frameset, not reload the page
		$("a").live('click', function() {
			if (this.href.indexOf(host) == -1) {

				try {
					var h = this.href;
					var ios = h.indexOf('//') + 2;
					h = h.substr(ios, h.indexOf('/', ios + 1) - ios);

					_gaq.push(['_trackPageview', '/track/' + h + '/link']);

				} catch (err) { }

				if (this.target == "" && parent != self) {
					top.location.href = this.href;
				}
			}
		});

	}

	$('.loginButton').click(winnla.authenticate);
});





winnla.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};

winnla.showLoader = function(html) {
	_isLoading = true;
	if (!html) {
		html = '&nbsp;'
	}
	$('#ajaxLoader').html(html).show();
}

winnla.hideLoader = function() {
	_isLoading = false;
	$('#ajaxLoader').hide();
}

