﻿var i = 0;

$(function() {
	var photos = new Array();
	var imageArray = new Array();
	var hidden = $('body').append('<div id="img-cache" style="display: none">').children('#img-cache');
	$.ajax({
		url: "/js/photos.xml",
		dataType: "xml",
		success: function(data){
			$(data).find('photo').each(function() {
			    var src = $(this).find('src').text();
			    var href = $(this).find('href').text();
			    var head = $(this).find('header').text();
			    var desc = $(this).find('desc').text();
				var photo = new Array(src, href, head, desc);
				photos.push(photo);
				imageArray.push(src);
			});
			$.each(imageArray, function (i, val) {
				$('<img>').attr('src', val).appendTo(hidden);
			});
			cyclePhotos(photos);
		}
	});
	    $('.gal-container a').click(function(e){
		if (confirm("Nastąpi bezpowrotne usunięcie wybranego zdjęcia.\nKontynuować?")) {
			return true;
		} else {
			return false;
		}
    });
	
	$('#gallery a').fancybox();
	$('#galeria a').fancybox();
	
	if( window.location.hash && $("#photo-"+window.location.hash.substr(1)).length )
	{
		$("#photo-"+window.location.hash.substr(1)).trigger("click");
	}
	else
	{
		$("#gallery table td:first-child a").trigger("click");
	}
	
	$(".ukryj-mnie table, .ukryj-mnie p, .ukryj-mnie legend span").hide();
	$(".ukryj-mnie legend").css("cursor", "pointer").click(function() {
		$(this).children("span").toggle();
		$(this).next().toggle();
		$(this).next().next().toggle();
	});
	
	$(".ukryj-mnie a[href*=przenies]").click(function(event) {
		event.stopPropagation();
	});
	
	$("a[href*=/galeria-admin/?delete=]").click(function() {
		if( confirm("Czy na pewno chcesz usunąć CAŁĄ kategorię #" + $(this).attr("href").substr(33) + "?") )
			return true;
		else
			return false;
	});
	
	$("a[href*=/galeria-admin/?delete_photo=]").click(function() {
		if( confirm("Czy na pewno chcesz usunąć zdjęcie #" + $(this).attr("href").substr(39) + "?") )
			return true;
		else
			return false;
	});
	
	$("input[name^=photo_description]").focus(function() {
		input = $(this);
		input.hide();
		
		$('<textarea cols="20" rows="5">' + input.val() + '</textarea>').insertAfter(input).focus().blur(function() {
			input.val( $(this).val() );
			$(this).remove();
			input.show();
		});
	});
	
});

function cyclePhotos(ph) {
	j = (i%4)+1;
	k = i%(ph.length);
	$('#galph'+j).stop().delay(5000).animate({
		opacity: 0
	}, 500, function() {
		$(this).children('a').css('background-image', 'url('+ph[k][0]+')').attr('href', ph[k][1]).attr('title', ph[k][3]);
		$(this).children('div').children('h3').text(ph[k][2]);
		$(this).children('div').children('p').text(ph[k][3]);
		$('#galph'+j).animate({
			opacity: 1
			}, 500, function() {
				i++;
				cyclePhotos(ph);
			}
		);
	});
}
