/************************************************************
 * Choco-Slider v1.0
 * http://chocoslider.alandawi.com.ar
 *
 * Desarrollado por Alan G. Dawidowicz
 * Web Site: www.alandawi.com.ar
 *
 * Copyright 2010
 * Licencia: MIT - http://es.wikipedia.org/wiki/Licencia_MIT
************************************************************/

(function($) {
  
  var ie6 = (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4);

  if (ie6) {
    try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {}
  };

  $.bind = function(object, method) {
    var args = Array.prototype.slice.call(arguments, 2);
    return function() {
      var args2 = [this].concat(args, $.makeArray( arguments ));
      return method.apply(object, args2);
    };
  };

  var SSPrototype = function() { };

  $.extend(SSPrototype.prototype, {
  
  init: function(el, options) {
    var defaults = {
      width              : 500,
      height             : 332,
      numberStrips       : 20,
	  speedStrip         : 400,
	  transparencyTitle  : 0.7,
      speedTitle         : 1000,
      sliderDelay        : 3000,
	  auto               : true,
      autopause          : true,
	  control            : '',
      effect             : 'effect1'
    };

    this.imgInc = 0;
    this.imgInterval = 0;
    this.inc    = 0;
	this.dom    = {};
    this.img    = [];
    this.titles = [];
    this.links  = [];
	this.order  = [];
    this.controls = [];

    this.options = $.extend({}, defaults, options);
    this.element = el;

    var params = this.options;
    var self   = this;

		$('img', el).each(function(i) {
      var item       = $(this);
      self.img[i]    = item.attr('src');
      self.titles[i] = item.attr('alt') ? item.attr('alt') : (item.attr('title') ? item.attr('title') : '');
      self.links[i]  = item.parent().is('a') ? item.parent().attr('href') : false;
      
      if (self.options.control) {
        self.controls[i] = $('<a href="#" class="chocoslider-control" rel="'+i+'"><span>'+(i+1)+'</span></a>');
        $(self.options.control).append(self.controls[i]);
        
        if (i==0) {
          self.controls[i].addClass('active');
        }

        self.controls[i].click(function(event) {
          self.transition($(this).attr('rel'));
          event.preventDefault();
        });
      };
      
      item.hide();
		});

		$(this.element).css({
			'background-image'    : 'url('+this.img[0]+')',
			'background-position' : 'top left',
			'position'  : 'relative',
			'overflow'  : 'hidden',
			'width'     : params.width,
			'height'    : params.height
    });

    this.dom.title = $("<div class='chocoslider-title'>"+this.titles[0]+"</div>");
    this.dom.title.css({
      'background-color' : '#666666',
      'color'     : '#FFFFFF',
      'position'  : 'absolute',
      'bottom'    : 0,
      'left'      : 0,
      'width'     : params.width - 20,
      'padding'   : '5px 10px',
      'z-index'   : 5
    });
    $(this.element).append(this.dom.title);

    if (this.titles[this.imgInc]) {
      $(this.dom.title).css({
        'opacity' : params.transparencyTitle
      });
    } else {
      $(this.dom.title).css({
        'opacity' : 0
      });
    };
    
		var stripWidth  = parseInt(params.width / params.numberStrips);
		var gap         = params.width - stripWidth * params.numberStrips;
		var stripLeft   = 0;
    	var odd         = 1;
    
    this.dom.strip  = [];


    for (i=0; i < params.numberStrips; i++) {

      if ( gap > 0) {
        tstripWidth = stripWidth + 1;
        gap--;
      } else {
        tstripWidth = stripWidth;
      }
			
      var eachStrip = $("<div class='strip-"+this.element.id+"'></div>").get(0);
      $(eachStrip).css({
        'background-position': -stripLeft +'px top',
        'width'   : tstripWidth + "px",
        'height'  : params.height + "px",
        'float'   : 'left',
        'position': 'absolute',
        'left'    : stripLeft
      });
      
      this.dom.strip.push ( eachStrip );

      stripLeft += tstripWidth;

      this.order[i] = i;

    };
    $(this.element).append(this.dom.strip);

    this.dom.link = $("<a class='chocoslider-link'></a>");
    this.dom.link.css({
      'text-decoration' : 'none',
      'position'  : 'absolute',
      'top'       : 0,
      'left'      : 0,
      'border'    : 0,
      'z-index'   : 8,
      'width'     : params.width,
      'height'    : params.height
    });
    $(this.element).append(this.dom.link);

    if (this.links[this.imgInc]) {
      this.dom.link.attr('href', this.links[this.imgInc]);
    } else {
      this.dom.link.css({'display':'none'});
    };

    
    if (params.auto) {
      this.slideshow();
    }
    return this;
  },
  
  slideshow: function() {
    clearInterval(this.imgInterval);
    this.imgInterval = setInterval($.bind(this, function() {this.transition();} ), this.options.sliderDelay+((this.options.speedStrip / 6)*this.options.numberStrips)+this.options.speedStrip);
  },

  setpause: function(val) {
    this.pause = val;
  },

  transition: function(dir) {
    if (this.pause == true || dir == this.imgInc) {
      return false;
    };
    
    
    this.pause = true;
    this.stripInterval = setInterval($.bind(this, function() { this.numberStrips(this.order[this.inc]); }), this.options.speedStrip / 6);

    $(this.element).css({
      'background-image' : 'url('+this.img[this.imgInc]+')'
    });

    switch (dir) {
      case "next":
        this.imgInc = (this.imgInc+1 >= this.img.length) ? 0 : this.imgInc+1;
        break;
      case "prev":
        this.imgInc = (this.imgInc-1 < 0) ? this.img.length-1 : this.imgInc-1;
        break;
      case "first":
        this.imgInc = 0;
        break;
      case "last":
        this.imgInc = this.img.length-1;
        break;
      default:
        if (!isNaN(parseFloat(dir)) && isFinite(dir)) {
          this.imgInc = parseInt(dir);
        } else {
         
          this.imgInc = (this.imgInc+1 >= this.img.length) ? 0 : this.imgInc+1;
        };
        break;
    };
    
    if (dir !== undefined) {
      if (this.options.autopause) {
        clearInterval(this.imgInterval);
      } else {
        this.slideshow();
      }
    }

    if (this.titles[this.imgInc]!='') {
      $(this.dom.title).html(this.titles[this.imgInc]);
      opacity = this.options.transparencyTitle;
    } else {
      opacity = 0;
    };

    $(this.dom.title).animate({ 'opacity' : opacity }, this.options.speedTitle);

    if (this.links[this.imgInc]) {
      this.dom.link.attr('href', this.links[this.imgInc]);
      this.dom.link.css({'display':'block'});
    } else {
      this.dom.link.css({'display':'none'});
    };
    
    if (this.options.control) {
      $.each(this.controls, function(i, el) {
        $(el).removeClass('active');
      });
      $(this.controls[this.imgInc]).addClass('active');
    }

    this.inc = 0;

    switch (this.options.effect) {
      case 'effect1':
        $.bind(this, this.effects.effect1)();
        break;
      case 'effect2':
        $.bind(this, this.effects.effect2)();
        break;
      case 'effect3':
        $.bind(this, this.effects.effect3)();
        break;
    };
	
  },

  shuffle: function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  },
  
  
  effects: {

    effect1: function() {
      for (i=0; i < this.order.length; i++) {
          $(this.dom.strip[i]).css( 'bottom', 'auto' );
          this.order[i] = i;
      };
    },
	
	effect2: function() {

    },
    
    effect3: function() {
      for (i=0; i < this.order.length; i++) {
        if (i%2 == 0) {
          $(this.dom.strip[i]).css( 'bottom', 0 );
        } else {
          $(this.dom.strip[i]).css( 'bottom', 'auto' );
        };
      };
    },
	
	random: function() {
	// Proximamente en la versión 1.1
    }
    
  },
  
  numberStrips: function(itemId) {
    if (this.inc == this.options.numberStrips) {

      clearInterval(this.stripInterval);
      
      setTimeout($.bind(this, function() {this.pause = false;} ), this.options.speedStrip);
      return false;
    };
    
    this.pause = true;
    
    var strip = $(this.dom.strip[itemId]);
    
    if (!ie6) {
      strip.css({ 'opacity' : 0 });
    };

    if (this.options.effect == 'effect2' || this.options.usewidth == true) {
      currWidth = strip.width();
      
      strip.css({
        'width'   : 0,
        'background-image' : 'url('+this.img[this.imgInc]+')'
      });
      
      strip.animate({
        'width'   : currWidth,
        'opacity' : 1
      }, this.options.speedStrip);

    } else {

      strip.css({
        'height'  : 0,
        'background-image' : 'url('+this.img[this.imgInc]+')'
      });

      strip.animate({
        'height'  : this.options.height,
        'opacity' : 1
      }, this.options.speedStrip);
      
    }

    this.inc++;
  }

	});


	$.fn.chocoslider = function(options) {
    this.each(function() {
      if (!this.SSObject) {
        this.SSObject = new SSPrototype().init(this, options);
      };
      return this.SSObject;
    });
  };

})(jQuery);
