jQuery(function(){
  initPlugins();
  initSlideShow();
  hoverForIE6('#nav > li');
});

//ie6 hover
function hoverForIE6(h_list, h_class){
  if($.browser.msie && $.browser.version < 7){
    if(!h_class) var h_class = 'hover';
    $(h_list).mouseenter(function(){
      $(this).addClass(h_class);
    }).mouseleave(function(){
      $(this).removeClass(h_class);
    });
  }
}

function initPlugins(){
  jQuery('div#header').fadeGallery({
    slideElements:'ul.gallery > li',
    autoRotation:true,
    switchTime:5000,
    duration:500
  });
  jQuery('ul.side-nav > li').OpenClose({
    activeClass:'active',
    opener:'a.opener',
    slider:'.slide',
    slideSpeed: 200
  });
  jQuery('div.image').corner({
    tl: { radius: 10 },
    tr: { radius: 10 },
    bl: { radius: 10 },
    br: { radius: 10 },
    antiAlias: true,
    autoPad: false,
    validTags: ["div"]
  });
}

function initSlideShow(){
  var slideshow = $('div.gallery-box').slideshow();
  slideshow.slides.bind('click',function(){
    if (!slideshow.busy) slideshow.nextSlide();
    return false;
  });
}

//create jQuery plugin
$.fn.slideshow = function(options){return new slideshow(this, options);}

//constructor
function slideshow(obj, options){this.init(obj,options)}

//prototype
slideshow.prototype = {
  init:function(obj, options) {
    this.options = $.extend({
      slides:'div.frame > ul >li',
      nextBtn:'a.btn-next',
      prevBtn:'a.btn-prev',
      pagingHolder:'div.switcher',
      pagingTag:'li',
      createPaging:true,
      autoPlay:false,
      dynamicLoad:false,
      imgAttr:'alt',
      effect:'fade',//fade, slideX, slideY,
      startSlide:false,
      switchTime:5000,
      animSpeed:700
    },options);
    
    this.mainHolder = $(obj);
    this.slides = $(this.options.slides,this.mainHolder);    
    this.nextBtn = $(this.options.nextBtn,this.mainHolder);
    this.prevBtn = $(this.options.prevBtn,this.mainHolder);
    this.dynamicLoad = this.options.dynamicLoad;
    this.imgAttr = this.options.imgAttr;
    this.animSpeed = this.options.animSpeed;
    this.switchTime = this.options.switchTime;
    this.effect = this.options.effect;
    this.autoPlay = this.options.autoPlay;
    this.previous = -1;
    this.loadingFrame = 1;
    this.busy = false;
    this.direction = 1;
    this.timer;
    this.pagingArray = new Array;
    this.loadArray = new Array;
    this.preloader = new Array;
    this.slidesParent = this.slides.eq(0).parent();
    this.slideW = this.slidesParent.width();
    this.slideH = this.slidesParent.height();
    
    (function(){
      if (this.options.startSlide) this.current = this.options.startSlide
      else {
        var active = -1;
        for(var i = 0; i< this.slides.length-1; i++) {
          if (this.slides.eq(i).hasClass('active')) {
            active = i;
            break;            
          }
        }
        if (active != -1) this.current = active;
        else this.current = 0;
      }
    }).apply(this);
    
    this.initPaging();
    this.setStyles();
    this.bindEvents();
    this.showSlide();
  },
  
  initPaging:function(){
    var obj = this;
    this.pagingHolder = $(this.options.pagingHolder,this.mainHolder);
    
    if (this.options.createPaging) {
      this.pagingHolder.each(function(i){
        var _this = $(this);
        _this.empty();
        var list = $('<ul>');
        for (var i = 0; i < obj.slides.length; i++) $('<li><a href="#">' + (i + 1) + '</a></li>').appendTo(list);
        _this.append(list);
      });
    }
    
    this.paging = $(this.options.pagingTag, this.pagingHolder);
    var ratio = Math.ceil(this.paging.length / this.slides.length);
    for (var i = 0; i < ratio; i++) {
      this.pagingArray.push(this.paging.slice(i*this.slides.length, (i*this.slides.length)+this.slides.length));
    }
  },
  
  setStyles:function(){
    //loader
    if (this.dynamicLoad) {
      this.loader = $('<div class="loader">');
      this.loaderDiv = $('<div>').appendTo(this.loader)
      this.loader.append(this.loaderDiv).appendTo(this.slidesParent);
    }
    
    //slides
    if (this.effect == 'fade') {
      this.slides.css({display:'none'});
      this.slides.eq(this.current).css({display:'block'});
    } else if (this.effect == 'slideX'){
      this.slides.css({display: 'none',left:-this.slideW});
      this.slides.eq(this.current).css({display:'block',left:0});
    } else if (this.effect == 'slideY'){
      this.slides.css({display:'none',top:-this.slideH});
      this.slides.eq(this.current).css({display:'block',top:0});
    }
  },
  
  bindEvents:function(){
    var obj = this;
    this.nextBtn.bind('click',function(){
      if (!obj.busy) obj.nextSlide();
      return false;
    });
    
    this.prevBtn.bind('click',function(){
      if (!obj.busy) obj.prevSlide();
      return false;
    });
    
    for (var i = 0; i < this.pagingArray.length; i++) {
      this.pagingArray[i].each(function(i){
        $(this).bind('click',function(){
          if (i != obj.current && !obj.busy) {
            obj.previous = obj.current;
            obj.current = i;
            if (obj.previous > i) obj.direction = -1
            else obj.direction = 1;
            obj.showSlide();
          }
          return false;
        });
      });
    }
    
    if (this.dynamicLoad) this.loader.bind('click',function(){
      obj.abortLoading();
    });
  },
  
  nextSlide:function(){
    this.previous = this.current;
    if (this.current < this.slides.length-1) this.current++
    else this.current = 0;
    this.direction = 1;
    this.showSlide();
  },
  
  prevSlide:function(){
    this.previous = this.current;
    if (this.current > 0) this.current--
    else this.current = this.slides.length-1;
    this.direction = -1;
    this.showSlide();
  },
  
  showSlide:function(){
    var obj = this;
    
    if (this.previous == this.current) return; 
    
    var _current = this.current;
    this.busy = true;
    clearTimeout(this.timer);
    
    if (typeof this.loadArray[_current] != 'undefined' || !this.dynamicLoad) {
      //slide already loaded
      this.switchSlide();
    
    } else {
      //slide not loaded
      this.showLoading();
      var images = $(this.dynamicLoad,this.slides.eq(this.current));
      if (images.length) {
        var counter = 0;
        images.each(function(){
          var preloader = new Image;
          obj.preloader.push(preloader);
          var img = $(this);
          preloader.onload = function(){
            counter++;
            checkImages();
          }
          preloader.onerror = function(){
            //ignore errors
            counter++;
            checkImages();
          }
          preloader.src = img.attr(obj.imgAttr);
        });
        
        function checkImages(){
          if (counter == images.length) {
            images.each(function(){
              var img = $(this);
              img.attr('src',img.attr(obj.imgAttr));
            });
            successLoad();
          }
        }
        
      } else successLoad();
    }
    
    function successLoad(){
      obj.loadArray[_current] = 1;
      obj.hideLoading();
      obj.switchSlide();
    }
  },
  
  switchSlide:function(){
    var obj = this;
    
    if (this.previous != -1) {
      var nextSlide = this.slides.eq(this.current);
      var prevSlide = this.slides.eq(this.previous);
      
      if (this.effect == 'fade') {
        nextSlide.css({display:'block',opacity:0}).animate({opacity:1},this.animSpeed,function(){
          $(this).css({opacity:'auto'});
        });
        prevSlide.animate({opacity:0},this.animSpeed,callback);
      } else if (this.effect == 'slideX'){
        nextSlide.css({display:'block',left:this.slideW*this.direction}).animate({left:0},this.animSpeed);
        prevSlide.animate({left:-this.slideW*this.direction},this.animSpeed+10,callback);
      } else if (this.effect == 'slideY'){
        nextSlide.css({display:'block',top:this.slideH*this.direction}).animate({top:0},this.animSpeed);
        prevSlide.animate({top:-this.slideH*this.direction},this.animSpeed+10,callback);
      }
    } else {
      if (this.autoPlay) this.startAutoPlay();
      this.busy = false;
    }
    
    this.refreshStatus();
    
    function callback(){
      prevSlide.css({display:'none'});
      if (obj.autoPlay) obj.startAutoPlay();
      obj.busy = false;
    }
  },
  
  refreshStatus:function(){
    for (var i = 0; i < this.pagingArray.length;i++) {
      this.pagingArray[i].eq(this.previous).removeClass('active');
      this.pagingArray[i].eq(this.current).addClass('active');
    }
    this.slides.eq(this.previous).removeClass('active');
    this.slides.eq(this.current).addClass('active');
  },
  
  showLoading:function(){
    var obj = this;
    this.loader.show();
    clearInterval(this.loadingTimer);
    obj.loadingTimer = setInterval(animateLoading, 66);
    
    function animateLoading(){
      obj.loaderDiv.css('top', obj.loadingFrame * -40);
      obj.loadingFrame = (obj.loadingFrame + 1) % 12;
    }
  },
  
  hideLoading:function(){
    this.loader.hide();
    clearInterval(this.loadingTimer);
  },
  
  abortLoading:function(){
    this.busy = false;
    this.hideLoading();
    this.current = this.previous;
    for (var i = 0; i < this.preloader.length; i++) {
      this.preloader[i].onload = null;
      this.preloader[i].onerror = null;
    }
    if (this.autoPlay) this.startAutoPlay();
  },
  
  startAutoPlay:function(){
    var obj = this;
    clearTimeout(obj.timer);
    obj.timer = setTimeout(function(){
      obj.nextSlide();
    },obj.switchTime);
  }
}

// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
  var _options = jQuery.extend({
    slideElements:'div.slideset > div',
    pagerLinks:'div.paging a',
    generatePagination:'div.paging',
    paginationUlClass:'switcher',
    switcherClasses:'',
    switcherClassTo:'a',
    currentNumSlide:'.count .current',
    indexOfNumsSlides:'.count .indexof',
    alwaysPutZero:true,
    btnPauseToSwitcher:'false',
    btnNext:'a.next',
    btnPrev:'a.prev',
    btnPlayPause:'a.play-pause',
    btnPlay:'a.play',
    btnPause:'a.pause',
    pausedClass:'paused',
    disabledClass: 'disabled',
    playClass:'playing',
    activeClass:'active',
    loadingClass:'ajax-loading',
    loadedClass:'slide-loaded',
    dynamicImageLoad:false,
    dynamicImageLoadAttr:'alt',
    currentNum:false,
    allNum:false,
    startSlide:null,
    noCircle:false,
    pauseOnHover:true,
    autoRotation:false,
    autoHeight:false,
    onInit:false,
    onBeforeFade:false,
    onAfterFade:false,
    onChange:false,
    disableWhileAnimating:false,
    switchTime:3000,
    duration:650,
    event:'click'
  },_options);

  return this.each(function(){
    // gallery options
    if(this.slideshowInit) return; else this.slideshowInit;
    var _this = jQuery(this);
    var _slides = jQuery(_options.slideElements, _this);
    var _pagerLinks = jQuery(_options.pagerLinks, _this);
    var _generatePagination = jQuery(_options.generatePagination, _this);
    var _paginationUlClass = _options.paginationUlClass;
    var _switcherClasses = _options.switcherClasses;
    var _switcherClassTo = _options.switcherClassTo;
    var _currentNumSlide = jQuery(_options.currentNumSlide, _this);
    var _indexOfNumsSlides = jQuery(_options.indexOfNumsSlides, _this);
    var _alwaysPutZero = _options.alwaysPutZero;
    var _btnPauseToSwitcher = _options.btnPauseToSwitcher;
    var _btnPrev = jQuery(_options.btnPrev, _this);
    var _btnNext = jQuery(_options.btnNext, _this);
    var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
    var _btnPause = jQuery(_options.btnPause, _this);
    var _btnPlay = jQuery(_options.btnPlay, _this);
    var _pauseOnHover = _options.pauseOnHover;
    var _dynamicImageLoad = _options.dynamicImageLoad;
    var _dynamicImageLoadAttr = _options.dynamicImageLoadAttr;
    var _autoRotation = _options.autoRotation;
    var _activeClass = _options.activeClass;
    var _loadingClass = _options.loadingClass;
    var _loadedClass = _options.loadedClass;
    var _disabledClass = _options.disabledClass;
    var _pausedClass = _options.pausedClass;
    var _playClass = _options.playClass;
    var _autoHeight = _options.autoHeight;
    var _duration = _options.duration;
    var _switchTime = _options.switchTime;
    var _controlEvent = _options.event;
    var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
    var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
    var _startSlide = _options.startSlide;
    var _noCycle = _options.noCircle;
    var _onChange = _options.onChange;
    var _onBeforeFade = _options.onBeforeFade;
    var _onAfterFade = _options.onAfterFade;
    var _onInit = _options.onInit;
    var _disableWhileAnimating = _options.disableWhileAnimating;
    
    if(_switcherClasses){_switcherClasses = _switcherClasses.split((/\s*,\s*/));}
    
    // gallery init
    var _anim = false;
    var _hover = false;
    var _prevIndex = 0;
    var _currentIndex = 0;
    var _slideCount = _slides.length;
    var _timer;
    var _switcherIndex = 0;
    if(_slideCount < 2) return;
    
    changeNum();
    function changeNum(){
      if(_currentNumSlide.length){
        if(_alwaysPutZero == false){
          _currentNumSlide.text(_currentIndex + 1);
        }else{
          if(_currentIndex + 1 < 10){
            var curIndNum = '0' + (_currentIndex + 1);
            _currentNumSlide.text(curIndNum);
          }
        }
      }
      if(_indexOfNumsSlides){
        if(_alwaysPutZero == false){
          _indexOfNumsSlides.text(_slides.length);
        }else{
          if(_slides.length < 10){
            var curIndNum = '0' + _slides.length;
            _indexOfNumsSlides.text(curIndNum);
          }
        }
      }
    }
    
    if(_generatePagination.length) {
      var list = $('<ul class="'+_paginationUlClass+'">');
      var classTagLi = '';
      var classTagA = '';
      for(var i=0; i<_slideCount; i++){
        if(_switcherClasses.length && _switcherClassTo == 'li'){
          classTagLi = ' class="'+_switcherClasses[_switcherIndex]+'"';
        }else if(_switcherClasses.length && _switcherClassTo == 'a'){
          classTagA = ' class="'+_switcherClasses[_switcherIndex]+'"';
        }
        $('<li'+classTagLi+'><a'+classTagA+' href="#">'+(i+1)+'</a></li>').appendTo(list);
        if(_switcherIndex < _switcherClasses.length -1){_switcherIndex++;}else{_switcherIndex = 0;}
      }
      _generatePagination.empty();
      list.appendTo(_generatePagination);
      _pagerLinks = list.children();
      if(_btnPauseToSwitcher == 'true'){_btnPause = list.children();}
    }
    
    _prevIndex = _slides.index(_slides.filter('.'+_activeClass));
    if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
    else _currentIndex = _prevIndex;
    if(_startSlide != null) {
      if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
      else _prevIndex = _currentIndex = parseInt(_startSlide);
    }
    _slides.hide().eq(_currentIndex).show();
    if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
    else _this.removeClass(_playClass).addClass(_pausedClass);


    // gallery control
    if(_btnPrev.length) {
      _btnPrev.bind(_controlEvent,function(){
        prevSlide();
        return false;
      });
    }
    if(_btnNext.length) {
      _btnNext.bind(_controlEvent,function(){
        nextSlide();
        return false;
      });
    }
    if(_pagerLinks.length) {
      _pagerLinks.each(function(_ind){
        jQuery(this).bind(_controlEvent,function(){
          if(_currentIndex != _ind) {
            if(_disableWhileAnimating && _anim) return;
            _prevIndex = _currentIndex;
            _currentIndex = _ind;
            switchSlide();
          }
          return false;
        });
      });
    }

    // play pause section
    if(_btnPlayPause.length) {
      _btnPlayPause.bind(_controlEvent,function(){
        if(_this.hasClass(_pausedClass)) {
          _this.removeClass(_pausedClass).addClass(_playClass);
          _autoRotation = true;
          autoSlide();
        } else {
          _autoRotation = false;
          if(_timer) clearTimeout(_timer);
          _this.removeClass(_playClass).addClass(_pausedClass);
        }
        return false;
      });
    }
    if(_btnPlay.length) {
      _btnPlay.bind(_controlEvent,function(){
        _this.removeClass(_pausedClass).addClass(_playClass);
        _autoRotation = true;
        autoSlide();
        return false;
      });
    }
    if(_btnPause.length) {
      _btnPause.bind(_controlEvent,function(){
        _autoRotation = false;
        if(_timer) clearTimeout(_timer);
        _this.removeClass(_playClass).addClass(_pausedClass);
        return false;
      });
    }

    // dynamic image loading (swap from ATTRIBUTE)
    function loadSlide(slide) {
      if(!slide.hasClass(_loadingClass) && !slide.hasClass(_loadedClass)) {
        var images = slide.find(_dynamicImageLoad) // pass selector here
        var imagesCount = images.length;
        if(imagesCount) {
          slide.addClass(_loadingClass);
          images.each(function(){
            var img = this;
            img.onload = function(){
              img.loaded = true;
              img.onload = null;
              setTimeout(reCalc,_duration);
            }
            img.setAttribute('src', img.getAttribute(_dynamicImageLoadAttr));
            img.setAttribute(_dynamicImageLoadAttr,'');
          }).css({opacity:0});

          function reCalc() {
            var cnt = 0;
            images.each(function(){
              if(this.loaded) cnt++;
            });
            if(cnt == imagesCount) {
              slide.removeClass(_loadingClass);
              images.animate({opacity:1},{duration:_duration,complete:function(){
                if(jQuery.browser.msie && jQuery.browser.version < 9) jQuery(this).css({opacity:'auto'})
              }});
              slide.addClass(_loadedClass)
            }
          }
        }
      }
    }

    // gallery animation
    function prevSlide() {
      if(_disableWhileAnimating && _anim) return;
      _prevIndex = _currentIndex;
      if(_currentIndex > 0) _currentIndex--;
      else {
        if(_noCycle) return;
        else _currentIndex = _slideCount-1;
      }
      switchSlide();
    }
    function nextSlide() {
      if(_disableWhileAnimating && _anim) return;
      _prevIndex = _currentIndex;
      if(_currentIndex < _slideCount-1) _currentIndex++;
      else {
        if(_noCycle) return;
        else _currentIndex = 0;
      }
      switchSlide();
    }
    function refreshStatus() {
      if(_dynamicImageLoad) loadSlide(_slides.eq(_currentIndex));
      if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
      if(_currentNum) _currentNum.text(_currentIndex+1);
      if(_allNum) _allNum.text(_slideCount);
      _slides.eq(_prevIndex).removeClass(_activeClass);
      _slides.eq(_currentIndex).addClass(_activeClass);
      if(_noCycle) {
        if(_btnPrev.length) {
          if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
          else _btnPrev.removeClass(_disabledClass);
        }
        if(_btnNext.length) {
          if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
          else _btnNext.removeClass(_disabledClass);
        }
      }
      if(typeof _onChange === 'function') {
        _onChange(_this, _slides, _prevIndex, _currentIndex);
      }
    }
    function switchSlide() {
      _anim = true;
      if(typeof _onBeforeFade === 'function') _onBeforeFade(_this, _slides, _prevIndex, _currentIndex);
      _slides.eq(_prevIndex).fadeOut(_duration,function(){
        _anim = false;
      });
      _slides.eq(_currentIndex).fadeIn(_duration,function(){
        if(typeof _onAfterFade === 'function') _onAfterFade(_this, _slides, _prevIndex, _currentIndex);
      });
      if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
      refreshStatus();
      autoSlide();
      changeNum();
    }

    // autoslide function
    function autoSlide() {
      if(!_autoRotation || _hover) return;
      if(_timer) clearTimeout(_timer);
      _timer = setTimeout(nextSlide,_switchTime+_duration);
    }
    if(_pauseOnHover) {
      _this.hover(function(){
        _hover = true;
        if(_timer) clearTimeout(_timer);
      },function(){
        _hover = false;
        autoSlide();
      });
    }
    refreshStatus();
    autoSlide();
    
    _this.bind('setslide',function(e,h){
      if(_currentIndex != h.num) _prevIndex = _currentIndex;
      _currentIndex = h.num;
      switchSlide();
    })
  });
}

// open-close plugin
jQuery.fn.OpenClose = function(_options){
  // default options
  var _options = jQuery.extend({
    activeClass:'active',
    opener:'.opener',
    slider:'.slide',
    slideSpeed: 400,
    animStart:false,
    animEnd:false,
    event:'click'
  },_options);

  return this.each(function(){
    // options
    var _holder = jQuery(this);
    var _slideSpeed = _options.slideSpeed;
    var _activeClass = _options.activeClass;
    var _opener = jQuery(_options.opener, _holder);
    var _slider = jQuery(_options.slider, _holder);
    var _animStart = _options.animStart;
    var _animEnd = _options.animEnd;
    var _event = _options.event;
    if(_slider.length) {
      _opener.bind(_event,function(){
        if(!_slider.is(':animated')) {
          if(typeof _animStart === 'function') _animStart();
          if(_holder.hasClass(_activeClass)) {
            _slider.slideUp(_slideSpeed,function(){
              if(typeof _animEnd === 'function') _animEnd();
            });
            _holder.removeClass(_activeClass);
          } else {
            _holder.addClass(_activeClass);
            _slider.slideDown(_slideSpeed,function(){
              if(typeof _animEnd === 'function') _animEnd();
            });
          }
        }
        return false;
      });
      if(_holder.hasClass(_activeClass)) _slider.show();
      else _slider.hide();
    }
  });
} 
