var submitOnce = 0;
var refreshedControl = null;
var countDown = 4;

function SelectedValue( elementName, matchWith ) {
	var els = document.getElementsByName(elementName);
	for(i=0; i<els.length; i++) {
		if(els[i] && els[i].checked) {
			if(els[i].value == matchWith) {
				return true;
			}
		}
	}
	return false;
}

function isUndefined(v) {
	var undef;
	return v===undef;
}

function raw_popup(url, target, features) {
	var _POPUP_FEATURES = 'location=0,statusbar=0,menubar=0,width=600,height=400';

	if (isUndefined(features)) features = _POPUP_FEATURES;
	if (isUndefined(target  )) target   = '_blank';
	var theWindow = window.open(url, target, features);
	theWindow.focus();
	return theWindow;
}

function link_popup(src, features) {
	return raw_popup(src.getAttribute('href'),src.getAttribute('target') || '_blank',features);
}

/* Function used to (attempt to) limit the amount of text
 * entered into a textarea
 * From various places, and modified strangely */
function textLimiter( field, counter, max ) {
	if( field.value.length > max ) {
		field.value = field.value.substring( 0, max );
		return false;
	} else {
		var divElement = $(counter);
		var remain = (max - (field.value.length));
		if( divElement ) {
			divElement.innerHTML = remain + " of " + max + " characters remaining.";
		}
	}
}

function textLimiterWordCount( field, counter, maxChars, maxWords ) {
	if( field.value.length > maxChars ) {
		field.value = field.value.substring( 0, maxChars );
		return false;
	} else {
		var text = field.value.replace(/^\s*|\s*$/,'');
		// JVDM: Gets a more accurate word count than counting spaces
		//var words = text.split(/\s+/).length;
		//var words = text.split(/\w+/).length;
		// IAS: better yet..
		//var words = text.replace(/\./g, ': ').replace(/\S+/g, 'a').replace(/\s+/g, '').length
		var words = text.split(/\b[A-Za-z0-9'’-]+\b/).length;
		
		if( text.length > 0 ) {
			// JVDM: OT2150 ...
			//var message = "You are on " + words + " of " + maxWords + " word" + (maxWords !=1 ? "s":"") + ".";			
			var message = "You have written " + words + " word" + (words !=1 ? "s":"") + ".";			

			if( words < maxWords ) {
				$(counter).innerHTML = "<div class='WCInError'>" + message + "</div>";			
			} else {
				$(counter).innerHTML = "<div class='WCComplete'>" + message + "</div>";
			}
		} else {
			$(counter).innerHTML = "<div class='WCInError'>You must enter " + maxWords + " words or more.</div>";			
		}
	}
}

/*
 * Same as above, but without notification
 */
function textLimitQuiet( field, max ) {
	if( field.value.length > max ) {
		field.value = field.value.substring( 0, max );
		return false;
	}
}

/* When leaving a given field, hide the counter..
 */
function textLimiterClear( counter ) {
	var divElement = $(counter);

	if( divElement )
		divElement.innerHTML = "";
}


/* Check that form submit happens once and once only! */
function checkSubmitOnce() {
	if( submitOnce == 0 ) {
		submitOnce++;
		return true;
	} else {
		return false;
	}
}

function getelement(id){ 
	if (document.getElementById){
		return document.getElementById(id);
	}else{
		return eval('document.all.' + id);
	} 
}

function onLayer(whichLayer) {
	if( $(whichLayer) ) {
		var style2 = $(whichLayer).style;
		style2.display = "block";
	}
}

function onTableRowLayer(whichLayer) {
	if( $(whichLayer) ) {
		var style2 = $(whichLayer).style;
		if(navigator.appName.indexOf("Microsoft") > -1){
			style2.display = 'block';
		} else {
			style2.display = 'table-row-group';
		}
	}
}
function offLayer(whichLayer) {
	if( $(whichLayer) ) {
		var style2 = $(whichLayer).style;
		style2.display = "none";
	}
}
/*
function refreshQuestion( whichQuestion, refresharea, refreshControl ){
	var postbackTo = document.forms["metaform"].action;
	var divElement = $(whichQuestion);
	var postback   = $('__postbackSource');
	var divRefresh = $(refreshControl);
	
	divElement.disabled = true;
	divRefresh.disabled = true;
	
	postback.value = whichQuestion;
	
	// don't forget error!
	var refresh = new Ajax.Updater( {success: refresharea}, postbackTo,
	{   onCreate: function() {
			$( whichQuestion ).disabled = true;
			$( refreshControl ).disabled = true;
		},
		onComplete: function() {
			$( whichQuestion ).disabled = false;
			$( refreshControl ).disabled = false;
			//alert('complete');
		},
		onFailure: function(){
			$( whichQuestion ).disabled = false;
			$( refreshControl ).disabled = false;
			$(whichQuestion).focus();
			//alert( 'failed' );
		},	    
		onSuccess: function(){
			$( whichQuestion ).disabled = false;
			$( refreshControl ).disabled = false;
			$(whichQuestion).focus();
		},
		parameters : { __postback_countrycode: divElement.value } 
	} );
		
	return false;
}
*/
function refreshQuestion( whichQuestion, refresharea, refreshControl ){
	var postbackTo = document.forms.metaform.action;
	var divElement = $(whichQuestion);
	var postback   = $('__postbackSource');
	var divRefresh = $(refreshControl);
	
	postback.value = whichQuestion;
	document.forms.metaform.submit();
	
}
function toggleLayer(whichLayer){
	var style2 = $(whichLayer).style;
	style2.display = style2.display == "block" ? "none" : "block";
}

function timedSaveFunction( postBackTo ){
	var formElements = ["input.text", "input.checkbox", "input.radio", "select", "textarea"];
	var theForm = document.forms['metaform'];
	var elements = theForm.length;
	var ctrls = '';
	var vals = '';
	
	for(var i=0; i<elements; i++){
		var it = theForm.elements[i];
		if( it.type=='textarea'){
			if( ctrls.length > 0 ){
				ctrls += '&';
			}
			
			ctrls += it.name + '=' + it.value;
		}
	}

	if( ctrls.length > 0 ){
		var connection = new XHConn();
		
		if( !connection ) window.status = 'XMLHTTP not available!';
		
		var fnWhenDone = function(oXML) { window.status = 'Data successfully saved.'; }; //alert(oXML.responseText);};
		
		window.status = 'Saving data';  
		connection.connect( postBackTo, "POST", ctrls, fnWhenDone );
	}
	
	// set timeout has to be set -- what, every time?
	setTimeout('timedSaveFunction(\'' + postBackTo + '\')', 10000 );
}

function textAreaChanged( textAreaControl, textAreaSaveBar ){
	textAreaSaveBar.src = "./img/save.gif";
}

function saveTextAreaData( controlToSave, notifyControl, postBackTo ){
	var url = postBackTo + "?control=" + controlToSave + "&value=" + escape ( $F(controlToSave) );
	
	new Ajax.Request(url, {
	  method: 'post',
	  parameters: { currentsectionid : $F('currentsectionid'), __backgroundSave : 1 },
	  onSuccess: function(transport) {
		window.status='Data successfully saved.'; 
					
		if( notifyControl ){
			notifyControl.src = "./img/saved.gif";
		}
	  }
	});

	return false;
}

function selectSubSection( subsection ) {
	Effect.toggle(subsection, 'slide', { duration: 0.5 } );
	return false;
}

function changeSection(newSection){
	var changesection = document.createElement('input');
	changesection.setAttribute('id', 'changesection' );
	changesection.setAttribute('name', 'changesection' );
	changesection.setAttribute('type', 'hidden');
	changesection.setAttribute('value', newSection );
	if( document.metaform != null ){
		document.metaform.appendChild(changesection);
		document.metaform.submit();
	}
	
	return false;
}

function changePage(newPage) {
	var changepage = document.createElement('input');
	changepage.setAttribute('id', 'changepage' );
	changepage.setAttribute('name', 'changepage' );
	changepage.setAttribute('type', 'hidden');
	changepage.setAttribute('value', newPage );
	if( document.metaform != null ){
		document.metaform.appendChild(changepage);
		document.metaform.submit();
		return true;
	}else{
		return false;
	}
}

function showInterviewerDetails( interviewerID ){
	var refresh = new Ajax.Updater( {success: 'selectedDetails'}, "components/selectInterviewer.aspx?view=" + interviewerID, 
	{   onCreate: function() {
			$( 'selectedDetails' ).innerHTML = "<img src='img/ajax-loader.gif' /><span class='note'>Loading...</span>";
		}
	} );   
	return false;
}

function toggleReviewBox( reviewBox ){
	$( reviewBox + '_rc' ).hide();
	Effect.toggle( 'rb_' + reviewBox, 'appear',{ duration: 0.5, afterFinish: function() { $('rbox_' + reviewBox).focus(); } } );  
	return false;
}

/// Agency Site tab management -- just in case we require any changes
function AS_ChangeSection(newSection){
	var changesection = document.createElement('input');
	changesection.setAttribute('id', 'changesection' );
	changesection.setAttribute('name', 'changesection' );
	changesection.setAttribute('type', 'hidden');
	changesection.setAttribute('value', newSection );
	if( document.metaform != null ){
		document.metaform.appendChild(changesection);
		document.metaform.submit();
	}
	
	return false;
}

function saveNotes( section, subsection, form, value, noteid, applicationid ){
	if (value.toString().length == 0) {
		alert("This field may not be blank");
	} else {
		var notify = 'nty_' + subsection;
		var submitURL = 'components/updatedocumentnotes.aspx?'
		  + 'applicationid=' + applicationid
		  + '&form=' + form
		  + '&section=' + section
		  + '&sub=' + subsection
		  + '&notes=' + value;
			
		var refresh = new Ajax.Updater( {success: notify}, submitURL, 
		{   onCreate: function() {
				$( notify ).innerHTML = "<img src='img/ajax-loader.gif' /><span>Loading...</span>";
			}
		} );
	}
	
	return false;
}

/// Cancel the note dialog
function cancelNote( reviewBox, textArea ) {
	$(textArea).value = '';
	$( reviewBox).hide();
	$( reviewBox.substring(3) + '_rc' ).show();
	return false;   
}

function deleteNote( noteID, noteIDField, reviewBox, textArea, applicationid ){
	// Has the note been saved yet?
	if( $(noteIDField) == null || $F(noteIDField).length == 0 ) {
		cancelNote( reviewBox, textArea );
	} else {
		if( confirm('Delete this note?') ) {
			var submitURL = 'components/UpdateDocumentNotes.aspx?delete=' + $F(noteIDField)
			+ '&applicationid=' + applicationid;

			var refresh = new Ajax.Request(
				submitURL, {
				method: 'get',
				onSuccess: function(transport) {
					$(textArea).value = '';
					$( reviewBox.substring(3) + '_rc' ).show();
					$(reviewBox).hide();
					if( transport.responseText == 'SC' ) {
						window.location.reload();
					}
				}
			});
			
		}
	}
	return false;
}

function reviewNote( noteID, reviewBox, subsectionheadingimage ){
	var submitURL = 'components/NoteAccepted.aspx?complete=' + noteID;
	 
	// used in applicationdata.aspx
	$('__noteID').value = noteID;
	
	var refresh = new Ajax.Updater( {
		onSuccess: function(transport) {
			// hide review box
			Effect.toggle(reviewBox, 'appear');
		}
	 }, 
	 submitURL );
	
	return false;
}

// I am so lazy. gacked from here: http://www.somacon.com/p117.php
function SetAllCheckBoxes(FormName, FieldName, CheckValue){
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

