$(document).ready(function(){
	
	/**
	 * Хранит данные пришедшие по ajax об изображении
	 */
	var jsonRequestData;
	
	/**
	 * Клик по имени фото галереи
	 */
	$('.photoGalleryBlock .categoryLine a').click(function(){
		$('.photoGalleryBlock .categoryLine a').removeClass('selected');
		$(this).addClass('selected');
		var galId = parseInt($(this).attr('id').replace(/pgal_(\d)/,'$1'));
		if($('.loadBox').css('top')>0){hideLoadBox();}
		$('.photoGalleryBlock .galleryLine pre').remove();
		$('.photoGalleryBlock .galleryLine').append('<pre><img src="/img/gif_loader.gif" alt="loading" border="0"/></pre>');
		$('.photoGalleryBlock .galleryLine pre').css({opacity: 0.5});
		requestGallery(galId,1);
		return false;
	});
	
	bindImageClick();
	bindPageLineClick();
	
	/**
	 * Loading box close click
	 */
	$('.loadBox .closeBtn').click(hideLoadBox);
	
	/**
	 * Клик по имени видео галереи
	 */
	$('.videoGalleryBlock .categoryLine > a').click(function(){
		$('.videoGalleryBlock .categoryLine a').removeClass('selected');
		$(this).addClass('selected');
		var vGalId = parseInt($(this).attr('id').replace(/vgal_(\d)/,'$1'));
		if($('.loadBox').css('top')>0){hideLoadBox();}
		$('.videoGalleryBlock .galleryLine pre').remove();
		$('.videoGalleryBlock .galleryLine').append('<pre><img src="/img/gif_loader.gif" alt="loading" border="0"/></pre>');
		$('.videoGalleryBlock .galleryLine pre').css({opacity: 0.5});
		requestVideoGallery(vGalId,1);
		return false;
	});
	
	bindVideoImageClick();
	bindVideoPageLineClick();	
});

/**
 * Клик по изображению галереи (открыть фоту)
 */
function bindImageClick(){
	$('.photoGalleryBlock .galleryLine > a').click(function(){
		var imageId = parseInt($(this).find('ins img.photofile').attr('id').replace(/pimg_(\d)/,'$1'));
		// clear previous image load
		$('.photoGalleryBlock .galleryLine a ins pre').remove();
		$(this).find('ins').append('<pre><img src="/img/gif_loader.gif" alt="loading" border="0"/></pre>');
		$(this).find('ins pre').css({opacity: 0.5});
		//if($('.loadBox').css('top')>0){hideLoadBox();}
		requestImageFile(imageId, null);
		return false;
	});
}

/**
 * Клик по страницам галереи
 */
function bindPageLineClick(){
	$('.photoGalleryBlock .galleryLine .galNavigation span a').unbind('click');
	$('.photoGalleryBlock .galleryLine .galNavigation span a').click(function(){
		$('.photoGalleryBlock .galleryLine pre').remove();
		$('.photoGalleryBlock .galleryLine').append('<pre><img src="/img/gif_loader.gif" alt="loading" border="0"/></pre>');
		$('.photoGalleryBlock .galleryLine pre').css({opacity: 0.5});
		var galId = parseInt($('.photoGalleryBlock .categoryLine a.selected').attr('id').replace(/pgal_(\d)/,'$1'));
		requestGallery(galId,parseInt($(this).text()));
		return false;
	});
	
	$('.photoGalleryBlock .galleryLine .galNavigation > a').unbind('click');
	$('.photoGalleryBlock .galleryLine .galNavigation > a').click(function(){
		var galId = parseInt($('.photoGalleryBlock .categoryLine a.selected').attr('id').replace(/pgal_(\d)/,'$1'));
		var curPage = parseInt($('.photoGalleryBlock .galleryLine .galNavigation span a.sel').text());
		$('.photoGalleryBlock .galleryLine pre').remove();
		$('.photoGalleryBlock .galleryLine').append('<pre><img src="/img/gif_loader.gif" alt="loading" border="0"/></pre>');
		$('.photoGalleryBlock .galleryLine pre').css({opacity: 0.5});
		if ($(this).find('img').attr('src').match('Fwd')){
			// next
			requestGallery(galId,curPage+1);
		}
		if ($(this).find('img').attr('src').match('Back')){
			// prew
			requestGallery(galId,curPage-1);
		}
		if ($(this).find('img').attr('src').match('Home')){
			// home
			requestGallery(galId,1);
		}
		return false;
	});
	
}

/**
 * Запрашивает дополнительный сведения по изображению
 * @param id
 * @return
 */
function requestImageFile(id,mod){
	$('.loadBox .middleLine').css({
		height: $('.loadBox .middleLine img').height()
	}).empty();
	$('.loadBox .footerLine').slideUp('fast');
	$.ajax({
		type: 'GET',
		url: 'ajax.php',
		cache: false,
		dataType: 'json',
		data: {a:'ph', i:id, m:mod},
		success: loadImageInfo,
		error: showImageError
	});
	return false;
}

/**
 * Загружаем инфу об изображении в loadBox, ресайзим его под новое изображение
 * @param data
 * @return
 */
function loadImageInfo(data){
	if (data.id == '') {hideLoadBox(); return false;}
	jsonRequestData = data;
	var lb = $('.loadBox');
	var w = $(window);
	lb.find('.footerLine strong').html(data.c);
	lb.find('.footerLine p').html(data.d);	
	
	// set new image height size
	$('.loadBox .middleLine').animate({height: data.h},'fast');
	
	var scrlTop = $(document).scrollTop();
	var scrlLeft = $(document).scrollLeft();
    var newWidth = data.w + 36; // 32 is middle line margin 6 - borders
    var newleft = scrlLeft + w.width()/2 - newWidth/2;
    var newtop = scrlTop + w.height()/2 - data.h/2;
    
    if(parseInt(lb.css('top'))<0){
    	lb.css({
    		display: 'none',
    		top: newtop,
    		left: newleft,
    		width: newWidth
    	});
        lb.find('.footerLine').css({display:'none'});
        
        lb.show('slow', function(){
        	loadImage();
        });
    }
    else{
    	lb.animate(
    			{
    	    		top: newtop,
    	    		left: newleft,
    	    		width: newWidth
    			},
    			'slow',
    			'swing',
    			loadImage
    	);
    }
	lb = null; w = null;
}

/**
 * Грузим фотку
 * @return
 */
function loadImage(){
	var lb = $('.loadBox');
    lb.find('.middleLine').empty().append('<img width="'+jsonRequestData.w+'" height="'+jsonRequestData.h+'" id="'+jsonRequestData.id+'" alt="" style="visibility: hidden"/>');
	lb.find('.middleLine img').load(showLoadBoxImage).attr('src', jsonRequestData.m);
	lb.find('.footerLine').slideDown('slow');
	lb = null;
}

/**
 * Показываем изображение
 * @return
 */
function showLoadBoxImage(){
	$('.photoGalleryBlock .galleryLine a ins pre').remove();
	$('.videoGalleryBlock .galleryLine a ins pre').remove();
	
	$('.loadBox .middleLine img').css({opacity:0}).css({visibility:'visible'}).animate({opacity:1},'slow');
	$('.loadBox .arrowLeft').unbind('click').click(function(){
    	requestImageFile($('.loadBox .middleLine img').attr('id'),'p');
    });
   $('.loadBox .arrowRight, .loadBox .middleLine img').unbind('click').click(function(){
    	requestImageFile($('.loadBox .middleLine img').attr('id'),'n');
    });
	
	
}

/**
 * Убирает анимацию загрузки при ошибке
 * @return
 */
function showImageError(){
	//console.log('show image error');
	$('.photoGalleryBlock .galleryLine a ins pre').remove();
	hideLoadBox();
};

/**
 * Убирает loadBox
 * @return
 */
function hideLoadBox(){
	//console.log('hideBox');
	$('.loadBox').hide('slow', function(){$(this).css({display: 'block',top: -10000,left: -10000});$('.loadBox').find('.middleLine').empty();});
}

/**
 * Запрашивает данные галереи
 * @param id
 * @return
 */
function requestGallery(id,p){
	$.ajax({
		type: 'GET',
		url: 'ajax.php',
		cache: false,
		dataType: 'json',
		data: {a:'ph', gi:id, p:p},
		success: showGallery,
		error: showGalleryError
	});
	return false;	
}

/**
 * Заполняет строку галереи
 * @param data
 * @return
 */
function showGallery(data){
	var itemCount = data.im.length;
	$('.photoGalleryBlock .galleryLine > a').remove();
	for (i=0;i<itemCount;i++){
		$('.photoGalleryBlock .galleryLine .clearFloater').before('<a href="#"><ins><img src="/img/photoFrame.png" width="193" height="131" alt="gallery image frame" border="0" class="iePngFix"/><img src="'+data.im[i].p+'" id="pimg_'+data.im[i].i+'" width="187" height="125" alt="gallery image" border="0" class="photofile"/></ins></a>');
	}
	$('.photoGalleryBlock .galleryLine .galNavigation span').empty();
	if (data.pc > 1){
		for (i=0;i<data.pc;i++){
			$('.photoGalleryBlock .galleryLine .galNavigation span').append('<a href="#" '+((i==data.cp)?'class="sel"':'')+'>'+(i+1)+'</a> ');
		}
	}
	$('.photoGalleryBlock .galleryLine pre').remove();
	bindImageClick();
	bindPageLineClick();
}

/**
 * Убирает анимацию загрузки при ошибке
 * @return
 */
function showGalleryError(){$('.photoGalleryBlock .galleryLine pre').remove();}

/*-----------------------------------------------------------------------------*/

/**
 * Запрашивает новую галерею
 */
function requestVideoGallery(galId,page){
	$.ajax({
		type: 'GET',
		url: 'ajax.php',
		cache: false,
		dataType: 'json',
		data: {a:'vg', gi:galId, p:page},
		success: showVideoGallery,
		error: showVideoGalleryError
	});
	return false;
}

/**
 * Убирает анимацию загрузки и отображает галерею
 * @param data
 * @return
 */
function showVideoGallery(data){
	var itemCount = data.im.length;
	$('.videoGalleryBlock .galleryLine > a').remove();
	for (i=0;i<itemCount;i++){
		$('.videoGalleryBlock .galleryLine .clearFloater').before('<a href="#"><ins><img src="/img/videoFrame.png" width="235" height="176" border="0" alt="video frame" class="iePngFix"/><img src="'+data.im[i].p+'" id="vimg_'+data.im[i].i+'" width="229" height="170" alt="gallery image" border="0" class="photofile"/></ins></a>');
	}
	$('.videoGalleryBlock .galleryLine .galNavigation span').empty();
	if (data.pc > 1){
		for (i=0;i<data.pc;i++){
			$('.videoGalleryBlock .galleryLine .galNavigation span').append('<a href="#" '+((i==data.cp)?'class="sel"':'')+'>'+(i+1)+'</a> ');
		}
	}
	$('.videoGalleryBlock .galleryLine pre').remove();
	bindVideoImageClick();
	bindVideoPageLineClick();	
}

/**
 * Убирает анимацию при ошибке загрузки видео галереи
 * @return
 */
function showVideoGalleryError(){
	$('.videoGalleryBlock .galleryLine pre').remove();
}

/**
 * Клик по изображению галереи (открыть видео)
 */
function bindVideoImageClick(){
	$('.videoGalleryBlock .galleryLine > a').click(function(){
		var videoId = parseInt($(this).find('ins img.photofile').attr('id').replace(/vimg_(\d)/,'$1'));
		// clear previous image load
		$('.videoGalleryBlock .galleryLine a ins pre').remove();
		$(this).find('ins').append('<pre><img src="/img/gif_loader.gif" alt="loading" border="0"/></pre>');
		$(this).find('ins pre').css({opacity: 0.5});
		requestVideoFile(videoId);
		return false;
	});
}

/**
 * Клик по страницам галереи
 */
function bindVideoPageLineClick(){
	$('.videoGalleryBlock .galleryLine .galNavigation span a').unbind('click');
	$('.videoGalleryBlock .galleryLine .galNavigation span a').click(function(){
		$('.videoGalleryBlock .galleryLine pre').remove();
		$('.videoGalleryBlock .galleryLine').append('<pre><img src="/img/gif_loader.gif" alt="loading" border="0"/></pre>');
		$('.videoGalleryBlock .galleryLine pre').css({opacity: 0.5});
		var galId = parseInt($('.photoGalleryBlock .categoryLine a.selected').attr('id').replace(/vgal_(\d)/,'$1'));
		requestGallery(galId,parseInt($(this).text()));
		return false;
	});
	
	$('.videoGalleryBlock .galleryLine .galNavigation > a').unbind('click');
	$('.videoGalleryBlock .galleryLine .galNavigation > a').click(function(){
		var galId = parseInt($('.videoGalleryBlock .categoryLine a.selected').attr('id').replace(/vgal_(\d)/,'$1'));
		var curPage = parseInt($('.videoGalleryBlock .galleryLine .galNavigation span a.sel').text());
		$('.videoGalleryBlock .galleryLine pre').remove();
		$('.videoGalleryBlock .galleryLine').append('<pre><img src="/img/gif_loader.gif" alt="loading" border="0"/></pre>');
		$('.videoGalleryBlock .galleryLine pre').css({opacity: 0.5});
		if ($(this).find('img').attr('src').match('Fwd')){
			// next
			requestVideoGallery(galId,curPage+1);
		}
		if ($(this).find('img').attr('src').match('Back')){
			// prew
			requestVideoGallery(galId,curPage-1);
		}
		if ($(this).find('img').attr('src').match('home')){
			// home
			requestVideoGallery(galId,1);
		}
		return false;
	});
	
}

/**
 * Запрашивает дополнительный сведения по изображению
 * @param id
 * @return
 */
function requestVideoFile(id){
	$('.loadBox .middleLine').empty();
	$('.loadBox .footerLine').slideUp('fast');
	$.ajax({
		type: 'GET',
		url: 'ajax.php',
		cache: false,
		dataType: 'json',
		data: {a:'vg', i:id},
		success: showVideo,
		error: showVideoError
	});
	return false;
}

/**
 * Показывает loadBox и загружает в него видео
 * @param data
 * @return
 */
function showVideo(data){
	var lb = $('.loadBox');
	lb.find('.footerLine strong').html(data.c);
	lb.find('.footerLine p').html(data.d);
	// load image
	lb.find('.middleLine').empty().append('\
			<object type="application/x-shockwave-flash" data="/player-viral.swf" height="300" width="400">\
				<param name="bgcolor" value="#FFFFFF" />\
				<param name="allowFullScreen" value="true" />\
				<param name="allowScriptAccess" value="always" />\
				<param name="movie" value="/player-viral.swf" />\
				<param name="FlashVars" value="file='+data.v+'&image='+data.o+'&backcolor=292929&frontcolor=cccccc&lightcolor=00CCCC&skin=/modieus.swf&bufferlength=10&volume=100" />\
			</object>\
	');//.css({height: '300px'});
	showLoadBox(data);
	lb = null;
}

/*
	<embed
  src="player-viral.swf"
  width="608"
  height="488"
  wmode="transparent"
  allowfullscreen="true"
  allowscriptaccess="always"
  bgcolor="000000"
  flashvars="file=video.flv&image=preview.jpg&backcolor=111111&frontcolor=cccccc&lightcolor=00CCCC&skin=modieus.swf&bufferlength=10&volume=100">
</embed> 
*/

/**
 * Убирает анимацию загрузки при ошибке в загрузке видео
 * @return
 */
function showVideoError(){
	$('.photoGalleryBlock .galleryLine a ins pre').remove();
}

/**
 * Показывает окно загрузки при загрузке в него видео
 * @return
 */
function showLoadBox(data){
	$('.photoGalleryBlock .galleryLine a ins pre').remove();
	$('.videoGalleryBlock .galleryLine a ins pre').remove();
	if (data.id == '') {hideLoadBox(); return false;}
	var lb = $('.loadBox');
	var w = $(window);
	
	$('.loadBox .middleLine').css({height: 300});
	
	var scrlTop = $(document).scrollTop();
	var scrlLeft = $(document).scrollLeft();
    var newWidth = 400 + 36; // 32 is middle line margin 6 - borders
    var newleft = scrlLeft + w.width()/2 - newWidth/2;
    var newtop = scrlTop + w.height()/2 - 300/2;
    
    if(parseInt(lb.css('top'))<0){
    	lb.css({
    		display: 'none',
    		top: newtop,
    		left: newleft,
    		width: newWidth
    	});
        lb.find('.footerLine').css({display:'none'});
        
        lb.show('slow', function(){
        	$('.loadBox .footerLine').slideDown('slow');
        });
    }
    else{
    	lb.animate(
    			{
    	    		top: newtop,
    	    		left: newleft,
    	    		width: newWidth
    			},
    			'slow',
    			'swing',
    			function(){$('.loadBox .footerLine').slideDown('slow');}
    	);
    }
	lb = null; w = null;
}
