$(document).ready(function() {
	gallery('.gallery li .img a, .img.main a');
	//projectsCarousel('.work-list');
	banners(3); // seconds
	subscribePopup('#head .subscribe a');
	selection('.work-list, .work-list li, .img');
	favorites('#head .favorite');
});

$(window).load(function() {
	headBanner('#head .slideshow', 3000); // delay
	centerImages('.img');
});

function banners(seconds) {
	if ( $('#thumbs li').length > 1 ) {
		// Banner slideshow
		$('#slideshow > span').remove();

		var gallery = $('#thumbs').galleriffic({
			delay:                     (seconds * 1000),
			preloadAhead:              2,
			enableTopPager:            false,
			enableBottomPager:         false,
			imageContainerSel:         '#slideshow', 
			controlsContainerSel:      '#ss-btns', 
			captionContainerSel:       '', 
			loadingContainerSel:       '', 
			renderSSControls:          true, 
			renderNavControls:         false, 
			playLinkText:              'Запустить слайдшоу',
			pauseLinkText:             'Остановить слайдшоу',
			prevLinkText:              'Previous',
			nextLinkText:              'Next',
			nextPageLinkText:          'Next &rsaquo;',
			prevPageLinkText:          '&lsaquo; Prev',
			enableHistory:             false,
			enableKeyboardNavigation:  false, 
			autoStart:                 true
		}).hide();

		$('#btns').show();

		$('#btns .next').click( function(e) {
			gallery.next();
			e.preventDefault;
			return false;
		});

		$('#btns .prev').click( function(e) {
			gallery.previous();
			e.preventDefault;
			return false;
		});

		$('#ss-btns').show();
	}
}

function favorites(s) {
	var $link = $(s);
	
	// add to favourites
	//if ( !$.browser.safari ) {
		$link.show();
		
		$link.attr('rel', 'sidebar').click(function(e) {
			var title = window.document.title;
			var url = window.location.href;
	
			try { 
				// Internet Explorer 
				window.external.AddFavorite(url, title); 
			} 
			catch (e) { 
				try { 
				// Mozilla 
					window.sidebar.addPanel(title, url, ""); 
				} 
				catch (e) { 
					// Opera 
					if (typeof(opera)=="object") { 
						a.rel="sidebar"; 
						a.title=title; 
						a.url=url; 
					}
					else {
					 alert('Нажмите Ctrl-D, чтобы добавить страницу в закладки');
					} 
				} 
			}
				
			e.preventDefault();
		});
	//}
}

function gallery(s) {
	var $items = $(s);
	
	if ( $items.length ) {
		$items.lightBox({
			overlayBgColor:'#3e2923',
			overlayOpacity:0.4,
			txtImage:'Изображение',
			txtOf:'из',
			imageLoading:'/images/lightbox/ico-loading.gif',
			imageBtnPrev:'/images/lightbox/btn-prev.gif',
			imageBtnNext:'/images/lightbox/btn-next.gif',
			imageBtnClose:'/images/lightbox/btn-close.gif',
			imageBlank:'/images/lightbox/blank.gif'
		});
	}
}

function projectsCarousel(s) {
	var $carousel = $(s);
	
	if ( $carousel.length ) {
		$('ul', $carousel).jcarousel({
			buttonNextHTML: '<div class="btn-next"></div>',
	        buttonPrevHTML: '<div class="btn-prev"></div>'
		});
	}
}

function subscribePopup(s) { 
	var $popup = $('#popup');
	var $overlay = $('#overlay');
	var $link = $(s);
	
	if ( $link.length && $popup.length ) {
		$link.click(function(e) { 
			$popup.fadeIn(400);
			if ( $overlay.length ) $overlay.fadeIn(400);
		
			e.preventDefault();
		});
		
		$overlay.click(function(e) {
			$popup.fadeOut(400);
			$(this).fadeOut(400);
		});
	}
}

function headBanner(s, slideshowDelay) {
	var $banner = $(s);
	
	if ($banner.length) {
		$banner.disableSelection();
	
		// elements
		var $thumbs = $('.slides ul li', $banner);
		var $slide = $('.slide', $banner);
		var $header = $('h3', $slide);
		var $price = $('.price', $slide);
		var $comment = $('.comment', $slide);
		var $image = $('.pic', $slide);
		var $link = $('a.click', $slide);
		
		// we start only if there's enough thumbs
		if ( $thumbs.length <= 1 ) {
			return;
		}
	
		// slideshow timer controller
		var slideshow = new Object();
		slideshow.timer = -1;
		slideshow.start = function() {
			if ( -1 != this.timer ) {
				clearInterval(this.timer);
			}
			
			if ( $banner.hasClass('play') ) {
				this.timer = setInterval( function() {
					$('a.next', $banner).click();
				}, slideshowDelay);
			}
		};
		slideshow.stop = function() {
			if ( -1 != this.timer ) {
				clearInterval(this.timer);
				timer = -1;
			}
		};
	
		$banner.addClass('play');
		
		// starting slideshow
		slideshow.start();
				
		// hover
		$banner.add($btns).hover(function() {
			slideshow.stop();
		}, function() {
			slideshow.start();
		});
	
		// html
		var $btns = $('<div class="controls" id="slideshow-btns""><a href="#" class="prev">Предыдущий</a><a href="#" class="pause">Пауза</a><a href="#" class="next">Следующий</a></div>');
		
		$banner.append($btns);
		$btns = $('#slideshow-btns a');
		
		// mark the first thumb as active
		$thumbs.filter(':first').addClass('active');
		
		// pause
		$btns.filter('.pause').click(function(e)	{
			if ( $banner.hasClass('play') ) {
				$banner.removeClass('play');
				
				slideshow.stop();
			} else  {
				$banner.addClass('play');
				
				slideshow.start();
			}
			
			e.preventDefault();
		});
		
		// prev-next click
		$btns.filter('.next, .prev').click(function(e) {
			if ( e.which ) {
				slideshow.stop();
			}
		
			var $next;
			
			if ($(this).hasClass('next')) {
				$next = $thumbs.filter('.active').next().length ? $thumbs.filter('.active').next() : $thumbs.filter(':first');
			} else {
				$next = $thumbs.filter('.active').prev().length ? $thumbs.filter('.active').prev() : $thumbs.filter(':last');
			} 	
				
			// changing classes
			$thumbs.removeClass('active');
			$next.addClass('active');
	
			// changing text
			var newHeader = $('.header', $next).html();
			var newPrice = $('.price', $next).html();
			var newComment = $('.comment', $next).html();
			var newImg = $('.pic', $next).html();
	
			$header.html(newHeader);
			$price.html(newPrice);
			$comment.html(newComment);
			$link.attr('href',$(newImg).attr('href'));
			
			// preloading image
			$banner.addClass('loading');
			$image.hide();
			
			var imgSrc = $(newImg).find('img').attr('src');
			var img = new Image();
			$(img).load(function() {
				$banner.removeClass('loading');
				
				$image.html(newImg);
				if ( $.browser.msie ) {
					$image.show();
				} else {
					$image.fadeIn();
				}
			}).attr('src', imgSrc);
			
			e.preventDefault();
		});
	}
}

function centerImages(images) {
	var appendBackground = false;
	var background = 'white';
	
	$(images).each( function() {
		var $img = $('img', this);
		var $imgContainer = $(this);
		
		$img.removeAttr('width').removeAttr('height').css({'height':'', 'width':''}); 
	
		var left = $img.outerWidth() / 2;
		var top = $img.outerHeight() / 2;

		// Centering image
		$img.css({
			'position': 'absolute',
			'left': '50%',
			'top': '50%',
			'margin-left': -left,
			'margin-top': -top
		});
	
		// Appending background
		if ( appendBackground ) {
			$imgContainer.css('background', background);
		}
	});
}


function selection(s) {
	$(s).disableSelection();
}

jQuery.fn.extend({
	disableSelection: function() {
		this.each(function() {
			this.onselectstart = function() { return false; };
			this.unselectable = "on";
			jQuery(this).css('-moz-user-select', 'none');
		});
	}
});


