/**
 *	CBC Radio Concerts on Demand Concert Finder class and Reviews Controller
 *	Also contains the codSpawn function
 *
 *	@author		gordongroup marketing + communications
 *	@link		<http://gordongroup.com>
 */


/**
 *	Radio Concert Player Scripts
 */
function codSpawn(mediaFile, concertName, trackName){
	var fullURL = "http://www.cbc.ca/radio2/cod/codPlayer.html?"+mediaFile+"#"+concertName+"|"+trackName;
	window.open(fullURL, "codWindow", "location=0,menubar=0,resizable=0,width=470,height=200").focus();
} // END FUNCTION: codSpawn


/**
 *	Function class for manipulating the concert finder
 */
function ConcertFinder(){

	/**
	 *	Holds the controller to remove when mod-rewrite isn't active
	 *
	 *	@access	public
	 *	@var	string
	 */
	this.controller = '';	// index.php?/
	
	/**
	 *	Holds the next page to load with ajax
	 *
	 *	@access	public
	 *	@var	int
	 */
	this.page = 1;
	
	/**
	 *	Holds the total number of pages
	 *
	 *	@access	public
	 *	@var	int
	 */
	this.total = 2;
	
	/**
	 *	Whether the values have been updated by Ajax or not
	 *
	 *	@access	public
	 *	@var	bool
	 */
	this.updated = false;
	
	/**
	 *	Holds the current genre
	 *
	 *	@access	public
	 *	@var	string
	 */
	this.genre = '';
	
	/**
	 *	Holds reference to the ajax search time-out
	 *
	 *	@access	public
	 *	@var	object
	 */
	this.timeout = '';
	
	/**
	 *	Holds the current Xhr object, so that filters requests can be aborted before starting another
	 *
	 *	@access	public
	 *	@var	object
	 */
	this.xhr = null;
	
	/**
	 *	Holds the Xhr request Ids, all requests are assigned Ids for proper event attachment
	 *
	 *	@access	public
	 *	@var	int
	 */
	this.xhrId = -1;
	
	
	/**
	 *	Sets up the th's so they can be re-ordered all Ajax like
	 *
	 *	@access	public
	 *	@return	void
	 */
	this.setup = function(){
		
		if( $('#finder').length > 0 ){

			$('table#concertFinderHeaders thead th a').click(
				function(){
					return concertFinder.resort( $(this).attr('href') );
				}
			);

			$('div#filter input#filter-submit').hide(1);

			$('div#filter select').change(
				function(){
					concertFinder.resortGenres();
					return false;
				}
			);
		
			$('div#filter form').submit(
				function(){
					concertFinder.resortGenres();
					return false;
				}
			);
		
			$('#filter-keyword').keypress(
				function(){
					clearTimeout( concertFinder.timeout );
					concertFinder.timeout = setTimeout( 'concertFinder.resortGenres()', 850 );
				}
			);

			$('div.pager ul').hide(1);
		
			// Check if a genre is displayed, and set it as the fetch point
			var regex = /\/genres\/([\w-,&]+)\/?/;
			var theLocation = window.location;
			var matches = regex.exec(theLocation);
			if( matches && matches[1] ){
				concertFinder.genre = matches[1];
			}
		
			$('div#finderWrapper').scroll(
				function(){
					var scrollTop = document.getElementById('finderWrapper').scrollTop;
					var scrollHeight = document.getElementById('finderWrapper').scrollHeight - document.getElementById('finderWrapper').offsetHeight;
					if( scrollTop >= scrollHeight ){
						concertFinder.fetch();
					}
				}
			);
		}
		
		if( $('ul#concert-gallery li a').length > 0 ){
			$('ul#concert-gallery li a').lightBox(
				{
					overlayBgColor: '#000',
					overlayOpacity: 0.6,
					imageLoading: 'images/lightbox/ajax-loader.gif',
					imageBtnClose: 'images/lightbox/close.gif',
					imageBtnPrev: 'images/lightbox/prev.gif',
					imageBtnNext: 'images/lightbox/next.gif',
					containerResizeSpeed: 10
				}
			);
		}
		
		if( $('.listing-numbered tbody tr td a').length > 0 ){
			$('.listing-numbered tbody tr td a').click(
				function(){
					var id = $(this).attr('class').replace( /media-/, 'title-' );
					codSpawn( $(this).attr('href'), $('#'+id).html(), $(this).text() );
					return false;
				}
			);
		}
		
		$('.play a').click(
			function(){
				var id = $(this).attr('class').replace( /media-/, 'title-' );
				codSpawn( $(this).attr('href'), $('#'+id).html(), $(this).text() );
				return false;
			}
		);
		
	}; // END PROPERTY: setup
	

	/**
	 *	Fetches more results for the table
	 *	
	 *	@access	public
	 *	@return false
	 */
	this.fetch = function(){
		
		concertFinder.page = parseInt(concertFinder.page);
		concertFinder.total = parseInt(concertFinder.total);
		var filter = concertFinder.getFilter();
		
		if( concertFinder.page < concertFinder.total ){
			
			concertFinder.page++;
			
			if( concertFinder.updated ){
				$('#finderOuterWrapper').append( '<div class="corner-loader" tabindex="-1"><span>Loading page '+concertFinder.page+' of '+concertFinder.total+'&#8230;</span></div>' );
			}else{
				$('#finderOuterWrapper').append( '<div class="corner-loader" tabindex="-1"><span>Loading&#8230;</span></div>' );				
			}
			$('.corner-loader').focus();
			
			if( concertFinder.genre != '' ){
				var theUrl = 'ajax.php?/'+filter+'genres/'+concertFinder.genre+'/'+concertFinder.page+'/';
			}else{
				var theUrl = 'ajax.php?/'+filter+concertFinder.page+'/';
			}

			$.ajax({
			    url: theUrl,
			    type: 'GET',
			    dataType: 'json',
			    timeout: 45000,
			    error: function( XMLHttpRequest, textStatus, errorThrown ){
					concertFinder.page--;
					$('#concertFinderHeaders').fadeTo( 'medium', 0.3 );
					$('#finderWrapper').fadeTo( 'medium', 0.3 );
					$('#finderOuterWrapper').append( '<div class="ajax-error" tabindex="-1"><p>Sorry there was an error retrieving the next page.<br /><br /><strong><a href="#" id="try-again">Try Again</a></strong> or <strong><a href="#" id="cancel">Cancel</a></strong></p></div>' );
						$('#try-again').click(
							function(){
								concertFinder.cancel(false);
								concertFinder.fetch();
								return false;
							}
						);
						$('#cancel').click(
							function(){
								concertFinder.cancel(false);
								return false;
							}
						);
					var position = ( $('#finderOuterWrapper').height() / 2 ) - ( $('.ajax-error').height() / 2 ) - 30;
					$('.ajax-error').css('top',position);
					$('.ajax-error').focus();
					$('.corner-loader').remove();
			    },
			    success: function(json){
					concertFinder.updated = true;
			        concertFinder.appendTBody(json);
					$('.corner-loader').remove();
					document.getElementById('finderWrapper').scrollTop = document.getElementById('finderWrapper').scrollTop - 1;
			    }
			});

		}
		
		return false;
		
	}; // END PROPERTY: fetch	


	/**
	 *	Resorts the table based on what Url it is passed
	 *	
	 *	@access	public
	 *	@param	string	p_href	The href to sort against
	 *	@return false
	 */
	this.resort = function( p_href ){

		var theHref = p_href.replace( concertFinder.controller, '' );
		theHref = theHref.replace( /filter\/.+?\//, '' );
		var segments = theHref.split('/');
		var filter = concertFinder.getFilter();
		if( segments[0] == 'genres' ){

			var sortOrder = segments[3].split(',');
			var href = concertFinder.controller+'genres/'+segments[1]+'/'+segments[2]+'/'+sortOrder[0]+','+concertFinder.reverseOrder( sortOrder[1] );

			$('#'+sortOrder[0]+' a').append( ' <strong class="sort-loader"><!-- --></strong>' );
			$('#'+sortOrder[0]).addClass('sorted-loading');
			$('#finderWrapper').fadeTo( 'medium', 0.3 );
			
			var theUrl = 'ajax.php?/'+filter+'genres/'+segments[1]+'/1/'+sortOrder[0]+','+sortOrder[1];
			
			$.ajax({
			    url: theUrl,
			    type: 'GET',
			    dataType: 'json',
			    timeout: 45000,
			    error: function( XMLHttpRequest, textStatus, errorThrown ){
					$('.sort-loader').remove();
					$('#finder table th').removeClass('sorted-loading');
					$('#finderWrapper').fadeTo( 'medium', 0.3 );
					$('#finderOuterWrapper').append( '<div class="ajax-error" tabindex="-1"><p>Sorry there was an error sorting the column.<br /><br /><strong><a href="'+p_href+'" id="try-again">Try Again</a></strong> or <strong><a href="#" id="cancel">Cancel</a></strong></p></div>' );
						$('#try-again').click(
							function(){
								concertFinder.cancel(false);
								concertFinder.resort(p_href);
								return false;
							}
						);
						$('#cancel').click(
							function(){
								concertFinder.cancel(false);
								return false;
							}
						);
					var position = ( $('#finderOuterWrapper').height() / 2 ) - ( $('.ajax-error').height() / 2 ) - 30;
					$('.ajax-error').css('top',position);
					$('.ajax-error').focus();
			    },
			    success: function(json){
					$('.sort-loader').remove();
					$('#finder table th').removeClass('sorted-loading');
					$('#finderWrapper').fadeTo( 'medium', 1 );
			        concertFinder.replaceTBody(json);
					document.getElementById('finderWrapper').scrollTop = 0;
			    }
			});
			
		}else{
			
			var sortOrder = segments[1].split(',');
			var href = concertFinder.controller+segments[0]+'/'+sortOrder[0]+','+concertFinder.reverseOrder( sortOrder[1] );

			$('#'+sortOrder[0]+' a').append( ' <strong class="sort-loader"><!-- --></strong>' );
			$('#'+sortOrder[0]).addClass('sorted-loading');
			$('#finderWrapper').fadeTo( 'medium', 0.3 );
			
			var theUrl = 'ajax.php?/'+filter+'1/'+sortOrder[0]+','+sortOrder[1];
			
			$.ajax({
			    url: theUrl,
			    type: 'GET',
			    dataType: 'json',
			    timeout: 45000,
			    error: function( XMLHttpRequest, textStatus, errorThrown ){
					$('.sort-loader').remove();
					$('#finder table th').removeClass('sorted-loading');
					$('#finderWrapper').fadeTo( 'medium', 0.3 );
					$('#finderOuterWrapper').append( '<div class="ajax-error" tabindex="-1"><p>Sorry there was an error sorting the column.<br /><br /><strong><a href="'+p_href+'" id="try-again">Try Again</a></strong> or <strong><a href="#" id="cancel">Cancel</a></strong></p></div>' );
						$('#try-again').click(
							function(){
								concertFinder.cancel(false);
								concertFinder.resort(p_href);
								return false;
							}
						);
						$('#cancel').click(
							function(){
								concertFinder.cancel(false);
								return false;
							}
						);
					var position = ( $('#finderOuterWrapper').height() / 2 ) - ( $('.ajax-error').height() / 2 ) - 30;
					$('.ajax-error').css('top',position);
					$('.ajax-error').focus();
			    },
			    success: function(json){
					$('.sort-loader').remove();
					$('#finder table th').removeClass('sorted-loading');
					$('#finderWrapper').fadeTo( 'medium', 1 );
			        concertFinder.replaceTBody(json);
					document.getElementById('finderWrapper').scrollTop = 0;
			    }
			});
			
		}
		
		concertFinder.changeProperties( sortOrder[0], sortOrder[1], href );
		
		return false;
		
	}; // END PROPERTY: resort
	

	/**
	 *	Resorts the table based on what Url it is passed
	 *	
	 *	@access	public
	 *	@param	string	p_href	The href to sort against
	 *	@return false
	 */
	this.resortGenres = function(){
		
		clearTimeout( concertFinder.timeout );
		
		var p_href = $('div#filter select').attr('value');
		var theHref = p_href.replace( concertFinder.controller, '' );
		var segments = theHref.split('/');
		var filter = concertFinder.getFilter();
		
		this.xhrId++;
		if( this.xhr ){
			this.xhr.abort();
		}
				
		$('#concertFinderHeaders').fadeTo( 'medium', 0.3 );
		$('#finderWrapper').fadeTo( 'medium', 0.3 );
		$('#finderOuterWrapper').append( '<div class="genre-loader" tabindex="-1"><p><strong>Please wait a moment while the concerts load&#8230;</strong></p></div>' );
		var loaderPosition = ( $('#finderOuterWrapper').height() / 2 ) - ( $('.genre-loader').height() / 2 ) - 30;
		$('.genre-loader').css('top',loaderPosition);
		
		if( filter == '' ){
			$('.genre-loader').focus();
		}
		
		if( segments[0] == 'genres' ){
			
			concertFinder.genre = segments[1];
			var theUrl = 'ajax.php?/'+filter+'genres/'+segments[1]+'/';
			
			this.xhr = $.ajax({
				id: this.xhrId,
		    	url: theUrl,
			    type: 'GET',
			    dataType: 'json',
			    timeout: 45000,
			    error: function( XMLHttpRequest, textStatus, errorThrown ){
					// Confirm there hasn't been another Ajax request started after this one
					if( this.id == concertFinder.xhrId ){
						$('.genre-loader').remove();
						$('#finderWrapper').fadeTo( 'medium', 0.3 );
						$('#finderOuterWrapper').append( '<div class="ajax-error" tabindex="-1"><p>Sorry there was an error loading the concerts.<br /><br /><strong><a href="'+p_href+'" id="try-again-'+this.id+'">Try Again</a></strong> or <strong><a href="#" id="cancel-'+this.id+'">Cancel</a></strong></p></div>' );
							$( '#try-again-'+this.id ).click(
								function(){
									concertFinder.cancel(false);
									concertFinder.resortGenres();
									return false;
								}
							);
							$( '#cancel-'+this.id ).click(
								function(){
									concertFinder.cancel(false);
									return false;
								}
							);
						var position = ( $('#finderOuterWrapper').height() / 2 ) - ( $('.ajax-error').height() / 2 ) - 30;
						$('.ajax-error').css('top',position);
						$('.ajax-error').focus();
					}
			    },
			    success: function(json){
			        concertFinder.replaceTBody(json);
					$('#results').colorBlend([{param:"color", fromColor:"#ffffff", toColor:"#638ebd", duration:1000, cycles:2}]);
					$('.genre-loader').remove();
					$('#finderWrapper').fadeTo( 'medium', 1 );
					$('#concertFinderHeaders').fadeTo( 'medium', 1 );
				
					$('table#concertFinderHeaders th a').each( function(){
						var href = $(this).attr('href');
						href = href.replace( concertFinder.controller, '' );
						href = href.replace( /filter\/.+?\//, '' );
						href = href.split('/');
						if( href[0] == 'genres' ){
							$(this).attr( 'href', concertFinder.controller+filter+'genres/'+segments[1]+'/'+href[2]+'/'+href[3] );
						}else{
							var link = $(this).attr('href');
							link = link.replace( concertFinder.controller, '' );
							link = link.replace( /filter\/.+?\//, '' );
							$(this).attr( 'href', concertFinder.controller+filter+'genres/'+segments[1]+'/'+link );
						}
					} );
		
					$('table#concertFinderHeaders thead th a').click( function(){ return concertFinder.resort( $(this).attr('href') ) } );
					document.getElementById('finderWrapper').scrollTop = 0;
				
			    }
			});
			
		}else{

			concertFinder.genre = '';
			var theUrl = 'ajax.php?/'+filter+'1/';
			
			this.xhr = $.ajax({
				id: this.xhrId,
			    url: theUrl,
			    type: 'GET',
			    dataType: 'json',
			    timeout: 45000,
			    error: function( XMLHttpRequest, textStatus, errorThrown ){
					// Confirm there hasn't been another Ajax request started after this one
					if( this.id == concertFinder.xhrId ){
						$('.genre-loader').remove();
						$('#finderWrapper').fadeTo( 'medium', 0.3 );
						$('#finderOuterWrapper').append( '<div class="ajax-error" tabindex="-1"><p>Sorry there was an error loading the concerts.<br /><br /><strong><a href="'+p_href+'" id="try-again-'+this.id+'">Try Again</a></strong> or <strong><a href="#" id="cancel-'+this.id+'">Cancel</a></strong></p></div>' );
							$( '#try-again-'+this.id ).click(
								function(){
									concertFinder.cancel(false);
									concertFinder.resortGenres();
									return false;
								}
							);
							$( '#cancel-'+this.id ).click(
								function(){
									concertFinder.cancel(false);
									return false;
								}
							);
						var position = ( $('#finderOuterWrapper').height() / 2 ) - ( $('.ajax-error').height() / 2 ) - 30;
						$('.ajax-error').css('top',position);
						$('.ajax-error').focus();
					}
			    },
			    success: function(json){
			        concertFinder.replaceTBody(json);
					$('#results').colorBlend([{param:"color", fromColor:"#ffffff", toColor:"#638ebd", duration:1000, cycles:2}]);
					$('.genre-loader').remove();
					$('#finderWrapper').fadeTo( 'medium', 1 );
					$('#concertFinderHeaders').fadeTo( 'medium', 1 );
				
					$('table#concertFinderHeaders th a').each( function(){
						var link = $(this).attr('href');
						link = link.replace( concertFinder.controller, '' );
						link = link.replace( /filter\/.+?\//, '' );
						var href = link.split('/');
						if( href[0] == 'genres' ){
							$(this).attr( 'href', concertFinder.controller+filter+href[2]+'/'+href[3] );
						}else{
							$(this).attr( 'href', concertFinder.controller+filter+href[0]+'/'+href[1] );
						}
					} );
				
					document.getElementById('finderWrapper').scrollTop = 0;
				
			    }
			});
			
		}
		
	}; // END PROPERTY: resortGenres
	
	
	/**
	 *	Reads the filter input and returns its value escaped or blank
	 *
	 *	@access	public
	 *	@return	string
	 */
	this.getFilter = function(){
		
		var keywords = $.trim( $('#filter-keyword').attr('value') );
		if( keywords != '' ){
			keywords = keywords.replace(' ', '+');
			keywords = keywords.toLowerCase();
			keywords = 'filter/'+keywords+'/';
		}else{
			keywords = '';
		}
		return keywords;
		
	} // END PROPERTY: getFilter
	
	
	/**
	 *	Replaces the tbody with new content
	 *	
	 *	@access	public
	 *	@param	object	p_json	the json response
	 *	@return	void
	 */
	this.replaceTBody = function( p_json ){
		
		var total = p_json.total;
		if( total <= 0 ){ total = '0'; }
		concertFinder.total = p_json.pages.total;
		concertFinder.page = p_json.pages.current;
		$('#results strong').html( total );
		var body = p_json.body.replace( /\"/, '"' );
		$('table#concertFinder tbody').html( body );
		$('table#concertFinder tbody tr:first-child td:first-child a').focus();
		
	}; // END PROPERTY: replaceTBody
	
	
	/**
	 *	Appends to the tbody with new content
	 *	
	 *	@access	public
	 *	@param	object	p_json	the json response
	 *	@return	void
	 */
	this.appendTBody = function( p_json ){
		
		concertFinder.total = p_json.pages.total;
		concertFinder.page = p_json.pages.current;
		var perPage = p_json.pages.perPage;
		var child = perPage * ( concertFinder.page - 1 ) + 1;
		var body = p_json.body.replace( /\"/, '"' );
		$('table#concertFinder tbody').append( body );
		$('table#concertFinder tbody tr:nth-child('+child+') td:first-child a').focus();
		
	}; // END PROPERTY: appendTBody
	
	
	/**
	 *	Switches between ascending and descending
	 *
	 *	@access	public
	 *	@param	string	p_order	The order to reverse
	 *	@return	string
	 */
	this.reverseOrder = function( p_order ){
		
		var order = 'ascending';
		if( p_order == 'ascending' ){ order = 'descending'; }
		
		return order;
		
	}; // END PROPERTY: reverseOrder
	
	
	/**
	 *	Closes the Ajax error dialogue
	 *
	 *	@access	public
	 *	@param	bool	p_fade
	 *	@return	string
	 */
	this.cancel = function( p_fade ){
		
		$('.ajax-error').remove();
		$('#filter-keyword').attr( 'value', '' );
		if( p_fade!=true ){
			$('#concertFinderHeaders').fadeTo( 'medium', 1 );
			$('#finderWrapper').fadeTo( 'medium', 1 );
		}
		
	}; // END PROPERTY: cancel
	
	
	/**
	 *	Changes the properties for the table headings
	 *
	 *	@access	public
	 *	@param	string	p_id	The id of the th element to change
	 *	@param	string	p_order	The order to display
	 *	@param	string	p_href	The new href for the link
	 *	@return	void
	 */
	this.changeProperties = function( p_id, p_order, p_href ){
		
		$('table#concertFinderHeaders th span').remove();
		$('table#concertFinderHeaders th').removeClass( 'sorted-'+p_order );
		$('table#concertFinderHeaders th').removeClass( 'sorted-'+concertFinder.reverseOrder(p_order) );

		$('table#concertFinder colgroup col').removeClass( 'active' );
		$('#col-'+p_id).addClass( 'active' );
		
		$('#'+p_id+' a').append('<span> (sorted '+p_order+')</span>');
		$('#'+p_id+' a').attr( 'href', p_href );
		$('#'+p_id+' a').unbind();
		$('#'+p_id+' a').click( function(){ return concertFinder.resort( $(this).attr('href') ) } );
		$('#'+p_id).addClass( 'sorted-'+p_order );
		$('#'+p_id).removeClass( 'sorted-'+concertFinder.reverseOrder(p_order) );
		
	}; // END PROPERTY: changeProperties
	
} // END CLASS


/**
 *	HTML template for the overall review
 *	Used for adding the average review to the top of the sidebar when there are reviews
 */
var overallTemplateReviews = '<h3>Overall Concert Rating</h3><img src="images/stars/stars-{starNumber}.gif" width="69" height="12" alt="{starNumber} Star(s)" /><ul><li class="read"><a href="{anchorPath}#readReviews">Read reviews</a></li><li class="review"><a href="{anchorPath}#addReview">Review this concert</a></li></ul><hr class="newbox" />';

/**
 *	HTML template for the overall review
 *	Used for adding the average review to the top of the sidebar when there are no reviews
 */
var overallTemplateNoReviews = '<h3>Overall Concert Rating</h3><p><a href="{anchorPath}#addReview">Be the first to review this concert</a></p><hr class="newbox" />';


/**
 *	Class for mainpulating the Pluck Reviews
 */
function ConcertReviews(){
	
	/**
	 *	Submits the concert review to the Pluck system
	 *	
	 *	@access	public
	 *	@param	string	uniqKey
	 *	@return	void
	 */
	this.reviewArticle = function( uniqKey ){
		
		var articleKey = new ArticleKey(uniqKey);
		var rating = StarRating.rating;
		var body = document.getElementById('reviewBody').value;
		
		$('.validation-error').remove();
		
		var valid = true;
		if( rating <= 0 || rating > 5 ){
			valid = false;
			$('.rating-wrapper label').after( '<p class="validation-error">Please select a rating between 1 and 5 stars.</p>' );
		}
		
		if( body == '' ){
			valid = false;
			$('.comments-wrapper label').after( '<p class="validation-error">Please enter a comment.</p>' );
		}
		
		if( body.length > 2500 ){
			valid = false;
			$('.comments-wrapper label').after( '<p class="validation-error">The comments must not exceed 2500 characters in length.</p>' );
		}
		
		if( valid ){
			body = body.substr( 0, 2500 );

			$('#reviewSubmit').attr('disabled','true');
			$('#reviewBody').attr('disabled','true');
			StarRating.disable();
		
			var requestBatch = new RequestBatch();
			var reviewAction = new ReviewAction( articleKey, document.location.href, document.title, '<span></span>', rating, body, '', '' );
			requestBatch.AddToRequest(reviewAction);
			requestBatch.BeginRequest( serverUrl, concertReviews.reviewSubmitted );
		}
		
	}; // END PROPERTY: reviewArticle


	/**
	 *	Confirms that the review was submitted
	 *
	 *	@access	public
	 *	@param	object	responseBatch
	 *	@return	void
	 */
	this.reviewSubmitted = function( responseBatch ){
		
		if( responseBatch.Messages[0].Message == 'ok' ){
			$('form.addReview').remove();
			$('#reviewMessage').html( '<p><strong>Thanks, your review has been submitted and is pending approval.</strong></p>' );
		}else{
			$('#reviewSubmit').attr('disabled','true');
			$('#reviewBody').attr('disabled','true');
			StarRating.disable();
		}
		
	}; // END PROPERTY: reviewSubmitted
	
	
	/**
	 *	Gets the average review
	 *
	 *	@access	public
	 *	@param	string	uniqKey
	 *	@return	void
	 */
	this.getAverageReview = function( uniqKey ){
		
		var requestBatch = new RequestBatch();
		var articleKey = new ArticleKey(uniqKey);
		var reviewPage = new ReviewPage( articleKey, 10, 1, "TimeStampDescending" );
		requestBatch.AddToRequest(reviewPage);
		requestBatch.BeginRequest( serverUrl, concertReviews.renderAverageReview );
		
	}; // END PROPERTY: getAverageReview
	
	
	/**
	 *	Gets the average review and displays it on the page
	 *	Also displays the total number of reviews in the review panel near the bottom
	 *
	 *	@access	public
	 *	@param	object	responseBatch
	 *	@return	void
	 */
	this.renderAverageReview = function( responseBatch ){
		
		var response = responseBatch.Responses[0];
		var reviewPage = response.ReviewPage;
		var averageReview = Math.round( reviewPage.AverageReviewRating );
		
		if( averageReview <= 0 ){
			overallTemplate = overallTemplateNoReviews;
		}else{
			overallTemplate = overallTemplateReviews;			
		}
		overallTemplate = overallTemplate.replace( /{starNumber}/g, averageReview );
		overallTemplate = overallTemplate.replace( /{anchorPath}/g, anchorPath );
		
		
		$('.average-review').html( overallTemplate );
		
		if( averageReview == 0 ){
			$('#Reviews_Container').remove();
			$('.review-jump').remove();
			$('.review-sep').remove();	
			$('.review-total').remove();
		}
		
		// Add the number of reviews to the review block
		$('.review-total span').html( reviewPage.NumberOfReviews );
		
	}; // END PROPERTY: renderAverageReview

} // END CLASS


/**
 *	Controls the star rating widget
 *	Holds the currently chosen rating as a property to be access publicly
 */
var StarRating = {
	
	/**
	 *	The currently selected rating
	 *
	 *	@access	public
	 *	@var	int
	 */
	rating : 0,
	
	/**
	 *	The selector to access the star list-items
	 *
	 *	@access	public
	 *	@var	string
	 */
	selector : '',
	
	/**
	 *	Timeout for setting the rating display back
	 *
	 *	@access	public
	 *	@var	object
	 */
	timeout : '',
	
	
	/**
	 *	Parses through all the stars in the rater and assigns events
	 *
	 *	@access	public
	 *	@param	string	p_selector	The list item that contains the stars
	 *	@return	void
	 */
	init : function( p_selector ){
		
		StarRating.selector = p_selector;
		
		$( p_selector + ' li a' ).each(
			function( i, val ){
				$(this).mouseover( function(){ StarRating.highlight(i); } );
				$(this).click( function(){ return StarRating.rate(i); } );	
			}
		)
		
	}, // END PROPERTY: init
	
	
	/**
	 *	Unbinds all the events from the rating system, so it appears to be disabled
	 *
	 *	@access	public
	 *	@return	void
	 */
	disable : function(){
		
		$( StarRating.selector + ' li a' ).each(
			function( i, val ){
				$(this).unbind( 'mouseover' );
				$(this).unbind( 'click' );
				$(this).click( function(){ return false; } );
				$(this).addClass( 'disabled' );
			}
		)
		
	}, // END PROPERTY: disable
	
	
	/**
	 *	Highlights the current star and all stars below it
	 *
	 *	@access	public
	 *	@param	int	p_index
	 *	@return	void
	 */
	highlight : function( p_index ){
		
		clearTimeout( StarRating.timeout );
		$( StarRating.selector + ' li' ).slice( 0, p_index + 1 ).addClass( 'active' );
		$( StarRating.selector + ' li' ).slice( p_index + 1 ).removeClass( 'active' );
		$( StarRating.selector + ' li').eq( p_index ).children('a').mouseout( function(){ StarRating.unhighlight(); } );
	
	}, // END PROPERTY: highlight
	
	
	/**
	 *	Clears all the stars if there is no rating, or sets the rating back to what if was prior to highlighting after a timeout
	 *
	 *	@access	public
	 *	@return	void
	 */
	unhighlight : function(){
		
		StarRating.clear();
		$( StarRating.selector + ' li a').unbind( 'mouseout' );
		if( StarRating.rating > 0 ){
			StarRating.timeout = setTimeout( 'StarRating.rehighlight()', 1000 );
		}
	
	}, // END PROPERTY: unhighlight
	
	
	/**
	 *	Sets the rating display based on the current rating
	 *
	 *	@access	public
	 *	@return	void
	 */
	rehighlight : function(){
		
		StarRating.clear();
		StarRating.highlight( StarRating.rating - 1 );
		clearTimeout( StarRating.timeout );
		
	}, // END PROPERTY: unhighlight
	
	
	/**
	 *	Clears all the highlighted stars
	 *
	 *	@access	public
	 *	@return	void
	 */
	clear : function(){
		
		$( StarRating.selector + ' li' ).removeClass( 'active' );
		
	}, // END PROPERTY: clear
	
	
	/**
	 *	Puts the correct rating into the property
	 *
	 *	@access	public
	 *	@return	void
	 */
	rate : function( p_index ){
		
		clearTimeout( StarRating.timeout );
		StarRating.rating = p_index + 1;
		StarRating.highlight( p_index );
		$( StarRating.selector + ' li a').unbind( 'mouseout' );
		
		return false;
		
	} // END PROPERTY: rate
	
} // END OBJECT



/**
 *	User object class to check if a user is logged in or not
 */
function ReviewUser() {
	
	this.isLoggedIn = function(){
		
		if( reviewUser.readCookie( 'at' ) ){
			return true;
		}else{
			return false;
		}
		
	}

	this.readCookie = function( name ){
		
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		
		return null;
		
	}
	
} // END FUNCTION


/**
 *	Create a new instance of the ConcertFinder and ConcertReviews, and ReviewUser objects
 */
var concertFinder = new ConcertFinder();
var concertReviews = new ConcertReviews();
var reviewUser = new ReviewUser();


/**
 *	Initialise the Dom load events
 */
if( document.getElementById && jQuery ){
	$(document).ready(
		function(){
			
			concertFinder.setup();
			
			if( $('.pluck').length > 0 ){
				$('.pluck').show();
				$('#reviews-box-top').show();
			}
			
			if( $('.star-rating').length > 0 ){
				StarRating.init( '.star-rating' );
			}

			if( $('.average-review').length > 0 ){
				concertReviews.getAverageReview( concertGuid );
			}

			if( reviewUser.isLoggedIn() ){
				$('#loginReview').remove();
			}else{
				$('.addReview').remove();
			}
			
		}
	);
}
