// $Id: main.js 339 2011-09-03 00:24:55Z jerico $

;(function($){

$(function(){

$('ul.events-list li a').hover( function() {
	$(this).children('span').css('background', 'url(/images/bg_trans-pink.png)');
}, function() {
	$(this).children('span').css('background', 'url(/images/bg-png.png)');
});

  initSelectHash();
  initCufon();
  clearInputs();
  initCustomForms();
//  initThemePicker();
  initOverlays();
  initGallerys();
  initMainGallery();
  initSlideSelect();
});

function initSlideSelect(){
  var duration = 350;
  var holder = $('div.form div.drop-box');
  var opener = $('a.link',holder);
  var slide = $('div.dropdown',holder);
  var list = $('>ul',slide);

  opener.click(function(){
    if (!list.is(':animated')) {
      if (slide.is(':hidden')) {
        slide.show();
        var h = list.outerHeight();
        list.css({marginTop:-h}).animate({marginTop:0},duration);
      } else {
        var h = list.outerHeight();
        list.animate({marginTop:-h},duration,function(){
          slide.hide();
        });
      }
    }
    return false;
  })
}

function initSelectHash(){
  var select = $('select.purpose');
  if (select.length) {
    var hash = window.location.hash;
    window.location.hash = '';
    if (hash.length) {
      var option = $(hash);
      if (option.length) {
        option.attr('selected','selected');
      }
    }
  }
}

function initMainGallery(){
  //thubmnaul/fullscreen view
  var holder = $('div.main-gallery')
  var thumbnailHolder = $('div.thumbnail-view',holder)
  var fullscreenHolder = $('div.fullscreen-view',holder)

  var fullscreenOpener = $('a.fullscreen-opener',thumbnailHolder);
  var thumbnailOpener = $('a.thumbnail-opener',fullscreenHolder);

  var thumbnailGallery = thumbnailHolder.scrollGallery({
    holder:'div.carusel-page div.mask',
    afterRefreshStatus:function(){
      Cufon.refresh('#main h2');
    }
  });

  var meta = $('ul.meta > li',fullscreenHolder);
  var heading = $('div.heading div.holder',fullscreenHolder)
  var fullscreenGallery = fullscreenHolder.slideshow({
    slides:'div.caruselfull-page > div > ul > li',
    nextBtn:'a.next',
    prevBtn:'a.prev',
    afterRefreshStatus:function(){
      var headingText = meta.eq(fullscreenGallery.current).html();
      heading.html(headingText);
      Cufon.refresh('#main h2');
    }
  })

  fullscreenOpener.click(function(){
    thumbnailHolder.hide();
    fullscreenHolder.show();
    fullscreenGallery.goToSlide(thumbnailGallery.current*2);
    return false;
  });

  thumbnailOpener.click(function(){
    fullscreenHolder.hide();
    thumbnailHolder.show();
    thumbnailGallery.goToSlide(Math.floor(fullscreenGallery.current/2));
    return false;
  });

  thumbnailHolder.find('div.mask > ul > li > a').each(function(i){
    $(this).attr('data-index', i);
    $(this).click(function(){
      if (fullscreenGallery.current != $(this).attr('data-index')) {
        $('li',fullscreenHolder).hide();
      }
      thumbnailHolder.hide();
      fullscreenHolder.show();
      fullscreenGallery.goToSlide(i);
      return false;
    });
  });
}

function initGallerys(){
  //fade dynamic img gallery + circle switcher
  $('div.area div.imgs').each(function(){
    var _this = $(this);
    var switcher = $('div.thumbs',_this).carousel();
    _this.slideshow({
      onChange:function(nextInd,direction){
        switcher.move(nextInd,direction);
      }
    });
  });

  //scroll dynamic img gallery
  $('div.wedding-carusel').each(function(){
    $(this).scrollGallery({
      holder:'div.mask > div',
      step:1
    });
  })
}

//bg color picker
function initThemePicker(){
  //colors arrays
  var romanticColors = ['#b2003e','#b2003e','#b2003e','#b2003e','#b2003e'];
  var freshColors = ['url(/images/bg1.jpg) center top repeat','url(/images/bg1.jpg) center top repeat','url(/images/bg1.jpg) center top repeat','url(/images/bg1.jpg) center top repeat','url(/images/bg1.jpg) center top repeat'];
  var mellowColors = ['url(/images/watercolor1.jpg) fixed center bottom no-repeat'];

  var body = $('body');
  var chooseHolder = $('div.choose');
  var confirmHolder = $('div.choosen');
  var colorLinks = $('div.holder a',chooseHolder);
  var colorsArray = [romanticColors,freshColors,mellowColors];
  var lightboxOpener = $('#footer a.change-color');
  var lightboxObj = lightboxOpener.modalPopup();
  var colorLinksLightbox = $('div.holder a',lightboxObj.popup);

  var duration = 60000;
  var timer;
  var activeSet = -1;
  var activeColor = -1;
  getCookie();

  colorLinks.each(function(i){
    var _this = $(this);
    _this.click(function(){
      activeSet = i;
      activeColor = 0;
      setColor();
      chooseHolder.hide();
      confirmHolder.eq(i).show();
      body.removeClass('white-theme');
      Cufon.refresh('#nav a');
      Cufon.refresh('#main h2');
      Cufon.refresh('#footer p');
      Cufon.refresh('#footer li a');
      return false;
    });
  });

  colorLinksLightbox.each(function(i){
    var _this = $(this);
    _this.click(function(){
      activeSet = i;
      activeColor = 0;
      setColor();
      lightboxObj.close();
      return false;
    });
  })

  function setColor(){
    var newcolor = colorsArray[activeSet][activeColor];
    body.css('background', '' + newcolor);
    rotateColors();
    setCookie();
  }

  function rotateColors(){
    clearTimeout(timer);
    timer = setTimeout(function(){
      var cur = colorsArray[activeSet];
      if (activeColor < cur.length-1) activeColor++;
      else activeColor = 0;
      setColor();
    },duration);
  }

  function setCookie(){
    $.cookie('color', activeSet+'#'+activeColor, {path: '/'});
  }

  function getCookie(){
    var colorCookie = $.cookie('color');
    if (colorCookie) {
      color = colorCookie.split('#');
      activeSet = color[0];
      activeColor = color[1];
      setColor();
    } else {
      if (!chooseHolder.length) lightboxObj.show();
    }
  }
}

;(function($){

//create jQuery plugin
$.fn.scrollGallery = function(options){return new scrollGallery(this, options);}

//constructor
function scrollGallery(obj, options){this.init(obj,options)}

//prototype
scrollGallery.prototype = {
  init:function(obj, options) {
    this.options = $.extend({
      holder:'>div',
      slider:'>ul',
      slides:'>li',
      nextBtn:'a.next',
      prevBtn:'a.prev',
      dynamicLoad:'img',
      imgAttr:'alt',
      startSlide:0,
      animSpeed:700,
      allNum:'strong.all-num',
      curNum:'strong.cur-num',
      afterRefreshStatus:null,
      step:false
    },options);

    this.mainHolder = $(obj);

    this.holder = $(this.options.holder,this.mainHolder);
    if (!this.holder.length) return;
    this.slider = $(this.options.slider,this.holder);
    this.slides = $(this.options.slides,this.slider);
    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.allNum = $(this.options.allNum,this.mainHolder);
    this.curNum = $(this.options.curNum,this.mainHolder);
    this.afterRefreshStatus = this.options.afterRefreshStatus;

    this.previous = -1;
    this.current = 0;
    this.loadingFrame = 1;
    this.busy = false;
    this.timer;
    this.loadArray = new Array;
    this.preloader = new Array;
    this.slideW = this.slides.eq(0).outerWidth(true);
    this.visibleStep = Math.round(this.holder.width()/this.slideW);
    this.options.startSlide ? this.current = this.options.startSlide : this.current = 0;
    this.options.step ? this.step = this.options.step : this.step = this.visibleStep;
    this.max = this.slides.length - this.visibleStep;
    this.stepCount = Math.ceil((this.slides.length-this.visibleStep)/this.step)+1;

    //loader
    if (this.dynamicLoad) {
      this.loader = $('<div class="loader">').hide();
      this.loaderDiv = $('<div>').appendTo(this.loader)
      this.loader.append(this.loaderDiv).appendTo(this.mainHolder);
    }

    this.bindEvents();
    this.showSlide();

  },

  bindEvents:function(){
    this.nextBtn.bind('click',function(){
      if (!this.busy) this.nextSlide();
      return false;
    }.bind(this));

    this.prevBtn.bind('click',function(){
      if (!this.busy) this.prevSlide();
      return false;
    }.bind(this));

    if (this.dynamicLoad) this.loader.bind('click',this.abortLoading.bind(this));
  },

  nextSlide:function(){
    this.busy = true;
    this.previous = this.current;
    this.current += this.step;
    if (this.previous == this.max) this.current = 0;
    else if (this.current > this.max) this.current = this.max;
    this.showSlide();
  },

  prevSlide:function(){
    this.busy = true;
    this.previous = this.current;
    this.current -= this.step;
    if (this.previous == 0) this.current = this.max;
    else if (this.current < 0) this.current = 0;
    this.showSlide();
  },

  showSlide:function(){
    var obj = this;
    var _current = this.current;
    var alreadyLoaded = true;
    var toLoadArray = new Array;

    for (var i = _current; i < _current + this.visibleStep; i++) {
      if (typeof this.loadArray[i] == 'undefined') toLoadArray[i] = this.slides.eq(i);
    }
    if (!toLoadArray.length) {
      //slide already loaded
      if (this.previous != -1) this.switchSlide()
    } else {
      if (obj.previous != -1) obj.switchSlide()
      else obj.refreshStatus();
      
      //slide not loaded
      this.showLoading();
      var slide = $();
      for (var i = 0; i < toLoadArray.length; i++)  {
        slide = slide.add(toLoadArray[i]);
      }
      var images = $(this.dynamicLoad,slide);
      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(i){
            var img = $(this);
            img
              .attr('src', img.attr(obj.imgAttr))
              .removeAttr('alt')
              .hide();
            setTimeout(function(){img.fadeIn()}, 50 * i);
          });
          for (var i = _current; i < _current + obj.visibleStep; i++) {
            obj.loadArray[i] = 1;
          }

          obj.hideLoading();
//          if (obj.previous != -1) obj.switchSlide()
//          else obj.refreshStatus();
        }
      }
    }
  },

  goToSlide:function(ind){
    var next = Math.floor(ind/this.step)*this.step;
    if (next > this.max) next = this.max;
    if (next != this.current) {
      this.busy = true;
      this.previous = this.current;
      this.current = next;
      this.showSlide();
    }
  },

  switchSlide:function(instant){
    var obj = this;
    if (instant) this.slider.css({marginLeft:-this.current*this.slideW})
    else this.slider.animate({marginLeft:-this.current*this.slideW},this.options.slideSpeed,function(){
      obj.busy = false;
    });
    this.refreshStatus();
  },

  refreshStatus:function(){
    this.curNum.text(Math.ceil(this.current/this.step)+1);
    this.allNum.text(this.stepCount);

    if (typeof this.afterRefreshStatus === 'function') this.afterRefreshStatus();
  },

  showLoading:function(){
//    var obj = this;
//    this.loader.show();
//    clearInterval(this.loadingTimer);
//    obj.loadingTimer = setInterval(animateLoading, 66);
//
//    function animateLoading(){
//      if (!obj.loader.is(':visible')){
//        clearInterval(obj.loadingTimer);
//        return;
//      }
//      obj.loaderDiv.css('top', obj.loadingFrame * -40);
//      obj.loadingFrame = (obj.loadingFrame + 1) % 12;
//    }
  },

  hideLoading:function(){
    this.loader.hide();
  },

  abortLoading:function(){
    this.busy = false;
    this.loader.hide();
    this.current = this.previous;
    for (var i = 0; i < this.preloader.length; i++) {
      this.preloader[i].onload = null;
      this.preloader[i].onerror = null;
    }
  }
}

})(jQuery);

(function($){

//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:'ul.slideset >li',
      nextBtn:'div.nav a.next',
      prevBtn:'div.nav a.prev',
      pagingHolder:'div.thumbs',
      pagingTag:'li',
      createPaging:false,
      autoPlay:false,
      dynamicLoad:'img',
      imgAttr:'alt',
      effect:'fade',//fade, slideX, slideY,
      startSlide:0,
      title:'div.nav p',
      onChange:null,
      afterRefreshStatus:null,
      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.onChange = this.options.onChange;
    this.afterRefreshStatus = this.options.afterRefreshStatus;
    this.title = $(this.options.title);
    this.previous = -1;
    this.current = this.options.startSlide;
    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();
    this.initPaging();
    this.setStyles();
    this.bindEvents();
    this.showSlide();
  },

  initPaging:function(){
    this.pagingHolder = $(this.options.pagingHolder,this.mainHolder);

    if (this.options.createPaging) {
      this.pagingHolder.each(function(i,obj){
        var _this = $(obj);
        _this.empty();
        var list = $('<ul>');
        for (var i = 0; i < this.slides.length; i++) $('<li><a href="#">' + (i + 1) + '</a></li>').appendTo(list);
        _this.append(list);
      }.bind(this));
    }

    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.mainHolder);
    }

    //slides
    if (this.effect == 'fade') {
      this.slides.css({display:'none',opacity:0});
      this.slides.eq(this.current).css({display:'block',opacity:1});
    } 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});
    }

    this.title.empty();
  },

  bindEvents:function(){
    this.nextBtn.bind('click',function(){
      if (!this.busy) this.nextSlide();
      return false;
    }.bind(this));

    this.prevBtn.bind('click',function(){
      if (!this.busy) this.prevSlide();
      return false;
    }.bind(this));

    for (var i = 0; i < this.pagingArray.length; i++) {
      this.pagingArray[i].each(function(i,obj){
        $(obj).bind('click',function(){
          if (i != this.current && !this.busy) {
            this.busy = true;
            this.previous = this.current;
            this.current = i;

            if (this.current > this.previous) this.direction = 1
            else this.direction = -1

            this.showSlide();
          }
          return false;
        }.bind(this));
      }.bind(this))
    }

    if (this.dynamicLoad) this.loader.bind('click',this.abortLoading.bind(this));
  },

  nextSlide:function(){
    this.busy = true;
    this.previous = this.current;
    if (this.current < this.slides.length-1) this.current++
    else this.current = 0;
    this.direction = 1;
    this.showSlide(true);
  },

  prevSlide:function(){
    this.busy = true;
    this.previous = this.current;
    if (this.current > 0) this.current--
    else this.current = this.slides.length-1;
    this.direction = -1;

    this.showSlide(true);
  },

  goToSlide:function(index){
    if (this.current != index) {
      this.busy = true;
      this.previous = this.current;
      this.current = index;
      this.showSlide();
    }
  },

  showSlide:function(btn){
    var obj = this;
    var _current = this.current;
    clearTimeout(this.timer);
    if (typeof this.loadArray[_current] != 'undefined' || !this.dynamicLoad) {
      //slide already loaded
      if (this.previous != -1) this.switchSlide(btn)
      else {
        obj.refreshStatus();
        if (obj.autoPlay) obj.startAutoPlay();
      }
    } else {
      //slide not loaded
      this.showLoading();

      var slide = this.slides.eq(this.current);
      var images = $(this.dynamicLoad,slide);
      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));
          });
          obj.loadArray[_current] = 1;
          obj.hideLoading();
          if (obj.previous != -1) obj.switchSlide(btn)
          else {
            obj.refreshStatus();
            if (obj.autoPlay) obj.startAutoPlay();
          }
        }
      }
    }
  },

  switchSlide:function(btn){
    var obj = this;

    if (this.effect == 'fade') {
      this.slides.eq(this.previous).stop().animate({opacity:0},this.animSpeed,callback);
      this.slides.eq(this.current).stop().css({display:'block'}).animate({opacity:1},this.animSpeed);
    } else if (this.effect == 'slideX'){
      this.slides.eq(this.current).css({display:'block',left:this.slideW*this.direction}).animate({left:0},this.animSpeed);
      this.slides.eq(this.previous).animate({left:-this.slideW*this.direction},this.animSpeed+5,callback);
    } else if (this.effect == 'slideY'){
      this.slides.eq(this.current).css({display:'block',top:this.slideH*this.direction}).animate({top:0},this.animSpeed);
      this.slides.eq(this.previous).animate({top:-this.slideH*this.direction},this.animSpeed,callback);
    }

    if (typeof this.onChange === 'function' && btn) {
      if (this.direction == 1) {
        this.onChange(this.current,1);
      } else {
        this.onChange(this.current,0);
      }
    }

    function callback(){
      $(this).css({display:'none'});
      if (obj.autoPlay) obj.startAutoPlay();
      obj.busy = false;
    }

    this.refreshStatus();
  },

  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');
    }
    if (this.title.length) this.title.empty().text(this.slides.eq(this.current).find('img').attr('title'));
    if (typeof this.afterRefreshStatus === 'function') this.afterRefreshStatus();
  },

  showLoading:function(){
    var obj = this;
    this.loader.show();
    clearInterval(this.loadingTimer);
    obj.loadingTimer = setInterval(animateLoading, 66);

    function animateLoading(){
      if (!obj.loader.is(':visible')){
        clearInterval(obj.loadingTimer);
        return;
      }
      obj.loaderDiv.css('top', obj.loadingFrame * -40);
      obj.loadingFrame = (obj.loadingFrame + 1) % 12;
    }
  },

  hideLoading:function(){
    this.loader.hide();
  },

  abortLoading:function(){
    this.busy = false;
    this.loader.hide();
    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);
  }
}

})(jQuery);

//gallery circle switcher module
;(function($){

//create jQuery plugin
$.fn.carousel = function(options){return new carousel(this, options);}

//constructor
function carousel(obj, options){this.init(obj,options)}

//prototype
carousel.prototype = {
  init:function(obj, options) {
    this.options = $.extend({
      holder:'>div',
      slider:'div.mask > ul',
      slides:'>li',
      nextBtn:'a.next',
      prevBtn:'a.prev',
      slideSpeed:700,
      step:false
    },options);
    //get elements
    this.mainHolder = $(obj);
    this.holder = $(this.options.holder, this.mainHolder);
    this.slider = $(this.options.slider, this.holder);
    this.slides = $(this.options.slides, this.slider);
    this.prevBtn = $(this.options.prevBtn, this.mainHolder);
    this.nextBtn = $(this.options.nextBtn, this.mainHolder);
    this.paging = $(this.options.paging,this.mainHolder);
    this.slideSpeed = this.options.slideSpeed;
    this.enable = true;

    //valiables
    this.slideW = this.slides.eq(0).outerWidth(true);
    this.slidesW = this.slideW*this.slides.length;
    this.offset = this.prevOffset = this.slidesW;
    if (this.slidesW < this.holder.width()) this.enable = false;

    this.visibleStep = Math.round(this.holder.width()/this.slideW);
    this.options.step ? this.step = this.options.step : this.step = this.visibleStep;
    this.stepW = this.step * this.slideW;

    //set styles & clone slides
    if (this.enable) {
      this.slider.append(this.slides.clone()).prepend(this.slides.clone());
      this.slider.css({marginLeft:-this.offset});
    }

    this.bindEvents();

    //create margin Array
    var createMarginArray = function(){
      var marginSum = 0;
      this.marginArray = new Array;
      for (var i = 0; i < 3; i++) {
        this.marginArray[i] = new Array;
        for (var j = 0; j < this.slides.length; j++) {
          this.marginArray[i][j] = marginSum;
          marginSum += this.slideW
        }
      }
    }.bind(this);
    createMarginArray();
  },

  bindEvents:function(){
    this.nextBtn.bind('click',function(){
      if (!this.slider.is(':animated') && this.enable) this.nextSlide();
      return false;
    }.bind(this));
    this.prevBtn.bind('click',function(){
      if (!this.slider.is(':animated') && this.enable) this.prevSlide();
      return false;
    }.bind(this));
  },

  nextSlide:function(){
    this.prevOffset = this.offset;
    this.offset += this.stepW;
    this.switchSlide();
  },

  prevSlide:function(){
    this.prevOffset = this.offset;
    this.offset -= this.stepW;
    this.switchSlide();
  },

  switchSlide:function(){
    //check offset range
    if (this.offset >= this.slidesW*2) {
      this.prevOffset -= this.slidesW;
      this.offset -= this.slidesW;
      this.slider.css({marginLeft:-(this.prevOffset)});
    } else if (this.offset < this.slidesW/2) {
      this.prevOffset += this.slidesW;
      this.offset += this.slidesW;
      this.slider.css({marginLeft:-(this.prevOffset)});
    }
    this.slider.animate({marginLeft:-this.offset},this.options.slideSpeed);
  },

  move:function(nextInd,direction){
    if (this.enable) {
      var min,toPos;
      if (direction) {
        for (var i = 0; i < 3; i++) {
          if (this.marginArray[i][nextInd] >= this.offset) {
            var tmp = Math.abs(this.marginArray[i][nextInd] - this.offset);
            if (tmp <= min || typeof min == 'undefined') {
              min = tmp;
              toPos = i;
            }
          }
        }
        if (min < this.stepW || min == 0) return;
        this.prevOffset = this.offset;
        this.offset = this.marginArray[toPos][nextInd];
      } else {
        var next = nextInd - this.visibleStep+1;
        if (next < 0) next += this.slides.length;
        for (var i = 0; i < 3; i++) {
          if (this.marginArray[i][next] <= this.offset) {
            var tmp = Math.abs(this.marginArray[i][next] - this.offset);
            if (tmp <= min || typeof min == 'undefined') {
              min = tmp;
              toPos = i;
            }
          }
        }
        if (min < this.stepW || min == 0) return;

        if (typeof toPos == 'undefined') {
          this.offset += this.slidesW;
          this.slider.css({marginLeft:-this.offset});
          this.prevOffset = this.offset;
          this.offset = this.marginArray[0][next];
        } else {
          this.prevOffset = this.offset;
          this.offset = this.marginArray[toPos][next];
        }
      }
      this.switchSlide();
    }
  }
}

// bind scope function
Function.prototype.bind = function(scope) {
  var _function = this;
  return function() {
    return _function.apply(scope, arguments);
  }
}

})(jQuery);

function initOverlays(){
  $('ul.events-list > li').each(function(){
    var _this = $(this);
    var duration = 350;
    var overlay = $('span',_this);
    var overlayH = overlay.outerHeight();
    overlay.css({bottom:-overlayH});

    _this.mouseenter(function(){
      overlay.stop().animate({bottom:0},duration)
    }).mouseleave(function(){
      overlay.stop().animate({bottom:-overlayH},duration)
    });
  })
}

//lightbox plugin
$.fn.modalPopup = function(options){return new modalPopup($(this).eq(0),options)}
function modalPopup(link, options) {this.init(link,options)}
modalPopup.prototype = {
  init:function(link,options){
    var el = this;
    //options
    el.options = $.extend({
      fadeSpeed:400,
      closer:'a.close',
      scroll:false,
      wrapper:'#wrapper',
      IE:true,
      zIndex:false
    },options);
    //popup & default css styles
    if ($.browser.msie && el.options.IE) el.popup = $(link.attr('href')).css({visibility:'hidden'})
    else el.popup = $(link.attr('href')).css({opacity:0,visibility:'hidden'});
    if (el.options.zIndex) el.popup.css({zIndex : el.options.zIndex});
    el.closer = $(el.popup.find(el.options.closer));
    el.popup.visible = false;
    modalPopup.prototype.activePopup = false;
    if (!modalPopup.prototype.firstRun) {
      modalPopup.prototype.firstRun = 'done';
      if ($.browser.msie && $.browser.version < 7) modalPopup.prototype.selects = $('select');
      //create fader
      if (!$('#fader').length) $('body').append('<div id="fader"></div>');
      modalPopup.prototype.fader = $('#fader');
      modalPopup.prototype.fader.css({position:'absolute',top:0,left:0,background:'#000',opacity:0,display:'none'});
      if (el.options.zIndex) modalPopup.prototype.fader.css({zIndex : el.options.zIndex-1});
      modalPopup.prototype.wrapper = $(el.options.wrapper);
      //fader click event
      modalPopup.prototype.fader.click(function(){
        if (modalPopup.prototype.activePopup == false) el.hideFader()
        else modalPopup.prototype.activePopup.hidePopup(function(){el.hideFader()});
        return false;
      });
      //esc event
      $(document).keydown(function (e) {
        if (e.keyCode == 27) {
          if (modalPopup.prototype.activePopup == false) el.hideFader()
          else modalPopup.prototype.activePopup.hidePopup(function(){el.hideFader()});
          return false;
        }
      });
    }

    el.wrapper = modalPopup.prototype.wrapper;

    if ($.browser.msie && $.browser.version < 7) {
      el.popupSelects = $('select',el.popup);
      modalPopup.prototype.selects = modalPopup.prototype.selects.not(el.popupSelects);
    }

    //open event
    link.click(function(){
      el.show();
      return false;
    });
    //close event
    el.closer.click(function(){
      el.close();
      return false;
    });
    //resize event
    $(window).resize(function(){
      if (el.popup.visible) el.positioning(false);
    });
    if (el.options.scroll) {
      $(window).scroll(function(){
        el.positioning(true);
      });
    }
  },

  close:function(){
    var el = this;
    el.hidePopup(function(){el.hideFader()});
  },

  show:function(){
    var el = this;
    if (modalPopup.prototype.activePopup == el) {return false;}
    if (modalPopup.prototype.activePopup) {
      modalPopup.prototype.activePopup.hidePopup(function(){
        el.showPopup()
        el.positioning(true);
      });
    } else {
      el.showFader(function(){el.showPopup()});
      el.positioning(true);
    }
  },

  showPopup:function(){
    var el = this;
    el.popup.visible = true;
    modalPopup.prototype.activePopup = el;
    if ($.browser.msie && el.options.IE) el.popup.css({visibility:'visible'})
    else el.popup.stop().css({'visibility':'visible'}).animate({opacity:1},el.options.fadeSpeed)
  },
  hidePopup:function(callback){
    var el = this;
    if ($.browser.msie && el.options.IE) {
      el.popup.css({left:'-9999px',top:'-9999px',visibility:'hidden'});
      el.popup.visible = false;
      modalPopup.prototype.activePopup = false;
      if ($.isFunction(callback)) callback();
    } else {
      el.popup.stop().animate({opacity:0},el.options.fadeSpeed,function(){
        el.popup.css({left:'-9999px',top:'-9999px',visibility:'hidden'});
        el.popup.visible = false;
        modalPopup.prototype.activePopup = false;
        if ($.isFunction(callback)) callback();
      });
    }
  },
  showFader:function(callback){
    var el = this;
    el.fader.stop().css({display:'block'}).animate({opacity:0.5},el.options.fadeSpeed,function(){
      if ($.isFunction(callback)) callback();
    });
    if ($.browser.msie && $.browser.version < 7) modalPopup.prototype.selects.css({'visibility': 'hidden'});
  },
  hideFader:function(){
    var el = this;
    el.fader.stop().animate({opacity:0},el.options.fadeSpeed,function(){
      el.fader.css({display:'none'});
      if ($.browser.msie && $.browser.version < 7) modalPopup.prototype.selects.css({'visibility': 'visible'});
    });
  },
  positioning:function(openFlag){
    var el = this;
    //x offset
    var windowW = $(window).width();
    var popupW = el.popup.outerWidth();
    var wrapperW = el.wrapper.outerWidth();

    if (windowW < wrapperW) {
      el.popup.css({left:wrapperW/2-popupW/2})
      el.fader.css({width:wrapperW});
    } else {
       el.popup.css({left:windowW/2-popupW/2});
       el.fader.css({width:windowW})
    }
    //y offset
    var docH;
    var windowH = $(window).height();
    var wrapperH = el.wrapper.outerHeight();
    if (windowH < wrapperH) docH = wrapperH
    else docH = windowH;

    var popupH = el.popup.outerHeight();
    if (openFlag) {
      var popupH = el.popup.outerHeight();
      if (popupH < windowH) el.popup.css({top:windowH/2-popupH/2+$(window).scrollTop()});
      else if ($(window).scrollTop()+popupH > docH){
        el.popup.css({top:docH-popupH});
      } else {
        el.popup.css({top:$(window).scrollTop()});
      }
    }
    el.fader.css({height:docH});
  }
}

// custom forms init
function initCustomForms() {
  $('select').customSelect();
  //$('input:radio').customRadio();
  //$('input:checkbox').customCheckbox();
}

// custom forms plugin
;(function(jQuery){
  // custom checkboxes module
  jQuery.fn.customCheckbox = function(_options){
    var _options = jQuery.extend({
      checkboxStructure: '<div></div>',
      checkboxDisabled: 'disabled',
      checkboxDefault: 'checkboxArea',
      checkboxChecked: 'checkboxAreaChecked',
      filterClass:'default'
    }, _options);
    return this.each(function(){
      var checkbox = jQuery(this);
      if(!checkbox.hasClass('outtaHere') && checkbox.is(':checkbox') && !checkbox.hasClass(_options.filterClass)){
        var replaced = jQuery(_options.checkboxStructure);
        this._replaced = replaced;
        if(checkbox.is(':disabled')) replaced.addClass(_options.checkboxDisabled);
        else if(checkbox.is(':checked')) replaced.addClass(_options.checkboxChecked);
        else replaced.addClass(_options.checkboxDefault);

        replaced.click(function(){
          if(checkbox.is(':checked')) checkbox.removeAttr('checked');
          else checkbox.attr('checked', 'checked');
          changeCheckbox(checkbox);
        });
        checkbox.click(function(){
          changeCheckbox(checkbox);
        });
        replaced.insertBefore(checkbox);
        checkbox.addClass('outtaHere');
      }
    });
    function changeCheckbox(_this){
      _this.change();
      if(_this.is(':checked')) _this.get(0)._replaced.removeClass().addClass(_options.checkboxChecked);
      else _this.get(0)._replaced.removeClass().addClass(_options.checkboxDefault);
    }
  }

  // custom radios module
  jQuery.fn.customRadio = function(_options){
    var _options = jQuery.extend({
      radioStructure: '<div></div>',
      radioDisabled: 'disabled',
      radioDefault: 'radioArea',
      radioChecked: 'radioAreaChecked',
      filterClass:'default'
    }, _options);
    return this.each(function(){
      var radio = jQuery(this);
      if(!radio.hasClass('outtaHere') && radio.is(':radio') && !radio.hasClass(_options.filterClass)){
        var replaced = jQuery(_options.radioStructure);
        this._replaced = replaced;
        if(radio.is(':disabled')) replaced.addClass(_options.radioDisabled);
        else if(radio.is(':checked')) replaced.addClass(_options.radioChecked);
        else replaced.addClass(_options.radioDefault);
        replaced.click(function(){
          if($(this).hasClass(_options.radioDefault)){
            radio.attr('checked', 'checked');
            changeRadio(radio.get(0));
          }
        });
        radio.click(function(){
          changeRadio(this);
        });
        replaced.insertBefore(radio);
        radio.addClass('outtaHere');
      }
    });
    function changeRadio(_this){
      $(_this).change();
      $('input:radio[name='+$(_this).attr("name")+']').not(_this).each(function(){
        if(this._replaced && !$(this).is(':disabled')) this._replaced.removeClass().addClass(_options.radioDefault);
      });
      _this._replaced.removeClass().addClass(_options.radioChecked);
    }
  }

  // custom selects module
  jQuery.fn.customSelect = function(_options) {
    var _options = jQuery.extend({
      selectStructure: '<div class="selectArea"><span class="left"></span><span class="center"></span><a href="#" class="selectButton"></a><div class="disabled"></div></div>',
      hideOnMouseOut: false,
      copyClass: true,
      selectText: '.center',
      selectBtn: '.selectButton',
      selectDisabled: '.disabled',
      optStructure: '<div class="optionsDivVisible"><div class="select-top"></div><div class="select-center"><ul></ul><div class="select-bottom"></div></div>',
      optList: 'ul',
      filterClass:'default'
    }, _options);
    return this.each(function() {
      var select = jQuery(this);
      if(!select.hasClass('outtaHere') && !select.hasClass(_options.filterClass)) {
        if(select.is(':visible')) {
          var hideOnMouseOut = _options.hideOnMouseOut;
          var copyClass = _options.copyClass;
          var replaced = jQuery(_options.selectStructure);
          var selectText = replaced.find(_options.selectText);
          var selectBtn = replaced.find(_options.selectBtn);
          var selectDisabled = replaced.find(_options.selectDisabled).hide();
          var optHolder = jQuery(_options.optStructure);
          var optList = optHolder.find(_options.optList);
          if(copyClass) optHolder.addClass('drop-'+select.attr('class'));

          if(select.attr('disabled')) selectDisabled.show();
          select.find('option').each(function(){
            var selOpt = $(this);
            var _opt = jQuery('<li><a href="#">' + selOpt.html() + '</a></li>');
            if(selOpt.attr('selected')) {
              selectText.html(selOpt.html());
              _opt.addClass('selected');
            }
            _opt.children('a').click(function() {
              optList.find('li').removeClass('selected');
              select.find('option').removeAttr('selected');
              $(this).parent().addClass('selected');
              selOpt.attr('selected', 'selected');
              selectText.html(selOpt.html());
              select.change();
              optHolder.hide();
              return false;
            });
            optList.append(_opt);
          });
          replaced.width(select.outerWidth());
          replaced.insertBefore(select);
          optHolder.css({
            width: select.outerWidth(),
            display: 'none',
            position: 'absolute'
          });
          jQuery(document.body).append(optHolder);

          var optTimer;
          replaced.hover(function() {
            if(optTimer) clearTimeout(optTimer);
          }, function() {
            if(hideOnMouseOut) {
              optTimer = setTimeout(function() {
                optHolder.hide();
              }, 200);
            }
          });
          optHolder.hover(function(){
            if(optTimer) clearTimeout(optTimer);
          }, function() {
            if(hideOnMouseOut) {
              optTimer = setTimeout(function() {
                optHolder.hide();
              }, 200);
            }
          });
          selectBtn.click(function() {
            if(optHolder.is(':visible')) {
              optHolder.hide();
            }
            else{
              if(_activeDrop) _activeDrop.hide();
              optHolder.children('ul').css({height:'auto', overflow:'hidden'});
              optHolder.css({
                top: replaced.offset().top + replaced.outerHeight(),
                left: replaced.offset().left,
                display: 'block'
              });
              if(optHolder.children('ul').height() > 200) optHolder.children('ul').css({height:200, overflow:'auto'});
              _activeDrop = optHolder;
            }
            return false;
          });
          replaced.addClass(select.attr('class'));
          select.addClass('outtaHere');
        }
      }
    });
  }

  // event handler on DOM ready
  var _activeDrop;
  jQuery(function(){
    jQuery('body').click(hideOptionsClick)
    jQuery(window).resize(hideOptions)
  });
  function hideOptions() {
    if(_activeDrop && _activeDrop.length) {
      _activeDrop.hide();
      _activeDrop = null;
    }
  }
  function hideOptionsClick(e) {
    if(_activeDrop && _activeDrop.length) {
      var f = false;
      $(e.target).parents().each(function(){
        if(this == _activeDrop) f=true;
      });
      if(!f) {
        _activeDrop.hide();
        _activeDrop = null;
      }
    }
  }
})(jQuery);

//clear inputs
function clearInputs(){
  $('input:text, input:password, textarea').each(function(){
    var _el = $(this);
    var _val = _el.val();
    _el.bind('focus', function(){
      if(this.value == _val) this.value = '';
    }).bind('blur', function(){
      if(this.value == '') this.value = _val;
    });
  });
}

//cufon settings
function initCufon() {
  Cufon.replace('#nav li a', {fontFamily: 'Trade Gothic LT Std Extended', hover: true});
  Cufon.replace('#main h2', {fontFamily: 'Trade Gothic LT Std Extended', hover:true});
  Cufon.replace('#footer li a', {fontFamily: 'Trade Gothic LT Std Extended', hover: true});
  Cufon.replace('#footer p', {fontFamily: 'Trade Gothic LT Std Extended'});
  Cufon.replace('#sidebar h3', {fontFamily: 'Trade Gothic LT Std Extended'});
  Cufon.replace('.menu a', {fontFamily: 'Trade Gothic LT Std Extended', hover: true});
  Cufon.replace('a.back, .back-to-category a', {fontFamily: 'Trade Gothic LT Std Extended', hover: true});
  Cufon.replace('.cols .person p', {fontFamily: 'Trade Gothic LT Std Extended'});
  Cufon.replace('#sidebar .menu .box strong', {fontFamily: 'Trade Gothic LT Std Extended'});
  Cufon.replace('.address h4', {fontFamily: 'Trade Gothic LT Std Extended'});
  Cufon.replace('.color-popup .close', {fontFamily: 'Trade Gothic LT Std Extended'});
  
}


})(jQuery);
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
