//Define initial states
var bookmarkedState = YAHOO.util.History.getBookmarkedState("app");
var queryState = YAHOO.util.History.getQueryStringParameter( "app" );

var initialState = bookmarkedState || defaultState; //defaultState is defined in regions/HEADER
var lastState = initialState;

//Register our module
YAHOO.util.History.register( "app", initialState, function( state ) {

	// Need to decode URL.  FF does not like certain characters
    state = unescape(state);
    var unmunged=state;
    unmunged = b(unmunged);
 
 	// Populate the page with the products filtered by the parameters
	getResults(unmunged);
	
	// Add listeners to the new HTML elements
	addListeners();
} );

// Called when Next, Prev, View All are clicked to populate offset
function handleOffsetClick(new_value, event) {
	//alert('handling offset click');
	$('offset').value = new_value;
	event_handler(event);
	//scroll to the top of the page
	window.scroll(window.scrollX,0);
	return true;
}

// Encode for FF
function a (str) {
	str = str.replace(/=/g,"~");
	return str.replace(/&/g,"+");
}

// Decode for FF
function b (str) {
	str = str.replace(/~/g,"=");
	return str.replace(/\+/g,"&");
}

// Called when a user changes a button or select
function doHandler(evt) {
	var pars=getParameters();
	
	// catch the case where the SiteCatalyst functions have not been loaded yet.  Should be a rare case, only occurring the
	// first time that a page is loaded and the user clicks a filter before the page is loaded.
	if(typeof ScFilterType == 'function') {
		var elementId = whichElement(evt);
		ScFilterType(elementId);  
	}
	// Encode for FF
	var munge=pars;
	munge=a(munge);

	if (munge != lastState) {
		try {
			YAHOO.util.History.navigate( 'app', munge );
			lastState = munge;
		} 
		catch ( e ) {
			//This happens a bit, app will still work as first page will still work with back buttons
			//alert('exception encountered:'+e);
			getResults(pars);
		}
	}
	YAHOO.util.Event.preventDefault( evt );
}

// Before handling a filter we must first set the offset to 0 so that we don't get stuck on an empty page
function doFilterHandler(evt) {
	$('offset').value = '';
	doHandler(evt);
}

// Function to be added with listeners
var event_handler = new Function ("evt","doHandler(evt);");

var filter_event_handler = new Function ("evt","doFilterHandler(evt);");

// Add listeners to HTML elements
function addListeners() {

		var filters = ['brand_id', 'price', 'sortby', 'discount', 'promo_group', 'size_filter'];
		for (var i = 0; i < filters.length; i++) {
			var filter = filters[i];
			if (ye.getListeners(filter, 'change') == undefined) {
				ye.addListener(filter, 'change', filter_event_handler);
			}
		}

}

// Initialise the application
function initialiseApp() {
	
	 var state = YAHOO.util.History.getCurrentState( "app" );
	
        if ( location.hash.substr(1).length > 0 ) {

			// Decode state for FF
            
            state=unescape(state);
            state=b(state);
            // Not sure if this bit works properly
            if ( state != lastState )
                $('results').innerHTML = "";
            getResults(state);
        }
        
        //Do this second so that things have the listener
        addListeners();
}


YAHOO.util.History.onLoadEvent.subscribe( function() {
 
 	initialiseApp();
} );


// Blank page is for IE bug - references bcs blank page
try {
	YAHOO.util.History.initialize("yui-history-field","yui-history-iframe"); 
}
catch(e) {
	initialiseApp();
} 

//Gets the id of the element that launched the event
function whichElement(e)
{
	var targ;
	if (!e) {
		var e = window.event;
	}
	if (e.target) {
		targ = e.target;
	}
	else { 
		if (e.srcElement) {
			targ = e.srcElement;
		}
	}
	if (targ.nodeType == 3) { // defeat Safari bug
   		targ = targ.parentNode;
   	}
	var tname;
	return targ.id;
}
