
//Define the following in magus_script_config.
//var HIDEIMG = 'url("/pics/orange-arrow-up.gif")'; 
//var SHOWIMG = 'url("/pics/orange-arrow-down.gif")';
//var TOGGLESPEED = 400;
//var ENABLEDEBUG = true;
//
//var BASEDIV    = 0;
//var BOXDIV     = 1;
//var TOGGLEDIV  = 2;
//var facets = new Array(
//	new Array('site',    '#sitebox',    '#site-toggle'),
//	new Array('doctype', '#doctypebox', '#doctype-toggle'),
//	new Array('lang',    '#langbox',    '#lang-toggle'));


var BASEDIV    = 0;
var BOXDIV     = 1;
var TOGGLEDIV  = 2;
var DEFAULT_SETTING = 3; // show/hide facet by default

jQuery(document).ready(function() {
	
	createSlider();
	setupSummaryOptions();
	
	if (!jQuery.cookie('initialised')) {
		jQuery.cookie('initialised', 'true');
		for(var i in facets){
			if (facets[i][DEFAULT_SETTING]) {
				jQuery.cookie(facets[i][BOXDIV], true);
			}
		}
	}
	for(var i in facets){	
		//debug("working on facets[" + i + "]: " + facets[i]);
		createClosureForOnClickHandler(facets[i][BOXDIV], facets[i][TOGGLEDIV]);
		(!jQuery.cookie(facets[i][BOXDIV])) ?
			hidePanel(facets[i][BOXDIV], facets[i][TOGGLEDIV])  :
			showPanel(facets[i][BOXDIV], facets[i][TOGGLEDIV]);
	}
	
	jQuery('.magus-external').bind('click', openInNewWindow);
});

function createClosureForOnClickHandler(boxDivId, toggleDivId){
	//debug("creating closure on toggleDivId:" + toggleDivId + " with boxDivId:" + boxDivId);
	jQuery(toggleDivId).click(function() {
		return togglePanel(boxDivId, toggleDivId);
	});
}

function togglePanel(boxDomId, toggleDomId){
	(jQuery(boxDomId).css('display') == 'none')  ?
		showPanel(boxDomId, toggleDomId) : hidePanel(boxDomId, toggleDomId); 
	return false;
}

function showPanel(boxDomId, toggleDomId){
	if(jQuery(boxDomId).css('display') == 'none'){
		jQuery(boxDomId).slideToggle(TOGGLESPEED);
	}
	jQuery(toggleDomId).css('background-image', HIDEIMG);
	jQuery.cookie(boxDomId, true);
}

function hidePanel(boxDomId, toggleDomId){
	jQuery(boxDomId).slideToggle(TOGGLESPEED);
	jQuery(toggleDomId).css('background-image', SHOWIMG);
	jQuery.cookie(boxDomId, null);
}

function debug(msg) {
	if(ENABLEDEBUG === true){
		try{ console.log(msg); }catch(e){ alert(msg); }
	}	
}


function switchFormValueAndSubmit(fullyQualifiedDOMFormId, fieldKey, fieldValue){
	jQuery(fieldKey).val(fieldValue);
	jQuery(fullyQualifiedDOMFormId).submit(); 
}




/** This will always use the DOM anchor/href in preference to arg passed unless == undef,'','#'
  * to reuse window pass empty string as 'url' 
  */
function openInNewWindow(url, reuse){
	var earl = (this.href === undefined || this.href === '' || this.href === '#' ) ? url : this.href;
	if(reuse){
		window.open(earl, (''+window.location).replace(/https?:\/\/([^\/]+)\/?.*/, '$1'));
	}else{
		window.open(earl);
	}
	return false;
}
