function search() {
	this.sites = [{1: {name:"Cadyou", id: "cdyu"},
		      2: {name:"Google 3D Warehouse", id:"3dwh"},
		      3: {name:"Form Fonts Exchange", id: "form"},
		      4: {name:"The 3D Studio", id: "3dst"},
		      18:{name:"Fallingpixel", id: "fall"},
		      5: {name:"3D Xtras", id: "3dxt"},
		      6: {name:"3D02", id: "3d02"},
		      7: {name:"3D Export", id: "3dex"},
		      14:{name:"Polantis", id: "pola"},
		      16:{name:"3dvia", id: "3dvia"}},{
		      8: {name:"Cadyou Textures", id:"cdyu2"},
		      15:{name:"Stock.xchng", id:"sxch"},
		      10:{name:"The 3D Studio Textures", id:"3dst2"},
		      11:{name:"Texture Spot", id:"txsp"},
		      12:{name:"Texturez", id:"txtz"},
		      13:{name:"Dreamstime", id:"drms"}}];
	
	this.totalsites = 0;
	this.totalresults = 0;
	this.filteredresults = 0;
	this.filters = new Array();
	this.running = 0;
	this.completed = 0;
	this.search_type = "";
	this.search_query = "";
	this.search_page = 1;
	this.path = "/";
	
	this.search_start = function(t, q, p) {
		if(q){
			this.completed = 0;
			this.totalsites = 0;
			this.running = 1;
			this.search_type = t;
			this.search_query = q;
			this.search_page = p;
			
			// start all engines
			for (var e in this.sites[t]) {
				var engine = this.sites[t][e];

				// check has user disabled this engine
				if(preferences.get(engine.id) != false){

					// add to total sites being searched
					this.totalsites++;	

					// trigger search
					this.search_engine(e, q, p);
				}
				
			}
			if(this.totalsites > 0){
				// show search gui
				this.status_searching();
				this.status_active();
				$("#searchengines").fadeIn("slow");
			}

			// handle bad search results
			$("body").ajaxError(function(event, request, settings){
				//alert("Error requesting page " + settings.url);
				++search.completed;
				search.check_complete(); 
			});

		}
	};
	this.search_more = function (){
		if(!this.running){
			this.search_start(this.search_type, this.search_query, ++this.search_page);
		}
	};
	this.hide_engine = function(e){
		$("#searchresults li").each(function(){
			if(this.val() == e){
				this.hide();
			}
		});
	};
	this.search_engine = function(e, q, p) {
		// new way, create dom on server and cache the whole lot
		$.get(this.path + "ajax/" + q + "/" + e + "/" + p,
		function(data, textStatus){
			if(textStatus == "success"){
				// append new results
				$("#searchresults ol").append(data);
			} else {
				// something went wrong with this search engine, fail silently
			}

			// check if all engines have completed
			++search.completed;
			search.check_complete(); 
		});
	};
	this.check_complete = function () {
		// check if all engines have completed
		if(this.completed == this.totalsites) {
			// count the total number of results
			this.totalresults = this.filteredresults = $("#searchresults ol").children().length;

			// update display
			this.status_complete(); 
			this.status_inactive(); 
			this.running = 0;

			// sort by relevance
			setTimeout('search.sort_relevance()',10);

			// add tooltips
			$(".result-thumb a[href^='http://www.3d02.com']").tooltip({ 
				track: true, 
				delay: 0, 
				showURL: false, 
				bodyHandler: function() { 
					return $("<p>Use code <font color='red'><strong>3F001</strong></font> for a 10% discount at checkout!</p>"); 
				},  
				fade: 250 
			});
		} else {
			this.status_searching();
			this.status_active();
		}
	};
	this.status_searching = function() {
		$("#searchstatus").html('Searching... (' + this.completed + '/' + this.totalsites + ')');
	};
	this.status_complete = function() {
		if(this.totalresults == this.filteredresults){
			$("#searchstatus").html('Search Complete (' + this.totalresults + ' Results)');
		} else {
			$("#searchstatus").html('Search Complete (' + this.filteredresults + '/' + this.totalresults + ' Results)');
		}
	};
	this.status_active = function() {
		$("#statusicon").html('<img src="' + this.path + 'media/loadspinner.gif">');
	};
	this.status_inactive = function() {
		$("#statusicon").html('<img src="' + this.path + 'media/tick.png">');
	};
	this.sort_relevance = function() {
		$("#searchresults li").tsort("span[class=result-pos]");
		this.status_inactive();
	};
	this.sort_title = function() {
		$("#searchresults li").tsort("p[class=result-title]");
		this.status_inactive();
	};
	this.sort_price = function() {
		$("#searchresults li.commercial").tsort("p[class=result-price]");
		this.status_inactive();
	};
	this.sort_format = function() {
		$("#searchresults li").tsort("span[class=result-format]");
		this.status_inactive();
	};
	this.sort_source = function() {
		$("#searchresults li").tsort("span[class=result-engine]");
		this.status_inactive();
	};
};

function filter (what,on,reverse) {
	// reset this filter
	if(on == "reset"){
		delete search.filters[what];
	} else if(search.filters[what] == on){
		delete search.filters[what];
	} else {
	// add a new filter
		search.filters[what] = on;
	}

	// clear GUI
	$("li .selected").removeClass('selected');
	
	// switch everything back on
	$("#searchresults li").show();

	// loop current filters
	for (var f in search.filters) {
		// do filter
		this.innerfilter(f,search.filters[f], 0);

		// select in GUI
		$("#" + f + "-" + search.filters[f]).addClass('selected');
	}

	// update count
	search.filteredresults = $("#searchresults ol").children(":visible").length;
	search.status_complete();

	sortresults('relevance');
};

function innerfilter(what,on,reverse) {

	// filter results
	if(what == "result-price" && on == "COMMERCIAL"){
		$("#searchresults ol li ."+what+":contains(FREE)").parent().hide();
	} else {
		$("#searchresults ol li ."+what+":not(:contains("+on+"))").parent().hide();
	}
};

function sortresults(order) {
	search.status_active();
	switch (order) {
		case "relevance":
			setTimeout('search.sort_relevance()',10);
			break;
		case "title":
			setTimeout('search.sort_title()',10);
			break;
		case "price":
			setTimeout('search.sort_price()',10);
			break;
		case "format":
			setTimeout('search.sort_format()',10);
			break;
		case "source":
			setTimeout('search.sort_source()',10);
			break;
	};
};

function saveoptions (){
	$("#searchoptions input").each(function(){
		// save search options
		preferences.set(this.id, $(this).is('[checked]'));
	});
};

function loadoptions (){

	for (var e in search.sites[0]) {
		addoption(search.sites[0][e], 0);
	}
	for (var e in search.sites[1]) {
		addoption(search.sites[1][e], 1);
	}
};

function addoption(engine, type){
	var checked = "checked";

	if(preferences.get(engine.id) == false){ checked = ""; }
	$("#searchoptions ul[class=type" + type+ "]").append('<li class="engine icon-'+engine.id+'" title="'+engine.name+'"><input type="checkbox" id="'+engine.id+'" onclick="saveoptions()" '+checked+'></input> '+engine.name+'</li>');
};

function opensearch () {
	// we have a browser that has support for opensearch?
	if (window.external && ("AddSearchProvider" in window.external)){
		// the click action for the button
		$('#searchprovider').click(function() {
			window.external.AddSearchProvider('http://www.3dfilter.com/opensearch.xml'); 
			$("#searchprovider").slideUp("slow");
			return false;
		});

		$("#searchprovider").slideDown("slow");	
	}
};

var preferences = $.cookieJar('preferences');
var search = new search();
