/*-------------------------------------------*\
Common Functions for the site
\*-------------------------------------------*/
var select = 0;
var MembershipUrl = "http://dev.standards.co.nz/services/Membership/Default.htm"; 

function popWindow(theURL,winName,features) {
  var newWin
  newWin = window.open(theURL,winName,features);
  newWin.focus();
}
function IsIE() {
	return (navigator.appName == "Microsoft Internet Explorer")
}
function openCalendar(prefixValue) {
	var Xpos = 200;
	var Ypos = 300;
	// set the prefix on the calling page so that the child window knows which calendar dropdown controls to update.
	prefix = prefixValue;
	popWindow('/CmsApp/Scripts/calendar.htm','termsWindow','scrollbars=no,resizable=no,width=181,height=155,left=' + Xpos + ',top=' + Ypos); //width=175, height=125
}
function isValidDate(source, arguments) {
	var y, m, d;
	// retrieve the values from the three dropdown controls (date, month, year).
	d = document.forms[0].elements[source.dateControlID].value;
	m = document.forms[0].elements[source.monthControlID].value - 1;	// m = 0..11
	y = document.forms[0].elements[source.yearControlID].value;
	
	// check for a valid date.
	with (new Date(y, m, d))
    if ((getDate()==d) && (getMonth()==m))
		arguments.IsValid = true;
	else
		arguments.IsValid = false;
}

// Start Javascript for the mouse over images
//<![CDATA[
function swapImgRestore() {
	var i,x,a=document.sr; 
	var y = swapImgRestore.arguments;
	if (y.length > 0){
		if (select == y[0]){ return false;}
	}
	for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function findObj(n, d) { 
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document); return x;
}
function swapImage() { 
	var i,j=0,x,a=swapImage.arguments; document.sr=new Array; 
	if (a[0] == "imgSearchStandards" && select == 0)
		return false;
	if (a[0] == "imgSearchEzine" && select == 0)
		return false;
	for(i=0;i<(a.length-2);i+=3)
	if ((x=findObj(a[i]))!=null){document.sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function swapBgdImage() {
	var i,j=0,x,a=swapBgdImage.arguments; document.sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=findObj(a[i]))!=null){
	var image = 'url(' + a[i+2] + ')';
	document.sr[j++]=x; if(!x.oSrc) x.oSrc=x.style.backgroundImage; x.style.backgroundImage=image;
	}
}
function swapBgdImgRestore() {
	var i,x,a=document.sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.style.backgroundImage=x.oSrc;
}//]]>
// End Javascript for the mouse over images

// BaseUrl should be defined in the aspx page
function shopSubmit(query) {
	location.href = BaseUrl + query;
}

function loginRedirect(query) {
	location.href = HeaderUrl + query;
}

function catalogueRedirect() {
	location.href = CatalogueUrl;
}

function redirectMembership(){
	location.href = MembershipUrl;	
}

function redirectSubscriptionService(){
	location.href = SubscriptionServiceUrl;
}

// Search box functions.

function toggleSearch(panelToActivate){
	if (panelToActivate == 'shop')
	{
		document.getElementById('searchCatalogue').className= "searchShow";
		document.getElementById('searchRestOfSite').className= "searchHide";
		document.images["imgSearchStandards"].src = "/images/tabs/tab-searchcatalogue-on.gif";
		document.images["imgSearchROS"].src = "/images/tabs/tab-searchrestofsite-off.gif";
		select = 0;
	}
	else if (panelToActivate == 'site')
	{
		document.getElementById('searchCatalogue').className= "searchHide";
		document.getElementById('searchRestOfSite').className= "searchShow";
		document.images["imgSearchROS"].src = "/images/tabs/tab-searchrestofsite-on.gif";
		document.images["imgSearchStandards"].src = "/images/tabs/tab-searchcatalogue-off.gif";
		select = 1;
	} else if (panelToActivate == 'ezine')
	{
		document.getElementById('searchRestOfSite').className= "searchHide";
		document.getElementById('searchEzine').className= "searchShow";
		document.images["imgSearchEzine"].src = "/images/searchTouchstone.gif";
		document.images["imgSearchROS"].src = "/images/tabs/tab-searchrestofsite-off.gif";
		select = 0;
	}
	else if (panelToActivate == 'site1')
	{
		document.getElementById('searchRestOfSite').className= "searchShow";
		document.getElementById('searchEzine').className= "searchHide";
		document.images["imgSearchEzine"].src = "/images/searchTouchstone-off.gif";
		document.images["imgSearchROS"].src = "/images/tabs/tab-searchrestofsite-on.gif";
		select = 1;
	}
}

function searchSubmit1(myfield, e) {
	
	var keycode;
	if (window.event){
		keycode = window.event.keyCode;
	}
	else if (e){
		keycode = e.which;
	}
	else {
		return true;
	}
	
	var form = document.forms[0];
	if (keycode == 13 && document.getElementById("SearchBox1_txtShopName").value != "" )
	{
		__doPostBack('shopSearch', '');
		return false;
	}
	else if (keycode == 13 && document.getElementById("SearchBox1_txtName").value != "") 
	{ 
		__doPostBack('siteSearch', '');
		return false;
	}
	else{
		return true;
	}
}






/*
 * Content-seperated javascript tree widget
 * Copyright (C) 2005 SilverStripe Limited
 * Feel free to use this on your websites, but please leave this message in the fies
 * http://www.silverstripe.com/blog
*/

/*
 * Initialise all trees identified by <ul class="tree">
 */
function autoInit_trees() {
	var candidates = document.getElementsByTagName('ul');
	for(var i=0;i<candidates.length;i++) {
		if(candidates[i].className && candidates[i].className.indexOf('tree') != -1) {
			initTree(candidates[i]);
			candidates[i].className = candidates[i].className.replace(/ ?unformatted ?/, ' ');
		}
	}
}
 
/*
 * Initialise a tree node, converting all its LIs appropriately
 */
function initTree(el) {
	var i,j;
	var spanA, spanB, spanC;
	var startingPoint, stoppingPoint, childUL;
	
	// Find all LIs to process
	for(i=0;i<el.childNodes.length;i++) {
		if(el.childNodes[i].tagName && el.childNodes[i].tagName.toLowerCase() == 'li') {
			var li = el.childNodes[i];

			// Create our extra spans
			spanA = document.createElement('span');
			spanB = document.createElement('span');
			spanC = document.createElement('span');
			spanA.appendChild(spanB);
			spanB.appendChild(spanC);
			spanA.className = 'a ' + li.className.replace('closed','spanClosed');
			spanA.onMouseOver = function() {}
			spanB.className = 'b';
			spanB.onclick = treeToggle;
			spanC.className = 'c';
			
			
			// Find the UL within the LI, if it exists
			stoppingPoint = li.childNodes.length;
			startingPoint = 0;
			childUL = null;
			for(j=0;j<li.childNodes.length;j++) {
				if(li.childNodes[j].tagName && li.childNodes[j].tagName.toLowerCase() == 'div') {
					startingPoint = j + 1;
					continue;
				}

				if(li.childNodes[j].tagName && li.childNodes[j].tagName.toLowerCase() == 'ul') {
					childUL = li.childNodes[j];
					stoppingPoint = j;
					break;					
				}
			}
				
			// Move all the nodes up until that point into spanC
			for(j=startingPoint;j<stoppingPoint;j++) {
				spanC.appendChild(li.childNodes[startingPoint]);
			}
			
			// Insert the outermost extra span into the tree
			if(li.childNodes.length > startingPoint) li.insertBefore(spanA, li.childNodes[startingPoint]);
			else li.appendChild(spanA);
			
			// Process the children
			if(childUL != null) {
				if(initTree(childUL)) {
					addClass(li, 'children', 'closed');
					addClass(spanA, 'children', 'spanClosed');
				}
			}
		}
	}
	
	if(li) {
		// li and spanA will still be set to the last item

		addClass(li, 'last', 'closed');
		addClass(spanA, 'last', 'spanClosed');
		return true;
	} else {
		return false;
	}
		
}
 

/*
 * +/- toggle the tree, where el is the <span class="b"> node
 * force, will force it to "open" or "close"
 */
function treeToggle(el, force) {
	el = this;
	
	while(el != null && (!el.tagName || el.tagName.toLowerCase() != "li")) el = el.parentNode;
	
	// Get UL within the LI
	var childSet = findChildWithTag(el, 'ul');
	var topSpan = findChildWithTag(el, 'span');

	if( force != null ){
		
		if( force == "open"){
			treeOpen( topSpan, el )
		}
		else if( force == "close" ){
			treeClose( topSpan, el )
		}
		
	}
	
	else if( childSet != null) {
		// Is open, close it
		if(!el.className.match(/(^| )closed($| )/)) {		
			treeClose( topSpan, el )
		// Is closed, open it
		} else {			
			treeOpen( topSpan, el )
		}
	}
}


function treeOpen( a, b ){
	removeClass(a,'spanClosed');
	removeClass(b,'closed');
}
	
	
function treeClose( a, b ){
	addClass(a,'spanClosed');
	addClass(b,'closed');
}

/*
 * Find the a child of el of type tag
 */
function findChildWithTag(el, tag) {
	for(var i=0;i<el.childNodes.length;i++) {
		if(el.childNodes[i].tagName != null && el.childNodes[i].tagName.toLowerCase() == tag) return el.childNodes[i];
	}
	return null;
}

/*
 * Functions to add and remove class names
 * Mac IE hates unnecessary spaces
 */
function addClass(el, cls, forceBefore) {
	if(forceBefore != null && el.className.match(new RegExp('(^| )' + forceBefore))) {
		el.className = el.className.replace(new RegExp("( |^)" + forceBefore), '$1' + cls + ' ' + forceBefore);

	} else if(!el.className.match(new RegExp('(^| )' + cls + '($| )'))) {
		el.className += ' ' + cls;
		el.className = el.className.replace(/(^ +)|( +$)/g, '');
	}
}
function removeClass(el, cls) {
	var old = el.className;
	var newCls = ' ' + el.className + ' ';
	newCls = newCls.replace(new RegExp(' (' + cls + ' +)+','g'), ' ');
	el.className = newCls.replace(/(^ +)|( +$)/g, '');
} 

/*
 * Handlers for automated loading
 */ 
 _LOADERS = Array();

function callAllLoaders() {
	var i, loaderFunc;
	for(i=0;i<_LOADERS.length;i++) {
		loaderFunc = _LOADERS[i];
		if(loaderFunc != callAllLoaders) loaderFunc();
	}
}

function appendLoader(loaderFunc) {
	if(window.onload && window.onload != callAllLoaders)
		_LOADERS[_LOADERS.length] = window.onload;

	window.onload = callAllLoaders;

	_LOADERS[_LOADERS.length] = loaderFunc;
}

appendLoader(autoInit_trees);




/*csjm */
function toggleLayer( whichLayer ) {  
	var elem, vis, link;  
	link = whichLayer+"link";
	if( document.getElementById ) // this is the way the standards work    
	{
		elem = document.getElementById( whichLayer );  
		link = document.getElementById( link );
	}
	else if( document.all ) // this is the way old msie versions work      
	{
		elem = document.all[whichLayer];  
		elem = document.all[link];
  	}
	else if( document.layers ) // this is the way nn4 works    
	{	
		elem = document.layers[whichLayer];  
		elem = document.layers[link];  
	}
	vis = elem.style;  
	// if the style.display value is blank we try to figure it out here  
	if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)    
		vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';  
	vis.display = (vis.display==''||vis.display=='block')?'none':'block';
	link.innerHTML = (link.innerHTML=='[hide]')?'[show]':'[hide]';
}



function toggleOverrideFields(chkd){
	//var chkbox = document.getElementById("override");
	var overrides = document.getElementsByClassName("override");
	if (chkd) {	// Show resell fields if checked
		for (var i = 0;i<overrides.length;i++) {
			overrides[i].style.display = 'block';
		}
	}
	else {	
		for (var i = 0;i<overrides.length;i++) {
			overrides[i].style.display = 'none';
		}
	}

}

/**
 * JS helper method to get all elements of a specific class. Should move this to an external file sometime. CSJM.
 */
document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	} return retnode;
}; 

