var needToConfirmWhenLeavingPage = true;  
var originalFormValues = '';
var disableAllForms = false;

window.onload = saveOriginalFormValues;
window.onbeforeunload = confirmExit;

//Prototype Windows overlay effects
Windows.overlayShowEffectOptions = {duration: 0.3};
Windows.overlayHideEffectOptions = {duration: 0.3};
var fadeAndAppearDuration = 0.3;

function confirmDeletion()
{
  return confirm('Are you sure you want to delete this record?');
}

function confirmRemoval()
{
  return confirm('Are you sure you want to remove this record?');
}

function saveOriginalFormValues()
{
	//If there's a form called theForm, save it's values and check them before the page is unloaded
	if($('theForm'))
	{
	  originalFormValues = $('theForm').serialize();
	}
}
  
function confirmExit()
{
	//If there's a form called theForm, save it's values and check them before the page is unloaded
	if($('theForm'))
	{
	  if (needToConfirmWhenLeavingPage && formHasChanged($('theForm')))
	  {
		  return "You have made changes, and have not saved them yet.";
	  }
	}
}
  
function formHasChanged(form)
{
   return originalFormValues != form.serialize();
}

function tryDelete()
{
    var url= "delete.rails";
    var params = $("theForm").serialize();
    
    $('Spinner').style.display = 'inline';

    new Ajax.Request(url, {
        method: 'post',
        evalScripts: true,
        parameters: params,
        onComplete: function() { 
			$('Spinner').style.display = 'none';
		}
    });
}

function redirect(url)
{
	window.location = siteRoot + '/' + url;
};

function redirectToCloseURL()
{
	window.location = $('closeLink').href;
};

function trySave()
{
    trySaveWithUrl("save.rails");
}

function trySaveWithUrl(url) {

    hideMessage();
  if(prototypeValidators['theForm'].validate())
  {
    var params = $("theForm").serialize();
    $('Spinner').style.display = 'inline';

    new Ajax.Request(url, {
        method: 'post',
        evalScripts: true,
        parameters: params,
        onComplete: function() { 
			$('Spinner').style.display = 'none';
		}
    });
  } 
  else
  {
	showFailedSave();
  }
}



function showSuccessfulSave()
{ 
	var msg = "Record saved.";
	showSuccessfulSaveMessage(msg);
}

function showSuccessfulSaveMessage(message)
{ 
    showMessage(message, 'success');
   	//openInfoDialog(message);
}

function showFailedSave()
{
   var msg = "The record could not be saved.  Please check fields marked with ";
   msg += ErrorIconImageTag();
   showFailedSaveMessage(msg);
}

function ErrorIconImageTag()
{
  return "<img src=\"" + siteRoot + "/content/images/error.gif\" style=\"padding:0px; margin:0px; border-width:0px; background-color:inherit; vertical-align:middle;\" />";
}  

function showFailedSaveMessage(message)
{
	showMessage(message, 'error');
}


function showMessage(message, cssClass)
{ 
    var delayBeforeAppear = 0;
    
	if($('message').style.display != 'none')
	{
		new Effect.Fade('message', {duration: fadeAndAppearDuration , afterFinish: function(obj) {
			    $('message').className = cssClass;
				$('message').innerHTML = message;
				new Effect.Appear('message', { duration: fadeAndAppearDuration });
		}});
	}
	else
	{
	    $('message').className = cssClass;
		$('message').innerHTML = message;
		new Effect.Appear('message', { duration: fadeAndAppearDuration });
	}
}

function hideMessage()
{
	if($('message').style.display != 'none')
	{
		new Effect.Fade('message', {duration: fadeAndAppearDuration });
	}
}

function showSuccessfulSaveOnDialog(formName, message) {
    if (typeof message == 'undefined')
        message = 'The record has been saved.';
    showMessage(formName + 'Message', message, 'dialogSuccess');
}

function showFailedSaveOnDialog(formName, message) {
    if (typeof message == 'undefined')
        message = "The record could not be saved.  Please check fields marked with " + ErrorIconImageTag();
    showMessage(message, 'dialogError');
}

function showWarningOnDialog(formName, message) {
    if (typeof message != 'undefined')
        showMessage(formName + 'Message', message, 'dialogWarning');
}


//DialogProperties is a class
function DialogProperties(Width, DialogType) {
    this.className = "spread";
    this.width = Width;
    this.showEffectOptions = { duration: 0.3 };
    this.hideEffectOptions = { duration: 0.3 };

    if (DialogType == "alert") {
        this.okLabel = "Close";
        this.onOk = function(win) {
            Dialog.closeInfo();
        }
    }

    if (DialogType == "confirm") {
        this.okLabel = "Save";
        this.cancelLabel = "Cancel";
    }

    if (DialogType == "search") {
        this.okLabel = "Search";
        this.cancelLabel = "Cancel";
    }

    if (DialogType == "repeater") {
        this.okLabel = "Save/Close";
        this.repeatLabel = "Save/New";
        this.cancelLabel = "Cancel";
    }

}

/* Journal methods from Club Nova */

function showForm(url, id) {
    showFormWithParams(url, 'id=' + id);
}

function showFormWithParams(url, params) {
    loadForm(siteRoot + '/' + url, params);
}

function loadForm(url, params) {
    // Retrieve a form for record entry, and show it.
    $('Spinner').style.display = 'inline';
    new Ajax.Request(url, {
        method: 'post',
        evalScripts: true,
        parameters: params,
        onComplete: function() {
            $('Spinner').style.display = 'none';
            showRetrievedForm();
        }
    });
}

function showRetrievedForm() {
    if (typeof formName == 'undefined') { alert('Form name must be set using page.Assign'); }
    if (typeof formWidth == 'undefined') { alert('Form width must be set using page.Assign'); }
    if (typeof formType == 'undefined') { formType = 'confirm'; }

    if ($(formName).hasClassName('disabled')) {
        dialogProperties = new DialogProperties(formWidth, 'alert');
        Dialog.alert($(formName + 'Container').innerHTML, dialogProperties);
    }
    else {
        dialogProperties = new DialogProperties(formWidth, formType);
        dialogProperties.onOk = function(win) {
            if (prototypeValidators[formName].validate())
                saveForm(false);
            else
                showFailedSaveOnDialog(formName);
        }
        if (formType == 'confirm') {
            Dialog.confirm($(formName + 'Container').innerHTML, dialogProperties);
        }
        else if (formType == 'repeater') {
            dialogProperties.onRepeat = function(win) {
                if (prototypeValidators[formName].validate())
                    saveForm(true);
                else
                    showFailedSaveOnDialog(formName);
            }
            Dialog.repeater($(formName + 'Container').innerHTML, dialogProperties);
        }
        else {
            alert('The form type ' + formType + ' is not valid.');
        }
    }

}

function saveForm(isRepeating) {
    var url = siteRoot + "/" + saveFormURL;
    var params = $(formName).serialize();

    if (params != "")
        params += "&"
    params += "isRepeating=" + isRepeating;

    $('Spinner').style.display = 'inline';

    new Ajax.Request(url, {
        method: 'post',
        evalScripts: true,
        parameters: params,
        onComplete: function() {
            $('Spinner').style.display = 'none';
        }
    });

}

function closeForm() {
    Dialog.closeInfo();
}


/*********************************/





/*************************************  JS for SubLists ***************************/
function CallURL (url) {
    CallURLWithParams(url, '');
}

function CallURLWithID (url, id) {
	params = 'id=' + id;
    CallURLWithParams(url, params);
}

function CallURLWithParentChildIDs (url, parentID, childID) {
	params = 'parentID=' + parentID
		+ '&childID= ' + childID;
    CallURLWithParams(url, params);
}

function CallURLWithParams (url, params) {
	url = siteRoot + '/' + url;
    $('Spinner').style.display = 'inline';
    new Ajax.Request(url, {
        method: 'post',
        evalScripts: true,
        parameters: params,
        onComplete: function() { 
			$('Spinner').style.display = 'none';
		}
	    });
}

function ShowForm (url, id) {
    ShowFormWithParams(url, 'id=' + id);
}

function ShowFormWithParams (url, params) {
    LoadForm(siteRoot + '/' + url, params);
}

function LoadForm (url, params) {
    $('Spinner').style.display = 'inline';
    new Ajax.Request(url, {
        method: 'post',
        evalScripts: true,
        parameters: params,
        onComplete: function() { 
			$('Spinner').style.display = 'none';
			ShowRetrievedForm(formName);
		}
	    });
}

var formSaveBlocked = new $H({});
function ShowRetrievedForm (formName) {
		var dialogWidth = 360;
		var form = $(formName);
		if(form.hasClassName('450WideDialog')) dialogWidth = 450;
		if(form.hasClassName('500WideDialog')) dialogWidth = 500;
		if(form.hasClassName('600WideDialog')) dialogWidth = 600;
		if(form.hasClassName('750WideDialog')) dialogWidth = 750;

		if(disableAllForms)
		{
		  form.disable();
		  form.addClassName('disabled');
		}		

		if(form.hasClassName('disabled') || form.hasClassName('showCloseButtonOnlyOnDialog'))
		{
			var dialogProperties = new DialogProperties(dialogWidth, 'alert');    
			Dialog.alert($(formName + 'Container').innerHTML, dialogProperties);
		}
		else 
		{
			dialogProperties = new DialogProperties(dialogWidth, 'confirm');    
			dialogProperties.onOk = function(win){ 
			    if(formSaveBlocked && formSaveBlocked.keys().size() > 0)
			    {
					var stillOccuring = '';
					formSaveBlocked.values().each(function(value){stillOccuring += '\n\n - ' + value; })
					alert('Please wait for the current processing to complete, and then try saving again.  The following is still occuring: ' + stillOccuring);
				}
				else
				{	
					if(prototypeValidators[formName].validate())
					{
						SaveForm();
						Dialog.closeInfo();
					}
					else
					{
						alert ('Please check your entry.');
					}
				}
			}

			Dialog.confirm($(formName + 'Container').innerHTML, dialogProperties);
		}
}

function SaveForm () {
  if(prototypeValidators[formName].validate())
  {
    var url= siteRoot + '/' + saveFormURL;
    var params = $(formName).serialize();
    
    $('Spinner').style.display = 'inline';

    new Ajax.Request(url, {
        method: 'post',
        evalScripts: true,
        parameters: params,
        onComplete: function() { 
			$('Spinner').style.display = 'none';
		}
    });
  } 
  else
  {
	showFailedSave();
  }
}


function removeRemoveLink(id) {
  if($('removeLink-'+id)) 
  {
	$('removeLink-'+id).remove();
  }
}

/*************************************  FormHelper helper methods ***************************/
/*************************************  Copied from Monorail source FormHelper.resx ***************************/

function monorail_formhelper_numberonly(e, exceptions, forbidalso)
{
	exceptions = exceptions.concat([8,9,13,38,39,40,46]);
	var code = e.charCode;
	if (!code) code = e.keyCode;
	if ((e.ctrlKey && code == 118) || (e.ctrlKey && code == 122))
	{
		return false;
	}
	if (e.ctrlKey || e.altKey) return true;
	for(var i=0; i < forbidalso.length; i++) if (forbidalso[i] == code) return false;
	for(var i=0; i < exceptions.length; i++) if (exceptions[i] == code) return true;
	if (code <= 47 || code > 57) return false;
	return true; 
}

// *********************** Functions for limiting length on a TextArea
//  To use these, add the following to the Text Area
//  onkeypress='return enforceMaxLength(event, 1000);', onchange='enforceMaxLengthAndWarn(event, 1000)'
//  where 1000 is the max length

function enforceMaxLength(event, maxlength)
{
	// if arrow/home/tab key then return true
	var code = event.charCode;
	if (!code) code = event.keyCode;
	
	switch(code) {
	   case Event.KEY_TAB:
	   case Event.KEY_LEFT:
	   case Event.KEY_RIGHT:
	   case Event.KEY_UP:
	   case Event.KEY_DOWN:
	   case Event.KEY_BACKSPACE:
	   case Event.KEY_HOME:
	   case Event.KEY_DELETE:
	   case Event.KEY_END:
	   case Event.KEY_PAGEUP:
	   case Event.KEY_PAGEDOWN:
			return true;
	}

	if(Event.element(event).value.length >= maxlength)
	{
	  Event.element(event).value = Event.element(event).value.substring(0,maxlength); 
	  return false;
	}
}

function enforceMaxLengthAndWarn(event, maxlength)
{
	if(Event.element(event).value.length > maxlength)
	{
	  Event.element(event).value = Event.element(event).value.substring(0,maxlength); 
	  alert('The information you have just entered was longer than the maximum limit of ' + maxlength + ' characters and has been automatically shortened.');
	}
}


/*************************************  UnClear and NA click handlers for Questions ***************************/

  function UnClearClick(questionID)
  {
    if($('question-' + questionID + '-Unclear').checked)
    {
		//Set value of answer to ""
		$('question-' + questionID).value = '';
		//Disable answer
		$('question-' + questionID).disabled = true;
		//Disable NA if it's shown
		if($('question-' + questionID + '-NA'))
		{
			$('question-' + questionID + '-NA').disabled = true;
		}
    }
    else
    {
		//Enable answer
		$('question-' + questionID).disabled = false;
		//Enable NA if it's shown
		if($('question-' + questionID + '-NA'))
		{
			$('question-' + questionID + '-NA').disabled = false;
		}
	}	
  }
  
  function NAClick(questionID)
  {
    if($('question-' + questionID + '-NA').checked)
    {
		//Set value of answer to ""
		$('question-' + questionID).value = '';
		//Disable answer
		$('question-' + questionID).disabled = true;
		//Disable Unclear if it's shown
		if($('question-' + questionID + '-Unclear'))
		{
			$('question-' + questionID + '-Unclear').disabled = true;
		}
    }
    else
    {
		//Enable answer
		$('question-' + questionID).disabled = false;
		//Enable Unclear if it's shown
		if($('question-' + questionID + '-Unclear'))
		{
			$('question-' + questionID + '-Unclear').disabled = false;
		}
	}
  }

/*************************************  Handles Printing - called via AJAX result ***************************/

function OpenReportInNewWindow(windowName, isPublic)
{
	WindowObjectReference = null; 
	var controller
	if (isPublic)
	    controller = '/PublicReports'
	else
	    controller = '/Reports'
	    
    WindowObjectReference = window.open(siteRoot + controller + '/view.rails?unique=windowName', 'reportWindow', 'width=750,height=540,menubar=no,toolbar=no,resizable=yes,scrollbars=yes,status=yes,top=10,left=10');

	if(!WindowObjectReference) alert('It appears you have some sort of pop-up blocker which is stopping reports from appearing.');
}


/*************************************  Handles Document Downloads  ***************************/

function GetDocument(cohortID, documentName)
{
	var url= siteRoot + '/Administration/GetDocument.rails';
	var params = 'cohortID=' + cohortID + '&documentName=' + documentName;
	
	$('Spinner').style.display = 'inline';
	
	new Ajax.Request(url, {
		method: 'post',
		evalScripts: true,
		parameters: params,
		onComplete: function() { 
			$('Spinner').style.display = 'none';
		}
	});
}

function DownloadDocument(cohortID, documentName)
{
    var form = $('downloadForm')
    form.setAttribute('action', siteRoot + '/Administration/DownloadDocument.rails?cohortID=' + cohortID + '&documentName=' + documentName);
    form.submit();
}


/*************************************  For CQI Review Comments  ***************************/

	function AddCommentToDiscussion(discussionTextArea, commentSpan)
	{
		if(discussionTextArea.value == '') 
		{
			discussionTextArea.value = commentSpan.innerHTML;
		}
		else
		{
			discussionTextArea.value = discussionTextArea.getValue() + "\n\n" + commentSpan.innerHTML;
		}
	}


/*************************************  For Reports  ***************************/

function showFailedReport(message)
{
    if(typeof message == 'undefined') {
        message = "The report could not be generated.  Please check fields marked with ";
        message += "<img src=\"" + siteRoot + "/content/images/error.gif\" style=\"padding:0px; margin:0px; border-width:0px; background-color:inherit; vertical-align:middle;\" />";
    }
 showMessage(message, 'error');
}
 
function showEmptyReport(message)
{
   if(typeof message == 'undefined') 
        message = "No records were found for the selected report.";
   showMessage(message, 'warning');
}

function hideEmptyReportWarning()
{
	hideMessage();
}

