var DBG = true;

Initialise();
function Initialise() {
	if(!DBG) window.onerror = ErrMsg;
	if(!window.SITE_PATH) window.SITE_PATH = ""; 		// if not specified, assume dedicated domain
	// OLD: 	
	CheckFrameset();
}

jQuery(document).ready(OnDocReady);
function OnDocReady($) {
	// OLD: FixPNGs($);
	TargetNonPageLinks($);
	RenameFavLink();
	ScheduleClock();
	EnableLoginLinkOnCtrlDblClick();
}

// *************************************************
// PAGE ROUTINES
// *************************************************

// on window error message, display in status bar (remove after 8 seconds)
function ErrMsg(vErrObjOrMsg, url, line) { 
	var sMsg = (typeof vErrObjOrMsg == "object")? vErrObjOrMsg.description : vErrObjOrMsg;
	window.status = sMsg + (line? "[line #"+ line +"]" : ""); 
	setTimeout("window.status = ''", 8000);
	return true; 
}

// if access content page directly, load in Haybridge frameset (live site only)
function CheckFrameset() {
	try {
		// abort redirect if localhost or already in live Haybridge CMS frameset
		if((/^http:\/\/.*\.neogic\.com|^http:\/\/localhost|^file:\/\/|^http:\/\/www\.haybridge\.worcs\.sch\.uk/i).test(top.location)) 
			// OLD:  if((/^(www\.)?haybridge\.worcs\.sch\.uk/i).test(top.location.hostname) || !( (/\bcms\b/i).test(location.hostname) ))
			return;
		else
			top.location = "http://www.haybridge.worcs.sch.uk" + top.location.pathname;

	} catch(oErr) { return; }			// abort if permission error accessing hostname
}

function PopupBigImg(oEvent) {
	var sBigImgPath, oImg = oEvent.srcElement || oEvent.target;
	if(oImg && oImg.src)
		sBigImgPath = oImg.src.substr(0,oImg.src.length-4) +"_big.jpg";
	if(sBigImgPath) 
		window.winBigImg = window.open(sBigImgPath, "winBigImg", "height=430,width=420,status=no,toolbar=no,menubar=no,location=no");
}

// IE only: login link hidden unless user double-clicks page while holding CTRL + ALT
// 		First time is called, attaches self as listener for dblclick event.
function EnableLoginLinkOnCtrlDblClick(e) {
	if(EnableLoginLinkOnCtrlDblClick.bInit) {
		e = e || window.event;
		if(e.ctrlKey /* DISABLED: && e.altKey */) { 
			window.jQuery('#divLogin').slideDown('normal'); 
			e.cancelBubble = true; e.stopPropagation(); 
		}
	}
	else {
		jQuery("BODY").dblclick(EnableLoginLinkOnCtrlDblClick);
		EnableLoginLinkOnCtrlDblClick.bInit = true;
	}
}


function SubmitSearchOnEnter(e, sSearchBtnId) {
	if(e.keyCode == 13) {
		// intercept ENTER key, click submit link instead
		if(e.stopPropagation) {
			e.stopPropagation(); e.preventDefault();
			// seems to be ignored in FF, click() doesn't work either!
			jQuery('#'+sSearchBtnId).click();
		}
		else {
			e.returnValue = false;
			document.getElementById(sSearchBtnId).click();
		}
	}
}

function SetSearchUrl(aSearchLink, sSearchBoxId) {
	var inpSearchBox = document.getElementById(sSearchBoxId);
	//aSearchLink.href = "http://www.google.com/search?domains=www.haybridge.worcs.sch.uk&sitesearch=www.haybridge.worcs.sch.uk&btnG=Search&q="
	aSearchLink.href = "http://www.google.com/search?domains=www.haybridge.worcs.sch.uk&sitesearch=www.haybridge.worcs.sch.uk&q="
		+ inpSearchBox.value;
		
	return true;
	
	/* ORIG FORM CODE:
		<form id="searchForm" target="_blank" method="get" action="http://www.google.co.uk/search">
			<input name="domains" type="hidden" value="www.haybridge.worcs.sch.uk" />
			<input name="sitesearch" type="hidden" value="www.haybridge.worcs.sch.uk" />
			<input name="q" type="text" size="20" />
			<input type="submit" name="btnG" value="Search" class="submit" />
		</form> 
	*/
}


// fix PNG images in IE5.5/IE6 via jQuery 'pngfix' plug-in
function FixPNGs($) {
	// if IE5.5/IE6, fix PNG transparency on IMG elements and #page
	if($.browser.msie && $.browser.version <= 6 && $.browser.version >= 5.5)
		$("#page").pngfix({ sizingMethod: "scale" });								// only fix side shadow PNGs, rest handled by HTC
		// OLD: $("IMG, #page").pngfix({ sizingMethod: "scale" });
}

// Returns scroll height (IE-specific) of tallest side column (#left/#right), or "auto" if neither has height.
// 	Used in CSS Expression in IE to make #centre match the height of tallest side col.
function GetLargestSideColHeight() {
	try {
		var iHeight = (window.left && (left.scrollHeight > 0))? left.scrollHeight : 0; 
		iHeight = (window.right && (right.scrollHeight > iHeight))? right.scrollHeight : iHeight; 
		return (iHeight > 0)? iHeight : "auto";
	} 
	catch(oErr) { return "auto" }
}

// target all hyperlinks to new window (+ give class 'extLink'), unless is internal page link (or already has 'target' defined)
function TargetNonPageLinks($, jqRootElem) {
	// alert("target non page");
	TargetNonPageLinks.reABS_URL = /^\w+:\/\//;
	TargetNonPageLinks.rePAGE_URL = /(?:\.(?:asp|aspx|htm|html|txt)|\/)(?:$|\?)/i;		// also handles default file URLs (e.g., "/myDir/")
	// OLD: window.PAGE_HOSTNAME = String(location.hostname).toLowerCase(); 

	jqRootElem = jqRootElem || $(document);
	var jqLinks = jqRootElem.find('A:not([href$=#], .extLink, .pdfLink)');
	
	var jqExtLinks = jqLinks.filter('A[href^=http://]').not('[href^=http://'+ location.hostname +'/]').addClass('extLink');		// external link class
	// DBG: alert(jqExtLinks.length);
	jqLinks.filter('A[href$=.pdf]').addClass('pdfLink')												// PDF link class (doesn't work if "?" querystring)
		.add(jqExtLinks).filter("[target=]").attr('target', '_blank');														// target both to new
	
	//jqLinks.filter(IsNotInternalPageURL).addClass('extLink').filter("[target=]").attr('target', '_blank');
}

// OLD: returns true if specified link points to an external URL or a non-HTML/ASP internal URL
function IsNotInternalPageURL() {
	// if is an external absolute URL, return true
	if( TargetNonPageLinks.reABS_URL.test(this.href) )
		// if points to an external domain, or if extension not recognised as a web page ..
		if( (String(this.hostname).toLowerCase() != PAGE_HOSTNAME) || !TargetNonPageLinks.rePAGE_URL.test(this.href) )
			return true;

	return false;			// return false for internal pages
}

function Ptr(sId) {
	if(window[sId])
		return window[sId];
	else {
		var e = document.getElementById(sId);
		if(e) window[sId] = e;
		return e; 
	}
}


// update date/time display every second
function UpdateTimeDate() {
	if(Ptr("timeDate")) timeDate.innerHTML = (new Date()).toLocaleString();
	//divTimeDate.innerHTML = new Date().toGMTString();
}
function ScheduleClock() { setInterval(UpdateTimeDate, 1000); }

// run by inline SCRIPT immediately after menu HTML
function CustomiseMenuLinks() {
	jQuery("#menu #menuItemHome A").html("Back to <b>Home</b>").attr('target', '_self');		// change text of 'Home' menu item

	// add CSS class "menuItemsAdmin" to top-level admin menu items, and set href to "#" (so aren't clickable)
	jQuery('#menuLink293, #menuLink309, #menuLink7').addClass('menuItemsAdmin').attr('href', '#');
	// OLD (ID independent, but slower): 	$('#menu > LI > A[href*=/Admin/], #menu > LI > A[href*=/Host/]').addClass('menuItemsAdmin');
}


/* sixth form course pages - dynamic Table of Contents */
function GenerateTOC() {
	document.write("<span id='spnTOCAnchor'></span>");
	jQuery(document).ready(GenerateTOC_onPageLoad);
}
function GenerateTOC_onPageLoad() {
	var $ = window.jQuery;
	
	// find the Table of Contents UL element and empty it
	var oUlToc = $('#spnTOCAnchor').parents('#ulTOC');
	oUlToc.html("");
	
	// for each H2 heading within the page content, prepend a named anchor and add a hyperlinked entry to the TOC
	var oHeadings = $('#centre H2');
	for(var i=0; i < oHeadings.length; i++) { 
		oUlToc.append( "<li><a href=\"#tocH2_"+ i +"\">"+ $(oHeadings[i]).text() +"</a></li>" );
		$(oHeadings[i]).before("<a name=\"tocH2_"+ i +"\"></a>");
	}
}


// *************************************************
// PAGE TOOL LINKS
// *************************************************

function Bookmark(title, url) {
	url = url || document.location;
	title = title || document.title;
	
  if (window.sidebar) { // firefox
     window.sidebar.addPanel(title, url, "");
  } else if (document.all) { // IE
     window.external.addFavorite(url, title);
  } else if (window.opera && window.print) { // opera
     var elem = document.createElement('a');
     elem.setAttribute('href',url);
     elem.setAttribute('title',title);
     elem.setAttribute('rel','sidebar');
     elem.click();
  }
}

// rename "Add to Favourites" link to "Bookmark Page" if non-IE browser
function RenameFavLink() {
	if(!document.all && (typeof window.external.AddFavorite == "undefined") && Ptr("favLink"))
		favLink.innerHTML = "<strong>Bookmark</strong> this Page";
}

function EmailPage(sTitle, sUrl) {
	sTitle = sTitle || document.title;
	sUrl = sUrl || document.location;

	window.open("mailto:?Subject="+ encodeURIComponent(sTitle) +"&body="+ encodeURIComponent(sTitle +" : \n"+ sUrl +"\n"),"_self");
}

