  var gallery_options;
  var gallery_block;
  var gallery_previous_id = 0;
  var gallery_previous_num = 0;
  var gallery_load_num;
  var gallery_load_id;
  var gallery_handle;
  var gallery_marker;
  var gallery_container;
  var gallery_inner;
  var gallery_itemsWidth;
  var gallery_perpage;
  var gallery_big_image;
  var gallery_big_block;
  var gallery_title;
  var gallery_prev;
  var gallery_next;
  var gallery_total;
  var gallery_menu;
  var gallery_slider_enable = true;

function fetch_thumbs_load (start) {
	
	start_image = Math.floor(start/gallery_options.thumb_div_width);
	end_image = Math.ceil((gallery_options.fullwidth+start)/gallery_options.thumb_div_width);

	if (start_image<0) start_image = 0

	if (end_image>gallery_options.last_num) {
		end_image = gallery_options.last_num+1;
	}

	for (i=start_image;i<end_image;i++) {
		gallery_preload_image_num = i;
		if (!$('#thumb_'+gallery_options.photos[i].id+' > img').attr('src')) {
				var gallery_load_image = new Image;
				$(gallery_load_image).load(function() {
					id = this.src.split('#thumb_')[1];
					$('#thumb_' + id +' > img').attr('src',this.src);
				}).attr('src',gallery_options.photos[i].src+'#thumb_'+gallery_options.photos[i].id);	
		}
	}
}

function  fetch_slide_to(val) {
	if (gallery_slider_enable) {
        $('.slider').slider('moveTo', val);
    }
}


function gallery_show_next () {

	next_num = Math.round(gallery_previous_num)+1;

	if (gallery_options.last_num<next_num) {
		next_num = 0;
	}
	
	next_id = gallery_options.photos[next_num].id;
	
	fetch_photo_show(next_id,next_num)
	
}

function gallery_preload_next (info) {

	if (info) {
		gallery_load_image = new Image;
		$(gallery_load_image).load().attr('src',info.src);
	} else { 
		next_num = Math.round(gallery_previous_num)+1;
		if (gallery_options.last_num<next_num) {
			next_num = 0;
		}
		next_id = gallery_options.photos[next_num].id;	
		if (gallery_options.photos[next_num].info) {
			gallery_preload_next(gallery_options.photos[next_num].info);
		} else {
			$.getJSON(gallery_options.info_url+next_id, function(json){gallery_preload_next(json)});
		}
	}
	
}

function gallery_show_prev () {
	next_num = Math.round(gallery_previous_num)-1;

	if (next_num<0) {
		next_num = gallery_options.last_num;
	}
	
	
	next_id = gallery_options.photos[next_num].id;
	
	fetch_photo_show(next_id,next_num)
}

function fetch_photo_show (ID,num) {
	 

    
    num = Math.ceil(num);

    num_center = gallery_perpage/2;
	
	move_to = (num-num_center+1)*gallery_options.thumb_div_width-(gallery_options.thumb_div_width/2);
	fetch_slide_to(move_to);
	
	if (gallery_previous_id) {
		$('#thumb_'+gallery_previous_id).parent().removeClass("active");
	}
	gallery_previous_id = ID;
	gallery_previous_num = num
	$('#thumb_'+ID).parent().addClass("active");
	
	gallery_marker.css('left',  Math.ceil(gallery_handle.css('left').replace('px',''))+17+'px');

	if (gallery_options.big_block_hide) {
		gallery_big_block.hide();
	}
	
	gallery_big_image.hide();
	if (gallery_options.usetitle) {
		gallery_title.html('');
	}	
	
	if (gallery_options.photos[gallery_previous_num] && gallery_options.photos[gallery_previous_num].info) {
		fetch_photo_large(gallery_options.photos[gallery_previous_num].info);
	} else {
		$.getJSON(gallery_options.info_url+ID, function(json){fetch_photo_large(json)});
	}
	document.location='#photo-'+ID;
	
}      

function fetch_photo_large(info) {

	if (gallery_options.photos[gallery_previous_num] && gallery_options.photos[gallery_previous_num].id==info.id) {
		gallery_options.photos[gallery_previous_num].info = info;
	}
	
	gallery_load_image = new Image;
	$(gallery_load_image).load(function () {
		gallery_big_image.html('<img src="'+info.src+'" />\n');
		gallery_big_image.show();
		imgObj = gallery_big_image.find('img');
		
		var imgHeight = this.height;
		var imgWidth = this.width;
		var imgAspect = imgWidth/imgHeight;
		if (imgHeight==0) imgHeight = gallery_options.big_photo_height;
		if (imgHeight<gallery_options.big_photo_height) {
			imgWidth = imgHeight*imgAspect;
			useFullscreen = false;
		} else {	
			useFullscreen = true;
			imgHeight = gallery_options.big_photo_height;
			imgWidth = imgHeight*imgAspect;
		}	
		
		imgPadding = (gallery_options.big_photo_height-imgHeight)/2;		
		imgObj.attr({'height':imgHeight, 'width':imgWidth });
		if (!gallery_options.big_block_padding) {
			imgObj.css('padding-top', imgPadding+'px');
		} else {
			gallery_big_block.css('padding-top', imgPadding+'px');
		}
		
		//alert('test'+gallery_big_block.css('padding'));
		//big_blockPadding = Math.ceil(gallery_big_block.css('padding').replace('px',''));
		big_blockPadding = Math.ceil(gallery_options.big_photo_padding);
		big_blockLeft = (gallery_options.fullwidth - imgWidth+big_blockPadding*2)/2;
		//alert('left'+ gallery_options.fullwidth + '::' + imgWidth + '::'+big_blockPadding);
		gallery_big_block.css({'width': imgWidth+'px', 'left': big_blockLeft+'px'});
		
		if (gallery_options.big_block_hide) {
			gallery_big_block.show();
		}
		
		if (gallery_options.usetitle) {
			gallery_title.html(info.title);
		}

		if (gallery_options.import_url) {
			importObj = $('.import_photo a',gallery_menu);
			importObj.click(function () { gallery_import(gallery_options.album_list_url,info.id) } );
		}
		
		if (useFullscreen && gallery_options.fullscreen) {
			gallery_big_image.append('<div class="fullscreen"></div>');
			fullscreenObj = $('.fullscreen',gallery_big_image);
			//alert(big_blockPadding);
			fullscreenTop = big_blockPadding+15;
			fullscreenLeft = imgWidth+big_blockPadding - 35;
			fullscreenObj.css({'left':fullscreenLeft+'px', 'top': fullscreenTop+'px'});
			fullscreenObj.click(function () {openInNewWindow(gallery_options.fullscreen_url + encodeURIComponent(info.src))});
		}
		if (gallery_options.update_photo_num) {
			$('#'+gallery_options.update_photo_num).html(gallery_previous_num+1);
		}		
		
		if (gallery_options.comment_url) {
			fetch_load(gallery_options.comment_url+info.id,'gallery_comments');
		}
		
		gallery_preload_next();
	}).attr('src',info.src);	
}  


        
function gallery_init(options) {
	
	gallery_options=options;
	
	gallery_block = $('#gallery');
	gallery_menu = $('#gallery_menu');
    gallery_container = $('div.sliderGallery');
    gallery_container.html('<div class="thumbs"></div>'+gallery_container.html());
    gallery_inner = $('.thumbs', gallery_container);
    gallery_big_image = $('.big_image', gallery_block);
    gallery_big_block = $('.big_block', gallery_block);
    if (!gallery_options.title_element) {
    gallery_title = $('.title', gallery_block);
    } else {
    gallery_title = $('#'+gallery_options.title_element);
    }
    gallery_prev = $('#gallery > .wrapper > .prev');
    gallery_prev.click(function(){gallery_show_prev();});
    gallery_next = $('#gallery > .wrapper > .next');
    gallery_next.click(function(){gallery_show_next();});

	if (location.hash != "" && location.hash.substr(0, 7) == '#photo-') {
		now_photo_id = location.hash.split('#photo-')[1];
	} else {
		now_photo_id=0;
	}


	gallery_total = options.total;
	if (gallery_options.update_photo_total) {
		$('#'+gallery_options.update_photo_total).html(gallery_total);
	}
	gallery_options.last_num = Math.round(gallery_total)-1;
	gallery_inner.css('width', (gallery_total*gallery_options.thumb_div_width)+'px');

	for (i=0;i<gallery_total;i++) {
 		if (now_photo_id && now_photo_id==options.photos[i].id) {
			gallery_load_id = options.photos[i].id;
			gallery_load_num = i 			
 		} else if (now_photo_id==0 && i==0) {
 			gallery_load_id = options.photos[i].id;
			gallery_load_num = i 			
 		}
 		if (options.photos[i] && options.photos[i].id) {
			gallery_inner.append('<div class="image"><div class="thumb"><a href="javascript:void(0)" num="'+i+'" id="thumb_'+options.photos[i].id+'"><img  /></a></div></div>\n');
			$('#thumb_'+options.photos[i].id).click(function(){
							fetch_photo_show(this.id.replace('thumb_',''),$(this).attr('num'));
						});
		}
	 	

	}

	gallery_handle = $('.handle', gallery_container);
	gallery_marker = $('.marker', gallery_container);		 
	gallery_itemsWidth = gallery_inner.innerWidth() - gallery_container.outerWidth();
	gallery_options.fullwidth = gallery_container.outerWidth();
	gallery_perpage = Math.ceil(gallery_container.outerWidth()/gallery_options.thumb_div_width);
    
        
    if (gallery_total>(gallery_perpage-1)) {
            $('.slider', gallery_container).slider({
                min: 0,
                max: gallery_itemsWidth,
                handle: '.handle',
                stop: function (event, ui) {
                    gallery_inner.animate({'left' : ui.value * -1}, 500);
                    fetch_thumbs_load(ui.value);
                },
                slide: function (event, ui) {
                    gallery_inner.css('left', ui.value * -1,500);
                }
            });
    } else {
    	$('.slider', gallery_container).css('display','none');
    	fetch_thumbs_load (0);
    	gallery_slider_enable = false;
    }
            
   	fetch_photo_show(gallery_load_id,gallery_load_num)
   	
   	if (gallery_options.import_url) {
   		$("#import_photo_dialog > form").attr('action', gallery_options.import_url);
   		$("#import_photo_dialog > form > input[name='type']").attr('value',gallery_options.type)
		$("#import_photo_dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			modal: true,
			closeOnEscape: true,
			resizable: false,
			buttons: {
				'Добавить': function() {
					$('#import_photo_dialog > form').ajaxSubmit();
					$(this).dialog('close');
				},
				'Отмена': function() {
					$(this).dialog('close');
				}
			},
			close: function() {
			}
		});  	
   	}
}

function gallery_import (url,imp_pid) {
	hash = "&t=" +new Date().getTime();
	fetch_load_select (url+hash,$("select[name='aid']",$("#import_photo_dialog > form")));
	//alert('test'+$("input[name='album_title']",$("#import_photo_dialog > form")).attr('value'));
	$("input[name='album_title']",$("#import_photo_dialog > form")).attr('value','');
	$("#import_photo_dialog > form > input[name='pid']").attr('value',imp_pid);
	$('#import_photo_dialog > form').ajaxForm(); 
	$('#import_photo_dialog').dialog('open');
	
}

