var xsite = null;
$(function() {
  xsite = this;
  this.load = function (selector, url, callback) {
	$(selector).html('<div style="margin:20px 0px;text-align:center;"><img src="images/ajax-loader-indicator.gif"></div>');
	$(selector).load(url, callback);
  }
  
  this.createDialog = function (options) {
	this.createModalDialog(options);
  }

  this.createModalDialog = function (options) {
	var options = options || {};
	var windowName = options.windowName || 'win' + this.getUUID();
	var title = options.title || 'untitled';
	var width = options.width || 300;
	var height = options.height || 'auto';
	var position = options.position || 'center';
	var openCallback = options.openCallback || null; //callback function after dialog is opened
	var url = options.url || '';
	var urlCallback = options.urlCallback || null; //callback function after url is loaded
	var html = options.html || '';
	var buttons = options.buttons || {};
	
	$("#" + windowName).unbind();//VERY IMPORTANT. This is to prevent events from binding multiple times and eventually cause browser crash
	
	var modal = true;
	if (options.modal && (options.modal=="No" || options.modal=="no")) modal=false;

	if ($("#" + windowName).length == 0) {
	  $("body").append('<div id="' + windowName + '"></div>');	
	}
	
	var parent = this;
	
	if (url != "") {
	  $("#" + windowName).bind('dialogopen', function(event, ui) {
		parent.load(this, url, urlCallback); 
	  });
	} else {
	  $("#" + windowName).html('<br />' + html);
	}
	
	$("#" + windowName).dialog({
	  title: title,
	  bgiframe: true,
	  dialogClass: 'dialog',
	  autoOpen: false,
	  width: width,
	  height: height,
	  position: position,
	  modal: modal,
	  buttons: buttons,
	  show: 'blind',
	  hide: 'blind'
	});
	
	if (position == "center-up") {
	  var bodyWidth=$("body").width();
	  var left = Math.ceil((bodyWidth - width)/2);
	  if (left < 0) left = 0;
	  $("#" + windowName).dialog('option', 'position', [left, 50]);
	}
	
	if (openCallback) $("#" + windowName).dialog('option', 'open', openCallback);	
	
	return $("#" + windowName);  
  }
	
  this.showWaitingDialog = function (options) {
	var html = '<div style="margin:20px 0px;text-align:center;">Please wait...<br /><br /><img src="images/ajax-loader-indicator.gif"></div>';  
	
	if ($("#waitingDialog").length == 0) {
	  $("body").append('<div id="waitingDialog">'+ html + '</div>');
	} else {
	  $("#waitingDialog").html(html);
	}
	
	var options = options || {};
	var width = options.width || 300;
	var height = options.height || 120;
	var position = options.position || 'center';
	var openCallback = options.openCallback || null; //callback function after dialog is opened
	
	var modal = true;
	if (options.modal && (options.modal=="No" || options.modal=="no")) modal=false;
	
	$("#waitingDialog").unbind();//VERY IMPORTANT. This is to prevent events from binding multiple times and eventually cause browser crash
	$("#waitingDialog").dialog({
	  bgiframe: true,
	  dialogClass: 'dialog',
	  autoOpen: false,
	  closeOnEscape: false,
	  stack: true,
	  minHeight: 120,
	  width: width,
	  height: height,
	  position: position,
	  modal: modal
	});
	  
	$("#waitingDialog").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();
	
	if (openCallback) $("#waitingDialog").dialog('option', 'open', openCallback);
	$("#waitingDialog").dialog({stack: true}).dialog('open');
  } 
  
  this.addMessageToWaitingDialog = function (msg) {
	if ($("#waitingDialog").length > 0) {
	  $("#waitingDialog").append(msg);  
	}
  }
  
  this.closeWaitingDialog = function () {
	$("#waitingDialog").dialog('close');
  }
  
  this.showAlertDialog = function (alertMsg) {
	var html = '' +
	  '<div class="ui-widget">' +
	  '	<div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">' +
	  '		<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>' + alertMsg + '</p>' +
	  '	</div>' +
	  '</div>';
	  
	if ($("#alertDialog").length == 0) {
	  $("body").append('<div id="alertDialog">'+ html + '</div>');	
	}
	
	$("#alertDialog").unbind();//VERY IMPORTANT. This is to prevent events from binding multiple times and eventually cause browser crash
	$("#alertDialog").dialog({
	  bgiframe: true,
	  dialogClass: 'dialog',
	  autoOpen: false,
	  closeOnEscape: false,
	  stack: true,
	  minHeight: 100,
	  width: 300,
	  height: 'auto',
	  modal: true,
	  buttons: {' OK ': function() { $(this).dialog('close'); }},
	  show: 'blind',
	  hide: 'blind'
	});
	  
	$("#alertDialog").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();
	$("#alertDialog").dialog('open').dialog('moveToTop');
  }
	
  this.showInformationDialog = function (infoMsg) {
	var html = '' +
	  '<div class="ui-widget">' +
	  '	<div class="ui-state-highlight ui-corner-all" style="padding: 0 .7em;">' +
	  '		<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>' + infoMsg + '</p>' +
	  '	</div>' +
	  '</div>';
	  
	if ($("#informationDialog").length == 0) {
	  $("body").append('<div id="informationDialog">'+ html + '</div>');	
	}
	
	$("#informationDialog").unbind();//VERY IMPORTANT. This is to prevent events from binding multiple times and eventually cause browser crash
	$("#informationDialog").dialog({
	  bgiframe: true,
	  dialogClass: 'dialog',
	  autoOpen: false,
	  closeOnEscape: false,
	  stack: true,
	  minHeight: 100,
	  width: 300,
	  height: 'auto',
	  modal: true,
	  buttons: {' OK ': function() { $(this).dialog('close'); }},
	  show: 'blind',
	  hide: 'blind'
	});
	  
	$("#informationDialog").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();
	$("#informationDialog").dialog('open');
  }
	
  this.resetCheckBoxes = function (clickedCheckbox) {
	var form = clickedCheckbox.form;
	var checkbox = form[clickedCheckbox.name];
	if (!checkbox.length) return;  
	for (var i = 0; i < checkbox.length; i++) if (clickedCheckbox!=checkbox[i]) checkbox[i].checked = false;  
  }
  
  this.checkAllBoxes = function (fieldObj) {
	if (fieldObj.length) {
	  for (var i = 0; i < fieldObj.length; i++) fieldObj[i].checked = true;
	} else {
	  fieldObj.checked = true;
	}
  }
  
  this.uncheckAllBoxes = function (fieldObj) {
	if (fieldObj.length) {
	  for (var i = 0; i < fieldObj.length; i++) fieldObj[i].checked = false;
	} else {
	  fieldObj.checked = false;
	}
  }
  
  this.getCheckedValue = function (fieldObj) {
	var checkedValue = null;
	if (fieldObj.length) {
	  for (var i = 0; i < fieldObj.length; i++) {
		if (fieldObj[i].checked) {
		  if (checkedValue) checkedValue = checkedValue + ',' + fieldObj[i].value;
		  else checkedValue = fieldObj[i].value;
		}
	  }
	} else {
	  if (fieldObj.checked) checkedValue = fieldObj.value;
	}
	return checkedValue;
  }
  
  this.getSelectedValue = function (fieldObj) {
	var selectedValue = null;
	if (fieldObj.length) {
	  for (var i = 0; i < fieldObj.length; i++) {
		if (fieldObj[i].selected) {
		  if (selectedValue) selectedValue = selectedValue + ',' + fieldObj.options[i].value;
		  else selectedValue = fieldObj.options[i].value;
		}
	  }
	}
  
	return selectedValue;
  }
  
  this.getFormFieldValue = function (fieldObj) {
	var returnedValue = null;
	var fieldType = null;
  
	if (fieldObj.type) fieldType = fieldObj.type;
	else if (fieldObj.length) fieldType = fieldObj[0].type;
  
	switch(fieldType) {
	  case 'text': case 'textarea': case 'hidden':
		returnedValue = fieldObj.value;
		break;    
	  case 'checkbox': case 'radio':
		returnedValue = this.getCheckedValue(fieldObj);
		break;
	  case 'select-one': case 'select-multiple':
		returnedValue = this.getSelectedValue(fieldObj);
		break;	
	  default:
		break;
	}
	return returnedValue;
  }
  
  this.clearFormField = function (formName, fieldName) {
	document[formName][fieldName].value = "";
  }
  
  this.clearTextNode = function (elementID) {
	if (document.getElementById(elementID)) document.getElementById(elementID).innerHTML="";
  }
  
  this.toggle = function (elementID, dependentCheckbox, reversed) {
	//dependentCheckbox is a checkbox object
	//if dependentCheckbox is provided then the visibility of the element depends on the status of the checkbox - display when checked
	//if 'reversed' is provided and its value is 'true' then hide when checked
	var elementObj =   document.getElementById(elementID);
	
	if (elementObj && elementObj.style && elementObj.style.display) {
	  if (!dependentCheckbox) {
	    if (elementObj.style.display == "none") elementObj.style.display = "block";
	    else elementObj.style.display = "none";
	  } else {
		if (reversed) {//hide when checked
		  if (dependentCheckbox.checked) elementObj.style.display = "none";
		  else elementObj.style.display = "block";
		} else {//show when checked
		  if (dependentCheckbox.checked) elementObj.style.display = "block";
		  else elementObj.style.display = "none";
		}
	  }
	}
  }
  
  this.showSubMenu = function(menuID, objClicked) {
	var subMenuObj = document.getElementById(menuID);
	if (!subMenuObj) return;
	if (subMenuObj.style.display == "block") {
	  subMenuObj.style.display = "none";
	  return;
	}
	var pos = findPosition(objClicked);
	var x = pos[0];
	var y = pos[1] + objClicked.offsetHeight + 1;
	  
	if (subMenuObj) {
	  subMenuObj.style.left = x + "px";
	  subMenuObj.style.top = y + "px";
	  subMenuObj.style.display = "block";
	}
  }

  this.hideSubMenu = function (menuID) {
	var subMenuObj = document.getElementById(menuID);
	if (!subMenuObj) return;
	subMenuObj.style.display = "none";
  }

  function findPosition(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
  }
  
  this.checkFileName = function (fileName) {
	var pattern=/^[0-9a-z_\-\.]*\.[0-9a-z_\-]+$/i;
	return pattern.test(fileName);
  }
  
  this.checkDirectoryName = function (dirName) {
	var pattern=/^[0-9a-z_]+[0-9a-z_\-\.]*$/i;
	return pattern.test(dirName);
  }
  
  this.getFileFromPath = function(filePath) {
	var divider="/";
	if (filePath.indexOf("\\") != -1) divider="\\";
	var parts = filePath.split(divider);
	return (parts[parts.length-1]);  
  }
  
  this.getURLParameter = function (name) {
    var paraName = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+paraName+"=([^&#]*)"; 
    var regex = new RegExp( regexS );
    var results = regex.exec(window.location.href);
    if( results == null )
      return "";
    else
      return results[1];
  }
  
  this.checkemail = function(str) {
	return this.checkEmail(str);
  }
  
  this.checkEmail = function(str) {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(str); 
  }
  
  this.checkInteger = function(str) {
	if (str == "0") return true;
	var pattern=/^[0-9]+[0-9]*$/i;
	return pattern.test(str);  
  }
  
  this.checkDigits = function(str) {
    var pattern=/^[0-9]+$/i;
	return pattern.test(str);
  }
  
  this.checkDate = function(str) {
	var dateParts = new Array();
	dateParts = str.split("/");
	if (dateParts.length != 3) return false;
	if (!this.checkDigits(dateParts[0]) || !this.checkDigits(dateParts[1]) || !this.checkDigits(dateParts[2])) return false;
	if (dateParts[0].length > 2 || dateParts[1].length > 2 || dateParts[2].length != 4) return false;
	if (parseFloat(dateParts[0]) < 0 || parseFloat(dateParts[0]) > 12) return false;
	if (parseFloat(dateParts[1]) < 0 || parseFloat(dateParts[1]) > 31) return false;
	return true;
  }
  
  this.checkNumber = function (str) {
	var start_format = " .+-0123456789";
	var number_format = " .0123456789";
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;
	
    if(str.length == 0) return false;

	check_char = start_format.indexOf(str.charAt(0));

	if (check_char == 1) decimal = true;
	else if (check_char < 1) return false;

	for (var i = 1; i < str.length; i++) {
	  check_char = number_format.indexOf(str.charAt(i));
	  if (check_char < 0) return false;
	  else if (check_char == 1) {
	    if (decimal) return false;
		else decimal = true;
	  }	else if (check_char == 0) {
	    if (decimal || digits) trailing_blank = true;
	  } else if (trailing_blank) return false;
	  else digits = true;
	}	

	return true;
  }
  
  this.checkPhone = function (str) {
    if (str.length == 0) return false;	

	return checkregex(str, /^(((1))?[ ,\-,\.]?([\\(]?([1-9][0-9]{2})[\\)]?))?[ ,\-,\.]?([^0-1]){1}([0-9]){2}[ ,\-,\.]?([0-9]){4}(( )((x){0,1}([0-9]){1,5}){0,1})?$/);
  }
  
  this.checkSSN = function (str) {
    if (str.length == 0) return false;

	return checkregex(str, /^[0-9]{3}(-| )[0-9]{2}(-| )[0-9]{4}$/);
  }


  this.openwindow = function (url, winname, w, h) {
	this.openWindow (url, winname, w, h);
  }
  
  this.openWindow = function (url, winname, w, h) {
	var nScrW = 800;
	var nScrH = 600;
	if (screen) {
	  nScrW = screen.availWidth;
	  nScrH = screen.availHeight;
	}
	var leftPos = (nScrW-w)/2;
	var topPos = (nScrH-h)/2;
	window.open (url, winname, 'width=' + w + ',height=' + h + ',menu=no,toolbars=no,status=yes,scrollbars=yes,resizable=yes,top=' + topPos + ',left=' + leftPos);
	return;  
  }
  
  this.getUUID = function () {
	return (new Date()).getTime();
  }
  
    this.displayDialogue = function (objName, useInnerHTML) {
	if (!useInnerHTML) {
		var scrollBarWidth = 25; //assuming scroll bar is this wide
		var diaObj = document.getElementById(objName);
		if (diaObj && diaObj.style) {
		  var dialogueBoxW=parseInt(diaObj.style.width);
		  var dialogueBoxH=parseInt(diaObj.style.height);		
			
		  var innerXY = GetInnerSize();
		  
		  var leftPos = Math.ceil((innerXY[0]-dialogueBoxW)/2);
		  var topPos = Math.ceil((innerXY[1]-dialogueBoxH)/2);
		  
		  diaObj.style.position="fixed";
		  diaObj.style.zIndex = 1000;
		  diaObj.style.display = "block";
		  diaObj.style.left = leftPos+"px";
		  diaObj.style.top = topPos+"px";
		  grayOut(true);
		}
	} else {
		var diaObj = document.getElementById(objName);
		if (diaObj && diaObj.style) {
		  var htmlCodes = diaObj.innerHTML;
		  var dialogueBoxW=parseInt(diaObj.style.width);
		  var dialogueBoxH=parseInt(diaObj.style.height);
		  this.displayHTMLDialogue(htmlCodes, dialogueBoxW, dialogueBoxH);		  
		}
	}
  }
  
  this.closeDialogue = function (objName) {
    var diaObj = document.getElementById(objName);
	if (diaObj && diaObj.style) {
      diaObj.style.display = "none";
	  grayOut (false);
    }
  }
  
  this.displayHTMLDialogue = function (htmlCodes, boxWidth, boxHeight) {
    //var closeCommandHTML = '<p align="right"><a href="javascript:xsite.closeHTMLDialogue()"><img src="images/icon_cancel.gif" border="0" alt="Close window" /></a></p>';
	var innerXY = GetInnerSize();
	  
	var leftPos = Math.ceil((innerXY[0]-boxWidth)/2);
    var topPos = Math.ceil((innerXY[1]-boxHeight)/2);
	
    var dialogueObj = document.getElementById("HTMLDialogueObj");
    if (dialogueObj && dialogueObj.style) {
	  dialogueObj.style.top=topPos+'px';
	  dialogueObj.style.left=leftPos+'px';
	  dialogueObj.style.width=boxWidth+"px";
	  dialogueObj.style.height=boxHeight+"px";	
	  //dialogueObj.innerHTML = closeCommandHTML + htmlCodes;
	  dialogueObj.innerHTML = htmlCodes;
	  dialogueObj.style.display="block";
	} else {
	  var tbody = document.getElementsByTagName("body")[0];
	  var tnode = document.createElement('div');
	  tnode.style.position='absolute';						
	  tnode.style.top=topPos+'px';
	  tnode.style.left=leftPos+'px';
	  tnode.style.width=boxWidth+"px";
	  tnode.style.height=boxHeight+"px";
	  tnode.id='HTMLDialogueObj';
	  tnode.style.backgroundColor="#ffffff";
	  tnode.style.paddingTop="0px";
	  tnode.style.paddingRight="0px";
	  tnode.style.paddingBottom="0px";
	  tnode.style.paddingLeft="0px";
	  //tnode.innerHTML = closeCommandHTML + htmlCodes;
	  tnode.innerHTML = htmlCodes;

	  tbody.appendChild(tnode);
	  tnode.style.zIndex=1000;
	  tnode.style.display='block';	  
	}
	grayOut(true);
  }
  
  this.closeHTMLDialogue = function () {
    var dialogueObj = document.getElementById("HTMLDialogueObj");
	if (dialogueObj && dialogueObj.style) dialogueObj.style.display="none";
	grayOut(false);
  }
  
  function grayOut(vis, options) {
    // Pass true to gray out screen, false to ungray
	// options are optional.  This is a JSON object with the following (optional) properties
	// opacity:0-100		// Lower number = less grayout higher = more of a blackout
	// zindex: #			// HTML elements with a higher zindex appear on top of the gray out
	// bgcolor: (#xxxxxx)	// Standard RGB Hex color code
	// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
	// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
	// in any order.  Pass only the properties you need to set.
	scroll(0,0);
	var options = options || {};
	var zindex = options.zindex || 50; 
	var opacity = options.opacity || 60; 
	var opaque = (opacity / 100);
	var bgcolor = options.bgcolor || '#999999';
	var dark=document.getElementById('darkenScreenObject');
	
	if (!dark) {
	  // The dark layer doesn't exist, it's never been created.  So we'll
	  // create it here and apply some basic styles.
	  // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917	  
	  var tbody = document.getElementsByTagName("body")[0];
	  var tnode = document.createElement('div');			// Create the layer.
	  tnode.style.position='absolute';						// Position absolutely
	  tnode.style.top='0px';								// In the top
	  tnode.style.left='0px';								// Left corner of the page
	  tnode.style.overflow='hidden';						// Try to avoid making scroll bars
	  tnode.style.display='none';							// Start out Hidden
	  tnode.id='darkenScreenObject';						// Name it so we can find it later
	  tbody.appendChild(tnode);								// Add it to the web page
	  dark=document.getElementById('darkenScreenObject');	// Get the object.
	}
	
	if (vis) {
	  // Calculate the page width and height
	  var screenW = 0;
	  var screenH = 0;
	  if (screen) {
    	screenW = screen.availWidth;
   		screenH = screen.availHeight;
  	  }
	  
	  var scrollBarWidth = 25; //assuming scroll bar is this wide
	  
	  
	  if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
	    if (document.body.scrollWidth < screenW) var pageWidth = (screenW - scrollBarWidth) +'px';
		else var pageWidth = document.body.scrollWidth+'px';
		
		if (document.body.scrollHeight  < screenH) var pageHeight = screenH+'px';
		else var pageHeight = document.body.scrollHeight+'px';		
	  } else if( document.body.offsetWidth ) {
	    if (document.body.offsetWidth < screenW) var pageWidth = (screenW - scrollBarWidth)+'px';
		else var pageWidth = document.body.offsetWidth+'px';
		
		if (document.body.offsetHeight < screenH) var pageHeight = screenH+'px';
		else var pageHeight = document.body.offsetHeight+'px';		
	  } else {
	    var pageWidth='100%';
		var pageHeight='100%';
	  }
  
	  //set the shader to cover the entire page and make it visible.
	  dark.style.opacity=opaque;
	  dark.style.MozOpacity=opaque;
	  dark.style.filter='alpha(opacity='+opacity+')';
	  dark.style.zIndex=zindex;
	  dark.style.backgroundColor=bgcolor;
	  dark.style.width= pageWidth;
	  dark.style.height= pageHeight;
	  dark.style.display='block';
	} else {
	  dark.style.display='none';
	}
  }
  
  function GetInnerSize () {
	var x,y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return [x,y];
  }
  
  function checkregex(str, regexPattern) {
    if (str.length == 0) return false;
	return regexPattern.test(str);
  }
});

