var Assanka = Assanka || {};
Assanka.wp = Assanka.wp || {};
Assanka.wp.cdnhost = 'http://av.r.ftdata.co.uk';
Assanka.wp.pluginsdir = '/blog/wp-content/plugins';
Assanka.wp.templatedir = '/blog/wp-content/themes/ft';
Assanka.wp.meteorhostroot = 't.ft.com';
var Assanka = Assanka || {};
Assanka.auth = Assanka.auth || {};
Assanka.wp = Assanka.wp || {};

// Functions to call when the page is ready, defined beneath for neatness.
Assanka.$(function() {
	Assanka.wp.initMeteor();
	Assanka.wp.initInfernoIntegration();
	Assanka.wp.initHintOnBlurElements();
	Assanka.wp.conditionallyRevealAdminElements();
});



// Connect to meteor if it loaded successfully, the browser is supported, and at least one channel was
// defined for the page
Assanka.wp.initMeteor = function() {
	if (typeof(Meteor) != "undefined" && Meteor.isSupportedBrowser() && (typeof Assanka.wp.meteorchannels == 'object' && Object.prototype.toString.apply(Assanka.wp.meteorchannels) === '[object Array]')) {

		// Set Meteor's client hostid
		if (Assanka.$.cookie('MeteorHostId')) {
			Meteor.hostid = Assanka.$.cookie('MeteorHostId');
		} else {
			var timenow = new Date();
			Meteor.hostid = timenow.getTime()+""+Math.floor(Math.random()*1000000);
			Assanka.$.cookie('MeteorHostId', Meteor.hostid, {path:'/'});
		}

		var serverid = (Assanka.ftlive && Assanka.ftlive.meteorserverid) ? Assanka.ftlive.meteorserverid : Math.floor(Math.random()*5)+1;
		Meteor.host = "data"+serverid+"."+Assanka.wp.meteorhost;

		// Register the meteor event handler - defined in meteorinteraction.js
		Meteor.registerEventCallback("process", Assanka.wp.processMeteorEvent.receive);

		// Subscribe to the channels, backtracking three events
		for (var i = 0; i < Assanka.wp.meteorchannels.length; i++)
			Meteor.joinChannel(Assanka.wp.meteorchannels[i], 3);

		// Connect after twenty seconds, so only page loads which have been open for a short time fire
		// a meteor request.  Use debug mode if requested.
		if (location.search.indexOf("meteordebug") != -1) Meteor.debugmode = true;
		setTimeout(Meteor.connect, Meteor.debugmode?1000:20000);
	}
}

// Set up Inferno integration
Assanka.wp.initInfernoIntegration = function() {
	if (typeof(Inferno) == 'undefined') return;

	Inferno.addFunctionHook(function() {
		Inferno.addFunctionHook(function(content, contid, itemid, mode, sortindex) {
			Assanka.$('#'+itemid).hide().slideDown(300, function(){ Assanka.$(this).css("height", "auto") });
		}, 'postDOMChange');
	}, 'load');
}

// Set up elements with the class .hintonblur to react to focus events
Assanka.wp.initHintOnBlurElements = function() {
	Assanka.$("input.hintonblur").each(function(){
		if (Assanka.$(this).val() == Assanka.$(this).attr("alt"))
			Assanka.$(this).css("color", "#aaa");
	}).focus(function(){
		if (Assanka.$(this).val() == Assanka.$(this).attr("alt"))
			Assanka.$(this).val("").css("color", "black");
	}).blur(function(){
		if (Assanka.$(this).val() == Assanka.$(this).attr("alt") || !Assanka.$(this).val())
			Assanka.$(this).val(Assanka.$(this).attr("alt")).css("color", "#aaa");
	});
}

// Display admin-only elements for "admins" - anyone who has a vaguely correct-looking cookie.
// This isn't a security risk as all it does is show links to admin functionality, which require proper
// authentication and are generally at known (WP) locations - but does mean we can cache pages.
Assanka.wp.conditionallyRevealAdminElements = function() {
	var adminonlyelements = Assanka.$('.alphavilleadminonly');
	if (!adminonlyelements.length) return;
	var lookslikeadmin = false;

	if (document.cookie && document.cookie != '') {
		var cookies = document.cookie.split(';');
		for (var i = 0; i < cookies.length; i++) {
			var cookie = Assanka.$.trim(cookies[i]);
			if (cookie.indexOf('wp-settings-') === 0) {
				lookslikeadmin = true;
				break;
			}
		}
	}
	
	if (lookslikeadmin) adminonlyelements.show();
}

Assanka.wp.toggleFTLiveTab = function(islive) {
	if (islive) {
		Assanka.$("#lnknavml").css({width:((Assanka.$("#lnknavml a").hasClass("on")) ? '7.25em' : '6.95em')}).addClass("live");
		var livetaburl = (Assanka.cdnhost?Assanka.cdnhost:'')+'/marketslive/lib/img/livetab.gif';
		Assanka.$("#lnkmarketslive").attr("href", "/marketslive/?inprogress=1").html("Markets<img src=\""+livetaburl+"\" /><i></i>");
	} else {
		Assanka.$("#lnknavml").css({width:'6.6em'}).removeClass("live");
		Assanka.$("#lnkmarketslive").attr("href", "/marketslive").html("Markets Live<i></i>");
	}
}

Assanka.wp = Assanka.wp || {};

Assanka.wp.expandPost = function(event) {

	// Ensure we have the event, loading the link normally if we don't
	if (!event) event = window.event;
	if (!event) return true;

	// Try to retrieve the clicked element, and if we can't get it load the link normally
	var linkel = event.target ? event.target : event.srcElement;
	if (!linkel.parentNode) return true;

	var divel = linkel.parentNode.parentNode;
	var postid = linkel.id.substr(10);

	// If full post element already exists in the document, simply display it and hide the abstract
	if (Assanka.$('#post'+postid+'full').length && !Assanka.$('#post'+postid+'full').hasClass('moreerror')) {
		var origheight = Assanka.$('#post'+postid+'stub').height() + 20;
		var targetheight = Assanka.$('#post'+postid+'full').height();
		Assanka.$('#post'+postid+'stub').hide();
		Assanka.$('#post'+postid+'full').height(origheight).show().animate({height:targetheight}, 500, "swing", function() { Assanka.$(this).css("height", ""); });
		return false;
	}

	// Otherwise, fetch the full post
	Assanka.$('#post'+postid+'full').remove();
	Assanka.$('#post'+postid+'more').addClass('working');
	var getposturl = Assanka.wp.pluginsdir+"/expandposts/getpost/"+postid;
	if (Assanka.$(linkel).hasClass('newcontent')) getposturl += '?updatedcontent=1';
	Assanka.$.getJSON(getposturl, function(data) {
		Assanka.$("#post"+postid+"more").hide().removeClass('working');
		if (!data.fullpost) return location.href=Assanka.$('#post-'+postid+' h2 a').attr('href');

		Assanka.$('#post'+postid+'stub').after("<div id='post"+postid+"full' class='avpoststub' style='hidden'>"+data.fullpost+"</div>");
		var origheight = Assanka.$('#post'+postid+'stub').height() + 20;
		var targetheight = Assanka.$('#post'+postid+'full').height();
		Assanka.$('#post'+postid+'stub').hide();
		Assanka.$('#post'+postid+'full').height(origheight).show().animate({height:targetheight}, 500, "swing", function() { Assanka.$(this).css("height", ""); });

		// Use Google Analytics to track the post view
		if (data.trackingurl) {
			try {
				pageTracker._trackPageview(data.trackingurl);
			} catch(err) {}
		}
		
		// Active any "Clip this" links
		Assanka.wp.processClipThis();
	});
	return false;
}

// Collapse a full post back to its abstract
Assanka.wp.collapsePost = function(postid) {

	var targetheight = Assanka.$('#post'+postid+'stub').height() + 5;

	Assanka.$('#post'+postid+'full').animate({height:targetheight}, 500, "swing", function() {
		Assanka.$('#post'+postid+'full').hide().css("height", "");
		Assanka.$('#post'+postid+'stub').show();
		Assanka.$("#post"+postid+"more").show();	
	});
}

// Display a "light box"
Assanka.wp.showLightBox = function(lightboxcontentelementid, anchorelement, classname, title, width) {

	// Set default classname
	if (typeof(classname) == "undefined") classname = "";

	// Set lightbox HTML
	var newel = Assanka.$('<div class="alphavillelightbox '+classname+'" style="width:'+width+'px"><div class="lightboxinner"><div class="lightboxheader"><span style="float:left;">'+title+'</span><a style="float:right;" href="javascript:void(0)" onclick="Assanka.$(this).parents(\'.alphavillelightbox\').fadeOut(250, function() { Assanka.$(this).remove()});" class="alphavillelightboxhidebutton">Close</a></div>'+Assanka.$('#'+lightboxcontentelementid).html()+'</div></div>').hide();

	// Add lightbox to page
	Assanka.$("body").append(newel);

	// Set position of lightbox, so that the lightbox lines up with the
	// anchor element vertically and is centered horizontally on the page
	// (has to be done after the lightbox is added to the page so that the width() and height() are nonzero)
	newel.css({"position":"absolute", "top":((parseInt(anchorelement.offset().top) - newel.outerHeight()) + anchorelement.outerHeight())+"px", "left":((Assanka.$(window).width() / 2) - (newel.width() / 2))+"px"});

	// Show lightbox
	Assanka.$(newel).fadeIn(250);
}

// Check for JSON errors and show an alert to the user.
Assanka.wp.checkDataForError = function(data) {
	if (data.error) {
		alert(data.error+"\n\nThere has been a fault.  We apoogise for the inconvenience.  If the problem persists, please contact help@ft.com");
		return true;
	}

	return false;
}

// Provide support collapsing and expanding the popular posts list
Assanka.wp.expandPopularPosts = function() {
	Assanka.$('#popularpostslist .contentexpander a').text('Show fewer').attr('href', 'javascript:Assanka.wp.collapsePopularPosts()');
	Assanka.$('#popularpostslist .collapsed').slideDown(200);
}
Assanka.wp.collapsePopularPosts = function() {
	Assanka.$('#popularpostslist .contentexpander a').text('Show more').attr('href', 'javascript:Assanka.wp.expandPopularPosts()');
	Assanka.$('#popularpostslist .collapsed').slideUp(200);
}

// And the same for collapsing and expanding the most commented posts list
Assanka.wp.expandMostCommentedPosts = function() {
	Assanka.$('#mostcommentedlist .contentexpander a').text('Show fewer').attr('href', 'javascript:Assanka.wp.collapseMostCommentedPosts()');
	Assanka.$('#mostcommentedlist .collapsed').slideDown(200);
}
Assanka.wp.collapseMostCommentedPosts = function() {
	Assanka.$('#mostcommentedlist .contentexpander a').text('Show more').attr('href', 'javascript:Assanka.wp.expandMostCommentedPosts()');
	Assanka.$('#mostcommentedlist .collapsed').slideUp(200);
}

// Provide support for the AJAX calendar plugin loading
Assanka.wp.calendarNav = function(year, month, usefull) {
	Assanka.$("#ajaxcalendarwidgetcontainer").addClass("working");
	Assanka.$.get(Assanka.wp.pluginsdir + '/ajax-calendar2/ajax.php?full=' + usefull + '&month=' + month + '&year=' + year, function(data, textStatus) {
		Assanka.$("#ajaxcalendarwidget").html(data);
		Assanka.$("#ajaxcalendarwidgetcontainer").removeClass("working");
	}, "text");

	return false;
}

// Provide support for "Clip this" links, both initially on-page in multiple locations and dynamically loaded
Assanka.wp.processClipThis = function() {
	for (var clipthisid in Assanka.clipthisitems) {
		if (typeof(Assanka.clipthisitems[clipthisid]) != "object") continue;
		var clipdetails = Assanka.clipthisitems[clipthisid];
		var scriptlink = 'http://clippings.ft.com/clipthis/js?url='+clipdetails.url+'&title='+clipdetails.title+'&note='+clipdetails.note+'&tags='+clipdetails.tags+'&datepublished='+clipdetails.datepublished+'&containerid=clipthis'+clipthisid+'&clipthisdisplay='+encodeURIComponent(Assanka.wp.cdnhost+Assanka.wp.templatedir+'/images/postactions/clipthis.png')+'&clippeddisplay='+encodeURIComponent(Assanka.wp.cdnhost+Assanka.wp.templatedir+'/images/postactions/clipped.png');
		Assanka.$.getScript(scriptlink);
		delete(Assanka.clipthisitems[clipthisid]);
	}
}

Assanka.wp.processMeteorEvent = {};

// Process received inferno messages - eval the data, then process via the correct event type.
// Inferno methods are redirected for use within this class.
Assanka.wp.processMeteorEvent.receive = function(msg) {
	eval("var data = "+decodeURIComponent(msg));
	if (data.hf == 'inferno') data.hf = 'Assanka.wp.processMeteorEvent.inferno';
	if (data.hf == 'mlstart') data.hf = 'Assanka.wp.processMeteorEvent.mlstart';
	if (data.hf == 'mlend') data.hf = 'Assanka.wp.processMeteorEvent.mlend';
	eval(data.hf+"(data)");
}

// Process new post events
Assanka.wp.processMeteorEvent.insertPost = function(data) {

	// Skip posts already present on the page
	if (data.dupcheck && Assanka.$('#'+data.dupcheck).length) return;

	// Extract the post content
	var postcontent = decodeURIComponent(data.content);
	if (!postcontent) return;

	// Append or prepend to the target element as appropriate
	if (data.mode == 'start') {
		Assanka.$(postcontent).prependTo('#'+data.element).hide().slideDown(function() { Assanka.$(this).css("height", "auto") });
	} else if (data.mode=='end') {
		Assanka.$(postcontent).appendTo('#'+data.element).hide().slideDown(function() { Assanka.$(this).css("height", "auto") });
	}
}

// Process post deletions
Assanka.wp.processMeteorEvent.deletePost = function(data) {
	Assanka.$('#'+data.id).remove();
}

// Inform Inferno about its own events
Assanka.wp.processMeteorEvent.inferno = function(data){
	if (!Inferno) return false;

	// Inform Inferno about deletions
	if (data.mode == 'remove') {
		Inferno.dom(false, 'inferno-item'+data.id, false, 'remove');

	// Inform Inferno about insertions
	} else if (!Assanka.$('#inferno-item'+data.id).length) {
		Inferno.dom(decodeURIComponent(data.html), 'inferno-commentlist', 'inferno-item'+data.id, data.mode, data.sortindex);

		// Update moderation options if appropriate
		Inferno.showHideModOpts();
		Inferno.renumberComments();
	}
}

// Deal with Markets Live start and end notifications
Assanka.wp.processMeteorEvent.mlstart = function(data){
	Assanka.wp.toggleFTLiveTab(true);
}
Assanka.wp.processMeteorEvent.mlend = function(data){
	Assanka.wp.toggleFTLiveTab(false);
}
