var debugMode=0
var lastcolselected='?'
var isIE = /*@cc_on!@*/false; //IE detector

function showSingleRP(RPID) {
    clearRPs()
    document.getElementById("Resource" + RPID).checked = true
    selectRP(document.getElementById("Resource" + RPID))
    showiframe()
}
function showToday() {//called from SUbDoc
    SelectSingleDate(0) //same as clicking 'Today'
}
function hideHlp() {
    document.getElementById('bannerdiv').style.display = "none"
    myResizeDef()
}
function gsSelectionChanged(pstr) {

    document.getElementById("txtselections").value = pstr 

    if (pstr == "") {
        disablebutt('btnnext', 'on')
        document.getElementById('btnnext').title = "You must first select desired time-slots"
    } else {
        var myarr = pstr.split( "|")
        var t1 = HMStoSec1(myarr[5]) //check duration against max allowed
        var t2 = HMStoSec1(myarr[6].replace("[", ""))
        var tdiff = (t2 - t1) / 60
        var rpid = myarr[0]
        var md = parseInt(document.getElementById("Resource" + rpid).getAttribute("md"))
        if(tdiff>md) {
            alert("Bookings for " + myarr[3] + " cannot be for longer than " + md + " minutes.\n Please de-select some of the selected time.")
            disablebutt('btnnext', 'on')
            document.getElementById('btnnext').title = "You must first select desired time-slots"
            return
        }

        disablebutt('btnnext', 'off')
        document.getElementById('btnnext').title = ""
        if (tdiff==md) { document.getElementById('btnnext').click() } //already selected max, so move on!
    }

}

function HMStoSec1(T) { // h:m or h:mpm
    var A = T.split(/\D+/);
    A[0] = parseInt(A[0])
    if (T.indexOf("pm") > -1 && A[0]<12) { A[0]+=12 } //get "12:00pm" for noon
    return (A[0] * 60 + +parseInt(A[1])) * 60 
}

function showHidePanel() {
    var el
    el = document.getElementById('hidePanel')
    if (document.getElementById('td1').style.display == "none") {
        document.getElementById('td1').style.display = "inline"
        el.src = "Static/I/slide1.jpg"
        el.title = "Hide Panel"
    } else {
        document.getElementById('td1').style.display = "none"
        el.src = "Static/I/slide2.jpg"
        el.title = "Show Panel"
    }

    myResizeDef()
}

function tabclick(el) {
   tabdisplay(el)
   setbuttons()
   showiframe()
} //end tabclick

function tabdisplay(el) {
    var tabname
    var thisel
    var i, k
    tabname = "tbrps" + el.id //eg. tbrpstab1
    el.className = "tabon"
    //deselect all other tabs
    myarr = document.getElementById('tbtabs').getElementsByTagName('div')
    for (i = 0; i < myarr.length; i++) {
        thisel = myarr[i]
        if (thisel != el) {
            thisel.className = "taboff"
        }
    }

    //Hide all other RP 'tables'
    myarr = document.getElementById('tbrps').getElementsByTagName('table')
    for (i = 0; i < myarr.length; i++) {
        thisel = myarr[i]
        if (thisel.id.substring(0, 8).toLowerCase() == "tbrpstab" && el.id != tabname) {
            thisel.style.display = "none"
        }
    }
    document.getElementById(tabname).style.display = ""
    resetGSScroll = true
}

//function hideRPS() { //called from DefaultSub
//return vHideRPs 
//}


function myResizeIFrame(x, y) {
    mgf = document.getElementById('mygridframe')
    //Only enlarge, never shrink (or it will get successively smaller with repeated calls!)
//    if (x > mgf.offsetWidth) {mgf.style.width = x + "px" }
    //    if (y > mgf.offsetHeight) {mgf.style.height = y + "px" }
    mgf.style.width = x + "px" 
    mgf.style.height = y + "px" 
}

function myResizeDef(suppressResizeOfGS) {
    //if smallscreen mode then we will always be sizing MGF to its CONTENTS.
    //However, we will still pre-size MGF so that GS will at least TRY to fit within it.
    //BUT, we will never shink MGF in smallscreenmode -  e.g. if we were showing a long schedule
    //and then called maximizeMGFToWindow it would size MGF to fit in the WINDOW,and would thereby 'chop' the schedule (with no scrollbars on sr).
    //

    maximizeMGFToWindow(suppressResizeOfGS)

    if (document.getElementById("EventList")) {
        sizeToFillAvailableVertSpace(document.getElementById("EventList"), 28)
    }
}

function maximizeMGFToWindow(suppressResizeOfGS) {
    //Size MGF to fill all available space in current window. Do this even in small-screen mode (so that GS will at least TRY and fit in it)
    // if (!smallScreenMode) { //if we are to dynamically resize MGF according to window size       
    var mgf = document.getElementById('mygridframe')

    if (!smallScreenMode) {
        sizeToFillAvailableVertSpace(mgf, 25)
        sizeToFillAvailableHorizSpace(mgf, 10) //note HORIZONTAL
    } else { //we'll never shrink mgf in this mode (to ensure we dont make it smaller than current contents)
        sizeToFillAvailableVertSpace(mgf, 25, mgf.offsetHeight)
        sizeToFillAvailableHorizSpace(mgf, 10, mgf.offsetWidth) //note HORIZONTAL

        //since we may have stretched the window vertically, may as well grow the eventlist to fill it up! - note we are NOT sizing to WINDOW.
//if (document.getElementById("EventList")) { sizeToFillParentVert(document.getElementById("EventList"), document.getElementById("td1"), 15, 30) }
    }

    if (!suppressResizeOfGS && typeof (window.frames['mygridframe'].myGSResize) == "function") { window.frames['mygridframe'].myGSResize(mgf.offsetWidth - 3, mgf.offsetHeight - 3) }
}


function refreshGridsub() {  //This is called from Confirmed.aspx (which,in Admin module, is in a pop-up window OR in IFrame)
    //we could do self.location.href="gridsub.aspx?ReQuery=1", but we don't
    showiframe()
}
function reOpen() { //called from GS
    var s = 'Default.aspx?open=1' //this wont work cos of use of redirect to get here...location.href.replace(location.search, "") //strip querystring
    location.href=s
}
function showWL(RPIDs, Ddate) { //called from GS
  var s = "WaitingList.aspx?" + "RPIDs=" + RPIDs + "&ddate=" + Ddate 
    location.href = s
}
function goE(id) {
    location.href='ViewEvents.aspx?id=' + id
}
function mymouseover(evt) {//also assigned to mousedown - see myinit
evt=(evt) ? evt : ((window.event) ? window.event : null) //W3C pass the event
var el = (evt.target) ? evt.target : evt.srcElement //W3c uses target, IE used srcElement
if (el.tagName == 'TD') {
    if (el.className == 'calendarunsel') { el.className = 'calendart' }
    if (el.className == 'calendarunselom') { el.className = 'calendartom' }
}
}	
function mymouseout(evt) {
evt=(evt) ? evt : ((window.event) ? window.event : null) //W3C pass the event
var el= (evt.target) ? evt.target :evt.srcElement //W3c uses target, IE used srcElement
if (el.tagName == 'TD') {
    if (el.className == 'calendart') { el.className = 'calendarunsel' }
    if (el.className == 'calendartom') { el.className = 'calendarunselom' }
}
}	
function mycalclick(evt){
evt=(evt) ? evt : ((window.event) ? window.event : null) //W3C pass the event
var el = (evt.target) ? evt.target : evt.srcElement //W3c uses target, IE used srcElement
if (el.tagName == 'TD') {
    if (el.className == 'calendart' || el.className == 'calendartom' || el.className == 'calendarseldate' || el.className == 'calendarseldateom') {
        sd(el.id)
    }
}
}
//THis may get called from "bootCode" JS which is generated by Default.aspx.vb... directly from the header fields in GridSub to switch to Detail view. Optionally specifies which RP if we are currently showing >1
//bootcode is called from myInit()
function fSSD(d,rp,force) 
//d should be "dnnn",rp should be "4" or "4|66"
{
cleardates()
 document.getElementById('seldates').value="|"+d+"|"
//In MEMBER app. we should never hide RPs here (in case RP checkboxes are not displayed to user - he'll never get them back!). So passed 'rp' should always be blank in MEMBER app.
if (rp!="") {
	clearRPs()
} 
if (force) {showiframe()}
}

function getactivetbrpstab() { //find which 'tab' is active in tbrps (will be tbrps itself if none defined)
 var myarr,i, thisel
     myarr = document.getElementById('tbrps').getElementsByTagName('table')
     for (i = 0; i < myarr.length; i++) {
         thisel = myarr[i]
         if (thisel.id.substring(0,5)=='tbrps' &&(getRenderedStyle(thisel, "display") + "") != "none") {
            return thisel
         }
     }
     return document.getElementById('tbrps')
}

function getselBFid() { //returns eg. "234|Ball-machine" for on-screen selected BF (if any)
    if (document.getElementById('selbfid').value == "") {
        return null
    } else {
        return document.getElementById('selbfid').value
    }
}

function getselRPids() {
	var locselRPids;
	var strRPs
	strRPs=getselRPidsString()
	return strRPs==""?null:strRPs.split("|")
}
function setselRPids() { 
//This called (in onsubmit) when user clicks on another month. store away the selected RPs so can reset. 
document.getElementById("selRPids").value =getselRPidsString()
}
function getselRPidsString() { //returns e.g. "4|66"
	var locselRPids, thisel
	var strRPs=""
	myarr = getactivetbrpstab().getElementsByTagName('input')
    for (i = 0; i < myarr.length; i++) {
   	    thisel = myarr[i]
   	    if (thisel.id.substring(0,8).toLowerCase() == "resource") {
   	        if (thisel.checked) {strRPs+= thisel.getAttribute("mytag")+"|"}
   	    }
   	}
   	if (strRPs != "") { strRPs = strRPs.substr(0,strRPs.length - 1) }
 	return strRPs
}
function getseldates() {
//returns integers WITHOUT "d" prefix
    var locseldates
    var strseldates
    locseldates = document.getElementById('seldates').value.replace(/\|\|/g, "|");
    if (locseldates == "") { return null }
    locseldates = locseldates.replace(/d/g, "")
    strseldates = locseldates.substring(1, locseldates.length - 1).split('|');
    return strseldates
}
function clearRPs() {
    var inti
	//follow the same sequence of the splitting of array
	var theform = GetFormObject();
	strresources = getselRPids()
	if (strresources != null) {
	    for (inti = 0; inti < strresources.length; inti++) {
	        document.getElementById("Resource" + strresources[inti]).checked = false
	    }
	    setbuttons()
	}
	resetGSScroll = true
}
function setAllRPs() {
    var locselRPids, thisel
    var strRPs = ""
    myarr = getactivetbrpstab().getElementsByTagName('input')
    for (i = 0; i < myarr.length; i++) {
        thisel = myarr[i]
        if (thisel.id.substring(0, 8).toLowerCase() == "resource") {
            thisel.checked=true
        }
    }
    resetGSScroll = true
}

function disablebutt(id,mode) {
var el=document.getElementById (id)
	if (mode=='on'){
	    el.className="mybtndis"
		}			
	else {
	    el.className="mybtn"
	}
}

function ci(el,mode) {
	if (mode=='on'){
		el.src=el.src.replace ('_off.','_on.')}
	else {
		el.src=el.src.replace ('_on.','_off.')
	}		
}
function GetFormObject()
{
	var theform;
	if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) 
	{
		theform = document.Form1;
	}
	else 
	{
		theform = document.forms["Form1"];
	}	
	return theform;
}           

function showiframe()
{ 
    var theform = GetFormObject();
	if ((theform.seldates.value.length ==0) || (getselRPids()==null)) { return false}
	if (allowsuperpooling == 'no') {
		if ((theform.seldates.value.indexOf('||') != -1)  && (getselRPids().length >1)) { 
		alert ('You have selected more than 1 Date AND more than 1 Resource. This is not a valid combination to display. Please select a single Date OR a single Resource.')
		return false
		}
	}
	if ((theform.seldates.value.indexOf('||') != -1)  && (getselBFid()!=null)) {
	    alert('To see the availability of ' + getselBFid().substring(getselBFid().indexOf("|") + 1) + ', please select only a SINGLE date.')
		return false
	}
    if (!fudgeCode()) {return false} //see dyamic JS in Default.aspx

   //resetGSScroll = !keepScroll //see setDefaultForGridSub

//if (!keepScroll==true) { 
//	document.getElementById('gsX').value=0
//	document.getElementById('gsY').value=0
//} 
    //this removed 9/6/6 to allow user to resubmit same request (to refresh screen if looking for walk-on etc.)    disablebutt('btngo','on')
    disablebutt('btnnext','on')
    document.getElementById('btnnext').title="You must first select desired time-slots"

    var sss, changedLayout=false
    var mgf = document.getElementById('mygridframe')
    //not needed now that GS resizes itself to viewport (in JS)
//    var ht = mgf.offsetHeight - 3
//    var wd = mgf.offsetWidth - 3
    var fid

    sss = "reqresourceIDs=" + getselRPidsString() + "&reqdates=" + theform.seldates.value //+ "&gsy=" + ht + "&gsx=" + wd
    //sss += "&restricttoframesize=" + sizeMGFToWindow + (noavail == 1 ? "&noavail=1" : "") + (consolemode == 1 ? "&consolemode=1" : "")
    sss += "&mfip=" + (smallScreenMode ? 0 : 1) + (noavail == 1 ? "&noavail=1" : "") + (consolemode == 1 ? "&consolemode=1" : "")

    fid = getselBFid()
    //if (fid!=null) sss= encodeURI(sss + "&fid=") + encodeURIComponent(fid) //selbfid may contain eg "#"
    if (fid != null) { sss += "&fid=" + encodeURIComponent(fid) }  //selbfid may contain eg "#"

    if (document.getElementById("tinstructs0").style.display != "none") {
        document.getElementById("tinstructs0").style.display = "none"
        changedLayout = true
    }
    if (document.getElementById("tinstructs1").style.display != "block") {
        document.getElementById("tinstructs1").style.display = "block";
        changedLayout = true
    }
    
    document.getElementById("mygridframe").src = "gridsub.aspx?" + sss;    

     //if we've just changed displayed Help blocks, we need to resize Iframe to window. Hopefully this completes before (asynchronous) load of IFrame!
    if (changedLayout) {
        maximizeMGFToWindow(true) //suppressResizeOfGS=true cos we are immediately going to requery it
    }
    //we have just shown tinstructs, so re-calculate reqd. height of EventList to take up space (or whole form grow below window!)
//    if(document.getElementById("EventList")) {
//        sizeToFillAvailableVertSpace(document.getElementById("EventList"),28) 
//    }
} 

function setDefaultForGridsub(x,y) {
    //call when display a gridsub in IFrame. This gets invoked from onload of Gridsub.aspx
    var mgf = document.getElementById('mygridframe')
    if (smallScreenMode) { // size frame to declared content (used for small screens)
        //dont allow shrinking, or might 'chop' current contents
        
        myResizeIFrame(Math.max(mgf.offsetWidth, x), Math.max(mgf.offsetHeight, y))
        if (document.getElementById("EventList")) { sizeToFillParentVert(document.getElementById("EventList"), document.getElementById("td1"), 15, 30) }
    }
    if (!resetGSScroll) {
        window.frames['mygridframe'].document.getElementById("scrollregion").scrollTop = document.getElementById('gsY').value
        window.frames['mygridframe'].document.getElementById("scrollregion").scrollLeft = document.getElementById('gsX').value
    } else {
        resetGSScroll=false //for next time around
    }

    document.getElementById('btngo').className="mybtn"
    showmess()
}


function setDefaultForNonGridsub(disablePanel, x, y) {
    //call when display anything other than gridsub in IFrame. 
    if (smallScreenMode && typeof x!="undefined") { // size frame to declared content (used for small screens)
        //dont allow shrinking, or might 'chop' current contents
        var mgf = document.getElementById('mygridframe')
        myResizeIFrame(Math.max(mgf.offsetWidth, x), Math.max(mgf.offsetHeight, y))
        if (document.getElementById("EventList")) { sizeToFillParentVert(document.getElementById("EventList"), document.getElementById("td1"), 15, 30) }
    }
}
//function resizeGSToIFrame() {
//    var mgf = document.getElementById('mygridframe')
//    if (typeof (window.frames['mygridframe'].myGSResize) == "function") { window.frames['mygridframe'].myGSResize(mgf.offsetWidth - 3, mgf.offsetHeight - 3) }
//}

function selectRP(el) { //add or remove passed RP to list of 'selecteds'
var theform = GetFormObject();
//to add when selected the id of the check box
if (el.checked) {
	 if (!checkBFsandRPs(false)) {
	    el.checked = false
        return	   	    
    }
}
resetGSScroll = true
showiframe()
}
function selectRPmulti(el) {
//adds or removes the passed RP checkbox to the list of 'selecteds'
var theform = GetFormObject();	
//	This logic will avoid ever duplicating the code
if (el.checked) 
{   if (!checkBFsandRPs(false)) {
	    el.checked = false
        return	   	    
    }
}
resetGSScroll = true
//Changed 1/18/10 so that it now auto-refreshes Gridsub whenever court-type selection is changed (same as selectRP above)
//out 1/18/10 setbuttons();
showiframe()	
}	
function selectBF(el) { //if el is selected, then deselect, onscreen, all other BFs
   	var i,o, j
   	var v, bfid
   	var myarr, myarr2
   	var chkRP, thisel, isSelected
   	
   	document.getElementById('selbfid').value = ''
   	if (el.type == "checkbox") {
   	    isSelected = el.checked;
   	    if (isSelected) { document.getElementById('selbfid').value = el.getAttribute("mytag") + "|" + el.getAttribute("nn") }
   	}
   	if (el.type == "select-one") {
   	    isSelected = !(el.selectedIndex == 0)//ASSUME 0th element is '(None)'
   	    if (isSelected) { document.getElementById('selbfid').value=String(el.value) + "|" + el.options[el.selectedIndex].text } //fla   
   	 } 

   	if (isSelected) {
   	    //If already got a BF selected(hopefully a max of 1!), we will blindly deselect it
   	    myarr = getactivetbrpstab().getElementsByTagName('*')
   	    for (i = 0; i < myarr.length; i++) {
   	        thisel = myarr[i]
   	        if (thisel.name == "BFs") {
   	            // bfid = theform.selbfid.value.substring(0, theform.selbfid.value.indexOf("|"))
   	            if (thisel.type == "checkbox") {//its a checkbox
   	                if (el != thisel) { thisel.checked = false }
   	            }
   	            if (thisel.type == "select-one") {//its a cbo
   	                if (el != thisel) { thisel.selectedIndex = 0 }
   	            }
   	        }
   	    } //end for each INPUT
   	} else {
   	//if RP panel is hidden need to re-select ALL, because user can't see 'em!
   	if (vHideRPs) {
   	        setAllRPs()
   	    }   	
   	}
   	
	if (checkBFsandRPs(true)) { showiframe()}	
}

function checkBFsandRPs( deselectBadRPs) {
var bfid, chkBF, chkRP,o
   	//check combinations of selected RPs and bookable flags. OUter loop is for each BF (checkbox or combo), then inner loop for each RP

    if (getselBFid() != null) { //if already got a BF selected
        bfid = getselBFid().substring(0, getselBFid().indexOf("|"))
        if (document.getElementById('BF' + bfid)) {//its a checkbox
            chkBF = document.getElementById('BF' + bfid)
        } else { //must be an option in a Select, get parent Select
        myarr = getactivetbrpstab().getElementsByTagName('option')
            for (i = 0; i < myarr.length; i++) {
                o = myarr[i]
                if (o.value == bfid) {
                    chkBF = o.parentNode
                    break
                }
            }
        }
    }

    if (chkBF) { //if got a BF selected 
        lst = chkBF.getAttribute("allow") //eg. |4|66|
        //this changed to handle tabbed RP-selection box
        myrparr = getselRPids()
        if (myrparr != null) {
            for (j = 0; j < myrparr.length; j++) {
                chkRP = document.getElementById('Resource' + myrparr[j])
                if (lst.indexOf("|" + String(chkRP.getAttribute("mytag")) + "|") == -1) {
                    if (!deselectBadRPs) {
                        alert("\'" + chkRP.getAttribute("nn") + "\' cannot be selected in combination with \'" + chkBF.getAttribute("nn") + "\'. please de-select one of the incompatible options.")
                        return false
                    } else {
                        chkRP.checked = false
                        //chkRP.click()//this will actually deselect it, then invoke handler
                    }
                } 
            }
        }
    }
   	return true
}

function setbuttons(dontbotherhidingiframe) 	{
//call this after user clicks a date or a RP
	var theform = GetFormObject();
	if ((theform.seldates.value.length >1) && (getselRPids()!=null  ))
	{
		//theform.btngo.disabled=false
			    disablebutt('btngo','off')
	}
	else 
	{
		//theform.btngo.disabled=true
			    disablebutt('btngo','on')
	}
	//as selection changed... disable the next button as will reflect in change of the 
	//court timings and dates.
	
	if (theform.seldates.value.indexOf("||")!=-1) 
	{ //display this only if >1 date selected (which most users will never do)
		document.getElementById('btncleardates').style.visibility="visible"
		//disablebutt('btncleardates','on')
	}
	else
	{
	    document.getElementById('btncleardates').style.visibility="hidden"
	    //disablebutt('btncleardates','off')
	}
	
	disablebutt('btnnext','on')
	document.getElementById('btnnext').title="You must first view a schedule"
	EnableDisableNavigation()
}
function EnableDisableNavigation()
{
	var theform = GetFormObject();
	var strseldates
	var arrseldates
	var inti
	var dayint
	
	if (theform.seldates.value.length > 0) 
	{
		disablebutt('btnMoveNext','off')
	    disablebutt('btnMovePrev','off')
	    disablebutt('btnPrevWeek','off')
	    disablebutt('btnNextWeek','off')
		//Smart disabling of buttons. This is not only nice, it prevents a mess if they jump onto a "X" date

	    arrseldates = getseldates()
	    for (inti=0;inti < arrseldates.length;inti++)
	    {
		dayint=parseInt(arrseldates[inti])
		if (document.getElementById('x'+(dayint-7))) { disablebutt('btnPrevWeek','on')}//if this is shown as an 'X'ed date,
		if (document.getElementById('x'+(dayint-1))) { disablebutt('btnMovePrev','on')}
		if (document.getElementById('x'+(dayint+1))) { disablebutt('btnMoveNext','on')}
		if (document.getElementById('x'+(dayint+7))) { disablebutt('btnNextWeek','on')}
		}			
	} else {
		disablebutt('btnMoveNext','on')
	    disablebutt('btnMovePrev','on')
	    disablebutt('btnPrevWeek','on')
	    disablebutt('btnNextWeek','on')	
	}
}
function setselecteddates() { //sets styles in calendar
    var locarr = getseldates()
    if (locarr != null) {
        document.getElementById('seldates').value = "" //clear out
        for (inti = 0; inti < locarr.length; inti++) {
            sd('d' + locarr[inti])
        }
    }
}



function sd(elid,dontbotherhidingiframe) 
{
	//to select or unselect the date in the calendar control
   	var theform=GetFormObject();
	var el=document.getElementById(elid)
	var n=elid

	//tempting to use if (el.className=="calendarunsel") but this fails if date is not in currently-displayed month!
	if (theform.seldates.value.indexOf('|' + n + '|') == -1)
	{
		//we have just selected a new date
		if (!CheckDateCount())
		{
			return;
		}
		else 
		{ if (el) 
			{	if (allowmultidays=="N") {cleardates(true)}
			    if (el.className=='calendart' ||el.className=='calendarunsel') {
					el.className="calendarseldate"
				}
				if (el.className=='calendartom' ||el.className=='calendarunselom' ) {
					el.className="calendarseldateom"
				}
				el.title="Click again to unselect"
			}
			//to change the color on select	
			theform.seldates.value+='|' + n + '|'
			showiframe(true); setbuttons(true); return false 
		}
	}
	else
	{
		//we are UNselecting it
		//the element may not be visible if this called from cleardates()
		if (el)
		{
			//we set this attribute in the code behing in day render event
			if (el.className=="calendarseldate")
			{
				el.className ="calendarunsel";
			}
			else
			{
				el.className ="calendarunselom";
			}
			el.title="";				
		}
		theform.seldates.value=theform.seldates.value.replace('|' + n + '|','')		
	}
	setbuttons(dontbotherhidingiframe)
}


function myInit() {

    if (window.location.search.toLowerCase().indexOf('debug') > -1) { debugMode = 1 }
    //Blackberry touchscreens have a 'pan' mode which allows cursor to be moved over an element without ever activating mouseover event! So the click will never work (looks at TD className).
    //This fix only REQUIRED for BB (and other phones?), but think its safe to leave in for all (if not, add test for useragent contains "BlackBerry")
    //do this early on in myInit before BB craps out - it will!
    document.getElementById('Calendar1').onmousedown = new Function("event", "mymouseover(event)")
        
    smallScreenMode = (screen.width <= 800)  //IPhone returns 420 even though 840 px!
    if (smallScreenMode && document.getElementById('hidePanel')) { document.getElementById('hidePanel').style.visibility = "hidden" }  //not useful in this mode

    myResizeDef(true) //this will NOT invoke showiframe
	//to reflect the status of the resource pools
	if (document.getElementById('selRPids').value != '')
	{
	    //Page may have passed us a bad RPID in selRPids (e.g. if the RP used to exist but does not now). So check and remove refs. to any RPs that don't exist as selectable checkboxes.
        var RPids;
        var inti,rpo
        RPids = document.getElementById('selRPids').value.split("|")
        for (inti = 0; inti < RPids.length; inti++) {
            if(document.getElementById("Resource" + RPids[inti])) {    document.getElementById("Resource" + RPids[inti]).checked = true }
        }
        //If got multiple 'tabs' of RPs make the one that contains the above-selected RP(s), visible
        rpo=document.getElementById("Resource" + RPids[0]) //arbitrarily select first one
        while (true) {
            rpo = rpo.parentNode
            if (rpo.id) {
                if ((rpo.id + 'xxxxx').substring(0,5)=="tbrps"){
                    if (rpo.id.length > 5) { //its one tab of many eg. "tbrpstab2"
                        var tabName=rpo.id.replace("tbrps","") // for passing to tabdisplay
                        tabdisplay(document.getElementById(tabName))
                    }
                    break
                }
            }
        }
    }

	//now to reflect the status of the bookableflag id (if any) visually on screen
	//Note - this setting is ONLY retained across postbacks. NOT stored in cookie.
	if (getselBFid() != null) { //if already got a BF selected
	    var bfid, i
	    bfid = getselBFid().substring(0, getselBFid().indexOf("|"))
	    if (document.getElementById('BF' + bfid)) {//its a checkbox
	        document.getElementById('BF' + bfid).checked=true
	    } else { //must be an option in a Select, get parent Select
	        myarr = getactivetbrpstab().getElementsByTagName('option')
	        for (i = 0; i < myarr.length; i++) {
	            o = myarr[i]
	            if (o.value == bfid) {
	                o.parentNode.selectedIndex =i
	                break
	            }
	        }
	    }
	}
	//We may have set an incompatible set of RPs and a BF (in the case of a post-back when user had selected a BF and the RP-selection checkboxes are hidden (see VB)
	//so now DE-select any incompatible RPs

	checkBFsandRPs(true)

	
	if (allowmultidays=="N") {
        document.getElementById('btncleardates').style.display="none"
	} else {//allow row and col-selection in calendar
	for (var c=1;c<8;c++) 
	{	var mycell = document.getElementById('Calendar1').rows[1].cells[c];	
		mycell.innerHTML = "<a style='color:White' title='Select all days in column' href='javascript:selectweekday(" + c  +");'>" + mycell.innerHTML + "</a></font>";
	}
	var wkb
	var wkbid
	var dayint
	var startd=0
	for (var r=2;r<8;r++) 
	{	
		//find first selectable cell in this row, if any
		startd=0
		for (var c=1;c<8;c++) 
		{ 			
			var mycell= document.getElementById('Calendar1').rows[r].cells[c];
			if (mycell.className!="calendarna" && mycell.className!="calendarnaom") {startd=mycell; break}			
		}
		mycell=document.getElementById('Calendar1').rows[r].cells[0];
		if (startd!=0) {
			dayint=parseInt(startd.id.substring(1))
			mycell.innerHTML = "<font size='3'><a style='color:white' title='Select whole week' href='javascript:selectweek(" + dayint + ")'>&gt;</a></font>"
			} 
		else {
			mycell.innerHTML = "<font size='3'><Div style='color:DimGray'>&gt;</Div></font>"
		}
	}	
	}
	if (debugMode == 1) { alert('777') }	
		
	if(autoshowtoday){
	    showToday()
	}else {	
	    setselecteddates()	
	   //out 2/9/10 showiframe()
	}

	setbuttons()

	var c
//highlight today if shown in calendar
	dayint= GetTodaysDayNum()
	c = document.getElementById('d' + dayint)
	if (!c && document.getElementById('x'+dayint)) {
	c=document.getElementById('x'+dayint)
	}
	if(c) {c.style.color="firebrick";c.style.fontWeight="bold"}
		 	 
	 if (document.images)
    {
	var image1=new Image
	image1.src="Static/I/bgball.bmp"
	var image2=new Image
	image2.src="Static/I/bgball2.bmp"	
    }

    //only NOW do we set myGridFrame src
    if (MGFSrc != "") { document.getElementById("mygridframe").src = MGFSrc + "?mfip=" + (smallScreenMode?0:1)}
}
function showmess() {
//called from GS - used to display mess AFTER iframe is refreshed
if (displaymess!='') {alert(displaymess); displaymess=""}
}
function selectweekday(ColNum)
	{
		for (var r=1 ;r<8 ;r++) 
		{
			var mycell=document.getElementById('Calendar1').rows[r].cells[ColNum]

			if ((mycell.className =="calendarunsel")  || (mycell.className ==  "calendarunselom"))
			{
				if (!CheckDateCount())
				{
					return;
				}
				sd(mycell.id)			 //This will re-display GS on each calling!! Not good. Should have a mode that tells sd NOT to re-display.
			}
		} //endFor
	}
function selectweek(el) 
{
	var d=el
	//switch basis from 1/1/2000 to 1/1/2005
	var cstr
	for (var n=0; n<=6;n++) 
	{
		cstr="d"		
		dd=d+n
		cstr=cstr+dd //eg dn34
		
		if (document.getElementById(cstr)) 
		{	
			//will not exist if this is an 'unavailable' (past) date
			//also will be when the date is selected
			if ((document.getElementById(cstr).className =="calendarunsel")  || (document.getElementById(cstr).className == "calendarunselom"))
			{
				if (!CheckDateCount())
				{
					return;
				}
				sd(cstr)					
			}
		}
	}		
}
//
function cleardates(dontbotherhidingiframe) 
{
	//to clear all the selected dates
   	var theform=GetFormObject();
	var valarr
	//clear selections of dates in calendar

	valarr = getseldates()
	if (valarr != null) {
	    for (var n = 0; n < valarr.length; n++) {
	        sd('d' + valarr[n], dontbotherhidingiframe)
	        //this will unselect in calendar and remove them from seldates (also disables btngo and btncleardates)
	    }
	}
}
function  CheckDateCount()
{
	//limit how many can be selected
	var theform = GetFormObject();
	//
	var numd=0
	for (var m=0; m<=(theform.seldates.value.length)-1;m++) 
	{
		if (theform.seldates.value.charAt(m)=="|") 
		{
			numd+=1
		}
	}
	if (numd>(6*2)) 
	{
		//to check if other dates are remaing then only display else no dispaly
		alert('A maximum of 7 dates can be selected for display.');
		return false;			
	}
	else
	{
		return true;
	}
}

	function GetTodaysDayNum()
	//returns days since 1/1/5
{
    var dtDate1 =new Date();
    var dstr=(dtDate1.getMonth()+1) + "/" + dtDate1.getDate() + "/" + dtDate1.getFullYear() //assumes m/d/y
    return DateDiff("1/1/2005",dstr,"D",true)
}
function DateDiff( start, end, interval, rounding ) {
    var iOut = 0;    
    var bufferA = Date.parse( start ) ;
    var bufferB = Date.parse( end ) ;    		   
    var number = bufferB-bufferA ;    
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'w': case 'W': 
            iOut = parseInt(number / 604800000) ;
            if(rounding) iOut += parseInt((number % 604800000)/302400001) ;
            break ;
        case 'd': case 'D': 
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
    }   
    
    return iOut ;
}
function SelectSingleDate(para)
{
	//para will be 0 if called from today
	//para will be 1 if called from >
	//para will be -1 if called from <
	//para will be 'dnn' if called from fssd
	var theform = GetFormObject();	
	var daynum
	var dayint=0
	if (para==0) {//select today
		dayint= GetTodaysDayNum()	
		daynum="d" + dayint
		if (document.getElementById('x'+dayint))  {alert ("Sorry! Closed today."); return}//if closed
	}
	
	if (para!=0) {
		daynum=para //will be 'dnn'
		dayint=parseInt(para.substring(1))
	}
		cleardates(true) //true is new 9/20/8 for FF
	
	if (document.getElementById(daynum)) 
	{ //this date is currently displayed in calendar		
		sd(daynum)	
	}
	else 
	{	
		theform.seldates.value='|' + daynum + '|'; 	//Note, this date may end up being closed when we display the correct month
		document.getElementById('calendarjump').value=dayint
		mysubmitform()
	}	
}
function moveweek(delta){
		var inti;
		var arrseldates
		var strdates
		var daynum
		var gotone
		gotone=false
		var datetoskipto
		datetoskipto=0

		arrseldates = getseldates()
		if (arrseldates != null) {
		    cleardates(true)//tell it not to bother hiding iframe (and help panel) cos we are going to redisplay immediately (this avoids tiny flicker)
		    for (inti = 0; inti < arrseldates.length; inti++) {
		        dayint = parseInt(arrseldates[inti])
		        dayint = dayint + delta
		        daynum = "d" + dayint
		        if (!document.getElementById('x' + dayint)) { //if this is shown as an 'X'ed date, do nothing
		            if (document.getElementById(daynum)) //this date is currently displayed in calendar	
		            {
		                gotone = true
		                sd(daynum, true)	//tell it not to bother hiding iframe (and help panel) cos we are going to redisplay immediately (this avoids tiny flicker)
		            } else //manually add it
		            {
		                document.getElementById('seldates').value += '|' + daynum + '|'
		                if (datetoskipto == 0) { datetoskipto = dayint }
		            }
		        } else {
		            alert('That date is not available for booking')
		        }
		    }
		    if (!gotone && datetoskipto != 0) {
		        document.getElementById('calendarjump').value = datetoskipto //delta
		        mysubmitform()
		    }
		}
}
function mysubmitform() {
var theForm = document.forms['Form1'];
if (!theForm) {theForm = document.Form1};
theForm.submit();
}


