var Search = Class.create();

Search.OrderByRE = new RegExp( "/+orderby/[^/]*(/descending)?/?", "g" );
Search.OrderByRE.compile( "/+orderby/[^/]*(/descending)?/?", "g" );

Search.CountRE = new RegExp( "/+count/[^/]*/?", "g" );
Search.CountRE.compile( "/+count/[^/]*/?", "g" );

Search.PrettyURL = new RegExp( "/{2,}", "g" );
Search.PrettyURL.compile( "/{2,}", "g" );

Search.prototype = {
	initialize: function( el ){
		this.el = el;
		try{
			var selectEls = el.select( ".SearchSortFields" );
			for( asdf=0; asdf<selectEls.length; asdf++)
				Event.observe( selectEls[asdf], 'change', this.change_order_by.bind(this, selectEls[asdf]) );
			selectEls = el.select( ".PageCountNumber" );
			for( asdf=0; asdf<selectEls.length; asdf++)
				Event.observe( selectEls[asdf], 'change', this.change_count.bind(this, selectEls[asdf]) );
		}catch( exception ){
			//console.debug( exception );
		}
	},
	change_order_by: function( selectEl ){
		this.__redirect( 'orderby/' + selectEl.options[selectEl.selectedIndex].value, Search.OrderByRE );
	},
	change_count: function( selectEl ){
		this.__redirect( 'count/' + selectEl.options[selectEl.selectedIndex].value, Search.CountRE );
	},
	__redirect: function( add, remove ){
		var current_href = document.location.pathname;
		current_href = current_href.replace( remove, '/' );
		//console.debug( current_href );
		if( current_href.substr( current_href.length-1 ) != '/' )
			current_href += '/';
		current_href += add;
		//current_href = current_href.replace( Search.PrettyURL, '/' );
		document.location.href = current_href + document.location.search;
	}
}

Search.InitPage = function(){
	els = $$( '.SearchResultsSection' );
	for( c=0; c<els.length; c++ )
		new Search( els[c] );
}

Event.observe( window, 'load', Search.InitPage );