var first_word;
var littleWords = new Array("in", "the", "of", "from", "an", "and", "with", "or", "by", "on", "at");
var allCaps = new Array("gjhgjcksj898jkjhfmnnbv09926u");

function uCase(textarea) {
	textarea.value=textarea.value.toUpperCase()
}

function lCase(textarea) {
	textarea.value=textarea.value.toLowerCase()
}

function changeCase(textarea) {		
	
	first_word = true;
	var s = replaceSubstring(textarea.value,"-","- ");
	var s = replaceSubstring(s,",",", ");
	
	var str = s.toLowerCase();
	var str_temp = new Array();
	str_temp = str.split(" ");
	
	for (var i = 0; i < str_temp.length; ++i) {
		var pattern = /(^[\'\"]?)(\w)([\w]*)([\.\',:;]?)(.*)/;
		var word = str_temp[i];
		var result = pattern.exec(word);
		if (result != null) {
			str_temp[i] = toTitleCase(result, littleWords, allCaps);
		}
		first_word = getFirstWord(str_temp[i]);
	}

	var currLength = 0;
	for (var i = 0; i < str_temp.length; i++) {
		currLength += str_temp[i].length;
	}
	currLength += str_temp.length - 1;
	
	s = str_temp.join(" ");
	
	//louis hack to make stuff like this '113 the' become '113 The'
	s = louis_hack(s);
	
	//paul's hack to capitalise first letter of string in brackets
	s = paul_hack(s);
	
	textarea.value = replaceSubstring(s,"- ","-");
}

//capitalises the first letter of a string when its in brackets and returns '(string)'
function paul_hack(str) {

	var patt1=/\(\s*[a-z].*\s*\)/gi;
	var word = "" + str.match(patt1);  //u have text

	word = word.slice(1, word.indexOf(")"));  //removes brackets

	word = word.toLowerCase();  //converts to lowercase

	wordInStrArr = word.split("");  //converts to string array

	startChar = wordInStrArr[0].toUpperCase();  //first letter to uppercase

	word = startChar + word.substr(1);

	return str.replace(/\(\s*[a-z].*\s*\)/gi, "(" + word + ")" );
}



function louis_hack(s)
{
  wholestr = trim(s);
	
  var pattern = /^\d+ the/;   // match a number from at start of str followed by space then 'the'
  var word = wholestr;
  var matchedPart = pattern.exec(word);
  
  if(matchedPart==null)
  	return s; // no match no need to do anymore

  matchedPart = ""+matchedPart; // hack as it think r is not a str weird ! 

  matchedPart = matchedPart.replace(/t/g, "T"); //upper the T of the 
  
  wholestr = wholestr.replace(pattern , matchedPart);

  return wholestr;    
}

function getFirstWord(word) {
	var ret = ( word.charAt(word.length-1) == ":");
	return ret;
}

function isInGroup(word, groupOfWords) {
//	word = word.replace(/:/, "");
	for (var i = 0; i < groupOfWords.length; ++i) {
		if (groupOfWords[i] == word)
			return true;
	}
	return false;
}

function getCase(word, littleWords, allCaps) {
	if (isInGroup(word, littleWords)) {
		return 1;	//return 1 if it is a little word;
	}
	if (isInGroup(word, allCaps)) {
		return 2;	//return 2 if this is an allcaps word;
	}
	return 3;		//return 3 for all other words;
}

function toTitleCase(result, littleWords, allCaps) {
	var word_temp, word_result;
//	result[0] contains the entire match
//	result[1] contains the (leading) ["'] (if any)
//	result[2] contains the first letter
//	result[3] contains the rest of the letters
//	result[4] contains the trailing punctuation (if any)
//	result[5] conains the trailing stuff and junk (if any)

	word_temp = result[2] + result[3];
	var word_case = getCase(word_temp, littleWords, allCaps);

	switch (word_case) {
		case 1:
			if (first_word) {
				first_word = false;
				word_result = result[2].toUpperCase() + result[3];
			} else {
				word_result = word_temp;
			}
			break;
		case 2:
			word_result = word_temp.toUpperCase();
			break;
		case 3:
			word_result = result[2].toUpperCase() + result[3];
			break;
	}

	word_result = result[1] + word_result;
	for (var i = 4; i < result.length; i++) {
		word_result += result[i];
	}
	
	return word_result;
}

function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function


//checking if property came from USA then convert abbrev address to long form
//e.g. "10 S 33 W"  to "10 South 33  West"

function checkUSaddressStyle(){
    if ($('id_country').value=="51") {
        var addr = $('address_line_1').value;
        
          var pattern = /^[0-9]*\ *[sSwWnNeE]\ *[0-9]*\ *[sSwWnNeE]$/;
          var result = pattern.exec(addr);          
          if (result!=null) {
                result=""+result;
                result = result.replace(/\ [nN]/g, " North");
                result = result.replace(/\ [sS]/g, " South");
                result = result.replace(/\ [eE]/g, " East");
                result = result.replace(/\ [wW]/g, " West");

                var question = confirm("This appears to be an abbreviated address, sometimes our system blocks these.\n"
                    +" \nWould you like us to expand it to this: "+result+ 
                    " ? \n");
                if (question==true) {
                    $('address_line_1').value =result;
                }
          }
        
    }    
}


