/*
 * oSlide - jQuery Plugin
 * A slideshow designet for the frontside of my protfolio
 *
 * Copyright (c) 2010 Andrés Bott
 * Examples and documentation at: http://andresbott.com or http://oslide.andresbott.com
 * 
 * Version: 0.7(19/Jan/2011)
 * Developed with: jQuery v1.4
 * 
 * licensed under the LGPL license:
 *   http://www.gnu.org/licenses/lgpl.html
 *   
 */
// TO DO
// 			      nota: si haces click y sales inmediateamente del mouse over



(function($){
 $.fn.oslide = function(options) {

	var defaults = {
		mouseOverStopSlide:true,
		enableCaptions:true,
		enableNavigation:true,
		divCaptionId: "oSlideCaption",
		divNavigationId:"oSlideNavigation",
   		images: false, 		// an array containing all data to the images
		fade_color:"white",		// color of the background div
		sleep:5000,			// time in ms, how long is the image displayed befor changing
		fade_time:300,			// speed of the fading of the images
		debug : false
	};

	var options = $.extend(defaults, options);



  	$(this).each(function(i){
	obj = new oSlideObject(options,this);
	});


// ############################################################################################################################3
// ##    Creating a oSlide object
// ############################################################################################################################3
	function oSlideObject(options,oSlide_container){

		// ###########################################################
		// ##    constructor
		// ###########################################################


		var this_obj=this;
		var oSlide_div= false;
		
		var div_heigh=$(oSlide_container).height();
		var div_width=$(oSlide_container).width();

		var imagenes = false;
		var loop_started = false;
		var currentImage=false;
		var nextImage=0;
		var main_loop=false;
// 		var main_loop_pause=false; // needed?
		var event_mouse_over = false;

		var loading=false;
		var loadingTimer = false;
		var loadingFrame=1;
		var active_transition = false;
		var main_loop_timer = "inavtive";

		// ###########################################################
		// ##    Init method
		// ###########################################################
		this.oSlide_init = function(){
		    
			$(oSlide_container).append(
/*				oSlide_div = $ ( '<div id="oSlideImageDiv" style="width:'+div_width+'px; height:'+div_heigh+'px;></div>')*/
				oSlide_div = $ ( '<div id="oSlideImageDiv"></div>')

			);
			$(oSlide_div).width(div_width)
			$(oSlide_div).height(div_heigh)

			imagenes=this.get_images_data(oSlide_container);

			if(imagenes!=false){
			      // add a div for the loading animation
			      $(oSlide_container).append(
				      loading	= $('<div id="oSlide-loading" ><div></div></div>')
			      );
			      // show the loading animation
			      this.showLoading();

// 			      $(oSlide_div).css("background-color",this.random_color("hex"))

// 			      pause the image loop
			      if(options.mouseOverStopSlide==true){


				$(oSlide_container).mouseenter(function() {
				      this_obj.consoleOut("Mouse Enter");

				      if(event_mouse_over==false){
					      clearTimeout(main_loop);
					      main_loop_timer="inavtive";
					      event_mouse_over = true;
				      }
				});

				$(oSlide_container).mouseleave(function() {
				      this_obj.consoleOut("Mouse Exit main_loop_timer: "+ main_loop_timer );
				      if(event_mouse_over==true){
					      if(main_loop_timer=="inavtive"){
						  main_loop_timer="avtive";
						  main_loop =  setTimeout( this_obj.SlideNext,options.sleep);

					      }
					      event_mouse_over = false;
				      }
				});
			     }

			      // start the loop
			      this.SlideNext();
			      if(options.enableNavigation==true){
				    this.navigation();
			      }


			}else{
			      if (window.console != undefined) {
				  console.log("ERROR: No images declarated for the contaning div (<ul><li><img src=....), hidding the divs!");
			      }
// 			      throw new Error("DEBUG: No images declarated for the contaning div, hidding the divs!");
			      $(oSlide_container).hide();
			}
		}
		// ###########################################################
		// ##    Gets image data from the DOM or passed as parameter
		// ###########################################################
		this.get_images_data = function (div){

			// Step 1
			// getting the content from dom
			if(options.images==false){

				// Gett the image list
				var imagenes = new Array();
				if(typeof($(div).find("img").first().attr("src"))!="undefined"){

				
					$(div).find("li").each(function(j){

						if( typeof($(this).find("img").attr("src")) != "undefined"){
							var this_img=$(this).find("img").first();
							imagenes[j] = new Array();

							// Getting the image URL
							imagenes[j]["url"]=this_img.attr("src");

							// Getting the image alt text
							if(typeof(this_img.attr("alt")) != "undefined"){
								imagenes[j]["desc"]=this_img.attr("alt");
							}

							// Getting the link URL
							var b=$(this).find("a").attr("href");
							if( typeof(b) != "undefined"){
							    imagenes[j]["link"]=b;
							} 
							imagenes[j]["loaded"]=false;
						}
						
// 					 Check of the image list works
// 					 alert( "informacion de la imagen "+j+"\n URL : "+imagenes[j]["url"] + " \n desc  "+imagenes[j]["desc"] + " \n link  "+imagenes[j]["link"]);

					});
				      $(div).find("ul").remove();
				}else{
				      return false;
				}

			}else{

				var imagenes=options.images;
			}
			imagenes["longitud"]= imagenes.length;
			return imagenes;
		};

		// ###########################################################
		// ##    console output
		// ###########################################################
		this.consoleOut = function(string){
		    if(options.debug==true){
			  if(typeof(string)!="undefined"){
			      console.log(string);
			  }else{
			      console.log("undefinied console break point called!");
			  }
		    }
		}
 
		// ###########################################################
		// ##    shows the loading icon
		// ###########################################################
		this.showLoading = function(){
			this_obj.consoleOut("showLoading");
			if(typeof(loadingTimer)!="undefined"){
				clearInterval(loadingTimer);
			}

			loading.show();
			loadingTimer = setInterval(this.animate_loading, 66);
		};

		// ###########################################################
		// ##    hide the loading icon
		// ###########################################################
		this.hideLoading = function (){
		      loading.hide();
		      clearInterval(loadingTimer);
		};

		// ###########################################################
		// ##   animate the loading icon
		// ###########################################################
		this.animate_loading = function (){

			if (!loading.is(':visible')){
				clearInterval(loadingTimer);
				return;
			}

			$(oSlide_container).find("#oSlide-loading div").css('top', (loadingFrame * -40) + 'px');
// 			$('div', loading).css('top', (loadingFrame * -40) + 'px');
			loadingFrame = (loadingFrame + 1) % 12;
		};


		// ###########################################################
		// ##   executes the next action
		// ###########################################################
		this.SlideNext = function (){
		      this_obj.consoleOut("slideNext");
		      active_transition = true;
		      main_loop_timer="inavtive";

		      this_obj.singleImagePreload(function(){this_obj.showImage(nextImage);});

		}

		// ###########################################################
		// ##    preloads a singe image 
		// ###########################################################

		this.singleImagePreload = function (callback){
		      if(imagenes[nextImage]["loaded"]!=true){

			    imagenes[nextImage]["img"] = new Image();
			    $(imagenes[nextImage]["img"]).load(function(){
				  imagenes[nextImage]["loaded"]=true;
				      callback();
			    }).attr("src",imagenes[nextImage]["url"]);

		      }else{

			     callback();
		      }
		}

		// ###########################################################
		// ##    inserts the image and deletes the previous
		// ###########################################################
		this.showImage = function (callback){
		      this_obj.consoleOut("showImage");
		      if(imagenes[nextImage]["loaded"]==true){
			  if(loop_started==false){

				this.hideLoading();

				this.inserImage(nextImage);
				
				$(oSlide_container).find('#'+options.divNavigationId+' .oSlideNavigationElementId_'+nextImage).addClass("oSlideNavigationActiveElement");


				$(oSlide_div).css("background-color",options.fade_color)

				loop_started = true;
				currentImage = nextImage;
				nextImage = nextImage +1;

				main_loop =   setTimeout( this_obj.SlideNext,options.sleep);
			  }else{
// 				alert("next loop"+" \n images:\n Imagenes[length]= "+imagenes["longitud"]+"\n Current image:"+currentImage+" \n next Image: "+nextImage)

				$(oSlide_div).find('#oSilideImg_'+currentImage).fadeOut(options.fade_time,function (){

					if(typeof(imagenes[currentImage]["link"])!="undefined"){
						$(oSlide_div).find('#oSilideImg_'+currentImage).parent().remove();
					}else{
						$(oSlide_div).find('#oSilideImg_'+currentImage).remove();
					}

					// odo nota: ¿es mejor ir eliminando y creando divs o crearlos todos e irlos mostrando y borrando?

					this_obj.inserImage(nextImage);
					$(oSlide_container).find('#'+options.divNavigationId+' .oSlideNavigationElementId_'+nextImage).addClass("oSlideNavigationActiveElement");
					$(oSlide_container).find('#'+options.divNavigationId+' .oSlideNavigationElementId_'+currentImage).removeClass("oSlideNavigationActiveElement");



					if(nextImage==imagenes["longitud"]-1){

					    currentImage = nextImage;
					    nextImage = 0;

					}else{
					    currentImage = nextImage;
					    nextImage = nextImage +1;
					}
					if(main_loop_timer=="inavtive"){
					    main_loop_timer="avtive";
					    main_loop =  setTimeout( this_obj.SlideNext,options.sleep);

					}
				});
				
			  }

		      }
		}// end of showImage

		// ###########################################################
		// ##    inserts a single image
		// ###########################################################
		this.inserImage = function (id){
		      this_obj.consoleOut("InsertImage");
			 var img =false;
			if(typeof(imagenes[id]["link"])!="undefined"){
				$(oSlide_div).append('<a href="'+imagenes[id]["link"]+'" ><div id="oSilideImg_'+id+'" style=" display:none; " ></div></a>');
			}else{
				$(oSlide_div).append('<div id="oSilideImg_'+id+'" style="display:none; " ></div>');
			}
			// caption
			if(typeof(imagenes[id]["desc"])!="undefined" && options.enableCaptions == true){
				$('#oSilideImg_'+id).append('<div id="'+options.divCaptionId+'"><span>'+imagenes[id]["desc"]+'</span></div>')
			}
// 			$(oSlide_div).find('#oSilideImg_'+id).append( img = $('<img src="'+imagenes[id]["url"]+'" />')).oSlideaeImageResize({ height: 200, width: 250 }).fadeIn(options.fade_time); ; 
			$(oSlide_div).find('#oSilideImg_'+id).append( img = $('<img src="'+imagenes[id]["url"]+'" />') )
			$(img).oSlideaeImageResize({ height: div_heigh, width: div_width })  
			$(oSlide_div).find('#oSilideImg_'+id).fadeIn(options.fade_time,function(){
				if( options.mouseOverStopSlide == true && event_mouse_over == true){
					main_loop_timer="inavtive";
					clearTimeout(main_loop);
				}
				active_transition = false;
			});
// 			$(oSlide_div).find('#oSilideImg_'+id).show();

		}



		// ###########################################################
		// ##   resumes the slide
		// ###########################################################
		this.navigation = function (){

			$(oSlide_container).append('<div id="'+options.divNavigationId+'"></div>')

			for (i=0;i<imagenes["longitud"];i=i+1){
			      $(oSlide_container).find('#'+options.divNavigationId).append('<div class="oSlideNavigationElement oSlideNavigationElementId_'+i+'"><span class="'+i+'">'+(i+1)+'</span></div>')

			      $(oSlide_container).find('.oSlideNavigationElementId_'+i).click(function() {

					if(active_transition != true){
					      this_obj.consoleOut("Click - active transition FALSE");
					      if(!$(this).hasClass('oSlideNavigationActiveElement')){
						    var element = $(this).children('span').attr('class');
						    clearTimeout(main_loop);
// 						    main_loop_timer="inavtive";
						    nextImage = parseInt(element)    ;
							    this_obj.SlideNext();
					      }
					}else{
					      this_obj.consoleOut("Click - active transition TRUE");
					    var delayed_timeout = function(obj, main_loop){
						if(!$(obj).hasClass('oSlideNavigationActiveElement')){
						      var element = $(obj).find('span').attr('class');
// 						      main_loop_timer="inavtive";
						      clearTimeout(main_loop);
						      nextImage = parseInt(element)    ;

						      this_obj.SlideNext();
						}
					    }
					    var obj = this;
					    if(main_loop_timer=="inavtive"){
						  main_loop_timer="avtive"
						  setTimeout( function(){ delayed_timeout(obj, main_loop)   },options.fade_time);
					    }
					}
			      });
			}
		}





		// ###########################################################
		// ##   Launch the object
		// ###########################################################
		this.oSlide_init();	
	}
// ############################################################################################################################3
// ##   end of the object
// ############################################################################################################################3


  }
})(jQuery);



/*
 * aeImageResize - jQuery Plugin (changed name to avoid name collision)
 * http://plugins.jquery.com/project/aeImageResize
 *
 * i only only one change to make the images fill the view div
 * 
 * 
 * Version: 2.1.1 2010-Nov-28 
 * Developed with: jQuery v1.4
 * 
 * License: Dual licensed under MIT and GPL licenses.
 *   
 */

(function( $ ) {

  $.fn.oSlideaeImageResize = function( params ) {

    var aspectRatio = 0
      // Nasty I know but it's done only once, so not too bad I guess
      // Alternate suggestions welcome :)
      ,	isIE6 = $.browser.msie && (6 == ~~ $.browser.version)
      ;

    // We cannot do much unless we have one of these
    if ( !params.height && !params.width ) {
      return this;
    }

    // Calculate aspect ratio now, if possible
    if ( params.height && params.width ) {
      aspectRatio = params.width / params.height;
    }

    // Attach handler to load
    // Handler is executed just once per element
    // Load event required for Webkit browsers
    return this.one( "load", function() {

      // Remove all attributes and CSS rules
      this.removeAttribute( "height" );
      this.removeAttribute( "width" );
      this.style.height = this.style.width = "";

      var imgHeight = this.height
        ,	imgWidth = this.width
        ,	imgAspectRatio = imgWidth / imgHeight
        ,	bxHeight = params.height
        ,	bxWidth = params.width
        ,	bxAspectRatio = aspectRatio;
				
      // Work the magic!
      // If one parameter is missing, we just force calculate it
      if ( !bxAspectRatio ) {
        if ( bxHeight ) {
          bxAspectRatio = imgAspectRatio + 1;
        } else {
          bxAspectRatio = imgAspectRatio - 1;
        }
      }

      // Only resize the images that need resizing
      if ( (bxHeight && imgHeight > bxHeight) || (bxWidth && imgWidth > bxWidth) ) {

//         if ( imgAspectRatio > bxAspectRatio ) {  mod by odo
        if ( imgAspectRatio < bxAspectRatio ) {

          bxHeight = ~~ ( imgHeight / imgWidth * bxWidth );
        } else {
          bxWidth = ~~ ( imgWidth / imgHeight * bxHeight );
        }

        this.height = bxHeight;
        this.width = bxWidth;
      }
    })
    .each(function() {

      // Trigger load event (for Gecko and MSIE)
      if ( this.complete || isIE6 ) {
        $( this ).trigger( "load" );
      }
    });
  };
})( jQuery );


