// Live Search
Epson.Search = function( element )
{
	var _url = '';
	var _searchfield = jQuery( element );
	var _dropdown =  null;
	var _results = [];
	var _active = null;
	var _timer = null;
	var _opened = false;
	var _header_search = false;
	var _is_opened = false;
	var _searching = false;
	var _query = '';
	var saved_json = null;

	function setup()
	{
		// save ajax url
		_url = _searchfield.parents( 'form' )[0].className.match( /ls-url-([^\s]+)/ );

		_searchfield.attr( 'autocomplete', 'off' );

		if ( _url )
		{
			_url = _url[1];

			_header_search = _searchfield.parents( '.mastheadSearch' ).length ? true : false;

			_searchfield.bind( 'keyup', timeSuggestions );

			if ( document.addEventListener )
			{
				_searchfield[0].addEventListener( 'blur', function() { _timer = setTimeout( close, 500 ) }, false );
				_searchfield[0].addEventListener( 'focus', function() { clearTimeout( _timer ) }, false );
			}
			else if ( document.attachEvent )
			{
				//_searchfield[0].attachEvent( 'onblur', function() { _timer = setTimeout( close, 500 ) } );
				jQuery('body').bind('click', function() { _timer = setTimeout( close, 500 ) });
				_searchfield[0].attachEvent( 'onfocus', function() { clearTimeout( _timer ) } );
			}
		}
		

		if ( !_header_search ) _searchfield.parents( 'form' ).bind( 'submit', function(e) { e.preventDefault() } );
		else
		{
			_searchfield.parents( 'form' ).bind('submit', function(e)
			{
				 // prevent the user from submitting blanks
				var value = _searchfield.val().replace( /^\s+|\s+$/g, '' );
				var label = _searchfield.parents( 'form' ).find( 'label.fl_info' ).text();

				if ( value == '' || value == label ) e.preventDefault();
			});
		}
	}

	function open()
	{
		// prepare the dropdown position and styles
		var position = _searchfield.offset( { border:true, padding:true } );

		_dropdown = jQuery( '<div id="LiveSearch" class="genericRoundedCorners"><div class="content"><ul></ul><div class="clear"><a href="#" class="buttonSmall"><span>' + Epson.Localisation.LiveSearch.TXT001 + '</span></a></div></div><div class="bottom"><div class="bl"></div><div class="br"></div><div class="b"></div></div></div>' );
		_dropdown.find( '.buttonSmall' ).bind( 'click', function() { _searchfield.parents( 'form' ).submit() } );
		_dropdown.css( { position:'absolute', top:position.top+_searchfield.height()+16+'px', left:position.left+'px'/* , opacity:0 */ } );
		_dropdown.bind( 'mousedown', function(e) { setTimeout( function() { _searchfield[0].focus() }, 100 ) } ); // fix for safari scrolling bug

		// add to container
		jQuery( '#Container' ).append( _dropdown );

		_opened = true;		

		//IE fix for z-index bug
		jQuery('#LiveSearch').bgiframe();
	}

	function close()
	{
		hideLoader();
		
		_active = null;
		_opened = false;
		if ( _dropdown )
		{
			_dropdown.remove();
			_dropdown = null;
		}
	}

	function timeSuggestions(e)
	{
		
		clearTimeout( _timer );
		
		if ( e.keyCode == 40 && _dropdown )
		{
			clearTimeout( _timer );
			downSuggestions(e);
		}
		else if ( e.keyCode == 38 && _dropdown )
		{
			clearTimeout( _timer );
			upSuggestions(e);
		}
		else if ( e.keyCode != 13 && _searchfield.val().length > 2 )
		{
			displayLoader();
			clearTimeout( _timer );
			_searching = true;
			_timer = setTimeout( function() { triggerSuggestions(e) }, 300 );
		}
		else if ( e.keyCode == 13 ) setTimeout( function() { submitSearch(e) }, 300 );
		else close();
	}

	function triggerSuggestions(e)
	{
		if ( _query != _searchfield.val() )
		{
			_query = _searchfield.val();
			_query = encodeURI(_query);
	
			jQuery.getJSON( _url, { query:_query }, handleResult );
		}
		else { handleResult( saved_json ); 	_searching = false; }
	}

	function submitSearch(e)
	{
		jQuery.cookie('categoryTab', null );
		if ( _active )
		{
			window.location = _active.find( 'a' ).attr( 'href' );
		}
		
		else if ( !_header_search && _results.length == 1 && !_searching )
		{
			window.location = _dropdown.find( 'ul li:first-child a.header' ).attr( 'href' );
		}
		
		else if ((!_header_search && _searchfield.val().length > 2 ) || ( !_header_search && _results.length > 1  ))
		{
			clearTimeout( _timer );
			_searching = true;
			_timer = setTimeout( function() { triggerSuggestions(e) }, 300 );
		}
	}

	function upSuggestions(e)
	{
		var active = _dropdown.find( 'ul li.active' );
		if ( active.length && active.prev( 'li' ).length ) active.prev( 'li' ).addClass( 'active' );
		else if ( active.length && !active.prev( 'li' ).length ) _dropdown.find( 'ul li:last-child' ).addClass( 'active' );
		else _dropdown.find( 'ul li:last-child' ).addClass( 'active' );

		active.removeClass( 'active' );

		_active = _dropdown.find( 'ul li.active' );

		e.preventDefault();
	}

	function downSuggestions(e)
	{
		var active = _dropdown.find( 'ul li.active' );
		if ( active.length && active.next( 'li' ).length ) active.next( 'li' ).addClass( 'active' );
		else if ( active.length && !active.next( 'li' ).length ) _dropdown.find( 'ul li:first-child' ).addClass( 'active' );
		else _dropdown.find( 'ul li:first-child' ).addClass( 'active' );

		active.removeClass( 'active' );

		_active = _dropdown.find( 'ul li.active' );

		e.preventDefault();
	}

	function clearActive()
	{
		if ( _active ) _active.removeClass( 'active' );
		_active = null;
	}

	function handleResult( json )
	{
		_searching = false;

		if ( !_opened ) open();

		// empty the content to prevent repeating
		_dropdown.find( 'ul' ).empty();

		//add the data to the html
		if ( json.results && json.results.length )
		{
			// save results
			_results = json.results;

			_dropdown.find( '.empty' ).remove();

			jQuery.each( json.results, function()
			{
				var options = '';
				var newindow=this.openNewWindow;
				
				
				if ( this.options ) jQuery.each( this.options, function() { options += '<div ><a class='+this.preRepId+' href='+this.url+' id='+this.newPage+'>'+this.title+'</a></div>' } );

				if(_header_search){
					_dropdown.find( 'ul' ).append( jQuery( '<li><a href='+this.url+'><img src="'+this.thumbnail+'" alt="' +this.alt+ '" /></a><div><a class="header" href='+this.url+'>'+this.title+'</a></div><div class="options">'+options+'</div></li>' ).bind( 'mouseover', clearActive ));
						if ( this.options )
							jQuery.each( this.options, function() {
									$('.'+this.preRepId).each(function()	{
												$(this).bind( 'click', 
												function(e)
												{ 							
													if(jQuery( this ).attr( 'id' )=='true' )
													{
														window.open(jQuery( this ).attr( 'href' ),'','scrollbars=yes,menubar=yes,height=600,width=800,resizable=yes,toolbar=yes,location=no,status=no');
														e.preventDefault();
													}
													else
														window.location = jQuery( this ).attr( 'href' );
												}		
											  );});
								});
					}
				else{
				_dropdown.find( 'ul' ).append( jQuery( '<li><a href='+this.url+' id='+this.openNewWindow+'><img src="'+this.thumbnail+'" alt="' +this.alt+ '" /></a><div><a class="header" href='+this.url+' id='+this.openNewWindow+'>'+this.title+'</a></div><div class="options">'+options+'</div></li>' ).bind( 'mouseover', clearActive ).bind( 'click', function(e) {
					
					if (jQuery( this ).find( 'a' ).attr( 'id' )=="true")
					{
						
						window.open(jQuery( this ).find( 'a' ).attr( 'href' ),'','scrollbars=yes,menubar=yes,height=600,width=800,resizable=yes,toolbar=yes,location=no,status=no');
						e.preventDefault();
					}
					else
					window.location = jQuery( this ).find( 'a' ).attr( 'href' ); } ) )
				}
			} );
			
			_dropdown.find( 'a' ).bind( 'click', function() {try { cmCreatePageviewTag("Search Results - Predictive", "100.4.1.1", _query, json.results.length ) } catch(e){};} );
			if ( _searchfield.parents( '.mastheadSearch' ).length )
			{
				if ( json.results.length > 4 ) _dropdown.find( '.buttonSmall' ).show();
				else _dropdown.find( '.buttonSmall' ).hide();					
			}
			else
			{
				_dropdown.find( '.buttonSmall' ).hide();
				_dropdown.width( _searchfield.width() + 11 );			
			}

			
		}
		else
		{
			//custom requirement to pass coremetrics params
			try { cmCreatePageviewTag("Search Results - Predictive", "100.4.1.1", _query, "0" ) } catch(e){};

			_dropdown.find( '.buttonSmall' ).hide();

			if ( !_dropdown.find( '.empty' ).length ) jQuery( '<div class="empty">' + Epson.Localisation.LiveSearch.TXT002 + '</div>' ).insertAfter( _dropdown.find( 'ul' ) );
		}
		
		saved_json = json;
		hideLoader();

	}
	
	function displayLoader()
	{
		if ( _searchfield )
		{
			var width = _searchfield.width();
			var offset = _searchfield.offset();

			var y;
			if ( _searchfield.parents( '.mastheadSearch' ).length ) y = 4
			else y = 9

			jQuery( '#Container' ).append( jQuery( '<div class="loader"></div>' ).css( { position:'absolute', top:offset.top+y+'px', left:offset.left+width-10+'px' } ) );
		}
		
	}

	function hideLoader()
	{
		jQuery( '#Container .loader' ).remove();
	}
		

	setup();
}
