
//Устнавливаем что-нибуть в куки
document.cookie='__ce=1';

//Ненавязчиво вставляем sh_ph
$(function() {
   $('a[shph]').click(function() {
       eval('sh_ph('+$(this).attr('shph')+')');
       return false;
   });
});






//GallView

function sh_ph(src, desc, caption, one_image, comm, cp)
{
	if (typeof src == 'object') {
		cp = src[5];
		comm = src[4];
		one_image = src[3];
		caption = src[2];
		desc = src[1];
		src = src[0];
	}
	
	
    var cit = $("#thumbs-container");
    var it = $("#IimgThumbs").empty();
    if (!one_image) {
		
		cit.show();
        $('#'+src).clone().show().appendTo(it);
        $(".IimgItem", it)
        .click(function() {
        	var a = eval($(this).attr('spattr'));
            setToImgContainer(a[0], $(this), a[1], a[2], a[4], a[5]);
        });
		
		
		
		//Настраиваем скролл если нужно
	    (function() {
	        var t = $("#IimgThumbs");
	        var p = t.parent();
	      
            var lar = $('#thumbs-container-left').hide();
            var rar = $('#thumbs-container-right').hide();		
		  
		    var checkar = function(pos) {
		        if (pos < 0 || isNaN(pos)) return;
		        if (t.width() < p.width()) {
		            lar.hide(); rar.hide(); return;
		        }
		        
		        if (Math.abs(pos-1.0) < 1e-2) {
		            lar.show(); rar.hide();
		        }
		        else if (Math.abs(pos) < 1e-2) {
		            lar.hide(); rar.show();
		        }
		        else {
		            lar.show(); rar.show();
		        }
		    }		  
		  
		  
		  
		  var np = 0;  //Новое положение скрола)

      				setInterval(function() {
                 var o = t.width()-p.width();
                 np = Math.min(Math.max(0, np), o+7);
                 
                 var q = -parseInt(t.css("left"));
                 var k = (np-q) / 10;
                 
                 var q = Math.min(Math.max(0, q+k), o);
                 t.css("left", -q);
                 checkar(q/o);
              }, 4);
		  
	        //Запускаем таймер, который проверяет нужен ли скрол
	        var i = setInterval(function() {
				checkar(parseInt(t.css("left")) / (p.width()-t.width()));
	
	
	            //Инициализация скрола
	            if (t.width() > p.width()) {
	                p.wheel(function(e, delta) {
	                    if (t.width() <= p.width()) return;
	                    
	                    var dp = -delta*0.15;            
	                    if ($.browser.opera) dp = -dp;
                      
                      np+=dp*500; 
						
	                    return false;
	                });         
	                
	                clearInterval(i);
	            }
	            
	        },500);
	        
			var arhclick = function(dp) {
                np+=dp;
			}
			
			//Теперь уснавливаем листание влево, вправо
			lar.click(function() {
                arhclick(-200);
			});
            rar.click(function() {
                arhclick(200);
            });			        
	
	    })();
			
		
    }
	else {
		cit.hide();
	}
    
    __lightResize();

    $("#lightPic")
        .css('opacity', 0.0)
        .show()
        .fadeTo(300, 0.6);

    $("#blockContainer").css({'visibility': 'hidden'}).show();
        __blockGenPos();
    $("#blockContainer").css({'visibility': 'visible'});
    
    
    $(window).resize(__lightResize);
  
  
    if (one_image) {
        setToImgContainer(src, null, desc, caption, comm, cp);   
    }
    else {
        var t = $(".IimgItem[@refid="+desc+"]:eq(0)", it);
        if (t.length) {
        	var a = eval(t.attr('spattr'));
            setToImgContainer(a[0], t, a[1], a[2], a[4], a[5]);
        }
    }
}

function dsh_close()
{
    $(window).unbind('resize', __lightResize);

    $("#blockContainer").hide();
    $("#lightPic").fadeTo(300, 0.0, function() {
        $("#lightPic").hide();     
    });
    
    $("#IimgContainer").css({width:'600px',height:'250px'});
    $('#blockTable').css("marginTop", 0);
    $("#IimgContainer, #descValue").empty();
    
    var hdr = $('#IimgHeader');
	$('.img-header-caption', hdr).text('');
	$('.img-header-comm-count', hdr).html('');
	shCurrentImage = ''
}



function __lightResize()
{

    var c = $('#lightPic, #blockContainer').hide();
    var w = $(document).width() - ($.browser.msie && $.browser.version < 7 ? 22 : 0);
    var h = $(document).height();
    c.css({width: w, height: h}).show();
}


function __blockGenPos()
{
    var b = $('#blockTable');
    var m = ($(window).height()  - b.height()) / 2 + $(document).scrollTop();      
    b.css("marginTop", m > 0 ? m : 0);
    
}

var shCurrentImage = '';
function setToImgContainer(image, node, desc, caption, comm, cp) {
	if (shCurrentImage == image) return;
	
	shCurrentImage = image;
	
	var hdr = $('#IimgHeader');
	$('.img-comments-back, .img-comments', hdr).hide();
	
	
    var t = $("#IimgContainer");
    var ldr = $("#IimgLoader").clone();
    //var f = 0;
    t.fadeOut(400, function() {
        
        
    	$('.img-header-caption', hdr).text('');
    	$('.img-header-comm-count', hdr).html('');        	
        
        t.empty().show();
        ldr.appendTo(t).hide()
        	.css('margin-top', (t.height()-ldr.height())/2)
        	.fadeIn(200, function() { 

            var h = $("#IimgHelper");
            
            var img = new Image();
            img.onload = function() { 
                img.onload = null;
            	
            	var descbl = $('#descBlock').slideUp();
            	
                var i = $(this);
                ldr.fadeOut(200, function() {
                    ldr.remove();                 
                    
                    var b = $('#blockTable');

                    var m = parseInt(b.css("marginTop")) - (Math.max(250,i.height())-t.height()) / 2;
                    if ($.browser.msie) m -= 1;
                    
                    b.animate({
                        "marginTop": m > 0 ? m : 0
                    }, 300, 'swing');

                    $("#descBlock").width(Math.max(Math.min(t.width(),i.width()), 600));
                
                    t.animate({
                        width: Math.max(300,i.width()) + ($.browser.msie ? 2 : 0),
                        height: Math.max(250, i.height()) + ($.browser.msie ? 2 : 0)
                    }, 300, 'swing', function() {
                    	
                    	
                        if (node) {
                            var os = node.offset();
                            var od = t.offset();
                        }
                        
                        $("img", h).hide().appendTo(t)
                        	.css('margin-top', (t.height()-i.height())/2)
                        	.fadeIn(300);
                        h.hide();
                        $("#descBlock").width(Math.max(t.width(), 600));
                        
                        
                        if (desc) { 
                            var d = $('#descValue').empty();
                            $("#" + desc).clone().show().appendTo(d);
                            
                            var mt = parseInt(b.css('margin-top'));
                            mt -= descbl.height()/2;
                            //b.animate({
                            //    "marginTop": mt > 0 ? mt : 0
                            //}, 300, 'swing');  

                            descbl.slideDown(300, function() {

                                if (caption) {
                                	$('.img-header-caption', hdr).text(caption);
                                }
                                
                                if (cp) {
                                	var uf = function() {
	                                	$('.img-header-comm-count', hdr).unbind('click').html('Комментарии &darr;')
	                                		.click(function() {
	                                			
	                                			var tk = $(this);
	                                			var nh = descbl.height() + t.height();
	                                			
	                                			$('.img-comments', hdr).html('');
	                                			$('.img-comments-back', hdr).html('<img src="/public/ipopup/preloader2.gif" style="margin-top:'+(nh-32)/2+'px;" />');
	                                			
	                                			if ($.browser.msie && $.browser.version < 7) {
		                                			$('.img-comments-back, .img-comments', hdr)
	                                				.css('display', 'block')
	                                				.height(nh);
	                                			}
	                                			else {
		                                			$('.img-comments-back, .img-comments', hdr)
		                                				.css('opacity', 0.0)
		                                				.css('display', 'block')
		                                				.height(nh);
		                                			
		                                			$('.img-comments-back', hdr).fadeTo(300,0.8);
		                                			$('.img-comments', hdr).fadeTo(300, 1.0);
	                                			}	
	                                			
	                                			var af = function() {
	                                				var ci = shCurrentImage;
	                                				
	                                				$.ajax({
	                                                    url: "/.comm",
	                                                    data: cp,
	                                                    success: function(data) {
	                                                        if (ci == shCurrentImage) {
	                                                        	$('.img-comments-back', hdr).html('');
	                                                        	$('.img-comments', hdr).html(data);
	                                                        }   
	                                                    },
	                                                    error: function() {
	                                                        if (data.errors) {
	                                                            setTimeout(function() {
	                                                            	if (ci == shCurrentImage) af();
	                                                            }, 1);
	                                                        }
	                                                    }
	                                                });
	                                			};
	                                			af();
	                                				                                			
	                                			
	                                			
	                                			tk.unbind('click');
	                                			tk.html('Закрыть комментарии').click(function () {
	                                				$('.img-comments-back, .img-comments', hdr).hide();
	                                				
	                                				uf();
	                                				return false;
	                                			});
	
	                                			return false;
	                                		});
                                	}
                                	uf();
                                		
                                }
                            	
                            	
                            	
                            });
                        }
                        
                    });
                
                });
                
            };
            img.src = image;
            h.show().empty().append( $(img) );
            
        });
    });
    
}
    














/*
//Делаем менюху
$(function() {
                 
  $('#main-menu .menu-sub-block').each(function() {
      var t = $(this);
      var p = t.parent();
      //var o = p.offset();
      //var fo = $('#main-frame').offset();
      t.css({
          left: -30,
          top: p.height()-5
      });
      
      var no = 0,
          co = 0,
          st = 0.13;
      
      setInterval(function() {
          var d = no-co;
          if (Math.abs(d) >= 0.1) {
              co += d/Math.abs(d)*st;
              t.css({opacity: Math.max(0,Math.min(1,co)), display: 'block'});
          }
          if (co > 0.9 && no==1) { co=1;
              t.css({opacity: 1});
          }
          if (co < 0.1 && no==0) { co=0;
              t.css({display: 'none'});
          }    
      }, 60);
      
      
      
      
      p.hover(function() {
           no=1;
      }, function() {
           no=0;
      });
  });

});
*/
















$(function() {
	//Инициализация скрола
    (function() {
        var o = $("#scroll-handler");
        var of = o.parent();
        var t = $("#main-content-block");
        var p = $("#main-content");
		
        //Запускаем таймер, который проверяет нужен ли скрол
		var i = setInterval(function() {

            //Инициализация скрола
			if (t.height() > p.height()) {
			
                of.show();
		        p.wheel(function(e, delta) {
		            if (t.height() <= p.height()) return;
		            
		            var dp = -delta*0.15;            
		            if ($.browser.opera) dp = -dp;
		            
		        
		            var pos = (parseInt(o.css("top")) / (of.height()-o.height()))+dp;
		            pos = Math.min(Math.max(pos, 0.0), 1.0);
		
		            
		            //Устанавливаем
		            t.css("top", -(t.height() - p.height()) * pos);
		            o.css("top", (of.height() - o.height()) * pos);
		              
		            return false;
		        });			
			
		        o.draggable({
		            containment: "parent",
		            axis: "y",
		            drag: function() {
		                if (t.height() <= p.height()) return;    
		                
		                var pos = parseInt(o.css("top")) / (of.height()-o.height());
		                pos = Math.min(Math.max(pos, 0.0), 1.0);               
		                t.css("top", -(t.height() - p.height()) * pos);
		            }
		        });			
				
				
				clearInterval(i);
				
				//Обновление позиции скрола, относительно распалагаемого контента
				setInterval(function() {
	                var pos = (parseInt(t.css("top")) / (p.height()-t.height()));
	                pos = Math.min(Math.max(pos, 0.0), 1.0);
	   
	                //Устанавливаем
	                o.css("top", (of.height() - o.height()) * pos);					
				},1500);
			}
			
		},500);
				


    })();	
});

    
    



//Корзина
$(function() {

	
    Cart = new function() {
		var t = this;

        //Смотрим корзина
        var cart = [], 
            c = (document.cookie || '').split(';');
		for (var i = 0; i < c.length; i++) {
			var y = c[i].split('=');
			if ($.trim(y[0]) == 'cart') {
				ct = $.trim(y[1]).split('-');
				for (var j = 0; j < ct.length; j++) {
					if (!parseInt(ct[j])) continue;
					var k = 0;
					for (var o = 0; o < cart.length; o++) {
						if (parseInt(cart[o]) == parseInt(ct[j])) { k = 1; break; }
					}
					if (k) continue;
					cart.push(parseInt(ct[j]));
				}
				    
			}
		}
		
        if (cart.length > 0) {
			$('.cart-count').html(cart.length);
            $('#main-cart').show(); 
        }

        t.check = function(vis, id) {
			
			if (!id) id = tid;
			
			if (cart.length > 0) {
				$('.cart-count').html(cart.length);
				$('#main-cart').show();
			}
			else {
				$('#main-cart').hide();
			}
			
			var f = false;
            for (var i = 0; i < cart.length; i++) {
                if (parseInt(cart[i]) == parseInt(id)) {
					f =  true;
					break;
				}
            }
	        if (vis) {
				if (!f)
		            n.html('<a href="javascript:Cart.add();" class="add-to-cart">добавить в корзину</a>');
		        else
		            n.html('<a href="javascript:Cart.remove();" class="remove-from-cart">удалить из корзины</a>');
			}
			else {
                var y = $('#cart-item-'+id+'-ctrl');
				if (y) {
	                if (!f)
	                    y.html('<a href="javascript:Cart.add('+id+');" class="add-to-cart">добавить в корзину</a>');
	                else
	                    y.html('<a href="javascript:Cart.remove('+id+');" class="remove-from-cart">удалить из корзины</a>');
				}
				
				return f;
			}        
        }

        t.checks = function(ids) {
			for (var i = 0; i < ids.length; i++)
                t.check(0,ids[i]);
		}
		
		
		
		t.add = function(id) {
            var f = 0;
            if (!id) {
                id = tid; f = 1;
            }			
			cart.push(id);
			t.check(f,id);
			t.save();
		}
		
		t.save = function() {
			
            var date = new Date();
            date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
            var expires = '; expires=' + date.toUTCString(); 			
			var path = '; path=/';
            
			document.cookie = 'cart='+cart.join('-')+expires+path;
		}
		
		t.remove = function(id) {
			var f = 0;
			if (!id) {
				id = tid; f = 1;
			}
			var cn = [];
            for (var i = 0; i < cart.length; i++) {
                if (parseInt(cart[i]) == parseInt(id)) {
                    continue;
                }
				cn.push(cart[i]);
            }
			cart = cn;
			t.check(f,id);
			t.save();
		}
		
		
		t.clear = function() {
			document.cookie = 'cart=;';
			cart = [];
			t.check();
		}
		
		
        var n = $('.cart-ctrl');
        if (!n) return;
        
        var tid = n.eq(0).attr('jtId');
        if (!tid) return;
		
		t.check(1);		

	}
	
});




//Комменты

var CommList = (function() {
    
    return {

        
        send: function() {
            var p = {};
            $('input,textarea', '#comm-form').each(function() {
                var t = $(this);
                p[t.attr('name')] = (t.is(':hidden') || t.attr('j_ch')) ? $.trim(t.val()) : ''; 
            });
            
            if (!p.user_name) {
            	$('#send-error').text('Вы указали некорректное имя.').show();
                return;
            }            
            
            reg = /^[a-z0-9_\-\.]+\@[a-z0-9\-\.]+\.[a-z0-9]{2,5}$/i;
            if (p.user_mail && !p.user_mail.match(reg)) {
                $('#send-error').text('Вы указали некорректный e-mail.').show();
                return;                 
            }
            
            if (!p.user_comment) {
            	$('#send-error').text('Поле комментария заполнено некорректно.').show();
                return;
            }            
    
            $('#send-error').hide();
            
            
            p.save = 1; //Пусть будет так
            $.ajax({
                url: "/.comm",
                type: "POST",
                data: p,
                beforeSend: function() {
                    $('#send-ctrl').hide();
                    $('#send-wait').show();               
                }, 
                success: function(data) {                    
                    $('#comm-area').html(data);

                    $('#comm-form').hide();
                    $('#send-ctrl').hide();
                    $('#send-wait').hide();      
                },
                error: function() {
                    $('#send-ctrl').show();
                    $('#send-wait').hide();
                    alert('Во время передачи данных возникла ошибка. Пожалуйста попробуйте снова.');   
                }
            });             
            
            
        },
        
        init: function() {
            $('input,textarea', '#comm-form').focus(function() {
                var t = $(this);
                if (!t.attr('j_ch')) {
                    t.attr('j_first', t.val());
                    t.val(''); return;
                }
            }).blur(function() {
                var t = $(this);
                if (!$.trim(t.val())) {
                    t.attr('j_ch', '');
                    t.val(t.attr('j_first'));
                }
                else t.attr('j_ch', 1);
            });
            
            
        }
        
    }
})();





