// ----------------------------- text in user typing ---------------------------

function replaceAll(raw, needle, pin) {
    var soFar = raw
    var soFar2 = soFar.replace(needle, pin)
    while (soFar.replace(needle, pin) != soFar) {
	var soFar = soFar.replace(needle, pin)
    }
    return soFar
}

function removeAllChildren(insertHere) {
    while (insertHere.hasChildNodes()) {
	insertHere.removeChild(insertHere.firstChild)
    }
}

function processElementForWeb(elementType, rawText) {
    var newPart = document.createElement(elementType)
//    newPart.innerHTML = rawText

    var textLeft = rawText
    while (textLeft.indexOf('[') != -1) {
	var linkStarts = textLeft.indexOf('[')
	var linkEnds = textLeft.indexOf(']')
	var newTextNode = document.createTextNode(textLeft.substr(0,linkStarts))
	newPart.appendChild(newTextNode)

	var linkSplitter = textLeft.indexOf('|')
	var linkTextPart = textLeft.substr(linkStarts+1, linkSplitter-linkStarts-1)
	var linkHREFPart = textLeft.substr(linkSplitter+1, linkEnds-linkSplitter-1)

	// at this point we are probably looking at [text|URL]
	// but we might be looking at [span|personFieldname|currentText]
	// or we might be looking at [person|personCode]
	if (linkTextPart == 'span') {

	    var linkSplitter = linkHREFPart.indexOf('|')
	    var firstPart = linkHREFPart.substr(linkStarts+1, linkSplitter-linkStarts-1)
	    var secondPart = linkHREFPart.substr(linkSplitter+1, linkEnds-linkSplitter-1)

	    var newAnchor = document.createElement('span')
	    var newTextNode = document.createTextNode(secondPart)
	    newAnchor.id = firstPart
	    newAnchor.appendChild(newTextNode)
	    newPart.appendChild(newAnchor)

	} else if (linkTextPart == 'person') {

	    var requestString = 'http://www.psych.lancs.ac.uk/people/' + linkHREFPart + '.html'
	    var tempRequest = createXMLHttpObject()
	    tempRequest.open("GET", requestString, false)
	    tempRequest.send(null)
	    var theirWebPage = tempRequest.responseText
	    var theTitle = getXMLValue(theirWebPage, "title")
	    var theTitle = theTitle.replace("'s Homepage", "")
	    var theTitle = theTitle.replace("' Homepage", "")
	    var linkTextPart = theTitle

	    var linkHREFPart = 'http://'+location.hostname + '/people/' + linkHREFPart + '.html'

	    var newAnchor = document.createElement('a')
	    var newTextNode = document.createTextNode(linkTextPart)
	    newAnchor.href = linkHREFPart
	    newAnchor.appendChild(newTextNode)
	    newPart.appendChild(newAnchor)

	} else {
	    if (linkHREFPart.indexOf(':') == -1) {
	        linkHREFPart = processLocalLinkForWeb(linkHREFPart)
	    }
	    var newAnchor = document.createElement('a')
	    var newTextNode = document.createTextNode(linkTextPart)
	    newAnchor.href = linkHREFPart
	    if (linkHREFPart.substr(0,5) == 'http:') {
		newAnchor.target = '_blank'
	    }
	    newAnchor.appendChild(newTextNode)
	    newPart.appendChild(newAnchor)
	}

	textLeft = textLeft.substr(linkEnds+1)
    }
    var newTextNode = document.createTextNode(textLeft)
    newPart.appendChild(newTextNode)
    return newPart
}

function processTextForWeb(insertHere, rawText, imagePath) {
    removeAllChildren(insertHere)

    var textSoFar = replaceAll(rawText, String.fromCharCode(10),String.fromCharCode(13))
    var lineArray = textSoFar.split(String.fromCharCode(13))
    var elementArray = new Array()

    var currentStatus = 'normal'
    var listElement = document.createElement('ul')
    var tableElement = document.createElement('table')
    var tableBodyElement = document.createElement('tbody')
    tableElement.appendChild(tableBodyElement)
    for (var i=0;i<lineArray.length;i++) {
	var wholeThing = lineArray[i]
	var thisKindOfItem = 'normal'
	switch (wholeThing.substr(0,2)) {
	    case "C:":
            var paramArray = wholeThing.split(':')
            var newPart = document.createElement('div')
            newPart.style.marginLeft="32px"
            var subPart = document.createElement('p')
            subPart.innerHTML = paramArray[1]+'<br>Department of Psychology<br>Lancaster University<br>Fylde College<br>Lancaster LA1 4YF<br>United Kingdom'
            newPart.appendChild(subPart)

            var subPart = document.createElement('table')
            subPart.innerHTML = '<tr><td align="right">☎</td><td><a href="tel:'+paramArray[2]+'">'+paramArray[2]+'</a></td></tr><tr><td align="right">℻</td><td>01524 593744</td></tr><tr><td align="right">✇</td><td><a href="mailto:'+paramArray[3]+'?subject=Mail about the department web site">'+paramArray[3]+'</a></td></tr>'
            newPart.appendChild(subPart)
            break
	    case "E:":
            var paramArray = wholeThing.split(':')
            var linkHREFPart = 'http://www.psych.lancs.ac.uk/includes/eventTable.php?datasetName='+ paramArray[1]+'&format=' + paramArray[2]

            var requestString = linkHREFPart
            var tempRequest = new XMLHttpRequest()
            tempRequest.open("GET", requestString, false)
            tempRequest.send(null)
            var theirWebPage = tempRequest.responseText

            var newPart = document.createElement('div')
            newPart.id = wholeThing
            //newPart.innerHTML = theirWebPage
            processTextForWeb(newPart, theirWebPage, imagePath)
            break

	    case "P:":
            var paramArray = wholeThing.split(':')
            var linkHREFPart = 'http://www.psych.lancs.ac.uk/includes/publicationTable.php?fieldName='+ paramArray[1]+'&fieldValue=' + paramArray[2]

            var requestString = linkHREFPart
            var tempRequest = createXMLHttpObject()
            tempRequest.open("GET", requestString, false)
            tempRequest.send(null)
            var theirWebPage = tempRequest.responseText
            var newPart = document.createElement('div')
            newPart.id = wholeThing
            newPart.innerHTML = theirWebPage
            break
	    case "F:":
            var newPart = document.createElement('div')
            newPart.align = "center"
            var temp = wholeThing.substr(2)
            fadeListInit(newPart,temp)
            break
	    case "G:":
            var paramArray = wholeThing.split(':')
            var linkHREFPart = 'http://www.psych.lancs.ac.uk/includes/grantList.php?fieldName='+ paramArray[1]+'&fieldValue=' + paramArray[2]

            var requestString = linkHREFPart
            var tempRequest = createXMLHttpObject()
            tempRequest.open("GET", requestString, false)
            tempRequest.send(null)
            var theirWebPage = tempRequest.responseText
            var newPart = document.createElement('div')
            newPart.id = wholeThing
            newPart.innerHTML = theirWebPage

		break
	    case "T:":
            var newPart = processElementForWeb('h1', wholeThing.substr(2))
            document.title = wholeThing.substr(2)
            break
	    case "H:":
            var newPart = processElementForWeb('h2', wholeThing.substr(2))
            break
	    case "S:":
            var newPart = processElementForWeb('h3', wholeThing.substr(2))
            break
	    case "I:":
            var newPart = document.createElement('div')
            newPart.align = "center"
            var temp = wholeThing.substr(2)
            if (temp.indexOf(':') == -1) {
                var theFilename = imagePath + temp
                var theCaptionText = ''
            } else {
                var theFilename = imagePath + temp.substr(0,temp.indexOf(':'))
                var theCaptionText = temp.substr(temp.indexOf(':')+1)
            }
            if (theFilename.indexOf('@') == -1) {
                var theFixedSize = false
            } else {
                var theFixedSize = true
                var temp = theFilename.substr(theFilename.indexOf('@')+1)
                var theFilename = theFilename.substr(0, theFilename.indexOf('@'))
                var theWidth = temp.substr(0,temp.indexOf('x'))
                var theHeight = temp.substr(temp.indexOf('x')+1)
            }

            if ((theFilename.indexOf('.mov') != -1) | (theFilename.indexOf('.qt') != -1)){
                if (!theFixedSize) {
                    var sizeString = ''
                } else {
                    var sizeString = 'WIDTH = "'+ theWidth +'" HEIGHT = "'+ theHeight +'" '
                }
                var theEmbed = '<EMBED TYPE="video/quicktime" src="'+theFilename+'" href="'+theFilename+'" autoplay="true" CONTROLLER="false" LOOP="true" VOLUME="0" '+ sizeString +'scale="aspect" PLUGINSPAGE="http://www.apple.com/quicktime/download/"></EMBED>'
                var newPartPic = document.createElement('div')
                newPartPic.innerHTML = theEmbed
                newPart.appendChild(newPartPic)
            } else if (theFilename.indexOf('.pdf') != -1) {
                var newPartPic = document.createElement('img')
                newPartPic.src = theFilename
                if (theFixedSize) {
                    newPartPic.width = theWidth
                    newPartPic.height = theHeight
                }
                var newPartAnchor = document.createElement('a')
                newPartAnchor.href = theFilename
                newPartAnchor.appendChild(newPartPic)
                newPart.appendChild(newPartAnchor)
            } else {
                var newPartPic = document.createElement('img')
                newPartPic.src = theFilename
                if (theFixedSize) {
                    newPartPic.width = theWidth
                    newPartPic.height = theHeight
                }
                newPart.appendChild(newPartPic)
            }
            if (theCaptionText != '') {
                var newPartCaption = processElementForWeb('p', theCaptionText)
                newPart.appendChild(newPartCaption)
            }
            break
	    case "M:":
            var newPart = document.createElement('div')
            newPart.align = "center"
            var temp = wholeThing.substr(2)
            if (temp.indexOf(':') == -1) {
                var theFilename = imagePath + temp
                var theCaptionText = ''
            } else {
                var theFilename = imagePath + temp.substr(0,temp.indexOf(':'))
                var theCaptionText = temp.substr(temp.indexOf(':')+1)
            }
            if (theFilename.indexOf('@') == -1) {
                var theFixedSize = false
            } else {
                var theFixedSize = true
                var temp = theFilename.substr(theFilename.indexOf('@')+1)
                var theFilename = theFilename.substr(0, theFilename.indexOf('@'))
                var theWidth = temp.substr(0,temp.indexOf('x'))
                var theHeight = temp.substr(temp.indexOf('x')+1)
            }

                if (theFixedSize) {
                    var sizeString = ''
                } else {
                    var sizeString = 'WIDTH = "'+ theWidth +'" HEIGHT = "'+ theHeight +'" '
                }
                var theEmbed = '<EMBED TYPE="video/quicktime" src="'+theFilename+'" href="'+theFilename+'" autoplay="false" controller="true" '+ sizeString +'scale="aspect" PLUGINSPAGE="http://www.apple.com/quicktime/download/"></EMBED>'
                var newPart = document.createElement('div')
                newPart.align = "center"
                newPart.innerHTML = theEmbed

            if (theCaptionText != '') {
                var newPartCaption = processElementForWeb('p', theCaptionText)
                newPart.appendChild(newPartCaption)
            }
            break
	    case "* ":
            var thisKindOfItem = 'list'
            var newPart = processElementForWeb('li', wholeThing.substr(2))
            break
	    case "| ":
            var thisKindOfItem = 'table'
            var notTheEnds = wholeThing.substr(2, wholeThing.length - 4)
            var itemArray = notTheEnds.split(' | ')
            var newPart = document.createElement('tr')
            for (var j in itemArray) {
                var temp = itemArray[j]
    //		    var extraString = ''
                if (temp.substr(0,1) == ">") {
                var temp = temp.substr(1)
                var thisCell = processElementForWeb('th', temp)
                thisCell.align = "right"
                newPart.appendChild(thisCell)
                } else if (temp.substr(0,1) == "<") {
                var temp = temp.substr(1)
                var thisCell = processElementForWeb('th', temp)
                thisCell.align = "left"
                newPart.appendChild(thisCell)
                } else if (temp.substr(0,4) == "&gt;") {
                var temp = temp.substr(4)
                var thisCell = processElementForWeb('th', temp)
                thisCell.align = "right"
                newPart.appendChild(thisCell)
                } else {
                var thisCell = processElementForWeb('td', itemArray[j])
                newPart.appendChild(thisCell)
                }
            }
            break
	    case "A:":
            var restOfALine = wholeThing.substr(2)
            i++
            
    // we get here only if it's a 'A:start' line
            var squeezeDiv = document.createElement('div')
            squeezeDiv.id = 'squeezeDiv'
            squeezeDiv.className = 'squeezeDiv'
            var contentOfCurrentSection = ''
            var nestLevel = 0
            
    // keep processing lines until we get to an 'A:end'
            var finished = false
            while (finished == false) {
                var wholeThing = lineArray[i++]
                switch (wholeThing.substr(0,2)) {
                case "A:":
                    if (wholeThing.substr(2,5) == 'start') {
    // we're starting another one inside this one, so the 'start' line is just a normal line
                    contentOfCurrentSection += wholeThing + String.fromCharCode(13)
                    nestLevel++
                    } else {
                    if (nestLevel > 0) {
    // ignore it: it's something to do with an inner level
                        contentOfCurrentSection += wholeThing + String.fromCharCode(13)
                        if (wholeThing.substr(2,3) == 'end') {
                        nestLevel--
                        }
                    } else {
                        if (contentOfCurrentSection != '') {
                        var newDiv = document.createElement('div')
                        newDiv.className = 'squeezeContentDivOpen'
                        processTextForWeb(newDiv, contentOfCurrentSection, imagePath)
                        squeezeDiv.appendChild(newDiv)
                        var contentOfCurrentSection = ''
                        }
                        if (wholeThing.substr(2,3) == 'end') {
                        var finished = true
                        } else {
                        var newPara = document.createElement('p')
                        newPara.className = 'squeezeHeaderParaOpen'
                        newPara.title = 'Click to expand this section'
                        newPara.innerHTML = '▼ '+wholeThing.substr(2)
                        squeezeDiv.appendChild(newPara)
                        }

                    }
                    }
                    break
                default:
                    contentOfCurrentSection += wholeThing + String.fromCharCode(13)
                }
		}

		squeezeTrapClicks(squeezeDiv)
		var newPart = squeezeDiv
		break
	    default:
		var newPart = processElementForWeb('p', wholeThing)
	}

	if (thisKindOfItem != currentStatus) {
	    if (currentStatus == 'list') {		// just in case we're still in one of them
		elementArray.push(listElement)
		var listElement = document.createElement('ul')
	    } else if (currentStatus == 'table') {
		elementArray.push(tableElement)
		var tableElement = document.createElement('table')
		var tableBodyElement = document.createElement('tbody')
		tableElement.appendChild(tableBodyElement)
	    } else {
//		elementArray.push(newPart)
	    }
	}
	if (thisKindOfItem == 'normal') {
	    elementArray.push(newPart)
	} else if (thisKindOfItem == 'list') {
	    listElement.appendChild(newPart)
	} else if (thisKindOfItem == 'table') {
	    tableBodyElement.appendChild(newPart)
	}
	var currentStatus = thisKindOfItem
    }
    if (currentStatus == 'list') {			// just in case we're still in one of them
	elementArray.push(listElement)
    } else if (currentStatus == 'table') {
	elementArray.push(tableElement)
    }

    for (var i in elementArray) {
	insertHere.appendChild(elementArray[i])
    }
}

// -------------------------------- personal homepages -------------------------------------

function replacePersonalInformation(theContent, theShortName) {

//if (usingIE()) return 'temporarily not working under IE'

    var soFar = theContent

	var thePerson = theShortName
	var thePersonRecord = getSelectRecordsPerson("SELECT * FROM people WHERE shortname='"+ thePerson +"'")
	var thePersonRecord = getXMLValue(thePersonRecord, 'record')
	if (thePersonRecord == 'field does not exist') {
	    soFar = "Nobody with that name works for the department."
	} else {
	    gTheURL = 'people/'+ thePerson +'.html'

	    soFar = setPersonalField(soFar, 'id', thePersonRecord)
	    soFar = setPersonalField(soFar, 'shortname', thePersonRecord)
	    soFar = setPersonalField(soFar, 'name', thePersonRecord)
	    soFar = setPersonalField(soFar, 'possessive', thePersonRecord)
	    soFar = setPersonalField(soFar, 'phone', thePersonRecord)
	    soFar = setPersonalField(soFar, 'email', thePersonRecord)
	    soFar = setPersonalField(soFar, 'jabber', thePersonRecord)
	    soFar = setPersonalField(soFar, 'building', thePersonRecord)
	    soFar = setPersonalField(soFar, 'room', thePersonRecord)
	    soFar = setPersonalField(soFar, 'researchInterests', thePersonRecord)

//	    gTheMenuPath = replaceAll(gTheMenuPath, 'this person', getXMLValue(thePersonRecord, 'name'))
	}

    return soFar
}

function setPersonalField(theText, fieldName, personRecord) {
    var newThing = getXMLValue(personRecord, fieldName)
//    newThing = '<span id="'+fieldName+'">'+newThing+'</span>'
//    newThing = '[span|'+fieldName+'|'+newThing+']'
    var oldThing = '{'+fieldName+'}'
    return replaceAll(theText, oldThing, newThing)
}

function getSelectRecordsPerson(requestText) {
    var requestString = "/includes/ajax_doSelectPerson.php?command="+encodeURIComponent(requestText)
    var personRequest = createXMLHttpObject()
    personRequest.open("GET", requestString, false)
    personRequest.send(null)
    return personRequest.responseText
}

// ----------------------------- utilities ---------------------------

function getCookie(cookieName) {
    if (document.cookie.length > 0) {
	var cookieNameBegin=document.cookie.indexOf(cookieName + "=")
	if (cookieNameBegin != -1) { 
	    var cookieNameBegin = cookieNameBegin + cookieName.length+1 
	    var cookieEnd = document.cookie.indexOf(";",cookieNameBegin)
	    if (cookieEnd == -1) cookieEnd = document.cookie.length
	    return unescape(document.cookie.substring(cookieNameBegin, cookieEnd))
	} 
    }
    return ""
}

function getURLParameter(paramName) {
    var currentUrl = window.location.search
    var strBegin = currentUrl.indexOf(paramName) + (paramName.length+1)
    var strEnd = currentUrl.indexOf("&", strBegin)
    if (strEnd == -1) strEnd = currentUrl.length
    return currentUrl.substring(strBegin, strEnd)
}

function splitXMLRecords(theXML, theTag) {
    var startTag = '<'+theTag+'>'
    var endTag = '</'+theTag+'>'

    var rawArray = theXML.split(startTag)
    rawArray.shift()	// first part of array is before the first element
    for (var i in rawArray) {
	var theOffset = rawArray[i].indexOf(endTag)
	rawArray[i] = rawArray[i].substring(0,theOffset)
    }

    return rawArray
}

function getAllXMLValues(theXML) {
    var soFar = new Array()
    var theParts = theXML.split('</')
    theParts.pop()	// remove last one
    for (var i in theParts) {
	theOffset = theParts[i].lastIndexOf('>')
	soFar.push(unescapeXMLValue(theParts[i].substring(theOffset+1)))
    }

    return soFar
}

function getXMLValue(theXML, theTag) {
    var startTag = "<"+theTag+">"
    var endTag = "</"+theTag+">"
    if (theXML.indexOf(startTag) == -1) {
	return 'field does not exist'
    } else {
	var strBegin = theXML.indexOf(startTag) + (startTag.length)
	var strEnd = theXML.indexOf(endTag, strBegin)
	return unescapeXMLValue(theXML.substring(strBegin,strEnd))
    }
}

function unescapeXMLValue(raw) {
    cooked = raw.replace(/&amp;/g,"&")
    cooked = cooked.replace(/&lt;/g,"<")
    cooked = cooked.replace(/&gt;/g,">")
    cooked = cooked.replace(/&quot;/g,'"')
    cooked = cooked.replace(/&#39;/g,"'")
    return cooked
}

// ------------------------------- handling IE ---------------------------------


function usingIE() {
	browserString = navigator.appName
	return (browserString.indexOf("Microsoft") != -1)
}

function getCurrentTarget(theEvent) {
    if (usingIE()) {
	var e = window.event
	var theEventTarget = e.srcElement
    } else {
	var theEventTarget = theEvent.currentTarget
    }
    return theEventTarget
}


function createXMLHttpObject() {
    var soFar=null
    try {
	soFar = new ActiveXObject("Msxml2.XMLHTTP"); //later IE
    } catch (e) {
	try {
	    soFar = new ActiveXObject("Microsoft.XMLHTTP"); //earlier IE
	    } catch (e) {
		soFar = null;
	    }
    }

    if (soFar==null) {
	soFar=new XMLHttpRequest() //IE7, Firefox, Safari
    }
    return soFar
}
