var language = 'english';

function getElement(anElement){
	var theElement = document.getElementById(anElement);
	
	return theElement;
}

// Class ----------------------------------------------------------------------
// Class Name: WorkAreaLibrary
// Description: This class encapsulates all basic and commmon functionality
//              used within the Work Area
// ----------------------------------------------------------------------------
function WorkAreaLibrary(){

}

// ---------------------------------------------------------------------------
// cleanParameters(dirtyString) 
//  Removes all undefined values from the string
// ---------------------------------------------------------------------------
WorkAreaLibrary.cleanParameters = function (dirtyString){
	return dirtyString.replace(/undefined/g, '');

}

// -------------------------------------------------------------------
// removeLeadingZero(anInteger)
//  This function removes the leading zero from a string representation
//  of an integer.
// -------------------------------------------------------------------
WorkAreaLibrary.removeLeadingZero = function(anInteger){
	if(anInteger.length > 1 && anInteger[0] == "0"){
		return anInteger.substring(1, anInteger.length);
	}	
	else{
		return anInteger;
	}
}


// ---------------------------------------------------------------------------
// convertTo12HrFormat()
//  Converts a javascript date value to a 12 hour format
// ---------------------------------------------------------------------------
WorkAreaLibrary.convertTo12HrFormat = function(aTimeValue){
	
	return aTimeValue > 12 ? aTimeValue - 12 : 
					aTimeValue == 0 ? 12 : aTimeValue; 
}

// ---------------------------------------------------------------------------
// convertDBTimeTo12HrFormat()
//  Converts a time value from a MySQL database value to a 12 hour format
// ---------------------------------------------------------------------------
WorkAreaLibrary.convertDBTimeTo12HrFormat = function(aTimeValue){
	
	var temp = aTimeValue.substring(0,2); 

	if(temp.charAt(0) == '0'){ 
		temp = aTimeValue.charAt(1); 
	} 
	var curHour = parseInt(temp); 
	temp = aTimeValue.substring(3,5); 

	var curMin = temp; 
	var curAMPM = " AM"; 
	var curTime = ""; 
	if (curHour >= 12){ 
		curHour -= 12; 
		curAMPM = " PM" 
	} 
	if (curHour == 0) curHour = 12 
	curTime = curHour + ":"	+ curMin + curAMPM;
	
	return curTime; 
}


// -------------------------------------------------------------------
// urlEncode(clearString) 
//  Encodes url for passing by GET or POST
// -------------------------------------------------------------------
WorkAreaLibrary.urlEncode = function (clearString) {
  if(clearString == 'undefined' || clearString == null){
  	return '';
  }
  
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

// -------------------------------------------------------------------
// urlDecode(clearString) 
//  Decodes url
// -------------------------------------------------------------------
WorkAreaLibrary.urlDecode = function (encodedString) {
  if(encodedString == 'undefined' || encodedString == null){
  	return '';
  }
  
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%\+]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
             //&& match[1][1] != '+') {
                    	
    	binVal = parseInt(match[1].substr(1),16);
    	thisString = String.fromCharCode(binVal);
   	 	output = output.replace(match[1], thisString);
  }
  
  // Replaces all '+' with a space
  output = output.replace(/\+/g, ' ');
  
  return output;
}

// -------------------------------------------------------------------
// attachEventListener(object, eventName, functionName)
//  Attaches an event to an object
// -------------------------------------------------------------------
WorkAreaLibrary.attachEventListener = function (object, eventName, functionName){
	
	// Must be backwards compatible
	var objectId = "#" + object.id;
	
	$(objectId).unbind(eventName, theFunctionToFire);
	
	var theFunctionToFire = functionName;
	
	$(objectId).bind(eventName, theFunctionToFire);
}

// ---------------------------------------------------------------------------
// getBodyHeight(aDocumentElement)
//  Calculates height of page body.
// ---------------------------------------------------------------------------
WorkAreaLibrary.getBodyHeight = function(aDocumentElement){	
	var yWithScroll;
	
	if (aDocumentElement.innerHeight && aDocumentElement.scrollMaxY) {// Firefox         
		yWithScroll = aDocumentElement.innerHeight + aDocumentElement.scrollMaxY;
	} 
	else if (
		aDocumentElement.scrollHeight > aDocumentElement.offsetHeight) {
		yWithScroll = aDocumentElement.scrollHeight;        
	 } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari     
	    yWithScroll = aDocumentElement.offsetHeight;     
	 }    
	 
	 return yWithScroll; 
}

// -------------------------------------------------------------------
// displayNewsletterEditor (showTextEditor)
//  Displays the newsletter editor window
// -------------------------------------------------------------------
WorkAreaLibrary.displayNewsletterEditor  = function(showTextEditor){
	
	// Centers editor
	var winH = $(window).height();
    var winW = $(window).width();
    var centerDiv = $("#newsletterEditor");
    
    centerDiv.css('top', winH/2-centerDiv.height()/2);
    centerDiv.css('left', winW/2-centerDiv.width()/2); 
	
	
	if(showTextEditor == true){
		$("#newsletterEditorTextSection").show();
		$("#newsletterEditorImageSection").hide();	    	
	}
	else{
		$("#newsletterEditorTextSection").hide();
		$("#newsletterEditorImageSection").show();	
	}
	
	// Displays editor
	$("#newsletterEditor").jqmShow();
}

// ---------------------------------------------------------------------------
// closeNewsletterEditor()
//  Closes the newsletter editor window
// ---------------------------------------------------------------------------
WorkAreaLibrary.closeNewsletterEditor = function(){
	// Closes editor window
	$("#newsletterEditor").jqmHide(); 		
}

// -------------------------------------------------------------------
// displayInfoWindow()
//  Displays info window
// -------------------------------------------------------------------
WorkAreaLibrary.displayInfoWindow = function(content, width, height){
	// Change contents of content div
	getElement('infoContent').innerHTML = content;
	
	// Sets width
	if(width != undefined && width != null && width > 0){
		$("#info").data("width.dialog", width);
	}
	
	// Sets height
	if(height != undefined && height != null && height > 0){
		$("#info").data("height.dialog", height);
	}
	
	$("#info").dialog("open");
}

// ---------------------------------------------------------------------------
// closeInfoWindow()
//  Closes info window
// ---------------------------------------------------------------------------
WorkAreaLibrary.closeInfoWindow = function(){
	$("#info").dialog("close");
	
	// Clears contents and removes from DOM
	var contentWindow = $("#info")
							.parents(".ui-dialog:first")
							.find("#warningContent").get(0);
	
	/*
	// First purge all childnodes
	purge(contentWindow);
	
	// Remove all nodes from DOM	
	while(contentWindow.childNodes.length > 0) {
        removeChildSafe(contentWindow.childNodes[contentWindow.childNodes.length-1]);
    }*/
	
	// Resets width and heights to default
	$("#info").data("width.dialog", '400');
    $("#info").data("height.dialog", '400');			
}

// -------------------------------------------------------------------
// displayWarningWindow()
//  Displays warning window
// -------------------------------------------------------------------
WorkAreaLibrary.displayWarningWindow = function(content, width, height){
	// Change contents of content div
	getElement('warningContent').innerHTML = content;
	
	// Sets width
	if(width != undefined && width != null && width > 0){
		$("#warning").data("width.dialog", width);
	}
	
	// Sets height
	if(height != undefined && height != null && height > 0){
		$("#warning").data("height.dialog", height);
	}
	
	$("#warning").dialog("open");
}

// ---------------------------------------------------------------------------
// closeWarningWindow()
//  Closes warning window
// ---------------------------------------------------------------------------
WorkAreaLibrary.closeWarningWindow = function(){
	$("#warning").dialog("close");
	
	// Clears contents and removes from DOM
	var contentWindow = $("#warning")
							.parents(".ui-dialog:first")
							.find("#warningContent").get(0);
	
	/*
	// First purge all childnodes
	purge(contentWindow);
	
	// Remove all nodes from DOM	
	while(contentWindow.childNodes.length > 0) {
        removeChildSafe(contentWindow.childNodes[contentWindow.childNodes.length-1]);
    }*/
	
	// Resets width and heights to default
	$("#warning").data("width.dialog", '400');
    $("#warning").data("height.dialog", '400');			
}

// -------------------------------------------------------------------
// displayConfirmationWindow()
//  Displays confirmation window
// -------------------------------------------------------------------
WorkAreaLibrary.displayConfirmationWindow = function(content, width, height){
	// Change contents of content div
	getElement("confirmationContent").innerHTML = content;
	
	// Sets width
	if(width != undefined && width != null && width > 0){
		$("#confirmation").data("width.dialog", width);
	}
	
	// Sets height
	if(height != undefined && height != null && height > 0){
		$("#confirmation").data("height.dialog", height);
	}
	
	$("#confirmation").dialog("open");
}

// -------------------------------------------------------------------
// addYesButtonHandler
//  Adds event listener to the confirmation 'Yes' button
// -------------------------------------------------------------------
WorkAreaLibrary.addYesButtonHandler = function(aFunction){
	var dialogWindow = $("#confirmation").parents(".ui-dialog:first");
	
	///////////////////////////////////////////////////////////////////////////
	// Handles Yes button
	///////////////////////////////////////////////////////////////////////////
		
	// Gets 'Yes' button and adds listener
	if(language == "english"){
		var button = dialogWindow.find(".ui-dialog-buttonpane button")
					.filter(":contains('Yes')");
	}
	else{
		var button = dialogWindow.find(".ui-dialog-buttonpane button")
					.filter(":contains('Oui')");
	}
	
	// Unbinds old handler
	button.unbind("click", processYesButtonClick);
	
	// Creates new handler and binds to click event
	var processYesButtonClick = aFunction;
	
	button.bind("click", processYesButtonClick);
	
	///////////////////////////////////////////////////////////////////////////
	// Handles No button
	///////////////////////////////////////////////////////////////////////////
	
	button = dialogWindow.find(".ui-dialog-buttonpane button")
					.filter(":contains('No')");
	
	if(language == "english"){
		button = dialogWindow.find(".ui-dialog-buttonpane button")
					.filter(":contains('No')");
	}
	else{
		button = dialogWindow.find(".ui-dialog-buttonpane button")
					.filter(":contains('Non')");
	}
	
	// Unbinds old handler
	button.unbind("click", processNoButtonClick);
	
	// Creates new handler and binds to click event
	var processNoButtonClick = function(){
			WorkAreaLibrary.closeConfirmationWindow();
			
			// Allows callout and info window to be displayed
			DayPlannerManager.setKeepCalloutClosed(false);
			DayPlannerManager.setKeepClosed(false);
		};
	
	button.bind("click", processNoButtonClick);
}

// -------------------------------------------------------------------
// addYesNoButtonHandlers
//  Adds event listener to the confirmation 'Yes' and 'No' button
// -------------------------------------------------------------------
WorkAreaLibrary.addYesNoButtonHandlers = function(aYesFunction, aNoFunction){	
	
	var dialogWindow = $("#confirmation").parents(".ui-dialog:first");
	
	///////////////////////////////////////////////////////////////////////////
	// Handles Yes button
	///////////////////////////////////////////////////////////////////////////
		
	// Gets 'Yes' button and adds listener
	if(language == "english"){
		var button = dialogWindow.find(".ui-dialog-buttonpane button")
					.filter(":contains('Yes')");
	}
	else{
		var button = dialogWindow.find(".ui-dialog-buttonpane button")
					.filter(":contains('Oui')");
	}
	
	// Unbinds old handler
	button.unbind("click", processYesButtonClick);
	
	// Creates new handler and binds to click event
	var processYesButtonClick = aYesFunction;
	
	button.bind("click", processYesButtonClick);
	
	///////////////////////////////////////////////////////////////////////////
	// Handles No button
	///////////////////////////////////////////////////////////////////////////
	
	if(language == "english"){
		button = dialogWindow.find(".ui-dialog-buttonpane button")
					.filter(":contains('No')");
	}
	else{
		button = dialogWindow.find(".ui-dialog-buttonpane button")
					.filter(":contains('Non')");
	}
	
	// Unbinds old handler
	button.unbind("click", processNoButtonClick);
	
	// Creates new handler and binds to click event
	var processNoButtonClick = aNoFunction;
	
	button.bind("click", processNoButtonClick);
}

// ---------------------------------------------------------------------------
// closeConfirmation()
//  Closes confirmation window
// ---------------------------------------------------------------------------
WorkAreaLibrary.closeConfirmationWindow = function(){
	$("#confirmation").dialog("close");
	
	// Clears contents and removes from DOM
	var contentWindow = $("#confirmation")
							.parents(".ui-dialog:first")
							.find("#confirmationContent").get(0);
	/*						
	// First purge all childnodes
	purge(contentWindow);
	
	// Remove all nodes from DOM	
	while(contentWindow.childNodes.length > 0) {
        removeChildSafe(contentWindow.childNodes[contentWindow.childNodes.length-1]);
    }*/
	
	// Resets width and heights to default
	$("#confirmation").data("width.dialog", '400');
    $("#confirmation").data("height.dialog", '400');			
}

// -------------------------------------------------------------------
// displayHelpWindow()
//  Displays help window
// -------------------------------------------------------------------
WorkAreaLibrary.displayHelpWindow = function(content, width, height){
	// Change contents of content div
	getElement("helpContent").innerHTML = content;
	
	// Sets width
	if(width != undefined && width != null && parseInt(width) > 0){
		$("#help").data("width.dialog", width);
	}
	
	// Sets height
	if(height != undefined && height != null && height > 0){
		$("#help").data("height.dialog", height);
	}
	
	$("#help").dialog("open");
}

// -------------------------------------------------------------------
// closeHelpWindow()
//  Closes help window
// -------------------------------------------------------------------
WorkAreaLibrary.closeHelpWindow = function(){
	$("#help").dialog("close");
	
	// Clears contents and removes from DOM
	var contentWindow = $("#help")
							.parents(".ui-dialog:first")
							.find("#helpContent").get(0);
	/*						
	// First purge all childnodes
	purge(contentWindow);
	
	// Remove all nodes from DOM	
	while(contentWindow.childNodes.length > 0) {
        removeChildSafe(contentWindow.childNodes[contentWindow.childNodes.length-1]);
    }*/
	
	// Resets width and heights to default
	$("#help").data("width.dialog", '400');
    $("#help").data("height.dialog", '400');		
}

// -------------------------------------------------------------------
// displayProgressWindow()
//  Displays help window
// -------------------------------------------------------------------
WorkAreaLibrary.displayProgressWindow = function(){
	$("#progressWindow").dialog("open");
}

// -------------------------------------------------------------------
// closeProgressWindow()
//  Closes help window
// -------------------------------------------------------------------
WorkAreaLibrary.closeProgressWindow = function(){
	$("#progressWindow").dialog("close");
}

// ---------------------------------------------------------------------------
// getScrollYPosition()
//  Calculates Y positioning.
// ---------------------------------------------------------------------------
WorkAreaLibrary.getScrollYPosition = function(){
	return window.pageYOffset != null ? 
		window.pageYOffset : 
			document.documentElement && document.documentElement.scrollTop ?
				document.documentElement.scrollTop : document.body != null ? 
					document.body.scrollTop : null;
}

// ---------------------------------------------------------------------------
// pageWidth()
//  Calculates page width.
// ---------------------------------------------------------------------------
WorkAreaLibrary.pageWidth = function(){
	return window.innerWidth != null ? 
		window.innerWidth : 
			document.documentElement && document.documentElement.clientWidth ? 
				document.documentElement.clientWidth : document.body != null ? 
					document.body.clientWidth : null;

}

// -------------------------------------------------------------------
// isNumeric(element, decimal)
//  
// -------------------------------------------------------------------
WorkAreaLibrary.isNumeric = function(element, decimal){
	var numericExpression = "";
	if(decimal){
		numericExpression = /^[0-9\.]+$/;
	}
	else{
		numericExpression = /^[0-9]+$/;
	}

	if(element.value.match(numericExpression)){
		return true;
	}else{
		return false;
	}
}

// -------------------------------------------------------------------
// removeItemFromString(originalArray, itemToRemove)
// 
// -------------------------------------------------------------------
WorkAreaLibrary.removeItemFromString = function(originalArray, itemToRemove) {	
	var j = 0;	
	var outPut = '';
	
	while (j < originalArray.length) {	
		
		if (originalArray.charAt(j) != itemToRemove) {			
			outPut += originalArray.charAt(j);
		}
		
		j++; 
	}	
	
	return outPut;
}

// -------------------------------------------------------------------
// allowOnlyNumeric(id, decimal)
// 
// -------------------------------------------------------------------
WorkAreaLibrary.allowOnlyNumeric = function(id, decimal){
	element = getElement(id);

	if(!this.isNumeric(element, decimal)){
		element.value = element.value.substring(0, element.value.length - 1) 
	}
}

// -------------------------------------------------------------------
// changeFocus(currentId, nextId, characterCount)
//  This function changes the focus automatically after a specific number
//  of characters are typed in the current field.
// -------------------------------------------------------------------
WorkAreaLibrary.changeFocus = function(currentId, nextId, maxCount){
	var currentElement = getElement(currentId);
	var nextElement = getElement(nextId);
	
	this.allowOnlyNumeric(currentId);

	if(currentElement.value.length == maxCount){
		nextElement.focus();
	}
}

// -------------------------------------------------------------------
// selectAllOptions(list)
//  This function selects all options within a select box.
// -------------------------------------------------------------------
WorkAreaLibrary.selectAllOptions = function(list){
	var list = getElement(list);
	
	for (var i=0; i<list.options.length; i++) {
		list.options[i].selected = true;
	}
}

// -------------------------------------------------------------------
// removeAllOptions(list)
//  This function removes all options from a select box.
// -------------------------------------------------------------------
WorkAreaLibrary.removeAllOptionsFromElement = function(list){
	var list = getElement(list);
	
	this.removeAllOptions(list);
}

// -------------------------------------------------------------------
// setOptionSelected(list, value)
//  This function sets a given value as selected
// -------------------------------------------------------------------
WorkAreaLibrary.setOptionSelected = function(list, value){
	for(var i=0; i<list.options.length; i++){
		if(list.options[i].value == value){
			list.options[i].selected = true;
			list.selectedIndex = i;
			break;
		}
	}	
}

// -------------------------------------------------------------------
// converToCurrency(amount)
//  This function ensures two decimal values
// -------------------------------------------------------------------
WorkAreaLibrary.converToCurrency = function(amount){

	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

// -------------------------------------------------------------------
// calculateTax(amount, taxRate)
//  This function calculates the tax amount
// -------------------------------------------------------------------
WorkAreaLibrary.calculateTax = function(amount, taxRate){

	return Math.round((parseFloat(amount)*(parseFloat(taxRate)/100))*100)/100;
}

// -------------------------------------------------------------------
// removeSelectedOptions(list)
//  This function removes all selected options from a select box.
// -------------------------------------------------------------------
WorkAreaLibrary.removeSelectedOptions = function(list){
	var list = getElement(list);
	
	// If nothing is selected then exit function
	if(list.selectedIndex == -1){
		return;
	}
	
	for (var i=list.options.length-1; i>=0; i--) {	
		if (list.options[i].selected){
				list.options[i] = null;
		}	
	}
}

// -------------------------------------------------------------------
// copySelectedOptions(select_object,select_object[,autosort(true/false)])
//  This function copies options between select boxes instead of 
//  moving items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
WorkAreaLibrary.copySelectedOptions = function(from,to) {
	var options = new Object();
	if (WorkAreaLibrary.hasOptions(to)) {
		WorkAreaLibrary.removeAllOptions(to);	
	}
	if (!WorkAreaLibrary.hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		
		if (options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text) {
				to.options[i] = new Option( o.text, o.value, false, false);
		}	
	}
	

	to.selectedIndex = 0;	
}

// -------------------------------------------------------------------
// addSelectOption(value, text)
//  This function adds new options to a select box
// -------------------------------------------------------------------
WorkAreaLibrary.addSelectOption = function(selectBox, value, text) {
	if (value != null && value != "undefined" && text != null) {
		var index = selectBox.options.length;
			
		selectBox.options[index] = new Option( text, value, false, false);
	}	

	selectBox.selectedIndex = 0;
}

// -------------------------------------------------------------------
// getStatusText(aStatus)
//  This function gets the correct status depending on the language
// -------------------------------------------------------------------
WorkAreaLibrary.getStatusText = function(aStatus){
	var status = "";
	
	if(language == "french"){
	
		switch(aStatus){
			case "Requested":
				status = "Demandé";
				break;
			case "Scheduled":
				status = "Réservé";
				break;
			case "Confirmed":
				status = "Confirmé";
				break;
			case "Attended":
				status = "Assisté";
				break;
			case "No Show":
				status = "Non Assisté";
				break;
			case "Cancelled":
				status = "Annulé";
				break;
		}
	}
	else{
		status = aStatus;
	}
	
	return status;
}

// -------------------------------------------------------------------
// hasOptions(obj)
//  Utility function to determine if a select object has an options array
// -------------------------------------------------------------------
WorkAreaLibrary.hasOptions = function(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
}

// -------------------------------------------------------------------
// removeAllOptions(select_object)
//  Remove all options from a list
// -------------------------------------------------------------------
WorkAreaLibrary.removeAllOptions = function(from) { 
	if (!WorkAreaLibrary.hasOptions(from)) { return; }
	for (var i=(from.options.length-1); i>=0; i--) { 
		from.options[i] = null; 
		} 
	from.selectedIndex = -1;
} 

// -------------------------------------------------------------------
// emailValidator()
//  This function evaluates the validity of the email's syntax. 
// -------------------------------------------------------------------
WorkAreaLibrary.emailValidator = function(str) {

	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var domain = str.substr(lat+1,lstr-1);
	var ldot= domain.indexOf(dot);
	
	if (str.indexOf(at)==-1){   
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    return false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    return false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
	    return false;
	 }
	 
	 if (ldot == -1){
	    return false;
	 }

	 if (domain.substr(ldot+1, domain.length -1).length < 2){
	    return false;
	 }


	return true;					
}