var engines = Array();
var kw;
var site;
var block;
var authorized = false;
var d = new Date();
var timer;
var actual = 0;

function checkSerp() {
    actual++;
	  timer = setTimeout("block = 'time'; blocker();", 30000);
    block = false;    
    engines = ["yahoo", "altavista", "msn", "google_en", "google_en_cp", "google_cs", "jyxo", "seznam_cr", "morfeo"];
    kw = $("#kw").attr("value");
    site = $("#site").attr("value");
    security_code = $("#security_code").attr("value");
    if (!kw || !site) {
        alert("Vyplňte, prosím, obě pole.");
    } else {
        $("tr td:nth-child(1)").each(function(i) {
            this.innerHTML = "zjišťuji";  
        });
        var i = 0;
        while (engines[i]) {
            $.post("serp.php", { kw: kw, site: site, engine: engines[i], security_code: security_code, actual: actual}, function(data) { resolve(data); });
            i++;
        }
    }
}

function authorize() {
  if (!authorized) {    
    $("#cap").css("display", "none");
    authorized = true;
  } 
}

function resolve(data) {    
    if (!block) {
  		if (data == "captcha") {
  			if (authorized) {
  			  block = true;
          $("#captcha_image").attr("src", "captcha.php?" + d.getTime());  
          alert("Vaše autorizace vypršela, prosím, opište znovu text z obrázku.");
          $("#cap").css("display", "inline");
        } else {
          block = 'captcha';
    			alert("Opsali jste nesprávně kód z obrázku");
    			$("tr td:nth-child(1)").each(function(i) {
            	this.innerHTML = "";  
        	});
        }
  		} else {
        var obj = data.split(";;;");
        if (actual == obj[1]) {
          authorize();          
    	    var engine = "#" + obj[0] + " td:nth-child(0)";
    	    var result = "#" + obj[0] + " td:nth-child(1)";
    	    $(engine).html(obj[2]);
    	    $(result).html(obj[3]);
    	  }
      }		
	 } else {
    if (block == "time") {
      blocker();
    }
   }
}

function blocker() {
  $("tr td:nth-child(1)").each(function(i) {
    	if (this.innerHTML == "zjišťuji") this.innerHTML = "Vypršel čas na spojení";  
	});
}

