var DMSearch = Class.create(); 
DMSearch.prototype = {
	initialize: function() 
	{ 
		this.q = "";
		this.browser = "";
		this.engines =  new Array();
		this.matrix =  new Object();
		this.indexing = new Array();
		this.ResultCount = this.matrixIndex = this.EngineTotal = this.EnginesLoading = this.CurrentSite = this.EnginesParsed = this.EnginesDone = 0;
		this.loading = true;
		this.log = "";
	},
	
	pollProgress: function(add)
	{
		var percent = 0;
		percent = Number(  (this.EnginesDone/ (this.EngineTotal-1))*100  );
		if (percent > 100) percent = 100;
		$("search_stat").innerHTML = percent+"%";
	},
	
	DoComplete: function(state)
	{
		switch(state)
		{
			case 0:
				if($("loading"))$("loading").style.display = "none";
				if($("results"))$("results").style.display = "block";
				if($("footer"))$("footer").style.display = "block";
			break;
			case 1:
				if (this.ResultCount == 0)
				{
					$("lowestprices_products").style.paddingTop = "50px";
					$("lowestprices_products").innerHTML  = "No products were found matching \""+this.q+"\".";
				}
				//$('search_status').hide();
				setTimeout("new Effect.Fade('search_status');", 1000);
			break;
		}
	},
	
	assignMatrix: function(engine, matrixIndex)
	{
		this.matrix[matrixIndex] = engine;
		this.construct(matrixIndex);
		delete(engine);
		return(true);
	},
	
	construct: function(matrixIndex)
	{
		var engine = this.matrix[matrixIndex];
		
		if (engine.status == "nochange")
		{
			var details = "No Results";
		}
		else
		{
			this.ResultCount++;
			var details = engine.results.total_count+" Results ";
			details += " <a href=\""+engine.results.url+"\" target=\"_blank\">view all</a>";
			//details += "[ <a href=\""+engine.results.url+"\" target=\"_blank\">view all</a> | <a href=\"javascript:void(0);\">More...</a> ]";
		}
		
		$(engine.name+"_details").innerHTML = details;
		delete(details);
		engine.foundon = engine.name+".com";
		this.productplacer(engine);
		return(true);
	},
	
	productrow: function(id, html)
	{
		$(id+"_products").innerHTML += html;
	},
	
	lowestPrice: function()
	{
		Array.prototype.sortAsc = function(field) {
			var saveO = Object.prototype.toString;
			var saveA = Array.prototype.toString;
			Object.prototype.toString = function(){ return this[field] };
			Array.prototype.toString = function(){ return this[field] };
			this.sort();
			Array.prototype.toString = saveA;
			Object.prototype.toString = saveO;
		}
		Array.prototype.sortDesc = function(field) {
			var saveO = Object.prototype.toString;
			var saveA = Array.prototype.toString;
			Object.prototype.toString = function(){ return this[field] };
			Array.prototype.toString = function(){ return this[field] };
			this.sort();
			this.reverse();
			Array.prototype.toString = saveA;
			Object.prototype.toString = saveO;
		}
		this.indexing.sortAsc("price"); 
		$('lowestprices_products').innerHTML = "";
		var m = (this.indexing.length < 7)?this.indexing.length:7;
		for (var i=0; i<m; i++)
		{
			if (this.indexing[i].product.price <= 0 || this.indexing[i].product.price == "") continue;
			this.productinsert(this.indexing[i].product, true);
		}
	},
	
	productinsert: function(product, doLow)
	{
		if (product.price == 0)
		var price = "$--";
		else
		var price = this.priceFormat(product.price);

		html = '<div class="product">';
		html += '<div><span>'+price+'</span><a href="'+decodeURIComponent(product.link)+'" target="_blank">';
		html += '<img src="/includes/'+decodeURIComponent(product.image)+'" height="50" width="50"><b>'+product.title+'</b><br>'+product.description+'</a></div>{HTML_ON}';
		if (doLow) html_on = '<div class="foundon"> <strong>Found on</strong>: <a href="'+product.viewall+'">'+product.foundon+' (view all)</a></div>';
		html += '</div>';
				
		if (doLow)
		this.productrow("lowestprices", html.replace("{HTML_ON}", html_on));
		else this.productrow(product.engine, html.replace("{HTML_ON}", ""));
	},
	
	productplacer: function(engine)
	{
		var html, foundon, html_on;

		if (engine.set != 1 && (engine.status == "nochange" || engine.results.count == 0))
		{
			$(engine.name+"_status").innerHTML = engine.foundon+" did'nt return any results for \""+this.q.replace(/\+/g, " ")+"\".";
		}
		else
		{
			$(engine.name+"_products").innerHTML = "";
			for (var i=0; i<engine.results.count; i++)
			{
				html_on = ""; 
				product = engine.results[i];
				
				//if (product.lowest == 1)
				if (product.price != "")
				this.indexing[this.indexing.length] = {
					price:product.price, product:product
				};
				
				product.foundon = engine.foundon;
				product.engine = engine.name;

				this.productinsert(product, false);
			}
			engine.set = 1;
		}
		this.EnginesDone++;
		this.pollProgress(1);
		delete(html);
		delete(foundon);
		delete(engine);
		delete(html_on);
		return(true);
	},
	

	option: function(option, bool)
	{
		switch (option)
		{
			case "complete": 
				this.loading = Boolean(bool); 
				$('loading').hide();
				$('footer').show();
			break;
			case "loading": 
				this.loading = Boolean(bool); 
			break;
		}
		return(true);
	},
	
	priceFormat: function(num)
	{
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num)) num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10) cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
		//return (((sign)?'':'-') + '$' + num + '.' + cents);
		return (((sign)?'':'-') + '$' + num);
	}
}


var Engine = Class.create();
Engine.prototype = Object.extend(new DMSearch(), {
	initialize: function(DM)
	{
		this.DM = DM;
		this.name = DM.engines[DM.CurrentSite];
		this.CurrentSite = DM.CurrentSite;
		this.attempts = 0;
		this.attemptLimit = 10;
		this.HTTPRequest;
		this.results = new Array();
		this.checkstatus = "unchanged";
		this.status = "initialize";
		this.loading = true;
	},
	
	XFER: function ()
	{
		var DM = this.DM;
		var self = this;
		var url = '/request.php';
		this.HTTPRequest = new Ajax.Request(url, {
			postBody: 'q='+DM.q+'&engine='+self.name,
			onFailure: function() { self.status = "failure"; },
			onComplete: function(transport)
			{
				var response = transport.responseText;
				if (response != "noresults")
				{
					self.status = "complete";
					self.loading = false;
					//if (self.name == "price") alert(response);
					var json = response.evalJSON();
					self.results = json;
				}
				else
				{
					self.status = "noresults";
					if (self.attempts > self.attemptLimit)
					{
						self.status = "nochange";
						self.loading = false;
					}
					self.attempts++;
				}
				
				//DM.log += '&bull; '+self.name+': '+self.status+" #"+self.attempts+"<br>";
				//$("debug").innerHTML += '&bull; '+self.name+': '+self.status+" #"+self.attempts+" : "+response+"<br>";
				delete(transport, response, json);
			}
		});
	}
}); 
function handleError(one, two, three) {
	//alert("An error has occured in search:\n"+one+"\nDomain:"+two+"\nLine Number:"+three);
	return true;
}

window.onerror = handleError;
