//---------------------------------------------------------------------------
// NAVIGATION FUNCTIONS

function fncNavPrimaryOver(oNavContainer) {
  fncAddClass(oNavContainer, "clsHover");
}
function fncNavPrimaryOut(oNavContainer) {
  fncRemoveClass(oNavContainer, "clsHover");
}

function fncValidateComment(oForm) {
  var strConfirm = document.getElementById('idConfirm').innerHTML.toLowerCase();
  var chrConfirm = strConfirm.charAt(strConfirm.length-1);
  var chrConfirmChoice = fncGetRadioValue(oForm.confirmChoice);
  if (chrConfirmChoice == chrConfirm) {
    return fncValidateForm(oForm);
  }
  else {
    alert("Please choose the " + strConfirm.toUpperCase() + " so we know you are a human!");
    return false;
  }
}


function fncValidateContact(oForm) {
  var strConfirm = document.getElementById('idConfirm').innerHTML.toLowerCase();
  var chrConfirm = strConfirm.charAt(strConfirm.length-1);
  var chrConfirmChoice = fncGetRadioValue(oForm.confirmChoice);
  if (chrConfirmChoice == chrConfirm) {
    return fncValidateForm(oForm);
  }
  else {
    alert("Please choose the " + strConfirm.toUpperCase() + " so we know you are a human!");
    return false;
  }
}


function fncAddTextareaSize(oField) {
  if (oField) {
    if (oField.rows) {
      var intCurrentRows = oField.rows;
      var intNewRows = intCurrentRows + 3;
      oField.rows = intNewRows;
    }
  }
}


function fncToggleBlogOrder(blnAscending) {
  var strExpire = "never";
  if (document.getElementById('idBlogOrderSwitchButton')) {
    oToggle = document.getElementById('idBlogOrderSwitchButton');
  }
  if (!blnAscending) {
    fncSetCookie('blogsortascd', '1', 'never', '/');
    if (oToggle) {
      oToggle.innerHTML = "Newest on Top";
    }
  }
  else {
    fncSetCookie('blogsortascd', '0', 'now', '/');
    if (oToggle) {
      oToggle.innerHTML = "Oldest on Top";
    }
  }
  window.location.reload();
}


function fncShowComments(strBlogEntryID) {
  var strBlogCommentID = "id" + strBlogEntryID + "Comments";
  if (document.getElementById(strBlogCommentID)) {
    document.getElementById(strBlogCommentID).style.display = "block";
    document.getElementById("id" + strBlogEntryID + "CommentsToggle").style.display = "none";
    fncSetCookie('showcomment_'+strBlogEntryID, '1', 'never', '/');
  }
}
function fncHideComments(strBlogEntryID) {
  var strBlogCommentID = "id" + strBlogEntryID + "Comments";
  if (document.getElementById(strBlogCommentID)) {
    document.getElementById("id" + strBlogEntryID + "CommentsToggle").style.display = "block";
    document.getElementById(strBlogCommentID).style.display = "none";
    fncSetCookie('showcomment_'+strBlogEntryID, '0', 'now', '/');
  }
}



//---------------------------------------------------------------------------
// HILITE FUNCTIONS

function fncRowHilite(oRow) {
  fncAddClass(oRow, "clsRowHilite");
}
function fncRowUnhilite(oRow) {
  fncRemoveClass(oRow, "clsRowHilite");
}


//---------------------------------------------------------------------------
// FORM FUNCTIONS
function fncFormInputFocus(oField) {
  oField.style.color = "#000000";
  oField.style.backgroundColor = "#E6F3FF";
  fncRemoveClass(oField, "clsFormInputInvalid");
}

function fncFormInputBlur(oField) {
  oField.style.color = "#666666";
  oField.style.backgroundColor = "#FFFFFF";
  fncValidFormField(oField, true);
}

function fncCheckCustom(oField, strMessage) {
  if (oField.value == "custom") {
    var strCustom = prompt(strMessage);
    if (strCustom.length > 0) {
      oField[oField.length] = new Option(strCustom,strCustom); 
      oField.options[oField.length-1].selected = true;
    }
  }
}

var blnDoFancyFields = false;
function fncValidateForm(oForm) {
  blnDoFancyFields = false;
  var strErrors = "";
  var oElements = oForm.elements;
  if (arguments.length >= 2) {
    if (arguments[1] == true) {
      blnDoFancyFields = true;
    }
  }
  
  for (var i=0;i<oElements.length;i++) {
    // Validate each element using the fncValidFormField function which will
    //   return any errors found.  
    strErrors = strErrors + fncValidFormField(oElements[i]);
  }
  
  if (strErrors.length > 0) {
    // Report any errors and return false
    alert("Please correct these errors before continuing: \n" + strErrors);
    return false;
  }
  else {
    // All elements have been validated, return true
    return true;
  }
}

function fncValidFormField(oElement) {
  // Returns error message if invalid
  // Form Elements can have the following additional attributes (which may lead to invalid XHTML)
  //   required - makes sure there is a value provided or selected
  //   validphone - ensures valid US/Canadian phone number
  //   validemail - ensures valid email address
  // Does not validate checkbox lists or radio buttons
  var strElementError = "";
  var strNiceName = oElement.name;
  var blnAllRequired = false;
  
  if (oElement.form) {
    if (oElement.form.getAttribute("required")) {
      blnAllRequired = true;
    }
  }
  
  if (typeof(blnDoFancyFields) == "undefined") {
    blnDoFancyFields = false;
  }
  if (arguments.length >= 2) {
    if (arguments[1] == true) {
      blnDoFancyFields = true;
    }
  }
  
  if (oElement.getAttribute("nicename")) {
    strNiceName = oElement.getAttribute("nicename");
  }
  
  if (!oElement.disabled && oElement.getAttribute("type") != "hidden") {
    
    // Validate Required Elements
    if (blnAllRequired || oElement.getAttribute("required")) {
      
      // Check Required Text Elements (Text, Textbox, Textarea)
      if ((oElement.type.indexOf("text") >= 0 || oElement.type.indexOf("password") >= 0) && oElement.value.length <= 0) {
        strElementError = "Please provide a response for " + strNiceName;
      }
      
      // Check Required Drop-Down Boxes
      if (oElement.type.indexOf("select") >= 0) {
        var intNumSelected = 0;
        for (var j=0;j<oElement.length;j++) {
          if (oElement[j].selected && oElement[j].value.length > 0) {
            intNumSelected++;
          }
        }
          
        if (intNumSelected == 0) {
          strElementError = "Please select a response for " + strNiceName;
        }
      }
    }
    
    // Validate Phone Number
    if (oElement.getAttribute("validphone") && oElement.value.length > 0) {
      if (!fncValidUSCanadaPhone(oElement.value)) {
        strElementError = "Please provide a valid " + strNiceName;
      }
    }
    
    // Validate Email Addresses
    if (oElement.getAttribute("validemail") && oElement.value.length > 0) {
      if (!fncValidEmail(oElement.value)) {
        strElementError = "Please provide a valid " + strNiceName;
      }
    }
    if (oElement.getAttribute("validintlphone") && oElement.value.length > 0) {
      if (!fncValidIntlPhone(oElement.value)) {
        strElementError = "Please provide a valid " + strNiceName;
      }
    }
  }
  
  if (strElementError.length > 0) {
    strElementError = "\n - " + strElementError;
    if (blnDoFancyFields) { fncAddClass(oElement, "clsFormInputInvalid"); }
  }
  else {
    if (blnDoFancyFields) { fncRemoveClass(oElement, "clsFormInputInvalid"); }
  }
  return strElementError;
}

function fncValidEmail(strEmail) {
	strInvalidChars = " /:,;'";
	if (strEmail == "" ) {
		return false;
	}
	for ( i = 0; i<strInvalidChars.length;  i++) {
		chrBadChar=strInvalidChars.charAt(i);
		if (strEmail.indexOf(chrBadChar,0) > -1) {
			return false;
		}
	}
	intPos=strEmail.indexOf("@",1)
	if (intPos == -1 ) {
		return false;
	}
	if (strEmail.indexOf("@",intPos+1) > -1 ) {
		return false;
	}
	intPeriodPos=strEmail.indexOf(".",intPos)
	if (intPeriodPos == -1 ) {
		return false;
	}
	if (intPeriodPos+3 > strEmail.length ) {
		return false;
	}
	return true;
}

function fncValidUSCanadaPhone(strPhone) {
	if (strPhone.match(/\s*\(?\s*[2-9]\d{2}\s*\)?\s*([-.]?)\s*\d{3}\s*([-.]?)\s*\d{4}\s*/)) {
	  if (fncValidIntlPhone(strPhone)) {
		  return true;
	  }
	}
	return false;
}

function fncValidIntlPhone(strPhone) {
	strPhone = strPhone.replace(/[\s\(\)\-\.]/g,"");
	if (strPhone.length >= 10) {
	  return true;
	}
}


function fncRowHilite(oRow) {
  fncAddClass(oRow, "clsRowHilite");
}
function fncRowUnhilite(oRow) {
  fncRemoveClass(oRow, "clsRowHilite");
}


//---------------------------------------------------------------------------
// LIST FUNCTIONS

function fncListItemUp(obj) {
	obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
	if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
		return false;
	var sel = new Array();
	for (var i=0; i<obj.length; i++) {
		if (obj[i].selected == true) {
			sel[sel.length] = i;
		}
	}
	for (i in sel) {
		if (sel[i] != 0 && !obj[sel[i]-1].selected) {
			var tmp = new Array((document.body.innerHTML ? obj[sel[i]-1].innerHTML : obj[sel[i]-1].text), obj[sel[i]-1].value, obj[sel[i]-1].style.color, obj[sel[i]-1].style.backgroundColor, obj[sel[i]-1].className, obj[sel[i]-1].id);
			if (document.body.innerHTML) obj[sel[i]-1].innerHTML = obj[sel[i]].innerHTML;
			else obj[sel[i]-1].text = obj[sel[i]].text;
			obj[sel[i]-1].value = obj[sel[i]].value;
			obj[sel[i]-1].style.color = obj[sel[i]].style.color;
			obj[sel[i]-1].style.backgroundColor = obj[sel[i]].style.backgroundColor;
			obj[sel[i]-1].className = obj[sel[i]].className;
			obj[sel[i]-1].id = obj[sel[i]].id;
			if (document.body.innerHTML) obj[sel[i]].innerHTML = tmp[0];
			else obj[sel[i]].text = tmp[0];
			obj[sel[i]].value = tmp[1];
			obj[sel[i]].style.color = tmp[2];
			obj[sel[i]].style.backgroundColor = tmp[3];
			obj[sel[i]].className = tmp[4];
			obj[sel[i]].id = tmp[5];
			obj[sel[i]-1].selected = true;
			obj[sel[i]].selected = false;
		}
	}
}

function fncListItemDown(obj) {
	obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
	if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
		return false;
	var sel = new Array();
	for (var i=obj.length-1; i>-1; i--) {
		if (obj[i].selected == true) {
			sel[sel.length] = i;
		}
	}
	for (i in sel) {
		if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
			var tmp = new Array((document.body.innerHTML ? obj[sel[i]+1].innerHTML : obj[sel[i]+1].text), obj[sel[i]+1].value, obj[sel[i]+1].style.color, obj[sel[i]+1].style.backgroundColor, obj[sel[i]+1].className, obj[sel[i]+1].id);
			if (document.body.innerHTML) obj[sel[i]+1].innerHTML = obj[sel[i]].innerHTML;
			else obj[sel[i]+1].text = obj[sel[i]].text;
			obj[sel[i]+1].value = obj[sel[i]].value;
			obj[sel[i]+1].style.color = obj[sel[i]].style.color;
			obj[sel[i]+1].style.backgroundColor = obj[sel[i]].style.backgroundColor;
			obj[sel[i]+1].className = obj[sel[i]].className;
			obj[sel[i]+1].id = obj[sel[i]].id;
			if (document.body.innerHTML) obj[sel[i]].innerHTML = tmp[0];
			else obj[sel[i]].text = tmp[0];
			obj[sel[i]].value = tmp[1];
			obj[sel[i]].style.color = tmp[2];
			obj[sel[i]].style.backgroundColor = tmp[3];
			obj[sel[i]].className = tmp[4];
			obj[sel[i]].id = tmp[5];
			obj[sel[i]+1].selected = true;
			obj[sel[i]].selected = false;
		}
	}
}      

function fncPopulateSortedList(strSourceID, strTargetID) {
  if (document.getElementById(strSourceID) && document.getElementById(strTargetID)) {
    var strNewList = "";
    for (var i=0;i<document.getElementById(strSourceID).length;i++) {
      strNewList = strNewList + document.getElementById(strSourceID).options[i].value + ",";
    }
    if (strNewList.indexOf(",") > 0) { strNewList = strNewList.substr(strNewList,strNewList.length-1); }
    document.getElementById(strTargetID).value = strNewList;
  }
}

//---------------------------------------------------------------------------
// UTILITY FUNCTIONS

function fncGetAbsoluteX(oObjectToGetPosition) {
  // Utility function to get the absolute X-coordinate of an object on the page
  var intCoords = {x: 0};
  while (oObjectToGetPosition) {
    intCoords.x += oObjectToGetPosition.offsetLeft;
    oObjectToGetPosition = oObjectToGetPosition.offsetParent;
  }
  return intCoords.x;
}
function fncGetAbsoluteY(oObjectToGetPosition) {
  // Utility function to get the absolute Y-coordinate of an object on the page
  var intCoords = {y: 0};
  while (oObjectToGetPosition) {
    intCoords.y += oObjectToGetPosition.offsetTop;
    oObjectToGetPosition = oObjectToGetPosition.offsetParent;
  }
  return intCoords.y;
}

function fncGetWidth(oObjectToGetWidth) {
  // Utility function to get the width of an object on the page
	if (oObjectToGetWidth.style.pixelWidth) {
		return oObjectToGetWidth.style.pixelWidth;
	}
  if (oObjectToGetWidth.style.width) {
      return oObjectToGetWidth.style.width;
  } 
  return oObjectToGetWidth.offsetWidth;
}

function fncGetHeight(oObjectToGetHeight) {
  // Utility function to get the height of an object on the page
	if (oObjectToGetHeight.style.pixelHeight) {
		return oObjectToGetHeight.style.pixelHeight;
	}
  if (oObjectToGetHeight.style.height) {
      return oObjectToGetHeight.style.height;
  }
  return oObjectToGetHeight.offsetHeight;
}


function fncGetRadioValue(oRadio) {
  var strValue = "";
  if (oRadio) {
    for (var i=0; i < oRadio.length; i++) {
      if (oRadio[i].checked) {
        var strValue = oRadio[i].value;
      }
    }
  }
  return strValue;
}



function fncAddClass(oElement, strClassName) {
  if (typeof(oElement) == "object" && strClassName.length > 0) {
    if (typeof(oElement.className) == "string") {  
      var strCurrentClassName = oElement.className;
      if (strCurrentClassName.indexOf(strClassName) < 0) {
        if (strCurrentClassName.length > 1) {
          strClassName = strCurrentClassName + " " + strClassName;
        }        
        oElement.className = strClassName;
      }
    }
  }
}

function fncRemoveClass(oElement, strClassName) {
  if (typeof(oElement) == "object" && strClassName.length > 0) {
    if (typeof(oElement.className) == "string") {  
      var strCurrentClassName = oElement.className;
      if (strCurrentClassName.indexOf(strClassName) >= 0) {
        strNewClassName = fncRemoveClassRecursive(" " + strCurrentClassName + " ", " " + strClassName + " ");
        if (strNewClassName.indexOf(" ") == 0) { strNewClassName = strNewClassName.substring(1); }
        if (strNewClassName.lastIndexOf(" ") == strNewClassName.length-1) { strNewClassName = strNewClassName.substring(0,strNewClassName.length-1); }
        oElement.className = strNewClassName;
      }
    }
  }
}

function fncRemoveClassRecursive(strSource, strSubstrToRemove) {
  var intIndex = strSource.indexOf(strSubstrToRemove);
  var strReturn = "";
  if (intIndex == -1) return strSource;
  strReturn += strSource.substring(0,intIndex) + " " + fncRemoveClassRecursive(strSource.substring(intIndex + strSubstrToRemove.length), strSubstrToRemove);
  return strReturn;
}

function fncMakeCurrency(dblSource) {
  var strReturn = dblSource;
  if (!isNaN(dblSource)) {
    strReturn = dblSource.toFixed(2);
  }
  return strReturn;
}


//---------------------------------------------------------------------------
// COOKIE FUNCTIONS

function fncSetCookie (name, value, exp, path) {
 /*
    INPUT
      name (string) - name of the cookie
      value (string) - value of the cookie
      exp (string) - default is "never"
                     if "never" it sets exp to "Thu, 7 Dec 2113 01:00:00 UTC"
                     if "exp" it sets exp to "Fri, 13 Apr 1970 01:00:00 UTC"
                     if int (ie "5", "20", "60000") it translates to int hours from now
                     if valid GMT date then it uses that as exp
                     else it defaults to 840 hours (5 weeks)
      path (string)
 */
 if(exp == "") {
   exp = "never";
 }
 if (typeof(exp) == 'string') {
   if (exp == 'never') { 
     var strExp = "Thu, 7 Dec 2113 01:00:00 UTC";
   }
   else if (exp == 'exp' || exp == 'now') { 
     var strExp = "Fri, 13 Apr 1970 01:00:00 UTC";
   }
   else {
     if (Date.parse(exp)) {
      var strExp = exp;
     }
     else {
       exp = exp*1;
       if (isNaN(exp)) {
        var strExp = (new Date((new Date()).getTime() + 840*3600000)).toGMTString();
       }
       else {
        var strExp = (new Date((new Date()).getTime() + exp*3600000)).toGMTString();
       }
     }
   }
 }
 document.cookie = name + '=' + escape(value) + ((strExp)?(';expires=' + strExp):'') + ((path)?';path=' + path:'');
}



function fncReadCookie(name) {
 var strCookies = document.cookie;
 
 // find beginning of cookie value in document.cookie
 var prefix = name + "=";
 var begin = strCookies.indexOf("; " + prefix);
 if (begin == -1) {
   begin = strCookies.indexOf(prefix);
   if (begin != 0) return null;
 }
 else begin += 2;
 
 // find end of cookie value
 var end = document.cookie.indexOf(";", begin);
 if (end == -1) end = strCookies.length;
 
 // return cookie value
 return unescape(strCookies.substring(begin + prefix.length, end));
}



function fncKillCookie(name, path) {
 /*
    REQUIRED MODULES
      "fncReadCookie" function
      "fncSetCookie" function
 */
 fncSetCookie (name, null, 'now', path);
}
