/*	Provjera JS-a
*/
$('html').addClass('js');

/*	Funckije
*/
function fixDate(date) {
	var base = new Date(0);
	var skew = base.getTime();
	if (skew > 0) { date.setTime(date.getTime() - skew); }
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function activateHeader () {
	$("#info.collapsable").hide(0);
    $("#toggleInfo").click(function () {
		if ($(this).hasClass('show')) { 
			$(this)
				.text ('Hide info')
				.removeClass ('show');
		}
		else { 
			$(this)
				.text ('Show info')
				.addClass ('show');
		}
	  $("#info.collapsable").fadeToggle(150);
    });
}

/*	zapisivanje dimenzija prozora u cookie na resize
*/
$(window).resize(function () { 
    var wheight = $(window).height() - $('#searchContainerTop, #searchContainerCenter').outerHeight(); 
	var wwidth = $(window).width();
	//document.cookie = 'wh='+wheight+' '+wwidth;
	createCookie ('wh', wheight+' '+wwidth, 7);
});

jQuery.fn.fadeToggle = function(speed, easing, callback) { 
   return this.animate({opacity: 'toggle'}, speed, easing, callback); 
}; 

/*	DOM ready
*/
$(function() {
	
	/*	image preload
	*/ 
	
	var searchBoxHeight = $('#searchContainerCenter, #searchContainerTop').outerHeight();
	
	$('#header').css ({top: (searchBoxHeight + 20) + 'px'});	
	$('#pics').css ({marginTop: searchBoxHeight + 'px'});
	var wheight = $(window).height() - searchBoxHeight; 
	var wwidth = $(window).width();
	
	/*	Cookie
	*/
	if ($('#header').length > 0) {
		if (readCookie ('wh') === null) {
			createCookie ('wh', wheight+' '+wwidth, 7);
			var item = gup ('item');
			var container = $('#content');
			var header = container.html();	
			container.load (
				"/_ajax/getPics.php?width=" + wwidth + "&height=" + wheight + "&item=" + item,
				"",
				function () { 
					activateSlideShow ();
					container.prepend (header);
					activateHeader ();
				}
			);
		}
		else {
			activateSlideShow ();
			activateHeader ();
		}
	}
	else {
		createCookie ('wh', wheight+' '+wwidth, 7);
	}
	
	/*	Keyup event na #searchField
	*/
	var yoffset = $("#searchContainerTop, #searchContainerCenter").height();
	
	$('#searchField').keyup (function () {
		var word = this.value;
		word = word.toLowerCase();
		word = trim (word);
		var izlaz1=""; 
		var izlaz2=""; 
		var izlaz="";
		var searchResults = $("#searchResults");
		var searchContainer = $("#searchContainerTop, #searchContainerCenter");
		//alert(yoffset);
		
		if (word!=="" && word.length>0) {
			for (x in tag_dictionary) {
				tmp=tag_dictionary[x].toLowerCase();
				if(tmp.indexOf(word)!=-1) { izlaz1+="<a href='index.php?item="+tag_dict_url[x]+"'>"+tag_dictionary[x]+"</a> &bull; "; }
			}
			for (x in page_dictionary) {
				tmp=page_dictionary[x].toLowerCase();
				if(tmp.indexOf(word)!=-1) { izlaz2+="<a href='index.php?item="+page_dict_url[x]+"'>"+page_dictionary[x]+"</a> &bull; "; }
			}
			if (izlaz1!=="") { izlaz += "<strong>Tags: </strong>"+izlaz1; }
			if (izlaz2!=="") { izlaz += "<strong>Pages: </strong>"+izlaz2; }
			izlaz = izlaz.substring(0, izlaz.length-8); 
			searchResults.html(izlaz);
			if (izlaz === "") { var next_height = 0; }
			else { var next_height = searchResults.outerHeight(); }
			searchContainer.stop().animate (
				{ height: next_height+yoffset+"px"}, 
				200, 
				function()
					{searchResults.css({'height':'auto'});}
				);
		}
		else {
			searchResults.html("");
			searchContainer.stop().animate(
			{ height: yoffset+"px"}, 
			200, 
			function()
				{searchResults.css({'height':'auto'});}
			);
		}
	});
	
	// Grid and item navigation
	// Izracun velicine group_containera 
	var group_container_h =$($("#parentDiv > div")[0]).height();
	$("#navi_down").bind("click",	function(){
					var animationSpeed = 200;
					var margin_step = 250;
					var group_container = $("#group_container");
					var grid_margin_max = $(window).height()-group_container_h;
					//alert(temp);
					var grid_margin = parseInt($("#group_container").css("margin-top").replace("px",""), 10);			
					// while ima smisla tj. "margin" nije veci od "div-screen.y"
					if (Math.abs(grid_margin) < Math.abs(grid_margin_max + margin_step)) { grid_margin -= margin_step; }
					else { grid_margin = grid_margin_max; }
					group_container
						.stop()
						.animate({marginTop:grid_margin+"px"}, animationSpeed);
						//.css ({marginTop: grid_margin+'px'});
				});
	$("#navi_up").bind("click",	function(){
					var animationSpeed = 200;
					var margin_step = 250;
					var group_container = $("#group_container");
					var grid_margin = parseInt($("#group_container").css("margin-top").replace("px",""), 10);			
					// while ima smisla tj. "margin" nije veci od "div-screen.y"
					if (grid_margin+margin_step<0) { grid_margin += margin_step; }
					else { grid_margin = 0; }
					group_container
						.stop()
						.animate({marginTop:grid_margin+"px"}, animationSpeed);
						//.css ({marginTop: grid_margin+'px'});
				});
	
	if ($("a.cell").length > 0) {
		// TEMP prikaz naslova u gridu
		var config = {    
		   sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
		   interval: 10, // number = milliseconds for onMouseOver polling interval    
		   over: function(){
					var caption = $(this).find("span.title");
					if ($(this).hasClass('noPhoto')) {
						 caption
							.stop(false, true).animate (
								{color: "#FFF", backgroundColor: "#000"}, 
								100);
					}
					else {
						caption.fadeIn(100);
					}
				}, // function = onMouseOver callback (REQUIRED)    
		   timeout: 10, // number = milliseconds delay before onMouseOut    
		   out: function(){
					var caption = $(this).find("span.title");
					if ($(this).hasClass('noPhoto')) {
						caption
							.stop(false, true).animate (
								{color: "#000", backgroundColor: "#FFF"}, 
								100);
					}
					else {
						caption.fadeOut(100);
					}
				} // function = onMouseOut callback (REQUIRED)    
		};

		$("a.cell")
			.hoverIntent(config);
	}
});

// function SetCookie (name, value, path) {  
	// var expires = '';
	// var now = new Date(); 
	// fixDate(now);
	// then = now.getTime() + (24 * 60 * 60 * 1000);
	// now.setTime(then);
	// expires = now.toGMTString();
	// var argv = SetCookie.arguments;  
	// var argc = SetCookie.arguments.length;  
	// var expires = (argc > 2) ? argv[2] : null;  
	// var path = (argc > 3) ? argv[3] : null;  
	// var domain = (argc > 4) ? argv[4] : null;  
	// var secure = (argc > 5) ? argv[5] : false; 
	// path = ""; 
	// document.cookie = name + "=" + escape (value) + 
	// ((expires == null) ? "" : ("; expires=" + expires)) + 
	// ((path == null) ? ("; path=" + "/") : ("; path=" + "/")) +
	// ((domain == null) ? "" : ("; domain=" + domain)) +    
	// ((secure == true) ? "; secure" : "");
// }