/**
 * Lightbox by 3sixty
 */ 
 
var lbLoaded = false;
var lbContent = new Array();
var lbActual = 0;
var lbCount = 0;
var lbSlideshowInterval;
var lbSlideshowActive = false;
var lbHiddenContent;

var lbOriginalImageWidth = 0;
var lbOriginalImageHeight = 0;
var lbAspectRatio = 0;
var lbPortait = true;
var lbIsVideo = false;

// IE8 nepodporuje metodu pole indexOf -> je treba ji doplnit
if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
  }
}

$(document).ready(function() {
	deactivateLightBox();
	$("a.lightbox").click(activateLightBox);
	$(document).keydown(function (e) {
		if(e.which == 27) { // esc
			deactivateLightBox();
			return true;
		}
		if(e.which == 39) { // right
			nextLightBox();
			return true;
		}
		if(e.which == 37) { // left
			previousLightBox();
			return true;
		}
	});
});

function activateLightBox() {
    deactivateLightBox();
	resizeLightBox();
	if(!lbLoaded) {
		loadLightBox();
	}
	$("div#lightBox").fadeIn("slow");	

    // kvuli IE, ktere by jinak lightboxy posunute castecne mimo obrazovku, pokud uzivatel neni nascrollovan uplne nahore
    window.scroll(0, 0);

	// kolikata je kliknuta polozka v seznamu polozek?
	lbActual = lbPhotoIds.indexOf(parseInt($(this).attr('rel')));

	if(lbActual == -1) lbActual = 0;


	focusLightBox(lbActual);		
	
	$(window).resize(function() {
		resizeLightBox();
	});
	
	//$("div#lightBoxInner").css('top',$(document).scrollTop());
	return false;
}

function resizeLightBox(){
    $("div#lightBox").css({
		//width:		$(document).width(), // proc nastavovat sirku? to akorat dela horizontalni scrollbar...
		height:		Math.max($(document).height(), $("#lightBoxInner").height()) // lightbox roztahneme bud podle tele dokumentu (pokud by nepokryval cele okno) nebo podle sveho obsahu (pokud by ho precuhoval)
	});
    
    //alert($(".lb-detail-container").css("width"));
    
    $("#lightBoxInner").css("width", $(".lb-detail-container").css("width"));

    if(typeof($(".lb-detail").offset()) != "undefined") {        
        
		if(lbPortait){			
			$(".lb-detail").height(Math.min(Math.max($(window).height() - $(".lb-detail").offset().top - 50, 300), lbOriginalImageHeight));
			$(".lb-detail").width($(".lb-detail").height() * lbAspectRatio);
			$(".lightBoxDesc").height($(".lb-detail").height() - 45);
			$(".lightBoxDesc").css("left", (($(".lb-detail-container").width() +  $(".lb-detail").innerWidth()) / 2) + 40 + "px");
        }
		else{
        	$(".lb-detail").width($(".lb-detail").height() * lbAspectRatio);
			$(".lb-detail").height(Math.min(Math.max($(window).height() - $(".lb-detail").offset().top - $(".lightBoxDesc").outerHeight() - 50, 200), lbOriginalImageHeight));
		}

		$(".lb-image-cover").width($(".lb-detail").height() * lbAspectRatio + 10);
        $(".lb-image-cover").css("left", $(".lb-detail-container").innerWidth() / 2 - $(".lb-detail").width() / 2);
		$(".prev-image, .next-image").css("top", (($("img.lb-detail").height()) / 2) - $(".prev-image").height() / 2 +"px");		
		$(".next-image").css("left", (($("img.lb-detail").width()) + 20)+"px");		
    }
}

function clickImageLightBox(e) {	
	
	 var relativeX = e.pageX - this.offsetLeft - 300;
	 var relativeY = e.pageY - this.offsetTop;
	 if(relativeX > ($(".lb-detail").width()/2)) {
		 nextLightBox();
	 } else {
		 previousLightBox();
	 }
}

function mousehoverImageLightBox(e) {	

	 var relativeX = e.pageX - $(this).offset().left;
	 var relativeY = e.pageY - this.offsetTop;
	 if(lbIsVideo){
		$(".next-image").fadeOut();
		$(".prev-image").fadeOut();
	 }
	 else if(relativeX > ($(".lb-detail").width()/2)) {
		$(".next-image").fadeIn();
		$(".prev-image").fadeOut();
		$(this).css("cursor", "pointer");
	 } else {
		$(".prev-image").fadeIn();
		$(".next-image").fadeOut();
		$(this).css("cursor", "pointer");
	 }
}

function mouseoutImageLightBox(e) {	
	$(".next-image").fadeOut();
	$(".prev-image").fadeOut();
}

function loadLightBox() {
	//lbPhotoIds = $("div#lightboxIdList").html().split(',');

	// -1 because of the last , in the list
	lbCount =  lbPhotoIds.length;

	lbContent = $("div.foto a.lightbox");
	$("#black-background, #lightbox, #black-background #lb-loader").css("height", ($(document).height())+"px"); 
	$("div#lightBox #lb-close").click(deactivateLightBox);
	$("div#lightBox #lb-first").click(firstLightBox);
	$("div#lightBox #lb-previous").click(previousLightBox);
	$("div#lightBox #lb-next").click(nextLightBox);
	$("div#lightBox #lb-last").click(lastLightBox);
	$("div#lightBox #lb-slideshow").click(activateSlideShowLightBox);
	lbLoaded = true;
}

function focusLightBox(offset) {
	
	lbActual = offset;
	if(hasPreviousLightBox()) {
		$("div#lightBox #lb-previous").addClass('active');	
	} else {
		$("div#lightBox #lb-previous").removeClass('active');
	}
	if(hasNextLightBox()) {
		$("div#lightBox #lb-next").addClass('active');	
	} else {
		$("div#lightBox #lb-next").removeClass('active');
	}	
	
	if(noLastLightBox()) {
		$("div#lightBox #lb-last").addClass('active');	
	} else {
		$("div#lightBox #lb-last").removeClass('active');
	}
	
	if(noFirstLightBox()) {
		$("div#lightBox #lb-first").addClass('active');	
	} else {
		$("div#lightBox #lb-first").removeClass('active');
	}
	
	var photoId = lbPhotoIds[offset];
	
	$.ajax({
		type		: 'GET',
		url			: URLROOT+'photo/0/text/' + photoId + '/text/0',
		dataType	: 'html',
		success		: function(data) {                 
						$("#lb-loader").html(data);
						/*var oldLb = $("#lb-loader").children();
						var newLb = $(data).hide();
						$("#lb-loader").append(newLb);
						oldLb.fadeOut('fast', function() {
							$(this).remove();							
						});*/
                        
                        
                        
						$("#lb-loader").children().fadeIn('fast');
						
						
						$("div#lightBox #lb-position").html(lbActual + 1 + "/" + lbCount);
						$("div#lightBox .lb-detail").click(clickImageLightBox);
						$("div#lightBox .lb-detail").mousemove(mousehoverImageLightBox);
						$("div#lightBox .lb-detail").mouseout(mouseoutImageLightBox);
						$(".next-image").hide();
						$(".prev-image").hide();
						
                        lbOriginalImageWidth = $(".lb-detail").width()
                        lbOriginalImageHeight = $(".lb-detail").height()
                        lbAspectRatio = lbOriginalImageWidth / lbOriginalImageHeight;
                        if(lbPortait = (lbAspectRatio < 1.0)){ 
                        	// portait                        	
							$(".lightBoxDesc").addClass("absolute");                        	                        
                        }
                        else{
							// landscape
						    $(".lightBoxDesc").removeClass("absolute");
						}
                        
						resizeLightBox();
						
						initForm(photoId);
						
						if( $(".lb-image-cover > object").attr("height") ){ // skryt v pripade ze je video
							$(".lb-order-btn").addClass("video");
							lbIsVideo = true;
						}
						else{
							lbIsVideo = false;
						}
						
						resizeLightBox();
						
						$(".prev-image").click(previousLightBox);
						$(".next-image").click(nextLightBox);	
						$("a.lb-order-btn").click(function(){
							openOrder(photoId);
							deactivateSlideShowLightBox();
							return false;
						});
						
						if(editationEnabled) {
						    $('#edit-title').editable(URLROOT + 'photo-edit', {
						         indicator : 'Saving..',
						         style	   : "inherit",
						         tooltip   : 'Click to edit...',
						         type      : 'textarea',	         
						         cancel    : 'Cancel',
						         submit    : 'OK',
						         submitdata  : {photoId: photoId, element: 'title'}
						    });	    		
						    $('#edit-note').editable(URLROOT + 'photo-edit', {
						    	indicator : 'Saving..',
						    	style	   : "inherit",
						    	tooltip   : 'Click to edit...',
						    	type      : 'textarea',	         
						    	cancel    : 'Cancel',
						    	submit    : 'OK',
						        submitdata  : {photoId: photoId, element: 'note'}
						    });	    		
						    $('#edit-edits').editable(URLROOT + 'photo-edit', {
						    	indicator : 'Saving..',
						    	style	   : "inherit",
						    	tooltip   : 'Click to edit...',
						    	type      : 'textarea',	         
						    	cancel    : 'Cancel',
						    	submit    : 'OK',
						    	submitdata  : {photoId: photoId, element: 'edits'}
						    });	    		
						}
                        
                        //alert($(".lb-comments").outerHeight());
                        
                        //alert($(".lb-detail").offset().top + "+" + "+" + $(".lightBoxDesc").outerHeight());                                                
					 }		
	});
	
	$("#lb-loader").html('<img class="photoLoader" src="' + URLROOT +'img/ajax-loader.gif" />'); 
	
	setTimeout('resizeLightBox();', 800); // kdyz to nebylo zpozdene, tak se to v IE neprovedlo.. 
}

function firstLightBox() {
	deactivateSlideShowLightBox();
	focusLightBox(0);
}

function lastLightBox() {
	deactivateSlideShowLightBox();
	focusLightBox(lbCount-1);
}

function previousLightBox() {
	deactivateSlideShowLightBox();
	if(hasPreviousLightBox()) {
		focusLightBox(lbActual-1);
	}
}

function nextLightBox() {
	deactivateSlideShowLightBox();
	if(hasNextLightBox()) {
		focusLightBox(lbActual+1);
	}
}

function noFirstLightBox() {
	return lbActual>0;
}

function noLastLightBox() {
	return lbCount-1>lbActual;
}

function activateSlideShowLightBox() {
	if(lbSlideshowActive) {
		return false;
	} else {
		lbSlideshowActive = true;
	}	
	$("div#lightBox #lb-slideshow").addClass('active');
	$("div#lightBox #lb-slideshow").unbind( 'click', activateSlideShowLightBox );
	$("div#lightBox #lb-slideshow").click(deactivateSlideShowLightBox);
	lbSlideshowInterval = setInterval(_slideShow,5000);	
}

function deactivateSlideShowLightBox() {
	if(lbSlideshowActive) {
		clearInterval(lbSlideshowInterval);
		$("div#lightBox #lb-slideshow").removeClass('active');
		$("div#lightBox #lb-slideshow").unbind( 'click',  deactivateSlideShowLightBox);
		$("div#lightBox #lb-slideshow").click(activateSlideShowLightBox);		
		lbSlideshowActive = false;
	}
}

function _slideShow() {
	if(hasNextLightBox()) {
		focusLightBox(lbActual+1);
		if(!hasNextLightBox()) {
			deactivateSlideShow();
		}
	}
}

function hasPreviousLightBox() {
	return lbActual>0;
}

function hasNextLightBox() {
	return lbActual<(lbCount-1);
}


function deactivateLightBox() {
	deactivateSlideShowLightBox();
	$("div#lightBox").fadeOut("slow", function() {$("#lb-loader").html("");});
	
}

function openOrder(photoId) {	
	



	$.ajax({
		type		: 'GET',
		url			: URLROOT+'order/' + photoId + '/0',
		dataType	: 'html',
		success		: function(data) {
			$("#lb-loader").html(data);
			$(".lb-order-close").click(closeOrder);
		}		
	});
	
	return false;
}

function closeOrder() {
	focusLightBox(lbActual);
}

/**
 * jQuery graphic part
 */ 
 
$(document).ready(function(){	

  $("#lightBoxInner").css("width", "1034px");   // zatim natvrdo
   
	$(".topLeft input").click(function(){
    $(this).focus();
    $(this).select();
  });
  
	if( $(".lb-image-cover > object").attr("height") ){ // skryt v pripade ze je video
		$(".lb-order-btn").addClass("video");
	}

});

function initForm(photoId){
	$("#formular").attr("action", URLROOT+"ajaxInsertComment?id="+photoId);
//   
//   $('#formular').attr("method", "get");
//   
	$(".showForm").show();
  
  $(".close-form").click(function(){
		$(".addcomment-form-over-image").fadeOut();
		$(".showForm").fadeIn();
		return false;
	});
  
  $(".showForm").click(function(){
  	  	$(".addcomment-form-over-image").load(URLROOT+"ajaxRecreateCommentForm?id="+photoId, {}, function(){initForm(photoId);});
  	  
		$(".addcomment-form-over-image").addClass("js-active");
		if( $(".lb-image-cover > object").attr("height") ){
			$(".addcomment-form-over-image").addClass("video");
		}
		$(".addcomment-form-over-image").fadeIn(function(){
			$(".showForm").fadeOut();
			$("#commentAuthor").focus();
		}); 
		return false;
	});
  
  $("#commentAuthor").click(function(){
		if( $("#commentAuthor").val() == "Required field." ){
			$("#commentAuthor").val("")
			return false;
		}
	});
	
	$(".commentText").click(function(){
		if( $(".commentText").val() == "Required field." ){
			$(".commentText").val("")
			return false;
		}
	});
  
  var chyba = false;
  
  var options = {  
        beforeSubmit:  function(){
					chyba = false;
					
					if($("#commentAuthor").val()  == "" || $("#commentAuthor").val() == "Required field."){
						$("#commentAuthor").val("Required field.");
						chyba = true;
					}
					
					if($(".commentText").val()  == "" || $(".commentText").val() == "Required field."){
						$(".commentText").val("Required field.");
						chyba = true;
					}
					
					if(chyba){
						return false;
					}
        
                	$(".submit_save").val("Sending");
                
                    $(".submit_save, #formular > table > tbody > tr > td > input, #formular > table > tbody > tr > td > textarea").attr("disabled", true);
                    $("#formular > table > tbody > tr > td > input, #formular > table > tbody > tr > td > textarea").attr("readonly", true);          
           
        },
        success: function(responseText, statusText){
                    //alert("1");                    
                    
                    // empty response means failed captcha test
                    if(responseText == ""){
                        $(".submit_save").val("Send");
                        
                        $(".submit_save, #formular > table > tbody > tr > td > input, #formular > table > tbody > tr > td > textarea").attr("disabled", false);
                        $("#formular > table > tbody > tr > td > input, #formular > table > tbody > tr > td > textarea").attr("readonly", false);
                            
                        $("#commentCaptcha-input").val("Please fill this correctly!");
                            
                        return;
                    }
                    
                    //$(".addcomment-form-over-image").load(URLROOT+"ajaxRecreateCommentForm?id="+photoId, {}, function(){initForm(photoId);});
                    
					$(".addcomment-form-over-image").html("");
					$(".comment:first").hide().fadeIn(function(){
						$(".addcomment-form-over-image").hide();
						resizeLightBox();
					});
					$(".showForm").text("Add new comment").fadeIn();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
					alert("error");
				}
      }
     
     $('#formular').ajaxForm(options);
}		

