//A .js file for useful functions

function toggleElement (sId){
    var oElement = get(sId);

    if (oElement.style.display == 'none'){
        oElement.style.display = 'block';
    }else{
        oElement.style.display = 'none';
    }
}

function showWarning (sWarnings) {

    var sWarningHtml = '';

	if(sWarnings.indexOf('\n') > 0){
        var aWarnings = sWarnings.split('\n');
        sWarningHtml += '<ul>'
	    for (var i=0;i<aWarnings.length -1;i++) {
	       if (aWarnings[i]!= ''){
    	       sWarningHtml += '<li>' + aWarnings[i] + '</li>';
    	   }
        }
        sWarningHtml += '</ul>'
	}else{
	   sWarningHtml = sWarnings;
	}
    var oWarning;
    oWarning = get('divWarning');
    
    oWarning.innerHTML = sWarningHtml;
    window.scroll(0,0);    
    oWarning.style.display = 'block' 
  
}

function hideWarning (){
    oWarning = get('divWarning');
	oWarning.style.display = 'none'
    oWarning.innerHTML = '';
}

function postBackForm(sForm, sPostbackCommand, sPostbackArgument) {

	if(sPostbackCommand){

		get("_postback_command").value = sPostbackCommand;
	}
	
	if(sPostbackArgument){
		get("_postback_argument").value = sPostbackArgument;
	}
	
    var oForm 	
    oForm = get(sForm);
	oForm.submit();
}

function setFocus(sID) {
	if(get(sID).disabled != true){
    	get(sID).focus();
	}
}

function validateEmail(sEmail) {
     var sEmailRegEx = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var oRegEx = new RegExp(sEmailRegEx);
     return oRegEx.test(sEmail);
}


function textboxNotEmpty (oTextbox, bSetWarnings){
    var bReturn
    if (oTextbox.value == ''){
        bReturn = false;
    }else{
        bReturn = true;
    }

    if(bSetWarnings != undefined && bSetWarnings != false && bReturn == false){
        oTextbox.className += ' error';
    } else {
        oTextbox.className = oTextbox.className.replace(' error', '' )
    }
    
    return bReturn
}

function textboxIsEmail (oTextbox, bSetWarnings){
    var bReturn
    if (oTextbox.value == '' || validateEmail(oTextbox.value) == false){
        bReturn = false;
    }else{
        bReturn = true;
    }
    
    if(bSetWarnings != undefined && bSetWarnings != null && bReturn == false){
        oTextbox.className += ' error';
    } else {
        oTextbox.className = oTextbox.className.replace(' error', '' )
    }

    return bReturn
}

function textboxIsNumeric (oTextbox, bSetWarnings){
    var bReturn
    if (oTextbox.value == '' || IsNumeric(oTextbox.value) == false){
        bReturn = false;
    }else{
        bReturn = true;
    }

    if(bSetWarnings != undefined && bSetWarnings != null && bReturn == false && bSetWarnings == true){
        oTextbox.className += ' error';
    } else {
        oTextbox.className = oTextbox.className.replace(' error', '' )
    }
    
    return bReturn
}

function textboxIsCreditCard (oTextbox, bSetWarnings){

    var bReturn = true;
	var sWarning = '';
	
	if (isCreditCardNumber(oTextbox.value) == false){
		bReturn = false;
	}
    if (oTextbox.value == ''){
        bReturn = false;
    }
	
	if(bSetWarnings != undefined && bSetWarnings != null && bReturn == false){
        oTextbox.className += ' error';
    } else {
        oTextbox.className = oTextbox.className.replace(' error', '' )
    }

    return bReturn; 

}

function textboxSubmit(oEvent, sForm, sCommand, sArgument) {

	if (oEvent.keyCode == 13) {
		if(sCommand){
			get("_postback_command").value = sCommand;
		}
		if(sArgument){
			get("_postback_argument").value = sArgument;
		}		
		
		document.getElementById(sForm).submit();
		oEvent.cancelBubble = true;
		oEvent.returnValue = false;
	}
}


function noEnterSubmit(oEvent) {
	
	var bReturn = true;
	
	if(!oEvent){ 
		oEvent=window.event;
	}
	
	if (oEvent.keyCode == 13) {
		bReturn = false;
	}
	
	return bReturn;
	
}

function dropdownNotEmpty (oDropdown, bSetWarnings){

    var bReturn
    if (oDropdown.value == ''){
        bReturn = false;
    }else{
        bReturn = true;
    }
    if(bReturn == false && bSetWarnings==true){
        oDropdown.className += ' error';
    } else {
        oDropdown.className = oDropdown.className.replace(' error', '' );
    }
    
    return bReturn
}

function setControlWarning (oControl, bState){

    if(bState == true){
        oControl.className += ' error';
    } else {
        oControl.className = oControl.className.replace('error', '' );
    }

}

function setControlDisabled (oControl, bState){

    if(bState == false){
		oControl.disabled = "disabled";
        oControl.className += " disabled";
    } else {
		oControl.disabled = "";
        oControl.className = oControl.className.replace('disabled', '' );
    }

}

function radioButtonSelected(oRadio) {
	var iCount = -1;
	var bReturn
	for (var i=oRadio.length-1; i > -1; i--) {
	   if (oRadio[i].checked) {iCount = i; i = -1;}
	   }
	if (iCount > -1) {
	   bReturn = true;
	}else{
	   bReturn = false;
	}
	
	return bReturn
}

function dropdownTextValue(sDropdownId){
	
	var iIndex = get(sDropdownId).selectedIndex;
	var sText = get(sDropdownId).options[iIndex].text;
	
	return sText;
}

function isAlphanumeric (c){
    var bReturn = true;
    
    if ((('abcdefghijklmnopqrstuvwxyz0123456789~@#?><\|!?$%^&*"()-_+=?{}[]').indexOf(c) <0)){
        bReturn = false;
    }

    return bReturn
}

function isExpiryDate (sExpiry) {

    bSuccess = false

    // make sure it is the correct format
    if (sExpiry.search(/^((0[1-9])|(1[0-2]))\/(\d{2})$/) >=0){
        bSuccess  = true
    }

   return bSuccess;
}

function isCardDate(sDate){
    bSuccess = false

    // make sure it is the correct format
    if (sDate.search(/^((0[1-9])|(1[0-2]))\/(\d{2})$/) >=0){
        bSuccess  = true
    }    
}

function IsNumeric(sText)

{
   var sValidChars = " 0123456789.";
   var bNumber=true;
   var sChar;

   for (i = 0; i < sText.length && bNumber == true; i++)
      { 
      sChar = sText.charAt(i); 
      if (sValidChars.indexOf(sChar) == -1) 
         {
         bNumber = false;
         }
      }
   return bNumber;
   
 }

function isCreditCardNumber(sCC){
	bReturn = true;

	sCC = 	sCC.replace(' ', '');
	if (sCC.length != 16){
		bReturn = false;
	}

	if (IsNumeric(sCC) == false){
		bReturn = false;
	}
	return bReturn;
}

function concatControlValues (aControlIDs){

	sConcat = "";
    for (var i=aControlIDs.length-1; i > -1; i--) {
    	if (get(aControlIDs[i]) != "undefined"){
        	sConcat += get(aControlIDs[i]).value;
		}
    }
    return sConcat
}

 function isInteger(oEvent)
 {
	var sChar = (oEvent.which) ? oEvent.which : event.keyCode
	if (sChar > 31 && (sChar < 48 || sChar > 57)) 
	   return false;

	return true;

 }

function get(sElementId){
	
	//wrapper for the prototype $ function that includes debugging
	var oElement = $(sElementId);

	bValid = true;
	if (!oElement){
		var oMooDebug = new MooDebug();
		oMooDebug.error("element(s) not found '" + sElementId + "'", false)
	}
	
	return oElement;
}

function currentTime(){

	var oDate = new Date();
	var iHours = oDate.getHours();
	var iMinutes = oDate.getMinutes();
	var iSeconds = oDate.getSeconds();
	var iMilliSeconds = oDate.getMilliseconds();

	return iHours + ":" + iMinutes + ":" + iSeconds + ":" + iMilliSeconds;

}

function randomNumber(iMax, b1Indexed){
		var iRandom = Math.floor(Math.random()*iMax);
		
		// if 0 the try again
		if (iRandom == 0 && b1Indexed == true){
			while(iRandom < 1 || iRandom > iMax){
				iRandom = Math.floor(Math.random()*iMax);
			}
		}
		
		return iRandom;
}

function setCursor (sCursor){
	document.body.style.cursor  = sCursor;
}

function safeInt(sNumber){
	
	var iNumber = parseInt(sNumber);
	if (iNumber == "NaN"){
		iNumber = 0;
	}
	
	return iNumber;
	
}

function print_r(oObject, bNoPrint){
	
	var sPrint = "";
  	if(oObject.constructor == Array ||
	     oObject.constructor == Object){
	    sPrint += "<ul>";
	    for(var p in oObject){
	      if(oObject[p].constructor == Array||
	         oObject[p].constructor == Object){
			sPrint +="<li>["+p+"] => "+typeof(oObject)+"</li>";
	        sPrint += "<ul>";
	        print_r(oObject[p], bNoPrint);
	        sPrint +="</ul>";
	      } else {
			sPrint +="<li>["+p+"] => "+theObj[p]+"</li>";
	      }
	    }
	    sPrint +="</ul>";
	  }
	if (bNoPrint == false){
		document.write(sPrint);
	}
	
	return sPrint;
}

function replaceAll (sSubject,sSearch,sReplace){

	var sTemp = sSubject;
	var i = sTemp.indexOf(sSearch);
	
	while(i > -1) {
		sTemp = sTemp.replace(sSearch, sReplace);
		i = sTemp.indexOf(sSearch, i + sReplace.length);
	}

	return sTemp;
}

function constrainByCropper(xDragger, xCropper, widthCropper, widthDragger, xBleed, 
	yDragger, yCropper, heightCropper, heightDragger, yBleed) {

//debug_write(xDragger + " " + xCropper  + " " +  widthCropper  + " " +  widthDragger  + " " +  xBleed  + " " + yDragger  + " " +  yCropper  + " " +  heightCropper  + " " +  heightDragger  + " " +  yBleed);

	//return vars
	returnY = yDragger;
	returnX = xDragger;
	
	//Y
  if (yDragger > (yCropper - yBleed)){
		returnY = (yCropper - yBleed);	
  }else if ((yDragger + heightDragger) < (yCropper + heightCropper + (yBleed * 2))){
		returnY = yCropper - (heightDragger - heightCropper - yBleed)
  }else{
		returnY = yDragger;
	}
	
	//X
	if (xDragger > xCropper - xBleed){
		returnX = xCropper - xBleed;	
  }else if ((xDragger + widthDragger) < (xCropper + widthCropper + (xBleed * 2))){
		returnX = xCropper - (widthDragger - widthCropper - xBleed)
  }else{
		returnX = xDragger;
	}

	return [returnX, returnY];
}


function makeStringSafeByCode(sString, iMaxCode, sReplacementChar){
	
	var sReturn = "";
	
	for (var i=0; i < sString.length; i++) {
		if (sString.charCodeAt(i) > iMaxCode){
			sReturn += sReplacementChar;
		}else{
			sReturn += sString.charAt(i);			
		}
	}
	
	return sReturn;
}

function stringContainsCharsByCode(sString, iMaxCode){
	
	var bReturn = false;
	
	for (var i=0; i < sString.length; i++) {
		if (sString.charCodeAt(i) > iMaxCode){
			bReturn = true;
		}		
	}
	
	return bReturn;
}

function unescape_from_input_element(sString){
	return replaceAll(sString, '@||@', '"');	
}

//Classes
 function ColourPicker (sColours, oULPicker, eFunctionName){
 
    //Get the list of colours    
    var aColours = sColours.split(",");

    //Add the the UL
        for (var i=0;i<aColours.length;i++) {    
            
            var oColour = document.createElement('li');
            oColour.style.backgroundColor = aColours[i];
            oColour.innerHTML = '<a onclick="javascript:' + eFunctionName + "('" + aColours[i] + "'" + ');"><span class="hide">' + aColours[i] + '</span></a>';
            oULPicker.appendChild(oColour);
          
    }
 
 }
 
 //Get all the elements on a page that share a class name
 function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}
 
function charCount(sNeedle, sHaystack){

	var iCharCount = 0;
  	var aSplit = sHaystack.split(sNeedle);
  	return aSplit.length - 1;	 
	
}

function newWindow(sUrl){
	window.open(sUrl);	
}

function caretPosition (oInput) {

	var iCaretPosistion = 0;
	
	//IE Support
	if (document.selection) {
		oInput.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart ('character', -oInput.value.length);
		iCaretPosition = Sel.text.length;
	}
	
	//Firefox et al support
	else if (oInput.selectionStart || oInput.selectionStart == '0')
		iCaretPosition = oInput.selectionStart;

	//Return
	return iCaretPosition;

}

function stringToLines(sString, iLineLength){
	var aTemp = sString.split(' ');	
 	var aLines = new Array(); 
	var iMaxIterations = 40;
	aLines[0] = "";

	for (var i=0; i < aTemp.length; i++) {
		if(i <= iMaxIterations){
			sTempString = aLines[aLines.length -1] + ' ' + aTemp[i];
			if (sTempString.length <= iLineLength){
				aLines[aLines.length -1] = aLines[aLines.length -1] + " " + aTemp[i];
			}else{
				aLines[aLines.length] = aTemp[i]
			}
		}else{
			break;
		}
	}
	
	return aLines;
}

function safeImage (sUrl){
	var sReturn = sUrl;
	if (sReturn == '' || sReturn == ' '){
		sReturn == '#';
	}
	return sReturn;
}

// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
function getPageSize(){
	
	var iXScroll, iYScroll;

	if (window.innerHeight && window.scrollMaxY) {	
		iXScroll = document.body.scrollWidth;
		iYScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		iXScroll = document.body.scrollWidth;
		iYScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		iXScroll = document.body.offsetWidth;
		iYScroll = document.body.offsetHeight;
	}
	
	var iWindowWidth, iWindowHeight;
	if (self.innerHeight) {	// all except Explorer
		iWindowWidth = self.innerWidth;
		iWindowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		iWindowWidth = document.documentElement.clientWidth;
		iWindowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		iWindowWidth = document.body.clientWidth;
		iWindowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(iYScroll < iWindowHeight){
		iPageHeight = iWindowHeight;
	} else { 
		iPageHeight = iYScroll;
	}

	// for small pages with total width less then width of the viewport
	if(iXScroll < iWindowWidth){	
		iPageWidth = iWindowWidth;
	} else {
		iPageWidth = iXScroll;
	}

	aPageSize = new Array(iPageWidth,iPageHeight,iWindowWidth,iWindowHeight) 
	return aPageSize;
}

