/**
 * Grid-A-Licious(tm)
 * Copyright (c) 2008 Suprb - info(at)suprb(dot)com
 *
 * License Agreement: By downloading Grid-A-Licious(tm),
 * you agree to the following: The copyright information 
 * must remain intact in the product.
 *
 * The product may be used for personal use only, no 
 * commercial projects. You are not free to remove the 
 * copyright information (anywhere).
 * 
 * You are not free to use or copy any of the 
 * "grid-a-licious.js" (this file) code on your own products
 * without asking for permission.
 * 
 * Thanks for understanding.
 */


	var MIN_COLS = 2;
	var COL_WIDTH = 220;
	var GAP = 0; 
	
	var offx, offy = 0;
	var maxy = new Array();
	
	//var loadingSequence = '←↑→↓';
	var loadingSequence = '⌜⌝⌟⌞';
	var loopCnt = 0;
	
	var loaded = false;
	var fontsLaded = false;
	var inited = false;
	var checkFontLoad;

	loopLoader();
	loadFonts();
	
	// on site load (DOM READY)
	$(init);	
	
	function init() { 
			if (fontsLaded) {
				offy = $('#allposts').offset().top+77;
				offx = $('#allposts').offset().left;

				arrange();
				initFooter();
				papagaja();
				handleFocus();

				// on window resize, call again
				$(window).resize( arrange );

				// call arrange again in case font behaves funny
				window.clearTimeout(checkFontLoad);
				checkFontLoad = window.setTimeout(function() {
					window.clearTimeout(checkFontLoad);
					arrange();
				}, 1000);

				try {
					if (loadOnScroll == true) {
						initAutoLoader();
					};
				} catch(e) {}

				//	setupFfffoundRollover();
				//	fadeInBoxes();
				//	colorTags();
				//	$('.eachpost').each(function(i){$(this).css('background-color', randomColor())});
				//	$('body').css('background-color', randomColor());
				//	$('body').css('background-image', 'url('+randomImage()+')');
				
				inited = true;
			} else {
				checkFontLoad = window.setTimeout(init, 20);
			}
	}
	
	function initFooter(){
		var footerHeight = $('#footer').height();
		$('#footer').css('bottom', 20 - footerHeight);
		$('#footer').show('fast');
		
		$('#footer').hover(
			function (){
				$('#footer').stop().show().animate({ 
				        bottom: 0
				      }, 200 );
			},
			function (){
				$('#footer').stop().animate({ 
				        bottom: 20 - footerHeight
				      }, 200);	
			}	
		);
	}
	
	function loadFonts() {
		// load google fonts
	     WebFontConfig = {
			google: { families: [ 'Arvo:regular,italic/*,bold,bolditalic*/' ] },
			//google: { families: [ 'Coustard::latin' ] }
			active: function () {
				fontsLaded = true;
			}
	     };
	     var wf = document.createElement('script');
	     wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
	     wf.type = 'text/javascript';
	     wf.async = 'true';
	     var s = document.getElementsByTagName('script')[0];
	     s.parentNode.insertBefore(wf, s);
	}
	
	function initAutoLoader(){
		$('.navigation_group').hide();
		$(window).scroll(onScoll);
	}
	
	function onScoll(){
        if  ($(window).scrollTop() > $(document).height() - $(window).height() - 500){
			if (loaded) loadMorePosts();
        }
	}
	
	function loadMorePosts(){
		loaded = false;
		loopLoader();
		$('#loading').show();
		$('#loading').removeClass('loading').addClass('loadMore');
		
		$.get(location.href+'?gimmeMorePosts=true&offset='+postsOffset+'&numPosts='+numPosts, function(data) {

			$('#posts').append(data);
			
			arrange();

			postsOffset += numPosts;
			
			// call analytics
			try	{ if (gaJsHost != undefined) pageTracker._trackPageview('/scroll/'+postsOffset); }
			catch (e){};
			
			console.log('data: '+data)
			if(data == ""){
				$(window).unbind('scroll');
			}
			
			loaded = true;
			$('#loading').hide();

		}, 'html');      
	}
	
	function loopLoader (){
		if(!loaded){
			window.setTimeout(function() {
			 $('#loading').html(loadingSequence.charAt(loopCnt)+((inited) ? ' <span class="grey">'+(postsOffset+1)+'-'+(postsOffset+numPosts)+'</span>' : ''));
			loopCnt++;
			if (loopCnt >= loadingSequence.length) {
				loopCnt = 0;
			};
			loopLoader();
			}, 200);
		}
	}
	
	var pos, cursor, w , altura= 0;
	
	function arrange() {
		// how many columns fits here?
		var columns = Math.max(MIN_COLS, parseInt($('body').innerWidth() / (COL_WIDTH+GAP)));
		$('.eachpost').css('width',COL_WIDTH  + 'px');
		$('.twocols').css('width', COL_WIDTH*2 + GAP  );
		$('.threecols').css('width', COL_WIDTH*3 + GAP*2);

		for (x=0; x < columns; x++) {
			maxy[x] = 0;
		}
		
		// lets iterate over all posts
		$('.eachpost').each(function(i) {

			pos, cursor, w , altura= 0;
	
			w = (Math.floor($(this).outerWidth() / COL_WIDTH));
			cursor = 0;

			if (w>1) {
				for (x=0; x < columns-(w-1); x++) {
					cursor = maxy[x] < maxy[cursor] ? x : cursor;
				}
				pos = cursor;
				
				for (var x=0; x<w; x++) {
					altura = Math.max(altura, maxy[pos+x]);
				}
				for (var x=0; x<w; x++) 
					maxy[pos+x] = parseInt($(this).outerHeight()-50) + GAP + altura;
					

				$(this).css('left', pos*(COL_WIDTH+GAP) + offx).css('top',altura + offy);
			}
			else {
			
				for (x=0; x < columns; x++) {
					cursor = maxy[x] < maxy[cursor] ? x : cursor;
				}
				$(this).css('left', cursor*(COL_WIDTH+GAP) + offx).css('top',maxy[cursor] + offy);
				
				maxy[cursor] += ($(this).outerHeight()-50) + GAP;
			}
			$(this).css('margin-left', '0px');

			//$(this).css('-webkit-transform', 'rotate('+Math.round(Math.random()*4-2)+'deg)');
			//$(this).css('-moz-transform', 'rotate('+Math.round(Math.random()*4-2)+'deg)');
			
			
		});
		
		loaded = true;
		$('#loading').hide();
		
	}
	
	// comments focus handling
	function handleFocus(){
		var authorText = 'Namn';
		var emailText = 'Mail (obligatoriskt)';
		var urlText = 'URL';
		$("#author").focus(function () { 
			if ($(this).val() == authorText) {$(this).val('')}; 
		});
		$("#email").focus(function () { 
			if ($(this).val() == emailText) {$(this).val('')}; 
		});
		$("#url").focus(function () { 
			if ($(this).val() == urlText) {$(this).val('')}; 
		});

		$("#author").blur(function () { 
			if ($(this).val() == '') {$(this).val(authorText)}; 
		});
		$("#email").blur(function () { 
			if ($(this).val() == '') {$(this).val(emailText)}; 
		});
		$("#url").blur(function () { 
			if ($(this).val() == '') {$(this).val(urlText)}; 
		});
	}
	
	
	//
	// random junk
	//
	
	function fadeInBoxes(){
		$('.eachpost').each(function(i) {
			$(this).css('display', 'none');
			var _this = this;
			window.setTimeout(function(){ setVisible(_this)	}, i*20);		
		});
	}
	
	function setVisible (item) {
		$(item).fadeIn(200);
	}
	
	function randomColor() {
		var hex=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
		var clr="#";
		for (var i=0; i < 6; i++) clr+=hex[Math.floor(Math.random()*hex.length)];
		return clr;
	}
	
	function randomImage() {
		return 'http://blog.lhli.net/wp-content/themes/grid-a-licious_svenska/tapetlagret/'+Math.floor(Math.random()*81)+'.gif';
	}
	
	function setupFfffoundRollover () {
		$('.ffffound small').css('opacity', '0');
		$('.ffffound').hover(
		function () {
			$(this).find('small').stop().show().animate({ 
			        opacity: 1
			      }, 200 );
		},
		function () {
			$(this).find('small').stop().animate({ 
			        opacity: 0
			      }, 200);
		});
	}
	
	function colorTags() {
		$('.tagLink a').each(function(i) {
			if ($(this).text() == 'rgb') $(this).html('<span style="color:#f00">r</span><span style="color:#0f0">g</span><span style="color:#00f">b</span>');
			else if ($(this).text() == 'r'){ $(this).css('backgroundColor','#f00').css('color','#f00');}
			else if ($(this).text() == 'g'){ $(this).css('backgroundColor','#0f0').css('color','#0f0');}
			else if ($(this).text() == 'b'){ $(this).css('backgroundColor','#00f').css('color','#00f');}
			else if ($(this).text() == 'c'){ $(this).css('backgroundColor','#0ff').css('color','#0ff');}
			else if ($(this).text() == 'm'){ $(this).css('backgroundColor','#f0f').css('color','#f0f');}
			else if ($(this).text() == 'y'){ $(this).css('backgroundColor','#ff0').css('color','#ff0');}
			else if ($(this).text() == 'k'){ $(this).css('backgroundColor','#000').css('color','#000');}
			
			//$(this).css('color','#fff');

		})
	}
	
	function papagaja() {
		if (Math.floor(Math.random()*50) == 0) {
			$('body').append('<div id="papagaja"></div>');
			$('#papagaja').addClass('papagaja').hide().delay(5000).fadeIn(500).delay(5000).fadeOut(500);
		}
	}
	

