﻿/**
	* KWP Pandora Gears
	*
	* jquery plugin for KWP functions; a tool box of mystery
	*
	* @author Michael Stamm, KWP Communications <m.stamm@kwp-communications.com>
	* @version 1.0
	* @timestamp 2011-10-19
	*/


	/**
		* Global Debug Functions
		*/

var debug = {
	"enabled":false,
	"global":true,
	"gearsImageGallery":true
};

var alertFallback = true;

if(typeof console === "undefined" || typeof console.log === "undefined"){
	console = {};
	if(alertFallback){
		console.log = function(msg){
			alert(msg);
		};
	}
	else{
		console.log = function(){};
	}
}

function debugging(msg){
	if(debug.enabled){
		console.log(msg);
	}
}


(function($){

	/**
		* gearsImageGallery
		*
		* cross fading image gallery
		*
		* @author Michael Stamm, KWP Communications <m.stamm@kwp-communications.com>
		* @version 1.0
		* @timestamp 2011-10-19
		*/

 $.fn.gearsImageGallery = function(config){



  var settings = jQuery.extend({
  	"firstImage":0,
  	
  	"selectorList":"ul",
  	"selectorItem":"li",
  	"selectorThumb":".thumb",
  	"selectorFull":".full",
  	"selectorUrl":".url",
  	
  	"fadeTransitionDurationItem":500,
  	"fadeTransitionDurationImage":500,
  	
  	"thumbList":true,
  	"thumbListOnTop":false,

  	"canvasWidth":-1,
  	"canvasHeight":-1,

  	"autoTransition": false,
  	"autoTransitionDelay":5000,
  	"autoTransitionDuration":2500,
  	"autoTransitionStopPermanentOnUserInput":true
  }, config);

		$(this).each(function(){

			/**
				* Init function to convert and set up a gallery
				*/
				
			var galleryTimer = {"clock":0};

			function init(rootObj){
			
				var imageGalleryObject = $("<div class=\"fullsize\"><div class=\"nest\"></div></div>")
				if(settings.thumbList){
					var thumbGalleryObject = $("<ul class=\"thumbnails\"></ul>")
				}
					
				$(rootObj).find(settings.selectorList).find(settings.selectorItem).each(function(){
     var hasUrl = $(this).find(".url").length > 0;
					var hasMap = $(this).hasClass("map");
					var hasDownload = $(this).hasClass("download");
					var isFirst = ($(this).index() == 0);
					var isLast = ($(this).index() == $(this).parent().children(settings.selectorItem).length - 1);
					
					// build thumbnail gallery
					if(settings.thumbList){
						var thumbHTML =	"<li><div class=\"item";
						if(hasMap){
							thumbHTML += " map";
						}						
						if(hasDownload){
							thumbHTML += " download";
						}						
						thumbHTML += "\"><a href=\"#\"><img src=\"" + $(this).find(".thumb img").attr("src") + "\" />";
						if(hasUrl){
							thumbHTML += "<span class=\"blend\"></span>";
						}
						thumbHTML += "</a></div></li>";
						$(thumbGalleryObject).append(thumbHTML);
						var currentThumbObject = $(thumbGalleryObject).find("li:last-child");
						if(isFirst){
							$(currentThumbObject).addClass("first");
						}
						if(isLast){
							$(currentThumbObject).addClass("last");
						}
						$(currentThumbObject).find("a").bind("click", function(event){
							event.preventDefault();
							$(rootObj).data("param", {"index":$(this).parent().parent().index()}).trigger("gears.showItem");
						});
					}
					
					// build image gallery
					var imageHTML = "<div class=\"item\"><div class=\"image\"></div>";
					if(hasUrl){
					 imageHTML += "<div class=\"blend\"><a"
						if($(this).find(".url a").attr("target") != undefined){
					  imageHTML += " target=\"" + $(this).find(".url a").attr("target") + "\"";
						}
					 imageHTML += " href=\"" + $(this).find(".url a").attr("href") + "\"></a></div>"
					}
					imageHTML += "</div>";
					$(imageGalleryObject).find(".nest").append(imageHTML);
					var currentGalleryObject = $(imageGalleryObject).find(".nest .item:last-child");
					if(hasMap){
						$(currentGalleryObject).addClass("map");
					}
					if(hasDownload){
						$(currentGalleryObject).addClass("download");
					}
					// saving the full image url for later on demand display
					$(currentGalleryObject).data("fullImage", $(this).find(".full a").attr("href"));
				});
				
				
				// add thumbnail gallery to DOM (on top)
				if(settings.thumbList && settings.thumbListOnTop){
					$(rootObj).append(thumbGalleryObject);
				}
				// add image gallery to DOM
				$(rootObj).append(imageGalleryObject);
				// add thumbnail gallery to DOM (at bottom)
				if(settings.thumbList && !settings.thumbListOnTop){
					$(rootObj).append(thumbGalleryObject);
				}
				// remove old list
				$(rootObj).find(settings.selectorList).not(".fullsize").not(".thumbnails").remove();

				// set up public events
				$(rootObj).bind("gears.showItem", function(event){
					setUserInput(rootObj);
					var newIndex = ($(rootObj).data("param")).index;
					if(newIndex == undefined){newIndex = 0;}
					$(rootObj).removeData("param");
					if(newIndex == $(rootObj).data("currentImageIndex")){
						autoFadeStart(rootObj);
					}
					else{
						autoFadeStop(rootObj);
					}
					crossfadeToIndex(rootObj, newIndex);
				});
				
				$(rootObj).bind("gears.prevItem", function(event){
					setUserInput(rootObj);
					prevImage(rootObj);
				});
				
				$(rootObj).bind("gears.nextItem", function(event){
					setUserInput(rootObj);
					nextImage(rootObj);
				});
				
				$(rootObj).bind("gears.autoFadeStart", function(event){
					$(rootObj).data("autoFade", true);
					autoFadeStart(rootObj);
				});
				
				$(rootObj).bind("gears.autoFadeStop", function(event){
					$(rootObj).data("autoFade", false);
					autoFadeStop(rootObj);
				});
				
				// set width / height / styles
				var canvasWidth = settings.canvasWidth > 0 ? settings.canvasWidth : $(rootObj).find(".nest:eq(0)").innerWidth();
				var canvasHeight = settings.canvasHeight > 0 ? settings.canvasHeight : $(rootObj).find(".nest:eq(0)").innerHeight();
				
				$(rootObj).find(".nest:eq(0)").css({"width":canvasWidth + "px", "height":canvasHeight + "px"});
				$(rootObj).find(".nest:eq(0) .item").css({"display":"none", "position":"absolute", "width":canvasWidth + "px", "height":canvasHeight + "px"});
				$(rootObj).find(".nest:eq(0) .item .blend").css({"display":"block", "position":"absolute", "width":canvasWidth + "px", "height":canvasHeight + "px"});
				$(rootObj).find(".nest:eq(0) .item .blend a").css({"display":"block", "width":canvasWidth + "px", "height":canvasHeight + "px"});
				
				// set first to show
				$(rootObj).data("currentImageIndex", -1);
				crossfadeToIndex(rootObj, settings.firstImage);
				
				// set up init timer
				if(settings.autoTransition){
					$(rootObj).data("autoFade", true);
					galleryTimer.clock = window.setTimeout(function(){autoFadeStart(rootObj);}, settings.autoTransitionDelay);
				}
				else{
					$(rootObj).data("autoFade", false);
				}
			}
			
			function crossfadeToIndex(rootObj, newIndex){
				var currentIndex = $(rootObj).data("currentImageIndex");
				if(newIndex != currentIndex){
					$(rootObj).find(".fullsize .nest .item").stop(true, true);					
					var currentItemObj = currentIndex == -1 ? -1 : $(rootObj).find(".fullsize .nest .item").eq(currentIndex);
					var newItemObj = $(rootObj).find(".fullsize .nest .item").eq(newIndex);
					if(newIndex > currentIndex){
						if(currentItemObj != -1){
							$(currentItemObj).css({"display":"block", "opacity":1});
						}
						$(newItemObj).css({"display":"block", "opacity":0}).animate(
							{"opacity":1},
							{
								duration:settings.fadeTransitionDurationItem,
       	complete:function(){
       		$(currentItemObj).css({"display":"none", "opacity":0});
  							// preload image if not already loaded
									if($(newItemObj).find("img").length == 0){
										setUpNewImage(rootObj, newItemObj);
									}
									autoFadeStart(rootObj);
       	}
       }
      );
					}
					else{
						if(currentItemObj != -1){
							$(currentItemObj).css({"display":"block", "opacity":1}).animate(
								{"opacity":0},
								{
									duration:settings.fadeTransitionDurationItem,
		       complete:function(){
		       	$(currentItemObj).css({"display":"none", "opacity":0});
	  							// preload image if not already loaded
										if($(newItemObj).find("img").length == 0){
											setUpNewImage(rootObj, newItemObj);
										}
										autoFadeStart(rootObj);
		       }
		      }
       );
						}
						$(newItemObj).css({"display":"block", "opacity":1});
					}
					
					$(rootObj).data("currentImageIndex", newIndex);
					setMenuCurrent(rootObj);
				}				
			}
			
			function prevImage(rootObj){
				var currentIndex = $(rootObj).data("currentImageIndex");
				var imageLength = $(rootObj).find(settings.selectorList).find(settings.selectorItem).length;
				var newIndex = currentIndex - 1 < 0 ? imageLength - 1 : currentIndex - 1;
				crossfadeToIndex(rootObj, newIndex)
			}
			
			function nextImage(rootObj){
				var currentIndex = $(rootObj).data("currentImageIndex");
				var imageLength = $(rootObj).find(settings.selectorList).find(settings.selectorItem).length;
				var newIndex = currentIndex + 1 < imageLength ? currentIndex + 1 : 0;
				crossfadeToIndex(rootObj, newIndex)
			}
			
			function setUpNewImage(rootObj, imageItemObj){
				autoFadeStop(rootObj);
				var imageUrl = $(imageItemObj).data("fullImage");
				$(imageItemObj).find(".image").append("<img src=\"" + imageUrl + "\" />");
				
				var timeLoadingStart = new Date().getTime();
				
				var imageObj = $(imageItemObj).find(".image img:eq(0)");
				$(imageObj).parent().css({"opacity":0});
				$(imageObj).bind("load", function(event){
					var timeLoadingEnd = new Date().getTime();
					if(debug.gearsImageGallery){
						debugging("gearsImageGallery: image loaded after " + (timeLoadingEnd - timeLoadingStart) + "ms");
					}
					// resizing and positioning
					var imageWidth = $(imageObj).width();
					var imageHeight = $(imageObj).height();
					var imageRatio = imageWidth / imageHeight;
					var frameWidth = $(imageObj).parent().parent().innerWidth();
					var frameHeight = $(imageObj).parent().parent().innerHeight();
					var frameRatio = frameWidth / frameHeight;
					debugging(imageWidth + ":" + imageHeight + " (" + imageRatio + ") / " + frameWidth + ":" + frameHeight + "(" + frameRatio + ")");
					
					if(imageRatio >= frameRatio){
						// resize horizontal
						var scaleRatio = imageWidth / frameWidth;
						$(imageObj).css({"width":frameWidth + "px", "height":parseInt(imageHeight / scaleRatio) + "px"});
						$(imageObj).parent().css({"width":frameWidth + "px", "height":parseInt(imageHeight / scaleRatio) + "px", "top":Math.floor((frameHeight - parseInt(imageHeight / scaleRatio)) / 2) + "px"});
					}
					else if(imageRatio < frameRatio){
						// resize vertical
						var scaleRatio = imageHeight / frameHeight;
						$(imageObj).css({"width":parseInt(imageWidth / scaleRatio) + "px", "height":frameHeight + "px"});
						$(imageObj).parent().css({"width":parseInt(imageWidth / scaleRatio) + "px", "height":frameHeight + "px", "left":Math.floor((frameWidth - parseInt(imageWidth / scaleRatio)) / 2) + "px"});						
					}
					
					// show image
					$(imageObj).parent().animate({"opacity":1}, settings.fadeTransitionDurationImage);
					autoFadeStart(rootObj);
				});
			}
			
			function setMenuCurrent(rootObj, newIndex){
				if(newIndex == undefined){var newIndex = $(rootObj).data("currentImageIndex");}
				$(rootObj).find(".thumbnails li").removeClass("current");
				$(rootObj).find(".thumbnails li").eq(newIndex).addClass("current");
			}
			
			function autoFadeStart(rootObj){
				if($(rootObj).data("autoFade")){
					autoFadeStop(rootObj);
					galleryTimer.clock = window.setTimeout(function(){nextImage(rootObj);}, settings.autoTransitionDuration);
				}
			}
			
			function autoFadeStop(rootObj){
				if(galleryTimer.clock){
					window.clearTimeout(galleryTimer.clock);
				}
			}
			
			function setUserInput(rootObj){
				if(settings.autoTransitionStopPermanentOnUserInput){
					$(rootObj).data("autoFade", false);
				}
			}
			


			// init gallery
			init(this);
			
		});

 };


 // slideOut accordion
 $.fn.slideOut = function(config){

  var settings = jQuery.extend({
   "accordionSelector":"ul",
   "itemSelector":"li",
   "headerSelector":"h3",
   "bodySelector":"div.accordion_content",
   "openedIndex":-1,
   "classOpened":"opened",
   "classClosed":"closed",
   "duration":500
  }, config);


  var animationRunning = false;
  var itemObj = $(this).is(settings.accordionSelector) ? $(this).children(settings.itemSelector) : $(this);
  var isSingleSlide = $(this).is(settings.accordionSelector) ? false : true;

  itemObj.each(function(){
   $(this).addClass("silde_out_item");
   $(this).children(settings.headerSelector + ":eq(0)").addClass("silde_out_header");
   var backupHeight = $(this).children(settings.bodySelector + ":eq(0)").outerHeight();
   var backupContent = $(this).children(settings.bodySelector + ":eq(0)").detach();
   $("<div></div>").append(backupContent).insertAfter($(this).children(settings.headerSelector + ":eq(0)"));
   $(this).children("div:eq(0)").attr("backupheight", backupHeight).addClass("slide_out_nest");
   $(this).children("div:eq(0)").children("div:eq(0)").addClass("slide_out_content");

   if(!isSingleSlide && settings.openedIndex == $(this).index()){
    $(this).children(settings.headerSelector + ":eq(0)").addClass("opened");
   }
   else{
    $(this).children(settings.headerSelector + ":eq(0)").addClass("closed");
    $(this).children("div.slide_out_nest:eq(0)").css({"height":"0px"});
    $(this).find("div.slide_out_content:eq(0)").css({"margin-top":"-" + backupHeight + "px"});
   }
   $(this).children(settings.headerSelector + ":eq(0)").bind("click", function(event){
     event.preventDefault();
     if(animationRunning == false){
      animationRunning = true;
      var clickedIndex = isSingleSlide ? 0 : $(this).parent().index();
      var clickedNestObj = isSingleSlide ? $(this).parent(".silde_out_item:eq(" + clickedIndex + ")") : $(this).parent().parent().children(".silde_out_item");
      var isClickedSlideOpen = clickedNestObj.eq(clickedIndex).children(settings.headerSelector + ":eq(0)").hasClass("opened");
      clickedNestObj.each(function(){
       var isSlideOpened = $(this).children(settings.headerSelector + ":eq(0)").hasClass("opened");
       if(isSlideOpened){
        // Close it!
        $(this).children(settings.headerSelector + ":eq(0)").removeClass("opened").addClass("closed");
        $(this).children(".slide_out_nest:eq(0)").animate(
         {"height":"0px"},
         {duration:settings.duration}
        );
        $(this).children(".slide_out_nest:eq(0)").children(".slide_out_content:eq(0)").animate(
         {"margin-top":"-" + $(this).children(".slide_out_nest:eq(0)").attr("backupheight") + "px"},
         {duration:settings.duration,
        	 complete:function(){
        	  animationRunning = false;
        		}
         }
        );
       }
       else if((!isSlideOpened && clickedIndex == $(this).index()) || isSingleSlide && !isSlideOpened){
        // Open it!
        $(this).children(settings.headerSelector + ":eq(0)").removeClass("closed").addClass("opened");
        $(this).children(".slide_out_nest:eq(0)").animate(
         {"height":$(this).children(".slide_out_nest:eq(0)").attr("backupheight") + "px"},
         {duration:settings.duration}
        );
        $(this).children(".slide_out_nest:eq(0)").children(".slide_out_content:eq(0)").animate(
         {"margin-top":"0px"},
         {duration:settings.duration,
        	 complete:function(){
        	  animationRunning = false;
        		}
         }
        );
       }
      });
     }
   });
  });
 };


})(jQuery);
