function pswFocus() {
  if (this.value=="пароль") {
    if ($.browser.msie || $.browser.safari || $.browser.opera) {
      $("#login_form input[name='password']").replaceWith("<input type='password' name='password' value=''/>");
      $("#login_form input[name='password']")[0].value='';
      $("#login_form input[name='password']").focus();
      $("#login_form 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) {
        $("#login_form input[name='password']").replaceWith("<input type='text' name='password' value='пароль'/>");
        $("#login_form input[name='password']")[0].value='пароль';
        $("#login_form input[name='password']").bind("focus",pswFocus).bind("blur",pswBlur);
      } else {
        this.value="пароль";
        this.type = "text";
      }    
     }
  }
  


var curImgID = 0;

function setImageHeight(w,h) {
	if (w>0 && h>0) {
	//	var fh = 345*parseInt(h)/parseInt(w);
		var fh = parseInt(h);
		var fw = parseInt(w);
		$("#fullimage .loading").css({
		  left:45,
			height:Math.round(fh)+10,
			width:Math.round(fw)
		});
		$("#fullimage").css({ height:Math.round(fh)-1,"margin-top":Math.round(-fh/2-20) });
 		if ($.browser.safari)
  		  $("#fullimage").css({ 
  			marginLeft:Math.round(-fw/2),
  			width:Math.round(fw)
  		});
		else 
		  $("#fullimage").animate({ 
			marginLeft:Math.round(-fw/2),
			width:Math.round(fw)
		}, 500 );
    $("#close_fullimage").css({"margin-top":-fh/2-46})
		$("#fullimage .loading img").css({ "margin-top":Math.round((fh-1))/2-32 });
	}
}

function makeGalleryImage(container,j) {
	j.each(function() {
	 var link = this;
	  $(this).hover(function() {
	   $("span",this).addClass("jsover");
    },function() {
	   $("span",this).removeClass("jsover");
    });
		$(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 });
			moveToImage(0);
			$("#fullimage").show();
			return false;        
		});
	});
}

function moveToImage(direction) {
	var full_image  = $("#fullimage > img.full")[0];
  var gallery_id = $(full_image).attr("gallery_id");
	var container = $(".photos[gallery_id="+gallery_id+"]")[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).attr("rw"));
	var fh = parseInt($(newimg).attr("rh"));
	$("#gal_nav a").css("visibility","hidden");

	setImageHeight($(newimg).attr("rw"),$(newimg).attr("rh"));

	$("#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);
			$("#img_counter span").text((img_index+1)+"/"+$("a",container).length);
    	if (img_index<=0) {
    		$("#prev_fullimage").css("visibility","hidden");
    	}	else {
    		$("#prev_fullimage").css("visibility","visible");
    	}
     	if (img_index>=$("a",container).length-1) {
    		$("#next_fullimage").css("visibility","hidden");
    	} else {
    		$("#next_fullimage").css("visibility","visible");
    	}
		}
	})
	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().css("visibility","hidden");
	$("#prev_fullimage").stop().css("visibility","hidden");
	$("#close_fullimage").stop().css({ "margin-left":0,"margin-top":0 }).hide();
	$("#fullimage").stop();
	$("#overlay").fadeOut(500);
	return false;
};

function prolog() {
	$("#overlay").click(closeGallery);
	if ($(".photos")[0]) {
		$(".photos").each(function() {
			makeGalleryImage(this,$("a",this));
		});
		$("#prev_fullimage").click(function() { return moveToImage(-1); });
		$("#next_fullimage").click(function() { return moveToImage(+1); });
		$("#close_fullimage").click(closeGallery);
	}
}
var ival = 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 hideChildMenu() { 
  $("#menu .jsover").css("z-index",0).removeClass("jsover");
  $("#menu .submenu-items").hide();
  if (!ival)
    return;
  clearInterval(ival); 
  ival = null; 
}

function bindMenu() {
  var mainpos = getPositionLite($("#mainmenu")[0]).x;
  $("#menu .submenu").hover(function() {
    hideChildMenu();
    $(this).addClass("jsover");
    pos = getPositionLite(this);
    var parts = $("a:first",this).attr("id").split('-');
    if (!parts || parts.length!=2) return;
    var submenu_id = parts[1];
    var submenu = $("#submenu-"+submenu_id)[0];
    if (!submenu) return;
    var size = getSizeLite(submenu);
    var itemsize = getSizeLite(this);
    var wb = Math.max(itemsize.wb+30,size.wb);
    if (itemsize.wb+30>size.wb) {
      $(submenu).css("width",wb-20);
    } 
    $(".filler",this).css("width",wb);
    $(this).css("z-index",1);
    $(submenu).css({left:pos.x,top:pos.y}).show();
  },function() {
    if (!ival)
      ival = setInterval(hideChildMenu,400);
  });
  $("#menu .jsover.filler,#menu .submenu-items").hover(function() {
    if (!ival)
      return;
    clearInterval(ival);
    ival = null;
  },function() {
    if (!ival)
      ival = setInterval(hideChildMenu,400);
  });

}

var tval = null; 

function calcTime(offset) {
   // create Date object for current location
    d = new Date();
    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    // create new Date object for different city
    // using supplied offset
    nd = new Date(utc + (3600000*offset));
    // return time as a string
    var hours = nd.getHours();
    var minutes = nd.getMinutes();
    var secs = nd.getSeconds();
    if (hours<10)
      hours = "0"+hours.toString();
    if (minutes<10)
      minutes = "0"+minutes.toString();
    return hours+(secs%2 ? ":" : " ")+minutes;
}


function showTime() {
  var daylightSavings = parseInt($("#toptime input[name='is_daylight']")[0].value);
  $("#moscow-time").text(calcTime(3-daylightSavings));
  $("#paris-time").text(calcTime(1-daylightSavings));
}

function bindTimers() {
  tval = setInterval(showTime,1000);
}

function changeOrderPrice() {
  var quantity = parseInt($("#order select[name='quantity']")[0].value);
  var price = parseInt($("#order input[name='price']")[0].value);
  var delivery_price = parseInt($("#order span.delivery-price").text());
  var items_price = quantity*price;
  var total = items_price+delivery_price;
  $("#order .item-price").text(items_price+".-");
  $("#order .total-price").text(total+".-");
}

$(document).ready(function() {
	$.preloadCssImages();
	prolog();
	if ($.browser.msie && $.browser.version<7) {
	 $(".popular .content a").hover(function() {
	   $(".semiheader",this).show();
   },function() { 
	   $(".semiheader",this).hide();
   });
	}
	$("#news .item .inner").hover(function() {
	 $("a:first",this).addClass("linkover");
  },function() {
	 $("a:first",this).removeClass("linkover");
  }).click(function() {
    document.location.href = $("a:first",this).attr("href");
  });
	
  $("#search_form input[name='q']").bind("focus",function() {
    if (this.value=="поиск...") {
      this.value="";    
    }
  }).bind("blur",function() {
    if (this.value=="") {
      this.value="поиск...";    
    }
  });
  $("#login_form input[name='login']").bind("focus",function() {
    if (this.value=="логин") {
      this.value="";    
    }
  }).bind("blur",function() {
    if (this.value=="") {
      this.value="логин";    
    }
  });
  $("#login_form input[name='password']").bind("focus",pswFocus).bind("blur",pswBlur);


	$("#about_gallery").click(function() {
    $(".photos a:first").trigger('click');
    return false;
  });
  bindMenu();
  bindTimers();

  $(".inline-gallery #next").click(function() {
    var sc = parseInt($(".inline-gallery .gallery")[0].scrollLeft);
    $(".inline-gallery .gallery")[0].scrollLeft = sc+150;
    return false;
  }); 
  $(".inline-gallery #prev").click(function() {
    var sc = $(".inline-gallery .gallery")[0].scrollLeft;
    $(".inline-gallery .gallery")[0].scrollLeft = sc-150;
    return false;
  }); 
  $(".inline-gallery .gallery a").click(function() {
    $(".inline-gallery .selected").removeClass("selected");
    $(this).addClass("selected");
    var newimg = $("img:first",this);
  	var fw = parseInt($(newimg).attr("rw"));
  	var fh = parseInt($(newimg).attr("rh"));
  	$(".inline-gallery .loading").hide();
  	var ival = setInterval(function() { 
  			$(".inline-gallery .loading").show();
  			$(".inline-gallery #fullimage").hide();
  			clearInterval(ival); 
  			ival = null; 
  		},100);
  	var txt = $("p:first",this).text();
  	$.preload([ $(this).attr("href") ], {
  		onFinish: function(data) {
  			clearInterval(ival);
  			ival = null;
  			var max_height = parseInt($("#fullimage").css("height"));
  			var vmargin = Math.round((max_height-fh)/2);
  			var hmargin = Math.round((618-fw)/2);
  			$(".inline-gallery #fullimage #btn_order").css("width",fw).css("margin-top",vmargin).css("margin-left",hmargin);
  			$(".inline-gallery #fullimage img").css("margin-top",vmargin).attr({ "src":data.image }).fadeIn(300);
  			$(".inline-gallery .loading").hide();
        $(".inline-gallery #fullimage").show(); 
  		}
  	})
  	return false;
  });
  $("#form-close,#order-cancel").click(function() {
    $("#order-form").hide();
    return false;
  });
  $("#btn_order").click(function() {
    var img_src = $(".inline-gallery .gallery .selected img").attr("src");
		var photo_url = $(".inline-gallery .gallery .selected").attr("href");
    $("#order-form input[name='photo_url']")[0].value = photo_url;
    $("#order-form .desc .pic").attr("src",img_src);
    $("#order-form").show();
    $("#order-form .form input[name='username']").focus();
    return false;
  });
  $("#order-send").click(function() {
    var data = {
      quantity:$("#order-form select[name='quantity']")[0].value,
      page_id:$("#order-form input[name='page_id']")[0].value,
      item_id:$("#order-form input[name='item_id']")[0].value,
      photo_url:$("#order-form input[name='photo_url']")[0].value,
      username:$("#order-form input[name='username']")[0].value,
      email:$("#order-form input[name='email']")[0].value,
      address:$("#order-form input[name='address']")[0].value,
      userphone:$("#order-form input[name='userphone']")[0].value,
      comments:$("#order-form textarea[name='comments']")[0].value
    };
    if (!data.username) { alert("Введите имя"); $("#order-form input[name='username']").focus(); return false; };
    if (!data.email) { alert("Введите e-mail"); $("#order-form input[name='email']").focus(); return false; };
  	$.ajaxSetup({ async:false });
  	var result;
  	$.post("/order/", data,function(obj) {
  	 result = obj;
  	}, "json");
		if (result) {
		  alert("Ваш заказ принят.");
		  $("#form-close").trigger("click");
    } else {
		  alert("Произошла ошибка во время принятия заказа");
    }
    return false;
  });
  $("#vote").click(function() {
    var url = $("#vote-form").attr("action");
    if (!url)
      return false;
  	$.ajaxSetup({ async:false });
  	var result;
    $.post(url, {},function(obj) {
      result = obj;
    },"json");
    if (result) {
      if (result.error) {
        alert(result.error);      
      }
      else {
        alert("Ваш голос учтен.");
      }
    } else {
      alert("Произошла ошибка во время учета голоса");
    }
    return false;
  });
});
			
