/* 
	something we need to do
*/
google.load('search', '1');
var ETVTB = {
	firstLoad: true,
	loginStatus: null,
	current: false,
	popupContent: false,
	root: false,
	popup: false,
	rootURL: 'http://www.eurovision.tv/toolbar/',
	myURL: 'https://www.eurovisionfamily.tv/toolbar/',
	executing: false,
	store: {},
	cache: {

	}
};
(function($$, $) {
/** 
  * START 
**/


$$.loadScript = function(url, callback, params) {
	var time = (new Date()).getTime()/1000;
	var cacheParam = time - (time%15);
	if (typeof(params) == 'undefined') {
		params = {};
	}

	params._rt = cacheParam;

	$.ajax({
		url: url,
		type: 'GET',
		dataType: 'script',
		success: callback,
		data: params,
		cache: true
	});
}

$$.add_css = function(css_content) {
	var head = document.getElementsByTagName('head')[0];
	var style = document.createElement('style');
	style.type = 'text/css';

	if(style.styleSheet) {
		style.styleSheet.cssText = css_content;
	} else {
		rules = document.createTextNode(css_content);
		style.appendChild(rules);
	}
	head.appendChild(style);
};

$$.use_login_status = function() {
	if (this.loginStatus) {
		$('.etvtb-auth-false').hide();
		$('.etvtb-auth-true').show();
	} else {
		$('.etvtb-auth-true').hide();
		$('.etvtb-auth-false').show();
	}
};
$$.set_login_status = function(status, update_cookie) {
	this.loginStatus = status;

	if (typeof(update_cookie) != 'undefined' && update_cookie === true) {
		/* keeping the status for 20 minutes isn't too long */
		var expires = new Date();
		expires.setTime(expires.getTime() + (20 * 60));
		$.cookie('etvtb-login-status', status, { path: '/', expires: expires});
	}

	this.use_login_status();
};

$$.done = function() {

	$$.current 	= $$.executing;
	$$.executing = false;
	$$.popUp($$.current);

	// always update auth-elements-visibility
	$$.use_login_status();

	// and then we start to align the popup
	var alignTo 	= $$.root.find('.tb li.' + $$.current);
	var alignToWidth= alignTo.outerWidth();
	var point 		= alignTo.offset().left;
	// get some position properties
	var tb			= $$.root.find('.tb');
	var tbOffset	= tb.offset();
	var tbWidth 	= tb.outerWidth();
	var rangeLeft	= tbOffset.left;
	var rangeRight	= tbWidth + tbOffset.left;

	fromLeft = alignTo.offset().left - $('.etvtb-popup-container').offset().left;

	$$.popupArrow.css('left', fromLeft + (alignToWidth/20));

	if ((point - rangeLeft) < (rangeRight - point)) {

		// arrow.css({right: 'auto', left: (alignToWidth/2) - arrow.width()/2});

		point = 0;
		$$.popup
			.css({right: 'auto', left: point})
			.addClass('etvtb-popup-atleft')
			.removeClass('etvtb-popup-atright');

	} else {

		var totalWidth = $$.root.outerWidth();
		point = alignTo.offset().left + alignToWidth;

		// arrow.css({left: 'auto', right: (alignToWidth/2)});

		  //right: $$.root.find('.tb').offset().left})

		$$.popup
			.css({left: 'auto',
				  right: 0})
			.removeClass('etvtb-popup-atleft')
			.addClass('etvtb-popup-atright');

	}
};

$$.init = function(data) {

	$('body').append(data.content);

	this.root			= $('.etvtb');
	this.popup 		  	= this.root.find('.etvtb-popup');
	this.popupContent 	= this.popup.find('.etvtb-popup-content');
	this.popupArrow		= this.root.find('.etvtb-popup-arrow').hide();
	this.animateSearchHeight = function() {
		var fitSize = $(window).height() - 120;
		$('.etvtb-search:visible').animate({height:fitSize});
	};
	this.updateMaxHeight = function() {
		var fitSize = $(window).height() - 120;
		if ($$.isIE6) {

			$$.root.find('.etvtb-pin').css('height', fitSize + 'px');

		} else {
			$$.root.find('.etvtb-pin').css('max-height', fitSize + 'px');
		}
	};

	$(window).resize(this.updateMaxHeight);
	this.updateMaxHeight();
	/**
	 * IE6 and lower don't support fixed position, let's use
	 * some silly javascript to help out
	*/
	if ($$.isIE6) {

		var rootElement = this.root.get(0);

		var updateTbPosition = function() {

			var fromTop		= 0 
				+ ( document.documentElement.clientHeight 
					? document.documentElement.clientHeight 
					: document.body.clientHeight ) 
				+ ( ignoreMe = document.documentElement.scrollTop 
					? document.documentElement.scrollTop 
					: document.body.scrollTop );

			fromTop = fromTop - 31;

			var props = {
				position: 'absolute',
				left: 0,
				top: fromTop
			};
			$$.root.css(props);
		}
		setInterval(updateTbPosition, 300);
	}

	$('.etvtb-buttons > li').not('li.link').click(function() {

		var $a = $(this).find('a');

		if ($$.executing) {
			return false;
		}

		/* the method we want to call is found has fragment */
		var method = $a.attr('href').split('#')[1];

		/* and if $$ one is already open, well - then close it */
		if (method == $$.current) {
			$$.popDown();
			$$.current = false;
			return false;
		}

		$$.executing = method;

		var run = function() {
			if (typeof($$.cache[method]) == 'undefined') {

				var hasAuthParent = $a.parents('.etvtb-auth-true');

				if (hasAuthParent.length == 1) {
					// links in an auth-container are passed through the auth-script
					$.getScript($$.myURL + 'auth.php?method=' + method, $$.done);

				} else {
					// the rest gets static js
					$$.loadScript($$.rootURL + method + ".js", $$.done);
				}

			} else {

				$$.response($$.cache[method]);
				$$.popUp(method);
				$$.done();

			}
		};

		if ($$.popup.is(':visible')) {
			$$.popDown(run);
		} else {
			run();
		}
		return false;
	});

	$('.etvtb-close').click(function() {
		 $$.popDown();
		 return false;
	});

	/**
	 * And last but not least - we regularly update the live update
	 * section
	 */
	var updateInterval = (60 * 1000) * 5;
	var runUpdate = function() {
		$$.loadScript($$.rootURL + 'updates.js', function() {
			/*
			 * and don't start again before loading
			**/
			setTimeout(runUpdate, updateInterval);
		});
	};

	setTimeout(runUpdate, updateInterval);
	this.use_login_status(this.loginStatus);
};

$$.updatePopupContent = function(data, replace) {

	if (typeof(replace) == 'undefined') {
		replace = false;
	}

	var pinClass;
	if (typeof(data) != 'undefined') {

		pinClass 	= 'etvtb-' + data.method;
		var pinContent	= this.popupContent.find('.' + pinClass);

		if (pinContent.length === 0) {
			pinContent	= $('<div class="etvtb-pin ' + pinClass + '"></div>');
			this.popupContent.append(pinContent);
			replace 	= true;
		}

		if (replace) {
			pinContent.html(data.content);
		}
	}

	/*
	 * Along the course of execution, this variable
	 * has turned into an indication whether or not
	 * the html content has been updated
	 */
	return replace;
};

$$.popUp = function(method) {

	this.popupContent.find('.etvtb-pin').not('.etvtb-' + method).hide();

	var pinClass 	= 'etvtb-' + method;
	this.root.find('.' + pinClass).show();

	$$.popupArrow.fadeIn('slow');
	this.popup.fadeIn('slow', function() {
		$$.popupArrow.show();
	});

	this.updateMaxHeight();
};

$$.popDown = function(afterDown) {

	var destroy = this.current + '_destroy';
	if ($.isFunction(this[destroy])) {
		this[destroy]();
	}

	$$.popupArrow.fadeOut();

	if ($.isFunction(afterDown)) {
		// because it's upside down, we slideUp to hide
		this.popup.fadeOut('fast', afterDown);
	} else {
		this.popup.fadeOut('slow', function() {
			$$.current = false;
		});
	}
};

$$.response = function(data) {

	var method = data.method;

	if ($.isFunction(this[method])) {

		return this[method](data);

	} else {

		this.cache[method] = data;
		this.updatePopupContent(data);

	}

};
$$.logout = function(data) {
	$$.set_login_status(false, true);
	var updated 		= this.updatePopupContent(data);
};
$$.login = function(data) {

	this.cache.login 	= data;
	var updated 		= this.updatePopupContent(data, true);

	if (!updated) {
		return false;
	}

	var forms 	= this.popupContent.find('.etvtb-login form').submit(function() {

		var form = $(this);
		form.ajaxSubmit({
			dataType: 'json',
			iframe: true,
			url: data.info.myEurovisionUrl + 'toolbar/login'
		});

		setTimeout(function() {
			$.getScript($$.myURL + 'login-status.php', function() {
				if ($$.loginStatus) {
				} else {
					form.resetForm().enable();
					alert('Username or password incorret');
					$$.popUp('login');
				}
			});
		}, 2000);

		$$.popDown();

		return false;
	});
};

$$.inbox = function(data) {
	// always update html here, and
	// never cache locally
	this.updatePopupContent(data, true);
};

/*
 * This is just a passthrough function really
 */
$$.send_link = function(data) {
	if (data.info.sent) {

		$$.executing = data.method;
		$$.updatePopupContent(data, true);
		$$.popUp(data.method);
		$$.done();

	} else {
		data.method = 'share';
		$$.share(data);
		$$.popUp(data.method);
	}
}

$$.share = function(data) {

	this.cache.share = data;

	var updated = this.updatePopupContent(data, true);

	if (!updated) {
		return false;
	}

	var info = {
	};

	if ($('link[rel=image_src]').length) {
		info.image = html_entity_decode($('link[rel=image_src]').attr('href')).trim();
	}
	if ($('meta[name=title]').length) {
		info.title = html_entity_decode($('meta[name=title]').attr('content')).trim();
	} else {
		info.title = $('title').text().split(/\s+\|\s+/)[0];
	}
	if ($('meta[name=description]').length) {
		info.description = html_entity_decode($('meta[name=description]').attr('content')).trim();
	}

	// don't accidentally throw dev- and stage- links around
	info.link = document.location.href.replace(/\/(dev|stage)\./, '/www.');
	// nor share with the #hash in the url
	info.link = info.link.split(/#/)[0];

	var baseUrl = 'http://api.addthis.com/oexchange/0.8/forward/';

	this.root.find('.etvtb-share-email').submit(function() {

		var params = $(this).serializeArray();
		params.push({name: 'Link', 	value: info.link});
		params.push({name: 'Title', value: info.title});
		jQuery.ajax({url: 'http://www.eurovisionfamily.tv/toolbar/send_link', 
					 data: params, 
					 method: 'get', 
					 dataType: 'script'
					 });

		$$.popDown();
		return false;
	});

	this.popupContent.find('.etvtb-share-networks a').click(function() {

		var service = $(this).attr('class').split(/-/)[1];

		this.target = '_blank';
		this.href 	= baseUrl + service + '/offer?username=eurovisiontv&url=' + escape(info.link);

		if (info.title) {
			this.href += '&title=' + escape(info.title);
		}

		if (info.image) {
			this.href += '&image=' + escape(info.image);
		}

		if (info.description) {
			this.href += '&description=' + escape(info.description);
		}

		return true;

	});
};

$$.search_destroy = function() {
	$(window).unbind('resize', this.animateSearchHeight);
};

$$.search = function(data) {

	this.cache.search = data;
	this.updatePopupContent(data);

	$(window).bind('resize', this.animateSearchHeight);
	this.animateSearchHeight();

	if (typeof(this.store.cseLoaded) == 'undefined') {
		var customSearchControl = new google.search.CustomSearchControl('partner-pub-1516068875743774:3lbs4v6otpx');
		customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
		var options = new google.search.DrawOptions();
		options.setSearchFormRoot('cse-search-form');
		customSearchControl.draw('cse', options);
	}
};

$$.updates = function(data) {

	/**
	 * DO NOT interfere
	 */
	if ($$.current && $$.current != 'updates') {
		return false;
	}

	if (typeof(this.store.seen_update_ids) == 'undefined') {
		var seen_ids	= $.cookie('etvtb-update-seen');
		if (typeof(seen_ids) == 'undefined' || seen_ids === null) {
			this.store.seen_update_ids = ['none'];
		} else {
			this.store.seen_update_ids = seen_ids.split(',');
		}
	}

	/**
	 * We don't cache updates
	 */
	var autoUpdated 	= this.updatePopupContent(data);
	var content			= $(data.content);
	var seenSelector	= '#' + this.store.seen_update_ids.join(',#');
	// go throught he content and find the unseen items
	var unseen			= content.find('.etvtb-li').not(seenSelector); 

	if (unseen.length > 0 && !autoUpdated) {
		this.root.find('.etvtb-updates ul.etvtb-ul').prepend(unseen);
	}

	for (var i = 0; i < unseen.length; i++) {
		var thisId = unseen.get(i).id;
		this.store.seen_update_ids.push(thisId);
	}

	// check if nothing is open, we're not already requesting somebody to open
	// we have some unseen items AND it's not the initial load, making sure
	// it only popups for people who have been on the page for a while
	if (!$$.current && (!$$.executing && unseen.length > 0) && !$$.firstLoad) {
		this.executing 	= 'updates';
		this.done();
	}
	$$.firstLoad = false;

	/**
	 * And at the end, set the cookie - always if we have been updating
	 * valid for another 48 hours
	 */
	var expires = new Date();
	expires.setTime(expires.getTime() + (60 * 60 * 48 * 1000));
	$.cookie('etvtb-update-seen', this.store.seen_update_ids.join(','), { path: '/', expires: expires});
};

$(document).ready(function($) {
	/**
	 * We start by checking if we need to evaluate the login
	 * login status
	 */
	var status = $.cookie('etvtb-login-status');
	if (status === null) {
		$.getScript($$.myURL + 'login-status.php');
	} else {
		$$.set_login_status(status, false);
	}
	$$.loadScript($$.rootURL + 'init.js');
	$$.isIE6 = $.browser.msie && $.browser.version.substr(0,1)<7;
	$$.isIE7 = !$$.isIE6 && $.browser.msie && $.browser.version.substr(0,1)<8;
});


/** 
  * END
**/
})(ETVTB, jQuery);

