$(document).ready(function(){
	
	bind_bg_switch();
	
	if ($('ul.gallery-previews').html() != null) {
	
		$('ul.gallery-previews li').hover(function(){
			$(this).addClass('hover');
			return false;
		},function(){
			$(this).removeClass('hover');
			return false;
		});
		
		$('.tags a, .big-tags a').click(function(){
			window.tag = $(this).text();
			$('a.active, dd.active').removeClass('active');
			$('h1 i').css('visibility','visible').find('span').text(window.tag);
			$('ul.gallery-previews li').hide();
			$('.tags a:contains("' + window.tag + '")').each(function(){
				if ($(this).text() == window.tag) {
					$(this).addClass('active');
					$(this).parent().parent().show();
				}
			});
			$('.big-tags a:contains("' + window.tag + '")').each(function(){
				if ($(this).text() == window.tag) {
					$(this).parent().addClass('active');
				}
			});
			return false;
		});
		
		$('h1 span').click(function(){
			$('h1 i').css('visibility','hidden');
			$('a.active, dd.active').removeClass('active');
			$('ul.gallery-previews li').show();
			return false;
		});
		
	}
	
	if ($('.gallery-table').html() != null) {
		
		$('.big-tags a').click(function(){
			window.tag = $(this).text();
			$('h1 i')
				.css('visibility','visible')
				.find('span').text(window.tag);
			$('.big-tags dd.active').removeClass('active');
			$(this).parent().addClass('active');
			$('.screen').css('left','0');
			
			prts = document.location.href.split('#');
			prts[1] = window.tag;
			document.location.href = prts.join('#');
			
			init_gallery();
			return false;
		});
		
		$('h1 span').click(function(){
			$('h1 i').css('visibility','hidden');
			$('.big-tags dd.active').removeClass('active');
			prts = document.location.href.split('#');
			document.location.href = prts[0];
			
			window.tag = null;
			init_gallery();
			return false;
		});
		
		$('.scroll .left').click(function(){
			left = parseInt($('.screen').css('left')) + 123;
			if (left > 0) {
				left = 0;
			}
			$('.screen').animate({'left':left + 'px'},500);
			$('.handler').animate({'left': (-1) * left / window.ratio + 'px'},500,function(){
				set_position(0);
			});
		});
	
		$('.scroll .right').click(function(){
			left = parseInt($('.screen').css('left')) - 122;
			if (left < ($('.screen ul').length - 7) * (-122)) {
				left = ($('.screen ul').length - 7) * (-122);
			}
			$('.screen').animate({'left':left + 'px'},500);
			$('.handler').animate({'left': (-1) * left / window.ratio + 'px'},500,function(){
				set_position(0);
			});
		});
//	}
//	if ($('.scroll').html() != null) {

		prts = document.location.href.split('#');
		if (prts.length == 2) {
			window.tag = decodeURI(prts[1]);
			$('h1 i')
				.css('visibility','visible')
				.find('span').text(window.tag);
		} else {
			window.tag = null;
		}
		init_gallery();
	}

	if ($('.thumbs-line').html() != null) {

		$('.thumbs-line').bind('slide_select',function(){
			window.li_counter = 0;
			$('.thumbs-line li').each(function(){
				window.li_counter++;
				if ($(this).hasClass('active')) {
					if (window.li_counter < 4) {
						left = 0;
						$('.thumbs-line').animate({'left':'0'},400);
					} else {
						qty = $('.thumbs-line li').length;
						if (window.li_counter < (qty - 3)) {
							left = -1 * (window.li_counter - 4) * 122;
						} else {
							left = -1 * (qty - 7) * 122;
						}
						$('.thumbs-line').animate({'left':left},400);
					}
					
					left_n = (Math.floor(left / (-122) + 0.5) + 1);
					right_n = (Math.floor(left / (-122) + 0.5) + 1) + 6;
					if (right_n > $('.thumbs-line li').length) {
						right_n = $('.thumbs-line li').length;
					}
					$('.handler .left').html(left_n);
					$('.handler .right').html(right_n);
					
					$('.handler').animate({'left':(left / window.ratio * (-1) + 'px')},200);
				}
			});
			
		});
		
		$('.scroll .right').click(function(){
			window.scroll_click_flag = 0;
			$('.thumbs-line li').each(function(index){
				if (window.scroll_click_flag)
					return;
				if ($(this).hasClass('active')) {
					if ($('.thumbs-line li:eq(' + (index + 3) + ')').html() != null) {
						$('.thumbs-line li:eq(' + (index + 3) + ')').find('a').click();
						window.scroll_click_flag = 1;
					}
				}
			});
		});
	

		$('.scroll .left').click(function(){
			window.scroll_click_flag = 0;
			$('.thumbs-line li').each(function(index){
				if (window.scroll_click_flag)
					return;
				if ($(this).hasClass('active')) {
					if ($('.thumbs-line li:eq(' + (index - 3) + ')').html() != null) {
						$('.thumbs-line li:eq(' + (index - 3) + ')').find('a').click();
						window.scroll_click_flag = 1;
					}
				}
			});
		});
	

		
		prts = document.location.href.split('#');
		if (prts.length == 2 && parseInt(prts[1]) > 0) {
			li_id = prts[1];
		} else {
			li_id = $('.thumbs-line li:eq(0)').attr('class').replace('id-','');
		}

		$('.id-' + li_id).addClass('active');

		window.pic_url = $('li.active').find('img').attr('src').replace('120x80xM','0x408xIH');
		
		$('.big-pic img, .big-pic dd').css({'opacity':'0'});
		if (navigator.userAgent.indexOf ('Opera') == -1) {
			$('.big-pic img').attr('src','about:blank');
		}
		$('.big-pic img').attr('src',window.pic_url);
		if (navigator.userAgent.indexOf ('Opera') != -1) {
			try_load_photo();
		}

		tags = $('.active .li-tags').html();
		$('.big-pic dd .tags').html('<strong>Тэги:</strong> ' + tags);

		fileinfo = $('.active .li-file-info').html();
		$('.big-pic dd .file-info').text(fileinfo);
		
		description = $('.active img').attr('title');
		$('.big-pic dd .photo-description').text(description);
		
		pext = window.pic_url.split('.');
		ext = pext[pext.length-1];
		
		highres_link = window.page_url + 'highres/' + li_id + '.' + ext;
		$('a.download-highres').attr('href',highres_link);
		
		$('.thumbs-line a').click(function(){
			
			$('.thumbs-line li.active').removeClass('active');
			$(this).parent().addClass('active');
			
			if ($('li.active').find('img').attr('src').replace('120x80xM','0x408xIH') == window.pic_url) {
				return false;
			}
			
			window.pic_url = $('li.active').find('img').attr('src').replace('120x80xM','0x408xIH');
			
			$('.big-pic img, .big-pic dd').animate({'opacity':'0'},50,function(){
				
				$('#indicator').show();
				
				if (navigator.userAgent.indexOf ('Opera') == -1) {
					$('.big-pic img').attr('src','about:blank');
				}
				$('.big-pic img').attr('src',window.pic_url);
				if (navigator.userAgent.indexOf ('Opera') != -1) {
					try_load_photo();
				}
				
				tags = $('.active .li-tags').html();
				$('.big-pic dd .tags').html('<strong>Тэги:</strong> ' + tags);
	
				fileinfo = $('.active .li-file-info').html();
				$('.big-pic dd .file-info').text(fileinfo);
				
				description = $('.active img').attr('title');
				$('.big-pic dd .photo-description').text(description);
			
			});
			
			li_id = $('.thumbs-gallery li.active').attr('class').replace('active','').replace('id-','').replace(' ','');
			
			pext = window.pic_url.split('.');
			ext = pext[pext.length-1];
		
			highres_link = window.page_url + 'highres/' + li_id + '.' + ext;
			$('a.download-highres').attr('href',highres_link);

			prts = document.location.href.split('#');
			prts[1] = li_id;
			document.location.href = prts.join('#');
			
			$('.thumbs-line').trigger('slide_select');
			
			return false;
			
		});

		qty = $('.thumbs-line li').length;
		if (qty < 8) {
			$('.scroll').hide();
			return;
		} else {
			$('.scroll').show();
		}
	
		window.width = 122 * $('.thumbs-line li').length - 2;
		window.ratio = window.width / 854;
			
		//$('.handler').animate({'width':Math.floor(802 / window.ratio) + 'px','left':'0'},200,);
		$('.handler').css({'width':Math.floor(802 / window.ratio) + 'px','left':'0'});//,200,);

		window.ratio = (($('.thumbs-line li').length) * 122 - 856) / (802 - parseInt($('.handler').css('width')));
		
		$('.scroll .right span').html(qty);
			
		window.scroller = $('.handler')[0];
		window.scrollerBar = $('.scroll')[0];
			
		window.scroller.onmousedown = drag;
		window.scroller.onmousemove = move;
		$(document)[0].onmouseup = drop;
			
		$('.thumbs-line').trigger('slide_select');
		
	}
	
	
});

function fill_matrix() {

	html = '<ul>\n';
	j = 0;
	for (i=0;i<window.pics.length;i++) {

		if (window.tag != null && window.pics[i].indexOf(',' + window.tag + ',') == -1){
			continue;
		}
		
		parts = window.pics[i].split('/');
		html += '\t<li><a href="' + window.page_url + window.set_id + '/single.html#' + parts[0] + '" title="' + parts[2] + '"><img src="' + window.root_url + 'thumb/120x80xM/files/photo/' + parts[0] + '.' + parts[1] + '" /></a></li>\n';
		if (j > 0 && Math.round((j+1) / 6) * 1.0 == ((j+1) / 6)) {
			html += '</ul>\n<ul>\n';
		}
		j++;
	}
	html += '</ul>';
	html = html.replace('<ul>\n</ul>','');
	$('.screen').html(html);
	
}


function init_gallery() {

	fill_matrix();

	qty = $('.screen ul li').length;
	if (qty < 42) {
		$('.scroll').hide();
		return;
	} else {
		$('.scroll').show();
	}

	window.width = 122 * $('.screen ul').length - 2;
	window.ratio = window.width / 854;

	if (window.ratio > 15) {
		window.ratio = 15;
	}
	
	$('.handler').css({'width':Math.floor(802 / window.ratio) + 'px','left':'0'});
		
	window.ratio = ($('.screen ul').length * 122 - 856) / (802 - parseInt($('.handler').css('width')));

	$('.screen').css('left','0');
	
	$('.scroll .right span').html(qty);
		
	window.scroller = $('.handler')[0];
	window.scrollerBar = $('.scroll')[0];
		
	window.scroller.onmousedown = drag;
	window.scroller.onmousemove = move;
	$(document)[0].onmouseup = drop;
	
}

var can_drag = false;

function drag(event){
	
    if (!event){
        event = window.event;
    }
   
	can_drag = true;
	
    window.shift_x = event.clientX;
	window.mouse_x_pos = mouse_x(event);
	
    return false;
	
}

function move(event){

	if (!event){
        event = window.event;
    }
    
    if (can_drag) {
        set_position(mouse_x(event) - window.mouse_x_pos);
		window.mouse_x_pos = mouse_x(event);
        block_event(event);
    }
	
    return false;
	
}

function drop(){

	can_drag = false; 
	
}

function set_position(diff) {

	new_val = parseInt($('.handler').css('left')) + diff;
	if (new_val < 0) {
		new_val = 0;
	}
	
	if (new_val > 802 - parseInt($('.handler').css('width'))) {
		new_val = 802 - parseInt($('.handler').css('width'));
	}
	if ($('.screen').html() != null) {
		$('.screen').css('left','-' + Math.ceil(new_val * window.ratio) + 'px');
	} else {
		$('.thumbs-line').css('left','-' + Math.ceil(new_val * window.ratio) + 'px');
	}
	
	if ($('.screen').html() != null) {
		left_n = (Math.floor(new_val * window.ratio / 122 + 0.5) + 1) * 6 - 5;
		right_n = (Math.floor(new_val * window.ratio / 122 + 0.5) + 1) * 6 + 36;
		if (right_n > $('.screen ul li').length) {
			right_n = $('.screen ul li').length;
		}
	} else {
		left_n = (Math.floor(new_val * window.ratio / 122 + 0.5) + 1);
		right_n = (Math.floor(new_val * window.ratio / 122 + 0.5) + 1) + 6;
		if (right_n > $('.thumbs-line li').length) {
			right_n = $('.thumbs-line li').length;
		}
	}
	$('.handler .left').html(left_n);

	$('.handler .right').html(right_n);
	
	$('.handler').css('left',new_val + 'px');
    return false;
	
}

function block_event(event) {

    if (!event){
        event = window.event;
    }
	
    if(event.stopPropagation) {
		event.stopPropagation();
	} else {
		event.cancelBubble = true;
	}
    if(event.preventDefault) {
		event.preventDefault();
	} else {
		event.returnValue = false;
	}
	
}

function mouse_x(e) {

	var x = 0;

	if (!e) e = window.event;
	
	if (e.pageX) {
		x = e.pageX;
	}
	else if (e.clientX) {
		x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
	}
  
	return x;
  
}

function bind_bg_switch() {

	$('ul.switch-backgrounds li span').click(function(){
	
		span_class = $('ul.switch-backgrounds li.active').attr('class').replace('active','').replace('bg-','').replace(' ','');
		newhtml = '<span class="' + span_class + '">' + $('ul.switch-backgrounds li.active').text() + '</span>';
		$('ul.switch-backgrounds li.active').html(newhtml).attr('class','');
		
		$('body').attr('class',$(this).attr('class'));

		$(this).parent().addClass('bg-' + $(this).attr('class') + ' active');
		newhtml = $(this).text() 
	+ '<i class="crn c-tl"></i>'
	+ '<i class="crn c-tr"></i>'
	+ '<i class="crn c-bl"></i>'
	+ '<i class="crn c-br"></i>';		
		$(this).parent().html(newhtml);
		
		$.get('?bg_color=' + $(this).attr('class'));
		
		bind_bg_switch();
		
	});
	
}

function loaded_photo() {

	$('#indicator').hide();
	$('.big-pic img').animate({'opacity':'1'},500,function(){
		$('.big-pic dd').animate({'opacity':'1'});
	});
		
}

function try_load_photo() {

	if ($('.big-pic img')[0].complete) {
		loaded_photo();
	} else {
		window.setTimeout(".big-pic img",1000);
	}

} 
