/*
 * Eyedea Media Makers jQuery Image Gallery v1.0 - http://www.eyedea.com.au/
 *
 *
 * TERMS OF USE - Eyedea Media Makers jQuery Image Gallery Plugin
 * 
 * Copyright © 2009 Eyedea Media Makers
 * All rights reserved.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

(function($) {

       $.fn.start_gallery = function(options) {
			
			// Create the default options
			var defaults = {  
					type: "standard",
					title: null,
    				speed: "slow", 
					delay:3000, 
					heightadjust:"270px",
					closebutton: "/CMS/Plugins/ImageGallery/includes/images/close.png",
					thumbnailsize:150,
					rotate:true,
					largesize:650,		
					imgtitles:null
   			};  	
			var obj = $(this);
			// Extend the defaults into the options var
			var options = $.extend(defaults, options); 
		
	if ( options.type == "advanced" ) {
		
			// Start a loop for each element on the page
			return this.each(function() {
    		
			// Create a variable for this current looped object
			var obj = $(this);
				
				// Create the internal div for the image gallery thumbnails toggle control
				$(this,obj).html("<div class=\"image_gallery_toggle\"></div>");
				
				// Delay the script for the number of sections options.delay is set to
				$(".image_gallery_toggle",obj).animate({ top:options.heightadjust },options.delay);
			
				// Function to loop through the images in the gallery and display
				var loop_images = function(options){
				
				// Count the number of images in the array
				var num_images = options.images.length;
				
				if ( options.rotate===false ) { 
					// Fade Out
					obj.animate({opacity:0},options.speed,'swing',function(){
					// Change the BG image and fade in
						obj.css({'background-image':'url('+options.images[0]+')'}).animate({opacity:0},options.speed);
					});
					return;
				}
				
				// For each of the images in the array, fade out, fade in and wait.
				$(options.images).slowEach(options.delay,function(i,v){ 
																  
						// Fade Out
						obj.animate({opacity:0},options.speed,'swing', function(){
							// Change the BG image and fade in
							obj.css({'background-image':'url(/CMS/Core/Globals/thumbGenerator.php?height=300&width=650&cropratio=2.17:1&image='+v+')'}).animate({opacity:1},options.speed,'swing',function(){
									// When the array is at its end, start the function again
									if ( i==num_images-1 ){ 
										setTimeout(function(){loop_images(options);},options.delay/2);
									}																																					  
							});
						});
			
					
					
				});
				
			} // End of loop_images function
			
			// Initialise the loop function
			loop_images(options);
			
			// Setup the click event for the thumbnails button
			$(".image_gallery_toggle",obj).click(function(){
					
					// Create the DIV elements for the thumbs overlaty and the ppage overlay
					var o = $.create('div',{'id':'thumbs_overlay','class':'header'});
					var ol = $.create('div',{'id':'thumbs_page_overlay','class':'header'});
              
        			// Append object o
        			obj.after($(o));
					// Append object o
        			obj.before($(ol));
					
					// Fade int he Overlay
					$("#thumbs_page_overlay").stop().animate({opacity:0},0,function(){
						$("#thumbs_page_overlay").css({'display':'block'});
						$("#thumbs_page_overlay").stop().animate({opacity:1},options.speed);
					});
					
					// Fade the thumbs to zero
					$("#thumbs_overlay").stop().animate({opacity:0},0,function(){
						$("#thumbs_overlay").css({'display':'block'});
						$("#thumbs_overlay").stop().animate({opacity:1},options.speed);
						
						// Load the thumbnails function
						loadthumbnails(options);
					});
					
			}); // End thumbnail button click event
			
			// Load an insert all of the thumbnails into the box
			var loadthumbnails = function(options){
				
				// Clear the Overlay
				$("#thumbs_overlay").html("");
				
				$("#thumbs_overlay").append("<div style='float:left;background-image:url(/CMS/Plugins/ImageGallery/includes/images/title_main.png); margin-left:15px; color:#FFF;'>"+
											"<img src='/CMS/Plugins/ImageGallery/includes/images/title_right.png' style='margin-right:-15px;' align='right' /><img src='/CMS/Plugins/ImageGallery/includes/images/title_left.png' align='absmiddle' style='margin-left:-15px; />"+
											"<span id='thumb_title'> "+options.title+" </span>"+
											"</div>");
				
				// Load the Close Button
				$("#thumbs_overlay").append("<div id='image_gallery_close_button' style='margin-left:10px;'><img src='"+options.closebutton+"' /></div> <br clear='all' />");
				
				// Loop through all of the images and generate the thumbnails
				$(options.images).each(function(i,v){
					
					// Append the thumbnail into the DIV
					$("#thumbs_overlay").append("<div id='thumb_image'><img src='/CMS/Core/Globals/thumbGenerator.php?width="+options.thumbnailsize+"&height="+options.thumbnailsize+"&cropratio=1:1&image="+v+"' id='thu_"+i+"' /></div>");
					
					// If the image is clicked load the large version
					$("#thu_"+i).click(function(){
						enlarge_thumbs(options,v,i);
					});
					
					// If the close button is pressed, close
					$("#image_gallery_close_button").click(function(){
						close_overlays(options);
					});
					
					// If the overlay is pressed, close
					$("#thumbs_page_overlay").click(function(){
						close_overlays(options);
					});

				});
				
			} //  End of thumbnails
	
			
			function GetHeight() {
				var y = 0;
		        if (self.innerHeight) { y = self.innerHeight; }
		        else if (document.documentElement && document.documentElement.clientHeight) { y = document.documentElement.clientHeight; }
				else if (document.body) { y = document.body.clientHeight; }
				return y;
			}
			
			// Load the Large Version
			// options = Class Options, v = Loop Value, i = Loop number
			var enlarge_thumbs = function(options,v,i){
				
				// Delete the current content
				$("#thumbs_overlay").html("");
							
				// Type the title of the gallery
				$("#thumbs_overlay").append("<div style='float:left;background-image:url(/CMS/Plugins/ImageGallery/includes/images/title_main.png); margin-left:15px; color:#FFF;width:"+options.largesize/2+"px;'>"+
											"<img src='/CMS/Plugins/ImageGallery/includes/images/title_right.png' style='margin-right:-15px;' align='right' /><img src='/CMS/Plugins/ImageGallery/includes/images/title_left.png' align='absmiddle' style='margin-left:-15px; />"+
											"<span id='thumb_title'> "+options.title+" </span>"+
											"</div>");
					
					// Append the thumbnails button
					$("#thumbs_overlay").append("<div id='image_gallery_thumbs' align='left' style='cursor:pointer'><img src='/CMS/Plugins/ImageGallery/includes/images/thumbs.png' title='Back to Thumbnails' /></div><div id='image_gallery_close_button'><img src='"+options.closebutton+"' title='Close Popup' /></div><br clear='all' />");
										
					// Append the large image into the DIV
					$("#thumbs_overlay").append("<div id='large_image' align='center'><img src='/CMS/Core/Globals/thumbGenerator.php?width="+options.largesize+"&height="+(GetHeight()-300)+"&cropratio=1.1:1&image="+v+"' id='thu_"+i+"' style='border:solid 2px #000;' /></div>");		
					
					// Append the Next Button to the right of the screen
					$("#thumbs_overlay").append("<div id='image_gallery_next'><img src='/CMS/Plugins/ImageGallery/includes/images/right.png' /></div>");
					
					// Append the previous button to the screen
					$("#thumbs_overlay").append("<div id='image_gallery_back'><img src='/CMS/Plugins/ImageGallery/includes/images/left.png' /></div>");
						
					$("#thumbs_page_overlay").css({'height':window.innerHeight});
					
					// Check if there is titles per image
					if ( options.imgtitles[i] == null ){
						// There are no titles
					} else { 
						// There are titles
						$("#thumbs_overlay").append("<div id='gallery_image_title'><img src='/CMS/Plugins/ImageGallery/includes/images/title_left.png' align='absmiddle' style='margin-left:-15px;float:left;' /><div style='float:left;background-image:url(/CMS/Plugins/ImageGallery/includes/images/title_main.png); width:100%;color:#FFF;'>"+
											"<img src='/CMS/Plugins/ImageGallery/includes/images/title_right.png' style='margin-right:-15px;' align='right' />"+
											"<span id='gallery_image_title_text'> "+options.imgtitles[i]+" </span>"+
											"</div></div>");
					}
					
				// If you are at the start of the gallery, hide the prev button
				if ( i==0 ) {
					$("#image_gallery_back").hide();
				}
				
				// If you are at the end hide the next button
				if ( i==options.images.length-1 ) {
					$("#image_gallery_next").hide();
				}
				
				// Click Event for the Back Button
				$("#image_gallery_thumbs").click(function(){
					loadthumbnails(options);
				});
				// Click Event for the Back Button
				$("#image_gallery_back").click(function(){
					enlarge_thumbs(options,options.images[i-1],i-1);
				});
				// Click Event for the Back Button
				$("#image_gallery_next").click(function(){
					enlarge_thumbs(options,options.images[i+1],i+1);
				});
				
				// If close button is pressed, close
				$("#image_gallery_close_button").click(function(){
					close_overlays(options);
				});
				
				// If the overlay layer is clicked close
				$("#thumbs_page_overlay").click(function(){
					close_overlays(options);
				});
				
				
			}
			
			// Close all of the overlays
			var close_overlays = function(options) {
				
				$("#thumbs_overlay").stop().animate({opacity:0},options.speed,function(){$("#thumbs_overlay").css({'display':'none'});$("#thumbs_overlay").html("");});
				// Fade int he Overlay
				$("#thumbs_page_overlay").stop().animate({opacity:1},0,function(){
				$("#thumbs_page_overlay").stop().animate({opacity:0},options.speed,function(){$(this).css({'display':'none'});});
				$("#thumbs_overlay").html("");
				});
			}
			});
			
	} // End of Standard Box
	
	if ( options.type=="standard" ){
		
					// Start a loop for each element on the page
			return this.each(function() {
				
				var obj = $(this);
				
				// Loop through all of the images and generate the thumbnails
				$(options.images).each(function(i,v){
				
					// Append the thumbnail into the DIV
					$(obj).append("<div id='thumb_image'><img src='/CMS/Core/Globals/thumbGenerator.php?width="+options.thumbnailsize+"&height="+options.thumbnailsize+"&cropratio=1:1&image="+v+"' id='thu_"+i+"' /></div>");
					
					// If the image is clicked load the large version
					$("#thu_"+i,obj).click(function(){					
					
						var o = $.create('div',{'id':'thumbs_overlay','class':'header'});
						var ol = $.create('div',{'id':'thumbs_page_overlay','class':'header'});
					  
						// Append object o
						obj.after($(o));
						// Append object o
						obj.before($(ol));
							
						// Fade int he Overlay
						$("#thumbs_page_overlay").stop().animate({opacity:0},0,function(){
							$("#thumbs_page_overlay").css({'display':'block'});
							$("#thumbs_page_overlay").stop().animate({opacity:1},options.speed);
						});
							
						// Fade the thumbs to zero
						$("#thumbs_overlay").stop().animate({opacity:0},0,function(){
							$("#thumbs_overlay").css({'display':'block'});
							$("#thumbs_overlay").stop().animate({opacity:1},options.speed);
						});
				
						enlarge_thumbs(options,v,i);
				});
					
				});
				
				
			
			function GetHeight() {
				var y = 0;
		        if (self.innerHeight) { y = self.innerHeight; }
		        else if (document.documentElement && document.documentElement.clientHeight) { y = document.documentElement.clientHeight; }
				else if (document.body) { y = document.body.clientHeight; }
				return y;
			}
					
			// Close all of the overlays
			var close_overlays = function(options) {
				
				$("#thumbs_overlay").stop().animate({opacity:0},options.speed,function(){$("#thumbs_overlay").css({'display':'none'});$("#thumbs_overlay").html("");});
				// Fade int he Overlay
				$("#thumbs_page_overlay").stop().animate({opacity:1},0,function(){
				$("#thumbs_page_overlay").stop().animate({opacity:0},options.speed,function(){$(this).css({'display':'none'});});
				
				});
			}
	
			
			// Load the Large Version
			// options = Class Options, v = Loop Value, i = Loop number
			var enlarge_thumbs = function(options,v,i){
				
				// Delete the current content
				$("#thumbs_overlay").html("");
							
				// Type the title of the gallery
				$("#thumbs_overlay").append("<div style='float:left;background-image:url(/CMS/Plugins/ImageGallery/includes/images/title_main.png); margin-left:15px; color:#FFF;'>"+
											"<img src='/CMS/Plugins/ImageGallery/includes/images/title_right.png' style='margin-right:-15px;' align='right' /><img src='/CMS/Plugins/ImageGallery/includes/images/title_left.png' align='absmiddle' style='margin-left:-15px; />"+
											"<span id='thumb_title'> "+options.title+" </span>"+
											"</div>");
					
				// Append the thumbnails button
				$("#thumbs_overlay").append("<div id='image_gallery_close_button' style='margin-left:10px;'><img src='"+options.closebutton+"' title='Close Popup' /></div><br clear='all' />");
										
				// Append the large image into the DIV
				$("#thumbs_overlay").append("<div id='large_image' align='center'><img src='/CMS/Core/Globals/thumbGenerator.php?width="+options.largesize+"&height="+(GetHeight()-300)+"&image="+v+"' id='thu_"+i+"' style='border:solid 2px #000;' /></div>");		
					
				// Append the Next Button to the right of the screen
				$("#thumbs_overlay").append("<div id='image_gallery_next'><img src='/CMS/Plugins/ImageGallery/includes/images/right.png' /></div>");
					
				// Append the previous button to the screen
				$("#thumbs_overlay").append("<div id='image_gallery_back'><img src='/CMS/Plugins/ImageGallery/includes/images/left.png' /></div>");
						
				$("#thumbs_page_overlay").css({'height':window.innerHeight});
				
				// Check if there is titles per image
				if ( options.imgtitles == null || options.imgtitles[i] == null ){
					// There are no titles
				} else { 
					// There are titles
				$("#thumbs_overlay").append("<div id='gallery_image_title'><img src='/CMS/Plugins/ImageGallery/includes/images/title_left.png' align='absmiddle' style='margin-left:-15px;float:left;' /><div style='float:left;background-image:url(/CMS/Plugins/ImageGallery/includes/images/title_main.png); width:100%;color:#FFF;'>"+
											"<img src='/CMS/Plugins/ImageGallery/includes/images/title_right.png' style='margin-right:-15px;' align='right' />"+
											"<span id='gallery_image_title_text'> "+options.imgtitles[i]+" </span>"+
											"</div></div>");
				}
					
				// If you are at the start of the gallery, hide the prev button
				if ( i==0 ) {
					$("#image_gallery_back").hide();
				}
				
				// If you are at the end hide the next button
				if ( i==options.images.length-1 ) {
					$("#image_gallery_next").hide();
				}
				
				// Click Event for the Back Button
				$("#image_gallery_thumbs").click(function(){
					loadthumbnails(options);
				});
				// Click Event for the Back Button
				$("#image_gallery_back").click(function(){
					enlarge_thumbs(options,options.images[i-1],i-1);
				});
				// Click Event for the Back Button
				$("#image_gallery_next").click(function(){
					enlarge_thumbs(options,options.images[i+1],i+1);
				});
				
				// If close button is pressed, close
				$("#image_gallery_close_button").click(function(){
					close_overlays(options);
				});
				
				// If the overlay layer is clicked close
				$("#thumbs_page_overlay").click(function(){
					close_overlays(options);
				});
				
				
			}
		});
	}
};
		
		
		
		
		
		
		
		
		
		
		
		
		
		// Other Stuff Below....

 		$.fn.slowEach = function( interval, callback ) {
			var array = this;
			if( ! array.length ) return;
			var i = 0;
			next();
			function next() {
				if( callback.call( array[i], i, array[i] ) !== false )
					if( ++i < array.length )
						setTimeout( next, interval );
			}
    	}; 
		
	
	$.create = function() {
    if (arguments.length == 0) {return [];}
    var args = arguments[0] || {}, elem = null, elements = null;
    var siblings = null;

    // In case someone passes in a null object,
    // assume that they want an empty string.
    if (args == null) { args = ""; }
    if (args.constructor == String) {
        if (arguments.length > 1) {
            var attributes = arguments[1];
                if (attributes.constructor == String) {
                            elem = document.createTextNode(args);
                            elements = [];
                            elements.push(elem);
                            siblings = $.create.apply(null, Array.prototype.slice.call(arguments, 1));
                            elements = elements.concat(siblings);
                            return elements;

                    } else {
                            elem = document.createElement(args);

                            // Set element attributes.
                            var attributes = arguments[1];
                            for (var attr in attributes) {
                                $(elem).attr(attr, attributes[attr]);
							}
                            // Add children of this element.
                            var children = arguments[2];
                           // children = $.create.apply(null, children);
                            $(elem).append(children);

                            // If there are more siblings, render those too.
                            if (arguments.length > 3) {
                                    siblings = $.create.apply(null, Array.prototype.slice.call(arguments, 3));
                                    return [elem].concat(siblings);
                            }
                            return elem;
                    }
            } else return document.createTextNode(args);
      } else {
              elements = [];
              elements.push(args);
              siblings = $.create.apply(null, (Array.prototype.slice.call(arguments, 1)));
              elements = elements.concat(siblings);
              return elements;
      }
	};

})(jQuery);
