//
// frontend.js
//
// All content copyright 2007 DomainNameSuggest. All rights reserved.
//

	
// GLOBLAS:
var g_results_div_id 	= "results_div";
var g_messages_div_id	= "messages_div";
var g_keywords_input_id	= "keywords_input";
var g_domains_to_resolve= new Array(".com",".net",".biz",".tv");
var g_activity_indicator;
var g_grab_action_url_base = "index.php?op=grab&target=godaddy";
var g_grab_action_url_domain_param_name = "domain";
var g_grab_action_url_tld_param_name = "tld";

var g_counter_suggest_attempts = 0;			// increment each time user click on the Suggest button.
var g_counter_specific_attempts = 0;	
var g_counter_random_attempts = 0;		

// ============================================================
// handle input from form
function on_click_frontend(button_name) {
	
	html_clean_and_hide_element(g_results_div_id);
	hide_message_to_user();
	
	if (button_name=="suggest") {
		g_counter_suggest_attempts++;
		
		// get user input
		var keywords=document.getElementById(g_keywords_input_id).value;
		keywords=clean_keywords_string(keywords);
		document.getElementById(g_keywords_input_id).value = keywords;	// update user's sight with clean text
		
		if (keywords.length <= 0) {
			display_message_to_user("Type something in, or hit Randomize if clueless...");
			return true;
		}
		
		// get server suggestions
		get_keywords_suggestions(g_results_div_id,keywords);
		
	} else if (button_name=="random") {
		g_counter_random_attempts++;

		// Limit number of random attempts.
		//
		if (g_counter_random_attempts > 2)
		{
			redirect_to_godaddy();
			return;
		}
		
		var keywords=document.getElementById(g_keywords_input_id).value;
		if (keywords.length > 0) 
			display_message_to_user("This option ignores your input keywords !!");
		else 
			hide_message_to_user();
		
		get_random_suggestions(g_results_div_id);		

	} else if (button_name=="specific") {
		g_counter_specific_attempts++;
		
		// get user input
		var keywords=document.getElementById(g_keywords_input_id).value;
		keywords=clean_keywords_string(keywords);
		document.getElementById(g_keywords_input_id).value = keywords;	// update user's sight with clean text
		keywords = keywords.replace(/ /g,',');	// separate words with comma

		keywords = "names:\n"+keywords;		// simulate response from suggest and let 'populate' do the rest
		populate_results_table(g_results_div_id,keywords);
	}
	
	//hide_message_to_user();		// this is commented cause it kills the "please wait message".
	
	return true;
}

// ============================================================
// 
function get_random_suggestions(results_div_id) {
	start_activity_indicator("Generating random suggestions - hold on...");
	var url = document.location+"?op=random&anticache="+String(Math.floor(Math.random()*999999999));
									//random anticache param so that IE wont remember the reply somehow in its cache !?!?!?  without this, IE <6.0.2900.2180.XPSP_SP2_GDR.070227-2254> will always return the last XHR data it has in its cache.  ;";
	var callback = {
	  success:function(o){populate_results_table(results_div_id, o.responseText); },
	  failure:function(){YAHOO.log('get_random failure','error','frontend'); kill_activity_indicator();}
	}
	YAHOO.util.Connect.asyncRequest('GET', url, callback, null); 
}


// ============================================================
// 
function get_keywords_suggestions(results_div_id, keywords) {
	start_activity_indicator("Conencting... this may take a few secs !");

	var url = document.location+"?op=suggest&keywords="+keywords+"&anticache="+String(Math.floor(Math.random()*999999999));
									//random anticache param so that IE wont remember the reply somehow in its cache !?!?!?  without this, IE <6.0.2900.2180.XPSP_SP2_GDR.070227-2254> will always return the last XHR data it has in its cache.  ;";
	var callback = {
	  success:function(o){populate_results_table(results_div_id, o.responseText); },
	  failure:function(){YAHOO.log('get_keywords_suggestions failure','error','frontend'); kill_activity_indicator();}
	}
	YAHOO.util.Connect.asyncRequest('GET', url, callback, null); 
}



// ============================================================
function populate_results_table(results_div_id, results) {
	var html_tableid = "results_table";
	
	// did we get names only, to display to user or 
	// did we get full names with whois info ?
	var results_type = "";
	if (results.indexOf("names:")==0) results_type="names";
	else if (results.indexOf("whois status:")==0) results_type="whois";
	
	// skip type line:
	results = results.substr(results.indexOf("\n")+1);
	
	// results_type means one of the options: create table with headers but no table values, or fill in the values
	if (results_type == "names") {
		results = results.split(',');
		var new_results = new Array();
		for (r=0;r<results.length;r++){
			var name = results[r].replace(/^\s*|\s*$/g,'');
			if (name.length>1) new_results[new_results.length]=name;
		}
		results = new_results;
		
		if (results.length<=0) {
			kill_activity_indicator();
			display_message_to_user('Nothing to suggest !?!?  Try different keyword(s) or take a chance with the randomizer...'); 
			kill_activity_indicator();
			return;
		}
		
		YAHOO.log('results are:>>'+results+"<<",'info','frontend');
		var labels  = new Array("name"); labels = labels.concat(g_domains_to_resolve); 
		
		mytable = create_initial_table(labels, results, "?", html_tableid, results_div_id);
		toggle_panel_visibility(results_div_id,true);
	
		var names = results;//.replace("\n",",");
		var tlds  = g_domains_to_resolve.join(",");
		resolve_whois_for_results_table (results_div_id, names, tlds);
				// this will cause this function to be called again with full results.
		kill_activity_indicator();
		start_activity_indicator("wois...");
		hide_message_to_user();

	} else {
		// got full results.  put them in table:
		var mytable = document.getElementById(html_tableid);
		var list = results.split("\n");
		for (line in list) {
			line = list[line].split(",");
			if (!line[0]) continue;
			set_table_item_by_labels(mytable, line[1],line[0],line[2]);
		}
		kill_activity_indicator();
		hide_message_to_user();
	}
	
}

// ============================================================
//
function create_initial_table (head_labels, left_colum_labels, cell_init_value, table_id, append_to_id) {
	mytable = document.createElement("table");
	mytable.setAttribute("id","results_table");
    mytablebody = document.createElement("tbody");

	// create table header row:
	var row = document.createElement("tr");
	for (var i = 0; i < head_labels.length; i++) {
		var cell = document.createElement("th");
		var cellText = document.createTextNode(head_labels[i]);
		cell.appendChild(cellText);
		row.appendChild(cell);
	}
	mytablebody.appendChild(row);
	
	// creating all cells
	for (var j = 0; j < left_colum_labels.length ; j++) {
		// creates a table row
		var row = document.createElement("tr");
		if (j%2)  row.setAttribute("class","row-odd");
		//row.setAttribute("onClick","alert('cell clicked')");
		
		for (var i = 0; i < head_labels.length; i++) {
			var cell = document.createElement("td");			
			//cell.setAttribute("style","width: 4em");
			var cellText;
			if (i==0) {
				//cell.setAttribute("style","font-weight: bold;");
				cell.setAttribute("className","left-column-label");
				cell.setAttribute("class","left-column-label");
				cellText = document.createTextNode(left_colum_labels[j]);
			} else {
				cellText = document.createTextNode(cell_init_value);
			}
			cell.appendChild(cellText);
			row.appendChild(cell);
		}

		mytablebody.appendChild(row);
	}

	mytable.appendChild(mytablebody);
	document.getElementById(append_to_id).appendChild(mytable);

	// sets the border attribute of tbl to 2;
	mytable.setAttribute("border", "1");
	
	return mytable;
}
	

// ============================================================
function resolve_whois_for_results_table(results_div_id, names, tlds) {

	var whois_resolver = new String(document.location);
	var url = whois_resolver+"?op=whois&names="+names+"&tlds="+tlds+"&anticache="+String(Math.floor(Math.random()*999999999));
								//random anticache param so that IE wont remember the reply somehow in its cache !?!?!?  without this, IE <6.0.2900.2180.XPSP_SP2_GDR.070227-2254> will always return the last XHR data it has in its cache.  ;";
	var callback = {
		success:function(o){populate_results_table(results_div_id,o.responseText);},
		failure:function(){YAHOO.log('whois failure','error','frontend');}
	}
	YAHOO.util.Connect.asyncRequest('GET', url, callback, null); 			
	return;
}


// ============================================================
// 
function set_table_item_by_labels(mytable, head_label, column_label, text) {
	
	YAHOO.log('setting table['+head_label+']['+column_label+']='+text,'info','frontend');

	var mytablebody = mytable.getElementsByTagName("tbody")[0];
	var mytablerows = mytablebody.getElementsByTagName("tr");
	var head_items  = mytablerows[0].getElementsByTagName("th");
	
	// find column to set
	for (h=1; h < head_items.length; h++) {
		if (head_items[h].childNodes[0].nodeValue == head_label) {
			break;	// h has the columns index that will be set.
		}
	}

	// find row to set
	for (var r=1; r < mytablerows.length; r++) {
		data_items = mytablerows[r].getElementsByTagName("td");
		if (data_items[0].childNodes[0].nodeValue == column_label) {
			// this is the row to touch.
			// change element in this row that has index that we found above
			if (text=="free") {
				var grab_action_href = build_url_for_grab_action(column_label, head_label);
				var action_anchor = document.createElement("a");
				action_anchor.setAttribute("href",grab_action_href);
				
				action_anchor.setAttribute("onmouseover","window.status='available!'; return true;" );
				action_anchor.setAttribute("onmouseout", "window.status=' '; return true;"); 
				action_anchor.setAttribute("target","_blank");
				
				var free_img = document.createElement("img");
				free_img.setAttribute("src","yes-text.png");
				
				action_anchor.appendChild(free_img);
				data_items[h].replaceChild(action_anchor,data_items[h].childNodes[0]);
			} else
				data_items[h].childNodes[0].nodeValue = text;
		}
	}

}

// ============================================================
// 
function clean_keywords_string (keywords) {

	keywords=keywords.replace(/\./g,' ');
	keywords=keywords.replace(/\"/g,'');
	keywords=keywords.replace(/\'/g,' ');
	keywords=keywords.replace(/\s/g,' ');
	//keywords=keywords.replace(/,\.\?\\\;\:\'\"\[\{\]\}\~\`\!\@\#\$\%\^\&\*\(\)\+\=/g,' ');
		// eliminate bad symbols
	keywords.toLowerCase();

	return keywords;
}


// ============================================================
// if onoroff unspecified then toggle, else do as said in onoroff
function toggle_panel_visibility(id,onoroff) {

	var div = document.getElementById(id);
	//alert("id:"+id+" el:"+div);
	//alert(document.getElementById("register_div"));
	
	if (typeof onoroff != "undefined") {
		div.style.display = onoroff?"":"none";
		return;
	}
	
	if (div.style.display.length>0) {
		div.style.display = "";
	} else {
		div.style.display = "none";
	}
}


// ============================================================
function html_clean_and_hide_element(element_id) {
	el = document.getElementById(element_id);
	if (!el) return;
	
	el.innerHTML = "";
	toggle_panel_visibility(element_id,false);
}

// ============================================================
function display_message_to_user(msg) {

	var messages_div = document.getElementById(g_messages_div_id);
	if (!messages_div) {alert("cant disp msg"); return;}

	if (msg.length>0) {
		messages_div.innerHTML = 	'<p><EM><b>'+
									'<FONT style="BACKGROUND-COLOR: yellow">'+
									'&nbsp;'+msg+'&nbsp;'+
									'</FONT></b></EM></p>';
	} else {
		messages_div.innerHTML = '<p></p>';
	}
	
	toggle_panel_visibility(g_messages_div_id,true);
}

// ============================================================
function hide_message_to_user() {
	//toggle_panel_visibility(g_messages_div_id,true);
	display_message_to_user('');
}


// ============================================================
function update_activity_indicator() {
	if (g_activity_indicator) {
		//display_message_to_user('hold on...');
	}
}

// ============================================================
function kill_activity_indicator(element_id) {
	if (g_activity_indicator) {
		g_activity_indicator.hide();
		//display_message_to_user('');
		//clearInterval(g_activity_indicator);
		delete g_activity_indicator;
	}
}

// ============================================================
function start_activity_indicator(msg) {	
	// Initialize the temporary Panel to display while waiting for external content to load
	g_activity_indicator = 
		new YAHOO.widget.Panel("wait",  
			{ width:"240px", 
			  fixedcenter:true, 
			  close:false, 
			  draggable:false, 
			  modal:true,
			  visible:false
			} 
		);

	g_activity_indicator.setHeader(msg);
	g_activity_indicator.setBody('<img src="rel_interstitial_loading.gif" />');
	g_activity_indicator.render(document.body);
	
	//setTimeout('display_message_to_user("Getting results for you.  Hold on...");',900);
	//g_activity_indicator = setInterval('update_activity_indicator();',1000);
	g_activity_indicator.show();
}

// ============================================================
function build_url_for_grab_action(name,tld) {
	var u = g_grab_action_url_base + "&" + g_grab_action_url_domain_param_name + "=" + name + "&" + g_grab_action_url_tld_param_name + "=" + tld;
	return u;
}

// ============================================================
function redirect_to_godaddy() {
	window.location = 'http://www.anrdoezrs.net/click-2609156-10390987?url=http%3A%2F%2Fwww.godaddy.com%2Fgdshop%2Fregistrar%2Fsearch.asp%3Fisc%3D0000000000';
}