var onloads = new Array();
function bodyOnLoad()
{
    for ( var i = 0 ; i < onloads.length ; i++ )
  	{
    	onloads[i]();
   	}
   	 
    var prodsel=$('productselector');
    if (prodsel)
    {
    	Event.observe('productselector', 'change', onSwitchProduct);
    }
        
	if ($('toggleDisplaySearchResultChildren')) {
		var onload = ($('toggleDisplaySearchResultChildren').value);
		toggleDisplaySearchResultChildren(onload);
	}
	
	if ($('logo')) {
		$('logo').observe('click', toggleDiagnostic);
		$('diagnosticpanel').observe('click', toggleDiagnostic);
	}
	
	if ($('citationset1')) {
		this.citationcount = null;
		$('citationset1').observe('tvattrstring:addnew', this._onAddNew.bindAsEventListener(this));
	}
	initialiseBrowseDropDown();
}

String.prototype.pad = function(l, s, t){
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
};

/**
 * Popup function by Jonathan Snook
 */
var Popup = {
	open: function(options) {
		this.options = {
			url: '#',
			width: 500,
			height: 250,
			name:"_blank",
			location:"no",
			menubar:"no",
			toolbar:"no",
			status:"yes",
			scrollbars:"no",
			resizable:"no",
			left:"",
			top:"",
			normal:false
		}
    
		Object.extend(this.options, options || {});

		if (this.options.normal){
			this.options.menubar = "yes";
			this.options.status = "yes";
			this.options.toolbar = "yes";
			this.options.location = "yes";
		}

		this.options.width = this.options.width < screen.availWidth ? this.options.width : screen.availWidth;
		this.options.height = this.options.height < screen.availHeight ? this.options.height : screen.availHeight;
		
		var openoptions = 'width='+this.options.width+',height='+this.options.height+
						  ',location='+this.options.location+',menubar='+this.options.menubar+
						  ',toolbar='+this.options.toolbar+',scrollbars='+this.options.scrollbars+
						  ',resizable='+this.options.resizable+',status='+this.options.status;
		
		if (this.options.top != "")
			openoptions += ",top="+this.options.top;
		
		if (this.options.left != "")
			openoptions += ",left="+this.options.left;
			
		this.window = window.open(this.options.url, this.options.name, openoptions);
		return false;
	},
	
	focus: function() {
		if (this.window != null) {
			this.window.focus();
		}
	}
}


function toggleDiagnostic(e)
{
	if (e.ctrlKey)
	{
		$('diagnosticpanel').toggle()
	}
}
	
function toggleAdvancedSearchPersonSelector(selectid) 
{
	var value=document.getElementById(selectid).value;
	new Ajax.Request('/Search/toggleAdvancedSearchPersonSelector/'+value);
}

function onSwitchProduct()
{
	document.location='/start/'+$F('productselector');
}

/**
* Toggles visibility of a control.
* @param string elStr
* @param boolean force open or closed
*/
function toggleVisible(elStr, force)
{
	var el = $(elStr);
	if (el.style.display=='none')
	{
		el.style.display='';
	}
	else
	{
		el.style.display='none';
	}
}

/**
* From http://muffinresearch.co.uk/archives/2006/04/29/getelementsbyclassname-deluxe-edition/
* renamed 'getElementsByClassName' => 'getElementsByClassNameIE'
* prototype has getElementsByClassName, but this is for faster IE performance with large tables of contents etc
*/
function getElementsByClassNameIE(strClass, strTag, objContElm) {
  strTag = strTag || "*";
  objContElm = objContElm || document;
  var objColl = objContElm.getElementsByTagName(strTag);
  if (!objColl.length &&  strTag == "*" &&  objContElm.all) objColl = objContElm.all;
  var arr = new Array();
  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';
  var arrClass = strClass.split(delim);
  for (var i = 0, j = objColl.length; i < j; i++) {
    var arrObjClass = objColl[i].className.split(' ');
    if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
    var c = 0;
    comparisonLoop:
    for (var k = 0, l = arrObjClass.length; k < l; k++) {
      for (var m = 0, n = arrClass.length; m < n; m++) {
        if (arrClass[m] == arrObjClass[k]) c++;
        if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
          arr.push(objColl[i]);
          break comparisonLoop;
        }
      }
    }
  }
  return arr;
}

// To cover IE 5.0's lack of the push method
Array.prototype.push = function(value) {
  this[this.length] = value;
}

/**
* Toggles tree node
* @param string className CSS class to expand by
*/

function toggleTreeNode(className)
{
	//change expander graphic
	var item = $('expander_'+className);

 	if (item.src.search('plus.gif')>0)
 	{
	 	item.src = item.src.replace('plus.gif','minus.gif');
	 	document.treeNodeIsOpen = true;
 	}
 	else if (item.src.search('minus.gif')>0)
 	{
	 	item.src = item.src.replace('minus.gif','plus.gif');
	 	document.treeNodeIsOpen = false;
 	}	
	
	//alert(getElementsByClassNameIE(className).length);
	//alert($(el).getElementsBySelector('.'+className).length);
	//alert($$('.'+className).length);
	
	//document.getElementsByClassName(className).each( function(item, index){
	//$$('.'+className).each( function(item, index){
	getElementsByClassNameIE(className).each( function(item, index){
		if (document.treeNodeIsOpen){
			Element.show(item);
		}else{
			Element.hide(item);
		}
	});

}



/**
* Sorts contents of a select by value
*/
function sortOptions(elStr)
	{
	var select = $(elStr);
    var copyOption = new Array();
    var options = $A(select.getElementsByTagName('option'));
    options.each(function(option)
	    {
	     copyOption[copyOption.length] = new Array(option.value,option.text);
	    }
    )
	clearOptions(select);
    copyOption.sort(function(a,b) { return a[0]-b[0]; });
	copyOption.each(
		function(o)
		{
		 addOption(select,o[1],o[0]);
		}
	)       
}

function addOption(select,text,value) {
    var defaultSelected = false;
    var selected = false;
    var optionName = new Option(text, value, defaultSelected, selected)
    select.options[select.length] = optionName;
    select.options[select.length-1].selected = false;
}

function deleteOption(select,index) {
    select.options[index] = null;
}

function clearOptions(select)
{
    for(i=select.options.length; i>=0; i--)
    {
    	 deleteOption(select,i);
    }
}
/*Updating datepickers*/
function updateDatepicker(sEl)
{
	var date="";
	
	var sel=document.getElementById('century_'+sEl);
	date=sel.options[sel.selectedIndex].value.pad(2,'0');
	
	sel=document.getElementById('decade_'+sEl);
	date+=sel.options[sel.selectedIndex].value.pad(2,'0')+"-";
	
	sel=document.getElementById('mon_'+sEl);
	date+=sel.options[sel.selectedIndex].value.pad(2,'0')+"-";
	
	sel=document.getElementById('day_'+sEl);
	date+=sel.options[sel.selectedIndex].value.pad(2,'0');
	
	//circa date?
	if ($('circa_'+sEl) && $('circa_'+sEl).checked)
	{
		date+= ' 00:00:01'; //yes, store in time
	}
	else
	{
		date+= ' 00:00:00'; //no
	}


	document.getElementById(sEl).value=date;
}



/*Playlist editing*/

/**
* Shows group create controls when creating a playlist
*/
function showCreateGroupControls()
{
	toggleGroupControls('createGroupContainer', true);
	toggleGroupControls('editGroupContainer', false);
}

/**
* Shows group edit controls when creating a playlist,
* and also gets current values
*/
function showEditGroupControls()
{
	toggleGroupControls('editGroupContainer', true);
	toggleGroupControls('createGroupContainer', false);

	var group_id = $F('folder_viewergroup_id');
	if (group_id >0)
	{
	 	new Ajax.Updater(
	 	'ajaxEvaluationArea',
		'http://'+location.host+'/playlists/GetGroupInfo/'+group_id, 
		{
			method: 'get',
			evalScripts: true,
			onFailure: reportAjaxError
		});
		
	}
}

function padDigits(n, totalDigits) 
{ 
    n = n.toString(); 
    var pd = ''; 
    if (totalDigits > n.length) 
    { 
        for (i=0; i < (totalDigits-n.length); i++) 
        { 
            pd += '0'; 
        } 
    } 
    return pd + n.toString(); 
} 

/**
* toggle visibility of playlist group controls
*/
function toggleGroupControls(sEl,bForceOpen)
{
	var v = $F('visibility');
	var el = $(sEl);

	if (v=='group' && (el.style.display=='none' && bForceOpen!=false))
	{
		Effect.BlindDown(sEl);
	}
	else
	{
		Effect.BlindUp(sEl);
	}
}

/**
* Toggle display of children in search results
*/

function toggleDisplaySearchResultChildren(onload)
{

	if (onload) {
           onload!=false?value='1':value='0';
        }  else {
       	   ($('toggleDisplaySearchResultChildren').checked)?value='1':value='0';
        }

	if (document.hidChildrenIDs)
		{
			document.hidChildrenIDs.each(
			function(childrenID){
				(value=='1')?Element.hide(childrenID):Element.show(childrenID);
			}
		)
	}

	new Ajax.Request('/Search/toggleDisplaySearchResultChildren/'+value);
}

/**
* Toggle display of groups of works
*/

function toggleWorkGroup(key)
{
	var elWorks ='work_'+key;
	if (Element.visible(elWorks))
	{
		Effect.BlindUp(elWorks);
	}else{
		Effect.BlindDown(elWorks);
	}
	
	//change expander graphic
	var item = $('expander_'+key);
 	if (item.src.search('plus.gif')>0)
 	{
	 	item.src = item.src.replace('plus.gif','minus.gif');
 	}
 	else if (item.src.search('minus.gif')>0)
 	{
		item.src = item.src.replace('minus.gif','plus.gif');
 	}
}

/**
* Toggle appearance of customised selects
*/
function toggleCustomSelect(selectid)
{
	selectToToggle ='content_'+selectid;

	//close all others

	$$('.custom_select_content').each( function(item, index){
		  if (item.id!=selectToToggle)
		  {
				  item.style.display='none';
		  }
	  }
	  );	
	toggleVisible(selectToToggle);
}
	
/**
* Handle custom selects closing when a user clicks elsewhere on the page in IE
*/
function observeIECustomSelectClose()
{
	Event.observe(document.body, 'click', function(e){
    	//if target is not a custom select itself, they're all closed
		el = Event.element(e);
		if (el.className!='custom_select'){
			clearCustomSelects();
		}
	})
}	

/**
* Handle Ajax population of limit bys
*/
function populateLimitBys(el,uri)
{
		Element.show(el);
		new Ajax.Updater(
        el,
        uri,
        {
            method: 'get',
            onFailure: reportAjaxError
        });
        clearCustomSelects();
        Element.show(el);
}

/**
* Close all custom selects
*/
function clearCustomSelects()
{
	 $$('.custom_select_content').each( function(item, index){
		  item.style.display='none';
		  }
	  );
}


/**
* Clear fields in advanced search form, instead of resetting to given values
*/
function clearAdvancedSearch()
{
	Form.getElements('advanced_search').each(
		function(val)
		{
		 if ( val.className !='button' && val.className !='javascriptlink' && val.className !='time' && $(val).name >''){
			$(val).value='';
		 };
		}
	)
}

/**
* Advanced Search: Observe a field to suggest as-you-type
*/
function observeSearchTerm(el, attributeToSearch, fullTerm)
{

new Form.Element.Observer(
    el,
    2, 
    function(element, value) {
    if ($F(el).length>=3)
    {
		if ($('searchset')) {
		if ($('searchset').getValue() != 'true') {
        new Ajax.Updater(
        el+'_results',
        '/Search/Suggest/element/'+el+'/attribute/'+attributeToSearch+'/partial/'+$F(el)+'/fullterm/'+fullTerm,
        {
            method:'get',
            onSuccess: setupSuggestResult(el),
            onFailure: reportAjaxError
        })
        }
        $('searchset').value = 'false';
		} else {
		new Ajax.Updater(
        el+'_results',
        '/Search/Suggest/element/'+el+'/attribute/'+attributeToSearch+'/partial/'+$F(el)+'/fullterm/'+fullTerm,
        {
            method:'get',
            onSuccess: setupSuggestResult(el),
            onFailure: reportAjaxError
        })
        }
    } 
    });
        
   // Event.observe(el, 'blur', function(){setTimeout("Element.hide('"+document.suggestControl+"_results')",100)});
}

/**
* Advanced Search: Prep a suggest-as-you-type box
*/
function setupSuggestResult(el)
{
	Element.show(el+'_results');
	document.suggestControl = el;
	document.timeoutControl = setTimeout("Element.hide('"+el+"_results')",50000);
}

/**
* Advanced Search: Add a term from a suggest-as-you-type box
*/
function addSuggestResult(el, term)
{
	$(el).value=term;
	$(el+'_results').hide();
	if ($('searchset')) {
		$('searchset').value = 'true';
	}
}

/**
* Advanced search: toggle a selected term on and off
*/
function toggleSearchTerm(idx, term)
{
    if (!document.selectTerms)
    {
       document.selectTerms = new Array;
    }
	if (document.selectTerms.indexOf(term)>-1)
	{
		$(idx+'_checkbox').checked = false;
		document.selectTerms.pop(term); 
	} else	{
		$(idx+'_checkbox').checked=true;
		document.selectTerms.push(term); 
	}
}

/**
* Advanced search: insert all selected terms to parent document, & close
*/
function insertSearchTerms(control)
{
	if (window.opener) {
		window.opener.importSearchTerms(control,document.selectTerms);
	}
	window.close();
}

/**
* Advanced search: add in search terms from child popup
* @param string control control to add to
* @param array terms array of terms
*/
function importSearchTerms(control,terms)
{
	$(control).value += '"' + terms.join('" OR "') + '"';
}

/**
* traverse images on person entity page
*/
function showPersonEntityImage(personID, direction)
{
	//track current image. If none set, assume first
	if (!document.currentPersonImage)
	{
		document.currentPersonImage = 0;
	}
	if (direction=='prev')
	{
		document.currentPersonImage--;
	}
	else if (direction=='next')
	{
		document.currentPersonImage++;
	}
	document.currentPersonImage = Math.max(document.currentPersonImage,0);
	document.currentPersonImage = Math.min(document.currentPersonImage, document.maxPersonImage);
	

	new Ajax.Request(
       '/Person/Image/'+personID+'/'+document.currentPersonImage,
       {
           method:'get',
           onSuccess: function(transport) {
            el = $('personImage');
			el.src = transport.responseText;
			new Effect.Highlight(el);
		}
    });
}


/**
* traverse through displayed biographies
*/
function showBiography(type, direction)
{
	//track current image. If none set, assume first
	if (!document.currentBiography)
	{
		document.currentBiography = 0;
	}
	if (direction=='prev')
	{
		document.currentBiography--;
	}
	else if (direction=='next')
	{
		document.currentBiography++;
	}
	document.currentBiography = Math.max(document.currentBiography,0);
	document.currentBiography = Math.min(document.currentBiography, document.maxBiography);
	
	
	new Ajax.Request(
	      '/'+type+'/Biography/'+document.biographyEntityID+'/'+document.currentBiography,
	      {
	      	method:'get',
	        onSuccess: function(transport) {
		        el = $('biography');
	        	el.innerHTML = transport.responseText;
				new Effect.Highlight(el);
			}
	      });
}


function reportAjaxError(request)
{
	alert('An error has occured. Please try again; if the problem persists, please content Technical Support.');
}


function updateInformationBar()
{
	new Ajax.Updater('infobar_container', '/user/informationbar');
}

/**
* Browse dropdowns; called through BodyOnLoad
* Modern browsers do this automatically through :hover CSS, this script for IE
* Modified from http://www.htmldog.com/articles/suckerfish/dropdowns/
*/
function initialiseBrowseDropDown() {
if (document.getElementById("tabs")) {
	var sfEls = document.getElementById("tabs").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" over";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp("\\s?over\\b"), "");
			}
		}
	}	
}

function copyEmbed(inElement) {
  if (inElement.createTextRange) {
    var range = inElement.createTextRange();
    if (range && BodyLoaded==1)
      range.execCommand('Copy');
  } else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="/js/common/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}

function copyEmbedIE(inElement) {
	Copied = inElement.createTextRange();
	Copied.execCommand("Copy");
}

/**
 * Dynamically include a .js or .css file
 * Ensures the same file doesn't get included twice
 */
var includedFile=new Array();

function include( url ){

    // First make sure it hasn't been loaded by something else.
    if(includedFile.indexOf(url)>=0)
        return;
    // Determine the MIME-type
    var jsExpr = new RegExp( "js$", "i" );
    var cssExpr = new RegExp( "css$", "i" );
    
    if( jsExpr.test( url ) )
        type = 'text/javascript';
    else if( cssExpr.test( url ) )
        type = 'text/css';

    // Create the appropriate element.
    var tag = null;
    switch( type ){
        case 'text/javascript' :
            tag = document.createElement( 'script' );
            tag.type = type;
            tag.src = url;
            break;
        case 'text/css' :
            tag = document.createElement( 'link' );
            tag.rel = 'stylesheet';
            tag.type = type;
            tag.href = url;
            break;
    }

    // Insert it to the <head> and the array to ensure it is not
    // loaded again.
    document.getElementsByTagName("head")[0].appendChild( tag );
    includedFile.push(url);
}

function switchProduct(product,newwindow)
{
   var url='http://'+window.location.hostname+'/Start/'+product;
   if (newwindow)
   { 
       window.open(url, '_blank');
   }
   else
   {
       window.location=url;
   }
}

function _onAddNew(event){

	//event target is the input box we want to insert after
	var input=$(event.target);
	var parent=input.parentNode;

	var param = event.memo;
	
	param = param.split("||");
	
	if (this.citationcount == null) {
		this.citationcount = parseInt(param[0]);
		if (param[0] == 1) {
			this.citationcount = 2;
		}
		if (isNaN(this.citationcount)) {
			this.citationcount = 2;
		}
	}

//	alert(this.citationcount);
	
	var prevcount = (this.citationcount - 1);
		
	var citationsetid = 'citationset'+this.citationcount;
	var prevcsetid = 'citationset'+prevcount;
	var citationid = 'citation'+this.citationcount;
	var citationurlid = 'citationurl'+this.citationcount;
//	alert(prevcsetid);

	var html='<div id="'+citationsetid+'"><div class="formRow">';
	
	html+= '<label for="'+citationid+'" class="citationlabel">'+param[1]+'</label><input type=text id="'+citationid+'" name="'+citationid+'" ></div>';
	
	html+= '<div class="formRow"><label for="'+citationurlid+'" class="citationlabel">'+param[2]+'</label><input type=text id="'+citationurlid+'" name="'+citationurlid+'"></div>';

	html+='</div>';

	$(prevcsetid).insert({after:html});
	
	this.citationcount += 1;
}

