﻿var gWin;

function DeleteMessage( msgID ){
	if( confirm('Delete this message now?') ) {
		$('DeleteMessageID').value = msgID;
		document.MessageList.submit();
	}
}

function DeleteRow( dceID ) {
	if( confirm('Delete this childcare experience now?') ) {
		$('DeleteDetails').value = dceID;
		ignore = true;
		document.Childcare.submit();
	}	
	
	return false;
}

function ToggleChecklistItem( ciSpanID, applicationID, newStatus ) {
	new Ajax.Updater(
		'CI_' + ciSpanID,
		'components/UpdateChecklistItem.aspx?applicationid=' + applicationID + '&ci=' + ciSpanID + '&status=' + newStatus,
			{ onComplete:function show()
				{
					new Ajax.Updater( 'agencySiteActionBox', 'components/UpdateActionBox.aspx' );
				}
			}
		);
		
}

function ArchiveApplicant( applicationID ) {
	if( confirm('Are you sure you wish to archive this application?' ) ) {
		window.location = 'components/ArchiveApplicant.aspx?f=A&applicationID=' + applicationID;
	}
}

function ReinstateApplicant( applicationID ) {
	if( confirm('Are you sure you wish to reinstate this archived application?' ) ) {
		window.location = 'components/ArchiveApplicant.aspx?f=U&applicationID=' + applicationID;
	}
}

function ChangeInterviewer( applicationID ){
	DisplayDialogWindow( 'AssignInterviewer', true, applicationID, -1);
	return false;
}

function PopUpMakeComment( applicationID ){
	DisplayDialogWindow( 'MakeComment', true, applicationID, -1 );
	return false;
}

function SetReminder( applicationID ) {
	DisplayDialogWindow( 'CreateCalendarEvent', true, applicationID, -1 );
	return false;
}

function EditReminder( applicationID, reminderID ) {
	DisplayDialogWindow( 'CreateCalendarEvent', true, applicationID, reminderID );
	return false;
}

function DeleteReminder( applicationID, reminderID ) {
	if( confirm("Delete this reminder?") ) {
		window.location="components/UpdateCalendar.aspx?D=1&applicationID=" + applicationID + "&reminderID=" + reminderID;
	}
	
	return false;
}

function ApproveRejectDocument( documentID, applicationID ) {
	DisplayDialogWindow( 'ApproveRejectDocument', true, applicationID, documentID );
	return false;
}

function AddTelephoneReference( applicationID, documentType ) {
	DisplayDialogWindow( 'SelectReferenceCheckSource', true, applicationID, documentType );
	return false;
}

function SelectNewReferenceSource( applicationID, documentType ) {
	DisplayDialogWindow( 'SelectReferenceCheckSource', true, applicationID, documentType );
	return false;
}

function SubmitToAgency( applicationID ) {
	DisplayDialogWindow( 'SubmitApplication', true, applicationID, 'A' );
	return false;
}

function SubmitToOffice( applicationID ) {
	DisplayDialogWindow( 'SubmitApplication', true, applicationID, 'O' );
	return false;
}

function HM_AddHelp( formName, versionID, externalID ) {
	DisplayDialogWindow( 'HelpEditor', true, 0, formName + ':' + externalID + ':' + versionID );
	return false;
}

function HM_EditHelp( formName, versionID, externalID ) {
	DisplayDialogWindow( 'HelpEditor', true, 0, formName + ':' + externalID + ':' + versionID );
	return false;
}

function HM_DeleteHelp( formName, versionID, externalID ) {
	if( confirm('Delete the help for the selected question?') ) {
		$('DeleteHelpForm').value = formName;
		$('DeleteHelpVersion').value = versionID;
		$('DeleteHelpExternalID').value = externalID;
		document.HelpManagerSections.submit();
	}
}

// Applicant show help function
function  HM_ShowHelp( formName, externalID ) {
	DisplayDialogWindow( 'ShowHelp', false, 0, formName + ':' + externalID );
	return false;
}

function SB_SendBrochure( param ) {
	var pl = param.length;
	var identity = param.substr( 0, param.length - 1 );
	var type = param.substr( pl - 1, 1 );
	DisplayDialogWindow( 'SendBrochure', true, identity, type );
	return false;
}

function SB_Referral( param ) {
	var pl = param.length;
	var identity = param;
	var type = '';
	DisplayDialogWindow( 'Referral', true, identity, type );
	return false;
}

function Assign_ITep(applicationID) {
	DisplayDialogWindow('AssignITep', true, applicationID);
	return false;
}

function Assign_ITepConfirmed(applicationID, iTepTestId) {
	DisplayDialogWindow('AssignITepConfirmed', true, applicationID, iTepTestId);
	return false;
}

function DisplayDialogWindow( dialogName, isModal, applicationID, extraID ) {
	var url = "components/DisplayDialog.aspx";
	
	new Ajax.Updater('MWA', url, 
		{
		parameters: {	dialog: dialogName,
						modal: isModal,
						applicationid: applicationID,
						extra: extraID },
		onComplete:	function(transport) {
						if( isModal ) {
							$('modalBackground').style.display = 'block';
						}

						$('modalWindow').style.left = '-10000px';
						$('modalWindow').style.display = 'block';

						if( $F('md_init').length > 0 ){
							eval($F('md_init'));
							$('md_init').value = '';
						}
					
						CenterDialog();

						gWin = new Draggable('modalWindow', {
								handle: 'modalHeader',
								starteffect:function(){
								  new Effect.Opacity('modalWindow');
								},
								endeffect:function(){
								  new Effect.Opacity('modalWindow');
								}
							  });
						gWin.element.setStyle({ cursor: '' });
					}
		}
	);
	
	return false;
}

///
/// Size and centre the dialog
///
function SizeDialog( size ) {
	var div = $('modalWindow');
	div.style.height = size;
	
	CenterDialog();
}

function HideRejectionReason() {
	$('RejectionReason').hide();
	$('Padding').show();
	
	var div = $('modalWindow');
	div.style.height = '200px';
	
	CenterDialog();
}

function ShowRejectionReason() {
	$('Padding').hide();
	$('RejectionReason').show();
	$('ExtraDetails').focus();
		
	var div = $('modalWindow');
	div.style.height = '265px';
	
	CenterDialog();
}

function CheckApproveRejectDetails(){
	var rv = false;
	var typeValue = '';
	
	if( $$('input[type=radio][name=ApproveReject]:checked').first() != null ) {
		typeValue = $$('input[type=radio][name=ApproveReject]:checked').first().value;
	}

	if( typeValue == 'A' ) {
		rv = true;
	} 
	
	if( typeValue == 'R' ) {
		if( $F('ExtraDetails').length > 0 ) {
			rv = true;
		} else {
			alert('Please enter why you are rejecting this upload.');
			$('ExtraDetails').focus();
		}
	}
	
	if( typeValue != 'A' && typeValue != 'R' ) {
		alert('Please enter whether you are approving or rejecting this upload.');
	}
	
	return rv;
}

function CheckCalendarEventType() {
	if($F('eventType')=='2') {
		$('ShowTime').show(); 
				
		var div = $('modalWindow');
		div.style.height = '290px';

		CenterDialog();
	} else {
		$('ShowTime').hide();
		
		var div = $('modalWindow');
		div.style.height = '260px';

		CenterDialog();
	}
	
}

function ValidateCalendarEvent() {
	var rv = true;
	
	if( $F('eventType') == -1 ) {
		alert('Please select an event type');
		$('eventType').focus();
		rv = false;
	}
			
	if( rv && $F('eventDateDD') == '' ) {
		alert('Please enter the date of the event');
		$('eventDateDD').focus();
		rv = false;
	}
	
	if( rv && $F('eventDateMM') == '' ) {
		alert('Please enter the date of the event');
		$('eventDateMM').focus();
		rv = false;
	}
		
	if( rv && $F('eventDateYY') == '' ) {
		alert('Please enter the date of the event');
		$('eventDateYY').focus();
		rv = false;
	}
	
	if( rv ) {
		document.CalendarEventForm.submit();
	}
	
	return false;
}

function CheckSubmitApplication() {
	var rv = true;
	
	if( $('CommentEntryArea') ) {
		if( $F('CommentEntryArea').length == 0 ) {
			alert('Please enter why you are submitting this application despite the warnings');
			rv = false;
			$('CommentEntryArea').focus();
		}
	}
	
	if( rv ) {
		document.SubmitApplicationForm.submit();
	}
	
	return false;
}

function HM_ShowText() {
	$('TextSource').show(); 
	$('VideoSource').hide();
	
	SizeDialog( '350px' );
	
	$('HelpTextEditor').focus();
}

function HM_ShowVideo() {
	$('VideoSource').show();
	$('TextSource').hide(); 

	SizeDialog( '250px' );

	$('VideoSource').focus();
}

function HM_ValidateSave( ) {
	var rv = false;
	var typeValue = '';
	
	if( $$('input[type=radio][name=Source]:checked').first() != null ) {
		typeValue = $$('input[type=radio][name=Source]:checked').first().value;
	}

	if( typeValue == 'T' ) {
		if( $F('HelpTextEditor').length > 0 ) {
			rv = true;
		} else {
			alert('Please enter your help text in the field provided.');
			$('HelpTextEditor').focus();
		}
	} 
	
	if( typeValue == 'V' ) {
		if( $('VideoUpload') == null || $F('VideoUpload').length > 0 ) {
			rv = true;
		} else {
			alert('Please select a video to use for this help, or upload a new video.');
			$('VideoSource').focus();
		}	
	}
	
	if( typeValue != 'V' && typeValue != 'T' ) {
		alert('Please enter what type of help is to be displayed for the selected question.');
	}
	
	return rv;
}

function AA_ToggleItem( child, parent ){
	if( $(parent).hasClassName('aal_parent_open') ){
		$(parent).className = 'aal_parent_close';
	} else{
		$(parent).className = 'aal_parent_open';
	}
		
	Effect.toggle(child, 'slide'); 
	
	return false;
}

function NW_ToggleItem( child, parent ){
	if( $(parent).hasClassName('nw_parent_open') ){
		$(parent).className = 'nw_parent_close';
	} else{
		$(parent).className = 'nw_parent_open';
	}
		
	Effect.toggle(child, 'slide'); 
	
	return false;
}

function NW_ClearItem( articlediv, id ) {
		new Ajax.Request('components/WebSiteArticleRead.aspx', {
			method: 'post',
			parameters: {	
						articleid: id
						},
			onSuccess: function() {
				Effect.Fade(articlediv);
				
				var count = $F('NWCount');
				count--;
				$('NWCount').value = count;
				
				if( count == 0 ){
					// No more articles
					Effect.Fade('newscontainer');
				}
				
			}
		});
	return false;
}

function CenterDialog() {
	// we only need to move the dialog based on scroll position if
	//   we're using a browser that doesn't support position: fixed, like < IE 7
	var left = window.XMLHttpRequest == null ? document.documentElement.scrollLeft : 0;
	var top = window.XMLHttpRequest == null ? document.documentElement.scrollTop : 0;
	var div = $('modalWindow');

	div.style.left = Math.max((left + (GetWindowWidth() - div.offsetWidth) / 2), 0) + 'px';
	div.style.top = Math.max((top + (GetWindowHeight() - div.offsetHeight) / 2), 0) + 'px';
}

function CloseForm() {
	$('modalWindow').hide();
	$('modalBackground').hide();

	gWin = null;

	if( $('MWA') != null ) {
		$('MWA').innerHtml = '';
	}

	return false;
}

function ShowReferenceList() {
	$('ReferenceList').show();
	var div = $('modalWindow');
	div.style.height = '375px';

	CenterDialog();
}

function HideReferenceList() {
	$('ReferenceList').hide();
	
	// ensure that any prior selection is cleared
	SelectReferenceCheck( '', '' );
	
	var div = $('modalWindow');
	div.style.height = '150px';
	
	CenterDialog();
}

function SelectReferenceCheck( refereeName, documentID ) {
	var newSelection = 'RefDoc_' + documentID;
	var oldSelection = 'RefDoc_' + $F('documentID');
	
	if( $(oldSelection) ) {
		$(oldSelection).className = "Document";
	}
	
	if( $(newSelection) ) {
		$(newSelection).className = "DocumentSelected";
	}
	
	$('referee').value = refereeName; 
	$('documentID').value = documentID; 
	return false;
}

function CheckSelectReferenceSource(){
	var rv = false;
	var typeValue = '';
	
	if( $$('input[type=radio][name=basedon]:checked').first() != null ) {
		typeValue = $$('input[type=radio][name=basedon]:checked').first().value;
	}

	if( typeValue == 'U' ) {
		if( $F('documentID').length > 0 ) {
			rv = true;
		} else {
			alert('Please select a document from the list.');
		}
	} 
	
	if( typeValue == 'N' ) {
		rv = true;
	}
	
	if( typeValue != 'N' && typeValue != 'U' ) {
		alert('Please enter whether this reference is based upon a previously uploaded document or not.');
	}
	
	return rv;
}

function RC_EditRow( refID ) {
	ignore = true;

	$('EditDetails').value = refID;
	document.FormReferenceCheck.submit();
	
	return false;
}

function RC_DeleteRow( refID ) {
	ignore = true;

	if( confirm('Delete this telephone reference check now?') ) {
		$('DeleteDetails').value = refID;
		$('EditDetails').value = '';
		document.FormReferenceCheck.submit();
	}	
	
	return false;
}

function MediaReleaseNoticeClicked() {
	var checked = $('MediaReleaseNotice').checked ? "check" : "uncheck";
	new Ajax.Request('components/MediaReleaseNoticeChange.aspx', {
		method: 'post',
		parameters: {	
			mediaReleaseNoticeAccepted: checked
		}
	});
	return true;
}

function ShareDetailsChecked() {
    var checked = $('sharedetails').checked ? "check" : "uncheck";
    new Ajax.Request('components/ShareDetailsAccepted.aspx', {
        method: 'post',
        parameters: {
            sharedetailsAccepted: checked
        }
    });
    return true;
}

// Update the agent 
function TB_CountryChange() {

	var selectedParent = $("country").value;
	
	if( selectedParent.length > 0){
		new Ajax.Request('components/TalkbackUpdateControls.aspx?PARENT=country&ELEMENT=agencyid&PARAM=' + selectedParent, {
			method: 'get',
			onSuccess: function(transport) {
				if( transport.responseText.length > 0){
					$('agencyid').update( transport.responseText );
				}
			}
		});
	}
}

// Update the interviewer list
function TB_AgencyChange() {
	
	var selectedParent = $("agencyid").value;
	
	if( selectedParent.length > 0){
		new Ajax.Request('components/TalkbackUpdateControls.aspx?PARENT=agencyid&ELEMENT=interviewerid&PARAM=' + selectedParent, {
			method: 'get',
			onSuccess: function(transport) {
				if( transport.responseText.length > 0){
					$('interviewerid').update( transport.responseText );
				}
			}
		});
	}
}

function ShowQuestions( questions, ID ) {
	$(questions).toggle();
	return false;
}

/// Used on Make_Payment Page
function UpdateTotal(){
	var orderInfo = $('orderinfo');
	var paymentList = $('paymentlist');
	var paymentAmount = $('paymentamount');
	var originalAmount = $('originalAmount');
	var includeTravelInsurance = $('includeTravelInsurance');
	var includeMedicalInsurance = $('includeMedicalInsurance');
	var comprehensiveInsuranceAmount = $('comprehensiveInsuranceAmount');
	var travelInsuranceAmount = $('travelPackageAmount');
	var medicalInsuranceAmount = $('medicalUpgradeAmount');
	var targetAmount = $('amount');
	var savingsCurrency = $('savingsCurrency');
	var savingsAmount = $('savingsAmount');
	var currency = $('currency');
	if( originalAmount != null && comprehensiveInsuranceAmount != null && travelInsuranceAmount != null && 
			medicalInsuranceAmount != null && paymentAmount != null && savingsCurrency != null &&
			savingsAmount != null && currency != null ) {
		var total = parseInt( originalAmount.value ) / 100;
		if( includeTravelInsurance.checked && includeMedicalInsurance.checked ) {
			total += parseFloat( comprehensiveInsuranceAmount.value );
			orderInfo.value = "Invoice with travel and medical insurance";
			paymentList.value = "COMPINS";
		} else if( includeTravelInsurance.checked && !includeMedicalInsurance.checked ) {
			total += parseFloat( travelInsuranceAmount.value );
			orderInfo.value = "Invoice with travel insurance";
			paymentList.value = "TRAVINS";
		} else if( !includeTravelInsurance.checked && includeMedicalInsurance.checked ) {
			total += parseFloat( medicalInsuranceAmount.value );
			orderInfo.value = "Invoice with medical insurance";
			paymentList.value = "MEDINS";
		} else {
			orderInfo.value = "Invoice without optional insurance";
			paymentList.value="NOINS";
		}
		var savings = 
			parseFloat( travelInsuranceAmount.value ) + 
			parseFloat( medicalInsuranceAmount.value ) - 
			parseFloat( comprehensiveInsuranceAmount.value );
		savingsCurrency.innerHTML = currency.value;
		savingsAmount.innerHTML = savings + ".00";
		paymentAmount.innerHTML = total + ".00";
		targetAmount.value = parseInt(total + "00");
	}
}

/// utility functions
function GetWindowWidth() {
	var width =
		document.documentElement && document.documentElement.clientWidth ||
		document.body && document.body.clientWidth ||
		document.body && document.body.parentNode && document.body.parentNode.clientWidth ||
		0;
		
	return width;
}

function GetWindowHeight() {
	var height =
		document.documentElement && document.documentElement.clientHeight ||
		document.body && document.body.clientHeight ||
		document.body && document.body.parentNode && document.body.parentNode.clientHeight ||
		0;
		
	return height;
}

// From http://agrath.blogspot.com/2007/11/prototypejs-text-caretselection-methods.html
function setCaretPos(oField, iCaretPos) {
	if (Prototype.Browser.IE) {
		var oSel = document.selection.createRange ();
		//oSel.moveStart ('character', -oField.value.length);
		//oSel.moveStart ('character', iCaretPos);
		oSel.moveStart('character', 0 );
		oSel.moveEnd ('character', 0 );
		//oSel.select ();
	}else{
		oField.selectionStart = iCaretPos;
		oField.selectionEnd = iCaretPos;
		oField.focus();
	}
}
