function pswFocus() {
  if (this.value=="Пароль") {
    if ($.browser.msie || $.browser.safari || $.browser.opera) {
      $("#regform input[name='password']").replaceWith("<input type='password' name='password' value=''/>");
      $("#regform input[name='password']")[0].value='';
      $("#regform input[name='password']").focus();
      $("#regform input[name='password']").bind("focus",pswFocus).bind("blur",pswBlur);
    }
    else {
      this.value="";
      this.type = "password";
    }    
  }
}

function pswBlur() {
    if (this.value=="") {
      if ($.browser.msie || $.browser.safari || $.browser.opera) {
        $("#regform input[name='password']").replaceWith("<input type='text' name='password' value='Пароль'/>");
        $("#regform input[name='password']")[0].value='Пароль';
        $("#regform input[name='password']").bind("focus",pswFocus).bind("blur",pswBlur);
      } else {
        this.value="Пароль";
        this.type = "text";
      }    
     }
  }

var curImgID = 0;
var ival = null;
var itval = null;

function getPositionLite(el)
{
	var x = 0, y = 0;
	while(el) {
		x += el.offsetLeft || 0;
		y += el.offsetTop || 0;
		el = el.offsetParent;
	}
	return { x:x, y:y };
}

function getSizeLite(el){
		return {
			wb:el.offsetWidth||0,
			hb:el.offsetHeight||0
		};
}

function moveToImage(index) {
  if (index<0 || index>$("#about .gallery .photos a").length)
    return;
  var new_img = $("#about .gallery .photos a:eq("+index+")")[0];
  if (!new_img)
    return;
	var fw = parseInt($(new_img).attr("rw"));
	var fh = parseInt($(new_img).attr("rh"));
  var src = $(new_img).attr("href");
  $("#about .gallery .pic img").attr("img_index",index);
  	$("#about .gallery .loading").hide();
  	var ival = setInterval(function() { 
  			$("#about .gallery .loading").show();
  			$("#about .gallery .pic").hide();
  			clearInterval(ival); 
  			ival = null; 
  		},100);

  	$.preload([ src ], {
  		onFinish: function(data) {
  			clearInterval(ival);
  			ival = null;
  			$("#about .gallery .loading").hide();
  			$("#about .gallery .pic").show();
        $("#about .gallery .pic img").attr({ "src":data.image }).fadeIn(300);
  		}
  	})
}


function setImageHeight(w,h,txt) {
	if (w>0 && h>0) {
	//	var fh = 345*parseInt(h)/parseInt(w);
		var fh = parseInt(h)+(txt!="" ? 50 : 0);
		var fw = parseInt(w);
		$("#fullimage .loading").css({
			height:Math.round(fh),
			width:Math.round(fw)-1
		});
    $("#close_fullimage").css({"margin-top":-fh/2-21})
		$("#fullimage .loading img").css({ "margin-top":Math.round((fh-1))/2-20 });
		$("#fullimage").css({ height:Math.round(fh)-1,"margin-top":-fh/2 }).animate({ 
			width: fw,
			marginLeft:-fw/2
		}, 500 );
	}
}

function makeGalleryImage(container,j) {
	j.each(function() {
	 var link = this;
		$(link).click(function() {
			$("#overlay").css("opacity",0).show().fadeTo(500,0.9);
			//var row_index = $(".row",container).index($(this).parent().parent()[0]);
			var img_index = $("a",container).index(link);
			$("#fullimage > img.full").attr({ gallery_id:$(container).attr("gallery_id"),"image_index":img_index });
			moveToImage2(0);
			$("#fullimage").show();
			return false;        
		});
	});
}

function moveToImage2(direction) {
	var full_image  = $("#fullimage > img.full")[0];
	var container = $(".items")[0];
	if (!container)
	 return;
	var img_index = parseInt($(full_image).attr("image_index"))+direction;
//	var row_index = parseInt($(full_image).attr("row_index"));
	var newimg = $("a:eq("+img_index+") img",container)[0];
//	alert(newimg);
	if (!newimg) {
	 newimg = $("a:eq("+img_index+") div",container)[0];
  }
	if (!newimg)
	 return;
	var fw = parseInt($(newimg).parent().attr("rw"));
	var fh = parseInt($(newimg).parent().attr("rh"));
	if (fh>520)
	 fh=520;
	$("#close_fullimage").show().animate({ marginLeft:fw/2-38},500);
/*	var img_id = $(newimg).attr("image_id");
	if (img_id)
		$("#fullimage").attr({ "image_id":img_id });*/
  var txt = $(newimg).parent().attr("title");
	setImageHeight(fw,fh,txt);

	$("#fullimage .loading").hide();
	$("#fullimage .loading img").hide();
	var ival = setInterval(function() { 
			$("#fullimage .loading").show();
			$("#fullimage .loading img").show();
			$(full_image).hide();
			clearInterval(ival); 
			ival = null; 
		},100);
	$.preload([ $(newimg).parent().attr("href") ], {
		onFinish: function(data) {
			clearInterval(ival);
			ival = null;
			$("#fullimage > .loading").hide(); 
			$(full_image).attr({ "image_index":img_index,"src":data.image }).fadeIn(300);
			$("#fullimagedesc").text(txt); 
			$("#fullimagedesc").show();
		}
	})
	return false;
}

function closeGallery() {
	$("#fullimage .loading").stop();
	$("#fullimage").stop().css({ width:2,height:150,"margin-left":-1,"margin-top":-1 }).hide();
	$("#fullimage > img.full").hide();
	$("#next_fullimage").stop().hide();
	$("#prev_fullimage").stop().hide();
	$("#close_fullimage").stop().css({ "margin-left":0,"margin-top":0 }).hide();
	$("#fullimage").stop();
	$("#fullimagedesc").hide();
	$("#invite-form").hide();
	$("#basket-form").hide();
	$("#overlay").fadeOut(500);
	return false;
};

function prolog() {
	if ($(".items")[0]) {
	  $(".items tr").hover(function() {
	   if ($(this).is(".total-basket-row"))
	     return;
	   $(this).addClass("jsover");
    },function() {
	   if ($(this).is(".total-basket-row"))
	     return;
	   $(this).removeClass("jsover");
    }).click(function() {
      $("a.thumb",this).trigger("click");      
    });
		makeGalleryImage($(".items")[0],$(".items a.thumb"));
		$("#close_fullimage").click(closeGallery);
	}
}

function moveToItemPic(container,direction,index) {
  var cur_img = $(container+" .item_pics .selected").removeClass("selected")[0];
  if (!cur_img)
    cur_img = $(container+" .item_pics img:first")[0];
  if (!cur_img)
    return false;    
  switch(direction) {
    case -1:
      if ($(cur_img).prev()[0])
        cur_img = $(cur_img).prev()[0];
      else
        cur_img = $(container+" .item_pics img:last")[0];
      break;
    case +1:
      if ($(cur_img).next()[0])
        cur_img = $(cur_img).next()[0];
      else
        cur_img = $(container+" .item_pics img:first")[0];
      break;
    case 0:
      cur_img = $(container+" .item_pics img:eq("+index+")")[0];
  }
  $(cur_img).addClass("selected");
  var img_index = $(container+" .item_pics img").index(cur_img)+1;
  var fullimage = $(container+" .pics .pic")[0];
  var fullimage2 = $(container+" .pics .pic2")[0];
	$(container+" .loading").hide();
	$(container+" .loading img").hide();
  	var isLoading = false;
	var itval = setInterval(function() { 
			$(container+" .loading").show();
			$(container+" .loading img").show();
			$(fullimage).hide();
			$(fullimage2).hide();
			clearInterval(itval);
    	var isLoading = true;
       
			itval = null; 
		},100);
	$.preload([ $(cur_img).attr("src") ], {
		onFinish: function(data) {
			clearInterval(itval);
			itval = null;
			$(container+" .loading").hide(); 
      var imgel = ($(container+" .pics  img.first").is(".active") ? $(container+" .pics img.second")[0] : $(container+" .pics img.first")[0]);
        $(container+" .pic")[0].customAnimate = true;
        $(container+" .pic")[0].op = 1;
        $(container+" .pic")[0].params = { isLoading:isLoading,oldElem:$(container+" .pics .active")[0],newElem:imgel };
        $(imgel).attr({ "src":data.image }).show();
  			$(container+" .pic").stop().animate({ op:0 },{
          duration: 1000,complete:function() {
            $(container+" .pics .active").removeClass("active").hide();
            $(imgel).addClass("active");
            $(container+" .pic")[0].params = null;
          } });          
      $(container+" .pager .cur_pic").text(img_index);
		}
	})

   
}


function inviteFormSubmit(e) {
    var pass = jQuery("#invite-password")[0].value;
    jQuery.post("/invite/",{ invite_password:pass },function(res) {
      if (res=="OK") {
        location.href='/panic-room/';
      } else {
        alert("Вы неправильно ввели пароль.");
        jQuery("#invite-password").focus();
      }
    });
    return false;    
}

function pswInviteFocus() {
  if (this.value=="Кодовое слово") {
    if (jQuery.browser.msie || jQuery.browser.safari || jQuery.browser.opera) {
      jQuery("#invite-password").unbind("focus").unbind("blur").replaceWith("<input type='password' id='invite-password' value='' name='invite-password'/>");
      jQuery("#invite-password")[0].value='';
      jQuery("#invite-password").focus();
      jQuery("#invite-password").bind("focus",pswInviteFocus).bind("blur",pswInviteBlur);
    }
    else {
      this.value="";
      this.type = "password";
    }    
  }
}

function pswInviteBlur() {
    if (this.value=="") {
      if (jQuery.browser.msie || jQuery.browser.safari || jQuery.browser.opera) {
        jQuery("#invite-password").replaceWith("<input type='text' name='invite-password' id='invite-password' value='Кодовое слово'/>");
        jQuery("#invite-password")[0].value='Кодовое слово';
        jQuery("#invite-password").bind("focus",pswInviteFocus).bind("blur",pswInviteBlur);
      } else {
        this.value="Кодовое слово";
        this.type = "text";
      }    
     }
  }


function bindInviteForm() {
		$("#invite-form #close-form").click(closeGallery);
    $("#invite-password").bind("focus",pswInviteFocus).bind("blur",pswInviteBlur);
    $("#invite-form form").submit(inviteFormSubmit);
    $("#post-invite").click(inviteFormSubmit);
}

function basketChanged(result) {
  $("#basket_count").text(result.quantity);
  $(".total-basket-row .basket-total").text(result.total);
  $(".total-basket-row .basket-nds").text(result.nds);
  $(".total-basket-row .basket-totalnds").html("<b>"+result.totalnds+"</b>");
}
function changeQuantity(elem,type) {
  var inp = $("input.quantity",$(elem).parent()[0])[0]; 
  var item_id = $(inp).attr("item_id");
  var q = parseInt(inp.value);
  if (isNaN(q)) {
    inp.value='0';
    return;
  }
  var err = "Произошла ошибка во время изменения кол-ва товара в корзине";
  $.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) {
      alert(err);   
  }});
  switch (type) {
    case 'up':
      q++;
      break;
    case 'down':
      if (q<=0)
        return;
      q--;
      break;
  }
  $.getJSON("/ajax/basket/change/",{ item_id:item_id,quantity:q,ms:new Date().getTime() },function(result) {
    if (!result || result.error) {
      var error = result.error || err;
      alert(error);
      return;
    }
    if (result) {
       inp.value = q;
      $(".basket-item-price",$(elem).parent().parent().parent()[0]).text(result.item_price);        
       basketChanged(result);        
    }
  },function() {
    alert(err);
  });
}

function bindBasketFunctions() {
  $(".basket-price .quantity .arrow-up").click(function() {
    changeQuantity(this,'up');
    return false;
  });
  $(".basket-price .quantity .arrow-down").click(function() {
    changeQuantity(this,'down');
    return false;
  });
  $(".basket-price .quantity input.quantity").bind("change",function() {
    changeQuantity(this);
    return false;
  });
}


$(document).ready(function() {
    bindBasketFunctions();
		$("#overlay").click(closeGallery);
		
    var $_fx_step_default = $.fx.step._default;
    $.fx.step._default = function (fx) {
      if (!fx.elem.customAnimate) return $_fx_step_default(fx);
        if (fx.prop=="op" && fx.elem.params) {
          if ($(fx.elem.params.oldElem).css("opacity")>fx.now && !fx.elem.params.isLoading)
            $(fx.elem.params.oldElem).css("opacity",fx.now);
          $(fx.elem.params.newElem).css("opacity",1-fx.now);
        }
        fx.elem.updated = true;
    };  		

  prolog();
  bindInviteForm();
  $("#contacts input[name='contact_name']").bind("focus",function() {
    if (this.value=="Имя") {
      this.value="";    
    }
  }).bind("blur",function() {
    if (this.value=="") {
      this.value="Имя";    
    }
  });
  $("#contacts input[name='contact_email']").bind("focus",function() {
    if (this.value=="E-mail") {
      this.value="";    
    }
  }).bind("blur",function() {
    if (this.value=="") {
      this.value="E-mail";    
    }
  });

/*  $("#contacts input[name='contact_name']")
      .bind("focus",function() { if (this.value=="Имя") this.value=""; })
      .bind("blur",function() { if (!this.value) this.value=="Имя"; });*/
  $("#contacts .send-button").click(function() {
    var cname = $("#contacts input[name='contact_name']")[0].value; 
    var cemail = $("#contacts input[name='contact_email']")[0].value; 
    var ctext = $("#contacts textarea[name='contact_body']")[0].value;
    var errors = "";
    if (!cname)
       errors += "Введите имя\r\n";
    if (!cemail)
       errors += "Введите email\r\n";
    if (!ctext)
       errors += "Введите текст сообщения\r\n";
    if (errors) {
      alert(errors);
      return false;
    }
    return true;
  });
  $("#about .gallery .nav .prev").click(function() {
    var img_index = parseInt($("#about .gallery .pic img").attr("img_index")); 
    moveToImage(img_index-1);
  	return false;
  });
  $("#about .gallery .nav .next").click(function() {
    var img_index = parseInt($("#about .gallery .pic img").attr("img_index")); 
    moveToImage(img_index+1);
  	return false;
  });
  if (jQuery("#design-items .gallery .photos")[0]) {
    jQuery("#design-items .gallery .photos")[0].scrollLeft = 0;
  }
  $("#design-items .gallery .nav .prev").click(function() {
    var el = $("#design-items .gallery .photos")[0]; 
    var pos = el.scrollLeft-el.offsetWidth;
    $(el).animate({ "scrollLeft":pos },800,function() {
/*      $(el).parent()
        .css("border-left",el.scrollLeft>2 ? "1px solid #a9a9a9" : "none")
        .css("margin-left",el.scrollLeft>2 ? 0 : 1);*/
      $(el).parent()
        .css("border-right",el.scrollLeft+el.offsetWidth>=el.scrollWidth ? "none" : "1px solid #a9a9a9")
        .css("margin-right",el.scrollLeft+el.offsetWidth>=el.scrollWidth ? 1 : 0);
    });
  	return false;
  });
  $("#design-items .gallery .nav .next").click(function() {
    var el = $("#design-items .gallery .photos")[0]; 
    var pos = el.scrollLeft+el.offsetWidth;
    jQuery("#design-items .gallery .photos").animate({ "scrollLeft":pos },800,function() {
/*      $(el).parent()
        .css("border-left",el.scrollLeft>2 ? "1px solid #a9a9a9" : "none")
        .css("margin-left",el.scrollLeft>2 ? 0 : 1);*/
      $(el).parent()
        .css("border-right",el.scrollLeft+el.offsetWidth>=el.scrollWidth ? "none" : "1px solid #a9a9a9")
        .css("margin-right",el.scrollLeft+el.offsetWidth>=el.scrollWidth ? 1 : 0);
                
    });
  	return false;
  });
  if ($.browser.msie && $.browser.version<7) {
    $("#design-items .photos a").hover(function() {
      $(".border",this).show();
    },function() {
      $(".border",this).hide();
    });
    $("#arch-items .photos a").hover(function() {
      $(".border",this).show();
    },function() {
      $(".border",this).hide();
    });
  }
  $("#design-item .pics .pager .prev").click(function() {
    moveToItemPic("#design-item",-1);
    return false;
  });  
  $("#design-item .pics .pic,#design-item .pics .pic2,#design-item .pics .pager .next").click(function() {
    moveToItemPic("#design-item",+1);
    return false;
  });
  $("#arch-item .pager .num").click(function() {
    moveToItemPic("#arch-item",0,$("#arch-item .pager .num").index(this));
    $("#arch-item .pager .selected").removeClass("selected");
    $(this).addClass("selected");
    return false;
  });
  $("#arch-item .pics").css("cursor","pointer").click(function() {
    moveToItemPic("#arch-item",+1);
    $("#arch-item .pager .selected").removeClass("selected").next().addClass("selected");
    if (!$("#arch-item .pager .selected")[0])
      $("#arch-item .pager a:first").addClass("selected"); 
  });  
  $("#regform input[name='login']").bind("focus",function() {
    if (this.value=="Логин") {
      this.value="";    
    }
  }).bind("blur",function() {
    if (this.value=="") {
      this.value="Логин";    
    }
  });
  $("#regform input[name='password']").bind("focus",pswFocus).bind("blur",pswBlur);
  $("#price .quantity").click(function(e) {
    e.stopPropagation();
    return false;
  });
  $("#panicimage .panic-items a").click(function() {
    return false;
  }).hover(function() {
     var msg_name = this.className;
     $("#panicroom .messages ."+msg_name).stop(true,true).fadeIn(400);    
  },function() {
     var msg_name = this.className;
     $("#panicroom .messages ."+msg_name).stop(true,true).fadeOut(400);    
  });
  
	jQuery(".need-invite").click(function() {
	 jQuery("#invite-form").show();
	 jQuery("#overlay").css("opacity",0).show().fadeTo(500,0.9);
	 return false;
  });
  $("#basket-form #close-form").click(closeGallery);
  $("#add-to-basket").click(function() {
    var ids = [];
    var qs = []
    $("#price .items input.quantity").each(function() {
      var nm = parseInt($(this).attr("name").replace("item_quantity_",""));
      var q = parseInt(this.value);
      if (nm>0 && q>0) {
        ids.push(nm);
        qs.push(q);
      } 
    });

    $.post("/ajax/basket/add/",{ "ii[]":ids,"iq[]":qs },function(res) {
      if (res && !res.error && res.total && res.quantity>0) {
        $("#basket-form").show();
    	  $("#overlay").css("opacity",0).show().fadeTo(500,0.9);
  	  } else {
  	    alert("Произошла ошибка во время добавления товаров в корзину"+(res && res.error ? ": "+res.error : ""));  	   
      }
    },'json');
    return false;
  });       
});
			
