$(document).ready(function() {
	$(".infoless").mouseover(function(e) {
        var id = $(this).attr("id").split("-")[1];
        for (i in infoless) {       
            if (infoless[i]["id"] == id) {
                var board = $("<div style='background: url(media/images/infobox.png) no-repeat;'>").attr("id", "infoboard-"+id).css({
                    "width" : "250px",
                    "height" : "182px",
                    "padding" : "10px",
                    "position" : "absolute"
                }).html(infoless_info(infoless[i])).hide();   
                $("body").append(board);
                board["id"] = id;
                infoboard_cache[id] = board;
                infoboard_cache[id].show();
            }       
        }
    });
    
    $(".infoless").mouseout(function(e) {
        id = $(e.target).attr("id").split("-")[1];
        if (typeof infoboard_cache[id] != "undefined") {
            infoboard_cache[id].hide();
        }
    });
    $(".infoless").mousemove(function(e) {
        id = $(e.target).attr("id").split("-")[1];
        if (typeof infoboard_cache[id] != "undefined") {
            y = e.pageY+20;
            x = e.pageX+20;
            infoboard_cache[id].css({"left" : x, "top" : y});
        }
    });
    
    $("form.poll-form").submit(function() {
        data = $(this).serialize();
        id = $("input[name=poll]", this).val();
		$.getJSON("poll/json/", data, function (json) {
            $.fn.ecpopup({"url" : "/poll/"+id+"/"})
        });
        return false;
    });
	$("a.size-chart-link").click(function() {
		$.fn.ecpopup({"url" : $(this).attr("href")+"?ajax=1"});
		return false;
	});
    
    $("#product-tabs .tab:not(.active-tab)").each(function() {
        $(this).hide();
    });
    $("#product-tabs .tab-item a").each(function() {
        $(this).click(function() {
            $(".tab-item").removeClass("active");
            $(this).parent(".tab-item").addClass("active");
            $("#product-tabs .tab").hide();
            $($(this).attr("href")).show();
            return false;
        });
    });
    $("div.product-announce-image").each(function() {
        var pos = $(this).position();
        var left = pos["left"]+parseInt($(this).css("width"))/2+52;
        var step = 0;
		var indent = 6;
        if ($(this).hasClass("sale")) {
            var sale = $("<img>").attr({
                "src" : "/media/images/icons/sale.png",
                "alt" : "Распродажа!",
                "title" : "Распродажа!"
            }).css({
                "position" : "absolute",
                "top" : pos["top"]+(40*step+indent),
                "left" : left
            });
            $(this).append(sale);
            step += 1;
        }
        if ($(this).hasClass("new")) {
            var new_ = $("<img>").attr({
                "src" : "/media/images/icons/new.png",
                "alt" : "Новинка",
                "title" : "Новинка"
            }).css({
                "position" : "absolute",
                "top" : pos["top"]+(40*step+indent),
                "left" : left
            });
            $(this).append(new_);
            step += 1;
        }
		if ($(this).hasClass("hit")) {
			var hit = $("<img>").attr({
				"src" : "/media/images/icons/hit.png",
				"alt" : "Хит продаж",
				"title" : "Хит продаж"
			}).css({
				"position" : "absolute",
				"top" : pos["top"]+(40*step+indent),
				"left" : left
			});
			$(this).append(hit);
			step += 1;
		}
        if ($(this).hasClass("limited")) {
            var limited = $("<img>").attr({
                "src" : "/media/images/icons/limited.png",
                "alt" : "Ограниченное количество!",
                "title" : "Ограниченное количество!"
            }).css({
                "position" : "absolute",
                "top" : pos["top"]+(40*step+indent),
                "left" : left
            });
            $(this).append(limited);
            step += 1;
        }
        if ($(this).hasClass("exclusive")) {
            var exclusive = $("<img>").attr({
                "src" : "/media/images/icons/exclusive.png",
                "alt" : "Эксклюзив",
                "title" : "Эксклюзив"
            }).css({
                "position" : "absolute",
                "top" : pos["top"]+(40*step+indent),
                "left" : left
            });
            $(this).append(exclusive);
            step += 1;
        }
	});
	//div.product-announce-image 
	$("div.promobox-blank, div.promobox").vAlign();

    $("a.product-image").fancybox({
        'padding' : 5
    });
    
    $("div.promobox, div.promobox-blank,").click(function() {
       window.location = $(this).find('div.link a').attr('href');
    });
	if ($("#current-watching").is("div")) {
        get_current_watching();
        
        $("#watched ul").jcarousel({
            vertical: true,
            auto: 2,
            scroll: 1
        });
    }
    var search = $("#searchbar input.q");
	var search_term = "Поиск по сайту"
	if (search.val() == "") {
		search.css("color", "#bbb");
		search.val(search_term);
	}
	search.focus(function() {
		if (search.val() == search_term) {
	        search.css("color", null);
	        search.val("");
		}
	});
    search.blur(function() {
        if (search.val() == "") {
            search.css("color", "#bbb");
            search.val(search_term);
        }
    });
	$("#searchbar form").submit(function() {
		search.val(search.val().replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
	});
    $("#fitting").click(function() {
       $.fn.ecpopup({
           "url" : "/primerka/?ajax=1" 
       });
       return false;
    });
    $("div.more-images .content").jcarousel({
        auto : 3,
        wrap: 'last',
        scroll: 1
    });
});
function infoless_info(data) {
    var root = $("<div>").addClass("infoless_block");
    var title = $("<h2>")
        .text(data["title"]);
    var info = $("<p>")
        .html(data["description"])
        .append("<p>")
        .append(build_properties(data["properties"]));
    
    if (data["discount"]) {
        var price = $("<b>")
            .append("Цена со скидкой: ")
            .append($("<h3>")
            .text(data["price"]));
    } else {
        var price = $("<b>")
            .append("Цена: ")
            .append($("<h3>")
            .text(data["price"]));
        //var price = $("<h3>").text(data["price"]);
    }
    root.append(title).append(info).append(price);
    return root;
}
function build_properties(data) {
    var root = $("<span>")
    for (i in data) {
        $(root).append(data[i]["name"]+": "+data[i]["value"]);
        if (i != data.length) {
            $(root).append($("<br>"));
        }
    }
    return root;
}
var infoboard_cache = {};

function get_current_watching() {
	$.getJSON("/catalog/current_watching/", {}, function(json) {
		for (i in json) {
			var block = $("<li>").attr("id", "current-watching-"+json[i].id);
			var link = $("<a>").attr("href", json[i].url);
			var text = $("<div>").text(json[i].title);
			var img = $("<img>").attr({"src" : json[i].image, "border" : 0});
			$(block).append($(link).append($(img)).append($(text)));
			$("#current-watching ul.content").append(block);
		}
		var loading = false;
	    $("#current-watching ul.content").jcarousel({
	        vertical : true,
	        auto : 2,
			scroll : 1,
			itemLastInCallback : function(a, b) {
				var oldsize = a.options.size;
				if (a.last == oldsize && !loading) {
				    loading = true;
					$.getJSON("/catalog/current_watching/", {}, function(json) {
						for (i in json) {
	                        var block = $("<li>").addClass("jcarousel-skin-name");//.attr("id", "current-watching-"+json[i].id);
	                        var link = $("<a>").attr("href", json[i].url);
	                        var text = $("<div>").text(json[i].title);
	                        var img = $("<img>").attr({"src" : json[i].image, "border" : 0});
	                        $(block).append($(link).append($(img)).append($(text)));
	                        a.add(oldsize-(-1*i)+1, $(block));
							a.options.size++;
							a.remove(oldsize-(json.length-1*i)-3);
						}
						loading = false;
						a.startAuto(a.options.auto);
	                });
				}
		    }
	   });
	});
}


(function ($) {
    $.fn.vAlign = function(container) {
        return this.each(function(i){
       if(container == null) {
          container = 'div';
       }
       var paddingPx = 10; //change this value as you need (It is the extra height for the parent element)
       $(this).html("<" + container + ">" + $(this).html() + "</" + container + ">");
       var el = $(this).children(container + ":first");
       var elh = $(el).height(); //new element height
       var ph = $(this).height(); //parent height
       if(elh > ph) { //if new element height is larger apply this to parent
           $(this).height(elh + paddingPx);
           ph = elh + paddingPx;
       }
       var nh = (ph - elh) / 2; //new margin to apply
       $(el).css('margin-top', nh);
        });
     };
})(jQuery);
