var chkIntervalXML=true;
var startToGetResult=0;
var countArrayKeywords=0;
var objXML=null;
var IDintervalQuery=null;
var chkOperationComplete=false;
var chkOperationFinalComplete=false;
var totalTimeUsed=0;
var codice_cliente_temp=null;
var array_keywords=null;
var randomNumber=0;

var totKeyPages=0;
var totCustomers=0;
var totKeywords=0;
var fineLetturaPerQuellaKeyword=false;
var countRielaborazioni=0;

var arrayComponent=["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","MICROSOFT.XMLHTTP.1.0","MICROSOFT.XMLHTTP.1","MICROSOFT.XMLHTTP"];
function selectObj() {
	var varObjNew=null;
	for(var cc=0;cc<arrayComponent.length;cc++){
		try {varObjNew=new ActiveXObject(arrayComponent[cc]);break;}catch(c){varObjNew=null;}
	}
	if(typeof XMLHttpRequest!="undefined" || !varObjNew){
		try{varObjNew=new XMLHttpRequest();}catch(e){alert("Impossible to create an HTTP connection! No XML component installed on your PC! ("+e.message+")");}
	}
	return varObjNew;
}

function createRandomNumber() {
	var date_random=(new Date()).getTime();
	var temp_random=Math.floor(Math.random()*parseInt(date_random));
	return temp_random;
}

function openXML(url,obj,typeResponse,typeSend,postValue) {
//	addTextInfo(url);
	if(typeof obj=="object" && obj.readyState!=0){obj.abort();}
	if(typeof typeSend=="undefined" || typeSend.length<=0){typeSend='GET';}
	if(typeof postValue=="undefined" || postValue.length<=0){postValue=null;}else{postValue=encodeURIComponent(postValue);}
	typeSend=typeSend.toUpperCase();
	obj.open(typeSend,url,true);
	timeLoadingtemp=(new Date()).getTime();
	if(typeSend=='POST'){obj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");}
	obj.setRequestHeader("Cache-Control","no-cache");obj.setRequestHeader("Pragma","no-cache");obj.setRequestHeader("Cache-Control","no-store");
	obj.setRequestHeader("Expires","Wed, 31 Dec 1980 00:00:00 GMT");
	var paginaActualTemp=0;paginaActualTemp=(startToGetResult / 10) + 1;
	obj.onreadystatechange=function(){
		rv=obj.readyState;
		if(rv==1){
			var tempCount=countArrayKeywords+1;
			addTextInfo("Scan of the Keyword n."+tempCount+" in progress ...");
		}
		if(rv==4){
			if (obj.status==200){
				countRielaborazioni=0;
				var txtR='txt';if(typeResponse=="xml"){txtR=obj.responseXML}else{txtR=obj.responseText};
				timeLoading=((new Date()).getTime())-timeLoadingtemp;timeLoading=timeLoading/1000;
				totalTimeUsed+=parseFloat(timeLoading);
				if(txtR.replace(' ','')=="GoogleKeyError"){
					addTextInfo("Google Key not found ! Internal error ...");
					chkIntervalXML=false;//NEGO PER IL MOMENTO DI ELABORARE I RISULTATI DELLE PAGINE DELLE KEYWORDS
					window.clearInterval(IDintervalQuery);
					if(typeof objXML=="object" && objXML.readyState!=0){objXML.abort();objXML=null;}
					alert("Google Key not found ! Internal error ...");
				} else {
					addTextInfo("Keyword "+paginaActualTemp+" elaborata correttamente in "+timeLoading+" sec.");
					addTextInfo("Waiting for the next keyword !");
				}
			}else{
				if(countRielaborazioni<=3){
					//addTextInfo("Si è verificato un errore. N."+obj.status+" - "+obj.statusText +"");
					//addTextInfo("Errore on: "+url +"");
					startToGetResult-=10;
					fineLetturaPerQuellaKeyword=false;
					countRielaborazioni+=1;
					addTextInfo("Page "+paginaActualTemp+" in reworking ...");
				}else{}
			}
			chkIntervalXML=true;
			if(fineLetturaPerQuellaKeyword==true){
				countArrayKeywords+=1;//PASSO ALLA KEY SUCCESSIVA DA ANALIZZARE
				startToGetResult=0;//AZZERO ALLA PRIMA PAGINA DA DOVE LEGGERE I RISULTATI EPR LA NUOVA KEY
				//CONTROLLO SE LE KEYWORD SONO FINETE O NO
				if(countArrayKeywords<totKeywords){
					//CI SONO ALTRE KEYWORD DA LEGGERE
				} else {
					//KEYWORDS FINITE
					chkIntervalXML=false;//NEGO PER IL MOMENTO DI ELABORARE I RISULTATI DELLE PAGINE DELLE KEYWORDS
					window.clearInterval(IDintervalQuery);
					addTextInfo("Finish !");
//					document.formEsecuzione.sessionID.value=randomNumber;
//					document.formEsecuzione.salva.style.visibility="visible";//VISUALIZZO IL PULSANTE DI SALVATAGGIO DEI DATI
					changeStateForm(false);//RIPRISTINO il form di ricerca
					//CANCELLO gli oggetti XMLHTTP
					if(typeof obj=="object" && obj.readyState!=0){obj.abort();obj=null;}
					window.top.location.href="basic/showResult.asp?idS="+randomNumber;
				}
			}else{}
		}
	};
	if(typeSend=='POST'){obj.send(postValue);}else{obj.send(null);}
}

function getDataFromASP() {
	if(chkIntervalXML==true) {
		chkIntervalXML=false;
		if(startToGetResult==0){
			addTextInfo("Keyword in progress: "+array_keywords[countArrayKeywords]);
		}
//		alert("http://www.igloosoft.net/siteanalysis/basic/getData.asp?idSessione="+randomNumber+"&country="+countryCheck+"&q="+array_keywords[countArrayKeywords]+"&s="+startToGetResult+"&k=&ky=");
		openXML("http://www.keywordanalysis.info/basic/getData.asp?idSessione="+randomNumber+"&country="+countryCheck+"&q="+array_keywords[countArrayKeywords]+"&s="+startToGetResult+"&k=&ky=", objXML, "txt", "GET");
		
		startToGetResult+=10;
		var resultActualXX = parseInt(1)*10;
		
		if(startToGetResult<resultActualXX) {
			fineLetturaPerQuellaKeyword=false;
		} else {
			fineLetturaPerQuellaKeyword=true;
		}
	}
}

function readAPI() {
	totKeywords=parseInt(document.formEsecuzione.codKey_ok.length);
	if(totKeywords<=0) {
		alert("Insert a Keyword...");
		return false;
	}
	array_keywords=new Array();

	randomNumber=createRandomNumber();
	
	for(var ppcc=0; ppcc<=totKeywords-1; ppcc++) {
		array_temp2=document.formEsecuzione.codKey_ok.options[ppcc].value.toString();
		array_keywords[ppcc]=array_temp2;
	}
	
	addTextInfo("Keywords selezionate: "+totKeywords+".");
	
	if(totKeywords>0) {
		countryCheck=document.formEsecuzione.countryCheck.options[document.formEsecuzione.countryCheck.selectedIndex].value;
		if (!countryCheck) { countryCheck=""; }
		changeStateForm(true);
		chkIntervalXML=true;
		countArrayKeywords=0;
		objXML=selectObj();
		IDintervalQuery=window.setInterval("getDataFromASP()", 25000);
		addTextInfo("Starting in 25 sec.");
	} else {
		addTextInfo("Inserire almeno 1 Keyword ...");
	}
}

function changeStateForm(boolValue) {
	document.formEsecuzione.codKey.disabled=boolValue;
	document.formEsecuzione.codKey_ok.disabled=boolValue;
	document.formEsecuzione.button.disabled=boolValue;
	document.formEsecuzione.countryCheck.disabled=boolValue;
	document.formEsecuzione.addKeyToList.disabled=boolValue;
	document.formEsecuzione.removeKeyToList.disabled=boolValue;
	if(boolValue==true){
		
	} else {
		//RIASSEGNAZIONE VARIABILI
		countryCheck=false;
		chkIntervalXML=true;
		startToGetResult=0;
		countArrayKeywords=0;
		objXML=null;
		IDintervalQuery=null;
		chkOperationComplete=false;
		chkOperationFinalComplete=false;
		totalTimeUsed=0;
		codice_cliente_temp=null;
		array_keywords=null;
		cusomerSuccessivo=false;
		totKeyPages=0;
		totCustomers=0;
		totKeywords=0;
		fineLetturaPerQuellaKeyword=false;
		countRielaborazioni=0;
//		randomNumber=createRandomNumber();
	}
}

function addToCombo() {
	var chp=false;
	var actualToAddIntoCombo=parseInt(document.formEsecuzione.codKey.value.length);
	if(actualToAddIntoCombo>0) {
		if (parseInt(document.formEsecuzione.codKey_ok.length)<3) {
			document.formEsecuzione.codKey_ok.options[document.formEsecuzione.codKey_ok.length]=new Option(document.formEsecuzione.codKey.value,document.formEsecuzione.codKey.value);
			document.formEsecuzione.codKey.value="";
			document.formEsecuzione.codKey.focus();
		} else {
			alert("Max. 3 Keywords to analyze to try !");
		}
	} else {
		alert("Insert a keyword to add to the list !");
	}
}

function removeFromCombo(strValue) {
	var actualToAddIntoCombo=parseInt(document.formEsecuzione.codKey_ok.length);
	for(var ppc=actualToAddIntoCombo-1; ppc>=0; ppc--) {
		if(document.formEsecuzione.codKey_ok.options[ppc].value==strValue) {
			document.formEsecuzione.codKey_ok.options[ppc]=null;
		}
	}
}

function addTextInfo(strValue){createDiv100(strValue);}