// for AJAX, so it only sends requests every 200ms, to minimize server load.
var typeclock;

// quick function to replace document.getelementbyid, to make code cleaner
function $(id)
{
	return document.getElementById(id);
}

// function called when key is pressed in a text field; calls function only every given amount of time
// to stop superfluous AJAX requests  
function doTypeClock(perffunc)
{
	var d = new Date();
	
	// call the perform function at a set delay, in case this is the last character typed, but the
	// previous character was typed a very short time ago and the clock hasn't reset yet
	setTimeout("runTypeFunction('" + perffunc + "')", typetimer_timeout1);
	
	// if the previous key was a set time ago, then enough time has passed to call the perform
	// function such that this request will not be excessive and unneeded
	if (typeclock + typetimer_timeout2 < d.valueOf())
	{
		runTypeFunction(perffunc);
	}

	// reset the clock
	typeclock = d.valueOf();
}

// called by typetimer,  performs the function if enough time has elapsed since the timer was reset
function runTypeFunction(perffunc)
{
	(perffunc == 'title') ? doCountTitle() : (perffunc == 'desc') ? doCountDesc() : doCountKeyword();
}

// reset all the fields on the form to their default value
function doReset(perffunc)
{
	var keyword_id = '';
	
	for (i = 0; i < 3; i++) 
	{
		for (j = 0; j < title_desc_keywords_times[i]; j++)
		{
			// I think this mess shows that the naming conventions for the HTML elements
			// is a tad ineffective for clean client and server code.
			keyword_id = j+1 + '';
			keyword_id = title_desc_keywords_names[i] + '_keyword_' + keyword_id;
			$(keyword_id).value = (i == 0) ? default_keywords[j] : (i==2 && j==0) ? 'Main keyword' : default_keywords[j].toLowerCase();
			$(keyword_id).className = 'presetvalue';
		}
	}
			
	$('desc_company').value = 'Company Name';
	$('desc_company').className = 'presetvalue';
	$('keywords_keyword_last').value = 'last keywords';
	$('keywords_keyword_last').className = 'presetvalue';
	
	$('title_symbol_1')[0].selected = '1';
	$('title_symbol_2')[0].selected = '1';
	$('title_symbol_3')[0].selected = '1';
	$('desc_symbol_1')[0].selected = '1';
	
	$('desc_connect')[0].selected = '1';
	$('desc_call_to_action_1')[0].selected = '1';
	$('desc_call_to_action_2')[0].selected = '1';
	
	$('desc_connect')[7].innerHTML = 'custom';
	
	$('desc_call_to_action_1')[18].innerHTML = 'Custom';
	$('desc_call_to_action_2')[18].innerHTML = 'custom';
	
	$('titlecount').innerHTML = '<span class="good"><strong>' + max_title_words + '</strong></span> words left, <span class="good"><strong>' + max_title_chars + '</strong></span> characters left. ';
	$('desccount').innerHTML = '<span class="good"><strong>' + max_description_words + '</strong></span> words left, <span class="good"><strong>' + max_description_chars + '</strong></span> characters left. ';
	$('keywordcount').innerHTML= '<span class="good"><strong>' + max_keywords_words + '</strong></span> words left, <span class="good"><strong>' + max_keywords_chars + '</strong></span> characters left. ';
}

// uppercase function for regex
function ucase(txt)
{
	return txt.toUpperCase();
}

// fill in set text-fields on the form with the given string
function fillinFields(text, field1, field2, field3, field1cap, field2cap, field3cap)
{
	// only do anything if "auto-fillin-fields" checkbox is checked
	if ($('fillin').checked == true)
	{
		var fields = [field1, field2, field3];
		var caps = [field1cap, field2cap, field3cap];
		
		for (i = 0; i < 3; i++)
		{
			if(fields[i] != 'null')
			{
				$(fields[i]).className = '';
				if ((caps[i] == 0) || ($('capit').checked == false))
				{
					$(fields[i]).value = text;
				}			
				else if (caps[i] == -1)
				{
					$(fields[i]).value = text.toLowerCase();
				}
				else if (caps[i] == -2)
				{
					$(fields[i]).value = (text.substr(0, 1)).toUpperCase() + (text.substr(1)).toLowerCase();
				}
				else if (caps[i] == 1)
				{
					$(fields[i]).value = (text.substr(0, 1)).toUpperCase() + text.substr(1);
				}
				else if (caps[i] == 2)
				{
					$(fields[i]).value = (text.replace(/\b[a-z]/g, ucase));
				}
			}
		}
	}
}	
	
// clear the value of the given HTML element 
function clearOnClick(defaultStr, id)
{
	if ($(id).value == defaultStr)
	{
		$(id).value = '';
		$(id).className = '';
	}
}

// calculate the description string from the current value of the form on the HTML page
function getDescriptionStr()
{
	var keywords = [$('desc_keyword_1').value, $('desc_keyword_2').value, $('desc_keyword_3').value, $('desc_keyword_4').value, $('desc_keyword_5').value];	
	var keyword_str = [''];
	var implode_break = '';
	
	for (i = 0; i <= keywords.length-1; i++) 
	{
		if (keywords[i] != default_keywords[i].toLowerCase() && keywords[i] != '')
		{
			keyword_str[1] = keywords[i];
			(i == keywords.length-1) ? implode_break =  ' ' + $('desc_symbol_1').value + ' ' : implode_break = ', ';
			keyword_str[0] = keyword_str.join(implode_break);
		}	
	}
	
	keyword_str = $('desc_company').value + ' ' + $('desc_connect').value + ' ' + keyword_str[0] + '. ';
	keyword_str += $('desc_call_to_action_1').value + ', ' + $('desc_call_to_action_2').value + '.';
	
	return keyword_str;
}

// calculate the title string from the current value of the form on the HTML page
function getTitleStr()
{
	var keywords = [$('title_keyword_1').value, $('title_keyword_2').value, $('title_keyword_3').value, $('title_keyword_4').value];	
	var keyword_str = [''];
	var implode_break = '';
	var symbol_key = '';
	
	for (i = 0; i <= keywords.length-1; i++) 
	{
		if (keywords[i] != default_keywords[i] && keywords[i] != '')
		{
			keyword_str[1] = keywords[i];
			symbol_key = 'title_symbol_' + i;
			($(symbol_key)) ? implode_break = '' + $(symbol_key).value : implode_break = '';
			keyword_str[0] = keyword_str.join(implode_break);
		}	
	}
	
	keyword_str = keyword_str[0] + '.';
	
	return keyword_str;
}

// calculate the keyword string from the current value of the form on the HTML page
function getKeywordStr()
{
	var keywords = [$('keywords_keyword_1').value, $('keywords_keyword_2').value, $('keywords_keyword_3').value, $('keywords_keyword_4').value, $('keywords_keyword_5').value, $('keywords_keyword_6').value, $('keywords_keyword_7').value, $('keywords_keyword_8').value, $('keywords_keyword_9').value, $('keywords_keyword_10').value, $('keywords_keyword_last').value];
	var keyword_str = [''];
	var implode_break = '';
	
	for (i = 0; i <= keywords.length-1; i++) 
	{
		if (keywords[i] != default_keywords[i].toLowerCase() && keywords[i] != '')
		{
			keyword_str[i] = keywords[i];
		}	
	}
	
	keyword_str = keyword_str.join(', ') + '.';
	
	return keyword_str;
}

// display a dialog box asking the user to enter a custom connector
function setConnectCustom()
{
	cust = prompt('Enter your custom Connector');
	var obj = $('desc_connect');
	obj.options[7].text = cust;
}

// display a dialog box asking the user to enter a custom call to action
function setActionCustom1()
{
	cust = prompt('Enter your custom Call to Action');
	var obj = $('desc_call_to_action_1');
	obj.options[obj.selectedIndex].text = cust;
}

// display a dialog box asking the user to enter a custom call to action
function setActionCustom2()
{
	cust = prompt('Enter your custom Call to Action');
	var obj = $('desc_call_to_action_2');
	obj.options[obj.selectedIndex].text = cust;
}

// begin AJAX functions

// attempt to create an xmlHttp object
function createAjaxRequest()
{
	var obj = null;
 			
	var msxmlhttp = new Array(
		'Msxml2.XMLHTTP.5.0',
		'Msxml2.XMLHTTP.4.0',
		'Msxml2.XMLHTTP.3.0',
		'Msxml2.XMLHTTP',
		'Microsoft.XMLHTTP'
	);

	for (var i = 0; i < msxmlhttp.length; i++)
	{
		try
		{
			obj = new ActiveXObject(msxmlhttp[i]);
		}
		catch (e)
		{
			obj = null;
		}
	}
 			
	if ((!obj) && (typeof XMLHttpRequest != 'undefined'))
	{
		obj = new XMLHttpRequest();
	}

	if (!obj)
	{
		alert ('Error: AJAX is not supported by your Internet browser.');
	}

	return obj;
}

// initiate ajax with compatibility for browsers...
function initAjax(func_field)
{
	var d = new Date();
	typeclock = (d.valueOf());
	var xmlHttp;

	xmlHttp = createAjaxRequest();
	
	if (!xmlHttp)
	return false;
	
	xmlHttp.onreadystatechange = function()
	{
		if(xmlHttp.readyState == 4)
		(func_field == 'desc') ? countDesc(xmlHttp) : (func_field == 'title') ? countTitle(xmlHttp) : countKeyword(xmlHttp);
	}		
	
	return xmlHttp;
}

// call to calculate the title word/character count using AJAX
function doCountTitle()
{
	var title_cnt = $('titlecount');
	var title_str = getTitleStr();
	
	title_cnt.innerHTML = '- words left, ' + countString(title_str, 0, max_title_chars, 0, 1);
	
	xmlHttp = initAjax('title');
	xmlHttp.open('GET', 'stop_words.txt', true);
	xmlHttp.send(null);
}

// call to calculate the description word/character count using AJAX
function doCountDesc()
{
	var desc_cnt = $('desccount');
	var desc_str = getDescriptionStr();
	
	desc_cnt.innerHTML = '- words left, ' + countString(desc_str, 0, max_description_chars, 0, 1);
	
	xmlHttp = initAjax('desc');
	xmlHttp.open('GET', 'stop_words.txt', true);
	xmlHttp.send(null);
}

// call to calculate the keyword word/character count using AJAX
function doCountKeyword()
{
	var keyword_cnt = $('keywordcount');
	var keyword_str = getKeywordStr();
	
	keyword_cnt.innerHTML = '- words left, ' + countString(keyword_str, 0, max_keywords_chars, 0, 1);
	
	xmlHttp = initAjax('keyword');
	xmlHttp.open('GET', 'stop_words.txt', true);
	xmlHttp.send(null);
}

// Holy speed boost, Batman! Sure is a lot better than using PHP..
function countWords(str, xmlHttp, remove_stopwords)
{
	// Declare and assign the variables
	var words = xmlHttp.responseText.split(/\s/);
	var regex = '';
	
	// Replace punctuation with nothingness...
	str = str.replace(/[^\w\s]/g,"");
	
	if (remove_stopwords == 1)
	{
		// Make the stop words list an array, remove all stop words
		for(i=0 ; i<words.length; i++)
		{
			regex = '\\b' + words[i].replace(/^\s+|\s+$/g,"") + '\\b';
			regex = new RegExp(regex,"ig");
			str = str.replace(regex, "");
		}
	}
	
	// Determine the number of words without stop words
	return str.split(/\b[a-zA-Z]*\b/).length;
}

// count words and characters
// Okay, I admit that the abstraction here is way, way overboard, but I really
// wanted to see how much I could shrink the function... I could condense this to about
// 10 lines, but I think this is good enough.
function countString(string, words, max_chars, max_words, start_iteration_num)
{
	var class_type, remainder, output = '';
	var typeArray = ['word', 'character'], countArray = [max_words - words + 1, max_chars - string.length + 1 /* +1 to make up for the period */ ];
	
	for (i = start_iteration_num; i < typeArray.length; i++)
	{	
		(countArray[i] == Math.abs(countArray[i])) ? class_type = 'good' : class_type = 'warning';
		(countArray[i] == Math.abs(countArray[i])) ? remainder = 'left' : remainder = 'over';
		
		if (Math.abs(countArray[i]) > 1 || Math.abs(countArray[i]) == 0)
		{
			output += '<span class="' + class_type + '"><strong>' + Math.abs(countArray[i]) + '</strong></span> ' + typeArray[i] + 's ' + remainder;
		}
		else if (Math.abs(countArray[i]) == 1)
		{
			output += '<span class="' + class_type + '"><strong>' + Math.abs(countArray[i]) + '</strong></span> ' + typeArray[i] + ' ' + remainder;
		}
		else
		{
			output = '<span class="warning">JavaScript Error</span>';
		}
		
		(i == 0) ? output += ', ' : output += '.';
	}
	
	return output;
}

// count the title words/characters
function countTitle(xmlHttp)
{
	var title_cnt = $('titlecount');
	var title_str = getTitleStr();
	var title_words = countWords(title_str, xmlHttp, 1);
	
	title_cnt.innerHTML = countString(title_str, title_words, max_title_chars, max_title_words, 0);
}

// count the description words/characters
function countDesc(xmlHttp)
{
	var desc_cnt = $('desccount');
	var desc_str = getDescriptionStr();
	var desc_words = countWords(desc_str, xmlHttp, 0);
	
	desc_cnt.innerHTML = countString(desc_str, desc_words, max_description_chars, max_description_words, 0);
	//desc_cnt.innerHTML = desc_str;
}

// count the keywords words/characters
function countKeyword(xmlHttp)
{
	var keyword_cnt = $('keywordcount');
	var keyword_str = getKeywordStr();
	var keyword_words = countWords(keyword_str, xmlHttp, 1);
	
	keyword_cnt.innerHTML = countString(keyword_str, keyword_words, max_keywords_chars, max_keywords_words, 0);
}

// display the animated loading bar
function showLoadbar()
{
	$('loadbar').style.display = '';
}

// Bit of a hack to fix the bug of greyed out fields with non-default values when the page is refreshed after data is entered

function fixGrayFields()
{
	var keyword_id = '';
	
	for (i = 0; i < 3; i++) 
	{
		for (j = 0; j < title_desc_keywords_times[i]; j++)
		{
			keyword_id = j+1 + '';
			keyword_id = title_desc_keywords_names[i] + '_keyword_' + keyword_id;
			$(keyword_id).className = ($(keyword_id).value != (j == 0) ? default_keywords[j] : default_keywords[j].toLowerCase()) ? '' : 'presetvalue';
		}
	}
	
	$('desc_company').className = ($('desc_company').value != 'Company Name') ? '' : 'presetvalue';
	$('keywords_keyword_last').className = ($('keywords_keyword_last').value != 'last keywords') ? '' : 'presetvalue';
}
