var placeholder = function(elem){
	$.data(elem[0], 'placeholder', elem.attr("placeholder") );
	
	if( elem.val() == "" )
		elem.val( elem.attr("placeholder") ).addClass("placeholder");
	
	elem.focus(function(){
		if( $(this).val() == $.data( this, 'placeholder') )
			$(this).val("").removeClass("placeholder");
	});
	
	elem.blur(function(){
		if( $(this).val() == "" )
			$(this).val( $.data(this, 'placeholder') ).addClass("placeholder");
	});
}

$(document).ready(function(){

	var diva = {
		settings: {
			"loadingOpacity":	0.6,
			"auxFadeSpeed":		150,
			"loadingShowDelay": 150,
			"contentFadeSpeed": 650,
			"colorboxSettings": {
				"speed":		500,
				"transition": "fade"
				}
			},
		products: [],
		total: 0
	};

	// IE6 fix
	if( typeof DD_belatedPNG != "undefined" )
		$("#galerie a.thumb em, #galerie-prodejny a.image em, #sidebar a.image em").each(
			function(){
				DD_belatedPNG.fixPng(this);
			});
	
	// autofocus fallback
	if( !("autofocus" in document.createElement("input")) )
		if( $("input[autofocus=autofocus]").length )
			$("input[autofocus=autofocus]")[0].focus();
    
	// placeholder fallback
    if( !("placeholder" in document.createElement("input")) && $("input[placeholder]").length )
    {
    	// implement placeholders
		$("input[placeholder], textarea[placeholder]").each(function(){
			placeholder($(this));
		});
		
		// delete placeholders before submitting
		$("form").submit(function(){
			$(this).find("input[placeholder], textarea[placeholder]").each(function(){
				var that = $(this);
				if( that.val() == $.data( that[0], "placeholder" ) )
					that.val("");
			});
		});
	}
	
	/* Index autoscroll */
	if( $("#slider").length )
	{
		var slided = $("#slider ol");
		var max = $("#slider li").length;
		var shown = 2;
		var width = 187;
		var timeout = 6000;
		
		var slide = function(){
			slided.animate({ "marginLeft": "-=374px" }, 2000, function(){
				if( Math.abs(parseInt(slided.css("marginLeft"))) == (max-shown)*width )
					slided.css("marginLeft", 0);
				
				setTimeout(function(){ slide(); }, timeout);
			});
		};
		
		setTimeout(function(){ slide() }, timeout);
	}

	/* =========================================================================
	 *
			Gallery
	 *
	 * ====================================================================== */

	// Colorbox
	if( $("#gallery-slice ol").length )
		$("li>a", "#gallery-slice ol").colorbox(diva.settings.colorboxSettings);
	if( $("#galerie-prodejny").length )
		$("a.image", "#galerie-prodejny").colorbox(diva.settings.colorboxSettings);
	if( $("#uvod").length )
		$("a.image", "#uvod").colorbox(diva.settings.colorboxSettings);

	// Add/remove through checkbox
	$("p a", "#gallery-slice").live("click", function(){
		var data = diva.products[$(this).attr("rel")];

		// add to cart
		$.ajax({
			"url": root+"/galerie/akce:pridat/"+data.id+"/ajax",
			"success": function(){
				if( $("#reserved ul").length == 0 )
				{
					$("#reserved em").remove();
					$("#reserved h3").after("<ul></ul>");
				}

				$("#reserved ul").append("<li id='"+data.id+"'><a href=\""+root+"/galerie/single/"+data.id_model+"\">"+data.name+"</a> "+data.cost+
										'&nbsp;Kč (<a href="'+root+'/galerie/akce:smazat/'+data.id+'/ref:'+viewed_page+'" title="odstranit">Odstranit</a>)</li>');

				$("#reserved ul li#"+data.id).hide().fadeIn(diva.settings.contentFadeSpeed);

				diva.total -= -data.cost;
				$("#reserved h3").text("Rezervováno "+diva.total+' Kč');

				if( $("#reserved li").length == 1 )
					$("#reserve").removeClass("hidden");
			}
		});
			
		return false;
	});

	$("#galerie ol p a").live("hover",
		function(event){
			if (event.type == 'mouseover')
				$(this).children("img").attr("src", root+"/pcs/cart_inverse.gif");
			else
				$(this).children("img").attr("src", root+"/pcs/cart.gif");
		}
	);

	// Gather product data
	var refreshProductData = function(){
		diva.total = $("#reserved h3").text().match(/\d+/) != null ? $("#reserved h3").text().match(/\d+/)[0] : 0;

		$("#gallery-slice ol p").each(function(){
			var data = $(this).attr("data").split("-");
			
			if( typeof diva.products[data[0]] != "undefined" )
				return;
			
			diva.products[data[0]] = { id: data[0], id_model: data[1], name: data[2], cost: data[3] };
		});
	};
	refreshProductData();

	// AJAX gallery move
	if( $("#gallery-left").length )
	{
		var current_page = $("#paging strong").text().match(/.*?(\d+)/)[1]-0;
		var viewed_page = current_page;

		var max_page = $("#paging strong").text().match(/(\d+)\s*$/)[1]-0;

		var loaded = [];
		loaded[current_page] = true;

		var move = 748;

		var moveGallery = function(page){

			var gallery = $("#gallery-slice ol");
			var dir = (page < viewed_page) ? 0 : 1;
			
			var a = ((page-current_page)*4 < 0) ? 0 : ((page-current_page)*4);
			var b = ((page-current_page)*4 < 0) ? 4 : ((page+1-current_page)*4);
      
      if( console ) console.log( a, b );
			
			$("#gallery-slice").animate({"height": maxHeight( gallery.children("li").slice(a, b) )}, diva.settings.auxFadeSpeed);
			
				
			if( page < viewed_page )
				gallery.animate({"marginLeft": "+="+move});
			else
				gallery.animate({"marginLeft": "-="+move});

			viewed_page = page;

			if( viewed_page > 1 )
				$("#gallery-left").removeClass("disabled")
			else
				$("#gallery-left").addClass("disabled")
			
			if( viewed_page < max_page )
				$("#gallery-right").removeClass("disabled");
			else
				$("#gallery-right").addClass("disabled");

			$("#paging strong").text("Strana "+viewed_page+"/"+max_page);
			$("#content a[href*=ref:]").each(function(){
				$(this).attr("href", $(this).attr("href").replace(/ref:\d+/, "ref:"+viewed_page));
			});

			return true;
		}

		var loadGallery = function(page){

			// out of range?
			if( page < 1 || page > max_page )
				return false;

			// loaded already?
			if( typeof loaded[page] != "undefined" )
				return !moveGallery(page);
			
			var url = root+"/galerie/"+page+"/ajax";

			if( typeof loading != "undefined" )
				clearTimeout(loading);

			var loading = setTimeout(function(){
				$("#gallery-slice #loading").fadeTo(diva.settings.auxFadeSpeed, diva.settings.loadingOpacity);
			}, diva.settings.loadingShowDelay);

			// load
			$.ajax({
				"url": url,
				"dataType": "html",
				"success": function(data){
					

					clearTimeout(loading);
					$("#gallery-slice #loading").fadeOut(diva.settings.auxFadeSpeed);
					
					loaded[page] = true;

					var ol = $("#galerie #gallery-slice ol");
					ol.css("width", parseInt(ol.css("width"))+move+"px");
					
					var news;
					if( page < current_page )
					{
						ol.css("marginLeft", parseInt(ol.css("marginLeft"))-move+"px");
						ol.prepend( data );
					}
					else
						ol.append( data );

					$("li>a", "#gallery-slice ol").colorbox(diva.settings.colorboxSettings);
					
					// IE6 fix
					if( typeof DD_belatedPNG != "undefined" )
						$("li>a em", "#gallery-slice ol").each(
							function(){
								DD_belatedPNG.fixPng(this);
							});

					refreshProductData();
					moveGallery(page);
				}
			});

			return false;
		};

		$("#gallery-left")
			.click(function(){
				return loadGallery(viewed_page-1)
			});
		
		$("#gallery-right")
			.click(function(){
				return loadGallery(viewed_page+1)
			});


		function maxHeight(collection){
			var max = 0;
			for(var i=0;i<collection.length;i++)
				if( parseInt(collection.slice(i).outerHeight()) > max )
					max = parseInt(collection.slice(i).outerHeight());

			return max;
		}
	}
	
	/* --- Admin ----------------------------------- */
	var highlight_post = function(clicked){
		if( typeof clicked == "object" )
			var post = clicked.attr("href").match(/#(pr\d+)$/)[1];
		else if( window.location.hash.match(/pr\d+/) )
			var post = window.location.hash.match(/(pr\d+)/)[1];
		
		$("form div li").removeClass("highlighted");
		$("li#"+post).addClass("highlighted");
	};
	
	highlight_post();
	
	$("a[href*=#p]").click(function(){ highlight_post($(this)) });
	
	$("li", "#products").live("click", function(){ $(this).removeClass("highlighted"); });
});
