Element.addMethods({
	collectTextNodes: function(element){
		return $A($(element).childNodes).collect(function(node){
			return (node.nodeType==3 ? node.nodeValue : (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
		}).flatten().join('');
	}
});

//var url = "http://127.0.0.1/dropped/check/lib/results.php";
var url = "http://www.dropped.it/wp-content/themes/i-feel-dirty/check/lib/results.php";

var Domain = Class.create({
	initialize: function(name, id){
		this.name = name.gsub(/http:\/\/|www./, "");
		this.id = id;
		var arr = name.split('.');
		this.domain = arr[0];
		this.tld = arr[1];		
	},
	
	check: function(){
		new Ajax.Request(url, {
			method:'get',
			parameters: {name: this.name},
			onLoading: function(){
				$('pr-'+this.id).update('<div class="loader"></div>');
				$('bly-'+this.id).update('<div class="loader"></div>');
				$("al-"+this.id).update('<div class="loader"></div>');	
				$("age-"+this.id).update('<div class="loader"></div>');
				$("dmoz-"+this.id).update('<div class="loader"></div>');
				$("arch-"+this.id).update('<div class="loader"></div>');
				$("exp-"+this.id).update('<div class="loader"></div>');
				$("whois-"+this.id).update('<div class="loader"></div>');
			}.bind(this),
			onSuccess: function(transport){
				var content = transport.responseText.parseQuery();
				$("pr-"+this.id).replace(content.pr);
				$('bly-'+this.id).replace('<a href="http://siteexplorer.search.yahoo.com/advsearch?p=http%3A%2F%2F'+
										  this.name+'&bwm=i&bwmo=d&bwmf=s" target="_blank">'+content.yahoo+'</a>');
				$("al-"+this.id).replace('<a href="http://www.alexa.com/data/details/traffic_details/'+this.name+'" target="_blank">'+content.alexa+'</a>');
				$("age-"+this.id).replace((content.age != '-') ? '<a href="http://web.archive.org/web/*/http://'+this.name+
										   '" target="_blank">'+content.age+'</a>' : '-');
				$("dmoz-"+this.id).replace('<a href="http://search.dmoz.org/cgi-bin/search?search='+this.name+'" target="_blank">'+content.dmoz+'</a>');
				$("arch-"+this.id).replace((content.archive != '0') ? '<a href="http://web.archive.org/web/*/http://'+this.name+
											'" target="_blank">'+content.archive+'</a>' : "0");
				$("exp-"+this.id).replace(content.expire);
				if(content.avail == "true")
					$("whois-"+this.id).replace('<form action="http://ad.zanox.com/ppc/" method="get" target="_blank" id="form-'+this.id+'">'+
			'<input type="hidden" name="10069158C743508132&ULP" value="http://hosting.aruba.it/forward.asp?">'+
	        '<input name="Codifica2" type="hidden" value="1102436079">'+
			'<input name="domain" type="hidden" value="'+this.domain+'">'+
			'<input name="tld" type="hidden" value="'+this.tld+'"></form>'+
			'<a href="" onclick="$(\'form-'+this.id+'\').submit();return false;" class="green">Registra</a>');
				else
					$("whois-"+this.id).replace('<a href="http://whois.domaintools.com/'+this.name+'" target="_blank">Whois</a>');
			}.bind(this),
			onFailure: function(){}
		  });
	}

});

var CheckDomains = {	
	_templates: {
		domain: new Template(
			'<tr id="id-#{id}">' +
			'<td>#{index}</td>'+
			'<td class="nome"><a href="http://#{name}">#{name}</a></td>' +
			'<td><span id="pr-#{id}"></span></td>' +
			'<td><span id="bly-#{id}"></span></td>' +
			'<td><span id="al-#{id}"></span></td>' +
			'<td><span id="age-#{id}"></span></td>' +
			'<td><span id="arch-#{id}"></span></td>' +
			'<td><span id="dmoz-#{id}"></span></td>' +
			'<td><span id="exp-#{id}"></span></td>' +
			'<td><span id="whois-#{id}"></span></td>' +
			'</tr>'
		)
	},
	
	processForm: function(e){
		e.stop();
		this.reset();
		this.domains = [];
		if($F('domini').strip() != ''){
			$F('domini').split('\n').each(function(e, i){
				if(i+1 <= 200) 
					this.domains.push(new Domain(e.strip(), i));
			}.bind(this));
			this.buildTable();	
		}
	},
	
	buildTable: function(){
		var tpl = this._templates['domain'];
		var table = '<table id="domains">'+
						'<thead>'+
							'<tr>'+
								'<th></th>'+
								'<th class="nome"><span>Dominio</span></th>'+
								'<th class="pr"><span title="Google PageRank">PR</span></th>'+
								'<th><span title="Backlinks su Yahoo">Yahoo BL</span></th>'+
								'<th><span title="Traffico Alexa">Alexa Rank</span></th>'+
								'<th><span title="Et&agrave; del dominio in anni">Anni</span></th>'+
								'<th><span title="Numero di risultati nell\'Internet Archive">Archivio</span></th>'+
								'<th><span title="Presenza nella directory DMOZ">DMOZ</span></th>'+
								'<th><span title="Data di scadenza">Scadenza</span></th>'+
								'<th></th>'+
							'</tr>'+
						'</thead>'+
						'<tbody>'+
						'</tbody>'+
					'</table>';
		$('list').update(table);
		var tbody = $('domains').down('tbody');
		this.domains.each(function(e, i){
			e.index = i+1;
			tbody.insert(tpl.evaluate(e));
			if(1 == i % 2)
				$('id-'+i).addClassName('alternate');
			e.check();
		}.bind(this));
		new TableSorter($('domains'));
	},
	
	reset: function(){
		$("list").update('');
	}

};

var TableSorter = Class.create({
	initialize: function(element){
		this.element = $(element);
		this.sortIndex = -1;
		this.sortOrder = 'desc';
		this.initDOMReferences();
		this.initEventHandlers();
	},
	
	initDOMReferences: function(){
		var head = this.element.down('thead');
		var body = this.element.down('tbody');
		this.headers = head.down('tr').childElements();
		this.headers.each(function(e, i){
			e._colIndex = i;
		});
		this.body = body;
	},
	
	initEventHandlers: function(){
		this.handler = this.handlerClick.bind(this);
		this.element.observe('click', this.handler);
	},
	
	handlerClick: function(e){
		var element = e.element();
		if(!('_colIndex' in element)){
			element = element.ancestors().find(function(elt){
				return '_colIndex' in elt;
			});
			if(!((element) && '_colIndex' in element))
				return;
		}
		if(element._colIndex != 9 && element._colIndex != 0 && element._colIndex != 8)
			this.sort(element._colIndex);
	},
	
	adjustSortMarkers: function(index){
		if(this.sortIndex != -1)
			this.headers[this.sortIndex].removeClassName('sort-' + this.sortOrder);
		if(this.sortIndex != index){
			this.sortOrder = 'desc';
			this.sortIndex = index;
		}else
			this.sortOrder = ('asc' == this.sortOrder ? 'desc' : 'asc');
		this.headers[index].addClassName('sort-' + this.sortOrder);
	},
	
	sort: function(index){
		this.adjustSortMarkers(index);
		var rows = this.body.childElements();
		rows = rows.sortBy(function(row){
			var nodes = row.childElements()[this.sortIndex].collectTextNodes();			
			var num = (this.sortIndex != 0) ? parseInt(nodes) : nodes;
			return isNaN(num) ? 0 : num;
		}.bind(this));
		if('desc' == this.sortOrder)
			rows.reverse();
		rows.reverse().each(function(row, index){
			if(index > 0)
				this.body.insertBefore(row, rows[index -1]);
		}.bind(this));
		rows.reverse().each(function(row, index){
			row[(1 == index % 2 ? 'add' : 'remove') + 'ClassName']('alternate');
			row.down().update(index+1);
		});
	}
});

document.observe('dom:loaded', function(){
	$('form').observe('submit', CheckDomains.processForm.bindAsEventListener(CheckDomains ));
	var preload = new Image();
    preload.setAttribute('src', 'http://www.dropped.it/wp-content/themes/i-feel-dirty/check/images/loader.gif');
});
