  var $loadingImageURL = contentpath + "/theme/images/loading.gif";
  var $loadingImage = new Image();
  var $imageDialog = null;
  var $currentImage = null;
  var $line = null; 
  
  var $contentBox = null;
  var $prevBox = null;
  
  // Информация об изображениях
  var currentImageIndex = -1;
  var imageIDs = new Array();
  var imageWidths = new Array();
  var imageHeights = new Array();
  var thumbWidths = new Array();
  var thumbHeights = new Array();
  var imageNames = new Array();
  var thumbSizeX = 0;
  var thumbSizeY = 0;
  var thumbScale = 0.35;
  var previewCount = 0;
  var visCount = 0;  
  var itemW = 0;
  var itemH = 0;  
  var prevSpace = 4;
    
  var dialogWidth = 0;
  var dialogHeight = 0;
  
  var loadingImageIndex = -1;
  var previewItemOffset = 0;
  
  var previewBoxWidth = 0;
  var previewBoxHeight = 0;
  
  var imageOriginalScale = 0;
  var imageCurrentScale = 0;
  
  // Парсит информацию об изображениях
  function parseImageInfo(info){
  	imageIDs = new Array();
  	imageWidths = new Array();
  	imageHeights = new Array();
  	thumbWidths = new Array();
  	thumbHeights = new Array();
    imageNames = new Array();
  
  	thumbSizeX = thumbSizeY = 0;
  	//var parts = info.match(new RegExp("(\\d+)", "g"));
  	var parts = info.match(new RegExp("[^_#]+", "g"));
  	currentImageIndex = parseInt(parts[0]) - 1;
  	var index = 0;
  	for(var i = 1; i < parts.length; i++){
  		var item = parts[i];
  		switch( i % 6 ){
  			case 1: imageIDs[index] = parseInt(item);
  				break;
  			case 2: imageWidths[index] = parseInt(item);
  				break;
  			case 3: imageHeights[index] = parseInt(item);
  				break;
  			case 4: 
  				var sx = thumbWidths[index] = Math.round(parseInt(item) * thumbScale);
  				if(sx > thumbSizeX) thumbSizeX = sx;
  				break;
  			case 5: 
  				var sy = thumbHeights[index] = Math.round(parseInt(item) * thumbScale);
  				if(sy > thumbSizeY) thumbSizeY = sy;
  				break;
  			case 0:
  				imageNames[index] = item; 
  				index++;
  				break;	
  		}
  	}
  	previewCount = index;
  }

  function changeDialogBounds(x, y, w, h, callback){
  	var space = 15;
  	var ww = w + 2 * space;
  	var hh = h + 2 * space;
  	var $d = $(".imgdlg");
  	//alert("w = " + ww + " " + $d.width() + " h = " + hh + " " + $d.height());
  	if(ww > dialogWidth || ww > $d.width() + 2 * space || hh > dialogHeight || hh > $d.height() + 2 * space){
  		dialogWidth = ww;
  		dialogHeight = hh;
 		$d.animate({ left : (x - space) + "px", top : (y - space) + "px", width : w + "px", height : h + "px" }, "fast", "swing", function(){
 			callback();
 			$imageDialog.dialog("option", { width : ww, height : hh/*, maxWidth : w, maxHeight : h*/ });  
 		});
 	}else callback();
  }
  
  function reloadImage(index){
	  		$content = $("#imgcont");
	  		$content.empty();
	  		
	  		// Размеры отступов
	  		var space = 10;  		
	  		var titleHeight = Math.round($('div.ui-dialog-titlebar').height());
	  		var footerHeight = thumbSizeY + 6 * space;
  		
	  		var w = $(window).width();
	  		var h = $(window).height();
			if(w < 240) w = 240; if(h < 320) h = 320;
		
			// Клиентская область
	  		var cw = w - 2 * space; 
	  		var ch = h - 7 * space - (titleHeight + footerHeight);

			// Масштаб для картинки
			var imgW = imageWidths[index];
			var imgH = imageHeights[index];
	  		var scaleX = cw / imgW;
	  		var scaleY = ch / imgH;
  		
	  		var scale = Math.min(scaleX, scaleY);
	  		if(scale > 1.0) {
				imageCurrentScale = imageOriginalScale = 1.0;
	  		}else imageCurrentScale = imageOriginalScale = scale;
  		
	  		// Новый размер картинки
	  		var ww = Math.round( imgW * scale);
	  		var hh = Math.round( imgH * scale);
	  		var imgStartW = ww;
	  		var imgStartH = hh;
	  		if(scale > 1.0){
	  			imgStartW = imgW;
	  			imgStartH = imgH;
	  		}
  		
	  		// HTML код для картинки
	  		var id = imageIDs[index];
	  		var url = "/portal/object/" + id + "/1/1";  		
			var html = "<table width=\"100%\" height=\"100%\" border=\"0\"><tr><td valign=\"middle\" align=\"center\"><img id=\"imgbody\" src=\"" + url + "\" width=\"" + imgStartW + "\" height=\"" + imgStartH + "\"></td></tr></table>";
	 		$imageDialog.dialog( "option", { title : imageNames[index] });  		
 			$content.css({ "background-color" : "white", "background-image" : "url('" + $loadingImageURL + "')", "background-position" : "center center", "background-repeat" : "no-repeat", "height" : (($prevBox == null) ? (ch + footerHeight) : ch) + "px", "width" : "100%" });  			
		
			//alert("new img size = " + ww + "x" + hh + " thumb size = " + thumbSizeX + "x" + thumbSizeY + " img size = " + imgW + "x" + imgH + " scale = " + scale + " client area = " + cw + "x" + ch);
		
			// Ширину контейнера под новый размер картинки
	  		ww += 2 * space;
	  		hh += 2 * space + titleHeight + footerHeight;

	  		changeDialogBounds( Math.round((w - ww) / 2), $(document).scrollTop() + Math.round((h - hh) / 2), ww, hh, function(){
		  		$content.css({ "height" : ch + "px", "width" : "100%" });  			
		 		// HTML для списка превьюшек
		 		if($prevBox == null) {
		 			$content.after("<div id=\"imgprevbox\" align=\"center\" />");
		 			$prevBox = $("#imgprevbox");
		 			$prevBox.css({ "width" : "100%", "height" : footerHeight + "px", "background-color" : "transparent", "position" : "relative", "top" : "20px" });	  		
		 			mkPreviewList($prevBox);
		 			if(previewBoxWidth > ww) changeDialogBounds( Math.round((w - previewBoxWidth) / 2), $(document).scrollTop() + Math.round((h - hh) / 2), previewBoxWidth, hh, function(){
		 				$content.css({ "height" : ch + "px", "width" : "100%" });  			
		 			});
	 			}
	 			
	  		});

	  		var img = new Image(); 
  			$(img).load(function(){
  				//setTimeout(function(){
  					if(index == loadingImageIndex) {
  						$content.empty();
  						$content.append("<div id=\"imgscroll\" align=\"center\" style=\"overflow: auto; width: 100%; height: 100%; border: solid 1px #bbb;\">" + html + "</div>");
  						currentImageIndex = index;
  						$content.css({ "background-image" : "none" });  						
  						
			  			// Кнопки увеличить / уменьшить
	  					var $btnPane = $("<div id=\"btnpane\"/>");
	  					$btnPane.css({"float" : "left", "position" : "absolute", "left" : "30px", "top" : "20px", "z-index" : 100 });
				  		var $btnZoomIn = $("<span id=\"btnzoomin\"/>");
				  		var $btnZoomEqu = $("<span id=\"btnzoomequ\"/>");
				  		var $btnZoomOut = $("<span id=\"btnzoomout\"/>");
				  		var $zoomHint = $("<span id=\"zoomhint\" style=\"font-size: 10px; color: #aaa; position: relative; top: -4px; \" />");
				  		$btnZoomIn.button({ "icons" : { primary : "ui-icon-zoomin" } }).click(function(){
				  			if(imageCurrentScale <= 2.0){
					  			imageCurrentScale *= 1.2;
		  						$("#imgbody").effect("scale", { percent: 120 }, "fast");
		  						$("#btnzoomin").button("option", "disabled", (imageCurrentScale > 2.0) );
			  					$zoomHint.html(Math.round(imageCurrentScale * 100) + "%");
	  						}
	  					});
				  		$btnZoomEqu.button({ "icons" : { primary : "ui-icon-image" } }).click(function(){
				  			var proc = (1.0 / imageCurrentScale) * 100;
				  			imageCurrentScale = 1.0;
		  					$("#imgbody").effect("scale", { percent: proc }, "fast");
		  					$zoomHint.html(Math.round(imageCurrentScale * 100) + "%");
	  					});
				  		$btnZoomOut.button({ "icons" : { primary : "ui-icon-zoomout" } }).click(function(){
				  			if(imageCurrentScale > 0.2){
				  			imageCurrentScale /= 1.2;
		  						$("#imgbody").effect("scale", { percent: 80 }, "fast");	  		
		  						$("#btnzoomout").button("option", "disabled", (imageCurrentScale < 0.2) );	  							
			  					$zoomHint.html(Math.round(imageCurrentScale * 100) + "%");
	  						}
	  					});
	  					$zoomHint.html(Math.round(imageCurrentScale * 100) + "%");
	  						  					

				  		$("#imgscroll").prepend($btnPane);
	  					$btnPane.append($btnZoomIn).append($btnZoomEqu).append($btnZoomOut).append($zoomHint);
  					}
	  			//}, 3000);
  			}).error(function(){
  				//setTimeout(function(){
  					if(index == loadingImageIndex) {
 	 					$content.empty();
  						$content.append("<p>Ошибка при загрузке изображения</p>");
  						currentImageIndex = index;
  						$content.css({ "background-image" : "none" });
  					}
  				//}, 3000);
  			});
	  		$(img).attr("src", url);  		
  }
  
  /*function selectImage(index){
  	loadingImageIndex = index;
	reloadImage(index);  	  	
	var scrollDir = loadingImageIndex - currentImageIndex;
	if(scrollDir != 0){
		var $line = $("#imgsline");
		var leftPos = scrollDir * 100;
  		$line.animate({ left : leftPos + "px" }, 2000, "swing", function(){});
  	}
  }*/
  
  function updateImages(start, count, load){
  	var end = start + count;
  	for(var i = start; i < end; i++){
  		if(!load) clearImageContent(i); else setImageContent(i);
  	}
  }
  
  function clearImageContent(index){
  	$("#tdimg" + index).empty();
  }
  
  function setImageContent(index){
  	$img = $("#tdimg" + index);
  	$img.empty();
  	$img.append("<img id=\"btn" + index + "\" src=\"/portal/object/" + imageIDs[index] + "/1/0\" width=\"" + thumbWidths[index] + "\" height=\"" + thumbHeights[index] + "\">");
  }
  
  function mkPreviewList($box){
  	  var listSize = Math.min(5, previewCount);
  	  var part = Math.floor(listSize / 2);
  	  var start = loadingImageIndex - part;
  	  var end = loadingImageIndex + 1 + part;  	  
  	  if(start < 0) {
  	  	end -= start;
  	  	start = 0;
  	  }
  	  if(end > previewCount){
  	  	start = previewCount - listSize;
  	  	end = previewCount;
  	  }

  	  var space = prevSpace;
  	  visCount = end - start;
  	  previewItemOffset = start;
  	  $box.empty();
  	  $box.append("<div id=\"prevcont\"></div>");
  	  var $prevContainer = $("#prevcont");
  	  $prevContainer.append("<div id=\"imgarrow_left\" class=\"imgarrow\" style=\"float: left;\"></div>");
  	  
  	  var html = "";
  	  for(var i = 0; i < previewCount; i++){
  	  	html += "<span class=\"imgprev\" style=\"margin: 0px; position: relative; left: " + ((i + 1) * space) + "px; top: " + space + "px;\" name=\"#" + i + "\"><table width=\"" + (thumbSizeX + 2 * space) + "\" height=\"" + (thumbSizeY + 2 * space) + "\"><tr><td valign=\"middle\" id=\"tdimg" + i + "\">";
  	  	html += "</td></tr></table></span>";
  	  } 
  	  html = "<div id=\"imgsline\" style=\"float: left;\">" + html + "</div>";
  	  
   	  $prevContainer.append(html);
   	  $prevContainer.append("<div id=\"imgarrow_right\" class=\"imgarrow\" style=\"float: left;\"></div>");  	  
  	  for(var i = start; i < end; i++) setImageContent(i);
  	  
  	  var $previews = $(".imgprev");
  	  $previews.button();  	  
  	  
  	  $("#btn" + loadingImageIndex).toggleClass("ui-state-highlight");
  	  
  	  itemW = $previews.width() + 2; // 2 это рамка (1px + 1px)
  	  itemH = $previews.height() + 2;
  	  var rectW = previewCount * (itemW + space) + space;
  	  var rectH = itemH + 2 * space;
  	  var visRectW = visCount * (itemW + space) + space;
  	  
  	  $line = $("#imgsline");
	  $line.css({ "width" : rectW + "px", "height" : rectH + "px", "position" : "relative", "left" : (- previewItemOffset *  (itemW + space)) + "px" });	
	  $line.wrap("<div style=\"float: left; width: " + visRectW + "px; height: " + rectH + "px; overflow: hidden; zoom: 1;\" align=\"left\" />"); 

	  previewBoxWidth = visRectW + 4 * space + 80;
	  previewBoxHeight = rectH + 2 * space;
	  $prevContainer.css({ "width" : previewBoxWidth + "px", "height" : previewBoxHeight + "px" });

  	  $(".imgarrow").css({ "width" : "32px", "height" : itemH + "px", "position" : "relative", "top" : space + "px" });
  	  $("#imgarrow_right").button({ "icons" : { primary : "ui-icon-circle-arrow-e" } }).click(function(){
  	  	if(loadingImageIndex < previewCount - 1){
  	  		onButtonClick(loadingImageIndex + 1);
  	  	}
  	  });
  	  $("#imgarrow_left").button({ "icons" : { primary : "ui-icon-circle-arrow-w" } }).click(function(){
  	  	if(loadingImageIndex > 0){
  	  		onButtonClick(loadingImageIndex - 1);
  	  	}
  	  });

  	  $previews.click(function(){
 	 	  var index = parseInt($(this).attr("name").substring(1));
 	 	  onButtonClick(index);
  	  });
  	  
	  if(loadingImageIndex == 0) $("#imgarrow_left").button("option", "disabled", true);
	  if(loadingImageIndex == previewCount - 1) $("#imgarrow_right").button("option", "disabled", true);
  }
  
  function onButtonClick(index){
  	  	if(index != loadingImageIndex){
  	  		var space = prevSpace;
	  	  	$("#btn" + loadingImageIndex).removeClass("ui-state-highlight");
		  	loadingImageIndex = index;
  		  	//$("#btn" + loadingImageIndex).css("border", "1px solid red");
  		  	$("#btn" + loadingImageIndex).toggleClass("ui-state-highlight");
			reloadImage(index);  	
			var center = Math.floor(visCount / 2);
			var newSel = loadingImageIndex - previewItemOffset;
			if(newSel != center)
			{
				var oldOffset = previewItemOffset;
				previewItemOffset = loadingImageIndex - center;
				if(previewItemOffset < 0) previewItemOffset = 0;
				else if(previewItemOffset + visCount > previewCount) previewItemOffset = previewCount - visCount;
				var previewBoxOffset = - previewItemOffset * (itemW + space); 
				var d = previewItemOffset - oldOffset;
				if(d < 0){
					updateImages(previewItemOffset, -d, true);
				}else{
					updateImages(previewItemOffset + visCount - d, d, true);
				}
			 	
				$line.animate({ left : previewBoxOffset + "px" }, "fast", "swing", function(){
					if(d < 0){
						updateImages(previewItemOffset + visCount, -d, false);
					}else{
						updateImages(previewItemOffset - d, d, false);
					}
				});
				$(".imgarrow").button("option", "disabled", false);
				if(loadingImageIndex == 0) $("#imgarrow_left").button("option", "disabled", true);
				if(loadingImageIndex == previewCount - 1) $("#imgarrow_right").button("option", "disabled", true);
			}
			
		}
  }
	  
  $(document).ready(function(){
  
  	$loadingImage.src = $loadingImageURL;
  	
  	$(".catalogue-item-info-block-a").click(function () {
  		var obj = $(this).parent().parent().find("div.catalogue-item-info-block");		
		if(obj != null) {
			var t = obj.filter("div:visible"); 
			if(t.length > 0) {
				$(this).parent().removeClass("catalogue-item-arrow-exp").addClass("catalogue-item-arrow-coll");					
				t.hide("fast"); 				
			}else {
				$(this).parent().removeClass("catalogue-item-arrow-coll").addClass("catalogue-item-arrow-exp");					
				obj.show("fast");
			}
		}
		
		
  	});
  	
  	$("#pageopen, .imopen").click(function () {
  		parseImageInfo($(this).attr("name"));
  		
  		$imageDialog = $("<div></div>").dialog({ 
  			autoOpen: false, 
  			modal: true, 
  			dialogClass : "imgdlg", 
  			/*width : 240,
  			height : 320,
  			position: [500, 500],*/	
  			beforeclose: function() {
            	$(this).html(" ");
            },
            close: function() {
            	$prevBox = null;
            	dialogWidth = dialogHeight = 0;
            	loadingImageIndex = -1;
            	currentImageIndex = -1;
            	$line = null;
            	$(this).dialog('destroy');
            } 
        });
  	  	
  		$imageDialog.bind( "dialogopen", function(event, ui) {
  			//$imageDialog.empty();
	  		//$imageDialog.siblings('div.ui-dialog-titlebar').remove();
  			$imageDialog.append("<div id=\"imgcont\"></div>");
  			
  			loadingImageIndex = currentImageIndex;
  			reloadImage(currentImageIndex);
		});
  		
  		$imageDialog.dialog("open");
  	});
  	
  		
  });
  
  function stub(){
  
  }
  

