/**
 * PF Smart Gallery - jQuery plugin for gallery
 * @requires jQuery v1.4.0
 * 
 * code: comming soon
 *
 * Copyright (c) 2010 - 2011 Danny Otto (dannyotto.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.1.1
 * 
 */

(function($) {
  
  $.fn.extend({
    
    pfSmartGallery: function(config) {
      
      var defaults = {
        galleryObj: $('#gallery'),
        galleryContainer: 'gallery-container',
        galleryContainerObj: false,
        galleryNavigationObj: false,
        pointer: 1,
        history: true,
        btnCreate: true,
        btnPrevID: 'btn-prev',
        btnNextID: 'btn-next',
        btnPrevText: 'previous image',
        btnNextText: 'next image',
        loader: '<div class="loader"></div>'
      };
      var options = $.extend(defaults,config);
      
      return this.each(function(){
        
        // Startobjekt wird als Navigationsobjekt gespeichert
        options.galleryNavigationObj = $(this);
        
        // HTML wird erzeugt
        if (options.galleryObj.find('img').length > 0) {
          options.galleryObj.children('img').wrap('<div id="' + options.galleryContainer + '"><div class="image-container image-cur"></div></div>');
          // Ausrichtung korrigieren
          /* Nicht mehr nötig, wenn das Bild direkt neugeladen wird - Zeile 94
          if (options.galleryObj.attr('class') == 'landscape') {
            options.galleryObj.removeClass('landscape');
            $('#' + options.galleryContainer + ' .image-cur').addClass('landscape');
          } else if (options.galleryObj.attr('class') == 'portrait') {
            options.galleryObj.removeClass('portrait');
            $('#' + options.galleryContainer + ' .image-cur').addClass('portrait');
          }*/
        } else {
          options.galleryObj.append('<div id="' + options.galleryContainer + '"><div class="image-container image-cur"></div></div>');
        }
        
        // Button erstellen
        if(options.btnCreate == true) {
          $(options.galleryObj).prepend('<div id="btn"><a class="piwik_download" href="#" id="' + options.btnPrevID + '">' + options.btnPrevText + '</a> <a class="piwik_download" href="#" id="' + options.btnNextID + '">' + options.btnNextText + '</a></div>');
        }
        
        // Galerie-Container wird als Objekt gespeichert
        options.galleryContainerObj = $('#' + options.galleryContainer);
        
        // Navigation durchlaufen
        var i = 1;
        $(this).find('a').each(function(){
          
          var obj = $(this);
          var url = obj.attr('href');
          
          // Link-Ziel wird umgeschrieben
          obj.attr('rel',url).attr('href','#' + i);
          
          // Thumbnail markieren
          if (url == $('#' + options.galleryContainer + ' .image-cur img').attr('src')) { obj.addClass('cur'); }
          
          // Funktion anbinden
          obj.bind('click', function(e){ onNavClick(obj); return false; });
          
          i++;
        });
        
        // Pointer überschreiben, fass es ein Defaultbild gibt
        if ( $('#' + options.galleryContainer + ' .image-cur img').attr('src') != options.galleryNavigationObj.children('li:eq(' + (options.pointer - 1) + ')').children('a').attr('rel') ) {
          var url = $('#' + options.galleryNavigationObj.attr('id') + ' li a.cur').attr('href');
          if(url) options.pointer = url.replace(/^.*#/, '');
        }
        
        // Defaultbild wird entfernt und in der Folge neu eingesetzt
        // if (options.history == true) {}
        options.galleryContainerObj.children('.image-cur').children('img').remove();
        
        
        // Aktionen an die Button anbinden
        if(options.btnCreate == true) {
          setBtnURL(options.galleryNavigationObj.children('li:eq(' + (options.pointer - 1) + ')').children('a'));
          $('#' + options.btnPrevID).bind('click', function(e){ onBtnClick($(this)); return false; });
          $('#' + options.btnNextID).bind('click', function(e){ onBtnClick($(this)); return false; });
        }
        
        // Erstes Bild laden, gegebenenfalls über das History-Plugin
        if (options.history == true) {
          $.history.init( function(number) {
            if (!number) {
              number = options.pointer;
            } else {
              //alert(number);
              if (number == '8?piwik_campaign=many') { number = 8 }
              options.pointer = number;
            }
            loadImage();
          });
        } else {
          loadImage();
          $('#' + options.btnPrevID).bind('click', function(e){ onBtnClick($(this)); return false; });
          $('#' + options.btnNextID).bind('click', function(e){ onBtnClick($(this)); return false; });
        }
        
      });
      
      
      
      function setBtnURL(obj) {
        
        if(obj.attr('href') == $('#' + options.galleryNavigationObj.attr('id') + ' li:first-child a').attr('href')) {
          $('#' + options.btnPrevID).attr('href',$('#' + options.galleryNavigationObj.attr('id') + ' li:last-child a').attr('href'));
        } else {
          $('#' + options.btnPrevID).attr('href',obj.parent().prev().children('a').attr('href'));
        }
        
        if(obj.attr('href') == $('#' + options.galleryNavigationObj.attr('id') + ' li:last-child a').attr('href')) {
          $('#' + options.btnNextID).attr('href',$('#' + options.galleryNavigationObj.attr('id') + ' li:first-child a').attr('href'));
        } else {
          $('#' + options.btnNextID).attr('href',obj.parent().next().children('a').attr('href'));
        }
        
      }
      
      
      
      function onBtnClick(objBtn) {
        
        // Bild einblenden
        var url = objBtn.attr('href');
        var number = url.replace(/^.*#/, '');
        if (options.history == true) {
          $.history.load(number);
        } else {
          options.pointer = number;
          loadImage();
        }
        
      }
      
      
      
      function onNavClick(obj) {
        
        // prüfen ob das Thumbnail des aktuellen Bildes angeklickt wurde
        if (obj.attr('rel') == $('.image-cur img').attr('src')) return false;
        
        // Bild einblenden
        var url = obj.attr('href');
        var number = url.replace(/^.*#/, '');
        if (options.history == true) {
          $.history.load(number);
        } else {
          options.pointer = number;
          loadImage();
        }
        
      }
      
      
      
      function loadImage() {
        
        // Bildnummer auslesen und Objekt festlegen
        obj = options.galleryNavigationObj.children('li:eq(' + (options.pointer - 1) + ')').children('a');
        
        // Funktion abbrechen, fass es ein Startbild gibt
        if (obj.attr('rel') == $('.image-cur img').attr('src')) return false;
        
        // Loader einfügen
        obj.append(options.loader);
        options.galleryContainerObj.append(options.loader);
        
        // Bild laden
        imgPreloader = new Image();
        imgPreloader.onerror = function() {
          obj.children('.loader').remove();
          $(options.galleryContainerObj).children('.loader').remove();
        }
        imgPreloader.onload = function() {
          imgPreloader.onerror = null;
          imgPreloader.onload = null;
          imageIsLoaded(obj);
          obj.children('.loader').remove();
          options.galleryContainerObj.children('.loader').remove();
        };
        imgPreloader.src = obj.attr('rel');
      }
      
      
      
      function imageIsLoaded(obj) {
        
        // aktuelle Höhe ermitteln
        var curHeight = options.galleryObj.outerHeight();
        
        if (imgPreloader.height == curHeight) {
          // Bild einblenden
          animateImage(obj)
          
        } else if (imgPreloader.height < curHeight) {
          // Bild einblenden
          animateImage(obj)
          // Größe ändern
          $(options.galleryObj).stop().animate({height: imgPreloader.height}, 200);
          
        } else {
          // Größe ändern
          $(options.galleryObj).stop().animate({height: imgPreloader.height}, 200);
          // Bild einblenden
          animateImage(obj);
          
        }
      
      }
      
      
      
      function animateImage(obj) {
        
        if ( $('#' + options.galleryContainer + ' .image-cur').find('img').length == 0 ) {
          
          $('<img />').attr({'src':imgPreloader.src}).appendTo(options.galleryContainerObj.children('.image-cur'));
          adjustImagePosition($('.image-cur'),imgPreloader.width,imgPreloader.height);
          setNavStatus(obj);
          setBtnURL(obj);
          
        } else {
        
          var curPosition = $('#' + options.galleryNavigationObj.attr('id') + ' a').index($('#' + options.galleryNavigationObj.attr('id') + ' a.cur'));
          var nextPosition = $('#' + options.galleryNavigationObj.attr('id') + ' a').index(obj);
          
          if(curPosition < nextPosition) {
          
            $('<div />').attr({'class':'image-next image-container'}).appendTo(options.galleryContainerObj);
            $('<img />').attr({'src':imgPreloader.src}).appendTo(options.galleryContainerObj.children('.image-next'));
            adjustImagePosition($('.image-next'),imgPreloader.width,imgPreloader.height);
            $(options.galleryContainerObj).animate({left: '-900px'}, 300, 'linear', function() {
              $(options.galleryContainerObj).css('left','0px');
              $(options.galleryContainerObj.children('.image-cur')).remove();
              $(options.galleryContainerObj.children('.image-next')).addClass('image-cur image-container').removeClass('image-next');
              setNavStatus(obj);
              setBtnURL(obj);
            });
          
          } else {
          
            $('<div />').attr({'class':'image-next image-container'}).prependTo(options.galleryContainerObj);
            $('<img />').attr({'src':imgPreloader.src}).appendTo(options.galleryContainerObj.children('.image-next'));
            adjustImagePosition($('.image-next'),imgPreloader.width,imgPreloader.height);
            $(options.galleryContainerObj).css('left','-900px');
            $(options.galleryContainerObj).animate({left: '0'}, 300, 'linear', function() {
              $(options.galleryContainerObj.children('.image-cur')).remove();
              $(options.galleryContainerObj.children('.image-next')).addClass('image-cur image-container').removeClass('image-next');
              setNavStatus(obj);
              setBtnURL(obj);
            });
          
          }
        
        }
        
      }
      
      
      
      function adjustImagePosition (obj,imgWidth,imgHeight) {
        if (imgWidth <= imgHeight) {
          obj.addClass('portrait');
        } else {
          obj.addClass('landscape');
        }
      }
      
      
      
      function setNavStatus(obj) {
        $('#' + options.galleryNavigationObj.attr('id') + ' a.cur').toggleClass('cur');
        obj.addClass('cur');
      }
      
      
      
    }
    
  })

})(jQuery);
