﻿var _region = null;
/*
tracking categories:
	- share
	- popunder
*/

var track = function(category, action, label)
{

	if(typeof pageTracker == "undefined")
	{
		return;
	}

	return pageTracker._trackEvent(category, action, label);
}

var trackPopUnder = function(identifier, label)
{
	track("popunder", identifier, label);
}

var trackShare = function(service)
{
	var b = track("share", service, undefined);
}

var shared = function(evt)
{
	if (evt.type == 'addthis.menu.share')
	{
		//trackShare(evt.data.service);
	}
};

var yourWayMobile = function(obj)
{
	var r = $el("regionChoice");

	if(r != null)
	{
		r.onchange = function()
		{
			$el("regionForm").submit();
		}
		$el("submitRegion").style.display = "none";
}

var r = $el("dayChoice");

if (r != null) {
    r.onchange = function() {
        $el("dayForm").submit();
    }
    $el("submitDay").style.display = "none";
}
	

	if(typeof replaceSubmits !== "undefined")
	{
		var vote = $el("likeSubmit");

		if(vote != null)
		{
			replaceSubmitElement(vote, "vote-style");
			setupRemoteVote({region: obj.region, section:obj.section});
		}

		replaceSubmits(null);
	}

	addExternalTargets();

	addDropShadows();

	if(typeof hook !== "undefined")
	{
		hook(obj.section);
	}
}

var yourWay = function(obj)
{

	_region = obj.region;

	videoEmbed();

	yourWayMobile(obj);

	setupShareLinks();

	replaceLinks(null);

	styleUpSelects(null);

	hangEllipses();

	$('#follow-links').supersleight();
	$('.paging').supersleight();
	$('#topPanel h1').supersleight();
	$('.tagline').supersleight();
	$('.sponsors').supersleight();

	setupFloatingForm({region: obj.region, section:obj.section});
	setupFloatingView({region: obj.region, section:obj.section});

	$("body.browse .addthis_toolbox a").empty();

};

var hangEllipses = function()
{
	hangSpecificEllipses("#entryListing div.browse-details h3");
	hangSpecificEllipses("#entryListing div.browse-details div.name-location");
}

var hangSpecificEllipses = function(id)
{
	$(id).each(function(){
		var t = $(this).text();
		var l = t.length;

		$(this).html("<span>" + t + "</span>");
		$(this).attr("title", t);

		var span = $(this).children("span");

		if(span.width() > span.parent().width())
		{
			// perform truncate here
			while(span.width() > span.parent().width())
			{
				t = t.substr(0, l);
				span.html(t + "&hellip;");
				l--;
			}
		}

	});
}

var videoEmbed = function()
{
	$("#itemVideo").append("<div id=\"closeVideoPlayer\"><a href=\"javascript:void(0)\">" + $so("TextLinkClose") + "</a></div>");
	$("#closeVideoPlayer").hide();

	$("#itemVideo").append("<div id=\"videoPlayer\" />");

	$("#videoDownloads a").each(function(){
		$(this).click(function(){
			var mt = $(this).attr("rel");
			var url = $(this).attr("href");

			$("#videoPlayer").html("<a href=\"" + url + "\" />");
			$("#videoPlayer a").media({ width: videoWidth, height: videoHeight, autoplay: true });
			$("#videoDownloads").hide();
			$("#itemVideo h2").hide();
			$("#closeVideoPlayer").show();
			return false;
		});
	});

	$("#closeVideoPlayer a").click(function()
	{
		$("#closeVideoPlayer").hide();
		$("#videoPlayer").html("");
		$("#videoDownloads").show();
		$("#itemVideo h2").show();
	});

}

var hideVideoEmbed = function()
{
	
}

var sifrReplace = function()
{
	var strFlashPath = "/Content/Flash/sifr-optima-en-GB.swf";

	sIFR.setup();
	sIFR.replaceElement(named({sSelector:"h1", sFlashSrc:strFlashPath, sColor:"#3B3D3C", sLinkColor:"#3B3D3C", sHoverColor:"#3B3D3C"}));

}

var setupShareLinks = function(url)
{

	$("#entryListing div.browse").each(function(){
		var a, s, sa;
		var href;

		a = $(this).find("a.view-details-link");
		s = $(this).find("div.share_link");
		sa = s.find("a");

		href = a.attr("href");

		s.addClass("addthis_toolbox addthis_default_style");

		sa.click(function() {
			return addthis_sendto();
		}).hover(
		function() {
			return addthis_open(this, '', href, '[TITLE]');
		},
		function() {
			addthis_close();
		});

	});

	addSingleShares("body.view-item div.share_link", "body.view-item div.share_link a", url);
	addSingleShares(".drop-shadow-content div.share_link", ".drop-shadow-content div.share_link a", url);

}

var addSingleShares = function(a,b,u)
{

	$(a).addClass("addthis_toolbox addthis_default_style");

	$(b).click(function() {
		return addthis_sendto();
	}).hover(
	function() {
		if(typeof u == "undefined")
		{
			u = "[URL]";
		}
		return addthis_open(this, '', u, '[TITLE]');
	},
	function() {
		addthis_close();
	});
}

var setupFloatingVote = function(obj) {
	$(document).ready(function() {

		$(".like-link a").each(function() {
			var count = $(this).attr("title");
			var text = $(this).text() + "";

			$(this).html("<span><div>" + text + "</div><div class=\"count\">" + count + "</div></span>");
			$(this).addClass("button-link-replaced");

		});

	});

	if (FloatingVoter != null && typeof FloatingVoter === "object") {
		FloatingVoter.init({ region: obj.region, section: obj.section });
	}

}

var addDropShadows = function()
{
	if(typeof DropShadows === "object")
	{
		DropShadows.init();
	}
}

var styleUpSelects = function(root)
{

	if(root == null)
	{
		root = document;
	}

	if(typeof StyledSelects === "object")
	{
		StyledSelects.init(root);
	}
}

var addExternalTargets = function()
{
	var a = document.getElementsByTagName("a");

	for(var i = 0; i < a.length; i++)
	{
		if(a[i].rel.toLowerCase() == "external")
		{
			a[i].target = "_blank";
		}
	}

}

var setupRemoteVote = function(obj)
{
	if(typeof RemoteVote === "object")
	{
		RemoteVote.init(obj, null);
	}
}

var blockForms = function(isTerms) {
    var id = "formBlock";

    if (isTerms) id = "termsBlock";

    $("#" + id).remove();
    $("body").append("<div id=\"" + id + "\"><span /></div>");

    $("#" + id).css({ 'width': $(window).width(), 'height': $(window).height() });
}

var unBlockForms = function(isTerms)
{
	var id = "formBlock";

	if(isTerms)
	{
		id = "termsBlock";
	}

	$("#" + id).remove();
}

var setupFloatingView = function(obj)
{
	if(typeof OverlayView === "object")
	{
		OverlayView.init(obj);
	}
}

var setupFloatingForm = function(obj)
{
	setupFloatingFormById("sectionMenuEnterTop", obj);
	setupFloatingFormById("sectionMenuEnterBottom", obj);
	setupFloatingFormById("topPanelEnter", obj);
}

var setupFloatingFormById = function(id, obj)
{
	var a = $el(id);

	var f = $el("uploadForm");

	// the form is present, so don't recreate
	if(f != null)
	{
		return;
	}

	if(a != null)
	{

		a.onclick = function()
		{
			OverlayUpload.launch();
		}

		a.href = "javascript:void(0)";
		if(typeof OverlayUpload === "object")
		{
			OverlayUpload.init(obj);
		}
	}
}

var centreScreen = function(id)
{
	
}

var addCloseToPopup = function(id, func)
{
	$(id + " .popUpClose").remove();

	$(id).append("<div class=\"popUpClose\"><a href=\"javascript:void(0)\">" + $so("TextLinkClose") + "</a></div>");

	$(id + " .popUpClose a").click(function(){
		func();
	});

}

var replacementLink = function(value, extra)
{
	var a = ne("a");

	a.appendChild(tn(value));

	a.className = "button-link";

	if(extra == "back-style")
	{
		a.className = "button-link-back";
	}

	if(extra != null)
	{
		a.className += " " + extra;
	}

	a.href = "javascript:void(0)";

	return a;

}

var replaceLinks = function(root)
{

	if(root == null)
	{
		root = document;
	}

	var a = root.getElementsByTagName("a");
	var i = 0;

	for(i = 0; i < a.length; i++)
	{
		if(cls(a[i].className, "button-link") || cls(a[i].className, "button-link-back"))
		{
			var suffix = "";
			
			if(cls(a[i].className, "button-link-back"))
			{
				suffix = "-back";
			}
			
			var classes = a[i].className.replace("button-link" + suffix, "");
			var t = tn(a[i].firstChild.nodeValue);
			a[i].className = "button-link-replaced" + suffix + " " + classes;
			a[i].removeChild(a[i].firstChild);
			a[i].appendChild(ne("span"));
			a[i].firstChild.appendChild(t);
			a[i]._suffix = suffix;
			a[i].onmouseover = function()
			{
				addClass(this, "button-link-replaced" + this._suffix + "-active");
			}
			a[i].onmouseout = function()
			{
				removeClass(this, "button-link-replaced" + this._suffix + "-active");
			}
		}
	}

};

var addLightbox = function(selector) {
	$(selector).click(function() {
		blockForms(true);
		$("body").append("<div id=\"popUpImage\"><span /></div>");
		$("#popUpImage").show();

		$("#popUpImage").html("<img id=\"lgeImage\" />");
		$("#lgeImage").load(function() {
			if ($(this).height() > $(window).height() - 20 || $(this).width() > $(window).width() - 20) {
				var w, h, s;

				h = $(window).height() - 40;
				w = $(window).width() - 40;

				if ($(this).width() * h > $(this).height() * w) {
					s = w / $(this).width();
				}
				else {
					s = h / $(this).height();
				}

				w = $(this).width() * s;
				h = $(this).height() * s;

				$(this).width(Math.round(w));
				$(this).height(Math.round(h));

			}

			$("#termsBlock").click(function() {
				$("#popUpImage").remove();
				unBlockForms(true);
			});
			$("#popUpImage img").click(function() {
				$("#popUpImage").remove();
				unBlockForms(true);
			});

			$("#popUpImage").center();
			$("#popUpImage").show();
		})

		$("#lgeImage").attr("src", $(this).attr("href"));

		return false;
	});
}

var addClass = function(e, cls)
{
	e.className += " " + cls;
}

var removeClass = function(e, cls)
{
	var c = "";
	var a = e.className.split(" ");
	var i;

	for(i = 0; i < a.length; i++)
	{
		if(a[i] != cls)
		{
			c = c + " " + a[i];
		}
	}

	c = ltrim(c);

	e.className = c;

}

var ltrim = function(s)
{
	while(s.substr(0, 1) == " ")
	{
		s = s.substr(1);
	}
	return s;
}

var _waitHandle = null;

var waitMessage = function(msg)
{

	killWaitMessage();

	$("body").append("<div id=\"waitMessage\"><div id=\"waitMessageHolder\">" + $so("TextRemoteWaitMessage") + "</div></div>");

	DropShadows.addShadow($el("waitMessage"), "drop-shadow-message");

	$("#waitMessage").hide();

	_waitHandle = setTimeout("showWaitMessage()", 1000);

}

var showWaitMessage = function()
{
	clearTimeout(_waitHandle);
	_waitHandle = null;

	jQuery('#waitMessage').center();

	$('#waitMessage').show();
}

var killWaitMessage = function()
{
	if(_waitHandle != null)
	{
		clearTimeout(_waitHandle);
		_waitHandle = null;
	}

	$("#waitMessage").remove();

}

var generalError = function(msg, killBlock)
{
	var combined = "";
	hideGeneralError();

	if(typeof msg == "string")
	{
		combined = "<div>"+msg+"</div>";
	}

	if(typeof msg == "object")
	{
		if(msg.length > 0)
		{
			combined = "<ul>";
			for(var i = 0; i < msg.length; i++)
			{
				combined += "<li>" + msg[i] + "</li>";
			}
			combined += "</ul>";
		}
		else
		{
			combined = "<div>"+msg+"</div>";
		}
	}

	$("body").append("<div id=\"generalError\"><div id=\"generalErrorContainer\"><h2>" + $so("HeadingGeneralNetworkIssue") + "</h2>" + combined + "</div></div>");

	DropShadows.addShadow($el("generalError"), "drop-shadow-general-error");

	if(killBlock)
	{
		addCloseToPopup("#generalError", function(){
			hideGeneralError();
			unBlockForms(false);
		});
	}
	else
	{
		addCloseToPopup("#generalError", hideGeneralError);
	}

	jQuery('#generalError').center();

}

var hideGeneralError = function()
{
	$("#generalError").remove();
}

var checkFlash = function(){

		var v = document.createElement('video');

		alert(typeof v);
		alert(!!v.canPlayType)
		alert('poster' in v);

}
