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

    $roto = $.fn.roto; 

    return this.each(function(){
      $this = $(this);
      set_opts($.extend({}, $.fn.roto.defaults,options),$this.attr('id'));
      var pattern = String(opts().pattern);
      try{$.fn.roto[pattern]();} catch(error) { alert(error) }         
    });

  }
  
  $.fn.roto.swatchScaffold = function() {

    var el = opts().swatch.parent;
    var swatches = $(div(el));
    swatches.html("<ul></ul>")

    $this.append(swatches)
    
    $.each(opts().assets,function(i){
      var item =  '<li>'+img(this.thumb)+'<p>'+this['title']+'</p></li>'
      item = $(item).click(function(){attach_focus(i)});
      swatches.find('ul').append(item)
    })
  }
  
  $.fn.roto.slides = function(){
    build_slide_arr()
    $(opts().slides.list).hide()
    $(opts().assets[0]).show()
    slide_tabs()
    selection(".roto-slide-tabs [rel="+opts().rotate+"]")
    $roto.play('playSlides')
  }
  
  $.fn.roto.focus = function(asset){ 

    var focus = opts().focus.parent 
    var imgg = img(asset.img)
    var wrap = asset.title+"<span>(Click here for more videos)</span>"
    var title = '<a href="'+asset.path+'">'+div('roto-title',wrap)+'</a>'

    if(!exsist(focus)) { 
      focus = div(opts().focus.parent); 
      $this.append(focus); 
      focus = opts().focus.parent 
    } // think about this one...
    
    $(focus).html(imgg).append(title)
      
  }
  
  $.fn.roto.shuffle =function(){
    if( opts().assets.length <= 0 ) { build_asset_arr(); } else { $.fn.roto['swatchScaffold']()  }
    $roto.focus(opts().assets[0])
    $roto.play() 
    set_opts({rotate: opts().rotate + 1 })
    var list = "." + $this.attr('class') + " " + opts().swatch.parent + " ul"
  }
  
  $.fn.roto.play = function(action){ 
    $roto.flush()
    $roto.startRotate = setInterval(function(){
      $roto[(action ||'playShuffle')]()
    },opts().delay)
  }
  
  $.fn.roto.pause = function() {
    $roto.flush()
    setTimeout('$roto.play()', 120000 )         // upond idle resume after 2 minutes
  }  

  $.fn.roto.flush = function() {clearTimeout($roto.startRotate) }   
  
  $.fn.roto.playShuffle = function(){
    var len = opts().assets.length - 1;
    var count = opts().rotate;
    $.fn.roto['focus'](opts().assets[count])
    count = (count >= len) ? 0 : count + 1;
    set_opts({rotate:count})
  }
  
  $.fn.roto.playSlides = function(slide){
    set_count()
    $(opts().slides.list).hide()
    var position = slide || opts().rotate;
    $(opts().assets[position]).show()
    set_opts({rotate:position})
    var set_tab_class = ".roto-slide-tabs [rel="+position+"]"
    selection(set_tab_class)
  }
  
 // Private   
 var invoke = function() { }
 
 var selection = function(item) {
   $('.roto-slide-tabs a').each(function(){$(this).removeAttr('style')})
   $(item).css({color:'#fff',background:"#3d3d3d"})
 }
 
 var set_count = function() {
  var len = opts().assets.length - 1;
  var count = opts().rotate; 
  count = (count >= len) ? 0 : count + 1;
  set_opts({rotate:count}) 
 }
 
 var slide_tabs = function(){
  var list='';
  $.each(opts().assets, function(i){
    count = i+1;
    list += '<li><a href="javascript:void(0)" rel="'+i+'" class="roto-play-slide">'+count+'</a>'
  });
  $('.roto-slide-tabs').append('<ul>'+list+'</ul>')
 }
 
 var build_slide_arr = function() {
   $(opts().slides.list).each(function(i){
      opts().assets[i] = $(this)
      $(this).click(function(){ 
        $roto.play('playSlides') 
        $roto.playSlides()
      });
   })
 }

 var build_asset_arr = function() {
    $(opts().swatch.list).each(function(i){
      var asset_index = i;
      opts().assets[asset_index] = { title: $(this).find('p').text(), img: $(this).find('.roto-thumb').attr('src'), thumb: $(this).find('.roto-thumb').attr('thumb')  };
      $(this).click(function(){ attach_focus(asset_index) });
    })
  }
  
  var attach_focus = function(asset_index) {
    $roto.focus(opts().assets[asset_index])
    $roto.pause()
  }
  
  var opts = function() { return $.fn.roto.defaults }

  var set_opts = function(options) { 
    $.fn.roto.defaults = $.extend({}, $.fn.roto.defaults,options) 
  }

  var exsist = function(el){ 
    return ($(el).size() > 0) ? $(el) : false    //debating this...
  }
  
  var div = function(klass,content) {
   return '<div class="'+klass.replace('.','')+'">'+( content || "" )+'</div>'  
  }
  
  var img = function(path) {
    return '<img src="'+path+'" />'
  }
  
  $.fn.roto.defaults = {
     delay:2500,
     rotate:0, 
     assets:[],
     pattern:'shuffle',
     slides:{parent:'.roto-slides',list: ".roto .roto-slides .roto-slide"},
     swatch:{parent:'.roto-swatch',list: ".roto .roto-swatch ul li" },
     focus:{parent:'.roto-focus'}
  }
  $('.roto-play-slide').live('click',function(){
    $roto.play('playSlides') 
    $roto.playSlides($(this).attr('rel'))
  })
})(jQuery);


(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)