/**
 * Aktualni index prvni zobrazene fotografie.
 */
var currentFirstCarPhoto = 0;

var buttonsVisible = false;

function carousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
	
	carousel.clip.click(function() {
		carousel.startAuto(0);
	});

	$('#jcarousel-control a').click(function(e) {
		carousel.startAuto(0);
		var scToId = parseInt($(this).attr('href')) + 1;
		carousel.scroll(scToId);
		return false;
	});
}

/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 */
function carousel_itemFirstInCallback(carousel, item, idx, state) {
	var next = $('.jcarousel-skin-detailvozu .jcarousel-next-horizontal');
	var prev = $('.jcarousel-skin-detailvozu .jcarousel-prev-horizontal');
	
    if (!isDisabled(next) && buttonsVisible) {
		next.css('display', 'block');
	} 

	if (!isDisabled(prev) && buttonsVisible) {
		prev.css('display', 'block');
	}

	var i = $(item).attr('jcarouselindex');
	var $target = $('#jcarousel-control #item'+(i-1));
	
	// Ak je pozicia $target vacsia/mensia ako hranice maleho carouselu, len vtedy sa scrolluje.
	var targetOffset = $target.offset();
	var targetWidth = $target.width();
	var containerOffset = $('#jcarousel-control').offset();
	var containerWidth = $('#jcarousel-control').width();
	
	if ( ((targetOffset.left + targetWidth*2) > (containerOffset.left + containerWidth)) 
		|| (targetOffset.left < containerOffset.left) ) {
		$('#jcarousel-control').scrollTo($target, 200);
	}
	
	var offX = (i-1)*64;

	$('.control-select-wrapper').css('background-position', offX+'px '+0);
}

/**
 * This is the callback function which receives notification
 * when an item is no longer the first one in the visible range.
 */
function carousel_itemFirstOutCallback(carousel, item, idx, state) {
	var next = $('.jcarousel-skin-detailvozu .jcarousel-next-horizontal');
	var prev = $('.jcarousel-skin-detailvozu .jcarousel-prev-horizontal');
	
    if (isDisabled(next) || !buttonsVisible) {
		next.css('display', 'none');
	} 

	if (isDisabled(prev) || !buttonsVisible) {
		prev.css('display', 'none');
	} 
}

/**
 * jCarousel pre detail auta
 */
function initCarousel()
{
	$('#carousel').jcarousel({
		auto: 8,
		scroll: 2,
		initCallback: carousel_initCallback,
		itemFirstInCallback:  carousel_itemFirstInCallback,
		itemFirstOutCallback: carousel_itemFirstOutCallback
	});
	
	$('.jcarousel-skin-detailvozu .jcarousel-container-horizontal').hover(arrowEnter, arrowLeave);
	
	arrowLeave();
	
	//initControlCarousel();
	// Upravi sirku vnutorneho wrapperu control carouselu
	var cnt = 0;
	$('#jcarousel-control .control-wrapper img').each(function() {
		cnt++;
	});
	$('#jcarousel-control .control-wrapper').css('width', (cnt*64+1));
	$('#jcarousel-control .control-select-wrapper').css('width', (cnt*64+1));
}

/**
 * jCarousel pre thumbnaily hlavneho carouselu pre detail auta
 */
function initControlCarousel()
{
	$('#jcarousel-control').jcarousel({
		scroll: 2
	});	
}

function arrowEnter(e) {
	var next = $('.jcarousel-skin-detailvozu .jcarousel-next-horizontal');
	var prev = $('.jcarousel-skin-detailvozu .jcarousel-prev-horizontal');

	if (!isDisabled(next)) {
		next.css('display', 'block');
	} else {
		next.css('display', 'none');
	}
	
	if (!isDisabled(prev)) {
		prev.css('display', 'block');
	} else {
		prev.css('display', 'none');
	}
	
	buttonsVisible = true;
}

function arrowLeave() {
	$('.jcarousel-skin-detailvozu .jcarousel-next-horizontal').css('display', 'none');
	$('.jcarousel-skin-detailvozu .jcarousel-prev-horizontal').css('display', 'none');
	buttonsVisible = false;
}

function isDisabled(element) {
	var dis = String(element.attr('disabled'));
	if ( dis == 'true') {
		return true;
	} else return false;
}

/**
 * Spousti se pri kliknuti na "dalsi snimky".
 * Posouva fotografie vozu doleva.
 * 
 */
function previousPhotosClicked(carId)
{
	var firstPhoto = document.getElementById('carPhoto1');
	var secondPhoto = document.getElementById('carPhoto2');
	var image0 = document.getElementById('mediumImage0');
	var image1 = document.getElementById('mediumImage1');

	secondPhoto.src = firstPhoto.src;
	firstPhoto.src = carPhotos[currentFirstCarPhoto - 1];

	currentFirstCarPhoto--;

	image0.onclick = function() {popupPhoto(carId, currentFirstCarPhoto )};
	image1.onclick = function() {popupPhoto(carId, currentFirstCarPhoto+1 )};

	if (currentFirstCarPhoto == 0) {
		document.getElementById('previousPhotosButton').style.display = 'none';
	}

	document.getElementById('nextPhotosButton').style.display = 'block';
}

/**
 * Spousti se pri kliknuti na "predchozi snimky".
 * Posouva fotografie vozu doprava.
 */
function nextPhotosClicked(carId)
{
	var firstPhoto = document.getElementById('carPhoto1');
	var secondPhoto = document.getElementById('carPhoto2');
	var nextButton = document.getElementById('nextPhotosButton');
	var previousButton = document.getElementById('previousPhotosButton');
	var image0 = document.getElementById('mediumImage0');
	var image1 = document.getElementById('mediumImage1');

	firstPhoto.src = secondPhoto.src;
	secondPhoto.src = carPhotos[currentFirstCarPhoto + 2];

	currentFirstCarPhoto++;

	image0.onclick = function() {popupPhoto(carId, currentFirstCarPhoto )};
	image1.onclick = function() {popupPhoto(carId, currentFirstCarPhoto+1 )};

	if (currentFirstCarPhoto == carPhotos.length - 2) {
		nextButton.style.display = 'none';
	}

	previousButton.style.display = 'block';
}

/**
 * Zobrazi stranku s nekterym z jiz navstivenych vozidel.
 */
function loadCarFromHistory()
{
	var history = document.getElementById('carsHistory');
	var selectedCarId = history.options[history.selectedIndex].value;

	if (selectedCarId != 0)
		document.location = urlPrefix + '/Car/' + selectedCarId;
}

/**
 * Aktualne vybrana stranka v "dalsi vozy z vyberu". Cislovano od nuly.
 */
var currentOtherCarsFromSelectionPage = 0;

/**
 * Poradi posledni stranky v "dalsi vozy z vyberu". Cislovano od nuly.
 * Inicializovano v PHP sablone.
 */
var lastOtherCarsFromSelectionPage;

/**
 * Maximalni pocet dalsich aut z vyberu, ktery se zobrazi pod aktualnim autem.
 * Pokud ma byt inicializovano dynamicky - presunout do PHP sablony.
 */
var maxOtherCarsFromSelectionOnPage = 5;

/**
 * Nacita seznam aut do sekce "dalsi vozy z vyberu" podle poradi stranky.
 * @param page poradi stranky (cislovany od nuly)
 */
function loadOtherCarsFromSelection(page)
{
	currentOtherCarsFromSelectionPage = page;

	var fromIndex = maxOtherCarsFromSelectionOnPage * page;
	var toIndex = Math.min(fromIndex + maxOtherCarsFromSelectionOnPage,
			otherCarsFromSelectionIds.length);
	var selectedIds = otherCarsFromSelectionIds.slice(fromIndex, toIndex);
	var carIdsQuery = selectedIds.toString();

	var ajaxFunction = function(request) {
		var otherCars = document.getElementById('otherCarsFromSelection');
		otherCars.innerHTML = request.responseText;
		
		// tooltip pri hoveru nad celym radkem
		$(".vypis_vozu DIV.popis_bez_obr").hover(function(e){
			if ($(this).find(".vybava").length > 0) {
				$("body").append("<p id='tooltip'></p>");
				$("#tooltip")
					.html($(this).find(".vybava").html())
					.css("top",(e.pageY - 10) + "px")
					.css("left",(e.pageX + 10) + "px")
					.fadeIn("fast");
			}		
	    },
		// hover-out: opusteni popisu
		function(){
			$("#tooltip").remove();
	    });	
		$(".vypis_vozu DIV.popis_bez_obr").mousemove(function(e){
			$("#tooltip")
				.css("top",(e.pageY - 10) + "px")
				.css("left",(e.pageX + 10) + "px");
		});
		// tooltip pri hoveru nad celym radkem
		// vetsi obrazek pri hoveru na malem obrazku
		$(".vypis_vozu IMG.obrazek").hover(
			// najeti na obrazek
			function(e){
      			imgPath = $(this).parent().find(".vetsi_obrazek").html();
      			$("body").append("<p id='picture'>"+ "e" +"</p>");

		      if ( imgPath != "")
		      {
		         $("#picture")
		          .html( '<img src="'+imgPath+'" alt="foto" width="320" height="240"/>' )
		          .css("top",(e.pageY - 120) + "px")
						  .css("left", ( e.pageX + 65 ) + "px")
		          .fadeIn("fast");		
		      }
		      else
		      {
		        $("#picture").css("display","none");
		      }
			},
			// opusteni obrazku
			function(){
				$("#picture").remove();
			});			
	};

	sendAjaxRequest(urlPrefix + "/Ajax/CarsList?ids=" + carIdsQuery, ajaxFunction);

	updateOtherCarsFromSelectionNavigation();
}

/**
 * Nacita predchozi stranku do sekce "dalsi vozy z vyberu".
 */
function loadPreviousOtherCarsFromSelection()
{
	currentOtherCarsFromSelectionPage -= 1;

	loadOtherCarsFromSelection(currentOtherCarsFromSelectionPage);
}

/**
 * Nacita nasledujici stranku do sekce "dalsi vozy z vyberu".
 */
function loadNextOtherCarsFromSelection()
{
	currentOtherCarsFromSelectionPage += 1;

	loadOtherCarsFromSelection(currentOtherCarsFromSelectionPage);
}

/**
 * Aktualizuje navigaci strankovani v sekci "dalsi vozy z vyberu":
 * - skryva sipku pri vybrane krajni strance
 * - prepina vzhled aktualni stranky
 */
function updateOtherCarsFromSelectionNavigation()
{
	var previousOtherCarsFromSelection = document.getElementById('previousOtherCarsFromSelection');
	var nextOtherCarsFromSelection = document.getElementById('nextOtherCarsFromSelection');

	if (previousOtherCarsFromSelection == null || nextOtherCarsFromSelection == null) {
		// Pokud neexistuji predchozi/dalsi sipky, znamena to, ze navigace nebyla
		// vubec zobrazena a neni ji treba aktualizovat.
		return;
	}

	if (currentOtherCarsFromSelectionPage == 0) {
		previousOtherCarsFromSelection.style.display = 'none';
	} else {
		previousOtherCarsFromSelection.style.display = 'inline';
	}

	if (currentOtherCarsFromSelectionPage == lastOtherCarsFromSelectionPage) {
		nextOtherCarsFromSelection.style.display = 'none';
	} else {
		nextOtherCarsFromSelection.style.display = 'inline';
	}

	/*for (i = 0; i <= lastOtherCarsFromSelectionPage; i++) {
		var resultPageButton = document.getElementById('otherCarsFromSelectionResultPage' + i);

		if (i == currentOtherCarsFromSelectionPage) {
			resultPageButton.className = 'vybrane';
		} else {
			resultPageButton.className = '';
		}
	}*/
}
