var scrollPane;
var scrollPaneApi;
var scrollPaneSetting = {};
var slideSpeed = 300;

/**
 * DOCUMENT READY
 */
$(document).ready(function()
{

    //lightbox
    $(function() {
        $('.lightboxclass').lightBox();
    });

    //schovani prvku kdyz jede JS
    $(".inputDis").hide();

    //nastylovani tabulek
    $('.table01').each(
        function()
        {
            $(this).find('tr:first').addClass('first');
            $(this).find('tr:odd').addClass('odd');
            $(this).find('tr:even').addClass('even');
        }

    );

	scrollPane = $(".scroll-pane").jScrollPane(scrollPaneSetting);

	if (scrollPane)
	{
		scrollPaneApi = scrollPane.data('jsp');
	}

    var SearchStringClicked = false;
    $("#SearchString").click(function(){ if(!SearchStringClicked) {$("#SearchString").val('');SearchStringClicked=true;} });

// 	loadMessagesFromXML();


	addCommentExposition();

	$("#inputSearch").focus(function()
	{
		$(this).val("");
	});


	targetBlank();


	$("#facebookShare").click(function(e)
	{
		e.preventDefault();

		window.open("http://www.facebook.com/sharer.php?u="+ escape(window.location.href), '_blank', 'width=600,height=400');
	});

        prepareAddresses();


});



function targetBlank()
{
	var url_match = null;
	var target_domain = null;
	var this_domain = window.location.hostname;

	// funkce vrátí doménu z odkazu
	var get_hostname_from_url = function(url)
	{
		if (typeof url == "undefined")
		{
			return null;
		}

		url_match = url.match(/:\/\/(.[^/]+)/);

		if (url_match != null)
		{
			return url_match[1];
		}

		return null;
	}

	// vybereme všechny odkazy
	$("a").click(function(event)
	{
		var href = $(this).attr("href");

		// získáme doménu cíle odkazu
		target_domain = get_hostname_from_url(href);

		// pokud je doména jiná než aktuální, nebo je nastaveno class="target_blank", otevřeme v novém
		if ( ($(this).hasClass("target_blank") == true || (target_domain != null && target_domain != this_domain)) && !$(this).hasClass("noBlank"))
		{
			window.open($(this).attr("href"), "");
			event.preventDefault();
			return false;
		}
	});
}

/**
 * Projde stranku, najde adresy a doplni tag pro prime otevreni postovniho klienta - ochrana proti robotum
 */
function prepareAddresses()
{


	//Maska je address - domena 2.radu - jmeno - domena 1.radu

	$('.addressHolder').each(
		function()
		{

			//Naparsujem idcko
			parts = $(this).attr('id').split('-');

			address = parts[2] + '@' + parts[1] + '.' + parts[3];

			//$(this).replaceWith($('<a href="mailto:'+address+'">' + this.innerHTML + '</a>'));
			$(this).replaceWith($('<a href="mailto:'+address+'"><span>' + parts[2] + '</span><span class="sep">(at)</span><span>' + parts[1] + '.' + parts[3] + '</span></a>'));


			//alert(address);
		}
	);


}


function Gallery2(c, actualPage)
{
	this.holder = $(c);
	this.imageBigHolder = $(".galleryImageBigThumb", this.holder);
	this.imageBig = $(".galleryImageBigThumb img", this.holder);
	this.imageListHolder = $(".galleryThumbList", this.holder);
	this.imageList = $(".row", this.imageListHolder);
	this.imageHolders = $("> *", this.imageList);
	this.spanActualPage = $(actualPage);
	this.imageListWidth = 0;
	this.imageListCount = this.imageHolders.length;
	this.imagesViewInList = 0;	// počet viditelných obrázků (nastaveno v setListWidth)
	this.actualPosition = 0;	// aktuální pozice (nastaveno v setListWidth)
	this.maxPosition = 0;		// maximální pozice (nastaveno v setListWidth)
	this.selectedIndex = 0;		// index obrázku s nastavnou třídou selected

	this.inc = function(c)
	{
		this.setListWidth();
		this.setList();
		this.addArrowsList();
		this.addArrowsBig();
		this.fillInformation($(this.imageHolders[this.selectedIndex]));

		if ( !this.isImageInView(this.selectedIndex) )
		{
			this.moveList(this.selectedIndex);
		}

		this.spanActualPage.html( this.actualPosition + 1 );
	};

	this.setListWidth = function()
	{
		var width = 0;
		var widthNoPadding = 0;
		var holderWidth = this.imageListHolder.width();
		var imagesViewInList = 0;
		var selectedIndex = 0;

		$.each(this.imageHolders, function(i, val)
		{
			val = $(val);

			if (val.hasClass("selected"))
			{
				selectedIndex = i;
			}

			width += ( val.width() + parseInt(val.css("padding-left")) + parseInt(val.css("padding-right")) );

			// vypočítáme, kolik jich je vidět
			if (widthNoPadding + val.width() < holderWidth)
			{
				widthNoPadding += val.width();
			}
			else
			{
				if (imagesViewInList == 0)
				{
					imagesViewInList = i;
				}
			}
		});

		if (imagesViewInList == 0)
		{
			imagesViewInList = this.imageListCount;
		}

		this.selectedIndex = selectedIndex;
		this.imagesViewInList = imagesViewInList;
		this.maxPosition = this.imageListCount - this.imagesViewInList;
		this.imageListWidth = width;
		this.imageList.width( width );
	};

	this.setList = function()
	{
		if (this.imageBig.length == 0)
		{
			return;
		}

		var imageBig = this.imageBig;
		var thisObject = this;

		$.each(this.imageHolders, function(i, val)
		{
			var holder = $(val);
			var links = $("a", holder);
			var image = $("img", links);

			var images = image.attr("class").split("|")

			links.click(function()
			{
				imageBig.attr("src", images[0]);
				imageBig.parent().attr("href", images[1]);

				thisObject.fillInformation($(this).parent().parent());

				return false;
			});

		});
	};


	this.addArrowsList = function()
	{
		if (this.imageListCount <= this.imagesViewInList)
		{
			return;
		}

		var arrows = $("a.arrow", this.imageListHolder);
		var firstImageHeight = $("img", this.imageHolders[0]).parent().height();
		var top = Math.floor( (firstImageHeight - arrows.height()) / 2 ) + parseInt(this.imageListHolder.css("padding-top"));

		arrows.css({"top":top});

		var actualPosition = this.actualPosition;

		var thisObject = this;

		arrows.click(function()
		{
			var thisArrow = $(this);

			if (thisArrow.hasClass("right"))
			{
				actualPosition = thisObject.moveList(null, actualPosition+1);
			}
			else if (thisArrow.hasClass("left"))
			{
				actualPosition = thisObject.moveList(null, actualPosition-1);
			}

			return false;
		});



		arrows.show();
	};

	this.addArrowsBig = function()
	{
		if (this.imageListCount <= this.imagesViewInList)
		{
			return;
		}

		var arrows = $("a.arrow", this.imageBigHolder);
		var navigator = $(".navigator", this.imageBigHolder);

		var thisObject = this;

		this.imageBigHolder.mouseover(function()
		{
			navigator.stop(true, false).animate(
			{
				"bottom": 0
			}, 300);
		});

		this.imageBigHolder.mouseout(function()
		{
			navigator.stop(true, false).animate(
			{
				"bottom": -(navigator.height())
			}, 300);
		});

		arrows.mouseover(function()
		{
			$("span", $(this)).addClass("hover");
		});

		arrows.mouseout(function()
		{
			$("span", $(this)).removeClass("hover");
		});


		var actualIndex = this.selectedIndex;
		var imageHolders = this.imageHolders;

		arrows.click(function()
		{
			var thisArrow = $(this);

			if (thisArrow.hasClass("right"))
			{
				if ( actualIndex < (imageHolders.length - 1) )
				{
					actualIndex++;

					$("img", imageHolders[ actualIndex ]).parent("a").trigger("click");

					thisObject.moveList(actualIndex);
				}
			}
			else if (thisArrow.hasClass("left"))
			{
				if (actualIndex > 0)
				{
					actualIndex--;

					$("img", imageHolders[ actualIndex ]).parent("a").trigger("click");

					thisObject.moveList(actualIndex);
				}


			}

			return false;
		});



	};


	this.moveList = function(index, position)	// 1 až this.imageListCount
	{
		if (typeof position == "undefined")
		{
			var position = (index - this.imagesViewInList + 1) > 0 ? (index - this.imagesViewInList + 1) : 0;
		}

		if (position >= 0 && position <= this.maxPosition && position != this.actualPosition)
		{
			if (typeof this.imageHolders[ position ] == "undefined")
			{
				return;
			}

			var moveToPx = $(this.imageHolders[ position ]).position().left;

			this.imageList.stop(true, true).animate(
			{
				"left": -(moveToPx)
			}, 300);

			this.actualPosition = position;
		}

		if (typeof index != "undefined")
		{
			this.fillInformation(this.imageHolders[index]);
		}

		this.spanActualPage.html( this.actualPosition + 1 );

		return this.actualPosition;
	};

	this.isImageInView = function(index)
	{
		if (typeof this.imageHolders[index] != "undefined")
		{
			if ( index >= this.actualPosition && index <= (this.actualPosition + this.imagesViewInList - 1) )
				return true;
			else
				return false;
		}

		return false;
	}

	this.fillInformation = function(thumbHolder)
	{
		var infoHolder = $("#galleryImageInfo");

		if (infoHolder.length == 0)
		{
			return;
		}

		var name = $("a.name", thumbHolder).html();
		var info = $("span.photoInfo", thumbHolder).html();
		var html = "";

		html += "<span class='name'>"+ name +"</span>";
		html += "<span class='info'>"+ info +"</span>";

		infoHolder.html(html);
		infoHolder.show();
	}
}



// vkládání komentářů v detailu výstavy
function addCommentExposition()
{
	var addButton = $("#addComment");
	var form = $("#commentsForm");
	var commentHolder = $("#commentsList");

	if (addButton.length == 0 || form.length == 0 || commentHolder.length == 0)
		return;

	addButton.click(function()
	{
		form.stop(true, true).slideToggle(slideSpeed);
		return false;
	});

	$("button[type='reset']", form).click(function()
	{
		form.stop(true, true).slideUp(slideSpeed);
	});

	$("button[type='submit']", form).click(function(e)
	{
		e.preventDefault();

		var inputs = $("input, textarea", form);
		var param_string = [];

		$.each(inputs, function(i, value)
		{
			param_string[i] = $(this).attr("name") +"="+ $(this).val();
		});

		param_string = param_string.join("&");
		param_string = param_string.replace("+", "###");

		$.ajax(
		{
			type: "POST",
			url: WEB_URL +"ajax.php?modul=add_comment",
			data: param_string,
			dataType: "json",
			success: function(response)
			{
// 				console.log(response);

				if (response.result == false)
				{
					var error_msg = "";

					$.each(response.message, function(i, value)
					{
						error_msg += value+ "\n";
					});

					alert(error_msg);
				}
				else
				{
					$("button[type='reset']", form).trigger("click");

					alert('Děkujeme za komentář k výstavě.\nCo nejdříve bude u výstavy zobrazen.');

					$(".jspPane", commentHolder).html(response.html);

					scrollPaneApi.reinitialise();
				}
			},
			error: function(r, status, exc)
			{
// 				console.log(r);
// 				console.log(status);
// 				console.log(exc);

			}
		});

// 		return false;

	});



}





//Nacteni jazykovych hlasek do pole

function loadMessagesFromXML()
{
    $.ajax({
        type: "GET",
	url: WEB_URL+"langs/"+LANG+".xml",
	dataType: "xml",
        async:false,
	success: function(xml) {
          $(xml).find("messages").each(function()
          {
            $(this).find("item").each(function()
              {
                messages[$(this).attr('key')] = $(this).text();
              });
          });
	}
    });
}

//Zobrazeni hlasky
function get_message(key)
{

    if(messages[key])
    {
        return messages[key];
    }
    else
    {
        return key;
    }
}




/**
 * Validace telefonu pomoci JQuery validatoru
 */
  $.validator.addMethod("phone", function(value) {

    var reg_mobil1 = "^[1-9]{1}[0-9]{8}$";
    var reg_mobil2 = "^00[0-9]{12}$";
    var reg_mobil3 = "^[\+][0-9]{12}$";

    value = value.replace(/ /g,"");
    if(value.length){
    return ( value.match(reg_mobil1) || value.match(reg_mobil2) || value.match(reg_mobil3));
    }
    return true;
  }, "Telefon");



