$(document).ready(function(){
	
	// autosuggest
	jQuery('#organizers').hintbox({
		url: 'data/organizatori.txt',
		matchHint: true,
		matchRule: "C",
		onListLoaded: function(list) {
			hideEmptyHintList(list);
			fixWrongTop();
			
		}
	});
	jQuery('#locations').hintbox({
		url: 'data/lokacije.txt',
		matchHint: true,
		matchRule: "C",
		onListLoaded: function(list) {
			hideEmptyHintList(list);
			fixWrongTop();
		}
		
	});
	jQuery('#types').hintbox({
		url: 'data/tipovi.txt',
		matchHint: true,
		matchRule: "C",
		onListLoaded: function(list) {
			hideEmptyHintList(list);
			fixWrongTop();
		}
	});
	
	// second level category listing
	var items_on_page = 7;
	
	$('ul.level2').each(function() {
		if ($(this).children('li').size() > items_on_page)
		{
			var links =
				'<a href="#" class="prev" style="display: block; background: transparent url(/web_v2/img/prev.png) no-repeat 0 0; height: 16px; width: 16px; margin-top: -2px; position: absolute; left: 40px; z-index:1000; text-indent: -10000px;">Prev</a>' +
				'<a href="#" class="next" style="display: block; background: transparent url(/web_v2/img/next.png) no-repeat 0 0; height: 16px; width: 16px; margin-top: -2px; position: absolute; right: 40px; z-index:1000; text-indent: -10000px;">Next</a>';
			//$(this).before(links).css('padding-left', '20px').css('overflow','hidden');
			$(this).before(links).css('padding-left', '20px');
			
			var page = 1;
			var pages = Math.ceil($(this).children('li').size() / items_on_page);
			$(this).children('li:gt(' + (items_on_page-1) + ')').hide();
			var all_items = $(this).children('li');
			$(this).parent('div').children('a:eq(0)').fadeTo('slow', 0.4).click(function() {
				// previous
				$(this).parent().children('a:eq(1)').fadeTo(0, 1);
				if (page == 1) {
					return false;
				}
				page -= 1;
				var last = page * items_on_page;
				var first = last - items_on_page;
				var selector = ':lt(' + first + '),:gt(' + (last-1) + ')';
				$(all_items).show().filter(selector).hide();
				if (page == 1) {
					$(this).fadeTo('slow', 0.4);
				}
				else {
					$(this).fadeTo(0, 1)
				}
				return false;
			});
			$(this).parent('div').children('a:eq(1)').click(function() {
				// next
				$(this).parent().children('a:eq(0)').fadeTo(0, 1);
				if (page == pages)
				{
					return false;
				}
				page += 1;
				var last = page * items_on_page;
				var first = last - items_on_page;
				var selector = ':lt(' + first + '),:gt(' + (last-1) + ')';
				$(all_items).show().filter(selector).hide();
				if (page == pages) {
					$(this).fadeTo('slow', 0.4);
				}
				else {
					$(this).fadeTo(0, 1)
				}
				return false;
			});
		}
	});
	
	// search tool behavior
	var adSearchHeight = parseFloat($('#adsearch').height());
	var hideHeight = '-' + (adSearchHeight + 50) + 'px';
	var onClickSimpleSearch = function () {
		//$(this).toggleClass("off");
		$('#adsearch').animate({top:hideHeight},200,"swing",function() {
			$('#search').animate({top:"0px"},300,"swing");
		});
		
	}
	$('#simplesearch span').bind("click", onClickSimpleSearch);
	var onClickAdvancedSearch = function () {
		$('#search').animate({top:"-56px"},200,"swing",function() {
			$('#adsearch').animate({top:"0px"},300,"swing");
		});		
	}
	$('#advancedsearch').bind("click", onClickAdvancedSearch);
	
	
	// text inputs behavior
	var textInputs = $('input.txt, textarea.txt, .longinput, .shortinput, .login');
  textInputs
    // Store default values
    .each (function () {
      $(this).data ('default', {value: $(this).val()});
    })
    // Clear element on focus if default value
    .focus (function () {
      if ($(this).val () === $(this).data ('default').value) {
        $(this).val ('');
      }
    })
    // Restore element on blur if empty
    .blur (function () {
      if ($(this).val () === '') {
        $(this).val ($(this).data ('default').value);
      }
    });
	

	// poravnaj topcontent elemente
	timer = 0;
  var _timer = setInterval(function() {
		timer++;
    if (timer == 50) {
			clearInterval(_timer);
			//
			var tallest = 0;
			//var topcontent = $('#topcontent li div.nav_clanci');
			var topcontent = $('#topcontent div.clanak div.nav_clanci');
			topcontent.each(function () {
				thisHeight = $(this).height();
				if(thisHeight > tallest) {tallest = thisHeight;}
			});
			topcontent.each (function () {
				$(this).css ('height',tallest+'px');
			});
			thisHeight = parseInt(($("#topcontentlast").height())/15)*15-4;
			//topcontent = $('#topcontent li');
			topcontent = $('#topcontent div.clanak');
			topcontent.each(function () {
				$(this).height((thisHeight+55));
			});
			//
      pokreni_clanke();
    }
  }, 10);
	
	// Coloring of every second row in results list
	//$('#leftcontent ul, div#one-columnwrapper div#content ul:not(div#one-columnwrapper div#content div#reserve-tabs ul)').each(function() {
	//	$(this).find('li:even').css('background-color','#f4f4f4');
	//});
	
	// Padding removal of first tab element in ticket reservation
	$('div#one-columnwrapper div#content div#reserve-tabs ul#level1 li a:first').css('padding-left', '0');
	/*$('div#one-columnwrapper div#content div#reserve-tabs ul#level1 li a:not(div#one-columnwrapper div#content div#reserve-tabs ul#level1 li a a)').css('padding-right', '26px');*/
	$('div#one-columnwrapper div#content div#reserve-tabs ul#level1 li').children('a:last').css('padding-right', '0');
	$('div#one-columnwrapper div#content div#reserve-tabs ul#level1 li a:not(div#one-columnwrapper div#content div#reserve-tabs ul#level1 li a a):last').css('border-right', 'none');
	
	// Event picture hover
	$('div#leftcontent ul li a.eventicon').hover(
		function(){
			$(this).children('img').hide();
			$(this).children('span.icontext').show();
		},
		function(){
			$(this).children('img').show();
			$(this).children('span.icontext').hide();
		}
	);
	$('div#leftcontent ul li a.eventicon').each(function(i){
		var aHeight = parseInt($(this).height());
		var imgHeight = parseInt($(this).find('img').height());
		var marginHeight = parseInt((aHeight - imgHeight)/2) + 'px';
		$(this).find('img').css('margin-top',marginHeight);
	});
	
	// Ticket reservation tabs
	var $reservetabs = $('#reserve-tabs').tabs();
	// Next button behaviour
	$('div[id^=reserve-tabs-] a.boldbuttons-big, div[id^=reserve-tabs-] a.boldbuttons-big-prev').click(
		function(){
			var tabNum = parseInt($(this).attr('href')) - 1;
			console.log('tabnum: ' + tabNum);
			$reservetabs.tabs('select',tabNum);
			return false;
		}
	);
	
	// IE6 column stretching
	if ($.browser.msie && (parseInt($.browser.version) <= 6)) {
		var leftHeight = parseInt($('#leftcontent').height());
		var rightHeight = parseInt($('#rightcontent').height());
		
		if (leftHeight > rightHeight)
		{
      /* Right column with 2 sections */
			var newHeight = (
				leftHeight
				- parseInt($('#righttopcontent').height())
				- parseInt($('#rightbottomtop').height())
				- 36 - 37) + 'px';
			$('#rightbottomcontent').css('height',newHeight);
			
			/* Right column with only 1 section */
			var newHeight = (
				leftHeight
				- parseInt($('#righttop-1section').height())
				+ 'px'
			);
			$('#right-1section').css('height',newHeight);
			
		}
		else
		{
			var newHeight = (parseInt($('#rightcontent').height()) - 36) + 'px';
			$('#leftcontent #content').css('height',newHeight);
			
		}
		
		
	}
	
	/* Arrows by active links in event pages */
	var position = (parseInt($('ul#eventmenu li.active a').width()) + 5) + 'px 50%';
	$('ul#eventmenu li.active').css('background-image','url(images/arrow.gif)').css('background-repeat','no-repeat').css('background-position', position);
	
	// Selectbox
	/*$('#one-time-user select').selectbox();
	$('#one-time-user .selectbox-wrapper').css('width','279px');*/
});

// Don't show hintbox if there are no results.
function hideEmptyHintList(list) {
	if (list.find('li').size() == 0)
	{
		$('div.hintbox_list_container').hide();
	}
}

// The hintbox is 10px too low across all browsers, this is the fix.
function fixWrongTop() {
	var top = parseFloat($('div.hintbox_list_container').css('top'));
	var newTop = top - 10 + 'px';
	$('div.hintbox_list_container').css('top',newTop);
	
}

/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license and MIT:
 *   http://www.opensource.org/licenses/GPL-license.php
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
 * Revision: $Id$
 * Version: 0.5
 * 
 * Changelog :
 *  Version 0.5 
 *  - separate css style for current selected element and hover element which solve the highlight issue 
 *  Version 0.4
 *  - Fix width when the select is in a hidden div   @Pawel Maziarz
 *  - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
 */
jQuery.fn.extend({
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	}
});


/* pawel maziarz: work around for ie logging */
if (!window.console) {
	var console = {
		log: function(msg) { 
	 }
	}
}
/* */

jQuery.SelectBox = function(selectobj, options) {
	
	var opt = options || {};
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "current";
	opt.currentClass = opt.selectedClass || "selected"
	opt.debug = opt.debug || false;
	
	var elm_id = selectobj.id;
	var active = -1;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var $select = $(selectobj);
	// jquery container object
	var $container = setupContainer(opt);
	//jquery input object 
	var $input = setupInput(opt);
	// hide select and append newly created elements
	$select.hide().before($input).before($container);
	
	
	init();
	
	$input
	.click(function(){
    if (!inFocus) {
		  $container.toggle();
		}
	})
	.focus(function(){
	   if ($container.not(':visible')) {
	       inFocus = true;
	       $container.show();
	   }
	})
	.keydown(function(event) {	   
		switch(event.keyCode) {
			case 38: // up
				event.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				event.preventDefault();
				moveSelect(1);
				break;
			//case 9:  // tab 
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				$('li.'+opt.hoverClass).trigger('click');
				break;
			case 27: //escape
			  hideMe();
			  break;
		}
	})
	.blur(function() {
		if ($container.is(':visible') && hasfocus > 0 ) {
			if(opt.debug) console.log('container visible and has focus')
		} else {
			hideMe();	
		}
	});


	function hideMe() { 
		hasfocus = 0;
		$container.hide(); 
	}
	
	function init() {
		$container.append(getSelectOptions($input.attr('id'))).hide();
		var width = $input.css('width');
		$container.width(width);
    }
	
	function setupContainer(options) {
		var container = document.createElement("div");
		$container = $(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
		
		return $container;
	}
	
	function setupInput(options) {
		var input = document.createElement("input");
		var $input = $(input);
		$input.attr("id", elm_id+"_input");
		$input.attr("type", "text");
		$input.addClass(options.inputClass);
		$input.attr("autocomplete", "off");
		$input.attr("readonly", "readonly");
		$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
		
		return $input;	
	}
	
	function moveSelect(step) {
		var lis = $("li", $container);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass(opt.hoverClass);

		$(lis[active]).addClass(opt.hoverClass);
	}
	
	function setCurrent() {	
		var li = $("li."+opt.currentClass, $container).get(0);
		var ar = (''+li.id).split('_');
		var el = ar[ar.length-1];
		$select.val(el);
		$input.val($(li).html());
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return $select.val();
	}
	
	// input value
	function getCurrentValue() {
		return $input.val();
	}
	
	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		$select.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '_' + $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).html());
				$(li).addClass(opt.currentClass);
			}
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('over on : '+this.id);
				jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				if (opt.debug) console.log('out on : '+this.id);
				jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
			  var fl = $('li.'+opt.hoverClass, $container).get(0);
				if (opt.debug) console.log('click on :'+this.id);
				$('li.'+opt.currentClass).removeClass(opt.currentClass); 
				$(this).addClass(opt.currentClass);
				setCurrent();
				hideMe();
			});
		});
		return ul;
	}
	
};
