function updateSearch()
{
	if( document.forms[0] && document.forms[0].page ) 
		document.forms[0].page.value = 0;
		
	//minimizeResults();
	//window.location.hash = '';
	
	currentItemID = null;
	
	getItems();
}

function pageSearch(dir)
{
	var page = parseInt( $('#page').val() ) + dir;
	page = Math.max(0, page);
	
	$('#page').val( page );
	
	getItems();
}

function filterByType( type )
{
	$('input[name=type]').val( type );
	
	selectSubNav( type );
	
	updateSearch();
}

function selectSubNav( type )
{
	var subnav;
	
	if( selectedSubType ) 
	{
		subnav = $('#subnav_' + selectedSubType);
		if( subnav ) subnav.removeClass("navigation_item_selected").addClass( "navigation_item" );
	}
	
	subnav = $('#subnav_' + type);
	
	if( subnav ) $("#subnav_" + type).removeClass("navigation_item").addClass( "navigation_item_selected" );
		
	selectedSubType = type;
}

function getFirstChild(n)
{
	var x = n.firstChild;
	while (x.nodeType!=1)
  	{
  		x=x.nextSibling;
  	}
	return x;
}

function getItems()
{
	clearElement( document.getElementById('results_list') );
	
	$('#loader').show();
	$('#search').find('*').attr('disabled', true);
	
	var inputs = $('#filter_form :input');
	
	args = [];
	
	if( pageResults == true )
		args.push('page_results=' + pageResults);
	
	inputs.each(
		function() 
		{
			if( this.type == 'radio' )
			{
				if( this.checked )
					args.push( this.name + '=' + this.value );
			}
			else
			{
				if( this.value != 0 )
					args.push( this.name + '=' + this.value );
			}
		});
	
	params = 
	{
		url: 'ajax/get_items.php', 
		success: onGetItems,
		data: args.join("&")
	};
	
	//alert( params.url + '/' + params.data );
	
	$.ajax( params );
}

function onGetItems( data )
{
	$('#loader').hide();
	$('#search').find('*').attr('disabled', false);
	
	resultCache = [];
	
	var results = document.getElementById( resultsDivID );
	
	var items = data.getElementsByTagName('item');
	
	var firstChild = getFirstChild(data);
	
	var total_results = parseInt( firstChild.getAttribute('total') );
	numResults = total_results;
	
	var page = parseInt( firstChild.getAttribute('page') );
	var page_size = parseInt( firstChild.getAttribute('page_size') );
		
	var enable_prev = page > 0;
	var enable_next = page * page_size + page_size < total_results;
	
	$('#page_prev').css( { opacity: enable_prev ? 1 : .5 } );
	enable_prev ? $('#page_prev').show() : $('#page_prev').hide();
	
	$('#page_next').css( { opacity: enable_next ? 1 : .5 } );
	enable_next ? $('#page_next').show() : $('#page_next').hide();
	
	for(i=0;i<items.length;i++)
	{
		var item = items[i];
		var item_id = item.getAttribute('id');
		var item_thumb_id = item.getAttribute('thumb_id');
		var item_title = item.getAttribute('title');
		var item_price = item.getAttribute('price');
		
		var div = document.createElement('div');
		div.id = "result_" + i;
		div.className = 'result';
		
		var a = document.createElement('a');
		a.href = isCollections ?  'javascript:getItem("' + item_id + '")' : "index.php#" + item_id;
		div.appendChild(a);
		
		var img_div = document.createElement('div');
		$(img_div).css( 'width', thumbnailSize );
		$(img_div).css( 'height', thumbnailSize );
		$(img_div).css('background-image', 'url(' + (item_thumb_id!=null ? 'images/pieces/' + item_thumb_id + '_thumb.jpg' : 'images/no_image.gif') + ')' );
		a.appendChild(img_div);
		
		//	fade image
		var img = document.createElement('img');
		img.className = "fade";
		img.border = 0;
		img.src = 'images/fade.png';
		img_div.appendChild(img);
		
		results.appendChild(div);
		
		resultCache[ i ] = { id: item_id, title: item_title, price: item_price, materials: item.getAttribute('materials') };
		
		if( pageResults )
		{
			$(div).hide();
		
			if( i < minimizedPageSize )
				$(div).delay(i*100).fadeIn('slow');
		}
		else
		{
			$(div).mouseover( function() { showResultInfo( $(this).attr('id').split('_')[1] ) } );
    		$(div).mouseout( function () { hideResultInfo() } );
    	}
	}
	
	//	for some reason we have to reset this to fix an IE issue
	$(results).css( 'height', 560 );
	$(results).css( 'overflow', 'auto' );
	$(results).jScrollPane();
	
	//	show random item if none set
	if( isCollections
		&& currentItemID == null )
	{
		currentItemID = items[ Math.floor( Math.random() * items.length ) ].getAttribute('id');
		getItem( currentItemID );
	}
}

function getItem( id )
{
	if( id == undefined ) return;
	
	//minimizeResults();
	
	$('#content').fadeTo(25,.1);
	
	setHash( id );
	
	$('#loader').show();
	$('#search').find('*').attr('disabled', true);
	
	var params = 
	{
		url: 'ajax/get_item.php', 
		success: onGetItem,
		data: 'id=' + id
	};
	
	$.ajax( params );
}

function onGetItem( data )
{
	$('#loader').hide();
	$('#search').find('*').attr('disabled', false);
	
	var item = getFirstChild(data);
	
	// 	piece attributes
	var id = item.getAttribute('id');
	var title = item.getAttribute('title');
	var type = item.getAttribute('type');
	var code = item.getAttribute('code');
	var price = item.getAttribute('price');
	var description = item.getAttribute('description');
	var parent_id = item.getAttribute('parent_id');
	var image_id = item.getAttribute('image_id');
	
	var buy_html = unescape(item.firstChild.nodeValue);
	
	var content = document.getElementById("main");
	
	var product_div = document.getElementById('content');
	$(product_div).empty();
	$(product_div).hide();
	
	//	image
	var image_div = document.createElement('div');
	image_div.id = "product_image";
	product_div.appendChild(image_div);
	
	var image = document.createElement('img');
	$(image).load( function() { onImageReady( id ) } );
	image.id = "product_image_img";
	image.src = "images/pieces/" + image_id + "_main.jpg";
	image.border = 0;
	image_div.appendChild(image);
	
	//	info container
	var info_div = document.createElement("div");
	info_div.id = "product_info";
	product_div.appendChild(info_div);
	
	//	title
	var title_div = document.createElement('div');
	title_div.id = "title";
	title_div.appendChild( document.createTextNode(title) );
	info_div.appendChild(title_div);
	
	//	type
	
	/*
	var type_span = document.createElement('span');
	type_span.id = "type";
	type_span.appendChild( document.createTextNode(type) );
	title_div.appendChild( type_span );
	*/
	
	//	materials
	var materials = data.getElementsByTagName('material');
	if( materials.length>0 )
	{
		var m = [];
		
		var material_div = document.createElement('div');
		material_div.id = "materials";
		
		for(var i=0;i<materials.length;i++)
		{
			m.push( materials[i].getAttribute('material') );
		}
		
		material_div.appendChild( document.createTextNode( m.join(" + ") ) );
		info_div.appendChild(material_div);
	}
	
	//	description
	if( description )
	{
		var descrip_div = document.createElement('div');
		descrip_div.id = "description";
		descrip_div.appendChild( document.createTextNode(description) );
		info_div.appendChild( descrip_div  );
	}
	
	//	price
	var price_div = document.createElement('div');
	price_div.id = "price";
	price_div.appendChild( document.createTextNode('$' + price) );
	info_div.appendChild(price_div);
	
	//	buy button
	var buy_form = data.getElementsByTagName('buy_form')[0];
	var buy_div = document.createElement('div');
	buy_div.id = "purchase";
	buy_div.innerHTML = buy_form.firstChild.nodeValue;
	info_div.appendChild(buy_div);
	
	//	pairings
	var pairings = data.getElementsByTagName('pairing');
	if( pairings.length>0 )
	{
		var pairings_div = document.createElement('div');
		pairings_div.id = "pairings";
		
		var pairings_header = document.createElement('div');
		pairings_header.id = "pairings_header";
		pairings_header.appendChild( document.createTextNode( "Goes well with:" ) );
		pairings_div.appendChild( pairings_header );
		
		for(var i=0;i<pairings.length;i++)
		{
			var pairing = pairings[i];
			var pairing_id = pairing.getAttribute('id');
			var image_id = pairing.getAttribute('image_id');
			
			var pairing_div = document.createElement('div');
			pairing_div.className = "pairing";
			//$(pairing_div).mouseover( function(){ $(this).css('background-color','#EEEEEE'); } );
			//$(pairing_div).mouseout(  function(){ $(this).css('background-color','#FFFFFF'); } );			
			pairings_div.appendChild( pairing_div );
			
			var a = document.createElement('a');
			a.href = 'javascript:getItem("' + pairing_id + '")';
			pairing_div.appendChild(a);
			
			var img = document.createElement('img');
			img.border = 0;
			img.src = image_id !=null ? 'images/pieces/' + image_id + '_tiny.jpg' : 'images/no_image.gif';
			$(img).css('width', thumbnailSizeTiny );
			$(img).css('height', thumbnailSizeTiny );
			a.appendChild(img);
		}
		
		info_div.appendChild(pairings_div);
	}
	
	$('#content').fadeTo(0,1);
}

function onImageReady( id )
{
	var product = document.getElementById('content');
	var product_image = document.getElementById('product_image_img');
	var product_info = document.getElementById('product_info');
	
	$(product).fadeIn( 'slow' );
}

function clearElement( el )
{
	if ( el == undefined ) return;
	
	if ( el.hasChildNodes() )
	{
		while ( el.childNodes.length >= 1 )
		{
			el.removeChild( el.firstChild );       
		} 
	}
}

function clearProduct()
{
	var main = document.getElementById("main");
	var product = document.getElementById("content");
	
	if( main && product )
		main.removeChild( product );
}

/*
function maximizeResults(  )
{
	if( state != "minimized" 
		|| numResults <= minimizedPageSize ) return;
	
	state = "animating";
	
	$('.result').each
	(
		function(index) 
		{
			$(this).show();
			
    		$(this).mouseover( function() { showResultInfo( index ) } );
    		$(this).mouseout( function () { hideResultInfo() } );
  		}
  	);
  	
	var w = $('#main').width()/3;
	w = (thumbnailSize + thumbnailPadding * 2) * 2 + (thumbnailMargin * 2);
	
	if( animate )
	{
		$('#results').stop(true,true).animate( { width: w }, 1000, 'easeOutExpo', onMaximizeResults );
		$('#results_list').css('width',w);
	}
	else
	{
		$('#results').css('width',w);
		$('#results_list').css('width',w);
		
		onMaximizeResults();
	}
}

function onMaximizeResults()
{
	state = "maximized";
}

function minimizeResults()
{
	if( state != "maximized" ) return;
	
	state = "animating";
	
 	var w = 146;
 	//(thumbnailSize) + (thumbnailMargin * 2);
	
	$('.result').each
	(
		function(index) 
		{
			index > 3 ? $(this).hide() : $(this).show();
  		}
  	);
  	
	if( animate )
	{
		$('#results').stop(true,true).animate( { width: w }, 500, 'easeOutExpo', onMinimizeResults );
		$('#results_list').css('width',w - 10);
	}
	else
	{
		$('#results').css('width',w);
		$('#results_list').css('width',w - 10);
		
		onMinimizeResults();
	}
	
	hideResultInfo();
}

function onMinimizeResults()
{
	state = "minimized";
}
*/

function showResultInfo( id )
{
	if( state == 'minimized' && pageResults ) return;
	
	hideResultInfo();
	
	var thumb_info = resultCache[ id ];
	var thumb_div = document.getElementById("result_" + id);
	var thumb_size = thumbnailSize;
	var thumb_margin = thumbnailMargin;
	
	//$(thumb_div).css('background-color','#EEEEEE');
	
	var div = document.createElement('div');
	div.id = 'result_info';
	
	var results_list = document.getElementById('results_list');
	results_list.appendChild( div );
	
	var x = $(thumb_div).position().left;
	var y = $(thumb_div).position().top + thumb_margin;
	var w = thumb_size;
	var h = thumb_size;
	
	var show_left = x + w > thumbnailSize + thumbnailPadding * 2;
	show_left = true;
	
	x = show_left ? x - w - thumb_margin - 10 : x + thumb_size + thumb_margin * 3;
	
	$(div).css('left', x);
	$(div).css('top', y);
	$(div).css('width', w+'px');
	$(div).css('height', h+'px');
	$(div).css('text-align', show_left ? 'right' : 'left');
	
	//	title
	var title_div = document.createElement('div');
	title_div.id = "title";
	title_div.appendChild( document.createTextNode( thumb_info.title ) );
	div.appendChild( title_div );
	
	//	materials
	/*
	var materials_div = document.createElement('div');
	materials_div.id = "materials";
	materials_div.appendChild( document.createTextNode( thumb_info.materials ) );
	div.appendChild( materials_div );
	*/
	
	var img = document.createElement('img');
	img.border = 0;
	img.src = 'images/view_item.jpg';
	$(img).css('margin-top','10px');
	div.appendChild(img);
	
	currentRollOverItemID = id;
	
	$(div).hide().fadeIn(200);
}

function hideResultInfo()
{
	if( currentRollOverItemID != undefined )
	{
		var thumb_div = document.getElementById("result_" + currentRollOverItemID);
		$(thumb_div).css('background-color','#FFFFFF');
		
		currentRollOverItemID = undefined;
	}
	
	var resultInfo = document.getElementById("result_info");
	var results_list = document.getElementById("results_list");
	
	if( resultInfo )
		results_list.removeChild( resultInfo );
}

function getHash()
{
	var hash = window.location.hash;
	hash = hash.substr(1,hash.length);
	return hash;
}

function setHash( hash )
{
    window.location.hash = hash;
    currentItemID = hash;
}

function initHash( hash )
{
	if( hash && hash != null)
	{
		getItem( hash );
	}
}

function handleHistory()
{
	var hash = getHash();
	
    if ( hash != currentItemID )
    {
    	initHash( hash );
    }
}

var animate = true;

var pageResults = false;
var numResults;
var minimizedPageSize = 4;
var thumbnailSize = 0;
var thumbnailSizeTiny = 0;
var thumbnailMargin = 0;
var thumbnailPadding = 0;

var isCollections;
var resultCache;
var state = 'minimized';
var resultsDivID = "results_list";

var currentItemID;
var currentRollOverItemID;
var selectedSubType;
