// PRE-DEFINED VALUES FOR ENDCHEATING.COM (JAVASCRIPT)

var TEXTAREA_FILL = 'Type your phrases here. Examples of phrases you can search for: \n\nall the words in the English language are divided into nine \nlargest class of Latin words are those which came through';

var FIRST_LINE = 'Type your phrases here. Examples of phrases you can search for:';

var EXAMPLE_BGCOLOR = '#fc0'; // Change to this background color when "Show Me an Example" is clicked

var GOOGLE_MAX_WORDS = 32; // Maximum number of words allowed by Google in a query
var YAHOO_MAX_WORDS = 50;
var MINIMUM_WORDS_PER_LINE = 6; // Minimum number of acceptable words per line in query textarea on this site

// These values are echoes of what already appears in config.php.
// If the ones in config.php are changed, these must be changed MANUALLY to match.
var PREF_LANGUAGE = 0;
var PREF_LANGUAGE_EXPIRE = 1;
var PREF_CLEAR_USE = 2;
var PREF_CLEAR_CONTROL = 3;
var PREF_CLEAR_ALT = 4;
var PREF_CLEAR_SHIFT = 5;
var PREF_CLEAR_CHAR = 6;
var PREF_CLEAR_ACTION = 7;
var PREF_SUBMIT_USE = 8;
var PREF_SUBMIT_CONTROL = 9;
var PREF_SUBMIT_ALT = 10;
var PREF_SUBMIT_SHIFT = 11;
var PREF_SUBMIT_CHAR = 12;
var PREF_SUBMIT_ACTION = 13;
var PREF_EMAIL = 14;
var PREF_OPERATOR = 15;


// FUNCTIONS FOR ENDCHEATING.COM (JAVASCRIPT)


function textLimit(field, maxlen) {
  if (field.value.length > maxlen + 1)
  alert('You are trying to enter too much text!');
  if (field.value.length > maxlen)
  field.value = field.value.substring(0, maxlen);
  }


function deleteFieldValue(field, shouldFocus) {
 field.value = '';
if (shouldFocus == true)
  field.focus();
 }

 
function exampleText(inputItem) {
  inputItem.value = "use a big word or a foreign word when a small\nall the words in the English language are divided into nine\nlargest class of Latin words are those which came through";
}


function hotKeys(event, prefs) {

  // Get details of the event dependent upon browser
  event = (event) ? event : ((window.event) ? event : null);
	
	if (prefs[PREF_CLEAR_USE]) {
    checkHotKey(event, prefs[PREF_CLEAR_CONTROL], prefs[PREF_CLEAR_ALT], prefs[PREF_CLEAR_SHIFT], prefs[PREF_CLEAR_CHAR], prefs[PREF_CLEAR_ACTION]);
  }
	
	if (prefs[PREF_SUBMIT_USE]) {
	  checkHotKey(event, prefs[PREF_SUBMIT_CONTROL], prefs[PREF_SUBMIT_ALT], prefs[PREF_SUBMIT_SHIFT], prefs[PREF_SUBMIT_CHAR], prefs[PREF_SUBMIT_ACTION]);
  }
	
}


// JavaScript code for checkHotKey was MODIFIED by Hom from http://www.braemoor.co.uk/software/hotkeys.shtml
function checkHotKey(event, needControl, needAlt, needShift, needCharacter, doAction) {
	// We have found the event.
  if (event) { 
    if ((event.ctrlKey == needControl) && (event.altKey == needAlt) && (event.shiftKey == needShift)) {
		  // Pick up the Unicode value of the character of the depressed key.
      var charCode = (event.charCode) ? event.charCode : ((event.which) ? event.which : event.keyCode); 
      // Convert Unicode character to its lowercase ASCII equivalent
			var myChar = String.fromCharCode (charCode).toLowerCase(); 
      if (needCharacter == myChar) {
			  var action = new Function (doAction);
				// Perform the required action from within an anonymous function.
        action (); 
		    }
      }
    }
  }


// Script was MODIFIED from original at http://www.netmechanic.com/news/vol4/javascript_no1.htm
function addToFavorites(urlAddress, pageName) {
  if (window.external) {
    window.external.AddFavorite(urlAddress,pageName)
  } else { 
    alert("Sorry! Your browser doesn't support this function.");
  }
}


// Modified from John Russell's Web function - this one counts words in a string, not a textarea field
// I have permission to use and modify the word-counting function from John Russell's Web site.
// JavaScript Tutorial 12 - Smart Forms. 23 Jan 2006 <http://home.cogeco.ca/~ve3ll/jstutorc.htm>.
// He has informed me through e-mail that no license is required to use or modify the function.
function countWords(givenStr, show_word_count, show_char_count) {
  if (show_word_count===undefined) {show_word_count=false;} //show is default
  if (show_char_count===undefined) {show_char_count=false;} //noshow is deft
  char_count=givenStr.length;          // very crude measure
  fullStr=givenStr+" ";   // add space delimiter to end of text
  initial_whitespace_rExp= /^[^A-Za-z0-9]+/gi; //use for complex whitespace
  left_trimmedStr=fullStr.replace(initial_whitespace_rExp, " ");
  non_alphanumerics_rExp=/[^A-Za-z0-9]+/gi;    // and for delimiters
  cleanedStr=left_trimmedStr.replace(non_alphanumerics_rExp, " ");
  splitString=cleanedStr.split(" ");word_count=splitString.length -1;
  if (fullStr.length <2) {word_count=0;}
  if (word_count==1){wordOrWords=" word";}else{wordOrWords=" words";}
  if (char_count==1){charOrChars=" character";}else{charOrChars=" characters";}
  if (show_word_count && show_char_count) {
     msg="Word Count:\n"+" "+word_count+wordOrWords+"\n";
     msg += " "+char_count+charOrChars;window.alert(msg);
     } else {
     if (show_word_count) {alert("Word Count:  "+word_count+wordOrWords);}
     else {
        if (show_char_count) {
           window.alert("Character Count:  "+char_count+charOrChars);}
        }
     }
  return word_count;
}


// I have permission to use this word-counting function from John Russell's Web site.
// JavaScript Tutorial 12 - Smart Forms. 23 Jan 2006 <http://home.cogeco.ca/~ve3ll/jstutorc.htm>.
// He has informed me through e-mail that no license is required to use or modify the function.
function countFieldWords(this_field, show_word_count, show_char_count) {
  if (show_word_count===undefined) {show_word_count=false;} //show is default
  if (show_char_count===undefined) {show_char_count=false;} //noshow is deft
  el=document.getElementById(this_field);
  char_count=el.value.length;          // very crude measure
  fullStr=el.value+" ";   // add space delimiter to end of text
  initial_whitespace_rExp= /^[^A-Za-z0-9]+/gi; //use for complex whitespace
  left_trimmedStr=fullStr.replace(initial_whitespace_rExp, " ");
  non_alphanumerics_rExp=/[^A-Za-z0-9]+/gi;    // and for delimiters
  cleanedStr=left_trimmedStr.replace(non_alphanumerics_rExp, " ");
  splitString=cleanedStr.split(" ");word_count=splitString.length -1;
  if (fullStr.length <2) {word_count=0;}
  if (word_count==1){wordOrWords=" word";}else{wordOrWords=" words";}
  if (char_count==1){charOrChars=" character";}else{charOrChars=" characters";}
  if (show_word_count && show_char_count) {
     msg="Word Count:\n"+" "+word_count+wordOrWords+"\n";
     msg += " "+char_count+charOrChars;window.alert(msg);
     } else {
     if (show_word_count) {alert("Word Count:  "+word_count+wordOrWords);}
     else {
        if (show_char_count) {
           window.alert("Character Count:  "+char_count+charOrChars);}
        }
     }
  return word_count;
}


// Validates query string client-side when Submit button is clicked
function validateQuery(field, form, engineField) {

  engineElement = document.getElementById(engineField);
  engineStr = engineElement.value;
	
  if (engineStr == 'yahoo') {
	  engineName = 'Yahoo';
		maxWords = YAHOO_MAX_WORDS;
	} else {
	  engineName = 'Google';
		maxWords = GOOGLE_MAX_WORDS;
	}

  element=document.getElementById(field);
  queryStr=element.value;
	
  var editedQuery = ''; // String that represents what will be passed on to SE through redirect
	var editedQueryWords = 0; // Number of words in the edited query
	var numberValidLines = 0; // Number of lines that should be included in the final search query
	var numberShortLines = 0; // Number of lines that are too short - for error tracking
	var numberEliminatedLines = 0; // Number of lines eliminated because search query was too long
	var numberTruncatedLines = 0; // Number of lines truncated (shortened) because search query was too long
  
  var lineArray = queryStr.split('\n');
	
  var counter = 0;
	var thisLineWords = 0; // Number of words in the line currently being studied
  while (counter < lineArray.length)
   {
		thisLineWords = countWords(lineArray[counter]);
		
		if (thisLineWords < MINIMUM_WORDS_PER_LINE) {
		  if (lineArray[counter].length > 1) {  // Make sure that blank lines (containing just \n) don't get counted
		    numberShortLines += 1;
			}
		} else {
		  if ((editedQueryWords + thisLineWords) <= maxWords) {
  		  editedQuery += lineArray[counter];
  			editedQueryWords += thisLineWords;
				numberValidLines += 1;
			} else if ((maxWords - editedQueryWords) >= MINIMUM_WORDS_PER_LINE ) {
				editedQueryWords = maxWords;
			  numberValidLines += 1;
			  numberTruncatedLines += 1;
			} else {
			  numberEliminatedLines += 1;
			}
		}

    counter+=1;
    } 
	
	if (numberValidLines == 0) {
	  alert('Please enter at least ' + MINIMUM_WORDS_PER_LINE + ' words per line. \n\nDue to a word limit set by ' + engineName + ', do not use more than ' + maxWords + ' words altogether.');
	} else {
	
	  var alertStr = '';
		
  	if (numberShortLines > 0) {
  	  alertStr += numberShortLines + ' line'
			if (numberShortLines == 1) { alertStr += ' was'; } else { alertStr += 's were'; }
			alertStr += ' too short (less than ' + MINIMUM_WORDS_PER_LINE + ' words) and will not be included in your search.\n\n';
  	}
  	
		if (numberTruncatedLines > 0) {
			alertStr += 'One line will be shortened to make your total search ' + maxWords + ' words long, which is ' + engineName + '\'s word limit.\n\n';
  	}
		
  	if (numberEliminatedLines > 0) {
  	  alertStr += numberEliminatedLines
			if (numberShortLines > 0) { alertStr += ' more'; }
			alertStr += ' line'
			if (numberEliminatedLines > 1) { alertStr += 's'; }
			alertStr += ' will not be included in your search because you typed more than ' + maxWords + ' words, which is higher than ' + engineName + '\'s word limit.\n\n';
  	}
  	
  	if (alertStr != '') {
  	  alertStr += 'Do you want to go ahead and do the search anyway?';
  	  if (confirm(alertStr)) { 
        form.submit();
      }
  	} else {
  	  form.submit();
  	}
		
	}

}