/********************************************************
Set of Global JavaScript functions to be used
troughout CodeStore!

Jake Howlett, v1.5, 23/10/00 20:46
********************************************************/

/*doSearch is called from the button 
below simple query box on all forms */

function doCourseSearch (a,b,c) {
	var regExp1 = /\bfield\b/i; //used to test for reserved word field in query string
	var regExp2 = /[(,),<,>,\[,\]]/; //used to test for reserved char(s) in the query string
	var coursestr = a;
	var modulestr = b;
	var unitstr = c;

	if ( trim(coursestr) == "<--Select a course-->"){
		alert("Please be sure to enter something to search for.");
		return false;
	} else {
		if ( typeof regExp1.source != 'undefined' ) //supports regular expression testing
			if ( regExp1.test( coursestr ) || regExp2.test( coursestr ) ){
					var alrt = "Please note that you can not include:";
					alrt += "\n\nThe reserved word 'field'\nthe characters [, ], (, ), < or >";
					alrt += "\n\nin your search query!\n\nIf you are confident that you know";
					alrt += "\nwhat you are doing, then you can\nmanually produce the URL required."
					alert( alrt );
					return false;
			}
			
			//alert(coursestr + " " + modulestr + " " + unitstr);


			if((trim(modulestr) == "<--Select a module-->") && (trim(unitstr) == "<--Select a unit-->")){
						searchstring = 'FIELD Course=' + escape(coursestr);			
			}
			else if(trim(modulestr) == "<--Select a module-->"){
						searchstring = 'FIELD Course=' + escape(coursestr) + ' And FIELD Unit=' + escape(unitstr);						
			}
			else if(trim(unitstr) == "<--Select a unit-->"){
						searchstring = 'FIELD Course=' + escape(coursestr) + ' And FIELD Module=' + escape(modulestr);							}
		
			else{
						searchstring = 'FIELD Course=' + escape(coursestr) + ' And FIELD Module=' + escape(modulestr)+ ' And FIELD Unit=' + escape(unitstr);								
			}
				

			document.location = "/Dev/Chinook/website.nsf/srch?SearchView&Query=" + searchstring + "&start=1&count=10&SearchFuzzy=True";
	}
}



function doSearch ( s ) {
	var regExp1 = /\bfield\b/i; //used to test for reserved word field in query string
	var regExp2 = /[(,),<,>,\[,\]]/; //used to test for reserved char(s) in the query string
	var str = s.value;

	if ( trim(str) == "" ){
		alert("Please be sure to enter something to search for.");
		s.focus();
		return false;
	} else {
		if ( typeof regExp1.source != 'undefined' ) //supports regular expression testing
			if ( regExp1.test( str ) || regExp2.test( str ) ){
					var alrt = "Please note that you can not include:";
					alrt += "\n\nThe reserved word 'field'\nthe characters [, ], (, ), < or >";
					alrt += "\n\nin your search query!\n\nIf you are confident that you know";
					alrt += "\nwhat you are doing, then you can\nmanually produce the URL required."
					alert( alrt );
					s.focus();
					return false;
			}
					document.location = "/Dev/Chinook/website.nsf/srch?SearchView&Query=" + escape( str ) + "&start=1&count=10&SearchFuzzy=True";
	}
}

/*open search results and append the search term in the URL..*/
function openAndHighlight( docID ) {
	appTerm = document.forms[0].SearchTerm.value;
	
	document.location = "/Dev/Chinook/website.nsf/all/" + docID + "?OpenDocument&Highlight=0," + escape( appTerm );
}

//Remove leading and trailing spaces from a string
//Originally written by Jim Fricker
function trim(aStr) {
	return aStr.replace(/^\s{1,}/, "").replace(/\s{1,}$/, "")
}

/*
getPathName
Required due to Opera bug where location.pathname
returns location.search as well.
*/
function getPathName(){
var pth = location.pathname.split('?');
return pth[0];
}

/*
NavigateView cycles through a view using the
start and count paramaters of the ?OpenView 
method.

Required as @Commands do not work with single
category views on the web !! 

Arguments:
d = direction, either "prev" or "next"
n = incremental count number
*/

function navigateView (d, n) {
	var c = 0;
	var args = location.search.split('&');

	var news = new Array();
	var ii = 0;

	for (var i = 0; i < args.length; i ++) {
		if ( args[i].toLowerCase().indexOf('start=') != -1){
			c = parseInt(args[i].split('=')[1]);
		} else {
			news[ii] = args[i];
			ii ++;
		}
	}
	
 	var strt = getPathName();
  	
	if (args[0] == ''){
		location.href = strt + '?OpenView&start=' + n;
	} else if (c == 0 && d == 'next'){
		location.href += '&start=' + n;
	} else if (c == 0 && d == 'prev'){
		return alert('There are no more documents in that direction.');
	} else 	if (c <= n && d == 'prev'){
		location.href = strt + news.join('&');
	} else 	if (d == 'next'){
		location.href = strt + news.join('&') + '&start=' + ( c + n );
	} else 	if (d == 'prev'){
		location.href = strt + news.join('&') + '&start=' + ( c - n);
	}
}

//Loads Projects and Subcodes

function populateModule(course, target, target2)
{

	//declare general variables
	//general variables
	var temp;
	var Index = 0;
	var thisOption;
	var StartPointer, EndPointer;
	var ResultList;
	var newOption;
		
	//Get Object Handles
	var thisForm = window.document.forms[0];
	var moduleList = thisForm.modulestructure.value;
	var module = thisForm.elements[target];
	var unitList = thisForm.unitstructure.value;
	var unit = thisForm.elements[target2];

	//Get value of newly Selected Course field
	var coursename = course.options[course.selectedIndex].text;
	
	//Clear Current Values from List
	module.options.length = 1;
	unit.options.length = 1;

	//Get list of Values for module Field
	var StartPointer = moduleList.indexOf(coursename+"[");
	

	if(StartPointer!=-1){
		var test = moduleList.indexOf("]",StartPointer);
		StartPointer +=coursename.length+1;
	
		/*Check to make sure the Pointer is a main header i.e. xxx(, rather than
		  part of one of the values*/
		if(StartPointer<test){

			EndPointer = moduleList.indexOf("]",StartPointer);
			ResultList = moduleList.substring(StartPointer,EndPointer);
				
			List = ResultList.split("**");
			for(var i in List){
				newOption = new Option(List[i]);
				module.options[module.options.length] = newOption;
			}
		}
	}
			
	//Get list of Values for unit Field
	var StartPointer = unitList.indexOf(coursename+"[");
	if(StartPointer!=-1){
		var test = unitList.indexOf("]",StartPointer);
		StartPointer +=coursename.length+1;
	
		/*Check to make sure the Pointer is a main header i.e. xxx(, rather than
		  part of one of the values*/
		if(StartPointer<test){
			EndPointer = unitList.indexOf("]",StartPointer);
			ResultList = unitList.substring(StartPointer,EndPointer);
					
			List = ResultList.split("**");
			for(var i in List){
				newOption = new Option(List[i]);
				unit.options[unit.options.length] = newOption;
			}
		}
	}
	module.options[0].selected=true;			
	unit.options[0].selected=true;			
}


function validateFAQ(course)
{

	var theForm = window.document.forms[0];
	var selectedCourse = course.options[course.selectedIndex].text;
	//var selectedModule = theForm.Module.options[Module.selectedIndex].text;
	//var selectedUnit = theForm.Unit.options[Unit.selectedIndex].text;
	var subject = theForm.Subject.value;
	var body = theForm.Body.value;
	var message;
	
	message = "";
	
	if(selectedCourse=="<--Select a course-->")
	{
		message = message + "Course\n";
	}

	if(subject=="")
	{
		message = message + "Subject\n";
	}

	if(body=="")
	{
		message = message + "Question\n";
	}
	

	
	if(message != "")
	{
		message = "The following fields must have a value before the document can be submitted.\n\n" + message + "\nPlease complete before resubmitting." ;	
		alert(message);
		return false;	
	}
	else
	{
	
		alert("This question has been submitted to the Buttercup's Team.\n");
		return true;
	}
}


/***********************************************************
Added for Website 050304 MSP
doDelete is used to delete the form from the server

The user is first asked to confirm that this is what they
want to do. Giving them the chance to cancel the action.
This works SIMPLY by changing the end of the URL from 
"?OpenDocument" to "?DeleteDocument"

************************************************************/

function doDelete() {
	if ( confirm('Are you sure you want to delete this document?') ){
		location.search = "?DeleteDocument";
	}
}

//Set of JavaScript functions used throughout the database......
function trim(aStr) {
	return aStr.replace(/^\s{1,}/, "").replace(/\s{1,}$/, "")
}

function fullTrim(aStr) {
	return trim(aStr.replace(/\s{2,}/g, " "))
}

function trimVBars(field) {
	return field.value.replace(/[|]{1,}/g, "");
}

function isEmpty(field){
	if (trim(field.value)=="" || field.value=="null"){
		return true;
	}
}

function checkNotEmpty(field,name) {
	if (isEmpty(field)) { 
		alert(name +' is a required field !');
		field.focus();
		return false;
	}
	return true;
}

function checkHasSelected(field,name,index) {
	if (field.selectedIndex==index) {
		alert(name +' is a required field !');
		field.focus();
		return false;
	}
	return true;
}

function dateSplicer(dateField,dateFormat){
	var results = new Array();
	dateStr = dateField.value; 
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	var matchArray = dateStr.match(datePat);
	
	if (matchArray == null) { 
		return null; 
	}
	// parse date into variables
	if (dateFormat.charAt(0)=="d"){ //what format does the server use for dates? 
		results[0] = matchArray[1];
		results[1] = matchArray[3];
	} else { 
		results[1] = matchArray[1];
		results[0] = matchArray[3]; }
	results[2] = matchArray[4];
	return results;
}

function isDate(dateField, dateFormat) { // Checks for a valid date format. 
	
	dateBits = dateSplicer(dateField,dateFormat);
	if (dateBits == null){return false;};

	day = dateBits[0];
	month = dateBits[1];
	year = dateBits[2];

	if ((month < 1 || month > 12) || (day < 1 || day > 31)) { // check month range 
		return false;
	} 
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}
	if (month == 2) {
	// check for february 29th 
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); 
		if (day>29 || (day==29 && !isleap)) {
			return false;
		}
	} 
	return true; 
} 

function checkDateRange(fieldName, fieldDesc, dateFormat, rngStart, rngEnd){ 
	UBoundOK = false; LBoundOK = false;

	if (!isDate(fieldName, dateFormat)){alert('not a date'); return false;};

	dateBits = dateSplicer(fieldName, dateFormat);
	var dateNow = new Date();
	var theDate = new Date(dateBits[2], Math.abs(dateBits[1])-1, dateBits[0]);

 if (dateNow.getTime()+(60*60*24*(365*(rngStart/12))*1000) < theDate.getTime()){ 
   LBoundOK = true;
	}

	if (theDate.getTime() < dateNow.getTime()+(60*60*24*(365*(rngEnd/12))*1000)){ 
   UBoundOK = true;
	}

	if (!LBoundOK || !UBoundOK){
		if(!LBoundOK){
			alert('This date needs to be greater than ' + rngStart + ' months in the future!'); 
			fieldName.focus();
		}else{
			alert('This date needs to be less than ' + rngEnd + ' months in the future!'); 
			fieldName.focus();
		}	
		return false;
	}else{
		return true;
	}
}

function isNumber(field){
	if (isNaN(field.value)==false){
		return true;
	}
}

function deleteFromView(doc) {
	if (confirm("This will delete the selected document(s) !")) {
		doc.applets.view.markSelectedDocumentsForDelete();
		doc.applets.view.deleteMarkedDocuments();
	}
}

function modOnClick(link, funcStr1, funcStr2) {
	var occ = link.onclick.toString()
	var idx1 = occ.indexOf("{")
	var idx2 = occ.lastIndexOf("}")
	link.onclick = new Function(funcStr1 + occ.slice(idx1 + 1, idx2) + funcStr2)
}

function dlATagOnClicks(doc) {
	for (var i = 0; i < doc.links.length; i++) {
		if (doc.links[i].onclick != null) {
			alert("document.links[" + i + "].onclick\n" + doc.links[i].onclick)
		}
	}
}

function dlHiddenVals(form) {
	for (var i = 0; i < form.elements.length; i++) {
		if (form.elements[i].type == "hidden") {
			alert(form.elements[i].name + " = " + form.elements[i].value)
		}
	}	
}

//function to do a quicksearch (all)
	function searchDB(path,query) {
		path+="?SearchView&Query="+query+"&Count=10";
				window.location.href = "/"+path;
}

function searchInputKeyPress() {
	keyed=window.event.keyCode;
	if (keyed==13){
		return false;
	}
}

/********************************************************
Set of Menu Functions

MSP 13/4/04
********************************************************/


<!-- hide script from old browsers

// Script to create a drop-down menu effect using layers.

//(c)Copyright Daren Craddock 2002

//You may use this code in any application, no limits,

//provided that you acknowledge Daren Craddock as the originator.



// big() makes selected layer longer (height property)

function resizeLayer(lyr, hgt) {

document.all[lyr].style.height=hgt; }









