var ysCookieName = "ttyoursayJScustID";
var loginRatings = false;
var siteId = 1;

$(document).ready( function() {

	// nav dropdown fix for IE6
	$('li.nav-more, li.ms-nav-more').hover(function() { $('div', this).css('display', 'block'); }, function() { $('div', this).css('display', 'none'); });

	// activate team selectors
	$('div.team-select').hover(function(){
		$(this).click(function(){
			$(this).find('ul:first').show();})},function(){
				$(this).find('ul:first').hide()
		}
	);


	// sort out the login area
	renderLogin();

	// tab box
	tabs=function(p){

				$(p+" .anchors li:first").addClass('tabs-selected');
				$(p+" .anchors li").click(function(){
					$(this).parents('.anchors').find('li').removeClass('tabs-selected');
					$(this).addClass('tabs-selected');
					var tablink=$(this).find('a').attr('href');
					if (tablink.match('#')) {
						tablink=tablink.split('#')[1];
						$(this).parents('.tt-tabs').find("div[id^='"+tablink.slice(0,3)+"']").hide();
						$(this).parents('.tt-tabs').find("#"+tablink).show();
						$(this).parents('.tt-clip-tabs').find("div[id^='"+tablink.slice(0,3)+"']").hide();
						$(this).parents('.tt-clip-tabs').find("#"+tablink).show();
					}
					return false;
				});

	}

	tabs("#tt-tabs");
	tabs("#tt-clip-tabs");


	// TEAMTALK ROTATING TOP STORY

	rotateTopStory = function(){
		clearInterval(window.ttinterval)

				var p=1;
				var pos = $('#story-container .story-nav li').index($('#story-container .story-nav li.story-on')[0]);

				if(pos==4){pos=-1;}

				$('#story-container .story-nav li').eq(pos+1).trigger('click','x');
				$('.TStimer').css('width',"1px");
				window.ttinterval = setInterval("rotateTopStory()",7000);
		}

	topStory = function(){
		$('.count').html("1 de 5");

		var first = $('#story-container li.story-content:eq(4)').clone();

		$('#story-container .story-scroll').prepend(first).css({marginLeft:-496});

		rotateTopStory();
		$('#story-container .story-nav li').click(function(click,p){

			var pos = $('#story-container .story-nav li').index($(this))
			pos=pos;
			$('.count').html((pos+1) +" de 5");

			if(pos==4 && p=='x'){

				$('#story-container .story-scroll').animate({marginLeft:((496*pos)*-1)-496},800,function(){

					$('#story-container .story-scroll').css({'marginLeft':0})
				});
			}

			else{
				$('#story-container .story-scroll').animate({marginLeft:((496*pos)*-1)-496},{duration:800,queue:false});

			}

			$('#story-container .story-nav li').removeClass('story-on');
			$(this).addClass('story-on');
			if(p!='x'){
				clearInterval(window.ttinterval)
				//$('.TStimer').css('width',1);
			}
			return false;

	})

	}
	topStory();

	// TEAMTALK ACCORDIONS - stats (tables/fixtures/results) & features (your say/paper talk/rumour room)

		$(".tt-accordion h3:first").addClass("active");
		$(".tt-accordion div:not(:first)").hide();

		$(".tt-accordion h3").click(function(){
			if( $(this).next("div").is(":hidden") ) {
				$(this).next("div").show()
				.siblings("div:visible").hide();
				$(this).toggleClass("active");
				$(this).siblings("h3").removeClass("active");
			}
		});

		$(".tt-accordion2 h3:first").addClass("active");
		$(".tt-accordion2 div:not(:first)").hide();
		/*$(".tt-accordion2 div.papertalk").show();*/

		$(".tt-accordion2 h3").click(function(){
			if( $(this).next("div").is(":hidden") ) {
				$(this).next("div").slideToggle("slow")
				.siblings("div:visible").slideUp("slow");
				$(this).toggleClass("active");
				$(this).siblings("h3").removeClass("active");
			}
		});

		$(".tt-accordion3 h3:first").addClass("active");
		$(".tt-accordion3 div:not(:first)").hide();

		$(".tt-accordion3 h3").click(function(){
			if( $(this).next("div").is(":hidden") ) {
				$(this).next("div").show()
				.siblings("div:visible").hide();
				$(this).toggleClass("active");
				$(this).siblings("h3").removeClass("active");
			}
		});



	// bookmark hover
	$(".share-links a").hover(function() {
		$(this).next("em").show(); /*.animate({opacity: "show", top: "-75"}, "slow");*/
	}, function() {
		$(this).next("em").hide(); /*.animate({opacity: "hide", top: "-85"}, "fast");*/
	});

	// article pic switcher
	$(".article-pic-caption span").append('<em></em>')
	$(".thumbs a").click(function(){
		var largePath = $(this).attr("href");
		var largeAlt = $(this).attr("title");
		$("#largeImg").attr({ src: largePath, alt: largeAlt });
		$(".article-pic-caption span").html("" + largeAlt + ""); return false;
	});

	// comment reply form function
//	$(".comment-reply").click(function(){
//		$(this).parents('.tt-comment').find('.reply-form').toggle();
//		return false;
//	});

	$('.tt-menu .tt-menuul > li').hover(function(){
		var offset = $('.tt-wrap').offset().left;

		var overlay = $(this).find('.tt-menu-overlay');
		if(overlay[0]){
			$(this).find('a').addClass('overlayhover')
			overlay.css('left',offset+5);
			overlay.show();
		}


	},function(){

	$(this).find('.tt-menu-overlay').hide();
	$(this).find('a').removeClass('overlayhover');
	})

	// photo-component function
	configGallery=function(el, galXML) {
			var newHTML = "";
			$.ajax({
			    url: galXML,
			    dataType: 'xml',
			    timeout: 2000,
			    success: function(xml){

					$(xml).find("ARTICLE").each(function(i) {

						if (i < 4) {
							newHTML += "<li><a href='" + $(this).attr("link") + "'><img src='" + $(this).attr("galPicThumb") + "' width='68' height='60'><h4>" + $(this).find("HLHEAD").text() + "</h4><p>" + $(this).find("LLSNIPPET").text() + "</p></a></li>";
						}

						if(i==0){
							galh4 = $(this).find("HLHEAD").text();
							galp = $(this).find("LLSNIPPET").text();
						}

					});

					$("#tt-photo-box1 .tt-photo-gallery").html(newHTML);

					$(el).find('li:first a').addClass('highlight');
					$(el).find('.tt-photo-box-thumbs span').html("<h4>"+galh4+"</h4><p>"+galp+"</p>");

					$(el+ ' ul.tt-photo-gallery li a').mouseover(function(){
						$(el+ ' ul.tt-photo-gallery li a').removeClass('highlight');
						$(this).addClass('highlight');
						var h4 = $(this).find('h4').html();
						var p = $(this).find('p').html();
						$(el).find('.tt-photo-box-thumbs span').html("<h4>"+h4+"</h4><p>"+p+"</p>");

					})
			    }
			})

	}

	// generic tooltip
	tooltip = function() {
		this.xOffset = 10; // x distance from mouse
		this.yOffset = 20; // y distance from mouse

		$(".tooltip").unbind('hover','mousemove').hover(
			function(e) {
				this.t = this.title;
				this.title = '';
				this.top = (e.pageY + yOffset); this.left = (e.pageX + xOffset);
				$('body').append( '<p id="tooltip">' + this.t + '</p>' );
				$('p#tooltip').css("top", this.top+"px").css("left", this.left+"px").fadeIn("slow");
			},
			function() {
				this.title = this.t;
				$("p#tooltip").fadeOut("slow").remove();
			}
		).mousemove(
			function(e) {
				this.top = (e.pageY + yOffset);
				this.left = (e.pageX + xOffset);
				$("p#tooltip").css("top", this.top+"px").css("left", this.left+"px");
			}
		);

	};
	tooltip();



	$(".tt-home-promo").hover(function(){
	$(this).find('p.anim').animate({top:90},{queue:false})
	},function(){
	$(this).find('p.anim').animate({top:184},{queue:false})
	})

	$("ul.tt-news-tabs-tablinks li:first").addClass('tt-news-tabs-on');

	$(".tt-news-tabs-tablinks li").click(function(){

		$(this).parents('.tt-news-tabs-tablinks').find('li').removeClass('tt-news-tabs-on');
		$(this).addClass('tt-news-tabs-on');

		var tablink=$(this).find('a').attr('href');
		var tablink2=tablink.split('#')[1];
		tablink2=tablink2.slice(0,9);

		$(".tt-news-tabs-con div[id*='"+tablink2+"']").hide();
		$(".tt-news-tabs-con div"+tablink).show()
		return false;
	})

	tabs("#tt-news-tabs-box1");

}); // end document.ready


/*
 * renderLogin
 * Writes out the appropriate log-in/out buttons and changes My TEAMtalk link accordingly
 * If anything else should change dynamically when logged in - add them in here.
 * Called onLoad and from validate in login.php
 */
function renderLogin() {

	logBoxHtml = "";
	if (!getCookie(ysCookieName)) {

		// NOT LOGGED IN - show register / Log In button
		logBoxHtml += '<div class="tt-register">'
			+ '<a href="#" onclick="window.open(\'/yoursay/register\',\'Register\',\'width=500,height=500,statusbar=no,scrollbars=yes,resize=no\'); return false;">Register</a>'
			+ '</div>';
		logBoxHtml += '<div class="tt-login">'
			+ '<a href="/yoursay/login?height=200&amp;width=400&amp;" class="thickbox" style="text-decoration:none;">Log&nbsp;In</a>'
			+ '</div>';

		// My TEAMtalk link - force login box
		$(".tt-my-team")
			.html('<a href="/yoursay/login?height=170&amp;width=350&amp;redirect_url=/user/history/" class="thickbox" style="text-decoration:none;">My TEAM<i>talk</i></a>')
			.show();

	} else {

		// USER IS LOGGED IN - show Log Out button
		logBoxHtml += '<div class="tt-logout">'
			+ '<a href="javascript:void(0);" onClick="setCookie(ysCookieName,\'cookieValue\',-1);location.reload(true);">Log&nbsp;Out</a>'
			+ '</div>';

		// My TEAMtalk link - write out link to correct page
		$(".tt-my-team")
			.html("<a href='/user/history/"+getCookie(ysCookieName)+"'>My TEAM<i>talk</i></a>")
			.show();

	}
	$('#login-area').html(logBoxHtml);
	tb_init('#login-area a.thickbox , .tt-my-team a.thickbox');

}


/*
 * swfKitEmbed
 * @param: kitCode - example 2,0346db,8,304af7,130,FFFFFF,0346db,35,0346db,0346db,35,0346db
 *
 */
function swfKitEmbed(kitCode) {
	kitHtml = "";
	if (kitCode) {
		kitHtml = '<object type="application/x-shockwave-flash" data="/shared/swf/kit.swf?kitCode='+ kitCode +'" height="50" width="64">';
			kitHtml += '<param name="movie" value="/shared/swf/kit.swf?kitCode='+ kitCode +'">';
			kitHtml += '<param name="wmode" value="transparent">';
			kitHtml += '<p><a href="http://www.adobe.com/go/flashplayer/" target="blank">Get the Adobe Flash Player to view this content</a>.</p>';
		kitHtml += '</object>';
	}
	return kitHtml;
}

/*
 * renderYourSayComment
 * @param: ysc - should be the json object "ysc"
 * @param: ysListType - passes in listType, if it's byUser we don't want to show view all option
 * @returns: the comment formatted for a your say listing (which replies if avaliable).
 * Called from the loadComments as it loops through each comment
 */
function renderYourSayComment(ysc, ysListType) {

if (ysc) {
		if (ysc.reply) {
			var numReplies = ysc.reply.length;
		}
		allowedRatings = new Array("thumbs-up", "thumbs-down");

		cmtHtml = '<div class="tt-comment-wrap">';
			cmtHtml += '<a name="'+ ysc.id+'"></a>';
			cmtHtml += '<div class="tt-comment-detail">';
				if (ysc.user.kitCode) cmtHtml += swfKitEmbed(ysc.user.kitCode);
				cmtHtml += '<p>'+ ysc.dateCreated +'</p>';
			cmtHtml += '</div><!--tt-comment-detail-->';
			cmtHtml += '<div class="comment" yscId="'+ysc.id+'">';
				cmtHtml += '<p><b>'+ ysc.user.nickname +'&nbsp;';
				if (ysc.user.team) cmtHtml += '('+ysc.user.team+')';
				cmtHtml += ': </b>' + ysc.comment + '</p>';
				cmtHtml += '<p class="comment-links">';
					cmtHtml += '<a href="#" return false;" class="comment-reply">Reply to this comment</a>';
					if (ysListType && ysListType == 'byUser') {
					// don't show view all if we're on the user comment listing page
					} else {
					cmtHtml += '&nbsp;|&nbsp;<a href="/user/comments/'+ ysc.user.id +'" class="viewAll_'+ysc.user.id+'">View All '+ ysc.user.nickname +'\'s comments</a>';
					}
					if (numReplies && numReplies > 1) {
					cmtHtml += '&nbsp;|&nbsp;<a class="replies" href="/yoursay/comment/'+ ysc.id +'">View All Replies</a>';
					}
				cmtHtml += '</p>';

				// have they already rated on this ysc? if so grab the value
				prevRate = (prevRatingData != null) ? checkPreviousRating(prevRatingData,ysc.id) : null;

				cmtHtml += '<ul class="comment-thumbs" yscId="'+ysc.id+'">';
					cmtHtml += renderRatings(ysc.ratings, allowedRatings, false);
				cmtHtml += '</ul>';
			cmtHtml += '</div><!--comment-->';
        cmtHtml += '</div><!--tt-comment-wrap-->\n';

		if (ysc.editorsResponse) {
			cmtHtml += '<div class="tt-comment-wrap editor">';
				cmtHtml += '<div class="tt-comment-detail"><p></p></div>';
				cmtHtml += '<div class="comment">';
					cmtHtml += '<p><b>Editor Comments :</b> '+ysc.editorsResponse+'</p>';
				cmtHtml += '</div><!--comment-->';
			cmtHtml += '</div><!--tt-comment-wrap-->';
		}

		// REPLIES
		if (showReplies == true && numReplies) {
			var count = 1;

			$.each(ysc.reply, function(r,reply){
				if (count == 1) {
					// only show first comment
					cmtHtml += renderReplyComment(reply);
				} else {
					// do nothing. only want to show one reply. Break out the loop
					return false;
				}
				count ++;
			});
		} // end reply

		return cmtHtml;

	} else {
		return null;
	}

}

/*
 * renderReplyComment
 * @param: reply - should be the json object "ysc"
 * @param: ysId - shows a view all replies link if this is passed in
 * @returns: the comment formatted for a reply listing
 * Called from the loadComments as it loops through each comment
 */
function renderReplyComment(reply, ysId) {

	if (reply) {
		allowedRatings = new Array("thumbs-up", "thumbs-down");

		rcmtHtml = '<div class="tt-reply-wrap">';
			rcmtHtml += '<div class="tt-reply-detail">';
				if (reply.user.kitCode) rcmtHtml += swfKitEmbed(reply.user.kitCode);
				rcmtHtml += '<p>'+ reply.dateCreated +'</p>';
			rcmtHtml += '</div>';
			rcmtHtml += '<div class="tt-comment-reply">';
				rcmtHtml += '<p><b>'+ reply.user.nickname +'&nbsp;';
				if (reply.user.team) rcmtHtml += '('+reply.user.team+')';
				rcmtHtml += ': </b>' + reply.comment + '</p>';
				rcmtHtml += '<p class="comment-links">';
					rcmtHtml += '<a href="/user/comments/'+ reply.user.id +'">View All '+ reply.user.nickname +'\'s comments</a>';
				rcmtHtml += '</p>';

				if (reply.ratings) {
					rcmtHtml += '<ul class="comment-thumbs" yscId="'+reply.id+'">';

						// have they already rated on this ysc?if so grab the value
						prevRate = (prevRatingData != null) ? checkPreviousRating(prevRatingData,reply.id) : null;
						rcmtHtml += renderRatings(reply.ratings, allowedRatings, false);

					rcmtHtml += '</ul>';
				}

			rcmtHtml += '</div>';
			if (ysId) {
				rcmtHtml += '<p><a href="/yoursay/comment/'+ysId+'" class="view-replies">View All Replies</a></p>';
			}
		rcmtHtml += '</div>\n';

		if (reply.editorsResponse) {
			rcmtHtml += '<div class="tt-reply-wrap editor">';
				rcmtHtml += '<div class="tt-reply-detail"><p></p></div>';
				rcmtHtml += '<div class="tt-comment-reply">';
					rcmtHtml += '<p><b>Editor Comments :</b> '+reply.editorsResponse+'</p>';
				rcmtHtml += '</div><!--tt-comment-reply-->';
			rcmtHtml += '</div><!--tt-reply-wrap-->';
		}

		return rcmtHtml;

	} else {
		return null;
	}

}

/*
 * renderRumourComment
 * @param: ysc - should be the json object "ysc"
 * @returns: the comment formatted for a rumour room style listing.
 * Called from the loadComments as it loops through each comment
 *
 */
function renderRumourComment(ysc) {

	if (ysc) {

		allowedRatings = new Array("Stonker", "Maybe", "Stinker");

		cmtHtml = '<div class="rumour">';
			if (ysc.title) cmtHtml += '<h3>'+ysc.title+'</h3>';
			cmtHtml += '<div class="comment">';
				if (ysc.image) cmtHtml += '<img src="'+ ysc.image +'" alt="comment image" />';
				cmtHtml += '<h4>' + ysc.user.nickname;
					if (ysc.user.team) cmtHtml += ' ('+ ysc.user.team +')';
				cmtHtml += '</h4>';
				cmtHtml += (ysc.image) ? '<p class="plusimg">' : '<p>';
				cmtHtml += ysc.comment + '</p>';
			cmtHtml += '</div>';

			// now for the important bit - the ratings.
			// output the basic html - events will be added later
			if (ysc.ratings) {
				cmtHtml += '<div class="rate"><h4>Rate this rumour:</h4>';
				cmtHtml += '<ul yscId="'+ysc.id+'">';

					// have they already rated on this ysc?if so grab the value
					prevRate = (prevRatingData != null) ? checkPreviousRating(prevRatingData,ysc.id) : null;
					cmtHtml += renderRatings(ysc.ratings, allowedRatings, true);

				cmtHtml += '</ul></div>';
			}

			if (ysc.editorsResponse) {
				cmtHtml += '<div class="editor">';
					cmtHtml += '<h4>Editor Comments :</h4>';
					cmtHtml += '<p>'+ysc.editorsResponse+'</p>';
				cmtHtml += '</div>';
			}
		cmtHtml += '</div>\n';
		return cmtHtml;
	} else {
		return null;
	}
}

function renderUserComments(ysc) {
	if (ysc.association != null && ysc.association.typeId == 7 && ysc.association.id == 14007) {
		return renderRumourComment(ysc);
	} else {
		var ysListType = 'byUser';
		return renderYourSayComment(ysc, ysListType);
	}
}

(function() {
	var timer;

	$(document).ready(function() {
		if( getCookie(ysCookieName) != null )  {
			if( timer ) {
				clearInterval( timer );
			}

			var keepAliveCookie = function() {
				$.getJSON('/common/utils/keepalive.html', function(data) {
					if( data.valid == false ) {
						clearInterval( timer );
						//window.location.href = window.location.href;
					}
				});
			};
			keepAliveCookie();
			timer = setInterval( keepAliveCookie, 15 * 60 * 1000);
		}
	});
})();

var loginCallback;

(function($) {

	$.isUserLoggedIn = function(callbackFunction) {

		// if you're checking from a form then the callbackFunction should be something like
		//function() {
		//	$('form.myform').trigger('submit');
		//}
		var result = false;

		$.ajax( { 	type: 	'GET',
				url:	'/common/utils/keepalive.html',
				dataType: 'json',
				async: false,
				success: function(data) {
					result = data.valid;
				}
			});

		if( !result ) {
			// FALSE - FOR THE USER TO LOG IN
			tb_show(null,'/yoursay/login/?height=170&width=350',null);
			window.loginCallback = callbackFunction;
		} else {
			// USER LOGGED IN
		}


		return result;
	}
})(jQuery);

//HB: cut down version - just showing next/last
function writeYourSayPagination(page,outUL,render,outDiv) {
	var pagination = '';
	if (page > 1) {
		// show the previous linke
		pagination += '<li><a href="#load-comments" pn="' + (page-1) + '">< Previous</a></li>';
	}
	// show the next link
	pagination += '<li><a href="#load-comments" pn="' + (page+1) + '">Next ></a></li>';

	$(outUL).html(pagination);
	$(outUL+ ' a').click(function(){
		// the page number that the user's clicked on
		selPageNumber = parseInt($(this).attr("pn"));
		loadComments(ysListType, selPageNumber,outDiv,render,showReplies, true);
		$(outUL).html(writeYourSayPagination(selPageNumber,outUL,render,outDiv));
		return false;
	})
}

//function writeYourSayPagination(page,outUL,render,outDiv) {
//	var pagination = '<li class="last-child">Page: </li>';
//	var oddPages = pagesToShow % 2;
//	var firstPage, lastPage, pageClass;
//
//	if (totalPages <= pagesToShow) {
//		firstPage = 1;
//		lastPage = totalPages;
//		loop = totalPages;
//	} else {
//		firstPage = Math.floor(page - (pagesToShow / 2)+1);
//		lastPage = Math.ceil(page + (pagesToShow / 2));
//
//		if (oddPages == 1) {lastPage--;}
//
//		if (firstPage < 1) {
//			firstPage = 1;
//			lastPage = pagesToShow;
//		}
//
//		if (lastPage > totalPages) {lastPage = totalPages;}
//		if (lastPage == totalPages) {firstPage = lastPage - pagesToShow + 1;}
//	}
//
//	if (firstPage == 2) {
//		pagination += '<li><a href="#load-comments" pn="1">1</a></li>';
//	} else if (firstPage > 1 && firstPage != 1) {
//		pagination += '<li><a href="#load-comments" pn="1">First</a>...</li>';
//	}
//
//	for (var i=0;i<pagesToShow;i++) {
//		pageNumber = firstPage + i;
//		pageClass = (pageNumber == page) ? ' class="on"' : '';
//		pagination += '<li'+pageClass+'><a href="#load-comments" pn="'+pageNumber+'">'+pageNumber+'</a></li>';
//		if (pageNumber == lastPage || pageNumber == totalPages) {i = pagesToShow + 1;}
//	}
//
//	if (lastPage < totalPages) {pagination += '<li>...<a href="#load-comments" pn="'+totalPages+'">Last</a></li>';}
//
//	$(outUL).html(pagination);
//	$(outUL+ ' a').click(function(){
//		// the page number that the user's clicked on
//		selPageNumber = parseInt($(this).attr("pn"));
//		loadComments(ysListType, selPageNumber,outDiv,render,showReplies, true/*Trigger HBX*/);
//		$(outUL).html(writeYourSayPagination(selPageNumber,outUL,render,outDiv));
//		return false;
//	})
//}

