
var sugg_offset_ie7 = 0;
var sugg_offset_ie6 = 0;
 
(function(){
 
var global = this;
 
var log = function(){
if (global.console && console.log){
try {
console.log.apply(console, arguments);
} catch(e) {
console.log(Array.slice(arguments));
}
} else {
Log.logged.push(arguments);
}
return this;
};
 
var disabled = function(){
this.logged.push(arguments);
return this;
};
 
this.Log = new Class({
 
logged: [],
 
log: disabled,
 
resetLog: function(){
this.logged.empty();
return this;
},
 
enableLog: function(){
this.log = log;
this.logged.each(function(args){
this.log.apply(this, args);
}, this);
return this.resetLog();
},
 
disableLog: function(){
this.log = disabled;
return this;
}
 
});
 
Log.extend(new Log).enableLog();
 
// legacy
Log.logger = function(){
return this.log.apply(this, arguments);
};
 
})();

Request.JSONP = new Class({
 
Implements: [Chain, Events, Options, Log],
 
options: {/*
onRetry: $empty(intRetries),
onRequest: $empty(scriptElement),
onComplete: $empty(data),
onSuccess: $empty(data),
onCancel: $empty(),
log: false,
*/
url: '',
data: {},
retries: 0,
timeout: 0,
link: 'ignore',
callbackKey: 'callback',
injectScript: document.head
},
 
initialize: function(options){
this.setOptions(options);
if (this.options.log) this.enableLog();
this.running = false;
this.requests = 0;
this.triesRemaining = [];
},
 
check: function(){
if (!this.running) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
}
return false;
},
 
send: function(options){
if (!$chk(arguments[1]) && !this.check(options)) return this;
 
var type = $type(options),
old = this.options,
index = $chk(arguments[1]) ? arguments[1] : this.requests++;
if (type == 'string' || type == 'element') options = {data: options};
 
options = $extend({data: old.data, url: old.url}, options);
 
if (!$chk(this.triesRemaining[index])) this.triesRemaining[index] = this.options.retries;
var remaining = this.triesRemaining[index];
 
(function(){
var script = this.getScript(options);
this.log('JSONP retrieving script with url: ' + script.get('src'));
this.fireEvent('request', script);
this.running = true;
 
(function(){
if (remaining){
this.triesRemaining[index] = remaining - 1;
if (script){
script.destroy();
this.send(options, index).fireEvent('retry', this.triesRemaining[index]);
}
} else if(script && this.options.timeout){
script.destroy();
this.cancel().fireEvent('failure');
}
}).delay(this.options.timeout, this);
}).delay(Browser.Engine.trident ? 50 : 0, this);
return this;
},
 
cancel: function(){
if (!this.running) return this;
this.running = false;
this.fireEvent('cancel');
return this;
},
 
getScript: function(options){
var index = Request.JSONP.counter,
data;
Request.JSONP.counter++;
 
switch ($type(options.data)){
case 'element': data = document.id(options.data).toQueryString(); break;
case 'object': case 'hash': data = Hash.toQueryString(options.data);
}
 
var src = options.url +
(options.url.test('\\?') ? '&' :'?') +
(options.callbackKey || this.options.callbackKey) +
'=Request.JSONP.request_map.request_'+ index +
(data ? '&' + data : '');
if (src.length > 2083) this.log('JSONP '+ src +' will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs');
 
var script = new Element('script', {type: 'text/javascript', src: src});
Request.JSONP.request_map['request_' + index] = function(data){ this.success(data, script); }.bind(this);
return script.inject(this.options.injectScript);
},
 
success: function(data, script){
if (script) script.destroy();
this.running = false;
this.log('JSONP successfully retrieved: ', data);
this.fireEvent('complete', [data]).fireEvent('success', [data]).callChain();
}
 
});
 
Request.JSONP.counter = 0;
Request.JSONP.request_map = {};





var lQ = '', sOpt = 'none', maxOpt = 0, qfocus = false, cssLeft = 0;
var dbm = (Cookie.read('zugo_debug') == 'on' ? true : false );
var ssmp = '', ssmp2 = '', ssCache = [];

// mouse-tracking

window.addEvent('domready', 
	function() { 

		cssLeft = $('sugg').getStyle('left');

		$('srch_q').addEvent('keyup', showsuggest) 
		
		$('body').addEvent('keydown', function(event){

			if (event.key == 'esc')
			{
				event.stop();
				clearSuggBox( 'override' );
				
			}

			if ((event.key == 'up' || event.key == 'down') && maxOpt > 0 && $('sugg').style.display == 'block')
			{ 
				setSuggOpt( $('opt'+ ( sOpt == 'none' ? (event.key == 'up' ? maxOpt : 0) : (event.key == 'up' ? sOpt - 1 : sOpt.toInt() + 1) ) ) , 'key');
				event.stop();
			}
			
			if (event.key == 'enter' && sOpt != 'none' && $('sugg').style.display == 'block')
			{ 
				setSugg($('opt'+sOpt).title);
				clearSuggBox( 'override' );					
			}

		});	
		
		document.addEvent('click', clearSuggBox);
		
	});

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function setSugg(query)
{
	$('srch_q').value = query;
}


String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function showsuggest(e)
{
	if (Cookie.read('zugo_ss') != 'off')
	{

		if ( e.key != 'esc' && e.key !='enter' && ( ($('sugg').style.display == 'none' && $('srch_q').value.trim() != '') || (e.key != 'up' && e.key != 'down' && e.key != 'enter') ) )
		{
	
			var query =$('srch_q').value.trim();
			
			if (query != '')
			{
			
				if (!ssCache[query])
				{			
					setTimeout ( 'requestSugg("'+query+'")' , 200 );	
				}
				else
				{
					lQ = query;					
					showSuggBox(ssCache[query]);
				}
			}
			else
				clearSuggBox('override');
		
		}
	
	}
	
}

function requestSugg ( query )
{

	if ( $('srch_q').value.trim() == query )
	{
		
	lQ = query;		
		

		new Request.JSONP({
			  url: 'http://suggest.zugosearch.com/query',
		      data: {
		        fn: 'showSuggBox',
		        q: query,
		        sstype: 'prefix',
		        noCacheIE: '1252419681642'
		      }
		}).send();

	}

}

sugChain = new Chain();
	
function showSuggBox(text)
{
	
	ssCache[lQ] = text;
	
	sOpt = 'none';

	if (text.responseText)
		text = text.responseText;
	

	if ($('srch_q').value.trim() != '')
	{
		var rhtml = '';
		 
		 text['1'].each ( function ( sWord, i ) 
		 {
		 
		 	sLabel = sWord.replace('<span class="suggest">','<b>').replace('</span>','</b>');
		    sKeyword = sWord.replace('<span class="suggest">','').replace('</span>','');
		 
		 	rhtml += "<a class='suggopt"+(i%2 == 1 ? ' even' : '' )+"' onmouseover='setSuggOpt(this)' title='"+sKeyword+"' id='opt"+i+"'>"+sLabel+'</a>';
			maxOpt = i;
		 }
		 );
	
		if (rhtml != '')
		{
	
			rhtml += "<div class=close><a onclick=switchSS('off')><b>Turn Off Search Suggestions</b></a></div>";
			
			if (Browser.Engine.trident)
			{
								
				var sb_pos =  $('srch_q').getPosition();
				
				$('sugg').setStyle( 'position', 'absolute' );
				$('sugg').setStyle( 'top', sb_pos.y + 35);				
				
				if (Browser.Engine.version == 4)				
					$('sugg').setStyle( 'margin-left', (0-404+sugg_offset_ie6)+'px');
				else if (Browser.Engine.version == 5)
				{
					if(!document.querySelectorAll && Browser.Engine.trident) //IE7
					{
						$('sugg').setStyle( 'margin-left', (0-198+sugg_offset_ie7)+'px');
					}
					
				}
					
			}
			else
			{
				$('sugg').setStyle ( 'top', $('srch_q').getPosition().y + $('srch_q').getSize().y - 3 );

			}

			if ($('sugg').style.display == 'none' || $('sugg').style.display == '')
				$('sugg').style.display = 'block';

				if (Cookie.read('classicCookie') != null && Cookie.read('classicCookie') != 'false')
				{
					$('sugg').setStyle ('left' , '3px');
				}
				else if ( $('sugg').getStyle('left') == '3px')
				{
					$('sugg').setStyle ('left' , cssLeft);
				}
			
			$('sugg').innerHTML = rhtml;
		}
		else
			clearSuggBox('override');
		
	
		$$('.suggopt').each ( function (part, i)
		{
			part.addEvent('mouseenter', function(){
			    setSuggOpt($(part.id),'enter');
			});
		
			part.addEvent('click', function(){
				setSugg(part.title);
				clearSuggBox('override');
				$('srch_q').focus();
			});
		
		});
	}
	


}

function clearSuggBox(e)
{	
	if (e == 'override' || e.target.id != 'srch_q')
	{
		lQ = '';
		sOpt = 'none'; 
		maxOpt = 0;
		$('sugg').style.display = 'none';
		$('sugg').innerHTML = '';
	}

}

function setSuggOpt (selObj , source)
{
	
		$$('.suggopt').removeClass('sel');
	
		if (selObj)
		{
			sOpt = selObj.id.replace('opt','');
			selObj.addClass('sel');
			if (source == 'key')
				setSugg(selObj.title);
		}	
		else
		{
			sOpt = 'none';
			$('srch_q').focus();
			$('srch_q').value = lQ;
		}
		
}

function urlencode( str ) {

    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();

    histogram['!']   = '%21';
    histogram['%20'] = '+';

    ret = encodeURIComponent(ret);

    for (search in histogram) {
        replace = histogram[search];
        tmp_arr = ret.split(search);
        ret = tmp_arr.join(replace); 
    }

    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });

    return ret;
}	

function switchSS( value )
{
	if (value == 'off')
	{
		Cookie.write('zugo_ss','off');
		clearSuggBox('override');
	}
}