// page init
jQuery(function(){
	initSlideshow();
	initMainNav();
	initTabs();

  // search fields
  $('.search-field').click(
    function() {
      if (this.value == this.defaultValue) {
        this.value = '';
        this.style.color = '#000000';
      }
    }
  );
  
  $('.search-field').blur(
    function() {
      if (this.value == '') {
        this.value = this.defaultValue;
        this.style.color = '#000000';
      }
    }
  );

  // ticker
  $("#ticker li").hide();

  var headlineFadeSpeed = 10000;
  function showNextItem(){
      var index      = arguments[0] || 1;
      var $curLi     = $("#ticker li:nth-child("+index+")");
      var totalItems = $("#ticker li").length;

      $curLi.fadeIn("fast", function(){
          setTimeout(function(){
              $curLi.fadeOut("slow", function(){
                  index = (index < totalItems) ? index+1 : 1;
                  showNextItem(index);
              });
          }, headlineFadeSpeed);
      });
  }

  showNextItem();
});

// main navigation init
function initMainNav(){
	initNav({
		menuId: "nav",
		hoverClass: "hover",
		dropExistenceClass: "has-drop-down",
		sideClasses: false,
		cleverMode: true,
		flexibility: true,
		menuPaddings: 20,
		minWidth: 70
	});
};

// slideshow init
function initSlideshow(){
	jQuery('div.gallery').fadeGallery({
		pauseOnHover:true,
		autoRotation:true,
		switchTime:7000, // [1000 - 1sec]
		duration:700, // [1000 - 1sec]
		event:'mouseenter'
	});
	jQuery('div.carousel').NVcirclegallery({
		step:1, // slide items
		speed:700 //ms
	});
};

// circle gallery plugin
jQuery.fn.NVcirclegallery = function($options){
	var $options = jQuery.extend({
		//Options plugin
		sliderHolder: '>div',
		slider: '>ul',
		slides: '>li',
		btnPrev: '.prev',
		btnNext: '.next',
		paging: '.swicher',
		vertical: false,
		autorotate: false,
		hoverPause: true,
		speed: 650,
		easingEffect: 'swing',
		swichTime: 5000,
		startPosition: 8,
		step:false
	},$options);

	return this.each(function(){
		var $this = jQuery(this);
		//Set options for plugins
		var sliderHolder = jQuery($options.sliderHolder, $this);
		if(!sliderHolder.length){
			sliderHolder = $this;
		};
		var slider = jQuery($options.slider, sliderHolder),
			slides = jQuery($options.slides, slider),
			btnPrev = jQuery($options.btnPrev, $this),
			btnNext = jQuery($options.btnNext, $this),
			paging = jQuery($options.paging, $this),
			vertical = $options.vertical,
			startPosition = $options.startPosition,
			step = $options.step,
			autorotate = $options.autorotate,
			hoverPause = $options.hoverPause,
			speed = $options.speed,
			swichTime = $options.swichTime,
			easingEffect = $options.easingEffect,
			waitAnimation = false;
		if(!slider.length) return;
		var summHeight = 0,
			summWidth = 0,
			currentStep = 0,
			currentIndex,
			prevIndex,
			direction,
			timer,
			pagerLink,
			slidesCount = slides.length,
			visibleCount = vertical ? Math.ceil(sliderHolder.height()/slides.outerHeight(true)) : Math.ceil(sliderHolder.width()/slides.outerWidth(true)),
			holdW = sliderHolder.width();
		
		if(slidesCount <= visibleCount ) return;
		if(slides.hasClass('active')) currentIndex = slides.filter('.active:eq(0)').index();
		else currentIndex = 0;
		prevIndex = currentIndex;
		paging.empty();
		slides.each(function(){
			summWidth += jQuery(this).outerWidth(true);
			summHeight += jQuery(this).outerHeight(true);
		});
		var stepCount = Math.ceil(summWidth/sliderHolder.width());
		for(var i =0; i < stepCount+1; i++){
			paging.append('<li><a href="#">' + (i+1) + '</a></li>');
		}
		pagerLink = paging.children();
		if(vertical) slider.css({ height: summHeight });
		else slider.css({ width: summWidth });

		if(startPosition || startPosition > 1){
			for(var i = 0; i < startPosition-1; i++ ){
				slider.append(slides.eq(i).clone(true));
				slides.eq(i).remove();
			}
			slides = slider.children();
			slides.removeClass('last').eq(visibleCount-1).addClass('last');
		}
		function initRecalc(){
			if(!$options.step){
				var _w = 0;
				var num = 0;
				slides.each(function(i){
					if(vertical){
						if(_w <= holdW && vertical){
							_w += slides.eq(i).outerHeight(true);
						}
					}
					else {
						if(_w <= holdW){
							num++;
							_w += slides.eq(i).outerWidth(true);
						}
					}
				});
				step = num-1;
			}
			waitAnimation = true;
			
			
			if(direction == 1){
				for(var i = 0; i < slidesCount-1; i++ ){
					if(i < step ){
						slider.append(slides.eq(i).clone(true));
						if(vertical) { currentStep += slides.eq(i).outerHeight(true) }
						else { currentStep += slides.eq(i).outerWidth(true) }
					}
				}
				if(vertical){ slider.css({ height: summHeight + currentStep }); }
				else { slider.css({ width: summWidth + currentStep }); }
			}
			else if(direction == -1){
				for( var i = slidesCount-1; i > 0; i-- ){
					if(i > slidesCount - 1 - step ){
						slider.prepend(slides.eq(i).clone(true));
						if(vertical) { currentStep += slides.eq(i).outerHeight(true); }
						else { currentStep += slides.eq(i).outerWidth(true); }
					}
				}
				if(vertical) {
					slider.css({ marginTop: -currentStep, height: summHeight + currentStep });
					currentStep = 0;
				}
				else {
					slider.css({ marginLeft: -currentStep, width: summWidth + currentStep });
					currentStep = 0;
				}
			}
			
		}
		function prevSlide(){
			if(waitAnimation) return false;
			direction = -1;
			initRecalc();
			animateSlider();
		}
		function nextSlide(){
			if(waitAnimation) return false;
			direction = 1;
			initRecalc();
			animateSlider();
		}
		btnPrev.bind('click', function(){
			if(!waitAnimation){
				if(timer) clearTimeout(timer)
				prevSlide();
			}
			return false;
		});
		btnNext.bind('click', function(){
			if(!waitAnimation){
				if(timer) clearTimeout(timer)
				nextSlide();
			}
			return false;
		});
		if(pagerLink.length){
			pagerLink.each(function(i, item){
				jQuery(item).bind('click', function(){
					prevIndex = currentIndex;
					currentIndex = i;
					if(currentIndex != prevIndex && !waitAnimation){
						if(currentIndex > prevIndex){
							direction = 1;
						}
						else direction = -1;
						initRecalc();
						animateSlider();
					}
					return false;
				})
			})
		}
		function animateSlider(){
			var marginType = {};
			marginType[vertical ? 'marginTop' : 'marginLeft'] = -currentStep*direction;
			slider.animate(marginType, { queue: false, duration: speed, easing: easingEffect, complete: function(){
				if(direction == 1){
					slides.each(function(i, el){
						if(i < step ){
							slides.eq(i).remove();
						}
					})
				}
				else if(direction == -1){
					slides.each(function(i, el){
						if(i > slidesCount - step - 1 ){
							slides.eq(i).remove();
						}
					})
				}
				slides = slider.children();
				if(vertical){ slider.css({ marginTop: 0, height: summHeight }); }
				else { slider.css({ marginLeft: 0, width: summWidth }); }
				waitAnimation = false;
			}});
			currentStep = 0;
			if($options.autorotate) autorotate = true;
			autoSlide();
		};
		function autoSlide(){
			if(autorotate){
				if(timer) clearTimeout(timer);
				timer = setTimeout(nextSlide, swichTime)
			}
		};
		autoSlide();
		if(hoverPause){
			$this.hover(
				function(){ if(timer) clearTimeout(timer) },
				function(){ if($options.autorotate) autorotate = true; autoSlide(); }
			)
		}
	});
};

// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
	var _options = jQuery.extend({
		slideElements:'ul.slideshow > li',
		pagerGener: false,
		pagerHold: false,
		pagerLinks:'ul.switchers li',
		btnNext:'a.btn-next',
		btnPrev:'a.btn-prev',
		btnPlayPause:'a.play-pause',
		btnPlay:'a.play',
		btnPause:'a.pause',
		pausedClass:'paused',
		disabledClass: 'disabled',
		playClass:'playing',
		activeClass:'active',
		currentNum:false,
		allNum:false,
		startSlide:null,
		noCircle:false,
		caption:'ul.caption > li',
		pauseOnHover:false,
		autoRotation:false,
		autoHeight:false,
		onChange:false,
		switchTime:3000,
		duration:650,
		event:'click'
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _slides = jQuery(_options.slideElements, _this);
		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 _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		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 _pagerGener = _options.pagerGener;
		var _pagerHold = jQuery(_options.pagerHold,_this);
		var _caption = jQuery(_options.caption,_this);
		var _paging = '';
		if(_pagerGener){
			for(var i=0; i< _slides.length; i++){
				_paging += '<li><a href="#">'+(i+1)+'</a></li>';
			}
			_pagerHold.html('<ul>'+_paging+'</ul>');
		}
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		// gallery init
		var _hover = false;
		var _prevIndex = 0;
		var _currentIndex = 0;
		var _slideCount = _slides.length;
		var _timer;
		if(_slideCount < 2) return;

		_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();
		_caption.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) {
						_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;
			});
		}
		// gallery animation
		function prevSlide() {
			_prevIndex = _currentIndex;
			if(_currentIndex > 0) _currentIndex--;
			else {
				if(_noCycle) return;
				else _currentIndex = _slideCount-1;
			}
			switchSlide();
		}
		function nextSlide() {
			_prevIndex = _currentIndex;
			if(_currentIndex < _slideCount-1) _currentIndex++;
			else {
				if(_noCycle) return;
				else _currentIndex = 0;
			}
			switchSlide();
		}
		function refreshStatus() {
			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, _currentIndex);
			}
		}
		function switchSlide() {
			_slides.eq(_prevIndex).stop().animate({opacity:0},{duration: _duration, queue: false,complete:function(){
				jQuery(this).css({display:'none'});
			}})
			_slides.eq(_currentIndex).stop().css({display:'block',opacity:0}).animate({opacity:1},{duration: _duration, queue: false,complete:function(){
				jQuery(this).css({opacity:''});
			}})
			_caption.eq(_prevIndex).fadeOut();
			_caption.eq(_currentIndex).fadeIn();
			if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
			refreshStatus();
			autoSlide();
		}

		// 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();
	});
};

// tabs init
function initTabs(){
	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{
		if (sets[i].className.indexOf("tabset") != -1)
		{
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");
			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					tabs.push(links[j]);
					links[j].tabs = tabs;
					var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

					if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
					else c.style.display = "none";

					links[j].onclick = function ()
					{
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							for (var i = 0; i < this.tabs.length; i++)
							{
								var tab = document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1));
								if (tab)
								{
									tab.style.display = "none";
								}
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							return false;
						}
					}
				}
			}
		}
	}
};

// navigation plugin
function initNav(o){
	if (!o.menuId) o.menuId = "nav";
	if (!o.cleverMode) o.cleverMode = false;
	if (!o.flexibility) o.flexibility = false;
	if (!o.dropExistenceClass) o.dropExistenceClass = false;
	if (!o.hoverClass) o.hoverClass = "hover";
	if (!o.menuHardCodeClass) o.menuHardCodeClass = "menu-hard-code";
	if (!o.sideClasses) o.sideClasses = false;
	if (!o.center) o.center = false;
	if (!o.menuPaddings) o.menuPaddings = 0;
	if (!o.minWidth) o.minWidth = 0;
	if (!o.coeff) o.coeff = 1.7;
	var n = document.getElementById(o.menuId);
	if(n)
	{
		n.className = n.className.replace(o.menuHardCodeClass, "");
		var lfl = [];
		var li = n.getElementsByTagName("li");
		for (var i=0; i<li.length; i++)
		{
			li[i].className += (" " + o.hoverClass);
			var d = li[i].getElementsByTagName("div").item(0);
			if(d)
			{
				if(o.flexibility)
				{
					var a = d.getElementsByTagName("a");
					for (var j=0; j<a.length; j++)
					{
						var w = a[j].parentNode.parentNode.offsetWidth;
						if(w > 0)
						{
							if(typeof(o.minWidth) == "number" && w < o.minWidth)
								w = o.minWidth;
							else if(typeof(o.minWidth) == "string" && li[i].parentNode == n && w < li[i].offsetWidth)
								w = li[i].offsetWidth - 5;
							a[j].style.width = w - o.menuPaddings + "px";
						}
					}
					d.style.width = li[i].getElementsByTagName("div").item(1).clientWidth + "px";
				}
				var t = document.documentElement.clientWidth/o.coeff;
				if(li[i].parentNode != n && (!o.cleverMode || fPX(li[i]) < t))
				{
					d.style.right = "auto";
					d.style.left = li[i].parentNode.offsetWidth + "px";
					d.parentNode.className += " left-side";
				}	
				else if(li[i].parentNode != n && (o.cleverMode || fPX(li[i]) >= t))
				{
					d.style.left = "auto";
					d.style.right = li[i].parentNode.offsetWidth + "px";
					d.parentNode.className += " right-side";
				}
				else if(li[i].parentNode == n && o.cleverMode && fPX(li[i]) >= t)
				{
					li[i].className += " right-side";
				}
				if(li[i].parentNode == n && o.center)
					d.style.left = -li[i].getElementsByTagName("div").item(1).clientWidth/2 + li[i].clientWidth/2 + "px";
			}
			if(o.dropExistenceClass && li[i].getElementsByTagName("ul").length > 0)
			{
				li[i].className += (" " + o.dropExistenceClass);
				li[i].getElementsByTagName("a").item(0).className += (" " + o.dropExistenceClass + "-link");
				li[i].innerHTML += "<em class='pointer'></em>";
			}
			if(li[i].parentNode == n) lfl.push(li[i]);
		}
		if(o.sideClasses)
		{
			lfl[0].className += " first-child";
			lfl[0].getElementsByTagName("a").item(0).className += " first-child-link";
			lfl[lfl.length-1].className += " last-child";
			lfl[lfl.length-1].getElementsByTagName("a").item(0).className += " last-child-link";
		}
		for (var i=0; i<li.length; i++)
		{
			li[i].className = li[i].className.replace(o.hoverClass, "");
			li[i].onmouseover = function()
			{
				this.className += (" " + o.hoverClass);
			}
			li[i].onmouseout = function()
			{
				this.className = this.className.replace(o.hoverClass, "");
			}
		}
	}
	function fPX(a)
	{
		var b = 0;
		while (a.offsetParent) {b += a.offsetLeft; a = a.offsetParent;}
		return b;
	}
}

