window.focus();

//simple function to open a new window with a url passed. Used in sax so that a user can type or click on a link entered into a form field to check that its actually working
function checkURL(theURL) {
	if (!isWhitespace(theURL)) {
		var varPos = theURL.indexOf("http://",varPos);
		if (varPos == -1) {
			theURL = "http://" + theURL;
		}
		window.open(theURL);
	} else {
		alert('No link URL has been entered');
	}
}

// used to highlight a forms text label when validation fails
function blurField(label) {
	if (document.getElementById(label).className == 'labelError') document.getElementById(label).className = 'label';
}

//function to focus the fckeditor from the previous form field see: (http://wiki.fckeditor.net/FAQ/JavaScript)
//usage: onKeyDown="focusIframeOnTab(this, 'obj_bodyCopy___Frame', event);if(!document.all) return false;"
//replace obj_bodyCopy above with the instance name of your fckeditor field
function focusIframeOnTab(caller, tabTargetId, callEvent) {
    // If keypress TAB and not SHIFT+TAB     
    if(callEvent.keyCode == 9 && !callEvent.shiftKey)
        document.getElementById(tabTargetId).contentWindow.focus();
}

// isEmail (STRING s)
// 
// Email address must be of form a@b.c ... in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//

function isEmail (s)
{
   if (isEmpty(s)) return false;
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

// Check whether string s is empty.
function isEmpty(s)
{   
	return ((s == null) || (s.length == 0));
}


// whitespace characters
var whitespace = " \t\n\r";

// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace (s)
{   
	var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
	
		if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}



var numeric = "1234567890-."
function isNumeric (s)
{
    for (i = 0; i < s.length; i++)
    {   
		// Check that current character is numeric.
		var c = s.charAt(i);
	
		if (numeric.indexOf(c) == -1) return false;
    }
	return true;
}

function cal1DateBeforeCal2Date(calendarOneField, calendarTwoField)
{
	var publishDateValue=calendarOneField.value;
	//alert('publishDate:'+publishDateValue);
	publishArray=publishDateValue.split("/");
	//alert(publishArray[0] +'/'+ publishArray[1] +'/'+ publishArray[2]);
	var publishDate=new Date();
	publishDate.setYear(publishArray[2]);
	publishDate.setMonth(publishArray[1]-1);
	publishDate.setDate(publishArray[0]);
	//alert(publishDate);
	
	var expireDateValue=calendarTwoField.value;	
	expireArray=expireDateValue.split("/");
	var expireDate=new Date();
	expireDate.setYear(expireArray[2]);
	expireDate.setMonth(expireArray[1]-1);
	expireDate.setDate(expireArray[0]);
	//alert(expireDate);
	
	if(expireDate.getTime() < publishDate.getTime())
	{
		return false;	
	}
	else
	{
		return true;
	}
}	

function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function

function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
} // Ends the "getSelectedRadioValue" function

function getSelectedCheckbox(buttonGroup) {
   // Go through all the check boxes. return an array of all the ones
   // that are selected (their position numbers). if no boxes were checked,
   // returned array will be empty (length will be zero)
   var retArr = new Array();
   var lastElement = 0;
   if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            retArr.length = lastElement;
            retArr[lastElement] = i;
            lastElement++;
         }
      }
   } else { // There is only one check box (it's not an array)
      if (buttonGroup.checked) { // if the one check box is checked
         retArr.length = lastElement;
         retArr[lastElement] = 0; // return zero as the only array value
      }
   }
   return retArr;
} // Ends the "getSelectedCheckbox" function

function getSelectedCheckboxValue(buttonGroup) {
   // return an array of values selected in the check box group. if no boxes
   // were checked, returned array will be empty (length will be zero)
   var retArr = new Array(); // set up empty array for the return values
   var selectedItems = getSelectedCheckbox(buttonGroup);
   if (selectedItems.length != 0) { // if there was something selected
      retArr.length = selectedItems.length;
      for (var i=0; i<selectedItems.length; i++) {
         if (buttonGroup[selectedItems[i]]) { // Make sure it's an array
            retArr[i] = buttonGroup[selectedItems[i]].value;
         } else { // It's not an array (there's just one check box and it's selected)
            retArr[i] = buttonGroup.value;// return that value
         }
      }
   }
   return retArr;
} // Ends the "getSelectedCheckBoxValue" function



function GetFCKLength(instance){
	//alert(instance);
	// This functions shows that you can interact directly with the editor area
	// DOM. In this way you have the freedom to do anything you want with it.

	// Get the editor instance that we want to interact with.
	var oEditor = FCKeditorAPI.GetInstance(instance) ;
	// Get the Editor Area DOM (Document object).
	var oDOM = oEditor.EditorDocument ;
	var iLength ;
	var str;

	// The are two diffent ways to get the text (without HTML markups).
	// It is browser specific.
	if ( document.all )		// If Internet Explorer, removing html from the editor leave an empty P.
	{
		str = new String(oDOM.body.innerHTML);
		iLength = oDOM.body.innerText.length + str.replace(/<P>&nbsp;<\/P>/g,"").length;
	}
	else					// If Gecko.
	{
		var r = oDOM.createRange() ;
		r.selectNodeContents( oDOM.body ) ;
		iLength = r.toString().length ;
	}
	return iLength;
	//alert( 'Actual text length (without HTML markups): ' + iLength + ' characters' ) ;
}

/**
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : dd/mm/yyyy")
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false;
	}
return true;
}


  /* 
    =============================================================================
    Name: function removeSpaces(theField) {}
    
    Description:
      THIS FUNCTION REMOVES ALL SPACES FROM A FIELD.
      IT CAN TO BE INCLUDED ON A FIELDS "onBlur" ATTRIBUTE OR CAN BE INCLUDED
      ON FORM VALIDATION ETC.
      
    Example:
     <input type="text" name="phone" value="" onblur="removeSpaces(this);">
    =============================================================================
  */
  function removeSpaces(theField) {
    if (theField.value != '') {
      var txt=theField.value;
      var fieldArray = txt.split(" ");
      var newString = "";
      for (var i = 0; i < fieldArray.length; i++) {
        var arrayText = fieldArray[i];
        var newString = newString + arrayText;
      }
      theField.value = trim(newString);
    }
  }
  
  
  /* 
    =============================================================================
    Name: function trim(str) {}
    
    Description:
      THIS FUNCTION REMOVES EXTRA SPACES FROM BEFORE AND AFTER THE STRING.
      
    Example:
      someVal = trim(someString);
    =============================================================================
  */
  function trim(str) {
    return str.replace(/^\s*|\s*$/g,"");
  }

  
  /* 
    =====================================================================================================
    Name: function CamelCase(theField) {}
    
    Description:
      THIS FUNCTION CONVERTS THE FIRST CHARACTERS OF EVERY WORD TO UPPERCASE ALSO PRESERVING THE SPACES.
      IT CAN TO BE INCLUDED ON A FIELDS "onBlur" ATTRIBUTE OR CAN BE INCLUDED ON FORM VALIDATION ETC.
      
    Example:
      <input type="text" name="first_name" id="first_name" value="" onblur="CamelCase(this);">
    =====================================================================================================
  */
  function CamelCase(theField) {
    
    // if field value is empty then ignore
    if (theField.value != '') {
      // get field value
      var txt=theField.value;
      // convert value to lowercase
      var txt=txt.toLowerCase();
      // split the string into an array
      var fieldArray = txt.split(" ");
      
      var newString = "";
      
      // for every string in the array convert first char to UpperCase
      for (var i = 0; i < fieldArray.length; i++) {
        var arrayText = fieldArray[i];
        var firstChar = arrayText.charAt(0);
        var firstCharUpper = firstChar.toUpperCase();
        
        var regEx = new RegExp (firstChar, 'i') 
        var arrayText = arrayText.replace( regEx, firstCharUpper );
        
        var newString = newString + arrayText + " ";
      } 
      
      // set the field value to the CamelCase value
      theField.value = trim(newString);
    }
  }
  
  
  /* 
    ===================================================================================================================================================================
    Name: function preventDoubleSubmit(submitFieldID,disable or enable) {}
    
    Description:
      THIS FUNCTION WILL PREVENT THE FORM BEING SUBMITTED TWICE IN RESULT OF A DOUBLE CLICK OR OTHER.
      THIS MUST BE CALLED ON THE FORMS "onSubmit" AND ALSO ON RETURN FALSE OF VALIDATION
      YOU MUST PASS IN THE SUBMIT FIELD ID IN THE FIRST PARAMETER AND EITHER TRUE OR FALSE AS THE SECOND PARAMETER (look at egxample below)
      TRUE = DISABLE SUBMIT
      FALSE = ENABLE SUBMIT
      
    Example:
      onSubmit:
        <form name="testForm" id="testForm" action="url" method="post" onsubmit="return validateForm(this); preventDoubleSubmit(document.getElementById(''),disable)">
      
      return false:
        function validateForm(theForm)
      	{
      		var errorMessage = "";
      		
          if(!isNumeric(theForm.phone.value)) 
      		{
      			errorMessage = errorMessage + (" - your phone number is invalid - use numbers only\n");
      		}
          if (errorMessage.length)
      		{
      			errorMessage = "Please fix the following items in this form:\n" + errorMessage;
      			alert(errorMessage);
            preventDoubleSubmit(document.getElementById('submitForm'),false);
      			return false;
      		}
      		else
      		{
      			return true;
      		}
      		return true;
      	}
    ===================================================================================================================================================================
  */
  function preventDoubleSubmit(submitFieldID,actionToDo) {
    submitFieldID.disabled = actionToDo;
  }
