$(document).ready(function(){
    $('#search_block input[type=checkbox]').change(function(){//Подсветка зеленым чекбоксов в форме поиска
        if($(this).is(':checked')){
            $('label[for='+$(this).attr('id')+']').addClass('active');
        }
        else{
            $('label[for='+$(this).attr('id')+']').removeClass('active');
        }
    });

    $('#search_block form li.floatleft>a').click(function(){//Скрыть/показать списки с чекбоксами в форме поиска
        $(this).next('ul').toggle(500);
        return false;
    });

    $('a.toggle_list').click(function(){//Скрыть/показать списки с чекбоксами списке товаров
        $(this).next().next().toggle(500);
        return false;
    });
    
//    if($("#bestsellers_block").attr('mainpage') == 'true') {
//        $("#bestsellers_block .carousel").jCarouselLite({
//            btnNext: "#bestsellers_block .next a",
//        	btnPrev: "#bestsellers_block .prev a"
//        });
//    }
        
    $('#search_bestsellers .main_tabs a').click(function(){//Переключение табов(поиск,бестселлеры)
    	$('#search_block').slideDown(2000);
//        parent_li=$(this).parents('li:first');
//        if(!parent_li.hasClass('active')){
//            $('#search_bestsellers .main_tabs li').each(function(){$(this).removeClass('active');$($('span a',$(this)).first().attr('href')).hide()});
//            parent_li.addClass('active');
//            $($(this).attr('href')).show();
//        }
        return(false);
    });
    
    $('#search_block').mouseout(function(){
    	//$('#search_block').slideUp();
    });
    
    $('#search_block .search_tabs a').click(function(){//Переключение табов(внутри поиска)
        parent_li=$(this).parents('li:first');
        if(!parent_li.hasClass('active')){ 
            $('#search_block .search_tabs li').each(function(){$(this).removeClass('active');$($('span a',$(this)).first().attr('href')).hide()});
            parent_li.addClass('active');
            $($(this).attr('href')).show();
        }
        return(false);
    });
    $('.category_switcher a').click(function(){//Переключение табов(категории в каталоге(1,5 спальное, 2 итд))
        var parent_li=$(this).parents('li:first');
        if(!parent_li.hasClass('active')){
        	var size_id = this.id.substr(7);
	    	var product_group = '#'+$("div.product_group_block:has(#switch_"+size_id+")").attr('id');
	    	
        	var ts = this;
        	var active = $(product_group+' .category_switcher li.active');
        	active.removeClass('active');
        	$($('a',active).first().attr('href')).fadeOut(function() {
	            parent_li.addClass('active');
	            $($(ts).attr('href')).fadeIn();
	            
	            location.hash = '#' + size_id;
	            
	            var url = location.href.replace("http://www.enix.ru", "");
	            url = url.replace("#", "&tab_id=");
//	        	$.get("/static/click_tabs/?url="+url);
        	});
        }
        return(false);
    });
    $(window).resize(function(){ //Перерасчет размеров карусельки при ресайзе окна
        if($('#bestsellers_block').is(":visible") &&  currwidth != document.documentElement.clientWidth){
            $("#bestsellers_block .carousel,#bestsellers_block .carousel *").removeAttr('style');
            $("#bestsellers_block .carousel").jCarouselLite({
                btnNext: "#bestsellers_block .next a",
                btnPrev: "#bestsellers_block .prev a"
            });
        }
        currwidth = document.documentElement.clientWidth;
    });
    
    
    $('.product_manufacturers li').mouseenter(function(){
        $('a',$(this).parents('ul:first')).each(function(){$($(this).attr('href')).hide()});
        $('li',$(this).parents('ul:first')).removeClass('active');
        $(this).addClass('active');
        $($('a',$(this)).attr('href')).show();
    });
    $('.product_manufacturers li:first-child').mouseenter();    
    
	$('a.toolTip').tooltip({showURL: false, positionTop: true, top: -15, left: 3});

    $('.product_color_radio').change(function(){// Радио батоны на странице инфо о товаре
        $('input[name='+$(this).attr('name')+']').each(function(){
            if($(this).is(':checked')){
                $('label[for='+$(this).attr('id')+']').addClass('bold');
            }
            else{
                $('label[for='+$(this).attr('id')+']').removeClass('bold');
            }
        });
    });
    $('.quant_plus').click(function(){//Плюс в корзине
        inp=$(this).prev();
        val=parseInt(inp.val());
        if(val<99){
        	basket.add_product(inp.attr('product_option_id'));
        	basket.update_basket_page();
//            inp.val(val+1);
        }
        return false;
    });
    $('.quant_minus').click(function(){//Минус в корзине
        inp=$(this).next();
        val=parseInt(inp.val());
        if(val>1){
        	basket.dec_product(inp.attr('product_option_id'));
        	basket.update_basket_page();
//            inp.val(val-1);
        }
        return false;
    });
    $('input').change();
    $("img.rounded_corners").each(function () {
    	var img = $(this);
     
    	// build wrapper
    	var wrapper = $('<div class="rounded_wrapper"></div>');
    	wrapper.width(img.width());
    	wrapper.height(img.height());
     
    	// move CSS properties from img to wrapper
    	wrapper.css('float', img.css('float'));
    	img.css('float', 'none')
     
    	wrapper.css('margin-right', img.css('margin-right'));
    	img.css('margin-right', '0')
     
    	wrapper.css('margin-left', img.css('margin-left'));
    	img.css('margin-left', '0')
     
    	wrapper.css('margin-bottom', img.css('margin-bottom'));
    	img.css('margin-bottom', '0')
     
    	wrapper.css('margin-top', img.css('margin-top'));
    	img.css('margin-top', '0')
     
    	wrapper.css('display', 'block');
    	img.css('display', 'block')
     
    	// wrap image
    	img.wrap(wrapper);
     
    	// add rounded corners
    	img.after('<div class="tl"></div>');
    	img.after('<div class="tr"></div>');
    	img.after('<div class="bl"></div>');
    	img.after('<div class="br"></div>');
    });
    currwidth = document.documentElement.clientWidth;
    $('#bodywrap').css('width','auto');
    
    $(".category_options input:checkbox").change(select_colors);
    
	$("#product_tabs").tabs({
		select: function(event, ui) {
			location.hash = $("#"+ui.panel.id+" li.active a").attr("id").substr(7);
		}
	});
	
	var selector = '#switch_' + parseInt(location.hash.substr(1));
	var link = $(selector);
	var tab = link.attr('href');
    if(tab) {
    	var product_group = '#'+$("div.product_group_block:has("+selector+")").attr('id');
		$("#product_tabs").tabs("select", product_group);
		var active = $(product_group+' .category_switcher li.active');
		active.removeClass('active');
		$($('a',active).first().attr('href')).hide();
	    link.parents('li:first').addClass('active');
	    $(tab).show();
    }
    else {
		var product_group = '#'+$("div.product_group_block:first").attr('id');
		var active = $(product_group+' .category_switcher li.active');
		active.removeClass('active');
		$($('a',active).first().attr('href')).hide();
		
		var max_count = 0;
		var element;
		$(product_group+' .category_switcher>li>a').each(function() {
			var size_count = parseInt( $(this).attr('size_count') );
			if(size_count > max_count) {
				max_count = size_count;
				element = this;
			}
		});
		
		$(element).parent().addClass('active');
		$( $(element).attr('href') ).show();
    }
    
//    window.onhashchange = function() {alert(location.hash)};
	
    
    $("a.zoom").fancybox({
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'titleShow'		: false,
		'cyclic'		: true
	});
	
	$('a.buy_button').click(buy_button_click);
	$('a.buy_relared_product').click(buy_related_button_click);
	$('a.remove_basket_product').click(remove_basket_product_click);
	$('#show_order_form').click(show_order_form);
	$('#send_order').click(send_order_click);
	$('div.terms_letter a').click(terms_letter_click);
	
	$('.img_tooltip').each(function() {
		var img_src = $(this).attr('img_src');
		$(this).attr('title', '<img src="'+img_src+'">');
	});
	$('.img_tooltip').tooltip({showURL: false, positionTop: true, top: -3, left: 3});
	
	$('a.jq_tooltip').tooltip({showURL: false, positionTop: true, top: -3, left: 3});
	
	$("#order_email").focus(function() {
		if ($(this).attr('changed') == 0) {
			$(this).val('');
			$(this).css('color', 'black');
			$(this).attr('changed', 1);
		}
	}).blur(function() {
		if ($(this).val() == '') {
			$(this).val('somemail@example.com');
			$(this).css('color', 'gray');
			$(this).attr('changed', 0);
		}
	}).blur();
	
	basket.refresh();
	
$('.brands_over').mouseover(function(){
	img_id = '#img_c_'+$(this).attr('c_id');
	$(img_id).attr('src', $(img_id).attr('rel'));
});
$('.autowrap div.product_block .top_part .img a img:visible').each(function(){
	$(this).attr('src', $(this).attr('rel'));
});

});



function select_colors() {
	
    if($(this).is(':checked')){
        $('label[for='+this.id+']').addClass('active');
    }
    else{
        $('label[for='+this.id+']').removeClass('active');
    }
    
	var size_block = $(this).attr('size_block');
	$(size_block + ' .fixed_blocks').fadeOut(function() {
		
		$(size_block + ' .product_block').hide();
		
		var count = 0;
		$(size_block + " input:checkbox:checked").each(function () {
			$(size_block + ' .' + $(this).val()).show();
			count++;
		});
		if(!count) {
			$(size_block + ' .product_block').show();
		}
		if ($.browser.msie) {
			$(size_block + ' .fixed_blocks').show(); // В IE8 почему то не работает fadeIn
		}
		else {
			$(size_block + ' .fixed_blocks').fadeIn();
		}
	});
}

function buy_button_click() {
	var product_option_id = $(this).attr('product_option_id');
	if(!product_option_id) {
		product_option_id = $('input:radio[name=product_option]:checked').val();
	}
	if(!product_option_id) {
		alert('Вы не выбрали товар');
		return false;
	}
	if(basket.add_product(product_option_id)) {
		return window.confirm("Товар добавлен в корзину. Перейти к оформлению заказа?");
		alert("Товар добавлен в корзину");
	}
	else {
		alert("Неизвестная ошибка!");
	}
	return true;
}

function buy_related_button_click() {
	var product_option_id = $(this).attr('product_option_id');
	if(basket.add_related_product(product_option_id)) {
		alert("Дополнительный товар добавлен в корзину");
	}
	else {
		alert("Вы не можете взять дополнительных товаров больше чем основных!");
	}
	return false;
}

function show_order_form() {
	$("#order_form_block").slideDown('slow');
	$('html').animate({scrollTop : $("#order_form_block").offset().top},'slow');
	return true;
}

function remove_basket_product_click() {
	var product_option_id = $(this).attr('product_option_id');
	basket.del_product(product_option_id);
    basket.update_basket_page();
	return false;
}

function send_order_click() {
	if( isEmpty(basket.products) ) {
		alert("Ваша корзина пуста");
		return false;
	}
//	var min_price = 1500
//	if( basket.sum_price < min_price ) {
//		alert("Сумма вашего заказа составляет " + basket.sum_price + " рублей, минимальная сумма заказа в нашем магазине - "+min_price+" рублей.");
//		return false;
//	}
	
	var success = true;
	
	if( $("#order_phone").val() == '' ) {
		$("#order_phone").css('border', '1px solid red');
		success = false;
	}
	else {
		$("#order_phone").css('border', '1px solid #E4E4E4');
	}
	
	if( $("#order_address").val() == '' ) {
		$("#order_address").css('border', '1px solid red');
		success = false;
	}
	else {
		$("#order_address").css('border', '1px solid #E4E4E4');
	}
	
	if (success) {
		if ($("#order_email").attr('changed') == 0) {
			$("#order_email").val('');
		}
	}
	else {
		alert("Вы не заполнили все обязательные поля");
	}
	
	return success;
}

function terms_letter_click() {
	
	var text;
	var ready = false;
	
	$.get($(this).attr('href'), function(data){
		text = data;
		if (ready) {
			$("#letter_description").html(text).slideDown();
		}
		else {
			ready = true;
		}
	});
	
	$('html').animate({scrollTop : 0},'slow');
	
	$("#letter_description").slideUp(function() {
		if (ready) {
			this.innerHTML = text;
			$(this).slideDown();
		}
		else {
			ready = true;
		}
	});
	
	return false;
}

function isEmpty(ob){
	for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
	return true;
}

function load_text(url) {
	return $.ajax({url: url, async: false}).responseText;
}

function new_window(window_name, url) {
	window.open(url, window_name, "left=70, top=100, width=1150, height=700, scrollbars=1, status=1");
}

//mydomain = 'http://www.enix.ru/';
//function handleErrorFn() { top.location=mydomain; }
//window.onerror = handleErrorFn;
//if (top.location.href != window.location.href) {top.location = mydomain;}

