var siteVals = new Array()
var theAgent = navigator.userAgent
var isMac = (theAgent.indexOf("Mac") >= 0) ? true : false
var spl = (isMac) ? "\r" : "\r\n"
//setVar("splitByRet",spl)

function getButton(n,v,c){
	var nme = (n) ? " name=\"" + n + "\"" : ""
	var val = (v) ? " value=\"" + v + "\"" : ""
	var onC = (c) ? " onclick=\"" + c + "\"" : ""
	return "<input type=\"button\"" + nme + val + onC + ">"
}

function parseArgs(fArgs){// returns a labelled array of arguments passed to a function, separate label from value with :
	var args = new Object()
	for (var i = 0; i < fArgs.length; i++){
		var a = fArgs[i]
		if(a.name){
			args[a.name] = a.obj
		} else {
			args[a.slice(0,a.indexOf(":"))] = a.slice(a.indexOf(":") + 1)
		}
	}
	args.common = commonTags
	if(args.args){return args.args}
	return args
}

function commonTags(){
	var htm = (this.id) ? ' id="' + this.id + '"' : ''
	htm += (this.cls) ? ' class="' + this.cls + '"' : ''
	htm += (this.name) ? ' name="' + this.name + '"' : ''
	return htm
}

function argObj(n,v){// used to pass a javascript object to a function through parseArgs()
	this.name = n
	this.obj = v
}

// String Functions

function insertBR(asAry){
	v = this.split(spl)
	if(!asAry){
		v = v.join("<br>")
	}
	return (v) ? v : this
}

function stripAmpersand(){
	var newA = this.split("&")
	if (newA.length > 1){
		var aStr = ""
		for (var i = 0; i < newA.length; i++){
			aStr += (i == newA.length - 1) ? newA[i] : newA[i] + " & "
		}
	} else {
		var aStr = this
	}
	return aStr
}

function capitaliseProto(w){
	t = "" + this
	if(w){
		var tSplit = t.split(" ")
		for (var i = 0; i < tSplit.length; i++){
			if (tSplit[i] != tSplit[i].split(spl)){
				var temp = tSplit[i].split(spl)
				for (var y = 0; y < temp.length; y++){
					temp[y] = capWord(temp[y])
				}
				tSplit[i] = temp.join(spl)
			} else {
				tSplit[i] = capWord(tSplit[i])
			}
		}
		t = tSplit.join(" ")
	} else {
		t = capWord(t)
	}
	return t
}

function capWord(t){
	t = "" + t
	tl = t.length
	fl = t.substring(0,1)
	fl = fl.toUpperCase()
	ol = t.substring(1,tl)
	ol = ol.toLowerCase()
	return  fl + ol
}

function replaceChar( srch , repl ) {
	var build = "" ;
	for (var i = 0; i < this.length; i++) {
		var oneChar = this.substring(i, i + 1)
		if (oneChar == srch ) {
			build += repl
		} else {
			build += oneChar
		}
	}
	return build
}

function parseString(){
	var args = parseArgs(parseString.arguments)
	var repl = (args.find) ? args.find : ""
	repl = (repl == "<empty>") ? "" : repl
	repl = (args.crs) ? spl : repl
	repl = (args.splt) ? repl.split(args.splt) : repl
	if(args.del){var newT = this.split(repl); return newT.join("")}
	if(!args.replace){return this.split(repl)}
	repl = (typeof repl == 'string') ? new Array(repl) : repl 
	if(args.splt){
		var newVal = args.replace.split(args.splt)
	} else {
		var newVal = (typeof args.replace == 'string') ? new Array(args.replace) : args.replace
	}
	var newT = '' + this
	for (var i = 0; i < repl.length; i++){
		newT = newT.split(repl[i])
		var nv = (newVal[i]) ? newVal[i] : newVal[0]
		nv = (nv == "<delete>") ? "" : nv
		nv = (nv == "<ret>") ? spl : nv
		newT = newT.join(nv)
	}
	switch(args.cnvrt){
		case "lc" : return newT.toLowerCase()
		case "uc" : return newT.toUpperCase()
		default : return newT
	}
}

function getFrontObj(searchStr){
	foundOffset = this.indexOf(searchStr)
	if (foundOffset == -1) {
		return null
	}
	return this.substring(0,foundOffset)
}

function getEndObj(searchStr){
	foundOffset = this.indexOf(searchStr)
	if (foundOffset == -1) {
		return null
	}
	return this.substring(foundOffset+searchStr.length,this.length)
}


// end string functions

// Array functions

function twoDarray(cols,obj){ // returns the array passed in a block the specified columns wide
	if(this.length){
		var trs = new Array()
		for (var i = 0; i < this.length; i++){
			var alg = (i - (i % cols))/cols
			var val = (obj) ? this[i] : this[i] + " "
			if (i % cols == 0){
				trs[alg] = new Array(val) 
			} else {
				trs[alg][i % cols] = val
			}
		}
		return trs
	} else {return false}
}

function buildTR(){
	var temp = this.join("")
	return retTableRow(temp)
}

function buildTBR(){
	var temp = ""
	for(var i = 0; i < this.length; i++){
		temp += this[i].tr()
	}
	return temp
}

function existsArrayProto(val,label) {
	var aVal,temp
	for (var i = 0; i < this.length; i++) { 
		aVal = this[i]
		if (label){
			aVal = eval("aVal." + label)
		}
		if (val == aVal) { 
			return i + 1
		}
	}
	return false
}

// End Array functions

function TBO(a,b,p){
	var args = parseArgs(TBO.arguments)
	this.intID = a
	this.user = (b) ? b : a
	this.params = (p) ? p : ""
}

function locDrop(){
	var args = parseArgs(locDrop.arguments)
	if(this.length > 0){
		var so = new Array()
		for(var i = 0; i < this.length; i++){
			if(this[i]){so[so.length] = this[i].option}
		}
		args.name = (args.name) ? args.name : 'location id'
		args.opts = so
		return makeSel(new argObj('args',args))
	} else {
		return ''
	}
}

// Date Time Functions
 
function withinQuarter(a,b){
/*	var a = a.split('/')
	var b = b.split('/')
	var t1 = (parseInt(a[2]) * 12) + parseInt(a[1])
	var t2 = (parseInt(b[2]) * 12) + parseInt(b[1])
	if ((t2-t1+1) < 4) {*/
		return true
/*	} else {
		alert('Cannot enter a date range that is longer than a quarter (3) months.')
		return false
	}*/
}

function validDate(txt){
	var temp = txt.split('/')
	if(temp.length != 3){
		return vDateAlrt()
	} else {
		var ml = new Array(31,(temp[2] % 4) ? 28 : 29,31,30,31,30,31,31,30,31,30,31)
	}
	if(temp[2].length != 4){
		return vDateAlrt()
	} else if (parseInt(temp[0]) < 1 || parseInt(temp[1]) < 1 || parseInt(temp[1]) > 12){
		return vDateAlrt()
	} else if (temp[0] > ml[parseInt(temp[1]) - 1]){
		return vDateAlrt()
	} else {
		return true
	}
}

function vDateAlrt(){
	alert('You must enter the date in the format dd/mm/yyyy.')
	return false
}

function formatType(a){
	a = a.toLowerCase()
	var b
	if (a == "inter"){
		b = "On-Site"
	} else if (a == "ph int") { 
		b = "Phone"
	} else {
		b = "Translation"
	}
	return b
}

function retEndTime(Ph,te,ts,bl){
	var strt = ts.split('/')
	var fini = te.split('/')
	var fTime = formatTime(te)
	var sTime = formatTime(ts)
	var sVals = new timeSplit(sTime)
	var theStart = retDate(strt[0],strt[1],strt[2],sVals.hr,sVals.min,0)
	var fVals = new timeSplit(fTime)
	var theFin = retDate(fini[0],fini[1],fini[2],fVals.hr,fVals.min,0)
	var b = theFin - theStart
	b = b/1000/60
	if(formatType(Ph) == "Phone") {
		return fTime
	} else if (b < (bl * 60)){
		var hrs = parseInt(sVals.hr) + parseInt(bl)
		var mins = parseInt(sVals.min) + ((bl - parseInt(bl)) * 60)
		if(mins >= 60){
			var temp = (mins/60) - parseInt(mins/60)
			hrs += parseInt(mins/60)
			mins = parseInt(temp * 60)
		}
		if (hrs >= 18 && ((sVals.hr * 60) + parseInt(sVals.min) + b) <= (18 * 60)){
			return formatTime("18:00")
		} else {
			return formatTime("" + hrs + ":" + mins) // sVals.min
		}
	} else {
		return fTime
	}
}

function retEndTimeObj(inInt){
	try{
		if(this.service.time.end){
			var theDay = this.service.day.num
			var theMonth = this.service.month
			var theYear = this.service.year
			var bl = this.client.minBookLength
			var sVals = new timeSplit(this.service.time.start)
			var theStart = retDate(this.service.day.num,theMonth,theYear,sVals.hr,sVals.min,0)
			var fVals = new timeSplit(this.service.time.end)
			var theFin = retDate(theDay,theMonth,theYear,fVals.hr,fVals.min,0)
			var b = theFin - theStart
			b = b/1000/60
			if(formatType(this.type) == "Phone") {
				return this.service.time.end
			} else if (b < (bl * 60)){
				var hrs = parseInt(sVals.hr) + parseInt(bl)
				var mins = parseInt(sVals.min) + ((bl - parseInt(bl)) * 60)
				if(mins >= 60){
					var temp = (mins/60) - parseInt(mins/60)
					hrs += parseInt(mins/60)
					mins = parseInt(temp * 60)
				}
				if (hrs >= 18 && ((sVals.hr * 60) + parseInt(sVals.min) + b) <= (18 * 60)){
					return formatTime("18:00")
				} else {
					return formatTime("" + hrs + ":" + mins) // sVals.min
				}
			} else {
				return this.service.time.end
			}
		} else {
			return "Not Supplied"
		}
	} catch(e) {
		return ""
	}
}

function formatTime(t) { 
	if(t){
		t = "" + t
		var temp = t.split(":")
		if(temp.length > 2){
			temp.length = 2
			t = temp.join(":")
		}
		re = new RegExp (":00","gi")
		newT = t.replace(re,""); newT = newT.toLowerCase()
		c = t.indexOf(":",1)
		h =  "" + parseInt(t.slice(0,c),10)
		if (newT.indexOf("pm",1) >= 0){
			var hh = parseInt(h) + 12
		} else { 
			var hh = parseInt(h) 
		}
		var temp = newT.end(h)
		var min = parseInt(substString(newT.end(h),":",""),10)
		var prem = (min < 10) ? "0" : ""
		var min = (isNaN(min)) ? ":00" : ":" + prem + min
		var midC = (h == 12) ? 12 : 0
		if(hh < 12){
			var tt = "" + hh + min + " am"
		} else {
			var tt = ((newT.indexOf("pm",1) < 0 || newT.indexOf("am",1) < 0) && hh == 12) ? hh : hh - 12 
			tt = (tt == 0) ? "" + tt + min + " am" : "" + tt + min + " pm"
		}
		tt = tt.toLowerCase()
		return tt
	} else { return "" }
}

function timeSplit(a){
	var h = a.front(":") // getFront(a,":")
	this.hr = (a.indexOf("pm") > -1 && h != 12) ? parseInt(h) + 12 : parseInt(h) 
	var temp = a.parseStr('find:' + h + ':','replace:<delete>') 
	this.min = temp.front(" ")
}

// End Time Functions

// Other Functions

function start( evnt , debug ) {
	try{
		var x = (posRight()-230) + 'px';
		var b = ( browser == 'Firefox' ) ? 65 : 55
		var y = (posBottom() - b) + 'px';
		var foot = document.getElementById('moveableFooter')
		if ( foot.style.height ) {
			b = parseInt ( foot.style.height ) + ( ( browser == 'Firefox' ) ? 14 : 4 )
			y = ( posBottom() - b ) + 'px' ;
		}
//		showProps ( foot , 'foot' , 'show' ) 
		foot.style.left = bdLeft
		foot.style.width = bdWidth
		foot.style.top = y
	} catch (e) {
	
	}
}

var bdWidth, bdLeft

function winResize( evnt , debug ){
	try{
		var bd = document.getElementById('bodyData')
		bdWidth = bd.offsetWidth
		bdLeft = bd.offsetLeft
	} catch (e) {}
	start('' , true )
} 

function moveFooterBrowserChanges(brows){
	if ( brows == 'Explorer' ) {
		var footObj = document.getElementById('footerObj')
		footObj.style.position = 'relative'
		footObj.style.top = '-35px'
	}
}

function testbook( msg , school , def , loc ){
	var pth = pathToBookings()
	var message = (msg) ? msg : 'Enter the number of bookings you wish to make...'
	var num = (school) ? 10 : ( ( def ) ? def : prompt(message,'10') )
	var goto = ( loc ) ? loc : 'OnSiteBook.php?numbook=' + parseInt(num)
	if (num != null){
		if ( parseInt(num) > 30 ) {
			testbook ( "Please enter a number that is up to 30")
		} else {
			try{
				document.location = pth + goto
			} catch (e) {
				document.location = pth + 'OnSiteBook.php'
			}
		}
	}
}

function pathToBookings(){
	var loc = '' + window.location
	var temp = loc.split('bookings/')
 	temp = temp[1].split('/')
	var pth = ''
	for ( var i = 0 ; i < temp.length - 1; i++){
		pth += '../'
	}
	return pth
}

// End Other Functions

// Standard Objects 

function homeLinks(a,b){
	var args = parseArgs(homeLinks.arguments)
	this.link = (args.link) ? args.link : "Link not specified"
	this.text = (args.text) ? args.text : this.link
	this.str = top.retLinkFromObj
}

function interpreterObj(){
	var args = parseArgs(interpreterObj.arguments)
	this.name = dispObj((args.name) ? args.name : '','lab:Name')
	this.surname = dispObj((args.sname) ? args.sname : '','lab:Surname')
	this.fullname = dispObj(this.name + ' ' + this.surname,'lab:Interpreter')
}

function dispObj(val){
	var args = parseArgs(dispObj.arguments)
	var str = new String(val)
	str.head = (args.nd) ? '' : rTC((args.lab) ? 'cont:' + args.lab.parseStr('find: ','replace:&nbsp;') : '',"nw:true",'va:t','w:100','cl:Heading')
	args.cl = 'listbody'
	args.cont = val
	str.nd = (args.nd) ? true : false
	str.data = (str.nd) ? '' : rTC(new argObj('args',args))
	str.cells = str.head + str.data
	str.td = dispObjTD
	str.tr = dispObjTR
	return str
}

function dispObjTD(){
	var args = parseArgs(dispObjTD.arguments)
	args.cont = '' + this
	args.cl = 'listbody'
	return (this.nd) ? '' : this.head + rTC(new argObj('args',args))
}

function dispObjTR(){
	var args = parseArgs(dispObjTR.arguments)
	return (this.nd) ? '' : rTR(this.td(new argObj('args',args)),(args.rcol) ? args.rcol : '')
}

function dispInpObj(a){
	var args = parseArgs(dispInpObj.arguments)
	var str = new String(a)
	str.bool = (a) ? true : false
	str.head = new String((args.head) ? args.head : '')
	var spcr = (args.spacer) ? rDivID("tag:span","w:" + args.spacer,"pos:r") : ''
	str.head.td = rTC('cont:' + str.head.parseStr('find: ','replace:&nbsp;') + ':' + spcr,"nw:true",'va:t','cl:Heading')
	str.noinp = (args.noinp) ? true : false
	args.type = (args.type) ? args.type.toLowerCase() : 'text'
	args.val = (args.type == 'textarea') ? a.parseStr('find:<br>','replace:<ret>') : a
	args.name = (args.fn) ? args.fn : (args.nfn) ? '' : '' + str.head
	str.inpObj = (args.inp) ? new String(args.inp) : new rInpObj(new argObj('args',args))
	if(args.inp){str.inpObj.str2 = new Function('return this')}
	str.td = dispInpObjTD
	str.htm = dispInpObjHTM
	return str
}

function dispInpObjTD(){
	var args = parseArgs(dispInpObjTD.arguments)
	args.cont = (this.noinp) ? '' + this : this.inpObj.str2()
	args.cl = 'listbody'
	return (this.nd) ? '' : rTC(new argObj('args',args))
}

function dispInpObjHTM(){
	var args = top.parseArgs(dispInpObjHTM.arguments)
	return this.head.td + this.td(new argObj('args',args))
}

function helpObj(){
	var args = parseArgs(helpObj.arguments)
	this.txt = (args.txt) ? args.txt : 'This is a help box'
	this.w = (args.w) ? args.w : 300
	this.h = (args.h) ? args.h : 200
	this.id = (args.id) ? args.id : ''
	this.top = (args.t) ? args.t : 10
	this.left = (args.l) ? args.l : 10
	this.width = (args.w) ? '' + args.w + 'px' : '300px'
}

// End Standard Objects

function retCDMLstring(){ // Defunct we are no longer using cdml. All references to this function should be removed before removing this function
	var args = top.parseArgs(retCDMLstring.arguments)
	if(args.db){
		if(args.fmat){
			var cdml = 'FMPro?-DB=' + args.db
			cdml += '&-Format=' + args.fmat
			if(!args.errOmit){
				cdml += '&-Error=' + ((args.err) ? args.err : args.fmat)
			}
			cdml += (args.lay) ? "&-lay=" + args.lay : ""
			cdml += (args.rec) ? '&-recid=' + args.rec : ''
			if(args.flds){
				var flda = (args.flds[0]) ? args.flds : new Array(args.flds)
				for(var i = 0; i < flda.length; i++){
					cdml += (flda[i].op) ? "&-op=" + flda[i].op : ''
					cdml += '&' + flda[i].name + '=' + flda[i].val
				}
			}
			cdml += (args.max) ? '&-Max=' + args.max : ''
			cdml += (args.act) ? '&-' + args.act : '&-Find'
			return cdml
		} else {
			return 'Error - no format file specified'
		}
	} else {
		return 'Error - no database specified'
	}
}

function cdmlField(n,v,o){ // Defunct we are no longer using cdml. All references to this function should be removed before removing this function
	this.name = (n) ? n : ''
	this.val = (v) ? v : ''
	this.op = (o) ? o : ''
}

// Handle CDML Errors

var errCodes = new Array()
errCodes["-1"] = "Unknown error"
errCodes["0"] = "No error"
errCodes["1"] = "User canceled action"
errCodes["2"] = "Memory error"
errCodes["3"] = "Command is unavailable (for example, wrong operating system, wrong mode, etc.)"
errCodes["4"] = "Command is unknown"
errCodes["5"] = "Command is invalid (for example, a Set Field script step does not have a calculation specified)"
errCodes["100"] = "File is missing"
errCodes["101"] = "Record is missing"
errCodes["102"] = "Field is missing"
errCodes["103"] = "Relationship is missing"
errCodes["104"] = "Script is missing"
errCodes["105"] = "Layout is missing"
errCodes["200"] = "Record access is denied"
errCodes["201"] = "Field cannot be modified"
errCodes["202"] = "Field access is denied"
errCodes["203"] = "No records in file to print or password doesn't allow print access"
errCodes["204"] = "No access to field(s) in sort order"
errCodes["205"] = "Cannot create new records; import can overwrite existing data"
errCodes["206"] = "Cannot change password or file is not modifiable"
errCodes["207"] = "Cannot access field definitions or file is not modifiable"
errCodes["300"] = "The file is locked or in use"
errCodes["301"] = "Record is in use by another user"
errCodes["302"] = "Script definitions are in use by another user"
errCodes["303"] = "Paper size is in use by another user "
errCodes["304"] = "Password definitions are in use by another user"
errCodes["305"] = "Relationship or value list definitions are in use by another user"
errCodes["400"] = "Find criteria is empty"
errCodes["401"] = "No records match the request"
errCodes["402"] = "Selected field is not a match field for a lookup"
errCodes["403"] = "Exceeding maximum record limit for trial version of FileMaker Pro"
errCodes["404"] = "Sort order is invalid"
errCodes["405"] = "Number of records specified exceeds number of records that can be omitted"
errCodes["406"] = "Replace/Reserialize criteria is invalid"
errCodes["407"] = "One or both match fields are missing (invalid relationship)"
errCodes["408"] = "Specified field has inappropriate data type for this operation"
errCodes["409"] = "Import order is invalid "
errCodes["410"] = "Export order is invalid "
errCodes["411"] = "Cannot perform delete because related records cannot be deleted "
errCodes["412"] = "Wrong version of FileMaker Pro used to recover file"
errCodes["500"] = "Date value does not meet validation entry options"
errCodes["501"] = "Time value does not meet validation entry options"
errCodes["502"] = "Number value does not meet validation entry options"
errCodes["503"] = "Value in field is not within the range specified in validation entry options "
errCodes["504"] = "Value in field is not unique as required in validation entry options "
errCodes["505"] = "Value in field is not an existing value in the database as required in validation entry options"
errCodes["506"] = "Value in field is not listed on the value list specified in validation entry option "
errCodes["507"] = "Value in field failed calculation test of validation entry option"
errCodes["508"] = "Invalid value entered in Find mode "
errCodes["509"] = "Field requires a valid value"
errCodes["510"] = "Related value is empty or unavailable"
errCodes["511"] = "Value in field exceeds maximum number of allowed characters"
errCodes["600"] = "Print error has occurred"
errCodes["601"] = "Combined header and footer exceed one page "
errCodes["602"] = "Body doesn't fit on a page for current column setup "
errCodes["603"] = "Print connection lost "
errCodes["700"] = "File is of the wrong file type for import"
errCodes["701"] = "Data Access Manager can't find database extension file "
errCodes["702"] = "The Data Access Manager was unable to open the session"
errCodes["703"] = "The Data Access Manager was unable to open the session; try later"
errCodes["704"] = "Data Access Manager failed when sending a query "
errCodes["705"] = "Data Access Manager failed when executing a query "
errCodes["706"] = "EPSF file has no preview image "
errCodes["707"] = "Graphic translator cannot be found "
errCodes["708"] = "Can't import the file or need color computer to import file"
errCodes["709"] = "QuickTime movie import failed "
errCodes["710"] = "Unable to update QuickTime file reference because the database is read-only "
errCodes["711"] = "Import translator can not be found "
errCodes["712"] = "XTND version is incompatible "
errCodes["713"] = "Couldn't initialize the XTND system "
errCodes["714"] = "Password privileges do not allow the operation"
errCodes["715"] = "Specified Excel worksheet or named range is missing"
errCodes["716"] = "A SQL query using DELETE, INSERT, or UPDATE is not allowed for ODBC import"
errCodes["800"] = "Unable to create file on disk"
errCodes["801"] = "Unable to create temporary file on System disk"
errCodes["802"] = "Unable to open file "
errCodes["803"] = "File is single user or host cannot be found"
errCodes["804"] = "File cannot be opened as read-only in its current state "
errCodes["805"] = "File is damaged; use Recover command"
errCodes["806"] = "File cannot be opened with this version of FileMaker Pro "
errCodes["807"] = "File is not a FileMaker Pro file or is severely damaged "
errCodes["808"] = "Cannot open file because access privileges are damaged"
errCodes["809"] = "Disk/volume is full "
errCodes["810"] = "Disk/volume is locked "
errCodes["811"] = "Temporary file cannot be opened as FileMaker Pro file"
errCodes["812"] = "Cannot open the file because it exceeds host capacity "
errCodes["813"] = "Record Synchronization error on network"
errCodes["814"] = "File(s) cannot be opened because maximum number is open"
errCodes["815"] = "Couldn't open lookup file "
errCodes["816"] = "Unable to convert file "
errCodes["817"] = "Unable to open file because it does not belong to this solution"
errCodes["818"] = "FileMaker Pro cannot network for some reason"
errCodes["900"] = "General spelling engine error "
errCodes["901"] = "Main spelling dictionary not installed "
errCodes["902"] = "Could not launch the Help system "
errCodes["903"] = "Command cannot be used in a shared file "
errCodes["904"] = "Command can only be used in a file hosted under FileMakerÝServer"

function errText(n){
	return errCodes[n]
}

// End Handle CDML Errors

