
$(document).ready(function() {
	// show banner once per session based on cookies
	if($("#flashBanner").length > 0) { 
		if($.cookie("flashBanner") != null) return;
		$.cookie("flashBanner", true);
		var flashvars = {}, params = { wmode:"transparent" }, attributes = {};
		swfobject.embedSWF("/static-images/jpt_flash_header.swf", "flashBanner", "990", "162", "9.0.0", false, flashvars, params, attributes);
	}
});
 
$(document).ready(function() {
	if ($("#flashVsAd").length > 0) { 
		var flashvars = {}, params = { wmode:"opaque" }, attributes = {};
		swfobject.embedSWF("/static-images/bbt_banner_3.swf", "flashVsAd", "306", "211", "9.0.0", false, flashvars, params, attributes);
	}
});
 
$(document).ready(function() {
	if ($("#paintpot").length > 0) { 
		var flashvars = (!$.cookie("myTeam") ? {} : {myTeam:$.cookie("myTeam")});
		var params = { wmode:"transparent" }, attributes = {};
		swfobject.embedSWF("/xml_banne.swf", "paintpot", "324", "142", "9.0.0", false, flashvars, params, attributes);
	}
});

$(document).ready(function() {
	if ($("#footballChallenge").length > 0) { 
		var flashvars = {file:'/flash/football.swf'}, params = { wmode:'transparent', allowfullscreen:'true', allowscriptaccess:'always' }, attributes = {};
		swfobject.embedSWF("/flash/football.swf", "footballChallenge", "580", "480", "9.0.0", false, flashvars, params, attributes);
	}
});

$(document).ready(function() {

	if ($("#surverysVideo").length > 0) { 

		var imgURL = $("#surverysVideo").find('img').attr('src');
		imgURL = imgURL.replace('/thumb/', '/original/');
		var flashvars = {
			file:$("#surverysVideo").find('a').eq(0).attr('href'),
			image: imgURL,
			autostart:false
		}
		$('#articleMediaContainer').html('<div id="containerInnerDiv">&nbsp;</div>');	
		var params = { wmode:'transparent', allowfullscreen:'true', allowscriptaccess:'always' }, attributes = {};
		swfobject.embedSWF("/javascript/player.swf", 'containerInnerDiv', "280", "280", "9.0.0", false, flashvars, params, attributes);				
	}
});

// initialise all the script objects
$(document).ready(function() { 
	includeVideosInNews.init();
	newsSelector.init();
	videoSelector.init();
	galleryImages.init();
	triviaModule.init();
	handleFormElems(); // add some events to forms to remove default text on focus
	articleVideo.init();
	articleScroller.init();
	userTools.init();
	ugcFileUpload.init();
	
	buildTicker.load();
});



var buildTicker = {
	
	offset: 0,
	paused: false,
	xml: '',
	maxRetries:5,
	tryNum:0,
	
	load:function() {
		if($('#swfhttprequestContainer').length < 1) { return; }
		var obj = this;
		obj.fetchXML();
	},
	
	fetchXML:function() {
		var obj = this;
		
		if(typeof(SWFHttpRequest) == 'undefined') {
			if(obj.tryNum < obj.maxRetries) { // flash not ready yet, wait and retry X times before fail
				obj.tryNum++;
				setTimeout ( function(){ obj.fetchXML(); }, 3500 );
			} else { // FAIL!
				return;
			}
		} else {
			var shr = new SWFHttpRequest();
			shr.open( 'GET', 'http://www.cogent3.co.uk/footballXML.php' );
			shr.onreadystatechange = function(){
				if (this.readyState!=4) return;
				if (this.status==200) {
					obj.xml = this.responseXML; // firefox will parse responsText but IE needs responseXML
					obj.init();
				} else {
					// feed not returned, do nothing!
					
				}
			};
			shr.send('');	
		}
	},
	
	init:function() {

		var obj = this, w = 0, h = 0;
		obj.buildHTML();
		
		
		
		$('#ticker li').each(function(s, e) {
			var inc = obj.getFullWidth($(e));
			h = (h < obj.getFullHeight($(e)) ? obj.getFullHeight($(e)) : h);
			
			if(s==0) { obj.offset = inc; }
			w += inc;
			$(e).mouseenter(function() { obj.paused = true; });
			$(e).mouseleave(function() { obj.paused = false; });
		});
		
		//$('#ticker div.hider').css({ 'height':h });
		$('#ticker div.slider').css({ 'width':(w+600), 'left':300 });
		obj.doAnim();
	},
	
	doAnim:function() {
	
		var obj = this;
		var p = $('#ticker div.slider').eq(0);
		
		if(parseInt(p.css('left'), 10) <= 0-obj.offset) {
			$('#ticker li').eq(0).appendTo($('#ticker ul'));
			obj.offset = obj.getFullWidth($('#ticker li').eq(0));
			$('#ticker div.slider').eq(0).css({'left':0});	
		}
		
		window.setTimeout(function(){
			if(!obj.paused) {
				var newPos = parseInt(p.css('left'), 10)-2;
				p.css({'left':newPos});
			}
			obj.doAnim();
		}, 60);
	},
	
	getFullWidth:function(elem) {
		var inc = 0;
		inc += parseInt(elem.width(), 10);
		inc += elem.css('margin-left') == 'auto' ? 0 : parseInt(elem.css('margin-left'), 10);
		inc += elem.css('margin-right') == 'auto' ? 0 : parseInt(elem.css('margin-right'), 10);
		inc +=  elem.css('padding-left') == 'auto' ? 0 : parseInt(elem.css('padding-left'), 10);
		inc +=  elem.css('padding-right') == 'auto' ? 0 : parseInt(elem.css('padding-right'), 10);
		return inc;
	},
	
	getFullHeight:function(elem) {
		var inc = 0;
		inc += parseInt(elem.height(), 10);
		inc += elem.css('margin-top') == 'auto' ? 0 : parseInt(elem.css('margin-top'), 10);
		inc += elem.css('margin-bottom') == 'auto' ? 0 : parseInt(elem.css('margin-bottom'), 10);
		inc +=  elem.css('padding-top') == 'auto' ? 0 : parseInt(elem.css('padding-top'), 10);
		inc +=  elem.css('padding-bottom') == 'auto' ? 0 : parseInt(elem.css('padding-bottom'), 10);
		return inc;
	},	
	
	buildHTML:function() {

		var obj = this;
		var xmlItems = $(obj.xml).find("item");
		
		if(xmlItems.length < 1) { return; }	
	
		var outputHTML = '';
		outputHTML += '<div id="ticker">' + "\n";
		outputHTML += '    <div id="tickerInner" class="clrNM">' + "\n";
		
		outputHTML += '        <h3><a href="http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml" rel="nofollow" target="_blank">From BBC Sport:</a></h3>';
		
		outputHTML += '        <div class="hider">' + "\n";
		outputHTML += '            <div class="slider">' + "\n";
		outputHTML += '                <ul>' + "\n";

		xmlItems.each(function(s, e) {
			outputHTML += '                <li><a href="' +  $(e).find('link').text() + '" rel="nofollow" target="_blank">' + $(e).find('title').text() + '</a></li>';
		});
		
		outputHTML += '                </ul>' + "\n";
		outputHTML += '            </div>' + "\n";
		outputHTML += '        </div>' + "\n";
		
		//outputHTML += '       <p class="note">From BBC Sport</p>' + "\n";
		
		outputHTML += '    </div>' + "\n";
		outputHTML += '</div>' + "\n";
		
		$('#swfhttprequestContainer').after(outputHTML);
	}
}


var articleVideo = {
	
	init:function(){
		
		//if($('#newsThumbsVideos').length < 1 || $('#newsThumbsImages').length < 1) return;
		if($('#newsThumbsVideos').length < 1) return;

		$('#newsThumbsVideos a').each(function(s, e) {
			$(e).click(function(el){
				$('#articleMediaContainer').html('<div id="containerInnerDiv">&nbsp;</div>');
				
				var imgURL = $(e).find('img').attr('src');
				imgURL = imgURL.replace('/thumb/', '/original/');
				
				var flashvars = {
					file:$(e).attr('href'),
					image: imgURL,
					autostart:true
				}
				
				var params = { wmode:'transparent', allowfullscreen:'true', allowscriptaccess:'always' }, attributes = {};
				swfobject.embedSWF("/javascript/player.swf", 'containerInnerDiv', "280", "280", "9.0.0", false, flashvars, params, attributes);				
				el.preventDefault();
			});
		});
		
		if($('#displayImagesContainer').length > 0) {
			$('#displayImagesContainer').click(function(e) {
				$('#newsThumbsVideos').hide();
				$('#newsThumbsImages').show();
				e.preventDefault();
			});
			$('#displayVideoContainer').click(function(e) {
				$('#newsThumbsVideos').show();
				$('#newsThumbsImages').hide();
				e.preventDefault();
			});			
		}
	}
}




function handleFormElems(){

	if($('#newsletter').length > 0) {
		$('#newsletter').focus(function(){ if(this.value == 'Email:') { this.value = ''; } });
		$('#newsletter').blur(function(){ if(this.value == '') { this.value = 'Email:'; } });
		
		/*$('#newsletterSignupForm').submit(function(e) {
			$.cookie('emailAddress', $('#newsletter').val());
			//e.preventDefault();
		});*/
	}

	/*
	if($('#searchKeyword').length > 0) {
		$('#searchKeyword').focus(function(){ if(this.value == 'keyword') { this.value = ''; } });
		$('#searchKeyword').blur(function(){ if(this.value == '') { this.value = 'keyword'; } });
	}
	*/	

	/* if($('input[name="username"]').length > 0 && $.cookie('emailAddress')) {
		$('input[name="username"]').val($.cookie('emailAddress'));
		$.cookie('emailAddress', null);
	}*/

}


var triviaModule = {
	elemID:'#triviaModule',
	modRef:'div.triviaModule', // html element reference to the container module
	panelWidth:306,
	arr:new Array(),
	arrLength:0,
	maxHeight:0,
	heightMod:96, // add some additional height to allow buttons to sit properly
	init:function(){
		if($(triviaModule.elemID).length < 1) return;
		
		this.build();
		this.addOnClicks();
	},
	build:function(){
		
		var out = '';
		
		$(triviaModule.elemID + ' ' + triviaModule.modRef).each(function(s, e){
			
			triviaModule.arr[s] = { num:s+1, question:$(e).find('div.question p').html(), answer:$(e).find('div.answer p').html() };
			
			if(parseInt($(e).find('div.question p').height(), 10) > triviaModule.maxHeight) { triviaModule.maxHeight = parseInt($(e).find('div.question p').height(), 10); }
			if(parseInt($(e).find('div.answer p').height(), 10) > triviaModule.maxHeight) { triviaModule.maxHeight = parseInt($(e).find('div.question p').height(), 10); }
			
			triviaModule.arrLength = (s+1);
		});
		
		var out = '';
		
		out += '	<div class="top">';
		out += '		<h3>Football Trivia</h3>'
		out += '		<div id="footballTriviaSlideContainer" style="width: ' + triviaModule.panelWidth + 'px; overflow: hidden; position: relative; height: ' + (triviaModule.maxHeight+triviaModule.heightMod) + 'px; min-height: 135px;">';
		out += '		<div id="footballTriviaSlider" style="height: ' + (triviaModule.maxHeight+triviaModule.heightMod) + 'px; width: ' + ((2*triviaModule.panelWidth)*triviaModule.arrLength) + 'px; position: absolute; top: 0; left: 0;">';
		out += '		<div style="position: relative;">';
		
		for(i=0, x=triviaModule.arrLength; i<x; i++) {
			out += 	'		<div class="triviaModule" style="position: absolute; top: 0; left: ' + ((i*2)*triviaModule.panelWidth)+ 'px;">';
			out += 	'			<div class="top">';
			out += 	'				<h4>Question ' + triviaModule.arr[i]['num'] + ':</h4>';
			out += 	'			</div>';
			out += 	'			<div class="middle">';
			out += 	'				<div class="question" style="height: ' + triviaModule.maxHeight + 'px; min-height:60px; padding:5px 0 0 0;">';
			out += 	'					<p>';
			out += 	'						' + triviaModule.arr[i]['question'];
			out += 	'					</p>';
			out += 	'				</div>';
			out += 	'			</div>';
			out += 	'			<div class="bottom"><p class="blueLinkButton"><a href="#">Answer</a></p></div>';
			out += 	'		</div>';

			out += 	'		<div class="triviaModule" style="position: absolute; top: 0; left: ' + (((i*2)*triviaModule.panelWidth)+triviaModule.panelWidth) + 'px;">';
			out += 	'			<div class="top">';
			out += 	'				<h4>Answer:</h4>';
			out += 	'			</div>';
			out += 	'			<div class="middle">';
			out += 	'				<div class="answer" style="height: ' + triviaModule.maxHeight + 'px; min-height:60px; padding:5px 0 0 0;">';
			out += 	'					<p>';
			out += 	'						' + triviaModule.arr[i]['answer'];
			out += 	'					</p>';
			out += 	'				</div>';
			out += 	'			</div>';
			if(i == (triviaModule.arrLength-1)) {
				out += 	'			<div class="bottom"><p class="blueLinkLeft"><a href="#">Back to the start</a></p></div>';
			} else {
				out += 	'			<div class="bottom"><p class="blueLinkButton"><a href="#">Question ' + (parseInt(triviaModule.arr[i]['num'], 10)+1) + '</a></p></div>';	
			}
			out += 	'		</div>';
		}
		out += '		</div>';
		out += '		</div>';
		out += '		</div>';
		out += '	</div>';
		out += '	<span class="bottom">&nbsp;</span>';
		$(this.elemID).html(out);
		
		
	},
	
	addOnClicks:function(){
		$(triviaModule.elemID + ' ' + triviaModule.modRef + ' p.blueLinkButton').click(function (e) {
				triviaModule.scrollIt('next');
				$(this).find('a').blur();
				e.preventDefault();
		});
		$(triviaModule.elemID + ' ' + triviaModule.modRef + ' p.blueLinkLeft').click(function (e) {
				triviaModule.scrollIt('first');
				$(this).find('a').blur();
				e.preventDefault();
		});
	},
	
	removeOnClicks:function(){
		$(triviaModule.elemID + ' ' + triviaModule.modRef + ' p.blueLinkButton').unbind('click', triviaModule.scrollIt()).click(function (e) {e.preventDefault();});
		$(triviaModule.elemID + ' ' + triviaModule.modRef + ' p.blueLinkLeft').unbind('click', triviaModule.scrollIt()).click(function (e) {e.preventDefault();});
	},
	
	scrollIt:function(dir){
		if(!dir) return;
		
		var p = $("#footballTriviaSlider");
		var newPos = (dir == 'first' ? '0' : p.position().left-triviaModule.panelWidth);
		var speed = (dir == 'first' ? 'normal' : 'slow');
		if(dir=='prev' && (parseInt(p.position().left, 10) + triviaModule.panelWidth) > 0) return;
		if(dir=='next' && (parseInt((triviaModule.numPanels*triviaModule.panelWidth), 10) + (parseInt(p.position().left, 10) - triviaModule.panelWidth)) < 1) return;
		
		triviaModule.removeOnClicks();
		p.stop().animate(
			{left:newPos}, speed, "swing", function() { triviaModule.addOnClicks(); }
		);
	}		
}

var includeVideosInNews = {
	init:function(){
	
	}
}


var newsSelector = {

	selectorID:'newsSelector',
	mediaSelectorID:'newsSelectorMedia',
	ignoreFirstLast:'true',
	currPos:0,
	arr:new Array(), // array of video objects
	arrLength:0, // legth of video object array
	mediaContainer:'newsMediaSelectorTarget',
	
	init:function(){
		if ($('#' + newsSelector.selectorID).length < 1) return;
		newsSelector.buildMediaObj();
		newsSelector.addHover();
	},
	
	buildMediaObj:function() {
		if(typeof swfobject == 'undefined') return;
		
		//build an array to hold our media objects
		$('#' + newsSelector.mediaSelectorID + ' div.mediaContainer').each(function(s, e){
			if($(e).hasClass('video')) {
				newsSelector.arr[s] = { 
					num:s, 
					type:'video',
					vidURL:$(e).find('a').attr('href'),
					imgURL:$(e).find('img').attr('src'),
					caption:$(e).find('span').html()
				};
			} else {
				newsSelector.arr[s] = { 
					num:s, 
					type:'image',
					vidURL:'',
					imgURL:$(e).find('img').attr('src'),
					caption:$(e).find('span').html()
				};
			}
		});
		newsSelector.createMediaContainer();
	},	
	createMediaContainer:function(el){
		el = (!el ? parseInt(0, 10) : el);
		e = '#' + newsSelector.mediaSelectorID;
		
		// build or rebuild the container
		outputHTML = '';
		outputHTML += ' <div class="media show">';
		outputHTML += '		<div class="top">';
		
		if(newsSelector.arr[el].type == 'video') {
			outputHTML += '			<div id="' + newsSelector.mediaContainer + '">&nbsp;</div>';
		} else {
			outputHTML += '			<img src="' + newsSelector.arr[el].imgURL + '" alt="" height="270" width="270"/>';
		}
		
		outputHTML += '		</div>';
		outputHTML += '		<div class="bottom">';
		outputHTML += '			<p>' + newsSelector.arr[el].caption + '</p>';
		outputHTML += '		</div>';
		outputHTML += '	</div>';
		$(e).html(outputHTML);

		if(newsSelector.arr[el].type == 'video') {

			var flashvars = {
				file: newsSelector.arr[el].vidURL,
				image: newsSelector.arr[el].imgURL,
				autostart:false
			};
			var params = { wmode:'transparent', allowfullscreen:'true', allowscriptaccess:'always' };
			var attributes = {
				switchVar:'gallery',
				name:newsSelector.mediaContainer
			}; // switchvar allows different switch case triggers in player function, name is required in addition to id in some browsers to trigger functin call!
			swfobject.embedSWF("/javascript/player.swf", newsSelector.mediaContainer, "295", "270", "9.0.0", false, flashvars, params, attributes);	
		}
	},
	addHover:function(){
		$('#' + newsSelector.selectorID + ' li').each(function(s, el) {
			if(newsSelector.ignoreFirstLast != 'true' || s > 0) {
				$(el).mouseenter(function (e) {
					newsSelector.select(el, '#' + newsSelector.selectorID + ' li');
				});	
			}
		});
	},
	select:function(el, pn){
		var elPos = 0;
		$(pn).each(function(s, e) {
			if(newsSelector.ignoreFirstLast != 'true' || s > 0) {
				if(e != el) {
					$(e).removeClass('selected').removeClass('jsSelect');
				}
			}
			if(e == el) { 
				elPos = (newsSelector.ignoreFirstLast == 'true' ? (s-1) : s);
			}
		});
		if(newsSelector.currPos != elPos) {
			newsSelector.createMediaContainer(elPos);
			newsSelector.currPos = elPos;
		}
		$(el).addClass('jsSelect');
	}	
}


// !!! generic global variable and method for use by the jwplayer so be careful how/where this gets overwritten!
var player; 
function playerReady(obj) {
	player = document.getElementById(obj['id']);
	if(typeof($(player).attr('switchvar')) == 'undefined') return;
	switch ($(player).attr('switchvar')) {
		case 'gallery':
			//player.addControllerListener("STOP","videoSelector.stopPlayback");
		break;
	}

};

var videoSelector = {
	selectorID:'galleryVideoSelector',
	mediaSelectorID:'galleryVideoSelectorMedia',
	ignoreFirstLast:'false',
	maxItems:4,
	panelHeight: 270,
	panelWidth: 324,
	prevNav:'galleryVideoScrollPrev',
	nextNav:'galleryVideoScrollNext',
	currPos:0, // current position of the video tabs
	arr:new Array(), // array of video objects
	arrLength:0, // legth of video object array
	vidContainer:'videoSelectorTarget',
	
	init:function(elem, selectorID, mediaSelectorID, ignoreFirstLast){
		if ($('#' + videoSelector.selectorID).length < 1) return;
		//videoSelector.buildVideos();
		videoSelector.buildVideo();
		videoSelector.menuSlider();
		videoSelector.addHover();
		videoSelector.selectTab(0);
	},
	addHover:function(){
		// determine if a new set of video galleries was built by checking if the ul uses the class or id attribute
		navSelector = ($('.' + videoSelector.selectorID + ' li').length > 0 ? '.' + videoSelector.selectorID + ' li' : '#' + videoSelector.selectorID + ' li');
		$(navSelector).each(function(s, el) {
			if(videoSelector.ignoreFirstLast != 'true' || s > 0) {
				$(el).mouseenter(function (e) {
					videoSelector.select(el, navSelector);
				});
				$(el).find('a').click(function (ev) {
					ev.preventDefault();
				});				
			}
		});
	},
	select:function(el, pn){
		var elPos = 0;
		$(pn).each(function(s, e) {
			if(videoSelector.ignoreFirstLast != 'true' || s > 0) {
				if(e != el) {
					$(e).removeClass('selected').removeClass('jsSelect');
				}
			}
			if(e == el) { 
				elPos = (videoSelector.ignoreFirstLast == 'true' ? (s-1) : s);
			}
		});
		
		if(videoSelector.currPos != elPos) {
			videoSelector.createVideoContainer(elPos);
			videoSelector.currPos = elPos;
		}
		$(el).addClass('jsSelect');
	},
	
	setCurrentPos:function(pos){
		videoSelector.currPos = pos;
	},
	
	selectTab:function(pos) {
		if(!pos) { pos = 0; }
		elem = ($('#' + videoSelector.selectorID).length < 1 ? '.' + videoSelector.selectorID : '#' + videoSelector.selectorID);
		$(elem).find('li').eq(pos).addClass('jsSelect');
	},
	
	buildVideo:function() {
		
		if(typeof swfobject == 'undefined') return;
		
		//build an array to hold our video objects
		$('#' + videoSelector.mediaSelectorID + ' div.mediaContainer').each(function(s, e){
			
			videoSelector.arr[s] = { 
				num:s, 
				type:'video',
				vidURL:$(e).find('a').attr('href'),
				imgURL:$(e).find('img').attr('src'),
				caption:$(e).find('span').html()
			};	
		});
		
		videoSelector.createVideoContainer();
	},
	
	createVideoContainer:function(el){
		
		el = (!el ? parseInt(0, 10) : el);
		e = '#' + videoSelector.mediaSelectorID;
		
		// build or rebuild the container
		outputHTML = '';
		outputHTML += ' <div class="media show">';
		outputHTML += '		<div class="top">';
		outputHTML += '			<div id="' + videoSelector.vidContainer + '">&nbsp;</div>';
		outputHTML += '		</div>';
		outputHTML += '		<div class="bottom">';
		outputHTML += '			<p>' + videoSelector.arr[el].caption + '</p>';
		outputHTML += '		</div>';
		outputHTML += '	</div>';
		$(e).html(outputHTML);
		
		var flashvars = {
			file: videoSelector.arr[el].vidURL,
			image: videoSelector.arr[el].imgURL,
			autostart:false
		};
		var params = { wmode:'transparent', allowfullscreen:'true', allowscriptaccess:'always' };
		var attributes = {
			switchVar:'gallery',
			name:videoSelector.vidContainer
		}; // switchvar allows different switch case triggers in player function, name is required in addition to id in some browsers to trigger functin call!
		swfobject.embedSWF("/javascript/player.swf", videoSelector.vidContainer, "295", "270", "9.0.0", false, flashvars, params, attributes);	
		
	},
	
	startPlayback:function(){
		if(typeof('player.sendEvent') == 'undefined') return;
		$('div.media.show object').attr({width: "295"});
		$('div.media.show div.subContainer img.overlayThumb').addClass('hide');
		$('div.media.show div.subContainer div.overlayControl').addClass('hide');
		player.sendEvent("PLAY","true");
	},
	
	stopPlayback:function(){
		
		$('#' + videoSelector.mediaSelectorID + ' div.media').each(function(s, e){
			$(e).find('div.subContainer img.overlayThumb').removeClass('hide');
			$(e).find('div.subContainer div.overlayControl').removeClass('hide');
			$(e).find('object').attr({width: "270"});
		});
		
	},
	
	menuSlider:function(){
		if($('#' + videoSelector.selectorID + ' li').length <= videoSelector.maxItems) { return; }
		
		var out = '';
		out += '<div id="videoScrollContainer" style="margin-left: 315px; overflow: hidden; position: relative; height: ' + videoSelector.panelHeight + 'px; width: ' + videoSelector.panelWidth + 'px;">';
		out += '	<div id="videoScrollableArea" style="position: absolute; top: 0; left: 0; height: ' + videoSelector.panelHeight + 'px;">';
		out += '		<div id="videoScrollInner" style="position: relative; height: ' + videoSelector.panelHeight + 'px;">';
		out += '			<div style="clear: both; display: block; position: absolute; top: 0; left: 0; width: ' + videoSelector.panelWidth + 'px; height: ' + videoSelector.panelHeight + 'px;">';
		out += '				<ul class="'+videoSelector.selectorID+'" style="float: none; margin-left: 0;">';
		
		var inc = 1;
		$('#' + videoSelector.selectorID + " li").each(function(s, el) {
			if(s > 0 && s%videoSelector.maxItems == 0) {
				
				out += '		</ul>';
				out += '	</div>';
				out += '	<div style="clear: both; display: block; position: absolute; top: 0; left: ' + (videoSelector.panelWidth*inc) + 'px; width: ' + videoSelector.panelWidth + 'px; height: ' + videoSelector.panelHeight + 'px;"><ul class="'+videoSelector.selectorID+'" style="float: none; margin-left: 0;">';
				inc++;
			}
			out += '<li>' + el.innerHTML + '</li>';
		});
		out += '				</ul></div></div></div></div>';
		this.numPanels = inc;
		
		var nav = '';
		nav += '<div class="galleryVideoThumbs clrNM">';
		nav += '	<div class="nav clrNM">';
		nav += '		<p id="galleryVideoScrollPrev" class="blueLinkLeft"><a href="#">Previous set</a></p>';
		nav += '		<p id="galleryVideoScrollNext" class="blueLinkButton"><a href="#">Next set</a></p>';
		nav += '	</div>';
		nav += '</div>';
		
		$('#'+videoSelector.selectorID).after(nav);
		
		// output the generated gallery
		$('#' + videoSelector.selectorID).after(out);

		// remove the original images - note this only removes them from the DOM, not from jquery
		$('#' + videoSelector.selectorID).remove();
		
		// make the nav clickyesque
		videoSelector.addOnClicks();
	},	
	
	addOnClicks:function(){
		$('#'+videoSelector.prevNav).click(function (e) {
			videoSelector.scrollIt('prev');
			$(this).find('a').blur();
			e.preventDefault();
		});

		$('#'+videoSelector.nextNav).click(function (e) {
			videoSelector.scrollIt('next');
			$(this).find('a').blur();
			e.preventDefault();
		});	
		
		var p = $("#videoScrollableArea");
		if(p.length > 0) {
			if(p.position().left == 0) { $('#'+videoSelector.prevNav).addClass('grey'); } 
			else { $('#'+videoSelector.prevNav).removeClass('grey'); }
			
			if(parseInt((videoSelector.numPanels*videoSelector.panelWidth), 10) + (parseInt(p.position().left, 10) - videoSelector.panelWidth) < 1) { $('#'+videoSelector.nextNav).addClass('grey'); } 
			else { $('#'+videoSelector.nextNav).removeClass('grey'); }
		}		
	},
	removeOnClicks:function(){
		$('#'+videoSelector.prevNav).unbind('click', galleryImages.scrollIt()).click(function (e) {e.preventDefault();});
		$('#'+videoSelector.nextNav).unbind('click', galleryImages.scrollIt()).click(function (e) {e.preventDefault();});
	},
	
	scrollIt:function(dir){
		if(!dir) return;
		
		var p = $("#videoScrollableArea");
		var newPos = (dir == 'prev' ? p.position().left+videoSelector.panelWidth : p.position().left-videoSelector.panelWidth);
		
		if(dir=='prev' && (parseInt(p.position().left, 10) + videoSelector.panelWidth) > 0) return;
		if(dir=='next' && (parseInt((videoSelector.numPanels*videoSelector.panelWidth), 10) + (parseInt(p.position().left, 10) - videoSelector.panelWidth)) < 1) return;
		
		videoSelector.removeOnClicks();
		p.stop().animate(
			{left:newPos}, "slow", "swing", function() { videoSelector.addOnClicks(); }
		);
	}	
}

// build and initialise the image gallery
var galleryImages = {

	numImages:0,
	maxImages:10, // maximum number of images to show in the panel at once
	numPanels:1,
	pointer:0,
	pxWidth:0,
	panelHeight: 235,
	panelWidth: 618,
	thumEl: 'ul#galleryThumbs',
	init:function(){
		if ($(galleryImages.thumEl + " img").length <= galleryImages.maxImages) {
			// we still want the lightbox even if there aren't enough images to scroll
			galleryImages.enableLightBox($('ul#galleryThumbs a'));
			return;
		}
		galleryImages.numImages = $("ul#galleryThumbs img").length;
		galleryImages.createGallery();
		
	},
	
	createGallery:function(){
		var out = '';
		
		out += '<div id="galleryScrollContainer" style="height: ' + galleryImages.panelHeight + 'px; width: ' + galleryImages.panelWidth + 'px;">';
		out += '	<div id="galleryScrollableArea" style="height: ' + galleryImages.panelHeight + 'px;">';
		out += '		<div id="galleryScrollInner" style="height: ' + galleryImages.panelHeight + 'px;">';
		out += '			<div style="left: 0; width: ' + galleryImages.panelWidth + 'px; height: ' + galleryImages.panelHeight + 'px;">';
		out += '				<ul class="galleryThumbs">';
		
		var inc = 1;
		$(galleryImages.thumEl + " li").each(function(s, el) {
			if(s > 0 && s%galleryImages.maxImages == 0) {
				
				out += '		</ul>';
				out += '	</div>';
				out += '	<div style="left: ' + (galleryImages.panelWidth*inc) + 'px; width: ' + galleryImages.panelWidth + 'px; height: ' + galleryImages.panelHeight + 'px;"><ul class="galleryThumbs">';
				inc++;
			}
			out += '<li>' + el.innerHTML + '</li>';
		});
		out += '				</ul></div></div></div></div>';
		this.numPanels = inc;
		
		var nav = '';
		nav += '<div class="galleryThumbs clrNM">';
		nav += '	<div class="nav clrNM">';
		nav += '		<p id="galleryScrollPrev" class="blueLinkLeft"><a href="#">Previous set</a></p>';
		nav += '		<p id="galleryScrollNext" class="blueLinkButton"><a href="#">Next set</a></p>';
		nav += '	</div>';
		nav += '</div>';
		
		// output the nav
		$(galleryImages.thumEl).parent().parent().after(nav);
		
		// output the generated gallery
		$(galleryImages.thumEl).after(out);

		// remove the original images - note this only removes them from the DOM, not from jquery
		$(galleryImages.thumEl).remove();
		
		// attach onclick events to nav
		galleryImages.addOnClicks();
		
		// enable lightbox on thumbnails
		galleryImages.enableLightBox($('#galleryScrollInner ul a'));
		$('#galleryScrollInner ul a').each(function(e){ $(e).focus(function(el){ $(el).blur(); }); });
	},
	
	enableLightBox:function(elem){
		$('a[rel="imageshow"]').colorbox({transition:'fade', speed:500, current:''});
	},

	addOnClicks:function(){
		$('#galleryScrollPrev').click(function (e) {
			galleryImages.scrollIt('prev');
			$(this).find('a').blur();
			e.preventDefault();
		});

		$('#galleryScrollNext').click(function (e) {
			galleryImages.scrollIt('next');
			$(this).find('a').blur();
			e.preventDefault();
		});	
		
		var p = $("#galleryScrollableArea");
		if(p.length > 0) {
			if(p.position().left == 0) { $('#galleryScrollPrev').addClass('grey'); } 
			else { $('#galleryScrollPrev').removeClass('grey'); }
			if(parseInt((galleryImages.numPanels*galleryImages.panelWidth), 10) + (parseInt(p.position().left, 10) - galleryImages.panelWidth) < 1) { $('#galleryScrollNext').addClass('grey'); } 
			else { $('#galleryScrollNext').removeClass('grey'); }
		}
		
	},

	removeOnClicks:function(){
		$('#galleryScrollPrev').unbind('click', galleryImages.scrollIt()).click(function (e) {e.preventDefault();});
		$('#galleryScrollNext').unbind('click', galleryImages.scrollIt()).click(function (e) {e.preventDefault();});
		
	},
	
	scrollIt:function(dir){
		if(!dir) return;
		
		var p = $("#galleryScrollableArea");
		var newPos = (dir == 'prev' ? p.position().left+galleryImages.panelWidth : p.position().left-galleryImages.panelWidth);
		
		if(dir=='prev' && (parseInt(p.position().left, 10) + galleryImages.panelWidth) > 0) return; 
		if(dir=='next' && (parseInt((galleryImages.numPanels*galleryImages.panelWidth), 10) + (parseInt(p.position().left, 10) - galleryImages.panelWidth)) < 1) return;
		
		galleryImages.removeOnClicks();
		p.stop().animate(
			{left:newPos}, "slow", "swing", function() { galleryImages.addOnClicks(); }
		);
	}
}

var articleScroller = {

	scrollerId:		'#homeScroller',
	sliderName:		'.slider',
	panelName:		'.panel',
	panelWidth: 	324,
	numPanels:		0,
	activePanel:	1,
	animSpeed:		1000,
	scrollInterval:	3500,
	timeout:		null,
	autoScroller:	true,
		
	init:function() {

		// Set the number of panels
		this.numPanels = $(this.scrollerId + ' ' + this.panelName).length;

		// Set the width of the slider (plus 1 is to accomodate the cloned panel also)														
		$(this.scrollerId + ' ' + this.sliderName).css({ 'width' : this.panelWidth * (this.numPanels + 1) });	

		if(this.autoScroller && this.numPanels > 1)	this.autoScroll();
	},
	autoScroll:function() {
		
		var obj = this;
		this.timeout = setInterval( function(){
			obj.scroll();
		}, obj.scrollInterval);	
			
	},
	scroll:function() {
			
		// If the active panel is equal to the total number of panels clone the first panel and append to the end of slider
		if(this.activePanel == this.numPanels)
			$(this.scrollerId + ' ' + this.sliderName).append($(this.scrollerId + ' ' + this.sliderName + ' ' + this.panelName).eq(0).clone());			

		// If we are at the cloned first panel reset everything and remove the cloned panel
		if(this.activePanel == this.numPanels + 1) {
			this.activePanel = 1;
			$(this.scrollerId + ' ' + this.sliderName).css({ 'left' : '0px' });
			$(this.scrollerId + ' ' + this.sliderName).stop();
			$(this.scrollerId + ' ' + this.sliderName + ' ' + this.panelName).eq($(this.scrollerId + ' ' + this.sliderName + ' ' + this.panelName).length-1).remove();
		}
			
		// Animate the panel
		var sliderLeft = this.activePanel * this.panelWidth;
		$(this.scrollerId + ' ' + this.sliderName).animate({ 'left' : '-' + sliderLeft + 'px' }, this.animSpeed);
		this.activePanel++;		
	}
}

var userTools = {

	sizes:{'textSmall':63, 'textMedium':75, 'textLarge':88},	// define sizes as percentages
	sizeSelected:'textSmall', 									// default selected
	sizeCookie: 'sizes',										// cookie name

	init:function(){
		
		if($('#userToolsContainer').length < 1) {
			$('#footer div.info').before('<div id="userToolsContainer">&nbsp;</div>'); // if the user tools area is not present, add it dynamically to give a hook for the controls
		}
					
		if($.cookie(this.sizeCookie) != null && $.trim($.cookie(this.sizeCookie)) != '') { this.sizeSelected = $.trim($.cookie(this.sizeCookie)); }
		
		this.attachHTML();
		this.attachEvents();
	},
		
	attachHTML:function(){	
		
		var emailBodyMsg = '';
		emailBodyMsg 	+= 'Check out this link from Johnstone\'s Paint Trophy:%0d%0d';
		emailBodyMsg	+= 'http://www.johnstonespainttrophy.com%0d%0dRegards';

		var output = '';

		output +=	'		<div id="userTools"><div id="userToolsInner">';
		output +=   ' 			<ul>';
		output +=   '				<li><p>User Tools</p></li>';
		output +=   '				<li class="size" id="textSmall"><a href="#" title="Small text"></a></li>';
		output +=   '				<li class="size" id="textMedium"><a href="#" title="Medium text"></a></li>';
		output +=   '				<li class="size" id="textLarge"><a href="#" title="Large text"></a></li>';
		output +=   '				<li id="print"><a href="#"></a></li>';
		output +=   '				<li id="bookmark"><a href="#"></a></li>';
		output +=   '				<li id="email"><a href="mailto:&body=' + emailBodyMsg + '"></a></li>';
		output +=   '			</ul>';
		output +=   '		</div></div>';

		
		$("#userToolsContainer").html(output);
		output = null;

		$('#userTools ul #'+this.sizeSelected).addClass('selected');
		$('body').css({'font-size':this.sizes[this.sizeSelected]+'%'});

	},

	attachEvents:function(){
		var obj = this;
		
		$('#userTools ul li.size').click(function(ev) {
			ev.preventDefault();
			$(this).find('a').blur();
			for(var i in obj.sizes) {
				if($(this).attr('id') == i) {
					$('#userTools ul li.size').removeClass('selected');
					$(this).addClass('selected');
					$('body').css({'font-size':obj.sizes[i]+'%'});
					obj.sizeSelected = i;
				}
			}
			obj.storeValue(obj.sizeCookie, obj.sizeSelected);
			//location.href = location.href;
		});
		
		$('#print').click(function(ev) {			
			window.print();
			$(this).find('a').blur();
			ev.preventDefault();
		});
		
		$('#bookmark').click(function(ev) {
			$(this).find('a').blur();
			ev.preventDefault();
			
			if (window.sidebar) {			// Firefox
				window.sidebar.addPanel(document.title,self.location,'');
			}
			else if (window.external) {		// IE
				window.external.AddFavorite(self.location,document.title);
			}
		});
		
		$('#email').click(function(ev) {
			$(this).find('a').blur();
		});
	},
	storeValue:function(cookName, cookValue){ 
		cookName = $.trim(cookName);
		cookValue = $.trim(cookValue);

		$.cookie(cookName, null);
		$.cookie(cookName, cookValue, { path: '/' });
	}
}



// user generated content upload form

var ugcFileUpload = {
	
	formIdent: 'form#ugcForm',  // css reference to the form
	msgIdent: '',
	attMsgIdent: '',
	fileFielsIdent: '',            // these empty containers are set up in init
	fileCount: 0,                  // running count of num files attached
	maxFiles: 0, 			       // populated based on num of file fields in html
	//fileStore: new Array(),
	iter: 0,                       // stores current unique identifier for field
	captionPrompt: '',
	captionMaxChars: 100,           // maximum length of image descriptions
	
	init:function(){
		var obj = this;
		
		obj.msgIdent = obj.formIdent + ' fieldset.uploadMsg';
		obj.fileFielsIdent = obj.formIdent + ' fieldset.fileFields';
		obj.attMsgIdent = obj.formIdent + ' fieldset.filesAttached';
		obj.maxFiles = $(obj.fileFielsIdent).find('input[type=file]').length;
		
		if($(obj.formIdent).length < 1) return;
		
		obj.addMessageFieldset();
		$(obj.fileFielsIdent).html('');
		obj.showMessages();
		obj.attachFile();
		obj.attachValidation();
	},
	
	addMessageFieldset:function() {
		var obj = this;
		var outputHTML = '';
		outputHTML += '<fieldset class="filesAttached">';
		outputHTML += '    <h3>You have attached the following images to your post</h3>';
		outputHTML += '</fieldset>';
		$(obj.formIdent + ' fieldset.fileFields').after(outputHTML);
		
		var outputHTML = '';
		outputHTML += '<fieldset class="uploadMsg"></fieldset>';
		$(obj.formIdent + ' fieldset.msgFields').after(outputHTML);
		
	},
	
	showMessages:function() {
		var obj = this;
		var msg = '';
		//Upload images ('jpg', 'gif', 'png'. Upto 300kB each, max 3):
		if($(obj.attMsgIdent).find('p').length == 0) { msg = 'Upload images (\'jpg\', \'gif\' or \'png\' allowed. Up to 300kB each, max ' + obj.maxFiles + '):'; }
		else if($(obj.attMsgIdent).find('p').length == obj.maxFiles) { msg = 'Maximum of ' + obj.maxFiles + ' images allowed per post'; }
		else { msg = 'Upload another image with your post (max ' + obj.maxFiles + '):'; }

		if($(obj.msgIdent).find('p').length < 1) { $(obj.msgIdent).prepend('<p></p>'); }
		
		$(obj.msgIdent + ' p').html(msg);
		if($(obj.attMsgIdent).find('p').length > 0) { $(obj.attMsgIdent).css({'display':'block'}); } else { $(obj.attMsgIdent).css({'display':'none'}) }
		
	},

	attachFile:function() {
		var obj = this;
		
		if(obj.fileCount >= obj.maxFiles) { return; }
		if($(obj.msgIdent + ' input[type=file]').length > 0 && $(obj.msgIdent + ' input[type=file]').eq($(obj.msgIdent + ' input[type=file]').length-1).attr('value') =='') { return; }
		
		$(obj.msgIdent).append('<span><input type="file"/><input type="hidden" /></span>');
			
		var elem = $(obj.msgIdent + ' input[type=file]').eq($(obj.msgIdent + ' input[type=file]').length-1); 
		elem.change(function() {
			elem.attr({
				'id':'fileID_' + obj.iter,
				'name':'fileID_' + obj.iter
			});
			elem.parent().find('input[type=hidden]').eq(0).attr({'id':'fileCaption_' + obj.iter});
			
			obj.fileCaptionPrompt();
		});
	},
	
	fileCaptionPrompt:function() {
	
		var obj = this;
		if($('div.fileCaptionPrompt').length < 1) {
			obj.captionPrompt += '<div class="fileCaptionPrompt">';
			obj.captionPrompt += '    <label for="fileCaptionPrompt">Enter a title or caption for your image (max ' + obj.captionMaxChars + ' characters)</label>';
			obj.captionPrompt += '    <textarea type="text" name="fileCaptionPrompt" id="fileCaptionPrompt" rows="4"></textarea> <span id="fileCaptionCount">0/' + obj.captionMaxChars + '</span>';
			obj.captionPrompt += '    <div class="ugcControls">';
			obj.captionPrompt += '        <input type="submit" id="fileCaptionSubmit" value="Attach Image"/>';
			obj.captionPrompt += '        <input type="submit" id="fileCaptionCancel" value="Cancel"/>';
			obj.captionPrompt += '    </div>';
			obj.captionPrompt += '</div>';
			// TODO: need to check if this works in IE6, if not might require iframe underlay solution?
			$(obj.formIdent).append(obj.captionPrompt);
			
			$('#fileCaptionSubmit').click(function(ev) {
				ev.preventDefault();
				obj.fileCaptionCheck(this);
			});

			$('#fileCaptionCancel').click(function(ev) {
				ev.preventDefault();
				obj.fileCaptionCancel(this);
			});

			$('#fileCaptionPrompt').keyup(function(e) { obj.updateCharCount(this); });
		}
		$('div.fileCaptionPrompt').css({'display':'block'});
		$('#fileCaptionPrompt').focus();
		
	},
	
	updateCharCount:function(elem) {
		var obj = this;
		var maxValOut = $(elem).val().length > obj.captionMaxChars ? '<em>' + $(elem).val().length + '</em>' : $(elem).val().length;
		$('#fileCaptionCount').html(maxValOut + '/' + obj.captionMaxChars);	
	},
	
	fileCaptionCheck:function(elem) {
		var obj = this;
		if($('#fileCaptionPrompt').val().length > obj.captionMaxChars || $('#fileCaptionPrompt').val().length < 1) { 
			obj.updateCharCount('#fileCaptionPrompt');
			return; 
		}

		$('div.fileCaptionPrompt').css({'display':'none'});
		$('#fileCaption_' + obj.iter).attr({'value':$('#fileCaptionPrompt').attr('value')});
		$('#fileCaptionPrompt').attr({'value':''});
		obj.addFile(elem);
	},

	fileCaptionCancel:function(elem) {
		var obj = this;
		$('div.fileCaptionPrompt').css({'display':'none'});
		$('#fileID_' + obj.iter).remove();
		$('#fileCaptionPrompt').attr({'value':''});
		
		$('#itemTextSubtitle').focus();
		
		obj.attachFile();
	},
	
	addFile:function() {
		var obj = this;
		var num = obj.iter
		$(obj.attMsgIdent).append('<p id="fileRef_' + obj.iter + '" class="fileRef">' + obj.shortFileVal($('#fileID_' + obj.iter).attr('value')) +' <span>[<a href="#">&nbsp;remove&nbsp;</a>]</span></p>');
		$('p#fileRef_' + obj.iter + ' a').click(function(e){
			e.preventDefault();
			obj.removeFile(num);
		});
		$('#fileID_' + num).parent().css({ 'position': 'absolute', 'left' : -9999 });
		
		
		$('#itemTextSubtitle').focus();
		
		obj.iter++;
		obj.fileCount++;
		obj.showMessages();
		obj.attachFile();
	},
	
	// required to prevent IE6 outputting the entire file path
	shortFileVal:function(val) {
	
		var output = val.split('\\');
		return output[output.length-1];
	
	},
	
	removeFile:function(num) {
		var obj = this;
		$('p#fileRef_' + num).remove();
		$('#fileID_' + num).parent().remove();
		
		obj.fileCount--;
		obj.showMessages();
		obj.attachFile();
	},
	
	attachValidation:function() {
		var obj = this;
		$('#ugcForm').validate({
			rules: {
				itemTextSubtitle: "required",
				itemText: "required"
			},
			messages: {
				itemTextSubtitle: "You must add a title for your comment",
				itemText: "You must enter a comment"
			},
			
			submitHandler: function(form) {
				obj.attachSubmitProc(form);
			}			
			
		});	
	
	},
	
	attachSubmitProc:function(form) {

		var obj = this;
		// rename file input elements and submit form
		var inc = 1;
		$(obj.msgIdent + ' span').each(function(s, e) {
			if($(e).find('input[type=file]').length > 0 && $(e).find('input[type=file]').eq(0).attr('id') != '') {
				$(e).find('input[type=file]').eq(0).attr({
					'id':'imageItem_' + inc,
					'name':'imageItem_' + inc
				})
				$(e).find('input[type=hidden]').eq(0).attr({
					'id':'imageItemCaption_' + inc,
					'name':'imageItemCaption_' + inc
				})
				inc++;
			}
		});
		form.submit();
	}
}




						
$(document).ready(function() {
	getMatchArticleUGC.init();
});

// ########################################################################
// algorithm required to resize images to best fit at ratio specified
// ########################################################################

function sizeImages(imgX, imgY, maxX, maxY) {

	var maxWidth = parseInt(maxX, 10), maxHeight = parseInt(maxY, 10);
	var w = parseInt(imgX, 10), h = parseInt(imgY, 10);
	var output = new Array();
	var ratio = parseInt(w, 10) / parseInt(h, 10);
	
	w = maxWidth;
	h = Math.floor(maxWidth / ratio);
	
	if(h > maxHeight) {
		h = maxHeight;
		w = Math.floor(maxHeight * ratio);
	}
	
	output['h'] = h;
	output['w'] = w;
	return output;
}

var getMatchArticleUGC = {
	
	ugc: new Array(),
	xml: false,
	artID: false,
	version: false,
	jumpto: false,
	
	// paging data
	totalPages:1, 			// defaults to 1, set below
	startResultOffset: 0, 	// starting record to display - zero indexed
	batchSizes: 10,			// how many records to show per batch - currently hard coded
	totalResults: 0,		// size returned from xml
	currentPage: 1,			// defaults to 1, set below
	commentClosed: 'N',		// show/hide link to comments
	
	init:function(offset, jumpto) {
		var obj = this;
		if($('div.ugcData').length < 1) return;
		obj.artID = $('div.ugcData .aID').eq(0).html();
		obj.version = $('div.ugcData .aVrs').eq(0).html();
		obj.commentClosed = $('div.ugcData .closedComments').eq(0).html();
		obj.startResultOffset = (!offset ? obj.startResultOffset : offset);
		obj.jumpto = (!jumpto ? obj.jumpto : jumpto);
		
		if($('#ugcMatch').length < 1) { $('div.matchReportTop').eq(0).after('<div id="ugcMatch" class="ugcMatch"><div id="ugcMatchLoader"><div class="text"><p>Loading comments, please wait...</p></div><div class="loader"><img src="/static-images/ajax-loader.gif"/></div></div></div>'); }
		
		$.ajax({
			type: "GET",
			url: '/ajax/article-uploads/' + obj.artID + '-' + obj.startResultOffset + '-10/',
			dataType: "xml",
			success: function(xml){ 
				obj.xml = xml;
				obj.proc(); 
			},
			error: function(){
				$('#ucgMatch').eq(0).remove(); // currently don't show anything if the xml can't be retrieved
			}
		});
	},
	
	proc:function() {
		var obj = this, outputHTML = '';
		if($(obj.xml).find('upload').length < 1) {
			if(obj.commentClosed == 'Y') {
				$('#ugcMatch').eq(0).remove();
				return;
			} else {
				obj.outputFristPsot();
				return;
			}
		}
		obj.populateResultsTotal();
		obj.doHTML();
		obj.ugcLightbox();
	},
	
	populateResultsTotal:function() {
		var obj = this;
		obj.totalResults = $(obj.xml).find('page').attr('totalCount');
		obj.totalPages = Math.ceil( obj.totalResults/obj.batchSizes );
		obj.currentPage = Math.ceil((parseInt(obj.startResultOffset, 10)+1)/10);
	},
	
	// if ugc is allowed but there are no posts yet, show just the link
	outputFristPsot:function() {
	
		var obj = this, output = '';
		
		output += '<div class="matchReportTop">';
		output += '    <div class="top clrNM">';
		output += '        <h3>Leave your comments</h3>';
		output += '        <p>There are currently no comments for this article. </p><a class="leaveCommentsBtn" href="/user-content/match-report/?articleVersionId=' + obj.version + '">Leave us your comments</a>';
		output += '    </div>';
		output += '    <span class="bottom">&nbsp;</span>';
		output += '</div>';
		$('#ugcMatch').html(output);
		
	},
	
	doHTML:function(xml) {
		var obj = this, output = '';
		
		output += '    <div class="ugcPanelTop">&nbsp;</div>';
		output += '    <div class="ugcPanelMid">';
		output += '        <div class="ugcPanelInner">';
		output += '            <div class="title clrNM">';
		output +=                  obj.createPagination();
		output += '                <h2>Your comments...</h2>';
		output += '            </div>';
		
		$(obj.xml).find('upload').each(function(s, e) {
			
			output += '        <div class="div">&nbsp;</div>';
			output += '        <div class="comment">';
			output += '            <div class="title clrNM"><h3><strong>' + $(e).find('uploadItem[subtype=text]').eq(0).find('subtitle').eq(0).text() + '</strong></h3><p class="ugcObjectElem"><a href="/user-content/raise-objection/?uploadId=' + $(e).attr('id') + '">Report this comment</a></p></div>';
			output += '            <p><strong>' + obj.returnUser(e) + '</strong> said <span class="commentTime">' + obj.returnDate($(e).attr('creationTimestamp')) + '</span>:</p>';
			output += '            <p>' + $(e).find('uploadItem[subtype=text]').eq(0).find('text').eq(0).text()  + '</p>';
			
			if($(e).find('uploadItem[subtype=image]').eq(0).find('url').length > 0) {
				output += '<div class="images ugcLBox">';
				$(e).find('uploadItem[subtype=image]').find('url').each(function(t, img) {
					output += '<a href="/' + $(img).text() + '" class="image" rel="ugcImg" title="' + replaceQuotes($(img).parent().find('subtitle').eq(0).text()) + '"><img src="/' + obj.generateThumbLink($(img).text()) + '" title="' + replaceQuotes($(img).parent().find('subtitle').eq(0).text()) + '" alt="' + replaceQuotes($(img).parent().find('subtitle').eq(0).text()) + '" height="100" width="100" /></a>';
				});
				output += '</div>';
			}
			output += '        </div>';
		});
		
		output += '            <div class="div">&nbsp;</div>';
		
		output += '            <div class="links clrNM">';
		output += obj.createPagination();
		if(obj.commentClosed != 'Y') {
			output += '            <p><a href="/user-content/match-report/?articleVersionId=' + obj.version + '" class="ugcCommentLink"><span>Leave your comments on this match</span></a>(you must be logged in to comment)</p>';
		} else {
			output += '            <p>Comments for this page have now been closed</p>';
		}
		output += '            </div>';
		
		output += '            <div class="div">&nbsp;</div>';
		output += '        </div>';
		output += '    </div>';
		output += '    <div class="ugcPanelBottom">&nbsp;</div>';
		
		$('#ugcMatch').html(output);
		
		// add click events to pagination controls
		$('div.ugcPagingLinks li a').click(function(e) {
			e.preventDefault();
			$('#ugcMatch').eq(0).remove();
			var batch = $(this).attr('class').split('getResultsSet_')[1];
			getMatchArticleUGC.init(batch, true);
		});
		
		// add click event to comment link
		$('#ugcMatch a.ugcCommentLink').click(function(e) {
			obj.redirectWithCookie($(this).attr('href'), e);
		});

		// add click event to objection link
		$('#ugcMatch p.ugcObjectElem a').click(function(e) {
			obj.redirectWithCookie($(this).attr('href'), e);
		});
		
		
		if(obj.jumpto != false) { window.location.hash = 'ugcMatch'; }
	},
	
	redirectWithCookie:function(url, elem) {
			elem.preventDefault();
			// store cookie for redirect later
			$.cookie("ugcReturnPage", null);
			$.cookie("ugcReturnPage", location.href, { path: '/' }); // ensures no existing cookie, path must be explicit
			location.href = url;	
	},

	createPagination:function() {
		
		var obj = this, output = '';
		if(obj.totalPages < 2) { return ''; }
		
		output += '<div class="ugcPagingLinks">';
		output += '<ul>';
		
		for(var i = 0; i < obj.totalPages; i++) {
			output += (obj.currentPage == (i+1) ? '<li class="selected">' + (i+1) + '</li>' : '<li><a href="#" class="getResultsSet_' + i*parseInt(obj.batchSizes, 10) + '">' + (i+1) + '</a></li>');
		}
		
		output += '</ul>';
		output += '</div>';								
		return output;
	},
	
	returnTitle:function(elem) {
		var title = $(elem).find('uploadItem[subtype=text] subtitle').eq(0).text();
		return title;
	},
	
	ugcLightbox:function() {
		$('#ugcMatch div.ugcLBox').each(function(s, e) {
			$(e).find('a[rel="ugcImg"]').colorbox({transition:'fade', speed:500, current:''});
		});
	},
	
	generateThumbLink:function(link) {
		return link.replace("/original/", "/thumb/");
	},
	
	returnUser:function(elem) {
		var user = $(elem).find('registrantName').eq(0).text();
		return (!user ? 'Anonymous' : user);
	},
	
	returnDate:function(ts) {
		var obj = this;
		var ugcDate = new Date();
		ugcDate.setTime(ts*1000);
		if(!ugcDate) { return; }									
		else {
			var dayName = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
			var monthName = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
			var output = '(on ' + dayName[ugcDate.getDay()] + ' ' + obj.nicelyFormatDate(ugcDate.getDate()) + ' ' + monthName[ugcDate.getMonth()] + ', ' + ugcDate.getFullYear() + ' at ' + obj.formatTime(ugcDate.getHours(), ugcDate.getMinutes()) + ')';
			return output;
		}
	},
	
	nicelyFormatDate:function(d) {
		if(d == 1 || d == 21 || d == 31) { return d + 'st'; }
		else if (d == 2 || d == 22) { return d + 'nd'; }
		else if (d == 3 || d == 23) { return (d + 'rd'); }
		else { return (d + 'th'); }
	},
	
	formatTime:function(hours, minutes) {
		var meridian = 'am';
		if(hours == 0) {
			hours = 12;
		} else if (hours > 11) {
			meridian = 'pm';
			if(hours > 12) {
				hours = (hours - 12);
			}
		}
		// add leading zero to minutes
		minutes = ''+minutes;
		if(minutes.length < 2) { minutes = '0' + minutes; }
		return hours + ':' + minutes + meridian;
	}
}
	

// output link back to original ugc page
$(document).ready(function() {
	if($('div.ugcReturnOutput').length > 0 && $.cookie("ugcReturnPage") != null) {
		$('div.ugcReturnOutput').css({'display':'block'});
		$('div.ugcReturnOutput').html('<p><a href="' + $.cookie("ugcReturnPage") + '">Return to your original page</a></p>');
		$.cookie("ugcReturnPage", null, { path: '/' });
	}
});

// TO DO - escape single/double quotes
function replaceQuotes(str) {
	var regexp = new RegExp(/\"/g);
	str = str.replace(regexp, '&quot;');
	var regexp = new RegExp(/\'/g);
	str = str.replace(regexp, '&#39;');
	return str;
}
