$(document).ready(function() {
  
  var bodyClass = $('body').attr('class');
  $('body').append('<div id="trailimageid" style="position:absolute;"></div>');
  
  updateAdvText($('#f-search').val());
  
});


var images = new Array();
var lastInput = "simple";

function getWindowHeight() {
	var winHeight = 0;
	if (window.innerHeight) {
		winHeight = window.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		winHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		winHeight = document.body.clientHeight;
	}
	return winHeight;
}


function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else {
    var expires = "";
  }
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
	
/* nahrada 'in_array' php fce :) */
function in_array(hodnota,  pole) {
  for (i = 0; i < pole.length; i++) {
    if (pole[i] == hodnota) {
      return true;
    }
  }
  return false;
}

function findPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
  }
  return [curleft,curtop];
}

/*
Simple Image Trail script- By JavaScriptKit.com
Visit http://www.javascriptkit.com for this script and more
This notice must stay intact
@author For jQuery refactored Martin Talavasek <tm@pixmac.com>
*/

var offsetfrommouse=[30,20];  //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var displayduration= 0;        //duration in seconds image should remain visible. 0 for always.
var currentimageheight = 640;	// maximum image size.
var displayDelay = 150;
var showTrails = "true";
var imageHeight = 0;
var imageWidth = 0;
var preview = null;

function gettrailobj() {
  try {
    return $('#trailimageid').css();
  } catch (e) {
    return false;
  }
}

function gettrailobjnostyle() {
  try {
    return $('#trailimageid');
  } catch (e) {
    return false;
  }
}


function truebody(){
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function showtrail(imageSrc, title, width, height, crop) {
	
  if (showTrails != "true") {
    return false;
  }

  imageWidth = width;
	imageHeight = height;
  
  $(document).mousemove(function(e) {
    followmouse(e);
  });
  
	var newHTML = '<div class="trail-wrap" style="width: ' + width + 'px;">';
	
	if (timestamp) {
		var timestamp = "";
	} else {
	  var timestamp = "";
	}
  
    var thumbSrc = imageSrc.replace("preview", "thumbnail");
  
	newHTML += '<div class="trail-wrap-in">';
	if (crop) {
		newHTML += '<div style="overflow: hidden; width: ' + width + 'px; height: ' + height + 'px;">';
		var ratio = width / height;
		if (ratio >= 1) {
			var move = 15 * width / 170;
			newHTML += '  <img id="trailImage" src="' + thumbSrc + timestamp + '" width="' + width +'" height = "' + (height + 35) +'" border="0" />';
		} else {
			var move = 15 * height / 170;
			newHTML += '  <img id="trailImage" src="' + thumbSrc + timestamp + '" width="' + (width + move) +'" height = "' + height +'" border="0" />';
		}
		newHTML += '</div>';
	} else {
		newHTML += '  <img id="trailImage" src="' + thumbSrc + timestamp + '" width="' + width +'" height = "' + height +'" border="0" />';
	}
	
	newHTML += '  <div class="trail-title"><strong>' + title + '</strong></div></div>';
    newHTML += '</div>';
	
	gettrailobjnostyle().html(newHTML);
    gettrailobj().show();
    
    if (crop) {
	    setTimeout("displayTrail(" + ratio + ", " + move + ");", displayDelay);
    } else {
    	setTimeout("displayTrail();", displayDelay);
    }
	preview = new Image(width, height);
    preview.src = imageSrc;
  
}

function displayTrail(ratio, move) {
  try {
	if (ratio && move) {
		if (ratio >= 1) {
			$("#trailImage").attr('height', $("#trailImage").attr('height') - move + 15);
		} else {
			$("#trailImage").attr('width', $("#trailImage").attr('width') - move);
			$("#trailImage").attr('height', $("#trailImage").attr('height') + 15);
		}
	}
    $("#trailImage").attr('src', $(preview).attr('src'));
  } catch (e) { }
}

function switchDisplayTrail() {
  if (showTrails == "true") {
    showTrails = "false";
  } else {
    showTrails = "true"; 
  }
  createCookie("showTrails", showTrails, 7);
}

function hidetrail() {

  $(document).unbind('mousemove');
	gettrailobj().html(' ');
	gettrailobj().hide();

	gettrailobj().css('left', '-500px');
  gettrailobj().css('top', '');
  
}

/* Largely rewritten by Melda, 2009-02-15*/
function followmouse(e) {

	var topBound = 0;
	var bottomBound = 0;

	var xcoord = offsetfrommouse[0];
	var ycoord = offsetfrommouse[1];
	
	var fromLeft = e.pageX;
	var fromTop  = e.pageY;
	
	var windowWidth  = $(window).width();
	var windowHeight = $(window).height();

	var viewWidth  = windowWidth - 15;
	var viewHeight = windowHeight;
	
	var divHeight = imageHeight + 100;
	var topBound = $('body').scrollTop();
	var bottomBound = $('body').scrollTop() + viewHeight;
	
	xcoord = fromLeft;
	ycoord = fromTop;

  xcoord += offsetfrommouse[0];
	ycoord -= (divHeight / 2);
	
  // Adjust if necessary - height
	if (ycoord < topBound) {
		ycoord = (topBound + 10); // just a bit below the top of the view
	} else if (ycoord > (bottomBound - divHeight)) {
		ycoord = (bottomBound - divHeight);
	}
	
	// Adjust if necessary - width
	if (xcoord > (viewWidth - imageWidth)) {
		xcoord -= (imageWidth + (offsetfrommouse[0] * 2));
	}
  
  gettrailobj().css('left', xcoord + "px");
  if (gettrailobj().css('top') == '0px') {
    gettrailobj().css('top', ycoord + "px");
  }
  
}


// Displays advanced search box, hides link for showing and displays link for hiding advanced box
function displayAdvancedSearchForm() {
  try {
    showAdvancedTab("adv_quick");
    $("#adv_hide_link").show();
    $("#adv_link").hide();
    $("#adv").show();
    isAdvancedSearchLoaded = true;
  } catch (e) {}
}
    
// Hides advanced box, shows link for showing and hides link for hiding advanced box
function hideAdvancedSearchForm() {
  try {
    $("#adv_hide_link").hide();
    $("#adv_link").show();
    $("#adv").hide();
  } catch (e) {}
}

// Changes between tabs
function showAdvancedTab(tab) {
  try {
  
    // First we turn them of all
    var divs = $('#adv_tabs > div');
    for (i = 0; i < divs.length; i++) {
      if ($(divs[i]).hasClass('advanced_tab') == true) {
        $(divs[i]).hide();
      }
    }
    
    $('#link_adv_quick').removeClass();
    $('#link_adv_concept').removeClass();
    $('#link_adv_people').removeClass();
    $('#link_adv_scene').removeClass();
    $('#link_' + tab).addClass('selecttab');
    
    // Than turn on the chosen one
    $("#" + tab).show();
    
  } catch (e) { }
}

// Update simple text
function updateSimpleText() {
  try {
    var searchbox = $('#f-search');
    searchbox.val('');

    include = $('#search_include').val().split(' ');
    for (i=0; i < include.length; i++) {
      if (include.length > 0) {
        var val = searchbox.val();
        searchbox.val(val + (searchbox.val().length > 0 ? ' ' : '') + include[i]);
      }
    }

   exclude = $('#search_exclude').val().split(' ');
    for (i=0; i < exclude.length; i++) {
      if (exclude[i].length > 0) {
        var val = searchbox.val();
        searchbox.val(val + (searchbox.val().length > 0 ? ' ' : '') + '-' + exclude[i]);
      }
    }
  } catch (e) { }
}

// Resets form - because of setting values after search action, we cannot use just form.reset(),
// so it goes through form.elements[] and unsets checkboxes, selects and text inputs manually
function resetForm() {
  try {
  
    var topSearch = $("#topSearchForm");
    $("input,select", topSearch).each(function (el) {
      
      if ($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio') {
      
        $(this).attr('checked', false);
        
      } else if ($(this).attr('type') == 'select-multiple') {
      
        $("option", $(this)).each(function (opt) {
          $(this).attr('selected', false);
        });
        
      } else if ($(this).attr('type') == 'text') {
      
        $(this).val('');
        
      }
      
    });

    $('#adv_clear').hide();
    
  } catch (e) {  }
}


// Showing clear link (yes|no)
function showClearLink() {
  try {
    var show = false;
    var topSearch = $("#topSearchForm");
    $("input,select", topSearch).each(function (el) {
      
      if (!$(this).is(':hidden')) {
        
        if ($(this).attr('type') == 'checkbox' && $(this).attr('checked') == true) {
          if ($(this).attr('name') != "collection[]") {
            show = true;
          }
        } else if ($(this).attr('type') == 'select-multiple' && $(this).get(0).selectedIndex != -1) {
          show = true;
        } else if ($(this).attr('type') == 'text' && $(this).val() != '') {
          show = true;
        }
        
      }
      
    });
    
    if (show == true) {
      $('#adv_clear').show();
    } else {
      $('#adv_clear').hide();
    }
  } catch (e) {  }
}

// prepina advanced search po realoadu
// Not sure what this actually does...
function showAdvancedSearch(section) {
    displaySearch = readCookie("displaySearch");
    if (displaySearch == 1) {
      menuZobraz('advanced_search_form');
      zmenZnamenkoAdvanced(section)
    }
}

// Clear option of chosen selection
function clearOption(nameOption) {
  try {
    $("option", $("#"+nameOption)).each(function(el) {
      $(this).attr('selected', false);
    });
    
    showClearLink();
    $("#" + nameOption + '_Link').hide();
  } catch (e) { }
}

// Show clear option 
function showClearOptionLink(nameLink, value) {
  var showLink = false;
  if (value != 'undefined') {
    showLink = true;
  }
  if (showLink == true) {
    $("#"+nameLink).show();
  } else {
    $("#"+nameLink).hide();
  }
}

// Empty function
function synchroniseInputs() {
}

// Homepage functions

function updateAdvText(searchstring) {

  try {
    searchstring = searchstring.split(' ');
    var include = $('#f-include');
    var exclude = $('#f-exclude');
    if (include) {
      include.val('');
    }
    if (exclude) {
      exclude.val('');
    }
    
    var inVal = '';
    var exVal = '';
    
    for (i=0; i < searchstring.length; i++) {
      if (searchstring[i].charAt(0) == '-') {
        exVal += (exVal.length > 0 ? ' ' : '') + searchstring[i].substr(1);
      } else {
        inVal += (inVal.length > 0 ? ' ' : '') + searchstring[i];
      }
    }
    
    include.val(inVal);
    exclude.val(exVal);
    
  } catch (err) {
    
  }
}


function submitSearch() {

  if (lastInput == "advanced") {
    updateSimpleText();
  } else if ("simple") {
    updateAdvText($('#f-search').val());
  }
  setTimeout("doSubmitSearch()", 50);
  return false;
}

function doSubmitSearch() {
	$('#topSearchForm').submit();
}

function showIntroduction() {
  $('#topA').className = '';
  $('#intA').className = 'activelink';
  $('#right_home_content').show();
  $('#right_home_topsearches').hide();
}

function showCategories() {
  $('#intA').className = '';
  $('#topA').className = 'activelink';
  $('#right_home_topsearches').show();
  $('#right_home_content').hide();
}


function showPowerSearch() {
  $(document).ready(function() {
    $('body').removeClass('page-homepage');
    $('body').addClass('page-advanced-search');
    try {
      pageTracker._trackEvent('Search', 'PowerSearch', 'Open');
    } catch (e) {}
  });
}

function hidePowerSearch() {
  $(document).ready(function() {
    $('body').removeClass('page-advanced-search');
    $('body').addClass( $('#bodyClass').html() );
    try {
      pageTracker._trackEvent('Search', 'PowerSearch', 'Close');
    } catch (e) {}
  });
}

function changeOrderBy(orderby) {
    $("#orderby").val(orderby);
    $("#topSearchForm").submit();
}

function changeCollection(collection) {
	$("#collection").val(collection);
    $("#topSearchForm").submit();
}

function regenerate(objectId) {
	jQuery.get("/service", {'ajax':'ImageAjax', 'action': 'regenerate', 'objectId': objectId});
}


/****************/
/*** LIGHTBOX ***/
/****************/


/**
 * Loads items to actual lightbox
 * 
 * @return nothing
 */
function loadActualLightbox() {
	var actualLightboxId = $('#f-favorites').val();
	loadLightbox(actualLightboxId);
}

/**
 * Loads items to specified lightbox 
 * 
 * @param lightboxId specified lightbox id
 * @return nothing
 */
function loadLightbox(lightboxId) {
    jQuery.getJSON("/service", {'ajax':'LightboxAjax', 'action': 'show:lightboxContent,getLightboxes:lightboxSelect,getNumberOfPhotos:numberOfPhotos', 'lightboxId': lightboxId}, 
        function(data, status) {
            if (status == "success") {
                $('#lightboxFoto').html(data.result['lightboxContent']);
                $('#f-favorites').html(data.result['lightboxSelect']);
                $('#numberOfPhotos').html(data.result['numberOfPhotos']);
				$('#canvas-lightbox-content .thumbs ul').css({'width':data.result['numberOfPhotos'] * 165});
            }
        }
    );
}

function ajaxLoad(ajaxClass, actions, parameters) {
	var actionStrings = "";
	for (var name in actions) {
		actionStrings = actionStrings + name + ":" + actions[name] + ",";
	}
	actionStrings = actionStrings.substr(0,actionStrings.length - 1);
	parameters = parameters.concat({'ajax':ajaxClass, 'action':actionStrings}); 
	jQuery.getJSON("/service", parameters, 
        function(data, status) {
            if (status == "success") {
				for (var name in actions) {
				    $('#' + name).html(data.templates[name]);
				}
//                $('#lightboxFoto').html(data.lightboxContent);
//                $('#f-favorites').html(data.lightboxSelect);
//                $('#numberOfPhotos').html(data.numberOfPhotos);
//                $('#canvas-lightbox-content .thumbs ul').css({'width':data.numberOfPhotos * 160});
            } else {
				alert(status);
			}
        }
    );
}

/**
 * Adds specified object to selected lightbox
 * @param objectId object to be added to selected lightbox
 * @return nothing
 */
function addObjectToLightBox(objectId) {
	var actualLightboxId = $('#f-favorites').val();
//	ajaxLoad("LightboxAjax", {'add':'add','show':'lightboxContent','getLightboxes':'lightboxSelect','getNumberOfPhotos':'numberOfPhotos'}, {'lightboxId': actualLightboxId, 'objectId': objectId});
	jQuery.getJSON("/service", {'ajax':'LightboxAjax', 'action': 'add:add,show:lightboxFoto,getLightboxes:f-favorites,getNumberOfPhotos:numberOfPhotos', 'lightboxId': actualLightboxId, 'objectId': objectId}, 
		function(data, status) {
            if (status == "success") {
                $('#lightboxFoto').html(data.result['lightboxFoto']);
                $('#f-favorites').html(data.result['f-favorites']);
                $('#numberOfPhotos').html(data.result['numberOfPhotos']);
				$('#canvas-lightbox-content .thumbs ul').css({'width':data.result['numberOfPhotos'] * 165});
			}
        }
    );
}

/**
 * Removes specified object from selected lightbox
 * @param objectId object to be removed from selected lightbox
 * @return nothing
 */
function removeObjectFromLightBox(objectId) {
    var actualLightboxId = $('#f-favorites').val();
	jQuery.getJSON("/service", {'ajax':'LightboxAjax', 'action': 'remove:remove,show:lightboxContent,getLightboxes:lightboxSelect,getNumberOfPhotos:numberOfPhotos', 'lightboxId': actualLightboxId, 'objectId': objectId}, 
        function(data, status) {
            if (status == "success") {
                $('#lightboxFoto').html(data.result['lightboxContent']);
                $('#f-favorites').html(data.result['lightboxSelect']);
                $('#numberOfPhotos').html(data.result['numberOfPhotos']);
                $('#canvas-lightbox-content .thumbs ul').css({'width':data.result['numberOfPhotos'] * 165});
            }
        }
    );
}


/**
 * Hides all actions
 * 
 * @param preserveSelectedAction preserve selected action in select actions selectbox
 * @return nothing
 */
function hideAllActions(preserveSelectedAction) {
	if (preserveSelectedAction == true) {
	
	} else {
		// set action to -select action- 
		//TODO
		document.getElementById('lightboxAction').selectedIndex = 0;
	    //$('#ligbtboxAction').val('');
	}  
    $('#lightboxActions').children().each(function() {
        $(this).hide();
    });
}

/**
 * Opens dialog for selected action
 * 
 * @param string action id
 */
function switchActions(action) {
    hideAllActions(true);
    switch (action) {
        case "create":
            $('#newLightboxName').val('');
            $('#actionNewLightbox').show();
            break;
        case "rename":
		    $('#renameLightboxName').val('');
			$('#actionRenameLightbox').show();
            break;
        case "sendEmail":
		    $('#mailName').val('');
            $('#mailText').val('');
            $('#actionSendMail').show();
            break;
        case "showUrl":
		    $('#actionShowUrl').show();
		    var actualLightboxId = $('#f-favorites').val();
		    $('#favoritesUrl').load('/service', {ajax: 'LightboxAjax', action: 'getUrl', 'lightboxId': actualLightboxId});
            break;
		case "showFullLightbox":
		    closeLightbox();
		    var actualLightboxId = $('#f-favorites').val();
			jQuery.getJSON("/service", {'ajax':'LightboxAjax', 'action': 'getUrl:url', 'lightboxId': actualLightboxId}, 
		        function(data, status) {
		            if (status == "success") {
						location.href = data.result['url'];
		            }
		        }
		    );
            break;
        case "delete":
		    $('#actionDeleteLightbox').show();
            break;
        case "removeSelected":
		    $('#actionRemoveSelected').show();
            break;
     	case "moveToLightbox":
	        $('#actionMoveLightbox').show();
			$('#moveLightboxName').load("/service", {'ajax':'LightboxAjax', 'action': 'getLightboxes'});
            break;
        case "copyToLightbox":
            $('#actionCopyLightbox').show();
            $('#copyLightboxName').load("/service", {'ajax':'LightboxAjax', 'action': 'getLightboxes'});
            break;
//        case "buySelected":
//        case "buyLightbox":
//            ajaxRequest('/service', 'GET', {ajax: 'LightboxAjax', action: 'getSizes', lbId: lightboxId, all:(akce=='buyLightbox')}, null, true);
//            break;
        case "searchSimilar":
            doAction("searchSimilar");
            break;
		//TODO check out what these do if anything, delete if possible
        case "display":
            ajaxRequest('/service','POST', {ajax: 'LightboxAjax', action: 'showFull'},false,false,'','','obsahLightbox');
            document.getElementById('zalozkaLightbox').style.display = 'block';
            prepniNaLightbox();
            zalozkaAktivuj('12');        
            break;
        
        default:
		    if (action != '') {
                alert(action);
			}
            break;
    } // end switch(action)
}

/**
 * Perform selected action
 * @param string action selected action
 */
function doAction(action) {
    switch(action) {
        case "create":
            var name = document.getElementById('newLightboxName').value; 
            if (name != null) {
                $('#f-favorites').load("/service", {'ajax':'LightboxAjax', 'action': 'createLightbox', lbName: name}, function(text, status, request) {handleStatus(status, text); loadActualLightbox()});
            }
            break;        
        case "rename":
		    var actualLightboxId = $('#f-favorites').val();
			var name = $('#renameLightboxName').val();
			$('#f-favorites').load("/service", {'ajax':'LightboxAjax', 'action': 'renameLightbox', lightboxName: name, lightboxId: actualLightboxId});
            break;    
        case "delete":
            $('#f-favorites').load("/service", {'ajax':'LightboxAjax', 'action': 'deleteLightbox', lightboxId: $('#f-favorites').val()}, function(text, status, request) {loadActualLightbox();});
            cancelAll();
            break;
        case "moveToLightbox":
		    var actualLightboxId = $('#f-favorites').val();
			var destinationLightboxId = $('#moveLightboxName').val();
			// move pictures to destination lb and select destination lb
            $('#f-favorites').load("/service", {'ajax':'LightboxAjax', 'action': 'moveObjectsToLightbox', 'lightboxId': actualLightboxId, 'destinationLightboxId': destinationLightboxId}, function(text, status, request) {loadActualLightbox();});
            break;
        case "copyToLightbox":
            var actualLightboxId = $('#f-favorites').val();
            var destinationLightboxId = $('#copyLightboxName').val();
            // copy pictures to destination lb and select destination lb
            $('#f-favorites').load("/service", {'ajax':'LightboxAjax', 'action': 'copyObjectsToLightbox', 'lightboxId': actualLightboxId, 'destinationLightboxId': destinationLightboxId}, function(text, status, request) {loadActualLightbox();});
            break;
        case "removeSelected":
		    var actualLightboxId = $('#f-favorites').val();
		     $('#lightboxFoto').load("/service", {'ajax':'LightboxAjax', 'action': 'removeSelected', 'lightboxId': actualLightboxId}, function(text, status, request) {});
             break;  
//        case "buySelected":
//        case "buyLightbox":
//            var lightboxSelect = document.getElementById("lightboxVyber");
//            var lightboxID = lightboxSelect.options[lightboxSelect.selectedIndex].value;
//            var sizeSelect = document.getElementById("buyPictureSize");
//            var sizeID = sizeSelect.options[sizeSelect.selectedIndex].value;
//            ajaxRequest('/service', 'POST', {ajax: 'LightboxAjax', action: 'buySelected', lightboxID: lightboxID, sizeID: sizeID, all:(action=='buyLightbox'), onComplete: cancelAction('actionBuySelected')}, false, true, 'makeShow');
//            break;
        case "searchSimilar":
            var checks = document.getElementsByTagName("input");
            var selectedCount = 0;
            for (i = 0; i < checks.length; i++) {
                if (checks[i].className == "lbCheck") {
                    if (checks[i].checked == true) {
                        selectedCount++;
                    }
                }
            }
            if (selectedCount < 2) {
                alert('Please select at least two pictures');
                break;
            }
            var lightboxSelect = document.getElementById("lightboxVyber");
            var lightboxId = lightboxSelect.options[lightboxSelect.selectedIndex].value;
            var redirectUrl = "/similar-pictures/lightbox/" + lightboxId;
            window.location.href = redirectUrl;
            break;
        case "sendEmail":
		     var actualLightboxId = $('#f-favorites').val();
             var email = $('#mailName').val();
             var text = $('#mailText').val();
             if (email != null) {
			 	 jQuery.get("/service", {'ajax':'LightboxAjax', 'action': 'sendLightbox', 'email': email, lightboxId: actualLightboxId, 'text': text});
             }
             break;                     
    }
    hideAllActions();
}

/**
 * Mark object as selected
 * @param integer objectId
 */
function lightboxCheck(objectId) {
	var actualLightboxId = $('#f-favorites').val();
	jQuery.get('/service', {ajax: 'LightboxAjax', 'action': 'check', 'objectId': objectId, lightboxId: actualLightboxId}, function(text, status, request) {
		$('#check' + objectId).attr('checked', (text == "true" ? true : false));
	});
}

/**
 * 
 * @param {Object} status
 * @param {Object} text
 */
function handleStatus(status, text) {
	if (status != "success") {
        $('body').prepend(text);
		$('#messageBox').slideDown(1000);
	}
}

function openLightbox() {
	$('body').addClass('page-lightbox').addClass('page-lightbox-switch');
	$.get("/service", {'ajax': 'LightboxAjax', 'action': 'open'});
	try {
		if (loadWithOpen) {
			loadActualLightbox();
			loadWithOpen = false;
		}
	} catch(error) {}
 
  lightbox();
}

function closeLightbox() {
	$('body').removeClass('page-lightbox').addClass('page-lightbox-switch'); 
	$.get("/service", {'ajax': 'LightboxAjax', 'action': 'close'});
  $('#canvas-content').css({'height' : ''});
}

function lightboxSelectAll() {
    var actualLightboxId = $('#f-favorites').val();
    jQuery.getJSON("/service", {'ajax':'LightboxAjax', 'action': 'checkAll:check,show:lightboxContent', 'lightboxId': actualLightboxId}, 
        function(data, status) {
            if (status == "success") {
                $('#lightboxFoto').html(data.result['lightboxContent']);
            }
        }
    );
}

function lightboxDeselectAll() {
    var actualLightboxId = $('#f-favorites').val();
    jQuery.getJSON("/service", {'ajax':'LightboxAjax', 'action': 'uncheckAll:check,show:lightboxContent', 'lightboxId': actualLightboxId}, 
        function(data, status) {
            if (status == "success") {
                $('#lightboxFoto').html(data.result['lightboxContent']);
            }
        }
    );
}

function lightboxInvertSelection() {
    var actualLightboxId = $('#f-favorites').val();
    jQuery.getJSON("/service", {'ajax':'LightboxAjax', 'action': 'checkInvert:check,show:lightboxContent', 'lightboxId': actualLightboxId}, 
        function(data, status) {
            if (status == "success") {
                $('#lightboxFoto').html(data.result['lightboxContent']);
            }
        }
    );
}


/********** OLD TO BE CHECKED AND DELETED ***************/


function lightboxSent() {
	hideMsgBox(true);
}

function objectsMoved() {
	refreshFullLightbox(document.getElementById('lightboxVyber').value);
	hideMsgBox(true);
}

function objectsCopied() {
	refreshFullLightbox(document.getElementById('lightboxVyber').value);
	hideMsgBox(true);
}

function changeState(id)
{
	if (document.getElementById('check' + id)!=null)
	{
		if (document.getElementById('check' + id).checked == true)
		{
			document.getElementById('check' + id).checked = false;
            document.getElementById('lbObj' + id).style.borderColor = '#d3d3d3';
            document.getElementById('caption' + id).style.background = "none";
		}
		else
		{
			document.getElementById('check' + id).checked = true;
            document.getElementById('lbObj' + id).style.borderColor = '#ec008c';
            document.getElementById('caption' + id).style.background = "url(/image/lightbox-arrow.gif) no-repeat center center";
		}
	}
}

//function reloadLightbox() {
//	return;
//	var actualLightboxId = document.getElementById('lightboxVyber').options[document.getElementById('lightboxVyber').selectedIndex].value;
//	var lightboxSize = readCookie('lightboxSize');
//	if (lightboxSize == 1) {
//	   refreshFullLightbox(actualLightboxId);
//	} else {
//	   refreshBigLightbox(actualLightboxId);
//	}
//	updateCheckboxes();
//}
	
function changeLightbox(id) {
	cancelAll();
	ajaxRequest('/service', 'POST', {ajax:'LightboxAjax', action:'Lightbox', value: id}, false, false, 'reloadLightbox', '', 'lightboxFoto');
}
	
function updateCheckboxes() {
	var pictures = document.getElementsByClassName('object_info_lightbox');
	var selected = 0;
	for (var i in pictures) {
		if ((typeof(pictures[i]) == 'object')) {
			var checkbox = pictures[i].getElementsByTagName('input')[0];
			if (checkbox != null) {
    			if (document.getElementById('lbObj'+checkbox.id.substring(checkbox.id.indexOf('_')+1)) == null) {
    				checkbox.checked = false;
    			} else {
    				checkbox.checked = true;
    			}
			}
		}
	}
}

///**
// * Zobrazi maximalizovany lightbox
// */
function refreshBigLightbox(lightbox) {
    ajaxRequest('/service','POST', {ajax: 'LightboxAjax', action: 'lightbox', value: lightbox}, false, false, 'callAjaxUpdateActions', '', 'lightboxFoto');
    return;
}

function lightboxCommentLink() {
    var id = document.getElementById('lightboxVyber').options[document.getElementById('lightboxVyber').selectedIndex].value
    var note = document.getElementById('lightboxComment').style;
    var status;
    if(note.display == 'block') {
       status = 0;
       note.display = 'none';              
    } else {
       status = 1;
       note.display = 'block';              
    }
    ajaxRequest('/service','POST', {ajax: 'LightboxAjax', action: 'showComment', id: id, status: status},false,false);            
}


function lightboxSetNote(text)
{       
    var lightboxID = document.getElementById('lightboxVyber').value;
    ajaxRequest('/service', 'GET', {ajax: 'LightboxAjax', action: 'SetNote', lbID: lightboxID, text: text}, null, null);
}


function refreshFullLightbox(lightbox)
{
	$.getScript("/service/ajax/LightboxAjax/action/lightbox/value/" + lightbox);
	//ajaxRequest('/service','POST', {ajax: 'LightboxAjax', action: 'lightbox', value: lightbox}, false, false, 'callAjaxUpdateActions', '', 'lightboxFoto');
	return;
}

function lightboxRemove(objektID)
{
	checkbox = document.getElementById('checkbox_' + objektID);
	if (checkbox != null) {
		checkbox.checked = false
	}

	ajaxRequest('/service','POST', {ajax: 'LightboxAjax', action: 'delete', objektID: objektID},false,true,'makeShow');
}

function lightboxAddPhoto(object) {
    ajaxRequest('/service', 'POST', {ajax:'LightboxAjax', action:'add', objektID: object}, false, true);//,'makeShow','','lightboxFoto');
}

function makeShow()
{
	alert("reload");
	var actualLightboxId = document.getElementById('lightboxVyber').options[document.getElementById('lightboxVyber').selectedIndex].value;
	ajaxRequest('/service','POST', {ajax: 'LightboxAjax', action: 'Lightbox', value: actualLightboxId},false,false,'updateCheckboxes','','lightboxFoto');
}





// REDESIGN

/**
 * Zobrazi lightbox v dane velikosti, pokud neni velikost zadana, tak v posledni zadane velikosti(ulozeno v cookie)
 */
function displayLightbox(lightboxSize) {
	if (lightboxSize == undefined) {
		lightboxSize = readCookie('lightboxSize');
		if (!lightboxSize) {
			lightboxSize = 1;
		}
	}
	// pokud je promo tak to nezvetsujem
	/*if (typeof lightboxPromo != "undefined") {
		lightboxSize = 0;
	}*/
	createCookie("lightboxSize", lightboxSize, 7);
	var lightbox = document.getElementById("lightbox");
	var container = document.getElementById("container");
	var windowHeight = getWindowHeight();
	var lightboxHeadHeight = 35;
	var lightboxBodyHeight = 180;
	// aktivujeme vsecky ikony a potom deaktivujeme tu jednu na kterou se kliklo
//	if (typeof lightboxPromo == "undefined") {
//		document.getElementById("lightboxMinimizeButton").innerHTML = '<img src="/image/lightbox-minimize1.gif" />';
//		document.getElementById("lightboxDisplayButton").innerHTML = '<img src="/image/lightbox-small1.gif" />';
//		document.getElementById("lightboxMaximizeButton").innerHTML = '<img src="/image/lightbox-fullsize1.gif" />';
//	}
//	if (lightboxSize == 0) {
//		lightbox.style.height = lightboxHeadHeight + "px";
//		container.style.height = (windowHeight - lightboxHeadHeight) + "px";
//		if (document.getElementById("lightboxMinimizeButton")) {
//		    document.getElementById("lightboxMinimizeButton").innerHTML = '<img src="/image/lightbox-minimize0.gif" />';
//		}
//	} else if (lightboxSize == 1) {
//		lightbox.style.height = (lightboxHeadHeight + lightboxBodyHeight)+ "px";
//		container.style.height = (windowHeight - lightboxHeadHeight - lightboxBodyHeight) + "px";
//		document.getElementById("lightboxDisplayButton").innerHTML = '<img src="/image/lightbox-small0.gif" />';
		reloadLightbox();
//	} else if (lightboxSize == 2) {
//		container.style.height = 0 + "px";
//		lightbox.style.height = 'auto';//windowHeight + "px";
//		document.getElementById("lightboxMaximizeButton").innerHTML = '<img src="/image/lightbox-fullsize0.gif" />';
//		reloadLightbox();
//	}
}

/**
 * Prepina z minimalizovaneho na stredni
 */
function switchLightboxSize() {
	lightboxSize = readCookie('lightboxSize');
	if (lightboxSize == 0) {
		displayLightbox(1);
	} else if (lightboxSize == 1 || lightboxSize == 2) {
		displayLightbox(0);
	} 
}

function provedSkriptik() {
      eval(document.getElementById('scriptik').value);
      
}

function zamerFocus() {
      eval(document.getElementById('focusField').value);
}



function cancelAction(action) {
    if (action == '') {
        hideAllActions();
    } else {
        document.getElementById(action).style.display = 'none';
    }
    document.getElementById('lightboxActions').style.display = 'inline';
    document.getElementById('lightboxAction').selectedIndex = 0;    
}

function cancelAll() {
    document.getElementById('lightboxActions').style.display = 'inline';
	$('#actionNewLightbox').hide();
//    document.getElementById('actionNewLightbox').style.display = 'none'; 
    document.getElementById('actionRenameLightbox').style.display = 'none'; 
    document.getElementById('actionDeleteLightbox').style.display = 'none'; 
    document.getElementById('actionCopyLightbox').style.display = 'none'; 
    document.getElementById('actionMoveLightbox').style.display = 'none';
    document.getElementById('actionRemoveSelected').style.display = 'none'; 
    document.getElementById('actionSendMail').style.display = 'none';     
    document.getElementById('actionShowUrl').style.display = 'none';     
}



function displayBuySelected(sizes, all) {
    if (sizes.length > 0) {
        var i;
        var sizeSelect = document.getElementById('buyPictureSize');
        sizeSelect.innerHTML = '';
        var option;
        for(i=0; i<sizes.length; i++) {
            option = document.createElement('option');
            option.label = sizes[i]['description'];
            option.innerHTML = sizes[i]['description'];
            option.value = sizes[i]['sizeID'];
            sizeSelect.appendChild(option);
        }
        document.getElementById('actionBuySelected').style.display = 'inline';
        if (all) {
            document.getElementById('lightboxOptions').style.display = 'inline';
            document.getElementById('selectedOptions').style.display = 'none';
        } else {
            document.getElementById('selectedOptions').style.display = 'inline';
            document.getElementById('lightboxOptions').style.display = 'none';
        }
    } else {
        document.getElementById('actionBuySelectedNone').style.display = 'inline';
    }
}

function callAjaxUpdateActions() {
    ajaxRequest('/service','POST', {ajax: 'LightboxAjax', action: 'updateActions', value: lightbox}, false, true);
}

function updateActions(numSelected) {
    if (numSelected == 0) { // Changes for when nothing is selected
        document.getElementById('copyToLightboxOption').style.display = 'none';
        document.getElementById('moveToLightboxOption').style.display = 'none';
        document.getElementById('removeSelectedOption').style.display = 'none';
        document.getElementById('buySelectedOption').style.display = 'none';
        document.getElementById('buyLightboxOption').style.display = '';
    } else { // Changes for when something is selected
        document.getElementById('copyToLightboxOption').style.display = '';
        document.getElementById('moveToLightboxOption').style.display = '';
        document.getElementById('removeSelectedOption').style.display = '';
        document.getElementById('buySelectedOption').style.display = '';
        document.getElementById('buyLightboxOption').style.display = 'none';
    }
}


/************/
/*** AJAX ***/
/************/

// Needs to be removed from all our script and replaced by jQuery method

/***/

/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* 2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */
/* Modified by Tomas Vosatka, Clapix s.r.o. */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.loading = false;
  		this.loadingElement = 'ajaxStatusWindow';
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.childID = null;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onComplete = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};
	
	this.setLoading = function() {
        if (document.getElementById(this.loadingElement) == null)
        {
    	    var x = document.createElement('div');
    	    x.setAttribute('id',this.loadingElement);
    	    x.className = 'hideLoading';
    		document.body.appendChild(x);
		}
	    
        var e = document.getElementById(this.loadingElement);
	    
        this.onLoading = function() 
        {
            if (e)
            {
                var posX = Math.round(document.body.scrollLeft + (document.body.clientWidth / 2 - 10));
                var posY = Math.round(document.body.scrollTop + (document.body.clientHeight / 2 - 10));
				e.style.left = posX.toString()+'px';
                e.style.top = posY.toString()+'px';
                e.className = 'showLoading';
            } 
        }

        this.onLoaded = function()
        {
            this.onLoading();
        }
        
        this.onComplete = function()
        {
	    	if (e)
	        {
                e.className = 'hideLoading';
            }
        }   
    }

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
			    if (this.loading)
			    {
                    this.setLoading();
                }
			
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				        this.xmlhttp.setRequestHeader("Content-length", this.URLString.length);
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

                            
							if (self.execute) {
								self.runResponse();
								// TODO AJAX LIGHTBOX VYCHYTAVKA POZOR NA TO	
	                            self.onComplete();
	                            if (self.responseStatus[0] == "200") 
	                            {
	                                self.onCompletion(self,self.childID);
	                            } else {
	                                self.onError();
	                            }
	
	                            self.URLString = "";													
								return;
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
//								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
                            self.onComplete();
							if (self.responseStatus[0] == "200") 
                            {
								self.onCompletion(self,self.childID);
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};
				if (this.method == "GET")
				{
					this.URLString = null;
				}
				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}

/**
 *  Funkce zavola ajaxovy pozadavek a podle parametru provede vysledek.
 *  Je vhodne funkci volat jako onclick="return ajaxRequest(...);" - funkce vraci false a zamezi tak
 *  zastaveni nacitani zbytku stranky v IE.
 *
 *  Parametry
 *  ========= 
 *      url:                (string) URL na kterou se odesle pozadavek
 *      method:             (string) POST nebo GET, defaultne POST
 *      params:             (array) dalsi doplnujici parametry (napr. pro GET ve tvaru {param1:'hodnota1',param2:'hodnota2'}), bez parametru uvedte hodnotu {}   
 *      loading:            (boolean) true / false zda se  ma zobrazovat ikonka informujici o prubehu pozadavku 
 *      evaling:            (boolean) true / false zda se ma vysledek pozadavku rovnou provest pomoci metody eval()
 *      returnFunc:         (string) jmeno funkce, ktere se preda instance na ajaxRequest jako prvni parametr - pote lze s vysledkem 
 *                                   provadet cokoliv, evalovat, parsovatXML atd. - dosupne ve vlastnostech instance.response, 
 *                                   instance.responseXML, instance.responseStatus atd.
 *                                   pokud neni potreba, uvedte jako hodnotu parametru '' nebo null 
 *      returnFuncParam:    (mixed) druhy parametr, ktery bude predat funkci returnFunc (napr. ID elementu, cislo pro porovnani apod.)
 *      returnElement:      (string) id elementu do ktereho se primo vrati vysledek pozadavku - jako value pro SELECT, INPUT, OPTION, 
 *                                   TEXTAREA nebo jako innerHTML pro ostatni elementy
 *                                   pokud neni potreba, uvedte jako hodnotu parametru '' nebo null 
 */
function ajaxRequest(url, method, params, loading, evaling, returnFunc, returnFuncParam, returnElement, opener, winOpener) {
	var ajax = new sack();
	
	switch(method) {
		case 'POST' : 
		case 'GET':
			break;
		default : method = 'POST';
	}

	ajax.reset();
	
	if (params) {
		for (key in params) {
			ajax.setVar(key, params[key]); 
		}
	}
	
	if (loading == true) {	
		ajax.loading = true;
	} 

	ajax.requestFile = url;
	ajax.method = method;
	
	if (evaling == true) {
    ajax.execute = true;
  }
    
  if (returnElement != '' && returnElement != null) {
    ajax.element = returnElement;
  }
    
  if (returnFunc != '' && returnFunc != null) {
	  ajax.childID = returnFuncParam;
	  if (eval("window."+returnFunc)) ajax.onCompletion = eval(returnFunc);
	}
	
	ajax.runAJAX();
	
	return false;
}


/**
 *	DESIGN functionality
 * 
 *	@author Ondrej Valka  
 */

function thumbee() {

	// create equal spaces between single thumbnails
	// thumbnail image: 170px, borders: 2px, margins: 8px = 180px

	var body = $('#body');
	var bodyWidth = body.width() - 18;

	var freeSpace = bodyWidth % 180;
	var rowCount = (bodyWidth - freeSpace) / 180;

	var thumbMargin = Math.floor((freeSpace / rowCount) / 2) + 4;

	var css = {
		'margin-left' : thumbMargin,
		'margin-right' : thumbMargin
	}
	$('.non-ie6 .thumbs-result li').css(css);

	var css = {
		'margin-left' : thumbMargin - 1,
		'margin-right' : thumbMargin - 1
	}
	$('#ie7 .thumbs-result li').css(css);
	$('#ie6 .thumbs-result li').css(css);

	// center .thumbs

	var spaceTakenByThumbnails = (172 + thumbMargin*2) * rowCount;
	var bodyMargin = Math.round((bodyWidth - spaceTakenByThumbnails) / 2);

	var css = {
		'margin-left' : bodyMargin + 9
	}
	$('.non-ie6 .thumbs-result').css(css);
	$('.non-ie7 .thumbs-result').css(css);
}

function lightbox() {

  try {
  	var content = $('.page-lightbox #canvas');
  	var contentHeight = content.height();
    
  	var lightbox = $('.page-lightbox #canvas-lightbox');
  	var lightboxHeight = lightbox.height();
    
    var contentFinalHeight = parseInt(contentHeight) - parseInt(lightboxHeight);
  	$('.page-lightbox #canvas-content').css('height', contentFinalHeight + 'px');
  	
  	$('.page-lightbox #footer').css('margin-bottom', 0);
  	
	} catch (e) { }
  
}
