//shortcut
var bo = blog.options;
var mobile = (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/android/i) && navigator.userAgent.match(/mobile/i));
var scrollbar = {
	getSizes:	function(){
		this.handlerWidth = this.getLength();
		this.maxScroll = -this.handlerWidth + $('#area').width() - 20;
	},
	refreshWidth : function(){
		if(!mobile) return;
		var width = 0;
		this.wrap.children().each(function(){
			width += $(this).width();
		}).end().width(width);
	},
	init	:	function(){
		this.wrap = $('#block-wrap');
		blog.offset = 0;
		this.add(blog.data);
		$.sOff();
		if(!mobile){
			$('#scrollbar').scrollbar({
				size: $('#area').width() / (scrollbar.handlerWidth || $('#area').width()),
				position: -bo.startPos / scrollbar.maxScroll,
				scroll: function(e, ui, animate){
					if(ui.pos > .99) scrollbar.add();
					if(typeof animate == 'undefined') var animate = true;
					
					scrollbar.maxScroll = -scrollbar.handlerWidth + $('#area').width() - 20;
					if(animate /*&& !$.browser.msie*/) scrollbar.wrap.moving({'left': scrollbar.maxScroll * ui.pos + 'px'}, animate.duration || 500, animate.easing || 'easeOutExpo');
					else scrollbar.wrap.css('left', scrollbar.maxScroll * ui.pos + 'px');
				},
				load:function(){
					$(this).trigger('move', [bo.startPos / scrollbar.maxScroll, {duration: 1000, easing: 'easeInOutExpo'}]);
					setInterval(vis.check, 500);
				}
			});		
			$(window).resize(function(){
				$('#scrollbar').trigger('refresh', [{size: $('#area').width() / scrollbar.handlerWidth}]);
			});
			$('#block-wrap').mousedown(function(e){
				var options = {
					int: 50,
					speedLimit: .5,
					brakes: .2
				}
				if(e.target == $('#scrollbar').get(0) || $('#scrollbar').has(e.target).length) 
					return false;
				var start = old = e.pageX, first = true, tap, speed, timerSpeedTimer, old,
				timer = $.now(), speedTimer = setInterval(function(){
						speed = (start-old)/options.int;
					},options.int);
		if(!$.browser.msie) 
				$('body').bind({
					'mousemove.drag'	:	function(e){
						if(e.pageX == start) return false;
						if(!first) tap.css({left: e.pageX, top: e.pageY});
						e.stopPropagation();
						speed = (e.pageX-start)/($.now()-timer)
						timer = $.now();
						if(first){
							first = false;	
							$('#tap').remove();
							$('body').append(
								tap = $('<img />', {id: 'tap', src: '/images/tap.png'})
							);
							tap.css({
								width:0, height: 0, marginTop: 0, marginLeft: 0, opacity: 0, left: e.pageX, top: e.pageY
							}).animate({
								width:50, height: 50, marginTop: -25, marginLeft: -25, opacity: .5
							}, 200);
						}
						var newPos = e.pageX-start;
						old = start;
						start = e.pageX;
						$('#scrollbar').trigger('move', [newPos / scrollbar.maxScroll]);
					},
					'mouseup.drag mouseleave.drag'	:	function(e){
						$(this).unbind('.drag');
						if(typeof tap != 'undefined')
							tap.animate({
								width:0, height: 0, marginTop: 0, marginLeft: 0, opacity: 0
							}, 200, function(){ $(this).remove(); });
						if(first) return false;
						if(speed != 0)
						clearInterval(speedTimer);
						if(Math.abs(speed) > options.speedLimit){
							speedTimer = setInterval(function(){
								if(Math.abs(speed) < 1 / options.int){
									 clearInterval(speedTimer);
									 return false;
								}
								$('#scrollbar').trigger('move', [speed*options.int / scrollbar.maxScroll]);
								speed /= options.brakes+1;
							}, options.int);
						}
					}
				});
				return false;
			}).add('#scrollbar').mousewheel(function(e, delta){
					$('#scrollbar').trigger('move', [((delta>0)?1:-1) * 140/scrollbar.maxScroll]);
					return false;
			});
		}
		if(mobile){
			this.refreshWidth();
			$(window).scroll(function(){
				if($(this).scrollLeft() + $(this).width() > $('body').width() - 100) scrollbar.add();
			}).resize(function(){
				$('#scrollbar').width($(window).width()-40);
			});
			vis.check(true);
		}
		return this;
	},
	add:function(){
		if(this.loading() || blog.offset >= blog.count) return false;
		this.loading(true);
		var oldLength = this.maxScroll, i;
		var hoverTrigger = function(){
			var _this = this;
			$('.block-info', this).hover(function(){
				$(_this).addClass('hover');
			}, function(){
				$(_this).removeClass('hover');
			});
		}
		var append = function(){
		
		//Append		
		for(i=0; blog.data.length || i==0; i++){
			var dom = $.tmpl('template', [scrollbar.parseData()]);
			scrollbar.wrap.children('.block-date:last')
				.children('.block-top').append(dom.children('.block-top').children().each(hoverTrigger)).end()
				.children('.block-bottom').append(dom.children('.block-bottom').children().each(hoverTrigger));
			if(scrollbar.clear){
				scrollbar.addDateBlock().clear = false;	
			}
		}
		
		//Refresh
		scrollbar.getSizes();
		vis.check(true);
		var newLength = scrollbar.maxScroll;
		$('#scrollbar').trigger('refresh', [{length: newLength/oldLength}]);
		scrollbar.loading(false);
		scrollbar.refreshWidth();
		};
		
		//First launch
		if(!this.wrap.children().length){
			 scrollbar.addDateBlock();
			 append();
		}else this.wrap.queue(function(dequeue){
			//AJAX
			$.post(blog.url, {offset: blog.offset}, function(data){
					blog.data = blog.data.concat(data);
					append();
					dequeue();
				}, 'json');
		});
	},
	addDateBlock: function(){
		$('#block-wrap').append('<div class="block-date"><div class="block-top"></div><div class="block-bottom"></div></div>');
		return this;
	},
	getLength: function(){
		var w = 0;
		$('#block-wrap').children().each(function(){
			w += $(this).width();
		});
		return w;
	},
	parseData: function(){
			var bdir = [[],[]];
			for(var i = 0; i < blog.data.length; i++)
				if(blog.data[i]['clear']){
					delete blog.data[i]['clear'];
					scrollbar.clear = true;
					break;
				}else bdir[i%2].push(blog.data[i]);
			blog.data = blog.data.slice(i);
			blog.offset += i;
			return bdir;
	},
	loading : function(method){
		if(typeof method == 'undefined') return this.loadingStat || false;
		var loader = $('#blog-loader').length ? $('#blog-loader') : $('<div id="blog-loader" />').appendTo($('#scrollbar'));
		
		if(method) loader.fadeIn();
		else loader.stop(true).hide();
		
		return this.loadingStat = method;
	}
}

var vis = {
	//newElms - Бул. Обновить список елементов
	check : function(newElms){
		var newElms = newElms || false;
		if(!newElms)
			vis.thumbs = vis.thumbs || $('#block-wrap div.block-info:not(.block-type-text) > a');
		else
			vis.thumbs = $('#block-wrap div.block-info:not(.block-type-text) > a');
		var thumbs = vis.thumbs.filter('.notload:not(.loading):not(.checking)');
		thumbs.each(function(){
			var left = $(this).offset().left, elm = this;
			if(left > -$(elm.parentNode).width() && left < $(document).width()){
				$(elm).addClass('checking')
				setTimeout(function(){
					var left = $(elm).offset().left
					if(left > -$(elm.parentNode).width() && left < $(document).width())
						$(elm).addClass('loading').removeClass('checking').find('img').load(function(){
							$(elm).removeClass('loading notload');
							$(this).hide().fadeIn();
						}).attr('src', function(){
							return $(this).attr('toload');
						});
					else $(elm).removeClass('checking');
				}, 1000);
			}
		});
	}	
}

$(document).ready(function(){
	$.template('template', blog.template);	
	
	//
	if(mobile) $('body').addClass('mobile-mode');
	if($('#block-wrap').length) scrollbar.init();
	tint.hide();
	if($('#area.post').length) post.init();
	//
	$('a[href]').not('[target]').click(function(e){

        if(e.ctrlKey || e.shiftKey || e.metaKey || e.altKey) return true;

        if($(this).hasClass('js')) return false;

        tint.show();

    });
	
	$(window).resize(function(){
			var handlerWidth = 0;
			$('.block-date').each(function(){
				handlerWidth += $(this).width();
			});
			var maxScroll = -handlerWidth + $('#area').width() - 20;
			var left = (maxScroll < parseFloat($('#block-wrap').css('left')))? maxScroll : $('#block-wrap').css('left');
	});
});
var tint = {
	show : function(){
		$('#href-tint').addClass('load').show();
	},
	hide : function(callback){
		$('#href-tint').fadeOut(2000, callback || $.noop);
	}	
}

var post = {
	init: function(){
		if(mobile) return $('body').addClass('mobile-post');
		
		var post = $('#block-post');
		var slide, scrollb;
		post.wrapInner($('<div id="post-slide" />'))
		slide = $('#post-slide');
		post.prepend(scrollb = $('<div class="post-scrollbar" />'));
		$('body').mousewheel(function(e, delta){
				scrollb.trigger('move', [((delta>0)?-1:1) * 80/Math.abs(slide.outerHeight() - post.height())])
			});
		scrollb.scrollbar({
			vert: true,
			scroll: function(e, pos){
				slide.css('top', -pos.pos * Math.abs(slide.outerHeight() - post.height()));
			}
		}).selectHover();
		
		var resize = function(){
			var aHeight = $(window).height();
			post.height(aHeight);
			scrollb.height(aHeight - 230);
			if(aHeight >= slide.outerHeight())
				scrollb.hide().trigger('refresh', [{size: 1, pos: 0}, true]);
			else 
				scrollb.show().trigger('refresh', [{size: aHeight / slide.outerHeight()}, true]);
		};
		$(window).resize(resize);
		resize();
		
		$('img', post).load(resize);
	}	
}
