// functions shared between pages

function handleEditPersonOnClick(pid) {
	openWindow('edit-person?pid='+pid, 'editperson');
}

function handlePersonDetailsOnClick(personid) {
	openWindow('person-details-printable?pid='+personid, 'persondetailsprintable');
}

// disambiguate person

function handleDisambiguateSelectPersonOnClick(theform,pid) {
	theform.bc.value = 'sp';
	theform.pid.value = pid;
	theform.submit();
}

function handleDisambiguateAddPersonOnClick(theform) {
	theform.bc.value = 'ap';
	theform.submit();
}

// lookup person

function handleLookupPersonSelect(personid) {
	opener.document.handleLookupPersonSelect(personid);
	window.close();
}


// search

function handleSearchOnLoad() {
	document.handleLookupPersonSelect = handleSearchLookupPersonSelect;
}

function handleDisambiguateOnClick(personnameid) {
	theform = document.forms[0];
	personnameid = theform.elements['personnameid'].value;
	personfamilynames = theform.elements['personfamilynames'].value;
	openWindow('disambiguate-person?q='+personfamilynames+'&pn='+personnameid,'disambiguateperson');
}

function handleSearchLookupPersonSelect(personid) {
	window.location = 'search?st=browse-by-person&pid='+personid;
}

// edit user

function handleEditUserPersonSelect(personid) {
	document.forms[0].personid.value = personid;
}

// edit person

function handleAddPersonNameOnClick() {
	rownumber = ++(document.getElementsByName('personalternativenames-row-count')[0].value);

	personnametbody = document.getElementById('personalternativenamestbody');
	personnametr = document.createElement('tr');
	personfirstnamestd = document.createElement('td');
	appendTextInput(personfirstnamestd,'personalternativename-'+rownumber+'-personfirstnames',20,'');
	personnametr.appendChild(personfirstnamestd);

	personfamilynamestd = document.createElement('td');
	appendTextInput(personfamilynamestd,'personalternativename-'+rownumber+'-personfamilynames',20,'');
	personnametr.appendChild(personfamilynamestd);

	personnametr.appendChild(document.createElement('td'));
	personnametbody.appendChild(personnametr);
}

function handleEditPersonLookupCCLRCPerson(theform) {
	personid = theform.personid.value;
	personfamilynames = theform.personfamilynames.value;
	openWindow('lookup-cclrc-person?q='+personfamilynames+'&pid='+personid, 'lookupcclrcperson');
	theform.submit(); // to save any unsaved details
}

function handleLookupCCLRCPersonSelect(theform,cclrcpid) {
	theform.cclrcpid.value = cclrcpid;
	theform.submit();
}

function handleEditPersonDeleteCCLRCPerson(theform) {
	theform.cclrcpid.value = '';
	theform.submit();
}

// edit work metadata

//put focus on fast track areas depending on buttons clicked | josh

function handleOnLoadFocus() {

  var ffield = document.getElementById("ffocus");
  if (ffield != undefined) {
      switch (ffield.value){
      case (ffield.value = ""):
          document.input.title.focus();
      break
      case (ffield.value = "absb"):
          document.input.bitstream.focus();
      break
      }
  }
}


function handleAddWorkOnClick() {
	var url = 'add-work';
	var orgunitid = document.getElementById('orgunitid');
	if (orgunitid != undefined) {
		url = url + '?ou=' + orgunitid.value;
	}
	openWindow(url,'editwork');
}

function handleAddFastTrackWorkOnClick() {
	var url = 'add-fasttrack-work';
	var orgunitid = document.getElementById('orgunitid');
	if (orgunitid != undefined) {
		url = url + '?ou=' + orgunitid.value;
	}
	openWindow(url,'editwork');
}


function handleEditWorkOnClick(workid,workinstanceid) {
	openWindow('edit-work?w='+workid+'&wi='+workinstanceid,'editwork');
}

function handleCopyWorkOnClick(workinstanceid) {
	openWindow('copy-work?wi='+workinstanceid,'editwork');
}

function handleDeleteDraftWorkOnClick(workid) {
	openWindow('delete-draft-work?w='+workid,'deletework');
}

function handleDeletePendingWorkOnClick(workinstanceid) {
	openWindow('delete-pending-work?wi='+workinstanceid,'deletework');
}

function handleDeleteWorkOnClick(workid) {
	openWindow('delete-work?w='+workid,'deletework');
}

function handleCCLRCNeitherApply(checkbox) {
	if (checkbox.checked) {
		document.getElementById('cclrc-author').checked = false;
		document.getElementById('cclrc-facilities').checked = false;
	}
}

function handleCCLRCNotNeitherApply(checkbox) {
	if (checkbox.checked) {
		document.getElementById('cclrc-neither').checked = false;
	}
}

function handleAddKeywordOnClick(theform,sequencenumber) {
	theform.bc.value = 'akb';
	DisableWorkflowAndSubmit(theform);
}

function handleDeleteKeywordOnClick(theform,sequencenumber) {
	theform.bc.value = 'dkb';
	theform.elements['keyword-row-'+sequencenumber].value = '';
	DisableWorkflowAndSubmit(theform);
}

// edit contributions

function handleEditWorkContributionsOnLoad() {
	document.handleLookupPersonSelect = handleEditWorkContributionsLookupPersonSelect;
}

function handleAddContributionOnClick(theform,sequencenumber) {
	document.suppressOnBeforeUnload = true;
	theform.bc.value = 'acb';
	theform.sn.value = sequencenumber;
	DisableWorkflowAndSubmit(theform);
}

function handleAddReferenceBibtexOnClick(theform, sequencenumber) {
	// get the highest reference value and add one to it create a new element and display it on the form
	var highest = 1;
	for( i = 0; i < theform.elements.length; i++){
		//if the element starts with 'reference' find out what the value is
		if( theform.elements[i].id.indexOf("reference-") >= 0){
			val = parseInt(theform.elements[i].id.substr(theform.elements[i].id.indexOf("reference-") + 10));
			if( val > highest){
				highest = val;
			}
		}
	}
	//add one to the highest value
	highest = highest + 1;
	//create the new row in the table
	var html = "<td> " +
                       "<input name=\"reference\" id=\"reference-" + highest + "\" value=\"\" type=\"text\" size=\"20\"/>" +
                    "</td>&nbsp;" +
                    "<td>" +
                          "<input class=\"lookupButton\" id=\"add-reference-" + highest + "\" type=\"button\" value=\"+\" onclick=\"handleAddReferenceBibtexOnClick(this.form," + highest + ")\"/>" +
                          "&nbsp;" +
                          "<input class=\"lookupButton\" id=\"delete-reference-" + highest + "\" type=\"button\" value=\"-\" onclick=\"handleDeleteReferenceBibtexOnClick(this.form," + highest + ")\"/>"
                    "</td> ";
	referenceTable = document.getElementById("reference-table");
	row = document.createElement("tr");
	row.id = "addedref-" + highest
	row.innerHTML = html;
	
	referenceTable.appendChild(row);
	
}

function handleDeleteReferenceBibtexOnClick(theform,sequencenumber) {
	document.suppressOnBeforeUnload = true;
	// if its the first element don't delete just remove any text in it
	if(sequencenumber == 1){
		document.getElementById("reference-" + sequencenumber).value='';
	}else{
		node = document.getElementById("addedref-" + sequencenumber);
		node.parentNode.removeChild(node);
	}
}

function handleAddReferenceOnClick(theform,sequencenumber) {
	document.suppressOnBeforeUnload = true;
	theform.bc.value = 'arb';
	theform.sn.value = sequencenumber;
	DisableWorkflowAndSubmit(theform);
}

function handleDeleteReferenceOnClick(theform,sequencenumber) {
	document.suppressOnBeforeUnload = true;
	theform.bc.value = 'drb';
	theform.elements['reference-'+sequencenumber].value = '';
	DisableWorkflowAndSubmit(theform);
}

function handleAddContributionsOnClick(theform) {
	document.suppressOnBeforeUnload = true;
	theform.bc.value = 'acsb';
	DisableWorkflowAndSubmit(theform);
}

function handleDeleteContributionOnClick(theform,sequencenumber) {
	document.suppressOnBeforeUnload = true;
	theform.bc.value = 'dcb';
	theform.elements['personfamilynames-'+sequencenumber].value = '';
	theform.elements['personfirstnames-'+sequencenumber].value = '';
	theform.elements['affiliation-'+sequencenumber].value = '';
	DisableWorkflowAndSubmit(theform);
}

function handleEditWorkContributionsLookupPersonOnClick(sequencenumber) {
	theform = document.forms[0];
	theform.sn.value = sequencenumber;
	personfamilynames = theform.elements['personfamilynames-'+sequencenumber].value
	openWindow('lookup-person?q='+personfamilynames, 'lookupperson');
}

function handleEditWorkContributionsLookupPersonSelect(personid) {
	theform = document.forms[0];
	sequencenumber = theform.sn.value;
	if (sequencenumber != '') {
		theform.elements['personid-'+sequencenumber].value = personid;
	}
	theform.submit();
}

function handleEditWorkContributionsEditPersonOnClick(theform,sequencenumber) {
	personid = theform.elements['personid-'+sequencenumber].value;
	openWindow('edit-person?pid='+personid, 'editperson');
}

function handleEditWorkContributionsDeletePersonOnClick(theform,sequencenumber) {
	theform.bc.value = 'uc';
	theform.elements['personid-'+sequencenumber].value = '';
	DisableWorkflowAndSubmit(theform);
}

// edit expression

function handleAddExpressionOnClick() {
	var theform = document.getElementById('edit-work-expressions-form');
	theform.bc.value = 'amb';
	DisableWorkflowAndSubmit(theform);
}

function handleEditExpressionOnClick(workid,expressioninstanceid) {
	var theform = document.getElementById('edit-work-expressions-form');
	theform.bc.value = 'emb';
	theform.ma.value = expressioninstanceid;
	DisableWorkflowAndSubmit(theform);
}

function handleDeleteExpressionOnClick(workid,expressioninstanceid) {
	var theform = document.getElementById('edit-work-expressions-form');
	theform.bc.value = 'dmb';
	theform.ma.value = expressioninstanceid;
	DisableWorkflowAndSubmit(theform);
}


function handleWorkEditExpressionOnLoad() {
	var expressionType = document.getElementById('expressiontypeshortname').value;
	var hasMeetingCheckbox = document.getElementById('hasMeeting');
	var exprMeetRole = document.getElementById('expressionmeetingroleshortname').value;
	if (expressionType=='EP_MT_PRESENTATION' || exprMeetRole=='isPresentation' ||
		expressionType=='EP_MT_INPROCEEDINGS' || exprMeetRole=='isInProceedings' ||
		expressionType=='EP_MT_PROCEEDINGS' || exprMeetRole=='isProceedings') {
		hasMeetingCheckbox.checked = true;
	}
	initEditExpression();
}

function handleHasMeetingOnClick(thecheckbox) {
	var expressionType = document.getElementById('expressiontypeshortname').value;
	var hasMeetingCheckbox = document.getElementById('hasMeeting');
	if (expressionType=='EP_MT_PRESENTATION' ||
		expressionType=='EP_MT_INPROCEEDINGS' ||
		expressionType=='EP_MT_PROCEEDINGS') {
		hasMeetingCheckbox.checked = true;
	}
	initEditExpression();
}

function handleExpressionTypeOnChange() {
	var expressionType = document.getElementById('expressiontypeshortname').value;
	var hasMeetingCheckbox = document.getElementById('hasMeeting');
	if (expressionType=='EP_MT_PRESENTATION' ||
		expressionType=='EP_MT_INPROCEEDINGS' ||
		expressionType=='EP_MT_PROCEEDINGS') {
		hasMeetingCheckbox.checked = true;
	}
	initEditExpression();
}

function handleDisplayHtmlTitleFieldOnClick() {

	var htmlInput = document.getElementById('htmltitleinput');
	// switch
	if(htmlInput.style.display=='none'){
		htmlInput.style.display='block';
	}else{
		htmlInput.style.display='none';
	}

}

function handleDisplayHtmlTitleFieldOnLoad() {

	var htmlInput = document.getElementById('htmltitleinput');
	htmlInput.style.display='none';
}


function handleDisplayParsedAuthorFieldsOnLoad() {
	//<input id="cc" type="hidden" name="cc" value="{$contribution-count+1}"/>
	var numAuthors = document.getElementById('cc').value - 1;
	if(numAuthors == 0){
		// hide it then
		document.getElementById('parsedauthors').style.display='none';
	}
}

function initEditExpression() {
	var expressionType = document.getElementById('expressiontypeshortname').value;
	var hasMeetingCheckbox = document.getElementById('hasMeeting');
	var exprMeetRole = document.getElementById('expressionmeetingroleshortname').value;
	var hasMeeting = hasMeetingCheckbox.checked;
	var publicationStatus = document.getElementById('publicationstatus');
	var serialSection = document.getElementById('serialsection');
	var meetingSection = document.getElementById('meetingsection');
	var bookHeadingSection = document.getElementById('bookHeadingSection');
	var bookTitleSection = document.getElementById('bookTitleSection');
	var bookSection = document.getElementById('bookSection');
	var bookDescriptionSection = document.getElementById('bookDescriptionSection');
	var inBookSection = document.getElementById('inBookSection');
	var thesisSection = document.getElementById('thesisSection');
	var reportSection = document.getElementById('reportsection');
	var uriSection = document.getElementById('uriSection');
	var publicationDescriptionSection = document.getElementById('publicationdescription');

	if (hasMeeting ||
		expressionType=='EP_MT_PRESENTATION' ||
		expressionType=='EP_MT_INPROCEEDINGS' ||
		expressionType=='EP_MT_PROCEEDINGS') {
		meetingSection.style.display='block';
	} else {
		meetingSection.style.display='none';
	}

	if (expressionType=='EP_MT_JOURNALARTICLE' || expressionType=='EP_MT_JOURNALISSUE') {
		serialSection.style.display='block';
	} else {
		serialSection.style.display='none';
	}

	if (expressionType=='EP_MT_JOURNALARTICLE') {
		publicationStatus.style.display='block';
		document.getElementById('journalarticletable').style.display='inline';
		document.getElementById('journalarticledoip').style.display='inline';
	} else {
		publicationStatus.style.display='none';
		document.getElementById('journalarticletable').style.display='none';
		document.getElementById('journalarticledoip').style.display='none';
	}

	if (expressionType=='EP_MT_BOOK' || expressionType=='EP_MT_INBOOK') {
		bookHeadingSection.style.display = 'block';
		bookSection.style.display = 'block';
	} else {
		bookHeadingSection.style.display = 'none';
		bookSection.style.display = 'none';
	}

	if (expressionType=='EP_MT_INBOOK') {
		bookTitleSection.style.display = 'block';
	} else {
		bookTitleSection.style.display = 'none';
	}

	if (expressionType=='EP_MT_BOOK') {
		bookDescriptionSection.style.display = 'block';
	} else {
		bookDescriptionSection.style.display = 'none';
	}

	if (expressionType=='EP_MT_INBOOK') {
		inBookSection.style.display = 'block';
	} else {
		inBookSection.style.display = 'none';
	}

	if (expressionType=='EP_MT_THESIS') {
		thesisSection.style.display = 'block';
	} else {
		thesisSection.style.display = 'none';
	}

	if (expressionType!='EP_MT_JOURNALARTICLE' &&
		expressionType!='EP_MT_JOURNALISSUE' &&
		expressionType!='EP_MT_JOURNALISSUE' &&
		expressionType!='EP_MT_PRESENTATION' &&
		expressionType!='EP_MT_BOOK' &&
		expressionType!='EP_MT_INBOOK' &&
		expressionType!='') {
		reportSection.style.display='block';
	} else {
		reportSection.style.display='none';
	}

	// in the case of a journal article, the description is covered by the 'OtherDesignation' field
	// in the case of a presentation, the description is covered by the 'MeetingDescription' field
	if (expressionType!='EP_MT_JOURNALARTICLE' &&
		expressionType!='EP_MT_JOURNALISSUE' &&
		expressionType!='EP_MT_PRESENTATION' &&
		expressionType!='EP_MT_BOOK' &&
		expressionType!='EP_MT_INBOOK') {
		publicationDescriptionSection.style.display='block';
	} else {
		publicationDescriptionSection.style.display='none';
	}

	if (expressionType!='EP_MT_JOURNALARTICLE') {
		uriSection.style.display = 'block';
	} else {
		uriSection.style.display = 'none';
	}
}

function handleLookupJournalOnClick(query) {
	var query = document.getElementById('journaltitle').value;
	openWindow('lookup-journal?q='+query, 'lookupjournal');
}

function handleJournalSelectOnChange(theselect) {
	var serialid = theselect.value;
	var serialshorttitle = document.getElementById('serial-'+serialid+'-serialshorttitle').value;
	document.getElementById('journaltitle').value = serialshorttitle;
}

function handleReportSeriesSelectOnChange(theselect) {
	var serialid = theselect.value;
	var serialshorttitle = document.getElementById('serial-'+serialid+'-serialshorttitle').value;
	document.getElementById('reportseriestitle').value = serialshorttitle;
}

function handleLookupJournalSelect(serialid,journaltitle) {
	var serialSelect = opener.document.getElementById('journalserialid');
	var journalTitleInput = opener.document.getElementById('journaltitle');
	serialSelect.value = serialid;
	journalTitleInput.value = journaltitle;
	opener.focus();
	window.close();
}

function handleLookupDOIOnClick(aufirst) {
	var title = document.getElementById('journaltitle').value;
	var volume = document.getElementById('journalarticlevolume').value;
	var artnum = document.getElementById('journalarticlenumber').value;
	var spage = document.getElementById('journalarticlefirstpagenumber').value;
	var date = document.getElementById('expressionyear').value;
	var wndhnd = window.open('lookup-doi?title='+title+'&aufirst='+aufirst+'&volume='+volume+'&artnum='+artnum+'&spage='+spage+'&date='+date,'lookupdoi','width=100,height=100');
	window.focus();
}

function handleLookupDOIOnLoad(doi) {
	if (doi != '') {
		opener.document.getElementById('journalarticledoi').value = 'doi:'+doi;
	}
	window.close();
}

// edit bitstream

function handleAddBitstreamOnClick(bitstreamid) {
	var theform = document.getElementById('edit-work-expression-form');
	theform.bc.value = 'absb';
	DisableWorkflowAndSubmit(theform);
}

function handleEditBitstreamOnClick(bitstreamid) {
	var theform = document.getElementById('edit-work-expression-form');
	theform.submit();
	openWindow('edit-bitstream?b='+bitstreamid,'editbitstream');
}

function handleDeleteBitstreamOnClick(bitstreamid) {
	var theform = document.getElementById('edit-work-expression-form');
	theform.bc.value = 'dbsb';
	theform.bitstreamid.value = bitstreamid;
	DisableWorkflowAndSubmit(theform);
}

// ********************** workflow controls

function DisableWorkflowAndSubmit(theform) {
	DisableWorkflow();
	theform.submit();
}

function handleSaveCancelCancelOnClick(theform) {
	theform.bc.value = 'sccb';
	DisableWorkflowAndSubmit(theform);
}

function handleSaveCancelSaveOnClick(theform) {
	theform.bc.value = 'scsb';
	DisableWorkflowAndSubmit(theform);
}


function handleCancelOnClick(theform) {
	document.suppressOnBeforeUnload = true;
	theform.bc.value = 'cb';
	DisableWorkflowAndSubmit(theform);
}

//Prompt Author Validation if add author not clicked.
// josh | 08 Mar 07
function validateB4HandleNextOnClick(theform){
    document.suppressOnBeforeUnload = true;
    var textfield = theform.cs.value;
    if (textfield != "" ){
        alert ("Please validate contributor's names by clicking on 'Add authors' button.");
        document.input.cs.focus();
        }
    else {
        handleNextOnClick(theform);
        }
    }


function handleNextOnClick(theform) {
	document.suppressOnBeforeUnload = true;
	theform.bc.value = 'nb';
	DisableWorkflowAndSubmit(theform);
}

function handleSaveOnClick(theform) {
	document.suppressOnBeforeUnload = true;
	theform.bc.value = 'sb';
	DisableWorkflowAndSubmit(theform);
}

function handlePublishOnClick(theform) {
	theform.bc.value = 'pub';
	DisableWorkflowAndSubmit(theform);
}

function handlePreviousOnClick(theform) {
	document.suppressOnBeforeUnload = true;
	theform.bc.value = 'pb';
	DisableWorkflowAndSubmit(theform);
}

function DisableWorkflow(theform) {

	wfnext = document.getElementById('wfnext');
	wfprev = document.getElementById('wfprev');
	wfsave = document.getElementById('wfsave');
	wfsubmit = document.getElementById('wfsubmit');
	wfapprove = document.getElementById('wfapprove');
	wfcancel = document.getElementById('wfcancel');
	wfuploadbitstream = document.getElementById('wfuploadbitstream');
	wfaddcontributions = document.getElementById('wfaddcontributions');

	if (wfnext != null) {
		wfnext.disabled = true;
	}
	if (wfprev != null) {
		wfprev.disabled = true;
	}
	if (wfsave != null ) {
		wfsave.disabled = true;
	}
	if (wfsubmit != null ) {
		wfsubmit.disabled = true;
	}
	if (wfapprove != null ) {
		wfapprove.disabled = true;
	}
	if (wfcancel != null) {
		wfcancel.disabled = true;
	}
	if (wfuploadbitstream != null) {
		wfuploadbitstream.disabled = true;
	}
	if (wfaddcontributions != null) {
		wfaddcontributions.disabled = true;
	}

}

// ********************** end of workflow controls

// system administration

// admin
function handlePeopleOnLoad() {
	document.handleLookupPersonSelect = handlePeopleLookupPersonSelect;
}

function handlePeopleLookupPersonSelect(personid) {
	url = window.location;
	window.location = url;
}

function handleAddSerialOnClick(serialid) {
	openWindow('add-serial?sty=1','editserial');
}

function handleEditSerialOnClick(serialid) {
	openWindow('edit-serial?s='+serialid,'editserial');
}

function handleDeleteSerialOnClick(serialid) {
	openWindow('delete-serial-confirm?s='+serialid,'editserial');
}

function handleAddAnnotationOnClick(workid) {
	openWindow('add-annotation?w='+workid,'addannotation');
}

function handleDeletePersonOnClick(personid) {
	openWindow('delete-person?pid='+personid);
}

function handleEditWorkSetOnClick(worksetid) {
	openWindow('edit-workset?ws='+worksetid, 'editworkset');
}

function handleAddWorkSetOnClick() {
	openWindow('edit-workset', 'editworkset');
}

function handleEditEpubUserOnClick(epubuserid) {
	openWindow('edit-user?u='+epubuserid, 'edituser');
}

function handleEditUserLookupPerson(query) {
	openWindow('lookup-person?q='+query, 'lookupperson');
}

function handleAddEpubUserOnClick(epubuserid) {
	openWindow('edit-user', 'edituser');
}

function handleEditOrgUnitOnClick(orgunitid) {
	openWindow('edit-orgunit?ou='+orgunitid, 'editorgunit');
}

function handleAddOrgUnitOnClick() {
	openWindow('edit-orgunit', 'editorgunit');
}

function handleEditBitstreamFormatOnClick(bitstreamformatid) {
	openWindow('edit-bitstream-format?bf='+bitstreamformatid, 'editbitstreamformat');
}

function handleAddBitstreamFormatOnClick() {
	openWindow('edit-bitstream-format', 'editbitstreamformat');
}

function handleAddFileExtensionOnClick() {
	rownumber = ++(document.getElementsByName('fileextensioncount')[0].value);
	fileextensionlist = document.getElementById('fileextensionlist');
	fileextensionlistitem = document.createElement('li');
	appendTextInput(fileextensionlistitem,'fileextension',5,'');
	fileextensionlist.appendChild(fileextensionlistitem);
}

function handleEditUserOnLoad() {
	document.handleLookupPersonSelect = handleEditUserPersonSelect;
}

/* ******************************* */

// utils

function handleBlankPageOnLoad(url) {
	if ((url != '') && (url != 'undefined')) {
		opener.location = url;
	} else {
		opener.location.reload(true);
	}
	opener.focus();
	window.close();
}

function SelectAll(theselect) {
	for (i=0;i<theselect.options.length;i++) {
		theselect.options[i].selected = true;
	}
}

function DeselectAll(theselect) {
	for (i=0;i<theselect.options.length;i++) {
		theselect.options[i].selected = false;
	}
}

function CheckAll(checkboxname, ischecked) {
	var checkboxes = document.getElementsByName(checkboxname);
	for(i=0;i<checkboxes.length;i++)
	{
		if((checkboxes[i].checked!=ischecked) && !(checkboxes[i].disabled)){
			checkboxes[i].checked=ischecked;
		}
	}
}

function clearSelect(theselect) {
	theselect.selectedIndex = 0;
	theselect.onchange();
}

function appendTextInput(element,name,size,value) {
	input = document.createElement('input');
	input.setAttribute('name',name);
	input.setAttribute('size',size);
	input.setAttribute('value',value);
	element.appendChild(input);
}

function appendButtonInput(element,inputclass,value) {
	input = document.createElement('input');
	input.setAttribute('type','button');
	input.setAttribute('class',inputclass);
	input.setAttribute('value',value);
	element.appendChild(input);
}

function openWindow(theurl,name) {
	var blankwndhnd = window.open('do-not-close', 'blank', 'width=200,height=100');
	blankwndhnd.blur();
	//var wndhnd = window.open(theurl, name, 'scrollbars,resizable');
	// see location for dev - put this back.
	var wndhnd = window.open(theurl, name, 'scrollbars,resizable,location=yes');
	wndhnd.focus();
}

function SignOut() {
	var blankwndhnd = window.open('do-not-close', 'blank', '');
	blankwndhnd.blur();
	blankwndhnd.close();
}


function handleViewExprButton(exprid,workinstanceid) {
	openWindow('/expression-details?ma='+exprid+'&wi='+workinstanceid, 'expressiondetails');
	//window.location = '/expression-details?ma='+exprid+'&wi='+workinstanceid;
}

/* Javascript Date Selector
   by Warren Brown (03/01/2004)
   Modified by josh (04-Sept-07)


var date_arr = new Array;
var days_arr = new Array;


date_arr[0]=new Option("January",31);
date_arr[1]=new Option("February",28);
date_arr[2]=new Option("March",31);
date_arr[3]=new Option("April",30);
date_arr[4]=new Option("May",31);
date_arr[5]=new Option("June",30);
date_arr[6]=new Option("July",31);
date_arr[7]=new Option("August",30);
date_arr[8]=new Option("September",30);
date_arr[9]=new Option("October",31);
date_arr[10]=new Option("November",31);
date_arr[11]=new Option("December",30);



function fill_select1(f)
{
        document.writeln("<SELECT name=\"days1\" id=\"days1\"></SELECT>");
        document.writeln("<SELECT name=\"months1\" id=\"months1\" onchange=\"update_days1(searchfields)\">");
        for(x=0;x<12;x++){
                document.writeln("<OPTION value=\""+date_arr[x].value+"\">"+date_arr[x].text);}
        document.writeln("</SELECT>");
        selection=f.months1[f.months1.selectedIndex].value;
}


function fill_select2(f)
{
        document.writeln("<SELECT name=\"days2\" id=\"days2\"></SELECT>");
        document.writeln("<SELECT name=\"months2\"  id=\"months2\" onchange=\"update_days2(searchfields)\">");
        for(x=0;x<12;x++){
                document.writeln("<OPTION value=\""+date_arr[x].value+"\">"+date_arr[x].text);}
        document.writeln("</SELECT>");
        var today = new Date();
        selection=f.months2[f.months2.selectedIndex].value;
}

function update_days1(f)
{
        temp=f.days1.selectedIndex;
        for(x=days_arr.length;x>0;x--)
        {
                days_arr[x]=null;
                f.days1.options[x]=null;
         }
        selection=parseInt(f.months1[f.months1.selectedIndex].value);
        ret_val = 0;
        if(f.months1[f.months1.selectedIndex].value == 28)
        {
                year=parseInt(f.years1.options[f.years1.selectedIndex].value);
                if (year % 4 != 0 || year % 100 == 0 )
                	ret_val=0;
                else if
                	(year % 400 == 0)  ret_val=1;
                else
                	ret_val=1;
        }
        selection = selection + ret_val;
        for(x=1;x < selection+1;x++)

        {
                days_arr[x-1]=new Option(x);
                f.days1.options[x-1]=days_arr[x-1];
        }
        if (temp == -1) f.days1.options[0].selected=true;
        else
           f.days1.options[temp].selected=true;
}
function update_days2(f)
{
        temp=f.days2.selectedIndex;
        for(x=days_arr.length;x>0;x--)
        {
                days_arr[x]=null;
                f.days2.options[x]=null;
         }
        selection=parseInt(f.months2[f.months2.selectedIndex].value);
        ret_val = 0;
        if(f.months2[f.months2.selectedIndex].value == 28)
        {
                year=parseInt(f.years2.options[f.years2.selectedIndex].value);
                if (year % 4 != 0 || year % 100 == 0 ) ret_val=0;
                else
                        if (year % 400 == 0)  ret_val=1;
                        else
                                ret_val=1;
        }
        selection = selection + ret_val;
        for(x=1;x < selection+1;x++)

        {
                days_arr[x-1]=new Option(x);
                f.days2.options[x-1]=days_arr[x-1];
        }
        if (temp == -1) f.days2.options[0].selected=true;
        else
             f.days2.options[temp].selected=true;
}
function year_install1(f)
{
        document.writeln("<SELECT name=\"years1\" id=\"years1\" onchange=\"update_days1(searchfields)\">")
        for(x=2004;x<2008;x++) document.writeln("<OPTION value=\""+x+"\">"+x);
        document.writeln("</SELECT>");
        update_days1(f);
}
function year_install2(f)
{
        document.writeln("<SELECT name=\"years2\" id=\"years2\" onchange=\"update_days2(searchfields)\">")
        for(x=2004;x<2008;x++) document.writeln("<OPTION value=\""+x+"\">"+x);
        document.writeln("</SELECT>");
        update_days2(f);
}

//selecting default dates on Load
function selectDefault1(f)
{
		var selDay = document.getElementById('days1');
		selDay.selectedIndex = 0;
		var selMon = document.getElementById('months1');
		selMon.selectedIndex = 0;
		var selYear = document.getElementById('years1');
		selYear.selectedIndex = 0;
}
function selectDefault2(f)
{
		var nowDate = new Date();
		var today = nowDate.getDate();
		var thisMonth = nowDate.getMonth();
		var thisYear = nowDate.getYear();
		var selDay = document.getElementById('days2');
		selDay.selectedIndex = today-1;
		var selMon = document.getElementById('months2');
		selMon.selectedIndex = thisMonth;
		var selYear = document.getElementById('years2');
		selYear.selectedIndex = 3;

}
*/
var numDays = {jan: 31, mar: 31, apr: 30, may: 31, jun: 30,
jul: 31, aug: 31, sep: 30, oct: 31, nov: 30, dec: 31};

function checkLeap(nYear) {
return (nYear % 4 == 0) ? 29 : 28;
}

function isDefault(oSelect) {
return oSelect[oSelect.selectedIndex].defaultSelected;
}

function setDays(oMonthSel, oDaySel, oYearSel) {
if (isDefault(oMonthSel) && isDefault(oDaySel)) return false;
var opt, oForm = oMonthSel.form;
var nDays = numDays[oMonthSel[oMonthSel.selectedIndex].value];
if (nDays == null && !isDefault(oYearSel))
nDays = checkLeap(oYearSel[oYearSel.selectedIndex].value);
var oDaySelLgth = oDaySel.length - 1;
	if (nDays != oDaySelLgth) {
		if (nDays<oDaySelLgth)
			oDaySel.length = nDays + 1;
		else {
			for (var i=1; i<nDays-(oDaySelLgth-1); i++) {
				opt = new Option(oDaySelLgth + i, oDaySelLgth + i);
				oDaySel.options[oDaySel.length] = opt;
				}
			}
	}
}

function checkdate(oForm) {
	if (!checkDateFields(oForm)){
	return true;
	}
	else {
	/*var oMonthSel = oForm.month, oDaySel = oForm.day, oYearSel = oForm.year;
	var aStr = msg = '';
	if (isDefault(oMonthSel))
		msg += 'MONTH\n';
	if (isDefault(oDaySel))
		msg += 'DAY\n';
	if (isDefault(oYearSel))
		msg += 'YEAR\n';
	if (msg != '' && !msg.match(/^MONTH\nDAY\nYEAR\n$/)) {
		aStr = '\nPlease choose from the following:\n\n';
		aStr += msg + '\n...to complete the date selection.\n\nThanks !\n\n';
		alert(aStr);
		oMonthSel.focus();*/
		return false;
		}
	//return true;

}


function checkDateFields(theform) {
if ((theform.days1.value) &&
(theform.months1.value) &&
(theform.years1.value) &&
(theform.days2.value) &&
(theform.months2.value) &&
(theform.years2.value)) {
	return true; }
else {
	return false;
	}
}

//Parsing search Parameters and minor validation.
function makeDates(theform){
	if (!checkDateFields(theform)) {
	var std = "";
	var end = "";
	return true;
	}
	else {

	//if (checkdate(theform)){
		var dst = theform.days1.value;
		if (dst<10){ dst = "0"+dst;}
		var mst = theform.months1.value;
		//if (mst<10){ dst = "0"+mst;}
		var yst = theform.years1.value;
		var std = yst+mst+dst;

		var dend = theform.days2.value;
		if (dst<10){ dst = "0"+dst;}
		var mend = theform.months2.value;

	//if (mend<10){ mend = "0"+mend;}
		var yend = theform.years2.value;
		var end = yend+mend+dend;

		theform.std.value = std;
		theform.end.value = end;
		var ending=new Date(yend,mend,dend);
		//alert ("ending is "+ ending);
		var starting=new Date(yst,mst,dst);
		//alert ("starting is "+ starting);
		var diff=Math.floor(ending.getTime()-starting.getTime());
		if(diff<0)
			{
			return false;
			}
		else
			{
			return true;
			}
		//}
	}
}


function submitForm(theform)
{
	var datesok = makeDates(theform);
	// check that end date is after start date
	if (datesok)
	{
		// submit the form
		theform.submit();
	}
	else
	{
		// show error message and don't submit the form

		alert("Please ensure end date does not occur before start date.");
		//document.theform.af.focus();

	}
}

function parseDate(){
	var theform = document.getElementById("searchfields");
	var firstdate = theform.sdate.value;
	var re = new RegExp ("/", "g");
	var std = firstdate.replace(re, "");
	//std = std.replace("/", "");
	//alert ("std = "+ std);
	var seconddate = theform.edate.value;
	var end = seconddate.replace(re, "");
	//end = end.replace("/", "");
	//alert ("end = "+ end);
	theform.std.value = std;
	theform.end.value = end;

}



