var homeContentSlide = null;
var searchContentSlide = null;

var searchContentLeaving = false;
var searchRequest = null;

var waitingImg = null;

var initing = true;

// RHS doesn't work well with Safari, though it tries. We disable it.
if(!Browser.Engine.webkit)
{
	window.dhtmlHistory.create({
        toJSON: function(o) {
                return JSON.stringify(o);
        }
        , fromJSON: function(s) {
                return JSON.parse(s);
        }
	});
}

window.addEvent('domready', function() {
	homeContentSlide = new Fx.Slide('home_content', {link:'chain'});
	searchContentSlide = new Fx.Slide('search_content', {link:'chain'});
	
	waitingImg = new Element('img');
	waitingImg.setProperty('src', '/img/ajax-loader.gif')
	waitingImg.setProperty('class', 'waiting_image')
	$('waiting_bar').grab(waitingImg);
	
	if(dhtmlHistory)
	{
		dhtmlHistory.initialize();
	    dhtmlHistory.addListener(homeHistoryListener);

	    var initialLocation = dhtmlHistory.getCurrentLocation();
	    if(initialLocation != undefined && initialLocation != "")
		    homeHistoryListener(initialLocation, null);
	}

	initing = false;
})
	
function homeSearch(query)
{
	homeContentSlide.slideOut();
	
	if(!query)
	{
		var q = $('search_text').value;
		query = "q="+ encodeURIComponent(q);	
	}
	else
	{
		var searchTerm = parseQuery(query)['q'];
		$('search_text').value = searchTerm;
	}
	
	if(dhtmlHistory)
	{
		dhtmlHistory.add("s_" + encodeURIComponent(query));
	}
	
	return runSearch(query);	
}

function homeHistoryListener(location, data) {
	if(location == undefined || location == "")
	{
		// the slides cause visual glitches if we run them on init, so just leave it alone
		if(!initing)
		{
			homeContentSlide.slideIn();
			searchContentSlide.slideOut();
			if(searchRequest) {
				searchRequest.cancel();
			}
		}
	}
	else
	{
		// on init, we jump to the right view, rather than letting things slide around too much
		if(initing)
		{
			searchContentSlide.hide();
			homeContentSlide.hide();
		}
		var query = decodeURIComponentAndSpace(location.substr(2));
		homeContentSlide.slideOut();
		
		var searchTerm = parseQuery(query)['q'];
		$('search_text').value = searchTerm;
		runSearch(query);	
	}
}

function parseQuery(query)
{
	var result = {}
	var pieces = query.split("&");
	for(var i = 0; i < pieces.length; i++)
	{	
		var piece = pieces[i];
		var keyValue = piece.split('=');
		
		result[keyValue[0]] = decodeURIComponentAndSpace(keyValue[1]);
	}
	return result;
}

function decodeURIComponentAndSpace(component)
{
	return decodeURIComponent(component.replace(/\+/g, " "));
}
	
function runSearch(query)
{
	if(!searchContentLeaving) {
		searchContentSlide.slideOut().chain(function() { searchContentLeaving = false; window.waitingImg.setStyle('display', 'block'); this.callChain(); });
		searchContentLeaving = true;
	}
	
	if(searchRequest) {
		searchRequest.cancel();
	}
	
	
	searchRequest = new Request({url: '/search_list', method:'get'}).addEvent('success', searchReady).send(query);

	return false;
}

function searchReady(text)
{
	if(searchContentLeaving) {
		searchContentSlide.chain(function() { setSearchResults($('search_content'), text); window.waitingImg.setStyle('display', 'none'); this.callChain(); }).slideIn()
	} else {
        waitingImg.setStyle('display', 'none');
		setSearchResults($('search_content'), text);
		searchContentSlide.slideIn();
	}
	searchRequest = null;
}

function setSearchResults(element, text)
{
	element.set('html', text);
	var links = element.getElements('a');
	for(var i = 0; i < links.length; i++)
	{
		var link = links[i];
		var href = link.href;
		var found = href.match(/.*\/search\?(.*)/);
		if(found) {
			link.addEvent('click', function(query) { window.homeSearch(query); return false; }.pass(found[1]) );
		}
	}
}

