/*#######################################
#  Shared JS functions                  #
#                                       #
#          (c) Digital Initiatives 2007 #
#######################################*/

$(function () {
	// extend the reader div to be almost the full height of the browser window
	//$('#readerDiv').css('height',($(window).height() - 200) + 'px');
	
	$('#newComment').bind('submit',function() {
		
		// remove all other classes from the fields
		$('#name,#email,#commentText').removeClass('error');
		$('#name,#email,#commentText').removeClass('compulsory');
		$('#name,#email,#commentText').removeClass('validated');
		
		// show waiting icons for all the fields
		$('#name,#username,#commentText').addClass('waiting');
		
		// send the form data via an ajax call
		$.post('/ajax/comment-new/?id='+iid+'&s='+sid,{ name: $('#name').attr('value'), email:$('#email').attr('value'), commentText: $('#commentText').attr('value') },
			function(data){
				// check the respone for errors
				if(data != '1')
				{
					$('#newCommentDiv h2').after(data);							// add the response to the DOM
					
					// highlight broken fields
					var badFields = $('#badFields').html();				// get the list of bad fields
					$(badFields).removeClass('waiting');				// remove all waiting icons
					$(badFields).addClass('error');						// add the error icon
					
					// highlight any good fields (iff applicable)
					var goodFields = $('#goodFields').html();			// get the list of bad fields
					if(goodFields){
						$(goodFields).removeClass('waiting');			// remove all waiting icons
						$(goodFields).addClass('validated');			// add the error icon
					}
					
					// remove the good and bad divs
					$('#badFields,#goodFields').remove();
				} else
				{
					// reload the comments, to the last page, to show the new comment
					
					// reset input flags to "required"
					$('#name,#email,#commentText').removeClass('error');
					$('#name,#email,#commentText').removeClass('waiting');
					$('#name,#email,#commentText').removeClass('validated');
					$('#name,#email,#commentText').addClass('compulsory');
					
					// remove old values so another comment can be added
					$('#commentText').attr('value','');
					
					// get the lastPage
					if ($('#comments .ajaxData').length > 0) {
						var temp = $('#comments .ajaxData').html().split('|');
						var lastPage = Math.ceil((parseInt(temp[0]) + 1) / parseInt(temp[1]));
					} else {
						var lastPage = 1;
					}
					
					// trigger a comments page refresh (to show the new comment);
					$('#comments').attr("page",lastPage);
					$('#comments').trigger('pagechange'); // triggter a load
				}
			});
		
		// return false to prevent the form from actually submitting
		return false;
	});
});

// sets the hidden field with the star rating value
function setStarRating(val)
{
	starRating = val;
	$('#rating').attr('value',val);
}

// extend jQuery to add cover rollovers
jQuery.fn.extend({
	coverRollover: function() {
		$('#floatingCover').remove();		// remove any existing floats
		
		$(this).bind('mouseenter',function(e){
			// how tall is the image (to ensure it fits on the screen)
			var imageHeightDefault = 340;
			var imgHeight = imageHeightDefault;
			
			// load the bigger cover
			var tmp = $(this).attr('src').split("-");
			$('#wrap').before('<img id="floatingCover" src="'+tmp[0]+'-'+tmp[1]+'-250.jpg" />');
			
			$('#floatingCover').ready(function(e){
				imgHeight = $('#floatingCover').height() + 15;
				if(imgHeight < 100) imgHeight = imageHeightDefault;
			});
			
			// attach the move listener
			$(this).bind('mousemove',function(e){
				
				// if the img would be off the bottom of the screen, bump it up
				var yOffset = 0;
				if((e.clientY + imgHeight) > $(window).height())
				{
					yOffset = (e.clientY + imgHeight) - $(window).height();
				}
				
				$('#floatingCover').css('left',(e.pageX+10)+'px');
				$('#floatingCover').css('top',(e.pageY+10-yOffset)+'px');
			});
			
			// attach the mouseout behavious
			$(this).bind('mouseout',function(e){
				$(this).unbind('mousemove');		// remove the mousemove listener
				$('#floatingCover').remove();		// remove the float
			});
		});
	}
});

// extend jQuery to add ajax sections
jQuery.fn.extend({
	ajaxSection: function(title,src,columns,getVars,fallback) {
		
		// set the initial heading stuff
		$(this).html('<div><div class="blankHeader"><h2>' + title + '</h2><table class="resultsPagination" summary="pagination"><tr><td class="featuredPrevious"/><td class="featuredNext"/></tr></table></div><br /><img class="ajaxWedge noIPhone" src="/css/default/blank.gif" alt="" style="width: 1px; float: right;" /><div class="ajaxDiv">&nbsp;</div></div>');
		
		// set the data source
		src = '/ajax/'+src+'/';
		
		// append getVars if set
		if(getVars){
			src = src + '?' + getVars;
		}
		
		// set the initial page number
		$(this).attr("page",1);
		var dst = this;			// reference to the holding element
		
		// set the load function
		this.load = function() {
			$.get(src,{s:sid,p:$(dst).attr("page")},function(data){
				if (!data) {
					if (fallback) {
						$('.ajaxDiv', $(dst)).html(fallback);
					} else {
						// if there are no results, and no fallback text remove the target div
						$(dst).remove();
					}
				} else
				{
					$('.ajaxDiv', $(dst)).fadeOut('slow',function(){
						
						// create the heading
						$(dst).html('<div><div class="blankHeader"><h2>' + title + '</h2><table class="resultsPagination" summary="pagination"><tr><td class="featuredPrevious"/><td class="featuredNext"/></tr></table></div><br /><img class="ajaxWedge noIPhone" src="/css/default/blank.gif" alt="" style="width: 1px; float: right;" /><div class="ajaxDiv"></div></div>');
					
						// set the data
						$('.ajaxDiv', $(dst)).hide();
						$('.ajaxDiv', $(dst)).html(data);
						$('.ajaxDiv', $(dst)).fadeIn('slow');
						
						// calculate the pagination
						var temp = $('.ajaxData', $(dst)).html().split('|');
						$(dst).attr("maxPages",Math.ceil(temp[0] / (temp[1] * columns)));
						
						// resize the wedge depending on rows
						$('.ajaxWedge', $(dst)).css("height", (temp[1] * 140) + 'px');
						
						// remove old nav click listeners
						$('.featuredPrevious', $(dst)).unbind('click');
						$('.featuredNext', $(dst)).unbind('click');
						
						if (parseInt($(dst).attr("page")) > 1) {
							$('.featuredPrevious', $(dst)).html('<img src="/images/btn_previous_small.png" alt="previous" />');
							$('.featuredPrevious', $(dst)).bind('click', function(){
								$(dst).attr("page",parseInt($(dst).attr("page"))-1);
								$(dst).trigger('pagechange'); // trigger a load
							});
						}
						else {
							$('.featuredPrevious', $(dst)).html('<img src="/images/btn_previous_small_disabled.png" alt="previous" />');
						}
						
						if (parseInt($(dst).attr("page")) < parseInt($(dst).attr("maxPages"))) {
							$('.featuredNext', $(dst)).html('<img src="/images/btn_next_small.png" alt="next" />');
							$('.featuredNext', $(dst)).bind('click', function(){
								$(dst).attr("page",parseInt($(dst).attr("page"))+1);
								$(dst).trigger('pagechange'); // triggter a load
							});
						}
						else {
							$('.featuredNext', $(dst)).html('<img src="/images/btn_next_small_disabled.png" alt="next" />');
						}
						
						// attach rollover behavious to any thumbs
						//$('.cover', $(dst)).coverRollover();
						
						// attach removal behaviour if applicable
						$('.remove',$(dst)).bind('click',function(e) {
							var id = e.currentTarget.id.substring(6);		// get the issueID from the img tag
							
							// send removal request
							$.get('/ajax/favourites-remove/',{id:id,sid:sid},function(data){
								if(data)
								{
									$('#miniPreview'+data).fadeTo('slow',0.33);					// fade out the miniBrowser
									$('.remove',$('#miniPreview'+data)).fadeOut('fast');		// remove the remove btn
									$('#miniPreview' +data+ ' .cover').unbind('mouseenter');	// remove the rollover behaviour
								}
							});
						});
					});
				}
			});
		}
		
		$(this).bind('pagechange',this.load);	// bind the load function to the custom event
		this.load();							// load the first page
	}
});

// add a random filter to jQuery
jQuery.jQueryRandom = 0;  
jQuery.extend(jQuery.expr[":"],  
{  
	random: function(a, i, m, r) {  
		if (i == 0) {  
			jQuery.jQueryRandom = Math.floor(Math.random() * r.length);  
		};  
		return i == jQuery.jQueryRandom;  
	}  
});