var Checker = function(ip,scanner) {
	var self = this;
	this.ip = ip;
	this.img = new Image();
	this.img.onerror = function() {
		scanner.callback.call(scanner,ip);
	}
	this.img.onload = this.img.onerror;
	this.img.src = "http://"+ip+"/spabanner.jpg";
};

var Scanner = {
		checkers: {}
	,	started: 0
	,	finished: 0
	,	delay: 1000
	,	parallel: 4
	,	popular: ['192.168.1.100','192.168.1.2','192.168.1.65','192.168.1.64','192.168.1.66','192.168.1.101','192.168.1.10','192.168.0.100','192.168.1.3','192.168.1.102','192.168.0.3','192.168.1.67','192.168.1.5','192.168.2.4','192.168.1.105','192.168.2.2','192.168.0.2','192.168.1.70','192.168.0.10','192.168.1.245','192.168.0.199','192.168.0.101','192.168.1.4','192.168.1.6','192.168.1.68','192.168.1.20','192.168.2.3','192.168.1.16','192.168.2.37','192.168.0.5','192.168.15.2','192.168.1.110','192.168.1.71','192.168.1.47','192.168.0.4','192.168.1.11','192.168.1.111','192.168.1.120','192.168.10.2','192.168.2.50','192.168.1.251','192.168.11.2','192.168.0.32','192.168.1.69','192.168.0.111','192.168.0.92','192.168.1.108','192.168.1.21','192.168.1.39','10.0.0.3','192.168.16.70','192.168.2.100','192.168.0.91','192.168.1.115','192.168.15.103','192.168.1.125','192.168.2.6','192.168.0.102','192.168.1.106','192.168.1.79','192.168.3.2','192.168.20.100','10.0.0.1','192.168.0.16','192.168.1.9','192.168.0.104','192.168.3.100','192.168.10.100','192.168.2.5','192.168.178.19']
	,	ip: function(n) {
		return this.popular[n];
	}
	,	start: function() {
		this.started = this.finished = this.n = 0;
		this.count = this.popular.length;
		while(this.launch());
	}
	,	launch: function() {
		if((this.started-this.finished)>=this.parallel || (this.n==this.count)) return false;
		var ip = this.ip(this.n++);
		var checker = this.checkers[ip] = new Checker(ip,this);
		++this.started;
		var self = this;
		setTimeout(function() {
			self.callback(ip);
		},this.delay);
		return true;
	}
	,	callback: function(ip) {
		++this.finished;
		//document.getElementById('progress').style.width = Math.round(this.finished/this.count*100)+'%';
		var checker = this.checkers[ip];
		if (checker) {
			if (checker.img.width && checker.img.width>100) { this.found(checker,1); }
			checker.img.onload = checker.img.onerror = function() {};
			checker.img.src = undefined;
			delete this.checkers[ip];
		}
		if (this.started != this.finished) { this.launch(); } else { this.done(); }
	}
	,	done: function() {
		this.delay = this.delay *= 2;
	}
	, found: function(checker,t) {
		var ip = document.getElementById('ip');
		if (ip.value == '') ip.value = checker.ip;
	}
};

