var ProgressBar = function(target, options){
  // default options
  var defaults = {
    sections:6,
    handleColor:'#333',
    easingMethod: 'swing',
    dur:200
  };
  var options = $.extend(defaults, options);
  var indicator = $('<div class="progressIndicator"></div>');
  var currPercent = 0;
  var sectionLength = target.width()/options.sections;
  
  indicator.css({position:'absolute', top:0, left:0, height:target.height(), width:0, backgroundColor:options.handleColor});
  target.append(indicator);
  
  var step = function(){
    indicator.width(indicator.width()+1);
  };
  
  var setIndicator = function(x){
    indicator.width(x)
  }
  
  var stepTo = function(percent){
    indicator.animate({width : target.width() * percent}, { duration:options.dur, easing:options.easingMethod });
    currPercent = percent;
  };
  var getPercentage = function(){
    return Math.floor(indicator.width()/target.width() * 100);
  };
  
  var inSection = function(){
    return indicator.width()/sectionLength;
  }
  
  //public functions
  return {
    step:step,
    stepTo:stepTo,
    getPercentage:getPercentage,
    inSection:inSection,
    setIndicator:setIndicator
  }
}





$.fn.iwcSlider = function(options) {
  
  // default options
  var defaults = {
    type:'detail',
    height:255,
    easingMethod :'swing',
    duration:300,
    speed: 30,
    progressHeight:6,
    timer:true
  };
  
  var options = $.extend(defaults, options);
  var surrogate = this;
  var wrap = $('<div class="iwcSlider '+ options.type +'"></div>');
  var textOverlay = $('<div class="textOverlay"></div>');
  var textTrack = $('<div class="textTrack"></div>');
  var imgHolder = $('<div class="imgHolder"></div>');
  var textHolder = $('<div class="textHolder"></div>');
  var progressBar = $('<div class="progressBar"></div>');
  var playPause = $('<div class="playPause"></div>');
  var indicator = $('<div class="indicator"></div>');
  var lis = $('li', this);
  var list = $(this.find('ul'));
  var imgs = lis.find('img');
  var liWidth = Math.floor(this.width()/lis.length);
  var textList = this.clone();
  var currIndex = 0;
  var headers = lis.find('h4');
  var titles = lis.find('h3');
  var hColor = $(headers[0]).css('color'); //initial header color
  var hHeight; //header height
  var totalHeight;//total height of the slider module
  var timer; //timeout timer
  var pb; //progress bar
  var isPaused = false;
  
  //set dimensions, add dom elements, add event listeners
  var init = function(){
        
    //wrap the ul with the wrapper element
    surrogate.wrap(wrap);

    //set the image holder dimensions and   
    imgHolder.width(surrogate.width()).height(options.height).html(imgs);
    
    //set the header positions and text
    headers.css({marginTop:options.height + options.progressHeight});

    switch(options.type){ // parse out the content to display
      
      case 'detail':
      headers.each(function(){
        var sur = $(this);
        sur.html('<span>0' + (headers.index(sur)+1) + '.</span> ' + sur.text());
      });
      break;
      
      case 'family':
      for(var i = 0;i<lis.length;i++){
        var h = $(lis[i]).children('h4').text();
        var p = $(lis[i]).children('p');
        var a = $(lis[i]).children('p').children('a').detach();
        p.html('<span><strong>'+ h +' &mdash; </strong>' + p.html() + '</span>').append(a);
      }
      headers.each(function(){
        var sur = $(this);
        sur.html('<span>0' + (headers.index(sur)+1) + '.</span>');
      });
      break;
      
      case 'homepage':
      for(var i = 0;i<lis.length;i++){
        var t = $(lis[i]).children('h3').text();
        var h = $(lis[i]).children('h4').text();
        var p = $(lis[i]).children('p')
        p.html('<span class="title ' + $(lis[i]).children('h3')[0].className + '">'+ t +'</span><span class="main"><strong>'+ h +' </strong>' + p.html() + '</span>');
      }
      
      headers.each(function(){
        var sur = $(this);
        sur.html('<span>0' + (headers.index(sur)+1) + '.</span>');
      });
      titles.hide();
      break;
      
      case 'homepage-titles':
      for(var i = 0;i<lis.length;i++){
        //var t = $(lis[i]).children('h3').text();
        var t = ''
        var h = $(lis[i]).children('h4').text();
        var p = $(lis[i]).children('p')
        p.html('<span class="title ' + $(lis[i]).children('h3')[0].className + '">'+ t +'</span><span class="main"><strong>'+ h +' </strong>' + p.html() + '</span>');
      }
      
      headers.each(function(){
        var sur = $(this);
        if(jQuery.trim(sur.prev().text())!="")
          sur.html(sur.prev().text());
        else{
          if(jQuery.trim($('img:eq('+headers.index(sur)+')',imgHolder).attr('alt'))!="")
            sur.html(jQuery.trim($('img:eq('+headers.index(sur)+')',imgHolder).attr('alt')));
          else
            sur.html('<span>0' + (headers.index(sur)+1) + '.</span>');
        }
      });
      titles.hide();
      break;
    }

    hHeight = $(headers[0]).outerHeight(); //set the height
    
    //set progress bar and text holder positions
    var texts = lis.children('p').clone();
    texts.hide().appendTo(textHolder);
    
    lis.width(liWidth - 1).bind('click', function(e){onLiClick(e, this);}).children('p').remove();
    
    if(options.type != 'homepage' && options.type != 'homepage-titles'){
      textHolder.css({bottom:hHeight + options.progressHeight});
    }
    
    surrogate.before(imgHolder).after(textHolder); //set ul height, insert stuff
    textOverlay.width(liWidth).height(hHeight).insertBefore(surrogate); //text overlay
    
    progressBar.css({bottom:hHeight}).width(surrogate.width()).insertAfter(surrogate);
    pb = new ProgressBar(progressBar, {sections:lis.length, dur:options.duration, easingMethod:options.easingMethod, handleColor:'#bf1e2e'});
    
    indicator.css({bottom:hHeight, left:liWidth/2}).insertAfter(progressBar);
    
    lis.append(playPause);
  
    
    //get it goin on    
    timerGo();
    highLight(0);
  }
  
  var timerGo = function(){
    timer = setInterval(function(){
      pb.step();
      var indPos =  Math.floor(pb.inSection());
      if(indPos < lis.length){
        if(currIndex != indPos){
          currIndex = indPos;
          highLight(indPos);
        }
      }else{
        highLight(0);
        pb.setIndicator(0);
      }      
    },options.speed);
  }
  
  var timerStop = function(){
    clearInterval(timer);
  }
  
  //list item click handler
  var onLiClick = function(e, t){
    if($(e.target).hasClass('playPause')){ //if the pause button is clicked
      if(isPaused){
        timerGo();
        isPaused = false;
        surrogate.find('.playPause').removeClass('play');
        
      }else{
        timerStop();
        isPaused = true;
        surrogate.find('.playPause').addClass('play');
        
      }
    }else{      
      var num = lis.index(t);
      highLight(num, true);    
      currIndex = num;
      timerStop();
    }
  }
    
  //show the image and animate the progress bar
  var highLight = function(num, clicked){
    var theLi = $(lis[num]);
    var theImg = $(imgs[num]);
    var theHeader = $(headers[num]);
    var theP = $(textHolder.find('p')[num]);
    var pauseBtn = theLi.find('.playPause');
    var indicatorTarget = theLi.position().left + theLi.width()/2 - indicator.width()/2;
    
    headers.not(headers[num]).animate({color:hColor});
    theP.fadeIn(options.duration).siblings('p').fadeOut(options.duration);
    
    surrogate.find('.playPause').not(pauseBtn).fadeOut();
    pauseBtn.fadeIn();
    
    theImg.css({'z-index':1}).fadeIn(options.duration * 1.5).siblings().css({'z-index':0}).fadeOut(options.duration);
    if(clicked){ 
      pb.stepTo(num/lis.length); //animate progress bar
    }
    theHeader.animate({color:'#ffffff'});
    indicator.stop().animate({left : indicatorTarget}, {duration:options.duration, easing:options.easingMethod});
    textOverlay.stop().animate({left : theLi.position().left}, {duration:options.duration, easing:options.easingMethod, complete: function(){
        if(clicked && !isPaused){
          timerGo();
        }
      }
    });
  }

  //intialize!  
  init();

  return this.each(function(){});
}


