
// Add event listeners to the Most Read tabs
// array can contain object references, element ids, or both
var tabsIds = ["most-read", "most-commented", "most-emailed"];
function swapMostReadTabs(e) { 
	// first turn everything to the off state
	for (x=0; x<tabsIds.length; x++) {
		if (document.getElementById(tabsIds[x])) {
			t = document.getElementById(tabsIds[x]);
			t.className = "";
			cId = tabsIds[x] + "-content";
			c = document.getElementById(cId);
			c.className = "";
		}
	}
	// light up the tab
	this.className = "on";
	// open the div
	cId = this.id + "-content";
	document.getElementById(cId).className = "on";
}
YAHOO.util.Event.addListener(tabsIds, "click", swapMostReadTabs);

// Clear the search box on focus if it's showing default content
function clearSearchBox(e) {
	if (this.value == "Search") {
		this.value = "";
	}
}
YAHOO.util.Event.addListener("searchField", "focus", clearSearchBox);

// Reset default text if the search box wasn't used
function resetSearchBox(e) {
	if (this.value == "") {
		this.value = "Search";
	}
}
YAHOO.util.Event.addListener("searchField", "blur", resetSearchBox);

// Toggle drop-down when 'share' is selected
function toggleShareOptions(e) {
	myId = this.id + "-menu";
	t = document.getElementById(myId);
	if (t.style.display == "block") {
		t.style.display = "none";
	} else {
		t.style.display = "block";
	}
}
YAHOO.util.Event.addListener("share-this1", "click", toggleShareOptions);
YAHOO.util.Event.addListener("share-this2", "click", toggleShareOptions);

// Show tool tips for fields
function toggleTooltips(e, showhide) {
	myId = "tip-" + this.id;
	t = document.getElementById(myId);
	if (showhide == "show") {
		t.style.display = "block";
	} else {
		t.style.display = "none";
	}
}

function toggleRssOpts(e, showhide) {
	if (showhide == "donothing") {
		if(e.stopPropagation) {
			e.stopPropagation();
		} else {
			e.cancelBubble = true;	
		}
	}
	if (showhide == "show") {
		YAHOO.util.Event.preventDefault(e); 

		// Stick in the right values for links
		if (this.innerText) {
			document.getElementById("rss-subject").innerHTML = this.innerText;
		} else {
			document.getElementById("rss-subject").innerHTML = this.textContent;
		}
		document.getElementById("rss-target-bloglines").href = "http://www.bloglines.com/sub/" + escape(this.href);
		document.getElementById("rss-target-google").href = "http://fusion.google.com/add?feedurl=" + escape(this.href);
		document.getElementById("rss-target-myaol").href = "http://favorites.my.aol.com/ffclient/AddFeed?url=" + escape(this.href);
		document.getElementById("rss-target-myyahoo").href = "http://add.my.yahoo.com/rss?url=" + escape(this.href);
		document.getElementById("rss-target-netvibes").href = "http://www.netvibes.com/subscribe.php?url=" + escape(this.href);
		document.getElementById("rss-target-newsgator").href = "http://www.newsgator.com/ngs/subscriber/subext.aspx?url=" + escape(this.href);
		document.getElementById("rss-target-pageflakes").href = "http://www.pageflakes.com/subscribe.aspx?url=" + escape(this.href);
		document.getElementById("rss-target-technorati").href = "http://technorati.com/faves?sub=favthis&add=" + escape(this.href);	
		document.getElementById("rss-target-direct").href = this.href;
		
		// Then attach it to the right place
		subs = document.getElementById("rss-subscriptions");
		this.parentNode.insertBefore(subs,this);
	}
	if (showhide == "hide") {
		document.getElementById("rss-subscriptions-parked").appendChild(document.getElementById("rss-subscriptions"));
	}
}

// Enlarge the comment box on focus
function enlargeComments(e) {
	this.style.height = "150px";
}
YAHOO.util.Event.addListener("add-your-comment-field", "focus", enlargeComments);

// Reset the comment box
function shrinkComments(e) {
	if (this.value == "")
	this.style.height = "70px";
}
YAHOO.util.Event.addListener("add-your-comment-field", "blur", shrinkComments);

// Set focus in the comments field
function focusComments(e) {
	document.getElementById("add-your-comment-field").focus();
	return false;
}
YAHOO.util.Event.addListener("add-comments-link", "click", focusComments);

// Show the 'all comments' div
function readAllComments(e) {
	document.getElementById("additional-comments").style.display = "block";
	document.getElementById("read-all-comments-link").style.display = "none";
	document.getElementById("read-fewer-comments-link").style.display = "block";
	return false;
}
YAHOO.util.Event.addListener("read-all-comments-link", "click", readAllComments);

// Hide the 'all comments' div
function readFewerComments(e) {
	document.getElementById("additional-comments").style.display = "none";
	document.getElementById("read-all-comments-link").style.display = "block";
	document.getElementById("read-fewer-comments-link").style.display = "none";
	return false;
}
YAHOO.util.Event.addListener("read-fewer-comments-link", "click", readFewerComments);

// Photo / video navigation
var picIds = ["pic0","pic1","pic2","pic3","pic4","pic5","pic6","pic7","pic8","pic9","pic10","pic11","pic12","pic13","pic14","pic15","pic16","pic17","pic18","pic19","pic20"];
var currentPic = 0;
var maxPics = 20;
function photoNavigation(e, dir) {
	// Clear all 'on' states
	for(x=0;x<picIds.length;x++) {
		if(document.getElementById(picIds[x])) { document.getElementById(picIds[x]).className = '';	}
		p = picIds[x] + '-pic';
		if(document.getElementById(p)) { document.getElementById(p).className = ''; }
		c = picIds[x] + '-cap';
		if(document.getElementById(c)) { document.getElementById(c).className = ''; }
	}
	// Set the 'on' state for this
	if (!dir) {
		myId = this.id;
	} else {
		if (dir == "back" && currentPic>0) currentPic --;
		if (dir == "next") { 
			test = (currentPic*1) + 1;  // force to numeric before adding
			if (document.getElementById("pic" + test)) {
				currentPic ++;
			}
		}
		myId = "pic" + currentPic;
	}
	document.getElementById(myId).className = 'on';
	myP = myId + '-pic';
	if (document.getElementById(myP)) {	document.getElementById(myP).className = 'on'; }
	myC = myId + '-cap';
	if (document.getElementById(myC)) {	document.getElementById(myC).className = 'on'; }
	currentPic = myId.match(/\d+/g);
	return false;
}
YAHOO.util.Event.addListener(picIds, "click", photoNavigation);
YAHOO.util.Event.addListener("pic-back", "click", photoNavigation, "back");
YAHOO.util.Event.addListener("pic-next", "click", photoNavigation, "next");


// Code to drive the breaking news ticker
// Requires a Javascript array of headlines
// to be available in the page

var bmt = document.getElementById("breaking-message-text");
var bmc = document.getElementById("breaking-message-clicker");
var bnCurrent = -1;
var bnCharacter = 0;
var bnInterval = "";

function initBreakingNews() {
	if(bnHeadlines.length) {
		if(bnCurrent >= (bnHeadlines.length-1)) {
		  bnCurrent = 0;
		} else {
		  bnCurrent ++;
		}
		bmt.innerHTML = "";
		bnCharacter = 0;
		bnInterval = setInterval("updateBreakingNews()",100);
		if (bnLinks[bnCurrent]) {
			bmc.style.cursor = "pointer";
		} else {
			bmc.style.cursor = "auto";
		}
	}
}

function updateBreakingNews() {
	var myChar = bnHeadlines[bnCurrent].charAt(bnCharacter);
	if (myChar) {
		bmt.innerHTML = "_" + bmt.innerHTML.substring(1,bmt.innerHTML.length) + myChar;	
	} else {
		clearInterval(bnInterval);
		setTimeout("initBreakingNews()",3000);
		return false;
	}
	bnCharacter ++;
	// Ensure that the last character is alpha-numeric
	if (myChar.search(/[a-z|A-Z|0-9]/) == -1) {
		if (bnCharacter < bnHeadlines[bnCurrent].length) {
			updateBreakingNews();
		} else {
			bmt.innerHTML = bmt.innerHTML.substring(0,bmt.innerHTML.length-1);
		}
	}
	return true;
}
YAHOO.util.Event.onDOMReady(initBreakingNews); 

function bnHandleClick() {
	var bnc = bnLinks[bnCurrent];
	if (bnc) {
		window.location.href = bnc;
	} 
}
YAHOO.util.Event.addListener("breaking-message-clicker", "click", bnHandleClick);

function iphoneShowNav() {
	document.getElementById("show-navigation").style.display = "none";
	document.getElementById("topnav").style.display = "block";
	document.getElementById("subnav").style.display = "block";
}
YAHOO.util.Event.addListener("show-navigation", "click", iphoneShowNav);

function showPollResults() {
	// This is currently a demo function.
	// Will be replaced by an AJAX call or whatever 
	// the Polopoly polls module supports
	document.getElementById("poll-1-bar").style.width = "150px";
	document.getElementById("poll-2-bar").style.width = "90px";
	document.getElementById("poll-3-bar").style.width = "50px";
	document.getElementById("poll-1-score").innerHTML = "62%";
	document.getElementById("poll-2-score").innerHTML = "26%";
	document.getElementById("poll-3-score").innerHTML = "12%";
}
var pollDemoLinkIds = ["poll-1","poll-2","poll-3","poll-view-link"];
YAHOO.util.Event.addListener(pollDemoLinkIds, "click", showPollResults);

function toggleSitemap(e) {
	var t = document.getElementById("sitemap");
	var smAnim = new YAHOO.util.Anim('sitemap');   
	
	if (t.style.height && t.style.height != "0px") {
		smAnim.attributes.height = { to: 0 };   
		smAnim.duration = 0.5;   
		smAnim.method = YAHOO.util.Easing.easeOut;   
		smAnim.animate(); 
	} else {
		smAnim.attributes.height = { to: 320 };   
		smAnim.duration = 0.5;   
		smAnim.method = YAHOO.util.Easing.easeOut;   
		smAnim.animate(); 
	}
}
YAHOO.util.Event.addListener(["sitemap-link","sitemap-close"], "click", toggleSitemap);

function moveSitemap() {
	var element = document.getElementById("sitemap");
	var newParent = document.getElementById("sitemap-target");
	newParent.appendChild(element);
}
YAHOO.util.Event.onDOMReady(moveSitemap); 

// Begin Accessibility / Presentation Control Functions
// We create a cookie called 'settings' with sub-cookies (fontSize, etc)
// to store all user preferences.  Sub-cookies are stored to the YUI format.

function initCSSPrefs() {
	// Read the current cookie, then use the value to set certain preferences
	var paragraphFontSize = "12px";
	var quoteFontSize = "16px";
	var userFontSize = YAHOO.util.Cookie.getSub("settings", "fontSize");
	
	if (userFontSize == "larger") {
		paragraphFontSize = "14px";
		quoteFontSize = "18px";
	}
	if (userFontSize == "largest") {
		paragraphFontSize = "16px";
		quoteFontSize = "20px";
	}
	// Target: "div.article-body p"
	var articles = YAHOO.util.Dom.getElementsByClassName("article-body", "div");
	for (x=0; x<articles.length; x++) {
			var pars = articles[x].getElementsByTagName("p");
			for (y=0; y<pars.length; y++) {
				pars[y].style.fontSize = paragraphFontSize;	
			}
	}
	// Target: "div.comment-block p" and "div.comment-block cite" 
	var comments = YAHOO.util.Dom.getElementsByClassName("comment-block", "div");
	for (x=0; x<comments.length; x++) {
			var pars = comments[x].getElementsByTagName("p");
			for (y=0; y<pars.length; y++) {
				if (pars[y].className != "reply-to-this") pars[y].style.fontSize = paragraphFontSize;	
			}
			var cite = comments[x].getElementsByTagName("cite");
			for (y=0; y<cite.length; y++) {
				cite[y].style.fontSize = paragraphFontSize;	
			}
	}
	// Target: "div.big-quote blockquote" and "div.big-quote cite"
	var quotes = YAHOO.util.Dom.getElementsByClassName("big-quote", "div");
	for (x=0; x<quotes.length; x++) {
			var bq = quotes[x].getElementsByTagName("blockquote");
			for (y=0; y<bq.length; y++) {
				bq[y].style.fontSize = quoteFontSize;	
			}
			var cite = quotes[x].getElementsByTagName("cite");
			for (y=0; y<cite.length; y++) {
				cite[y].style.fontSize = paragraphFontSize;	
			}
	}
}
YAHOO.util.Event.onDOMReady(initCSSPrefs); 

function changeFontSize(e, direction) {
	var userFontSize = YAHOO.util.Cookie.getSub("settings", "fontSize");
	//alert ("in cfs. direction: " + direction + ". ufs: " + userFontSize);
	if (direction == "up") {
		if (userFontSize == "larger") userFontSize = "largest";
		if (!userFontSize || userFontSize == "normal") userFontSize = "larger";
	}
	if (direction == "down") {
		if (userFontSize == "larger") userFontSize = "normal";
		if (userFontSize == "largest") userFontSize = "larger";
	}
	YAHOO.util.Cookie.setSub("settings", "fontSize", userFontSize, { expires: new Date("January 1, 2025") }); 
	initCSSPrefs();
}
YAHOO.util.Event.addListener(["font-up","font-up-small"], "click", changeFontSize, "up");
YAHOO.util.Event.addListener(["font-down","font-down-small"], "click", changeFontSize, "down");


function showHideSkyscraper() {
  if(!document.getElementById('skyscraper')) return false;
  if(document.body.offsetWidth > 1246) {
    document.getElementById('skyscraper').style.display = "";
  } else {
    document.getElementById('skyscraper').style.display = "none";
  }
}
YAHOO.util.Event.onDOMReady(showHideSkyscraper); 
YAHOO.util.Event.addListener(window, "resize", showHideSkyscraper);

// Show yellow help tips
var regTips = ["realName","displayName","email","password","confirmPassword","location", "postcode"];
YAHOO.util.Event.addListener(regTips, "focus", toggleTooltips, "show");
YAHOO.util.Event.addListener(regTips, "blur", toggleTooltips, "hide");

// Auto-suggest code for location drop downs
var myLocationList = ["Aberfeldy", "Aberfoyle", "Aberlady", "Aberlour", "Aberuthven", "Abington", "Aboyne", "Airdrie", "Alexandria", "Alford", "Alloa", "Annan", "Anstruther", "Arbroath", "Ardrossan", "Armadale", "Arran", "Auchinleck", "Auchterarder", "Auchtermuchty", "Aviemore", "Ayr", "Ballater", "Balloch", "Banchory", "Banff", "Bargeddie", "Barrhead", "Bathgate", "Bearsden", "Beith", "Bellshill", "Berwick Upon Tweed", "Biggar", "Bishopbriggs", "Bishopton", "Blackburn (Aberdeenshire)", "Blackburn (West Lothian)", "Blackford", "Blairgowrie", "Blanefield", "Blantyre", "Bonhill", "Bonnybridge", "Bonnyrigg", "Bothwell", "Braemar", "Brechin", "Bridge of Allan", "Bridge of Weir", "Broughty Ferry", "Broxburn", "Buckhaven", "Buckie", "Burntisland", "Busby", "Bute", "Caithness", "Callander", "Cambuslang", "Campbeltown", "Carluke", "Carnoustie", "Carnwath", "Carradale", "Carstairs", "Castle Douglas", "Clackmannan", "Clarkston", "Clydebank", "Coatbridge", "Cockenzie", "Coldstream", "Coupar Angus", "Cowdenbeath", "Crianlarich", "Crieff", "Cromarty", "Crosshouse", "Cumbernauld", "Cumnock", "Cupar", "Dalgety Bay", "Dalkeith", "Dalmellington", "Dalry", "Darvel", "Denny", "Dingwall", "Dollar", "Dornoch", "Douglas", "Doune", "Drymen", "Dufftown", "Dumbarton", "Dumfries", "Dunbar", "Dunblane", "Dundee", "Dunfermline", "Dunkeld", "Dunlop", "Dunoon", "Dyce", "Eaglesham", "East Calder", "East Kilbride", "Edinburgh", "Elgin", "Erskine", "Eskbank", "Falkirk", "Faslane", "Fauldhouse", "Fochabers", "Forfar", "Forres", "Fort William", "Fraserburgh", "Gairloch", "Galashiels", "Garelochhead", "Gartcosh", "Gartmore", "Gatehouse of Fleet", "Girvan", "Glasgow", "Gleneagles", "Glengarnock", "Glenochil", "Glenrothes", "Golspie", "Gourock", "Grangemouth", "Grantown on Spey", "Greenloaning", "Greenock", "Gullane", "Haddington", "Halbeath", "Hamilton", "Harthill", "Hawick", "Helensburgh", "Hopeman", "Houston", "Huntly", "Inveraray", "Invergordon", "Inverkeithing", "Inverness", "Inverurie", "Irvine", "Islay", "Jedburgh", "Johnstone", "Keith", "Kelso", "Kemnay", "Kilbarchan", "Kilbirnie", "Killearn", "Kilmacolm", "Kilmarnock", "Kilmaurs", "Kilsyth", "Kilwinning", "Kincardine", "Kingussie", "Kinross", "Kirkcaldy", "Kirkcudbright", "Kirkintilloch", "Kirknewton", "Lanark", "Langholm", "Larbert", "Largs", "Larkhall", "Lasswade", "Laurencekirk", "Law", "Lennoxtown", "Lenzie", "Lesmahagow", "Leven", "Linlithgow", "Linwood", "Livingston", "Loanhead", "Lochearnhead", "Lochgelly", "Lochgoilhead", "Lochwinnoch", "Lockerbie", "Lossiemouth", "Macduff", "Madderty", "Markinch", "Mauchline", "Melrose", "Methil", "Millport", "Milngavie", "Moffat", "Monifieth", "Montrose", "Moodiesburn", "Mossend", "Motherwell", "Mull", "Musselburgh", "Nairn", "Neilston", "New Cumnock", "New Stevenston", "Newhouse", "Newmains", "Newton", "Newton Stewart", "Newtongrange", "Newtonmore", "North Berwick", "Oban", "Orkney", "Paisley", "Peebles", "Penicuik", "Perth", "Peterhead", "Pitlochry", "Polmont", "Port Glasgow", "Portree and North Skye", "Prestwick", "Renfrew", "Ross-shire", "Rosyth", "Rothesay", "Roxburgh", "Rutherglen", "Salsburgh", "Saltcoats", "Sandbank", "Selkirk", "Shetland", "Shotts", "Skye and Lochalsh", "St Andrews", "Stepps", "Stirling", "Stonehaven", "Stonehouse", "Stornoway and Lewis", "Strachur", "Stranraer", "Strathaven", "Strathblane", "Strathpeffer", "Sutherland", "Symington", "Tain", "Tannochside", "Tarbert", "Taynuilt", "Thurso", "Tighnabruaich", "Tillicoultry", "Tomintoul", "Torrance", "Tranent", "Troon", "Tulloch", "Turriff", "Uddingston", "Ullapool", "Uphall", "Wemyss Bay", "West Calder", "Whitburn", "Wick", "Wishaw"];

doLocalSuggest = function() {
  // Use a LocalDataSource
  var oDS = new YAHOO.util.LocalDataSource(myLocationList);
  // Optional to define fields for single-dimensional array
  oDS.responseSchema = {fields : ["state"]};
  // Instantiate the AutoComplete
  var oAC = new YAHOO.widget.AutoComplete("location", "locationSuggest", oDS);
  oAC.prehighlightClassName = "yui-ac-prehighlight";
  oAC.useShadow = true;
                     
  return {
    oDS: oDS,
    oAC: oAC
  };
}();

//Show the 'change password' div
function showPasswordFields(e) {
	document.getElementById("password-fields").style.display = "block";
	document.getElementById("show-password-link").style.display = "none";
	return false;
}
YAHOO.util.Event.addListener("show-password-link", "click", showPasswordFields);

// Empty placeholder to avoid OAS javascript errors
function do_dp_ad() {
}

// Facebook Connect functions

var fbPosted = false;

function fbPostCallback(postId, exception) {
	if(postId) {
		// alert("Posted successfully to Facebook");
		var fbPostStatus = document.getElementById("fbPostStatus");
		fbPostStatus.innerHTML = "Publishing comment...";

		fbPosted = true;
		var commentForm = document.getElementById("commentForm");
		commentForm.submit();
	} else {
		alert("Sorry, there was an error posting to Facebook.");
	}
}

function publish_with_permission(permission,attachment,action_links) {
	// This function checks if user has permission, if not pops up the
	// Facebook dialog and ask for permission.
	// If permission is granted send without asking
	// anything, if permission is not granted pops up
	// and try to send again prompting for a comment.
	FB.ensureInit(function() {
		FB.Connect.requireSession(function(){
			//check is user already granted for this permission or not
			FB.Facebook.apiClient.users_hasAppPermission(permission,
			function(result) {
				// prompt offline permission
				if (result == 0) {
					// show the facebook permission dialog
					FB.Connect.showPermissionDialog(permission,
					function(result){
						if (!result) {
							// no permisson granted, pop up facebook dialog to post;
							FB.Connect.streamPublish('', attachment, action_links, null, "Post this:", fbPostCallback);
						} else {
							// permission granted, post without facebook dialog
							FB.Connect.forceSessionRefresh(function() {
								FB.Connect.streamPublish('', attachment, action_links, null, "Post this:", fbPostCallback,true);
							});
						}
					}, true, null);
				} else {
					// permission already granted, post suddenly
					// without facebook dialog
					FB.Connect.streamPublish('', attachment, action_links, null, "Post this:", fbPostCallback,true);
				}
			});
		});
	});
}


function fbCheckPost(f) {
	var fbPost = document.getElementById("fbpost");
	var fbComment = document.getElementById("add-your-comment-field");
	var fbPostStatus = document.getElementById("fbPostStatus");

	if(fbPost.checked && !fbPosted) {
		// Wants to also post to Facebook...
		fbPostStatus.innerHTML = "Posting to Facebook...";

		var fbTitle = "Commented on: " + document.title;
		var fbDescription = fbComment.value;
		var fbLink = document.location.href;

		var attachment = {	'name': fbTitle,
					'href': fbLink,
					'description': fbDescription};

		var action_links =  [{ 'text' : "Read comments", 'href' : fbLink }] ; 

		publish_with_permission("publish_stream",attachment,action_links);
		return false; 
	} else {
		// Do nothing special...
		fbPostStatus.innerHTML = "Publishing comment...";
		return true;
	}
}


function updateFacebookUser() {
	//alert("Logged in!");

	if (document.getElementById("facebookUser")) {
	  fbUserBox = document.getElementById("facebookUser");
	  fbUserBox.innerHTML =
	        "<span>"
	      + "Welcome, <fb:name uid=loggedinuser useyou=false></fb:name>. You are connected to your Facebook account."
	      + "</span>";
	      
	 // because this is XFBML, we need to tell Facebook to re-process the document 
	  FB.XFBML.Host.parseDomTree();
    }
    
	if (document.getElementById("fbPostContainer")) {
	  document.getElementById("fbPostContainer").style.display = "block";
	}
}
