var currentPage = 1;

$(function() {
    $(".l-side .b-subtitle A").bind("mouseover", function() {
        if ($(this).parent().next("UL").is(":hidden") || $(this).parent().next("UL").is(".pin")) {
            $(".l-side .b-sidenav:not(.pin)").slideUp("slow");
            $(".l-side .b-subtitle:not(.pin)").removeClass("b-subtitle_active")
            $(this).parent().next("UL").slideDown("slow");
            $(this).parent().addClass("b-subtitle_active");
        }
    });

    $(".l-side .b-sidenav > LI > A").bind("mouseover", function() {
        if ($(this).next("UL").is(":hidden") || $(this).next("UL").is(".pin")) {
            $(".l-side .b-sidenav > LI > UL:not(.pin)").slideUp("slow");
            $(this).next("UL").slideDown("slow");
        }
    });

    $(".l-side .b-subtitle A").bind("click", function() {
        if ($(this).attr("href") != "#") return true;

        $(".l-side .pin").removeClass("pin");

        $(this).parent(".b-subtitle").addClass("pin");
        $(this).parent().next(".b-sidenav").addClass("pin");

        return false;
    });

    $(".b-gallery").draggable({
        cursor: 'move',
        stack: ".b-gallery",
        stop: function(event, ui) {
            var id = ui.helper.attr("id").substring(5);
            dialogs[id].left = ui.helper.offset().left;
            dialogs[id].top = ui.helper.offset().top;
            saveDialogs();
        }
    });
});

function loadPics(id, page, query) {
    $.getJSON(
        "/ajax/catalog/" + id + "/?page=" + (page ? page : 1) + (query ? "&" + query : ""),
        function(data) {
            if (data.goods) {
                $("#pictures DIV").remove();
                $(data.goods).each(function(i, item) {
                    var $div = $("<div />")
                        .attr({ "class": data.topic.list_class })
                        .html(
                            item.pic1 ? '<a href="#"><img src="/catalog/' + item.topic + '/' + item.pic1 + '" /><span><i>' + item.title + '</i></span></a>' : "нет изображения"
                        )
                        .appendTo($("#pictures"));

                    if (item.pic2)
                        $div.find("a").bind("click", { "id": item.id }, itemInfo);
                });
            }
            currentPage = parseInt(data.page);

            if (data.is_first) $("#pictures .larr").hide(); else $("#pictures .larr").show();
            if (data.is_last)  $("#pictures .rarr").hide(); else $("#pictures .rarr").show();
        }
    );

    return false;
}

function zIndex(sel) {
    var zIndex = 333;
    $(sel).each(function(i, item) {
        if (parseInt($(item).css("z-index")) > zIndex) {
            zIndex = parseInt($(item).css("z-index"));
        }
    });
    return zIndex + 1;
}

function showHdItem(realId)
{
	$("#item_" + realId).width(460)
	if ($("#item_" + realId).is(":visible")) {
            $("#item_" + realId).css({ "z-index": zIndex(".b-gallery") });
            //$("#item_" + realId)
            //    .draggable("destroy")
            //    .hide("normal")
            //;
            //dialogs[realId] = null;
            saveDialogs();
        }
        else {
            $("#item_" + realId)
                .css({ "position": "absolute", left: "50%", "top" : "34px", "z-index": zIndex(".b-gallery") })
                .draggable({ cursor: 'move', stack: ".b-gallery" })
                .show("normal")
            ;
            dialogs[realId] = {
                "left": $("#item_" + realId).offset().left,
                "top": $("#item_" + realId).offset().top,
                "full": false
            };
            saveDialogs();
        }
}
function itemInfo(path, id, issearch) {
    var realId = id;

    if ($("#item_" + realId).length) {
        showHdItem(realId)
    }
    else 
    {
    	if(issearch && !realId.match(/^\d\.\d\d.\d\d\d$/)) {
    		 alert('Неправильный формат артикула (X.XX.XXX).')
    	}
			else
			{
        $.get(
        	
            "/ajax/"+(path?path:'catalog')+"/item/" + realId + "/",
            function(html) {
            		var nf = 0;
            	  if(parseInt(realId) != realId)  {
            	  	var re = / id="item_(\d+)"/;
									var res = re.exec(html)
            	  	if(res && res.length>1) realId = res[1]
            	  	else nf = 1
            	  }
            	  if ($("#item_" + realId).length) { showHdItem(realId);  }
            	  else if(issearch && nf) alert('Ничего не найдено по указанному артикулу.')
            	  else {
            	  	
                	$("#hdndivs").append(html);
                	$("#item_" + realId)
//                    .css({ "position": "absolute", "left" : $(".l-section").offset().left, "top" : parseInt($(".l-section").offset().top) + 40, "z-index": zIndex(".b-gallery") })
                    .css({ "position": "absolute", "left" : "532px", "top" : "34px", "z-index": zIndex(".b-gallery") })
                    .show("normal")
                    .draggable({
                        cursor: 'move',
                        stack: ".b-gallery",
                        stop: function(event, ui) {
                            var id = ui.helper.attr("id").substring(5);
                            dialogs[id].left = ui.helper.offset().left;
                            dialogs[id].top = ui.helper.offset().top;
                            saveDialogs();
                        }
                    })
                
                	dialogs[realId] = {
                    "left": $("#item_" + realId).offset().left,
                    "top": $("#item_" + realId).offset().top,
                    "full": false
                	};
                	saveDialogs();
                }
            }
        );
      } 
    }
		return false;  
}


function closeItemInfo(obj, id) {
    $(obj).parents(".b-gallery").find(".info, .thumbs").hide();
    $(obj).parents(".b-gallery").find("IMG.full").remove();
    $(obj).parents(".b-gallery").find(".ico-ctrl").removeClass("ico-ctrl-active");
    
    
    $(obj).parents(".b-gallery").draggable("destroy").hide("normal", function() {
        if (id) {
        	$("#item_"+id).css("left", 0)
        	$("#delail_td_"+id).css("marginLeft", 0)
            dialogs[id] = null;
            saveDialogs();
        }
    });
		if($('#delail_td_'+id).css("marginLeft") && $('#delail_td_'+id).css("marginLeft").indexOf("0") != "0") {
			$('#leftm_'+id).hide()
			var w = parseInt($("#item_"+id).css('width').replace('px','')) - 200
			$('#delail_td_'+id).css({marginLeft:0})
			$("#item_"+id).css({width:460})
			//.css("z-index")>0) $('#leftm_'+id).css("z-index", -$('#leftm_'+id).css("z-index"))
		}
    return false;
}

function itemDetail(obj, id, url) {
    //url = null;
    var dl = "+=200px"
    var dm = "-=200px"
    var $dialog = $(obj).parents(".b-gallery");
    if ($dialog.find(".info").is(":visible") || $dialog.find(".full").length) {
        $dialog.find(".info, .thumbs").hide();
        $dialog.find("IMG.full").remove();
        dialogs[id].full = false;
    }
    else {
        $dialog.find(".info, .thumbs").show();
				var ftd = $('#full_'+id)
        if (url) $("<img />")
            .attr({ "src": url, "class": "full" })
            .css(ftd.attr('id') == 'full_'+id ? {} : { "position": "absolute", "top": 24, "left": 21 })
            .appendTo(ftd.attr('id') == 'full_'+id ? ftd : $dialog);
	   //.appendTo($dialog);
        dialogs[id].full = true;
    }
    
    if($('#leftm_'+id).length>0) 
    {
    			if(dm.indexOf('-')>-1) $('#leftm_'+id).show()
    		  if($('#leftm_'+id).css("z-index")>0) $('#leftm_'+id).css("z-index", -$('#leftm_'+id).css("z-index"))
        	if($('#delail_td_'+id).css("marginLeft").indexOf("0") != 0) { dl = "-=200px";  dm = "+=200px"; }
        	$('#delail_td_'+id).animate({"marginLeft": dl}, "slow");
        	$("#item_"+id).animate({"left": dm, "width": dl}, "slow", null, function(){
        			if(dl!="-=200px"&&$('#leftm_'+id).css("z-index")<0)$('#leftm_'+id).css("z-index", -$('#leftm_'+id).css("z-index"))
        			if(dm.indexOf('-')<0) $('#leftm_'+id).hide()
        	});
        	
        	
     }
		saveDialogs();
		
    return false;
}

var currentScroll = 0;
function scrollPics(dir) {
    if (currentScroll - dir >= 0 && currentScroll - dir <= cols) {
        $("#pictures .scroller").animate({
            "left": parseInt($("#pictures .scroller").css("left")) + dir * parseInt($("#l-section").width()) + "px"
        }, 700);
        currentScroll = currentScroll - dir;

        if (currentScroll > 0)         { $(".larr").show(); } else { $(".larr").hide(); }
        if (currentScroll <= cols - 1) { $(".rarr").show(); } else { $(".rarr").hide(); }
    }

    return false;
}

function saveDialogs() {
    var result = "";
    $(".b-gallery:visible").each(function(i, item) {
        var id = $(item).attr("id").substring(5);
        if (dialogs[id])
            result = result + id + "_" + dialogs[id].top + "_" + dialogs[id].left + "_" + dialogs[id].full + "__";
    });
    setCookie("dialogs", result, 1);
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + (expiredays ? "" : ";expires=" + exdate.toUTCString()) + ";path=/";
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function showCart(obj, id)
{
	 $("#crt"+id).is(":visible")?$("#crt"+id).hide():$("#crt"+id).show();
}
function addtocart(id)
{
	var p = $("#price"+id).val()
	var q = parseInt($("#fld_cnt"+id).val())
	if(q > 0 && p > 0) {
		 
	$.get("/ajax/addtocart/"+id+"/"+q+"/", function(html) { 
		if(html == '1') {
		 	$("#cartn").hide();
		 	$("#carta").html( parseFloat($("#carta").html()) + q*p )
		 	$("#cartg").show();		
		 	$("#crt"+id).hide();
		 	$("#crta"+id).removeClass("ico-ctrl-active");
		}
	});
		 		 
		 //var arr = new Array()
		 //var ucr = getCookie('ucr')
		 //if(ucr && ucr != '') arr = ucr.split(/;/)
		 //var fnd = 0;
		 //for(var i=0; i<arr.length; i++) {
		 //	var v = arr[i].split(/=/)
		 //	if(v[0] == id) { arr[i] = v[0] + '=' + (parseInt(v[1])+q); fnd = 1; }
		 //}
		 //if(!fnd) arr[arr.length] = id+'='+q
		 //setCookie('ucr', arr.join(';'), 1)
		 
		 
	}
}

function artsearch()
{
	
	itemInfo('catalog', $("#wrd").val(), 1)
	return false
}
function hssearch(hs)
{
	if(!hs) { $("#searcha1").show(); $("#searcha2").show(); }
	else { $("#searcha1").hide(); $("#searcha2").hide(); }
}

