function debug($obj){if(window.console && window.console.log){window.console.log($obj);}}
(function($)
{
	
   $.fn.Nav = function(settings)
   {
    if (settings) $.extend(config, settings);
      this.each(function()
		{
      
			var $self   = $(this),
				$navs   = $self.find('a'),
				_iphone = ((navigator.userAgent.match(/Android/i)) || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
			
			$(document)
			.bind('KEYBOARD_KEY',on_keyboard_key)
			.bind('click',on_click);
			
			function on_keyboard_key(e,id)
			{
				$navs.each(function()
				{
					if ($(this).attr('rev')==id)
					location.href = $(this).attr('href');
				});        
        	}
			
       		function on_click(e){}        
        
      });
   
   }

   $.Post = {
      
      version: '1.0.9',
      mobile:  false
      
   };
   
   $.fn.Post = function(settings) {
     
     var config = {},
        $body            = $('body'),
        $html            = ($.browser.mozilla || $.browser.msie) ? $('html') : $body,
        $wrapper         = $('#grid-wrapper'),
        _sadBrowser      = $.browser.opera || ($.browser.msie && $.browser.version.indexOf('7.')>-1),
        _iphone          = ((navigator.userAgent.match(/Android/i)) || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
    
     if (settings) $.extend(config, settings);
  
     
  
     this.each(function() { 
 
          var $self            = $(this),
              $article_content = config.CONTENT,
              _column_width    = config.COLUMN_WIDTH ? config.COLUMN_WIDTH : 240,
			  _container_width = 90000,
              _speed           = config.SPEED ? config.SPEED : 650,
              _ease            = config.EASE ? config.EASE : 'easeInOutQuart',
              _loadingnext     = false,
              _shift           = false,
              _pagewidth       = 1,//$body.hasClass('category-cover') || $body.hasClass('home') ? 3 : 1,
              _is_feature      = $wrapper.hasClass('site-features'),
              _swipe_offset    = 0,
              active_col       = 0,
              active_row       = 0,
              total_col        = $self.find('.grid-item').length-1;

          //if (_is_feature) total_col+=2;
            
          $.Post.self = $self;  
            
          $self.PostNav();
          
          $body
          .bind('LOADED',onloaded);
                    
          $(document)
          .bind('KEYBOARD_RIGHT',on_key_right)
          .bind('KEYBOARD_LEFT',on_key_left)
          .bind('KEYBOARD_UP',on_key_up)
          .bind('KEYBOARD_DOWN',on_key_down)
          .bind('KEYBOARD_SHIFT',on_shift)
          .bind('KEYBOARD_RELEASE',on_key_release);
          
          $self
          .bind('NEXT',on_key_right)
          .bind('PREV',on_key_left);
          
          setTimeout(init_view,1);
          
          function init_view()
		  {
			reset_width();
            seek();
          } 
          
		  function reset_width()
		  {
			 _container_width = (total_col+2)*_column_width;
			 $article_content.width(_container_width);
		  }
		  
          function seek(position)
		  {
            if (_sadBrowser)
              $article_content.stop().animate({marginLeft:-_column_width*_pagewidth*active_col+'px'},_speed,_ease);
			else
              $self.stop().animate({scrollLeft:_column_width*_pagewidth*active_col},_speed,_ease);
          }
                    
          function on_key_release(e)
		  {
            _shift = false;
          }
          
          function on_shift(e)
		  {
            _shift = true
          }
          
          function on_key_right(e)
		  {
			if($("#colorbox").is(":visible")) return;
            active_col++;
            if (active_col>total_col) active_col = total_col;
            if (active_col>total_col-4 && !_loadingnext) load_next();
            seek();
          }
          
          function on_key_left(e)
		  {
			if($("#colorbox").is(":visible")) return;
			if (active_col==total_col) active_col-=3;
			active_col--;
			if (active_col<0) active_col = 0;              
			seek();
          }
          
          function on_key_up(e)
		  {
			  if($("#colorbox").is(":visible")) return;
              active_row--;
              if (active_row<0)active_row = 0;
              e.preventDefault();
			  
			  var scrolltop = $html.scrollTop();
			  var defaultscroll = 300*active_row;
			  var scrollt = defaultscroll > scrolltop ? scrolltop : defaultscroll;
			  
			if($.browser.opera)
				$.scrollTo(scrollt+"px",_speed,{easing:_ease});
			else
				$html.stop().animate({scrollTop:scrollt},_speed,_ease);
          }
          
          function on_key_down(e)
		  {
			if($("#colorbox").is(":visible")) return;
			
			var maxscroll = $body.height() - $html.height();
				maxscroll = maxscroll == 0 ? $body.height()-$(window).height():maxscroll;
			
			if($html.scrollTop() >= maxscroll)
			{
				active_row = Math.ceil(maxscroll/300);
				if($.browser.opera)
					$.scrollTo(maxscroll+"px",_10,{easing:_ease});
				else
					$html.stop().animate({scrollTop:maxscroll},10);
				return;
			}
			
			active_row++
			e.preventDefault();
			if($.browser.opera)
				$.scrollTo((300*active_row)+"px",_speed,{easing:_ease});
			else
			$html.stop().animate({scrollTop:300*active_row},_speed,_ease);
          }
                    
          function load_next()
		  {
            if (!$body.hasClass('single')){_loadingnext = true; $body.triggerHandler('APPEND',(total_col+1));}
            else  return;
                     
          }
          
          function onloaded(e,append)
		  {
            total_col = $self.find('.grid-item').length-1;
			reset_width();
            _loadingnext = false;
          }
          
      }); 
      
      return this;
    
    
  } 


  $.fn.PostNav = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
      
      
          var $self   = $(this),
              $next   = $('#overlay-right'),
              $next_a = $next.find('a'),
              $prev   = $('#overlay-left'), 
              $prev_a = $prev.find('a'),
              $html   = ($.browser.mozilla || $.browser.msie) ? $('html') : $('body'),
              _iphone = ((navigator.userAgent.match(/Android/i)) || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
              
          $(document)
          .bind('KEYBOARD_RIGHT',on_key_right)
          .bind('KEYBOARD_LEFT',on_key_left)
          .bind('KEYBOARD_RELEASE',on_key_release);
          
          $next
          .css({display:'block'})
          .bind('click', function(e) { $self.triggerHandler('NEXT'); e.preventDefault() })
          .bind('mouseenter',on_next_enter)
          .bind('mouseleave',on_next_leave);
          
          
          $prev
          .css({display:'block'})
          .bind('click', function(e) { $self.triggerHandler('PREV'); e.preventDefault() })
          .bind('mouseenter',on_prev_enter)
          .bind('mouseleave',on_prev_leave);
          
          $(window)
          .bind('scroll',on_scroll);
          
          function on_key_right(e)
		  {
			if($("#colorbox").is(":visible")) return;
            $next_a.addClass('key-active');
          
          }
          
          function on_key_left(e)
		  {
			if($("#colorbox").is(":visible")) return;
            $prev_a.addClass('key-active');
          }
          
          function on_key_release(e)
		  {
            $next_a.removeClass('key-active');
            $prev_a.removeClass('key-active');
          }
          
          
          function on_next_enter(e)
		  {
            $next_a.stop();
            $next.bind('mousemove',on_next_move)
          }
          
          function on_next_leave(e)
		  {
            $next.unbind('mousemove',on_next_move)
            $next_a.animate({top:$html.attr('scrollTop') + 200},500,'easeInOutQuart')
          }
          
          function on_next_move(e)
		  {
            $next_a.css({top:e.pageY - $next.offset().top})
          }
          
          function on_prev_enter(e)
		  {
            $prev_a.stop();
            $prev.bind('mousemove',on_prev_move)
          }
          
          function on_prev_leave(e)
		  {
              $prev.unbind('mousemove',on_prev_move)
              $prev_a.animate({top:$html.attr('scrollTop') + 200},500,'easeInOutQuart')
          }
          
          function on_prev_move(e)
		  {
            $prev_a.css({top:e.pageY - $prev.offset().top})
          }
          
          function on_scroll(e)
		  {
            var t = (!_iphone) ? $html.attr('scrollTop') + 200 : _getScroll().scrollTop
            $prev_a.css({top:t})
            $next_a.css({top:t})
          }
          
          function _getScroll()
		  {
    		return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};
		  }

      
      });
      
  };
  


   $.fn.PostContent = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
 
          var $body            = $('body'),
              $self            = $(this),
              xmlhttp_uri      = '',
              _offset          = 0,
              _append          = false,
              _loading          = false,
			  _empty			= false;
              
          $body
          .bind('FILTER',on_filter)
          .bind('APPEND',on_append)
          .bind('REPOST',on_repost);
          
          $.ajaxSetup({
			         cache: false,
			         dataType: 'html',
			         global: false,
			         timeout: 5000
		        });
		        
          function on_filter(e,uri,ignore)
		  {
            if (!ignore)
			{
				xmlhttp_uri = uri;
				_offset = 0;
				_append = false;
				outro();
            }

          }
          
          function on_append(e,count) 
		  {
			  if(_empty) return;
            _offset = count;
            _append = true;
            outro();
          }
          
          function on_repost(e,count)
		  {
            xmlhttp_uri = '?offset='+count;
            outro();
          }
          
          function outro()
		  {
			if (!_append)
			{
				$self.html('');
				$self
				.addClass('ajax-loading')
				.animate({opacity:1},750,'easeOutQuart',load)
			}else load();
            
          }
          
          function load()
		  {
			if(_loading) return;
            _loading = true;
            $.ajax({
              beforeSend: before_send,
              error: on_error,
              success: on_success,
              data:{xmlhttp: true,offset: _offset},
              url: xmlhttp_uri
            });
            
          }
          
          function before_send()
		  {
			$self.width(9000);
            if (!_append)
              $body.triggerHandler('FILTER_OUT');
            else
             $('<div id="content-loader"></div>').appendTo($self);
          }
          
          function on_success(response)
		  {
          
            if (!_append) {$self.css({opacity:0}); }
            
			$self.removeClass('ajax-loading')
			$('#content-loader').remove();
			$self.append(response); 
			//$self.stop().animate({opacity:1},1000,'easeOutQuart')
			$body.triggerHandler('LOADED',_append);
			_empty = response=='';
			_loading = false;
			$(".gallery").gallery();
			$(".post-body img.size-thumbnail").parent("a").each(function(){$(this).colorbox({rel:Math.random()});});
			$("img").parent("a").css({border:0});
			font();
          }
          
          function on_error(e) {}
          
      
      });
      
    }
    
    
$.fn.gallery = function()
{
	this.each(function()
	{
		var $self		= $(this).hide()
			,$items		= $self.find("a")
			,count  	= $items.length
			,$new		= $('<div class="post-gallery" />').insertAfter($self)
			,$slider 	= $('<div class="post-gallery-slider" />').appendTo($new)
			,$container = $('<div class="post-gallery-content" />').appendTo($slider)
			,$page		= $('<div class="post-gallery-pagination chalet"><span class="gallery-count" /><a href="" class="post-gallery-zoom" /><div class="clear" /></div>').appendTo($new)
			,$count		= $page.find(".gallery-count").html('1 / '+count)
			,$zoom 		= $page.find('.post-gallery-zoom').html('[ + ]').openGallery()
			,width		= 300
			,_sadBrowser= $.browser.opera || ($.browser.msie && $.browser.version.indexOf('7.')>-1)
			,galleryid 	= $self.attr('class').match(/galleryid-[\d]+/i)[0];
		
		$container.append($items);
		$slider.append('<div class="clear" />');
		$self.remove();
		
		$items.bind("click"
		,function(e)
		{
			if(typeof e.altKey == "undefined") return;
			$container.find(".current-thumb").removeClass('current-thumb');
			if($(this).next("a").length==1)
			{
				var index = $items.index(this)+1;
				if (_sadBrowser)
					$container.stop().animate({marginLeft:-width*index},400,'easeInOutQuart');
				else
					$slider.stop().animate({scrollLeft:width*index},400,'easeInOutQuart');
				
				$count.html((index+1)+" / "+count);
				$(this).next("a").addClass('current-thumb');
			}
			else
			{
				if (_sadBrowser)
					$container.stop().animate({marginLeft:0},400,'easeInOutQuart');
				else
					$slider.stop().animate({scrollLeft:0},400,'easeInOutQuart');
				
				$count.html("1 / "+count);
				$items.eq(0).addClass('current-thumb');
			}
			
			font();
			return false;
		})
		.each(function(){$(this).colorbox({rel:galleryid,title:$(this).attr("title")});})
		.eq(0).addClass('current-thumb');
	 		
	});
	
}
	
						
$.fn.openGallery = function()
{
	return this.each(function()
	{
		$(this).bind("click",function(){debug(1);$(this).parent().parent().find(".current-thumb").trigger("click");return false;});
		
	});
};


})(jQuery);


jQuery(function()
{
	(function($){
	
		$(document).Keyboard();
		$('div[scope=PostContent]').PostContent();
		$('div[scope=Post]').Post({
			   WRAPPER:$('#container'),
			   CONTENT:$('#grid-wrapper-slide'),
			   COLUMN_WIDTH:320,
			   SPEED:800,
			   EASE:'easeOutQuart'
			});
		
		$(".gallery").gallery();
		$(".post-body img.size-thumbnail").parent("a").each(function(){$(this).colorbox({rel:Math.random()});});
		$("img").parent("a").css({border:0});
		$("#show-tooltip").hover(function(e)
		{
			var $self = $(this);
			//var off = $self.offset();
			var tp = $('<div id="keyboard-tooltip" />')
						.css("top",(e.pageY - 15) + "px")
						.css("left",(e.pageX + 15) + "px")
						.appendTo("body");
		},function(){$("#keyboard-tooltip").remove();})
		.mousemove(
			function(e)
			{
				$("#keyboard-tooltip")
					.css("top",(e.pageY - 15) + "px")
					.css("left",(e.pageX + 15) + "px");
			});;
		font();
		
		if($.browser.safari)// && 
		{
			if(navigator.userAgent.indexOf('Mac') != -1)
			$("span.line-trough").css({backgroundPosition:'0 11px'});
			else
			$("span.line-trough").css({backgroundPosition:'0 14px'});
		}
				
 })(jQuery);
});

function font()
{
	Cufon.replace('.chalet,h2.post-title',{ fontFamily: 'chalet',letterSpacing:'-1px'});	
}

