
var GalTrmbDiv;
var ImgCnt = 0;
var LastActiveId = 0;
var CurrentGalId = 0;
var CurrentSrc = '';
var ImgFullSized = 0;
var Img;

var LastImgRealW, LastImgRealH;

var EnableHashId = 0;
var ImgFromAnc = GetImgFromAnc();
var GalIsLoad = 0; //0 - NoLoad, 1 - Loaded, 2 - Closed, 11 - fixedLoad (NoAjax) = reset Page After Close

function LoadGallery() {

	if(TimerEnabled == 1) { TimerEnabled = 0; clearTimeout(Timer); }
		
	var width = $("#container").css("width");
	$("#wrapper").css('z-index', '-2');

	var WInt = parseInt(width)+500;
	$('#GalleryFon').css({'width': WInt+'px', 'left': -WInt+'px', 'display':''});
	
		$("#container").fadeTo(500, 0, function() {$(this).hide();});
		
		if(MainPage == 1) 
		{	$("#wrapper").fadeTo(500, 0, function() {$(this).hide();});
			$("body").css({ 'background-color': '#fff', 
							'background-image': 'url(/static/themes/nirsi/images/bg_sidebar.gif)',
							'background-position': '50% 0%'					
						});
		}
		
	$('#GalleryFon').animate({'left':0+'px'},500, function(){
		$(this).css('width', '100%');

		if(GalIsLoad == 0)
		{
		  $.ajax({   
                url: "/GalAjax/" + GetGalIdFromAnc() + "/",   
                cache: false,   
                success: function(html)
                {   
                    if(GalIsLoad == 2) {
                    	$('#Gal_box').html(html);
                    }
                    else {             
	                    $('#GGlobalLoad').fadeTo(300, 0, function(){
							$(this).hide();
							GalIsLoad = 1;
							$('#GalleryFon').css('z-index', -1);	
	                    	$('#Gal_box').html(html);  
	                    	$('#Gal_box').css('display', '');
	                    	$('#ImgPreLoaderDiv').css('display', '');
	                    });
                    }
                }   
            });
        }
        else {
				$('#GalleryFon').css('z-index', -1);	
                $('#Gal_box').css('display', '');
                $('#ImgPreLoaderDiv').css('display', '');
				if(LastActiveId == 0) LastActiveId = 1;
				window.location.href = '#id='+LastActiveId+':'+CurrentGalId;
        }
	});
}


var SummWidth = 0; var LastImgWeight = 0;

function LineImgLoad(p) {  //Загрузка слайдера (динамическое увеличение ширины скрытого слайдера с каждой новой загруженной картинкой-Trmb)
	SummWidth += p.width + 10;
	if(SummWidth > 800)
		GalTrmbDiv.css('width', SummWidth+200 + 'px');
	
	LastImgWeight = p.width;
	
	$(p.parentNode).css('max-width', p.width+'px');
	ImgCnt += 1;
	$('#ImgCounter').html(LastActiveId + '/' + ImgCnt);
	
	if(ImgCnt == ImgFromAnc) GalClickTrmb(ImgFromAnc);
}


var Slide = 0;
var SlidedMove = 300;

function SlideR() {
	if( (SummWidth + Slide) > 600)
	{
		Slide -= SlidedMove;
		$('#GalTrumbDiv').animate({'left': Slide+'px'}, 500);
	}
}

function SlideL() {
	
	if( Slide < 10)
	{
		Slide += SlidedMove; if(Slide > 10) Slide = 10;
		$('#GalTrumbDiv').animate({'left': Slide+'px'}, 500);
	}

}

var ImgLoadStatus = 1; //GifTable is visible
function GalClickTrmb(id) {
	if(id == LastActiveId) return;
	
	if (LastActiveId != 0)
	{
		$('#tr-'+LastActiveId).fadeTo(300, 0.5);
	}
	$('#tr-'+id).fadeTo(100, 1);

	$('#Gal_text').fadeTo(300, 0, function() {
		
		$('#Gal_text h2:first').html( $('#tr-'+ id +' div:first').html() );
		$('#Gal_text p:first').html(  $('#GDesc-'+id).html() );
		
		$(this).fadeTo(300, 1);
	});
	
	LastActiveId = id;
	CurrentSrc = $('#tr-'+id).attr('rel');
	window.location.href = '#id='+id+':'+CurrentGalId;

	$('#ImgCounter').html(id + '/' + ImgCnt);
	
	if(ImgLoadStatus == 0)  //No Gif - Last Image is visible
	{
		$('.GImgNavL').stop();
		$('.GImgNavR').stop();
		
		$('#ImgDiv').stop().css({'height': $('#ImgDiv').height(), 'width': $('#ImgDiv').width(), 'max-width':''});
		Img.stop().fadeTo(200, 0, function(){
			$(this).hide();
			$('#PreloadGif').fadeTo(200, 1, function(){
				$('#ImagePreLoader').attr('src', CurrentSrc);
			});
			ImgLoadStatus = 1;
		});
	}
	else { $('#ImagePreLoader').attr('src', CurrentSrc); }
		
}

/* Hover/Unhover trmb */
function GTrmbHov(id)   { if(LastActiveId == id) return; $('#tr-'+id).stop().fadeTo(200, 1);}

function GTrmbUnHov(id) { if(LastActiveId == id) return; $('#tr-'+id).stop().fadeTo(200, 0.5);}

function PreloadOk(p) {
		if(p.src.indexOf(CurrentSrc) == -1) return;
		
		LastImgRealW = p.width;
		LastImgRealH = p.height;
		
		var Scale, H, W, delta = 0;
		availableW = $('#ImgDiv1').width() - 25; /* ImgDiv */
		if(availableW < p.width) {
			W = availableW;
			Scale = availableW/p.width;
			H = (p.height*Scale).toFixed();
		}
		else
		{
			H = p.height;
			W = p.width;
		}
		//alert(W + " " +H + " " +availableW + " " +Scale + " " +p.width + " " +p.height);
		delta = Math.abs(H - $('#ImgDiv').height()) + Math.abs(W - $('#ImgDiv').width());
		
		var time = 500;
		if(delta < 10) time = 10;			
	
		$('.GImgNavL').stop().animate({'height': H}, time);
		$('.GImgNavR').stop().animate({'height': H}, time);
		$('#ImgDiv').stop().animate({'height': H, 'width': W}, time, 
			function() 
			{
				Img.attr('src', p.src);

				$('#PreloadGif').fadeTo(300, 0, function()
				{ 
						$(this).hide();
						Img.fadeTo(300, 1, function() {
							$('#ImgDiv').css({'height': '', 'max-width': p.width, 'width': ''});
						}); 
						ImgLoadStatus = 0;
				} );
			} 
		);
}

var HoverR = 0;
var HoverL = 0;
function GImgNavHover(e) {

	var offset = $('#ImgDiv1').offset();
	
  	if (document.all)  { 
      x = event.x + document.body.scrollLeft; 
    } else {
      x = e.pageX; // Координата X курсора
    }
 	x = x - offset.left;
	w = $('#ImgDiv').width()+25;
	
	if(x < 25 && HoverL == 0) { $('#ImgDiv1').css({'background-position':'0px 50%', 'cursor':'pointer'});   HoverL = 1; }
	if(x >=25 && HoverL == 1) { $('#ImgDiv1').css({'background-position': '-25px 50%', 'cursor':'default'}); HoverL = 0; }
	
	if((w - x) < 0 && (w - x) > -25 && HoverR == 0)   { $('#ImgDiv').css({'background-image': 'url(/static/images/GalNav2.png)','cursor':'pointer'});    HoverR = 1;}
	if(((w - x) >= 0 || (w - x) <= -25) && HoverR == 1)  { $('#ImgDiv').css({'background-image': 'url(/static/images/GalNav.png)', 'cursor':'default'});  HoverR = 0;}
	
}

function GImgNavOut () {
	if(HoverL == 1) { $('#ImgDiv1').css({'background-position': '-25px 50%', 'cursor':'default'}); HoverL = 0; }
	if(HoverR == 1) { $('#ImgDiv').css({'background-image': 'url(/static/images/GalNav.png)', 'cursor':'default'});  HoverR = 0; }
}

function GImgNavClk() {
	if(HoverL == 1) 
	{ 
		if(LastActiveId > 1)
			GalClickTrmb(LastActiveId - 1); 
	}
	if(HoverR == 1) 
	{ 
		if(LastActiveId < ImgCnt)
			GalClickTrmb(LastActiveId + 1); 
	}
}

function CloseFullSize() {
    $("#GalMaxSize img").animate({'width': Img.width()+'px','height':Img.height()+'px'}, 200, function(){
		$("#GalMaxSize").hide();
	});
	$('.GalUser').css('padding-bottom', '40px');
	ImgFullSized = 0;
}

$(window).keydown(function(event){
  
  if(GalIsLoad != 1 && GalIsLoad != 11) return;
  if(ImgFullSized == 1) CloseFullSize(); 
    		
  switch (event.keyCode) {
    case 37: if(LastActiveId > 1)      GalClickTrmb(LastActiveId - 1); break; //Left
    case 39: if(LastActiveId < ImgCnt) GalClickTrmb(LastActiveId + 1); break;//Right
  }
});

$(window).click(function(){
	if(ImgFullSized == 0 || (GalIsLoad != 1 && GalIsLoad != 11) ) return;
	CloseFullSize();
});

function FullImageSiaze() {
	
	if(LastImgRealW > Img.width()+10 || LastImgRealH > Img.height()+10)
	{
		
		
		$("#GalMaxSize img").attr('src', Img.attr('src'));
		
		Itop  = Img.offset().top;
		Ileft = Img.offset().left;
		
		$('.GalUser').css('padding-bottom', (Img.height()-100) + 'px');
	
		$("#GalMaxSize img").css({'width': Img.width(),'height':Img.height()});
		$("#GalMaxSize").css({'width': LastImgRealW+'px','height':LastImgRealH+'px', 'display': '', 'top':Itop+'px', 'left':Ileft+'px'});
		
		$("#GalMaxSize img").animate({'width': LastImgRealW+'px','height':LastImgRealH+'px'}, 400);
		
		ImgFullSized = 1;
	}
}

function GetImgFromAnc() {
	var loc = window.location.hash;
	if(loc == "") return 1;
 	
 	loc = loc.replace("#id=","");
	loc = loc.substr(0, loc.indexOf(':'));
 	var val = parseInt(loc);
 	if(isNaN(val) || val != loc) return 1;
 	EnableHashId = 1;
 	return val;
}
function GetGalIdFromAnc() {
	var loc = window.location.hash;
	if(loc == "") return 1;
 	
 	loc = loc.replace("#id=","");
	loc = loc.substr(loc.indexOf(':')+1);
 	var val = parseInt(loc);
 	if(isNaN(val) || val != loc) return 1;
 	EnableHashId = 1;
 	return val;
}

	
function GalMenuOver(e)
	{
		em = e.getElementsByTagName('UL')
		if( em[0] )
		{
			e.style.background = '#393A3B'; 
		}
	}
	
function GalMenuOut(e)
	{
		e.style.background = '';
	}

function CloseGal() {
	if(GalIsLoad != 11)
		GalIsLoad = 2; //прервать Ajax-загрузку галереи
	window.location.href="#";
	var GalFon = $('#GalleryFon');
	
    $('#Gal_box').css('display', 'none');
    $('#ImgPreLoaderDiv').css('display', 'none');
	

    var WFon = GalFon.width();
    GalFon.css({'width': WFon+'px', 'z-index': 0});
    
    $("#container").fadeTo(500, 1);
	if(MainPage == 1) $("#wrapper").fadeTo(500, 1);
    GalFon.animate({'left':-WFon+'px'}, 500, function() { 
		$(this).hide(); 
		
			if(MainPage == 1) 
			{
				$("#wrapper").css('z-index', '');
				$("body").css({ 'background-color': '#4DA3D1', 
								'background-image': 'url(/static/themes/nirsi/images/bg_grad.gif)',
								'background-position': '50% 100%'					
							});
			}
	
		if(GalIsLoad == 11)
			window.location.href="/";
	});
    
}

	

