$(document).ready(function(){
	// alert('hi');
	// 	TOP MENU NAV:
	$("#nav").dropdown({timeout: 200});
	
	// IMG PRELOAD:
	preloadImages();
	
	$(".slider-range").slider({
		range: true,
		min: parseInt($("input#amount_min_helper").val()),
		max: parseInt($("input#amount_max_helper").val()),
		step: 5,
		values: [parseInt($("input#amount_min_helper").val()), parseInt($("input#amount_max_helper").val())],
		slide: function(event, ui) {
			$("#amount_min").val(ui.values[0] + ' лв');
			$("#amount_max").val(ui.values[1] + ' лв');
		},
		change: function(event, ui) {
			submitFilters({form: $(ui.handle).parents('form:first')});
		}
		
	});
	$("form.ajax-form").find('.inputfilter').live('click', function(e){
		if ( $(this).hasClass('colorfilter') ) {
			e.preventDefault();
			$(this).toggleClass('selected');
			if ( $(this).hasClass('selected') ) {
				$(this).next().next().val($(this).next().val());
			} else {
				$(this).next().next().val('');
			}
		}
		submitFilters({form: $(this).parents('form:first')});
	});
	$(".page-filter:not(.no-ajax)").find('a').live('click', function(e) {
		e.preventDefault();
		if ( $(this).attr('href') === undefined ) {
			return false;
		}
		submitFilters({form: $("form.ajax-form").eq(0), url: $(this).attr('href')});
	});
	$("a.ajax").live('click', function(e){
		e.preventDefault();
		if ( $(this).hasClass('selected') ) {
			return false;
		}
		var el = $(this);
		$.ajax({
			url: el.attr('href'),
			dataType: 'html',
			beforeSend: function() {
				// alert('asd');
				$(".rightside").before('<div class="ajax_loading_overlay"></div>');
				$(".ajax_loading_overlay").offset($(".ajax-content").offset());
				$(".ajax_loading_overlay").height($(".ajax-content").innerHeight());
				$(".ajax_loading_overlay").width($(".ajax-content").width());
			},
			success: function(data, textStatus, XMLHttpRequest) {
				$(".ajax-content").html(data);
				preloadImages();
				attachJZoom();
			}
		});
	});
	// PRODUCT INDEX:
	$(".products-sorter").live('change', function(e){
		// alert($(this).val());
		submitFilters({form: $("form.ajax-form").eq(0), url: $("form.ajax-form").attr('action') + '/sortby:' + $(this).val()});
	});
	
	// PRODUCT VIEW:
	$(".product-thumbnails").find('a').live('click', function(e){
		e.preventDefault();
		if ( $(this).hasClass('active') ) {
			return false;
		}
		var newSrc = $(this).children("img:first").attr('src').replace('width-44,height-61', 'width-305,height-405');
		var newHref = $(this).attr('href');
		$(this).siblings().removeClass('active');
		$(this).addClass('active');
		var mainThumbLink = $(this).parents(".product-thumbnails:first").prev("a");
		var mainThumbImg = mainThumbLink.children("img");
		mainThumbImg.css({opacity: 0.5});
		
		var pr1 = new Image();
		$(pr1).load(function(e){
			var pr2 = new Image();
			$(pr2).load(function(e){
				mainThumbLink.attr('href', newHref);
				mainThumbImg.attr('src', newSrc);
				mainThumbImg.css({opacity: 1});
			}).attr('src', newSrc);
		}).attr('src', newHref);
		
	});
	// PRODUCT VIEW SIZES:
	// $(".sizefilter.waist").live('click', function(e){
	// 	e.preventDefault();
	// 	selectSizes({
	// 		el: $(this),
	// 		siblings: '.sizefilter.waist',
	// 		depends: '.sizefilter.lenght',
	// 		replacement: 'L'
	// 	});
	// });
	// $(".sizefilter.lenght").live('click', function(e){
	// 	e.preventDefault();
	// 	selectSizes({
	// 		el: $(this),
	// 		siblings: '.sizefilter.lenght',
	// 		depends: '.sizefilter.waist',
	// 		replacement: 'W'
	// 	});
	// });
	$(".sizefilter").live('click', function(e){
		e.preventDefault();
		var repl = null;
		if ( $(this).hasClass('waist') ) {
			selectSizes({
				el: $(this),
				siblings: '.sizefilter.waist',
				depends: '.sizefilter.lenght',
				replacement: 'L'
			});
			$("p.choice").children(".current-choice-w").html($(this).html());
		} else if ( $(this).hasClass('lenght') ) {
			selectSizes({
				el: $(this),
				siblings: '.sizefilter.lenght',
				depends: '.sizefilter.waist',
				replacement: 'W'
			});
			$("p.choice").children(".current-choice-l").html(', ' + $(this).html());
		} else {
			// selectSizes({
			// 	el: $(this)
			// });
			// alert($(this).html());
			$(".sizefilter").removeClass('selecteds');
			$(this).addClass('selecteds');
			$("p.choice").children(".current-choice").html($(this).html());
		}
		if ( $("p.choice").is(':hidden') ) {
			$("p.choice").fadeIn();
		}
	});
	attachJZoom();
	
	// ADD TO CART EVENT
	// $("#add-to-cart").live('click', function(e){
	// 	var msgEl = $("#add-to-cart-msg");
	// 	msgEl.show();
	// 	setTimeout(function(){msgEl.hide();}, 5000)
	// });
});

function selectSizes(options) {
	var options = $.extend({
		el: null,
		siblings: '.sizefilter',
		depends: '.sizefilter',
		replacement: '',
		filter: 'p.accepts',
		split: ',',
		selectedClass: 'selecteds',
		inactiveClass: 'unav'
	}, options);
	
	$(options.siblings).removeClass(options.inactiveClass);
	$(options.siblings).removeClass(options.selectedClass);
	$(options.el).addClass(options.selectedClass);
	var accepts = $(options.el).next(options.filter).html().split(options.split);
	$.each($(options.depends), function(i){
		var val = $(this).html().replace(options.replacement, '');
		var accepted = $.inArray(val, accepts);
		if ( accepted == -1 ) {
			$(this).addClass(options.inactiveClass);
		} else {
			$(this).removeClass(options.inactiveClass);
		}
	});
	
}
// $(".filtered_container").append('<div class="ajax_loading_overlay"></div>');
// $(".ajax_loading_overlay").css('position', 'absolute');

// $(".ajax_loading_overlay").height($(".filtered_container").height());
// $(".ajax_loading_overlay").width($(".filtered_container").width());
			
function submitFilters(options) {
	var options = $.extend({
		form: null,
		url: null
	}, options);
	var url = options.url;
	if ( url === null ) {
		url = options.form.attr('action');
	}
	$.ajax({
		url: url,
		type: options.form.attr('method'),
		data: options.form.serialize(),
		dataType: 'html',
		beforeSend: function() {
			$(".filtered_container").before('<div class="ajax_loading_overlay"></div>');
			$(".ajax_loading_overlay").offset($(".filtered_container").offset());
			$(".ajax_loading_overlay").height($(".filtered_container").innerHeight());
			$(".ajax_loading_overlay").width($(".filtered_container").width());
		},
		success: function(data, textStatus, XMLHttpRequest) {
			$(".filtered_container").html(data);
			// $(".filtered_container").removeClass('loading');
			$(".ajax_loading_overlay").remove();
			// alert('aha');
			preloadImages();
		}
	});
}

function attachJZoom() {
	$('.jqzoom').jqzoom({
		zoomWidth: 633,
		zoomHeight: 573,
		xOffset: 10,
		yOffset: 0,
		position: "right", //and MORE OPTIONS
		title: false
	});
}

function preloadImages() {
	$("img.img-preload").each(function(e){
		var preloader = '<div class="img-loading"></div>';
		// alert($(this).css('paddingTop'));
		$(this).hide();
		$(this).parent().append(preloader);

		$(this).parent().children(".img-loading").css({
			width: $(this).width(),
			height: $(this).height(),
			left: $(this).offset().left,
			top: $(this).offset().top,
			paddingTop: $(this).css('paddingTop'),
			paddingRight: $(this).css('paddingRight'),
			paddingBottom: $(this).css('paddingBottom'),
			paddingLeft: $(this).css('paddingLeft'),
			marginTop: $(this).css('marginTop'),
			marginRight: $(this).css('marginRight'),
			marginBottom: $(this).css('marginBottom'),
			marginLeft: $(this).css('marginLeft'),
		});
		
		// $(this).parent().children(".img-loading").remove();
		// $(this).fadeIn();
		
		$(this)
		.attr('src', $(this).attr('src'))
		.load(function(ev){
			$(ev.target).parent().children(".img-loading").remove();
			$(ev.target).fadeIn();
		});
	});
}

jQuery.fn.dropdown = function(options) {
	var options = jQuery.extend({
		filter: 'ul',
		timeout: 300,
		timeoutHelper: null
	}, options);
	var main = this;
	main.children('li').bind('mouseenter', function(e){
		options.timeoutHelper = null;
		$(main).children('li').find(options.filter).css('visibility', 'hidden');
		$(this).find(options.filter).css('visibility', 'visible');
		// $(this).find(options.filter).animate({
		// 	'visibility': 'visible'
		// }, 100);
	});
	main.children('li').bind('mouseleave', function(e){
		var el = $(this).find(options.filter);
		options.timeoutHelper = setTimeout(function(){
			el.css('visibility', 'hidden');	
		}, options.timeout);
	});
	$(document).bind('click', function(){
		main.children('li').find(options.filter).css('visibility', 'hidden');
	});
}
