/*!
 * BCMS Gallery Module
 * Version 1.0 (24-MAY-2010)
 * @Built for jQuery v1.4.2 or later.
 *
 * Author: Alex Berriman, Boyd Design
 * Copyright (c) 2010 Boyd Design
 * Last modified: MAY 27 2010
 *
 */


// Arrays for storing image load results.
var Processed = new Array();
var Results = new Array();

// Image details
var Titles = new Array();
var Descriptions = new Array();
var Links = new Array();
var Copyrights = new Array();

var Delay = 8000;

var ImgDetails = new Array();

var CurInd = 0;
var Selected = 0;

// Pagination - current prev/next
var curPrev = 0;
var curNext = -1;

// Loading
var Loading = false;

// Template options
var RightImg = "<div>\n<a href=\"#\" title=\"[TITLE]\"><img src=\"" +  FilePath + "main[ID].jpg\" alt=\"[ALT]\" title=\"[TITLE]\"  border=\"0\" class=\"thumbnail ig_thumbnail\" />\n</a>\n</div>";
var PrevButton = "<a href=\"#\" onclick=\"#\" class=\"gPrev\">&laquo; Previous</a>";
var Copyright = "\n<div class='copyright'>[COPYRIGHT]</div>";

var FirstDelay = true;
var ImgElements = new Array;

// In Array function
Array.prototype.in_array = function(val) {
	for(var z = 0, l = this.length; z < l; z++) {
		if(this[z] == val) {
			return true;
		}
	}
	return false;
}

var Agent = navigator.userAgent

// Function called when document is ready.
$(document).ready(function() { 

	/*var xyz = 0;
	$("#curimg a img").each( function() {
		if( xyz != 0 ) {
			$(this).addClass('none');
		} 
		xyz++;
	});*/

	// User agent?
	if( Agent.indexOf("Safari") != -1 ) {
		$("#images div img").css("padding-bottom", "4px");
	}

	// Initialize - retrieve all of the current image details.
	$('.imgdsc').each( function() { 

		// Retrieve the image id.
		var Ind = $(this).html().toLowerCase().lastIndexOf("<span");
		var ImgId = $(this).attr("id").substr( $(this).attr("id").lastIndexOf("_") + 1 );
		var ImgTitle = $(this).html().substr( Ind );
		var ImgDesc = $(this).html().replace( ImgTitle, "" );
	
		ImgTitle = ImgTitle.replace("<span>", "").replace("</span>", "");
		
		Titles[ImgId] = ImgTitle;
		Descriptions[ImgId] = ImgDesc;
		Processed[ImgId] = ImgId;
		Copyrights[ImgId] = "";
		Links[ImgId] = "";
	});
		
	// Image click event
	$('#images img').live('click',  function() {
		return false;
	});
	
	$('#images img').live('mouseover', function() {
		switchImg( $(this) );
	});
	
	// Pagination options
	
	// Next onclick event
	$(".gNext").click(function() { 
		LoadImages( curNext );
		return false;
	});	
	
	// Click the current image
	$("#curimg img").live('click',  function() {
		if( onClickEvent == 0 ) return false;
		
		if( onClickEvent == 1 ) {
			var Id =  $(this).attr("id").substr( $(this).attr("id").lastIndexOf("_") + 1 );
			$(this).addClass("thickbox");
		}
	});
	
	// Default cursor for onclick
	if( onClickEvent == 0 ) {
		$('#curimg img:first').css("cursor", "auto");
	}
	
	setTimeout( "DelayImg()", Delay * 2 );
	
});

function DelayImg() {

	if( FirstDelay == true ) {
		$("#images div a img").each( function() {
			var Ide = $(this).attr('id').replace('thumb', '');
			ImgElements.push( Ide );
		});
	}
	
	var CurColImg = $(".colourimage").attr("id").replace("thumb", "");
	var NextColImg = 0;
	
	for( var x = 0; x < ImgElements.length; x++ ) {
		if( ImgElements[ x ] == CurColImg ) {
			var NextCurImg = x + 1;
			if( NextCurImg in ImgElements ) {
			
				NextColImg = NextCurImg;
			} else NextColImg = 0;
		}
	}
	
	var Obj = $("#thumb" + ImgElements[ NextColImg ]);
	switchImg( Obj );
	
	setTimeout( "DelayImg()", Delay );

}

function switchImg( Obj ) {
	
	// Loading bar
	//$('#gLoading').show();

	// Retrieve the current Id for the image.
	var ImgSrc = $(Obj).attr("src");
	var ImgId = $(Obj).attr("id").replace("main", "").replace('thumb', '');
	
	var Break = false;
	var CurId = $(".colourimage").attr("id").replace("thumb", "");
	if( CurId == ImgId ) Break = true;

	
	if( Break == true ) return;
	
	// Are we loading?
	if( Loading == true ) return;
	Loading = true;
	
	// Let's fetch the current image path
	var ImagePath = ImgSrc.replace( ImgSrc.substr( ImgSrc.lastIndexOf("/") + 1 ), "" );

	// Retrieve the image type (i.e. jpg/png/gif)
	var ImgType = ImgSrc.substr( ImgSrc.lastIndexOf(".") + 1 );
	
	// Create the new image before the Ajax request (will reduce loading time).
	if( Processed.in_array( ImgId ) == false ) { // Create new element
		// Thickbox?
		if( LoadWiget == 1 ) {
			var thickBox = " class='thickbox'";
		} else var thickBox = "";
		
		// Prepend to the html.
		$('#curimg').prepend("<a href='#' id='cur_limage_" + ImgId + "'" + thickBox + "><img src='" + ImagePath + "image" + ImgId + "." + ImgType + "' id='cur_image_" + ImgId + "' class='display none' /></a>\n<div class='gCopyright' style='width: auto; height: auto; margin: 0; padding: 0;' id='cur_copy_" + ImgId + "'></div>");
		Processed[CurInd] = ImgId;
		CurInd++;
	

		// Retrieve the details for the newly selected image
		$.ajax( {
			url: Base + '/modules/gallery/view.php?d=' + ImgId + '&section=' + imgSection,
			dataType: "xml",
			success: function(data) {	
				// Was an error detected? (add more advanced error handling later)
				if( $(data).find("error").text() != "" ) {
					alert( "We have encountered an error.\nError: " + $(data).find("error").text() );
					Loading = false;
					return;
				}					
									
				// Retrieve image details from XML file.
				ImgDetails['Title'] = $(data).find("title").text();
				ImgDetails['Description'] = $(data).find("description").text();
				ImgDetails['Alt'] = $(data).find("alt").text();
				ImgDetails['Modified'] = $(data).find("modified_when").text();
				ImgDetails['Link'] = $(data).find("link").text();
				ImgDetails['ImgId'] = ImgId;
				ImgDetails['Copyright'] = $(data).find("copyright").text();
				
				UpdateImage( ImgDetails );
			}
		});
	} else 
	{
		// We've already fetched the image in the past. No need to send another ajax request.
		var Update = new Array();
		Update['Title'] = Titles[ImgId];
		Update['Description'] = Descriptions[ImgId];
		Update['Link'] = Links[ImgId];
		Update['Copyright'] = Copyrights[ImgId];
		Update['ImgId'] = ImgId;

		UpdateImage( Update );
	}
	
	return false;
}

// Update function
function UpdateImage( Arr ) {
	
	var CurColour = 0;

	// Remove current colour images
	$('.colourimage').each( function() {
		var Ide = $(this).attr('id').replace('thumb','');
		
		if( Ide in Blacks && Blacks[ Ide ] != '' ) {
			$( '#thumb' + Ide ).attr('src', Blacks[ Ide ] ).removeClass('colourimage');
			CurColour = Ide;
		}
		
	});
	
	if( Arr['ImgId'] in Colours && Colours[ Arr['ImgId'] ] != '' ) {
		$( '#thumb' + Arr['ImgId'] ).attr('src', Colours[ Arr['ImgId'] ] ).addClass('colourimage');
	}
	
	// Update the main page.
	$('#cur_desc').fadeOut(500, function() {
		$('#cur_desc').html( Arr['Description'] ).fadeIn(500, function() { 
		});
	});
	$('#cur_title').hide().text( Arr['Title'] ).fadeIn(500);

	// What to do with the link?
	switch(onClickEvent) {
		// Link to image details page.
		case 2:
			$('#cur_limage_' + Arr['ImgId']).attr( 'href', Arr['Link'] );
			break;
		
		// Lightbox.
		case 1:
			var tmpSrc = $('#cur_image_' + Arr['ImgId']).attr("src");
			var tmpType = $('#cur_image_' + Arr['ImgId']).attr("src").substr( $('#cur_image_' + Arr['ImgId']).attr("src").lastIndexOf(".") );
			var Src = tmpSrc.replace( tmpSrc.substr( tmpSrc.lastIndexOf("/") + 1 ), "");
			$('#cur_limage_' + Arr['ImgId']).attr( 'href', Src + "image" + Arr['ImgId'] + tmpType );
			$('#cur_limage_' + Arr['ImgId']).attr("target", "_new");
			break;
			
		// Open in new window.
		case 3:
			var tmpSrc = $('#cur_image_' + Arr['ImgId']).attr("src");
			var tmpType = $('#cur_image_' + Arr['ImgId']).attr("src").substr( $('#cur_image_' + Arr['ImgId']).attr("src").lastIndexOf(".") );
			var Src = tmpSrc.replace( tmpSrc.substr( tmpSrc.lastIndexOf("/") + 1 ), "");
			$('#cur_limage_' + Arr['ImgId']).attr( 'href', Src + "image" + Arr['ImgId'] + tmpType );
			$('#cur_limage_' + Arr['ImgId']).attr("target", "_new");
			break;
		
		// Don't hotlink at all.
		default:
			$('#cur_limage_' + Arr['ImgId']).click( function() { return false; } );
			$('#cur_limage_' + Arr['ImgId']).css("cursor", "auto");
			break;
	}
		
	// Copyright function.
	function Copyright(Arr) {
		// Update the copyright?
		if( Arr['Copyright'] ) {
			$('#cur_copy_' + Arr['ImgId']).html( Arr['Copyright'] ).show();
		}
		Loading = false;
		return false;
	}
	
	// Fade out existing image
	if( Selected == 0 ) {
		tmpSelect = $('#curimg img.default').attr("src");
		tmpSelect = tmpSelect.substr( tmpSelect.lastIndexOf("/") + 1 ).replace( tmpSelect.substr( tmpSelect.lastIndexOf(".") ), "" ).replace("image", "");
		$('#cur_image_' + CurColour).fadeOut(500, function() {
			$('#cur_image_' + Arr['ImgId']).fadeIn(500, Copyright(Arr));
		});
	} else {
		tmpSelect = Selected;
		$("#cur_image_" + Selected).fadeOut(500, function() {
			$('#cur_image_' + Arr['ImgId']).fadeIn(500, Copyright(Arr));
		});
	}
	
	// Set current copyright to empty element.
	if( $('#cur_copy_' + tmpSelect).length != 0 ) {
		$('#cur_copy_' + tmpSelect).html("");
	}
				
	Selected = Arr['ImgId'];
	
	// Update image details
	Titles[ Arr['ImgId'] ] = Arr['Title'];
	Descriptions[ Arr['ImgId'] ] = Arr['Description'];
	Links[ Arr['ImgId'] ] = Arr['Link'];
	Copyrights[ Arr['ImgId'] ] = Arr['Copyright'];
				
	// Hide loading bar
	$('#gLoading').hide();
}

function LoadImages( Start ) {
	
	// Send the ajax request to load the images
	$.ajax( {
		url: Base + '/modules/gallery/view.php?pag=1&p=' + Start + '&section=' + imgSection,
		dataType: "xml",
		success: function(data) {	
		
			// Was an error detected? (add more advanced error handling later)
			if( $(data).find("error").text() != "" ) {
				alert( "We have encountered an error.\nError: " + $(data).find("error").text() );
				return;
			}
								
			// Retrieve the images
			var Replace = "";
			var First = 0;
			var n = 1;
			$(data).find("image").each(function() {
				// New line?
				if( n == 1 ) Replace += NewLine;
				
				Replace += RightImg.replace("[ID]", $(this).find("imageid").text() ).replace( '[TITLE]', $(this).find("title").text() ).replace( "[ALT]", $(this).find("alt").text() ).replace( '[TITLE]', $(this).find("title").text() );
				Replace += "\n";

				// First image? (i.e. update large image preview)
				if( First == 0 || 1 == 1 ) 
				{
					// We've already fetched the image in the past. No need to send another ajax request.
					var Update = new Array();
					Update['Title'] = $(this).find("title").text();
					Update['Description'] = $(this).find("description").text();
					Update['Link'] = $(this).find("link").text();
					Update['ImgId'] = $(this).find("imageid").text();
					Update['Extension'] = $(this).find("extension").text();
					Update['Copyright'] = $(this).find("copyright").text();
					
					// Let's figure out some iamge details
					var ImgSrc = $('#curimg a:first img').attr("src");
						
					var ImgId = ImgSrc.substr( ImgSrc.lastIndexOf("/") + 1 ).replace("image", "");
					ImgId = ImgId.replace( ImgId.substr( ImgId.indexOf(".") ), "" );
		
					// Let's fetch the current image path
					var ImagePath = ImgSrc.replace( ImgSrc.substr( ImgSrc.lastIndexOf("/") + 1 ), "" );
					
					// First one we're using?
					if( Selected == 0 ) {
						Selected = ImgId;						
					}
					
					// Have we processed it yet?
					if( Processed.in_array( Update['ImgId'] ) == false ) {
						// Thickbox?
						if( LoadWiget == 1 ) {
							var thickBox = " class='thickbox'";
						} else var thickBox = "";
						
						// If not, create the element.
						$('#curimg').prepend("<a href='#' id='cur_limage_" + Update['ImgId'] + "'" + thickBox + "><img src='" + ImagePath + "image" + Update['ImgId'] + "." + Update['Extension'] + "' id='cur_image_" + Update['ImgId'] + "' class='display none' /></a>\n<div class='gCopyright' id='cur_copy_" + Update['ImgId'] + "'></div>");
						Processed[CurInd] = Update['ImgId'];
						CurInd++;
					}
					
					// First?
					if( First == 0 ) {
						UpdateImage( Update );
						First = $(this).find("imageid").text();
					} else
					{
						// Update images.
						Titles[ Update['ImgId'] ] = Update['Title'];
						Descriptions[ Update['ImgId'] ] = Update['Description'];
						Links[ Update['ImgId'] ] = Update['Link'];
						Copyrights[ Update['ImgId'] ] = Update['Copyright'];
					}
				}
				
				// Do we need a new line?
				if( ( n % PerCol ) == 0 ) {
					Replace += NewLine;
				}
				
				// Increment counter
				n++;
				
			});
			
			// Replace HTML
			$('#images').html( Replace );
			
			// Retrieve pagination details from the xml.
			if( $(data).find("pag").find("prev").text() ) {
				// Does the link current exist?
				if( $(".gPrev").length == 0 ) {
					$("#gNav").prepend(PrevButton);
				}
				curPrev = $(data).find("pag").find("prev").text();
				
				// Previous onclick event
				if( curNext == -1 ) {
					$(".gPrev").click(function() { 
						LoadImages( curPrev );
						return false;
					});
				}
				
				$(".gPrev").show();
			} else {
				$(".gPrev").hide();
			}
			
			// Update next
			if( $(data).find("pag").find("next").text() ) {
				curNext = $(data).find("pag").find("next").text();
				$(".gNext").show();
			} else {
				$(".gNext").hide();
			}
			
			// Safari issue
			if( Agent.indexOf("Safari") != -1 ) {
				$("#images div img").css("padding-bottom", "4px");
			}

		}
	});
	
	return false;
}
