var xmlHttp;
var dynamic_object;
var default_message = "";
var dynamic_processing = false;
var google_data = "";
var pending_url = "";
var wait_timer;
var item_handle;
var dynamic_mode = false;
var current_x = 0;
var current_y = 0;

var post_completed = false;
var post_response = "";

//post a form to a url using ajax
function post_ajax(url, form, asynch){

	//reset completed flag
	post_completed = false;
	
	//create blank response object
	var http_request = null;

	try{
		
		http_request = GetXmlHttpObject();
	
		if (http_request == null) {
			alert ("Browser does not support HTTP Request");
			return;
		} 
		
		var post_data = prepare_post_query(form);

		http_request.open('POST', url, asynch);
		
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", post_data.length);
		http_request.setRequestHeader("Connection", "close");
		
		/* The callback function */
		http_request.onreadystatechange = function() {

			if (http_request.readyState == 4) {
				
				if (http_request.status == 200){
	
					post_response = http_request.responseText;
					post_completed = true;
					
				}

				post_completed = true;
				
			}
			
				
		}
		
		http_request.send(post_data);
		
	}catch(ex){
		alert(ex.description);
	}
	
	return http_request;

}

//prepares post query for ajax style posting to remote server
function prepare_post_query(form){
	
	var data = "";

	for (var i=0; i < document.getElementById(form).elements.length; i++) {
		
		var element = document.getElementById(form).elements[i];
		
		if(element.type == 'checkbox'){
			if(element.checked) data += element.name + "=" + encodeURI(element.value) + (i+1 < document.getElementById(form).elements.length ? '&' : '');
		}else{
			data += element.name + "=" + encodeURI(element.value) + (i+1 < document.getElementById(form).elements.length ? '&' : '');
		}
		
	}
	
	return data;
	
}

function get_dynamic(url, _dynamic_object){

	dynamic_object = _dynamic_object;

	xmlHttp=GetXmlHttpObject();
	
	if (xmlHttp==null) {
//  		alert ("Browser does not support HTTP Request")
  		return
  	} 
	
	xmlHttp.onreadystatechange=stateChanged ;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	dynamic_processing = true;
} 

function stateChanged(){ 


	try{
		if(dynamic_object != null){
			if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
				document.getElementById(dynamic_object).innerHTML = xmlHttp.responseText;
			}else{
				document.getElementById(dynamic_object).innerHTML = "";
			}
		}
	}catch(e){
	}
	
	dynamic_processing = false;

}

function GetXmlHttpObject(){

	var xmlHttp=null;
	
	try{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}catch (e){
		// Internet Explorer
		try{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	  	}catch (e){
	  		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	
	return xmlHttp;
}

function check_live_progress(api_session){
	
	xmlhttp=GetXmlHttpObject();
	
	if (xmlhttp==null) {
  		alert ("Browser does not support HTTP Request")
  		return
  	} 

    xmlhttp.open('GET', 'queue.php?a=progress_live&api_session=' + api_session, true);
    
    /* The callback function */
    xmlhttp.onreadystatechange = function() {
		
        if (xmlhttp.readyState == 4) {
			
            if (xmlhttp.status == 200){

				var data = xmlhttp.responseText;
				
				var stage_description = gbs(data, '<stage_description>', '</stage_description>');
				var stage_progress = gbs(data, '<stage_progress>', '</stage_progress>') + "%";
				var overall_progress = gbs(data, '<overall_progress>', '</overall_progress>') + "%";
				var download_link = gbs(data, '<download_link>', '</download_link>');
				var download_link_url = gbs(data, '<download_link_url>', '</download_link_url>');
				
				//only populate fields which exist on the form, and are different from the current stats
				
				if(document.getElementById('stage_description') != null && document.getElementById('stage_description').innerHTML != stage_description){
					document.getElementById('stage_description').innerHTML  = stage_description;
				}

				if(document.getElementById('stage_progress') != null && document.getElementById('stage_progress').innerHTML != stage_progress){
					document.getElementById('stage_progress').innerHTML  = stage_progress;
				}

				if(document.getElementById('overall_progress') != null && document.getElementById('overall_progress').innerHTML != overall_progress){
					document.getElementById('overall_progress').innerHTML  = overall_progress;
				}

				if(document.getElementById('download_link') != null && document.getElementById('download_link').innerHTML != download_link){
					document.getElementById('download_link').innerHTML  = download_link;
				}

				if(document.getElementById('download_link_url') != null && document.getElementById('download_link_url').innerHTML != download_link_url){
					document.getElementById('download_link_url').innerHTML  = download_link_url;
				}
				
				if(timer_id != null && overall_progress == '100%'){
					
					//clear the interval if we reached 100%
					clearInterval(timer_id);
					
					if(document.getElementById('tr_buttons') != null) hideObject('tr_buttons');
					
				}

			}

        }
		
    }

    xmlhttp.send(null);
	
}

function check_report_progress(){
	
	if(document.getElementById('button_queue') != null){
		
		xmlhttp=GetXmlHttpObject();
		
		if (xmlhttp==null) {
			alert ("Browser does not support HTTP Request")
			return
		} 
		
		xmlhttp.open('GET', 'dynamic.php?a=check_report_progress', true);
		
		/* The callback function */
		xmlhttp.onreadystatechange = function() {
			
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200)
					if(xmlhttp.responseText == '1'){
						document.getElementById('divider_queue').style.visibility="visible";
						document.getElementById('button_queue').style.visibility="visible";
					}else{
						document.getElementById('button_queue').style.visibility="hidden";
						document.getElementById('divider_queue').style.visibility="hidden";						
					}
	
			}
			
		}
	
		xmlhttp.send(null);
		
	}

}

function pp(e){
	
	if(window.event){
		
		item_handle = window.event;
		current_x = event.clientX + document.body.scrollLeft;
		current_y = event.clientY + document.body.scrollTop;		
		
	}else{
		item_handle = e;
	}
	
}

function validate_wait(url){
	
	dynamic_mode = true;
	
	//set temporary 
	document.onmousemove = pp;
	
	//clear previous timeouts
	if(wait_timer != null) clearTimeout(wait_timer);
		
	//set this timeout
	wait_timer = setTimeout('generate_dynamic_tip("' + url + '")', 750);
		
}

function clear_timer(){
	if(wait_timer != null) clearTimeout(wait_timer);
}

function generate_dynamic_tip(url){
	
	//clear timeout and proceed
	clearTimeout(wait_timer);
		
	if(dynamic_processing == false){

		var xml_object = GetXmlHttpObject();
		
		if (xml_object==null) {
			alert ("Browser does not support HTTP Request")
			return
		} 
		
		dynamic_processing = true;

		Tip('<div id="dynamic_tip_div" name="dynamic_tip_div"><table width="320" class="standard_table"><tr><td height="20"><center><b>Loading...<br></b></center></td></tr><tr><td><center><img src="img/loading.gif"></center></td></tr></table></div>', BALLOON, false, LEFT, false);

		//clear dynamic_processing flag after 4 seconds
		setTimeout("clear_dynamic_processing()",4000);
		
		xml_object.open('GET', url, true);
		
		/* The callback function */
		xml_object.onreadystatechange = function() {
			
			if (xml_object.readyState == 4) {
				if (xml_object.status == 200){
					dynamic_processing = false;
					if(document.getElementById('dynamic_tip_div') != null) document.getElementById('dynamic_tip_div').innerHTML = xml_object.responseText;
				}else{
					dynamic_processing = false;
				}
	
			}
						
		}
	
		xml_object.send(null);
		
	}else{

		//dynamic is still processing from another instance, so let's wait a second and try again
		Tip('<div>another check is still processing. please try again in 5 seconds.</div>', BALLOON, false, LEFT, false);
		
	}
	
}

function clear_dynamic_processing(){
	dynamic_processing = false;
	dynamic_mode = false;
}

function get_serp(keyword, type){

	validate_wait('dynamic.php?a=serp&data=' + keyword + '&type=' + type);
	
}


function get_reverse_ip(ip){

	validate_wait('dynamic.php?a=reverse_ip&data=' + ip);
	
}

function get_alexa(domain){

	validate_wait('dynamic.php?a=alexa&data=' + domain);
	
}

function get_whois(domain){

	validate_wait('dynamic.php?a=whois&data=' + domain);
	
}

function get_site(domain, result_div){
	
	xmlhttp=GetXmlHttpObject();
	
	document.getElementById(result_div).innerHTML = "<p align='center'>Crawling " + domain + ". Please wait...<br><br><img src='img/loader.gif'></p>";

	if (xmlhttp==null) {
  		alert ("Browser does not support HTTP Request")
  		return
  	} 

    xmlhttp.open('GET', 'dynamic.php?a=site&data=' + domain, true);
    
    /* The callback function */
    xmlhttp.onreadystatechange = function() {
		
        if (xmlhttp.readyState == 4) {
			
            if (xmlhttp.status == 200){

				var data = xmlhttp.responseText;
				
 				document.getElementById(result_div).innerHTML  = data;				

			}

        }
		
    }

    xmlhttp.send(null);
	
}

//queries a URL via ajax synched call
function query_url(url){
	
	xmlhttp=GetXmlHttpObject();
	
	if (xmlhttp==null) {
  		alert ("Browser does not support HTTP Request")
  		return
  	} 

    xmlhttp.open('GET', url, false);
    
    /* The callback function */
    xmlhttp.onreadystatechange = function() {
		
        if (xmlhttp.readyState == 4) {
			
            if (xmlhttp.status == 200){
				//we don't care
			}

        }
		
    }

    xmlhttp.send(null);
	
}

//downloads the news feed
function get_news_feed(start){
	
	if(start == null) start = 1;
	
	document.getElementById('news_feed').innerHTML = '<p><img src="img/spinner_grey.gif"></p>';
	
	populate_dynamic_data('dynamic.php?a=news_feed&start=' + start, true)
	
}

//processes ajax call and populates objects with returned values
function populate_dynamic_data(url, async){

	if(async == null || async == '') async = true;

	var local_http = GetXmlHttpObject();
	
	if (xmlhttp==null) {
  		alert ("Browser does not support HTTP Request")
  		return
  	} 

    local_http.open('GET', url, async);

    /* The callback function */
    local_http.onreadystatechange = function() {

        if (local_http.readyState == 4) {
			
            if (local_http.status == 200){

				var data = local_http.responseText;
				
				process_dynamic_data(data);
				
			}

        }
		
    }

    local_http.send(null);
	
	if(async == false){
		process_dynamic_data(local_http.responseText);
	}

}

//populates web objects with data received from the ajax query
function process_dynamic_data(data){
	
	var arr = data.split("<result>");
	var i = 0;

	for(i=0; i<arr.length; i++){

		var item_id  = gbs(arr[i], '<item_id>', '</item_id>');				
		var item_value  = gbs(arr[i], '<item_value>', '</item_value>');
		var container_name = gbs(arr[i], '<item_container>', '</item_container>');
		
		if(item_value.length > 0){

			if(document.getElementById(container_name).type == 'select-one'){
			
				var opt = new Option();
				
				opt.text = item_value;
				opt.value= item_id;
				
				document.getElementById(container_name).options.add(opt);
				
			}else if(document.getElementById(container_name).type == 'text' || document.getElementById(container_name).type == 'textarea'){
				
				document.getElementById(container_name).value = item_value;
				
			}else if(document.getElementById(container_name).type == null){

				if(document.getElementById(container_name).innerHTML != item_value) document.getElementById(container_name).innerHTML = item_value;
				
			}
			
		}
		
	}
	
}

//cleans data containers prior to populating them with dynamic data
function clean_data_container(data_container){

	if(document.getElementById(data_container).type == 'select-one'){
	
		for (var i=document.getElementById(data_container).options.length-1; i>=0; i--){
			document.getElementById(data_container).options[i] = null;
		}
		
		document.getElementById(data_container).options.selectedIndex = -1;

	}else if(document.getElementById(data_container).type == 'text' || document.getElementById(data_container).type == 'textarea'){
		
		document.getElementById(data_container).value = '';
	}
	
}




