var _GLOBAL = {};
_GLOBAL.transaction_key = null;
_GLOBAL.report_id = null;
_GLOBAL.website_list = null;

//##########################################################################################

//--> Begin Function :: LogAction
	function LogAction(Action){
		try{
			console.log(Action);
		}
		catch(err){}
	}
//--> End Function :: LogAction

//##########################################################################################

//--> Begin Function :: ViewReport
	function ViewReport(report_id){
		var its_random = new Date().getTime();
		ShadeScreen(false);
		window.open("/seo-tools/download_report.aspx?r=competition_report&report_id=" + _GLOBAL.report_id + "&no_cache=" + its_random ,'','scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
	}
//--> End Function :: ViewReport

//##########################################################################################

//--> Begin Function :: ValidateForm
	function ValidateForm(){
		if(document.$("captcha_code").value == ""){
			alert("Please enter a code");
			return;
		}
		
		var SubmitData = {};
		SubmitData["name_first"] 	= document.$("name_first").value;
		SubmitData["name_last"] 	= document.$("name_last").value;
		SubmitData["email"] 		= document.$("email").value;
		SubmitData["phone"] 		= document.$("phone").value;
		SubmitData["url"] 			= document.$('website').value;
		SubmitData["comment"] 		= "keyword:"+ document.$("keyword").value +"\n";
		SubmitData["source_id"] 	= "111";
		SubmitLead(SubmitData);
		
		//get form variables
		_GLOBAL.website = document.$('website').value;
		_GLOBAL.keyword = escape(document.$('keyword').value);
		_GLOBAL.email_address = document.$('email').value;
		_GLOBAL.captcha_code = document.$('captcha_code').value;
		
		document.$('action').setAttribute("disabled","true");
		
		//sequence out queues
		_GLOBAL.transaction_key = null;
		_GLOBAL.report_id = null;
		AddToQueue("GetTransactionKey()");
		AddToQueue("GetReportID()");
		//AddToQueue("GetWebsitelist('" + _GLOBAL.keyword + "')");
		AddToQueue("ExecuteReport()");
		
		//execute queue
		ExecuteQueue();
	}
//--> End Function :: ValidateForm

//##########################################################################################

//--> Begin Function :: ExecuteReport
	function ExecuteReport(){
		
		//request transaction key
		if(_GLOBAL.transaction_key != null && _GLOBAL.report_id != null){
			
			//create a new ajax object
			var MyAjax = new powerHTTP();
			
			MyAjax.complete = function(response) {
				if(this.was_successful()) {
					//get response json datatable
					var DataTable = eval('(' + response.text + ')');
					
					//show table
					document.$("results_table_b").style.display = "";
					
					for(Row in DataTable){
						var Response = DataTable[Row];
						document.$("domain_" + Row + "_name").innerHTML = Response.website;
						document.$("domain_" + Row + "_google_ranking").innerHTML = Response.google_keyword_ranking;
						document.$("domain_" + Row + "_page_rank").innerHTML = Response.pr;
						document.$("domain_" + Row + "_archive_date").innerHTML = Response.website_start_date;
						//document.$("domain_" + Row + "_reg_date").innerHTML = Response.reg_date;
						//document.$("domain_" + Row + "_yahoo_indexed_pages").innerHTML = CreateLink(Response.yahoo_indexed_pages,"http://siteexplorer.search.yahoo.com/advsearch?ei=UTF-8&p=" + Response.website + "&searchbwm=Explore+URL&txtSiteUrl="+ Response.website);
						document.$("domain_" + Row + "_yahoo_indexed_pages").innerHTML = CreateLink(Response.yahoo_indexed_pages,"http://www.google.com/search?hl=en&site=&q=site:" + Response.website);
						document.$("domain_" + Row + "_yahoo_backlinks").innerHTML = CreateLink(Response.yahoo_inbound_links,  "http://siteexplorer.search.yahoo.com/advsearch?p=" + Response.website + "&bwm=i&bwmo=d&bwmf=u");
						document.$("domain_" + Row + "_yahoo_ranking").innerHTML = Response.yahoo_keyword_ranking;
						
						if(Response.website_start_date != "N/A"){
							Response.website_start_date = CreateLink(Response.website_start_date, "http://web.archive.org/web/*/" + Response.website)
						}
		
						//if(Response.reg_date != "N/A"){
							//Response.reg_date = CreateLink(Response.reg_date, "http://www.dnsstuff.com/tools/whois.ch?ip=" + Response.website)	
						//}
					}
					
					//change gui to reflect finished report
					document.$('captcha_code').value = '';
					document.$('captcha_alert').innerHTML = '';
					document.$('action').removeAttribute('disabled');
					ShowQuickLoad(false);
					SetInnerHTMLById('download_link','<a href=\"#here\" onclick=\"ViewReport();\">Download Report</a>');
					ShadeScreen(true);
					RefreshCaptcha();
				}
	
				//release queue and cleanup
				_GLOBAL.queue_continue = true;
			};
			
			//change gui to reflect loading process
			document.$('download_link').innerHTML = '<a href=\"#stop\" name=\"stop\" onclick=\"StopReport()\">Stop</a>';
			document.$("results_table_a").style.display = "";
			ShowQuickLoad(true);
			
			document.$("domain_0_name").innerHTML = '<img id="loading" src="/_IMAGES/ajax_loading_small.gif" /> Loading...';
			document.$("domain_0_google_ranking").innerHTML = '...';
			document.$("domain_0_yahoo_indexed_pages").innerHTML = '...';
			document.$("domain_0_archive_date").innerHTML = '...';
			//document.$("domain_0_reg_date").innerHTML = '...';
			document.$("domain_0_yahoo_backlinks").innerHTML ='...';
			document.$("domain_0_yahoo_ranking").innerHTML = '...';
			document.$("domain_0_page_rank").innerHTML = '...';
			
			//set loading elements
			for(var i = 1; i <= 10; i++){
				document.$("domain_" + i + "_name").innerHTML = '...';
				document.$("domain_" + i + "_google_ranking").innerHTML = '...';
				document.$("domain_" + i + "_yahoo_indexed_pages").innerHTML = '...';
				document.$("domain_" + i + "_archive_date").innerHTML = '...';
				//document.$("domain_" + i + "_reg_date").innerHTML = '...';
				document.$("domain_" + i + "_yahoo_backlinks").innerHTML ='...';
				document.$("domain_" + i + "_yahoo_ranking").innerHTML = '...';
				document.$("domain_" + i + "_page_rank").innerHTML = '...';
			}
			
			var Data = new Array();
			Data.push("domain=" + _GLOBAL.website);
			Data.push("keyword=" + _GLOBAL.keyword);
			Data.push("transaction_key=" + _GLOBAL.transaction_key);
			Data.push("report_id=" + _GLOBAL.report_id);
			var myPostData = Data.join("&");
			MyAjax.post("/seo-tools/seo-competition-report.html?r=get_report_data", myPostData);
			
		}
	}
//--> End Function :: ExecuteReport

//##########################################################################################

//--> Begin Function :: StopReport
	_GLOBAL.stop_report = false;
	function StopReport(){
		_GLOBAL.stop_report = true;
		document.$('download_link').innerHTML = 'Stopping...';
		document.$('quick_load').innerHTML = '<img align="absmiddle" src="/_IMAGES/ajax_loading_small_black.gif"/> Stopping...';
	}
//--> End Function :: StopReport

//##########################################################################################

//--> Begin Function :: GetReport
	function GetReport(){

		//request transaction key
		if(_GLOBAL.transaction_key != null && _GLOBAL.report_id != null){

			document.$('download_link').innerHTML = '<a href=\"#stop\" name=\"stop\" onclick=\"StopQueue()\">Stop</a>';
			document.$("results_table_a").style.display = "";
			document.$("results_table_b").style.display = "";
			
			AddToQueue("ShowQuickLoad(true)");
			
			var GoogleRanking = "";
			var Domainname = "";
			
			//set loading columns and queue it up!
			for(var i = 0 ; i < 11 ; i++) {
				
				//accomodate for the main domain
				if(i == 0){
					GoogleRanking = "...";
					Domainname = _GLOBAL.website;
				}else{
					
					//something failed - restart
					if(_GLOBAL.website_list[i] == undefined){
						
						//reset stop queue
						_GLOBAL.stop_queue = false;
						
						//reset continue
						_GLOBAL.queue_continue = true;
						
						//clear queue
						_GLOBAL.queue = new Array();
						
						AddToQueue("GetWebsitelist('" + _GLOBAL.keyword + "')");
						AddToQueue("GetReport()");
						
						//execute queue
						ExecuteQueue();
						return;
					}
					
					GoogleRanking = i;
					Domainname = _GLOBAL.website_list[i];
				}
				document.$("domain_" + i + "_google_ranking").innerHTML = GoogleRanking;				
				document.$("domain_" + i + "_name").innerHTML = '&#160;';
				document.$("domain_" + i + "_yahoo_indexed_pages").innerHTML = '&#160;';
				document.$("domain_" + i + "_archive_date").innerHTML = '&#160;';
				//document.$("domain_" + i + "_reg_date").innerHTML = '&#160;';
				document.$("domain_" + i + "_yahoo_backlinks").innerHTML ='&#160;';
				document.$("domain_" + i + "_yahoo_ranking").innerHTML = '<img id="loading" src="/_IMAGES/ajax_loading_small.gif" /> Loading...';
				document.$("domain_" + i + "_page_rank").innerHTML = '&#160;';
				document.$("domain_" + i + "_name").innerHTML = Domainname;

				AddToQueue("GetDomainStats('" + Domainname + "', '" + _GLOBAL.keyword + "','" + i + "');");
			}
			
			AddToQueue("RefreshCaptcha(); _GLOBAL.queue_continue = true;");
			AddToQueue("document.$('captcha_code').value = ''; _GLOBAL.queue_continue = true;");
			AddToQueue("document.$('captcha_alert').innerHTML = ''; _GLOBAL.queue_continue = true;");
			AddToQueue("ShowQuickLoad(false)");
			AddToQueue("SetInnerHTMLById('download_link','<a href=\"#here\" onclick=\"ViewReport();\">Download Report</a>'); _GLOBAL.queue_continue = true;");
			AddToQueue("ShadeScreen(true); _GLOBAL.queue_continue = true;");
			AddToQueue("RefreshCaptcha(); document.$('captcha_code').value = ''; document.$('captcha_alert').innerHTML = '';  _GLOBAL.queue_continue = true;");
			AddToQueue("document.$('action').removeAttribute('disabled'); _GLOBAL.queue_continue = true;");
			
			//execute queue
			ExecuteQueue();
			
		}else{
			RefreshCaptcha();
			document.$("captcha_code").value = "";
			document.$("captcha_alert").innerHTML = "Incorrect Code.";	
		}
		
		//release queue and cleanup
		_GLOBAL.queue_continue = true;
	}
	
//--> End Function :: GetReport

//##########################################################################################

//--> Begin Function :: GetDomainStats
	function GetDomainStats(Website, Keyword, CurrentItem) {

		var MyAjax = new powerHTTP();	
		MyAjax.current_item = CurrentItem;
		MyAjax.loading = function() { };
		MyAjax.complete = function(response) {
			if(this.was_successful()) {
				var Response = eval('(' + response.text + ')');
				document.$("domain_" + this.current_item + "_page_rank").innerHTML = Response.pr;
				
				if(Response.website_start_date != "N/A"){
					Response.website_start_date = CreateLink(Response.website_start_date, "http://web.archive.org/web/*/" + Response.website)
				}

				if(Response.reg_date != "N/A"){
					//Response.reg_date = CreateLink(Response.reg_date, "http://www.dnsstuff.com/tools/whois.ch?ip=" + Response.website)	
				}
				
				document.$("domain_" + this.current_item + "_archive_date").innerHTML = Response.website_start_date;
				//document.$("domain_" + this.current_item + "_reg_date").innerHTML = Response.reg_date;
				document.$("domain_" + this.current_item + "_yahoo_indexed_pages").innerHTML = CreateLink(Response.yahoo_indexed_pages,"http://siteexplorer.search.yahoo.com/advsearch?ei=UTF-8&p=" + Response.website + "&searchbwm=Explore+URL&txtSiteUrl="+ Response.website);
				document.$("domain_" + this.current_item + "_yahoo_backlinks").innerHTML = CreateLink(Response.yahoo_inbound_links,  "http://siteexplorer.search.yahoo.com/advsearch?p=" + Response.website + "&bwm=i&bwmo=d&bwmf=u");
				document.$("domain_" + this.current_item + "_yahoo_ranking").innerHTML = Response.yahoo_keyword_ranking;
				
				if(this.current_item == 0){
					document.$("domain_" + this.current_item + "_google_ranking").innerHTML = Response.google_keyword_ranking;
				}
			}

			//release queue and cleanup
			_GLOBAL.queue_continue = true;
		};

		var Data = new Array();
		Data.push("website=" + Website);
		Data.push("keyword=" + Keyword);
		Data.push("transaction_key=" + _GLOBAL.transaction_key);
		Data.push("report_id=" + _GLOBAL.report_id);
		Data.push("field=domain_" + CurrentItem);
		var myPostData = Data.join("&");
		MyAjax.post("/seo-tools/seo-competition-report.html?r=get_domain_stats", myPostData);
	}
//--> End Function :: GetDomainStats

//##########################################################################################

//--> Begin Function :: GetWebsitelist

	function GetWebsitelist(Keyword) {

		var MyAjax = new powerHTTP();
		
	//begin handling loading
		MyAjax.loading = function() {};
	//end handling loading
	
	//begin handling response
		MyAjax.complete = function(response) {
			if(MyAjax.was_successful()) {

				var Response = eval('(' + response.text + ')');
				
				if(Response.is_success == "true"){				
					_GLOBAL.website_list = Response;
				}else{
					_GLOBAL.report_id = null;
				}
				
			}else{
				_GLOBAL.website_list = Response;
			}
			//release queue
			_GLOBAL.queue_continue = true;
		};
	//end handling response

	//begin execute request	
		var Data = new Array();
		Data.push("keyword=" + Keyword);
		Data.push("transaction_key=" + _GLOBAL.transaction_key);
		var myPostData = Data.join("&");
		MyAjax.post("/seo-tools/seo-competition-report.html?r=get_website_list", myPostData);
	//end execute request*/	
	
	}
	
//--> End Function :: GetWebsitelist

//##########################################################################################

//--> Begin Function :: CreateLink

	function CreateLink(InnerHtml, Href){
		return "<a target=\"_blank\" href=\""+Href+"\">"+InnerHtml+"</a>";
	}
	
//--> End Function :: CreateLink

//##########################################################################################

//--> Begin Function :: RefreshCaptcha

	function RefreshCaptcha(){
		var its_random = new Date().getTime();
		document.$("captcha").setAttribute('src', '/seo-tools/_captcha.aspx?' + its_random);
		document.$("captcha_code").value = "";
	}
	
//--> End Function :: RefreshCaptcha

//##########################################################################################

//--> Begin Function :: GetReportID
	function GetReportID() {
		
		var MyAjax = new powerHTTP();
		
	//begin handling loading
		MyAjax.loading = function() {};
	//end handling loading
	
	//begin handling response
		MyAjax.complete = function(response) {
			if(MyAjax.was_successful()) {
				
				//eval into response
				var Response = eval('(' + response.text + ')');
				
				if(Response.is_success == "true"){				
					_GLOBAL.report_id = Response.report_id;
				}else{
					_GLOBAL.report_id = null;
				}
			}
			else {
				_GLOBAL.report_id = null;
			}
			
			//release queue
			_GLOBAL.queue_continue = true;
		};
	//end handling response

	//begin execute request	
		var Data = new Array();
		Data.push("website=" 			+ _GLOBAL.website);
		Data.push("keyword=" 			+ _GLOBAL.keyword);
		Data.push("email_address=" 		+ _GLOBAL.email_address);
		Data.push("transaction_key=" 	+ _GLOBAL.transaction_key);
		var myPostData = Data.join("&");
		MyAjax.post("/seo-tools/seo-competition-report.html?r=get_report_id", myPostData);
	//end execute request
	
	}
//--> End Function :: GetReportID

//##########################################################################################

//--> Begin Function :: GetTransactionKey
	
	function GetTransactionKey() {
		
		var MyAjax = new powerHTTP();
		
	//begin handling loading
		MyAjax.loading = function() {};
	//end handling loading
	
	//begin handling response
		MyAjax.complete = function(response) {
			if(MyAjax.was_successful()) {
				
				//eval into response
				var Response = eval('(' + response.text + ')');
				
				//test for scraping
				if(Response.is_success == "false"){				
					_GLOBAL.transaction_key = null;
				}else{
					_GLOBAL.transaction_key = Response.transaction_key;
				}
				
			}
			else {
				_GLOBAL.transaction_key = null;
			}
			
			//release queue
			_GLOBAL.queue_continue = true;
		};
	//end handling response

	//begin execute request	
		var Data = new Array();
		Data.push("captcha_code=" + _GLOBAL.captcha_code);
		var myPostData = Data.join("&");
		MyAjax.post("/seo-tools/_captcha.aspx?r=get_transaction_key", myPostData);	
	//end execute request
	}
	
//--> End Function :: GetTransactionKey

//##########################################################################################

//--> Begin Function :: AddToQueue

	_GLOBAL.queue = new Array();
	_GLOBAL.queue_continue = true;
	function AddToQueue(obj){
		
		_GLOBAL.queue.push(obj);
	}
	
//--> End Function :: AddToQueue

//##########################################################################################

//--> Begin Function :: AddToQueue

	_GLOBAL.stop_queue = false;
	function StopQueue(){
		_GLOBAL.stop_queue = true;
		document.$('download_link').innerHTML = 'Stopping...';
		document.$('quick_load').innerHTML = '<img align="absmiddle" src="/_IMAGES/ajax_loading_small_black.gif"/> Stopping...';
	}
	
//--> End Function :: AddToQueue

//##########################################################################################

//--> Begin Function :: ExecuteQueue
	
	function ExecuteQueue(){

		//is the queue empty?
		if(_GLOBAL.queue.length == 0) {
			return;
		//is the engine busy?
		}else if(_GLOBAL.queue_continue == false) {

			//call the queue sender in another 10 m.s.
			setTimeout("ExecuteQueue()", 100);
		}
		else{
			
			//stop queue
			if(_GLOBAL.stop_queue == true){
				
				//reset stop queue
				_GLOBAL.stop_queue = false;
				
				//reset continue
				_GLOBAL.queue_continue = true;
				
				//clear queue
				_GLOBAL.queue = new Array();
				
				//hide quick load
				ShowQuickLoad(false);
				
				//clear empty result table
				for(var i = 0 ; i < 11 ; i++) {
					if(document.$("domain_" + i + "_yahoo_ranking").innerHTML.indexOf("Loading") != -1){
						document.$("domain_" + i + "_yahoo_ranking").innerHTML = '...';
					}
				}
				
				//place reset button
				SetInnerHTMLById('download_link',' ');
				
				//do other cleanup work
				RefreshCaptcha(); 
				document.$('captcha_code').value = ''; 
				document.$('captcha_alert').innerHTML = '';
				document.$('action').removeAttribute('disabled');
				document.$('quick_load').innerHTML = '<img align="absmiddle" src="/_IMAGES/ajax_loading_small_black.gif"/> Loading...';
				return;
			}

			//dont execute until the function called sets to true
			_GLOBAL.queue_continue = false;
			
			//shift off current function
			var CurrentCall = _GLOBAL.queue.shift();
			
			//execute
			eval(CurrentCall);
			
			if(_GLOBAL.queue.length > 0){
				ExecuteQueue();
			}
		}
			
	}
	
//--> End Function :: ExecuteQueue

//##########################################################################################

//--> Begin Function :: SetInnerHTMLById

	function SetInnerHTMLById(id, html){
		if(html == ""){
			html = "&#160;";	
		}
		var Elements = document.getElementsByTagName("*");
		for(var i = 0 ; i < Elements.length ; i++) {
			if(Elements[i].id == id){
				try{
					Elements[i].innerHTML = html;
				}catch(err){
					alert("error name:" + err.name + "\n message:" + err.message + "\n" + "id:"+ id + "\n html:" + html.length);	
				}
			}
		}

	}

//--> End Function :: SetInnerHTMLById
