$(document).ready(function() {
  
  var bodyClass = $('body').attr('class');
  $('body').after('<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 = 200;
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, author, timestamp) {
	
  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">';
	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();
  
	setTimeout("displayTrail();", displayDelay);
	preview = new Image(width, height);
    preview.src = imageSrc;
  
}

function displayTrail() {
  
  try {
    $("#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 = $('#searchTextHorni');
    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($("#searchTextHorni").value);
  }
  return true;
}

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() {
  $('body').removeClass('page-homepage');
  $('body').addClass('page-advanced-search');
}

function hidePowerSearch() {
  $('body').removeClass('page-advanced-search');
  $('body').addClass( $('#bodyClass').html() );
}

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

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