//var jq = jQuery.noConflict();

var setup = {
	'loader-time'        : 1000, // Minimalny czas pokazania się loadera
	'promotions-time'    : 1500, // Po jakim czasie od ukrycia się loadera mają pokazać się promocje na stronie głównej
	'promotions-speed'   : 1000  // Prędkość "wjazdu" promocji
}

/* Loader
---------------------------------------------- */
$(window).load(function() {
	
	/* Home ---------------------------------- */
	if ($('body').attr('id') == 'home' && !$('body').hasClass('no-loader')) {
		setTimeout(function() {
			$('#loader').fadeOut(1000);
			
			setTimeout(function() {
				promotions();
			}, setup['promotions-time']);
		}, setup['loader-time']);
	}
	if ($('body').hasClass('no-loader')) {
		$('#promotions').css('height', '266px');
	}
	
	$(window).bind('onload', function(){ background(); });
	
});

/* Global JS
---------------------------------------------- */
$(document).ready(function() {
	
	/* Home ---------------------------------- */
	if ($('body').attr('id') == 'home') {
		$('#promotions').css('height', '0');
	}
	$('#promotions-list').jcarousel();
	$('#wedding-dresses-intro ul').jcarousel({
		visible: 1,
		scroll: 1,
		itemVisibleInCallback: {
		  onAfterAnimation: function(carousel, item, idx, state){
			  $('#wedding-dresses-intro .pagination .current').html(idx);
		  }
		}	
	});
	
	/* Gallery ------------------------------- */
	$('.item-image .preview, .item-image .medium a, .fancybox').fancybox({
		overlayColor: '#000'
	});
	
	var DressMin 	= $('#wedding-dresses .item-image .min').attr('src'),
		DressMed 	= $('#wedding-dresses .item-image .med').attr('src'),	
		DressBig	= $('#wedding-dresses .item-image .medium a').attr('href'),
		DressAlt 	= $('#wedding-dresses .item-image .medium span').html();
	
	$('#wedding-dresses .small a').click(function() {
		var Min 	= $(this).find('.min').attr('src'),		
			Med		= $(this).parent().find('.med').attr('src'),
			Big 	= $(this).attr('href'),
			Alt 	= $(this).find('span').text();
		
		// Change small photo
		$(this).attr('href', DressBig);
		$(this).find('.min').attr('src', DressMin);
		$(this).parent().find('.med').attr('src', DressMed);
		$(this).find('span').html(DressAlt);		
		
		// Change preview
		$('#wedding-dresses .item-image .medium a').attr('href', Big);
		$('#wedding-dresses .item-image .medium .min').attr('src', Min);		
		$('#wedding-dresses .item-image .medium .med').attr('src', Med);
		$('#wedding-dresses .item-image .medium span').text(Alt);
		
		DressMin	= Min;
		DressMed	= Med;
		DressBig	= Big;
		DressAlt	= Alt;
		
		return false;
	});
	
	/* Truncate */
	var element = $('#description'),		
		detailsHeight = $('#details').height(),
		descriptionHeight = element.height(),		
		link = $('<a id="expander" class="link">'+ more +'</a>').toggle(expand, narrow);
		
	if(element.parent().parent().attr('id') == 'cars') {		
		var descriptionBig = 285,
			maxHeight = 140;
	}
	else {
		var descriptionBig = 260,
			maxHeight = 75;
	}
	
	if (descriptionHeight > maxHeight) {
		element.height(maxHeight);
		element.after(link);
	}
	
	function expand() {		
		$('.special-offer').hide();
		$('#details').animate({
			opacity: 0,
			height: 0,
			'min-height': 0
		}, 1000);
		
		element.animate({
			height: descriptionBig
		}, 1000);
		
		/* Add jScrollPane */
		setTimeout(function() {
			$('#description dd').jScrollPane();
		}, 1000);
		
		$(this).text(less);
	}
	
	function narrow() {		
		$('#details').animate({
			opacity: 1,
			height: detailsHeight
		}, 1000);
		
		element.animate({
			height: maxHeight
		}, 1000);
		
		setTimeout(function() {
			$('.special-offer').show();
		}, 1000);
		
		/* Remove jScrollPane */
		$('#description dd').jScrollPaneRemove();
		
		$(this).text(more);
	}
	
	/* Dresses list ------------------------- */
	var current = 1,
		all = Math.ceil(parseInt($('.dresses-list li').length) / 1);
	
	if(all > 1)
		$('.dresses-list').before('<div class="jcarousel-prev disabled">Poprzednia strona</div><div class="jcarousel-next">Następna strona</div>');

	$('.dresses-list').jCarouselLite({
		speed: 1000,
		scroll: 1,
		visible: 1,
		btnNext: '.jcarousel-next',
		btnPrev: '.jcarousel-prev',
		circular: false
	});
	$(".dresses-list .item").click(function() {
		var href = $(this).find('a').attr('href');
		
		window.location = href; 
	});
	
	// Pagination	
	$('#dresses-list .pagination .all').html(all);		
	$('#dresses-list .jcarousel-next').click(function() {
		if(current < all) {
			current = current + 1;
			$('#dresses-list .pagination .current').html(current);
		}
	});	
	$('#dresses-list .jcarousel-prev').click(function() {
		if(current > 1) {
			current = current - 1;
			$('#dresses-list .pagination .current').html(current);
		}
	});
	
	/* Cars gallery -------------------------- */
	var CarMed = $('#cars .gallery .active .med').attr('src'),
		CarBig = $('#cars .gallery .active a').attr('href');
	
	$('#cars .item-image .preview img').attr('src', CarMed);
	$('#cars .item-image .preview').attr('href', CarBig);
	
	$('#cars .gallery a').click(function() {
		CarMed = $(this).parent().find('.med').attr('src'),
		CarBig = $(this).attr('href');
			
		$('#cars .item-image .preview img').attr('src', CarMed);
		$('#cars .item-image .preview').attr('href', CarBig);
		
		$('.gallery li').removeClass('active');
		$(this).parent().addClass('active');
		
		return false;
	});
	
	/* Helpers ------------------------------- */
	$('#loader').click(function() { $(this).fadeOut(1000); });
	$('#wedding-tips').jScrollPane({ reinitialiseOnImageLoad: true });
	$('.float-content').jScrollPane({ reinitialiseOnImageLoad: true });
	$('#wedding-tip').jScrollPane({ reinitialiseOnImageLoad: true });
	$('.producers-wrapper').jcarousel({ visible: 4 });
	$('#fashions .item-description').jScrollPane({ reinitialiseOnImageLoad: true });
	$('#cities').jScrollPane({ reinitialiseOnImageLoad: true });
	
	/* FAQ */	
	var $pane4 = $('#faq');	
		$pane4.jScrollPane({ animateTo: true });
		
	$('#questions a').bind(
		'click',
		function()
		{
			var targetElementSelectorString = $(this).attr('href');
				$pane4[0].scrollTo(targetElementSelectorString);
			
			$('#questions li').removeClass('active');
			$(this).parent().addClass('active');
			
			return false;
		}
	);
	
	/* FAQ new version */
	var URL = location.href;
		URL = URL.split("#");
		
	if(URL[1] != undefined) {
		$('#'+URL[1]).prev().addClass('active');
		$('#'+URL[1]).show();
	}
	
	$('#questions-list dt a').click(function() {
		$('#questions-list dt').removeClass('active');
		$('#questions-list dd').slideUp();
		
		$(this).parent().addClass('active');
		$(this).parent().next().slideDown();
	});
	
	/* Gallery */
	$('.gallery').each(function() {
		var currentGalleryPos = parseInt($('.gallery ul .active').index()) + 1,
			galleryAll = parseInt($('.gallery ul li').size()),
			show = 9;
				
		if($(this).hasClass('short') && !$(this).hasClass('attractions')) {
			if (currentGalleryPos <= 4) currentGalleryPos = 1;
			else if (currentGalleryPos >= 5) currentGalleryPos = currentGalleryPos - 3;
			
			show = 7;
		}
		else if ($(this).hasClass('attractions')) {
			if (currentGalleryPos <= 2) currentGalleryPos = 1;
			else if (currentGalleryPos >= 3 && currentGalleryPos <= (galleryAll-3)) currentGalleryPos = currentGalleryPos - 2;
			else currentGalleryPos = galleryAll;
			
			show = 5;
		}
		else {
			if (currentGalleryPos <= 5) currentGalleryPos = 1;
			else if (currentGalleryPos >= 6) currentGalleryPos = currentGalleryPos - 4;
			
			show = 9;
		}
		
		$('.gallery ul').jcarousel({
			start: currentGalleryPos,
			visible: show
		});
	});
	
	/* Other products gallery (/produkt/product-name) */
	$('.other-products .pagination .all').html(parseInt($('.other-products ul li').size()));
	
	function op_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
		$('.other-products .pagination .current').html(idx);
	};

	$('.other-products').jcarousel({
		visible: 1,
		scroll: 1,
		start: parseInt($('.other-products .active').parent().index()) + 1,
		itemVisibleInCallback: {
			onAfterAnimation: op_itemVisibleInCallbackAfterAnimation
		}
	});

	// Wedding photos
	$(document).keyup(function(event){
		if($('.prev') || $('.next')){
			if (event.keyCode == 37 || event.keyCode == 40 || event.keyCode == 100){
		    	$('#photo .prev').click();
		    }
		    else if (event.keyCode == 39 || event.keyCode == 38 || event.keyCode == 102){
		    	$('#photo .next').click();
		    }	
		}		
	});
	var currentPhoto = $('#photos .active').index(),
		allPhotos = ($('#photos li').length - 1);

	$('#photos').jcarousel({
		initCallback: mycarousel_initCallback
	});

	$('#photos a').click(function() {
		$('#photos li').removeClass('active');
		$(this).parent().addClass('active');

		$('#photo .wrap a').attr('href', $(this).attr('href'));
		$('#photo .wrap img').attr('src', $(this).parent().find('.med').attr('src'));

		currentPhoto = $(this).parent().index();
		if (currentPhoto < 1) $('#photo .prev').hide(); else  $('#photo .prev').show();
		if (currentPhoto > (allPhotos-1)) $('#photo .next').hide(); else  $('#photo .next').show();

		return false;
	});

	$('#photo .prev').click(function() {
		if (currentPhoto > 1) {
			$('#photo .prev').show();
			$('#photo .next').show();
			currentPhoto--;
		}
		else {
			$('#photo .prev').hide();
			$('#photo .next').show();
			currentPhoto = 0;
		}

		$('#photos li').removeClass('active');
		$('#photos li:eq('+ currentPhoto +')').addClass('active');

		$('#photo .wrap a').attr('href', $('#photos li:eq('+ currentPhoto +') a').attr('href'));
		$('#photo .wrap img').attr('src', $('#photos li:eq('+ currentPhoto +')').find('.med').attr('src'));

		return false;	
	});
	$('#photo .next').click(function() {
		if (currentPhoto < (allPhotos-1)) {
			$('#photo .next').show();
			$('#photo .prev').show();

			currentPhoto++;
		}
		else {
			$('#photo .next').hide();
			$('#photo .prev').show();
			currentPhoto = allPhotos;
		}
		
		$('#photos li').removeClass('active');
		$('#photos li:eq('+ currentPhoto +')').addClass('active');

		$('#photo .wrap a').attr('href', $('#photos li:eq('+ currentPhoto +') a').attr('href'));
		$('#photo .wrap img').attr('src', $('#photos li:eq('+ currentPhoto +')').find('.med').attr('src'));

		return false;	
	});

	function mycarousel_initCallback(carousel) {
		$('#photo .next').bind('click', function() {
			carousel.scroll(jQuery.jcarousel.intval(currentPhoto - 1));
			return false;
		});

		$('#photo .prev').bind('click', function() {
			carousel.scroll(jQuery.jcarousel.intval(currentPhoto - 3));
			return false;
		});
	};

	$('#photo .wrap a').fancybox({
		overlayColor: '#000'
	});
	
	// Search
	$('#search li select').change(function() {
		var value = $(this).find('option:selected').attr('value');
		
		if(value == 'Wybierz' || value == '')
			$(this).parent().removeClass('selected');
		else
			$(this).parent().addClass('selected');
	});
	
	$('#search .size input').change(function() {
		$(this).parent().addClass('selected');
	});
	
	$('#search li select').each(function() {
		var value = $(this).find('option:selected').attr('value');
		
		if(value == 'Wybierz' || value == '')
			$(this).parent().removeClass('selected');
		else
			$(this).parent().addClass('selected');
	});
	$('#search .size input').each(function() {
		if($(this).attr('value') != '')
			$(this).parent().addClass('selected');
	});
	
	/* Background ---------------------------- */
	background();
	$(window).bind('resize', function(){ background(); });
	
	$('#share_close').live('click', function(){
		$('#share_box').remove();
		$('#details').show();
		$('#description').show();
		$('#expander').show();
		return false;	
	});
	$('#share_button').live('click', function(){
		$('#share_button').after('<img src="/images/ajax-loader.gif" alt="loading..." id="ajax_loader" />');
		$.ajax({
			type: 'post',
			data: $('#share_form').serialize(),
			url: $('#share_form').attr('action'),		
			dataType: 'html',
			success: function(data){
				$('#share_box').replaceWith(data);
				share_default();	
			}
		});
		return false;
	});
	
	$('#share').live('click', function(){
		$('#share_box').remove();
		$('#expander').hide();		
		var a = $(this);
		$('#details').hide();
		$('#description').hide();
		$('#details').before('<img src="/images/ajax-loader.gif" alt="loading..." id="ajax_loader" />');
		$.ajax({
			type: 'get',
			url: a.attr('href'),
			dataType: 'html',
			success: function(data){
				$('#ajax_loader').remove();
				$('#details').before(data);	
				share_default();
			}
		});
		return false;
	});
	
	function share_default(){
		$('.default-value').each(function() {
			var default_value = this.value;
			$(this).focus(function() {
				if(this.value == default_value) {
					this.value = '';
				}
			});
			$(this).blur(function() {
				if(this.value == '') {
					this.value = default_value;
				}
			});
		});
	};
	
	$('#add_del_fav').live('click', function(){
		var a = $(this);
		a.after('<img src="/images/ajax-loader.gif" alt="loading..." id="ajax_loader" />');
		$.ajax({
			type: 'get',
			url: a.attr('href'),
			dataType: 'json',
			success: function(data){
				console.log('dupa');
				a.replaceWith(data.msg);
				$('#ajax_loader').remove();
			}
		});
		return false;
	});
	
	$('#button_rate').click(function(event){
		var button = $(this);
		$('#rate_loader').hide(100, function(){
			$(this).remove();			
		});
		button.before('<img src="/images/ajax-loader.gif" alt="loading..." id="rate_loader" style="padding-right: 5px; vertical-align: middle;" />');
		$.ajax({
			type: 'post',
			url: $('#form_rate').attr('action'),
			dataType: 'json',
			data: $('#form_rate').serialize(),
			success: function(data){
				if(data.status == 'success'){
					button.remove();
					$('#rate_error_msg').remove();
					$('#rate_loader').replaceWith(data.msg);
					$('#info_rate').replaceWith(data.info);
				}else if(data.status == 'error'){
					button.remove();
					$('#rate_error_msg').remove();					
					$('#rate_loader').replaceWith('<span id="rate_error_msg">'+ data.msg +'</span>');
				}
			}
		});
		return false;
	});
	
	
});

function promotions() {
	$('#promotions').animate({
		height: '266px'
	}, setup['promotions-speed']);
	
	$('.promotions').parent().addClass('active');
}

function background() {
	var windowWidth  = $(window).width(),
		windowHeight = $(window).height(),
		setWidth     = 0,
		setHeight    = 0;
	
	var ratio = windowWidth / windowHeight;
	
	if (ratio > 1.6) {
		setWidth  = windowWidth;
		setHeight = windowWidth / 1.6;
	}
	else {
		setWidth  = windowHeight * 1.6;
		setHeight = windowHeight;
	}
	
	$('#background img').css({
		'width' : setWidth + 20,
		'height': setHeight + 20
	});
}
