// 03.13.2009: Merged dotCMS version with HUAM version. (CD of HUAM)
// HUAM has added their own code in this file and modified some of the
// pre-existing code from dotCMS.
var showDescription = false;
var showCommentary = false;
var showMarks = false;
var showProvenance = false;
var showBibliography = false;
var showExhibitionHistory = false;

function initToogleContent() {

  var paramsArr = location.search.split("&");
  for (var p=0; p < paramsArr.length; p++) {
    if (paramsArr[p].indexOf("showDescription") > -1) {
      var equals = paramsArr[p].indexOf("=");
      var value = paramsArr[p].substr(equals+1, 1);
      if (value == "y")
        showDescription = true;
    }
    if (paramsArr[p].indexOf("showCommentary") > -1) {
      var equals = paramsArr[p].indexOf("=");
      var value = paramsArr[p].substr(equals+1, 1);
      if (value == "y")
        showCommentary = true;
    }
    if (paramsArr[p].indexOf("showMarks") > -1) {
      var equals = paramsArr[p].indexOf("=");
      var value = paramsArr[p].substr(equals+1, 1);
      if (value == "y")
        showMarks = true;
    }
    if (paramsArr[p].indexOf("showProvenance") > -1) {
      var equals = paramsArr[p].indexOf("=");
      var value = paramsArr[p].substr(equals+1, 1);
      if (value == "y")
        showProvenance = true;
    }
    if (paramsArr[p].indexOf("showBibliography") > -1) {
      var equals = paramsArr[p].indexOf("=");
      var value = paramsArr[p].substr(equals+1, 1);
      if (value == "y")
        showBibliography = true;
    }
    if (paramsArr[p].indexOf("showExhibitionHistory") > -1) {
      var equals = paramsArr[p].indexOf("=");
      var value = paramsArr[p].substr(equals+1, 1);
      if (value == "y")
        showExhibitionHistory = true;
    }
  }

	
  // NOTE: i think should be using the slider id rather than this class to identify the items
	var arrDetail = $$('div.collectionDetail');
	
	if (arrDetail.length == 0)
		return;
	
	var aDLNode = arrDetail[0].getElement('dl');
  var dts = aDLNode.getElements('dt');
  var dds = aDLNode.getElements('dd');

  for(var i=0; i<dts.length; i++) {
    var dt = dts[i];
    var dd = dds[i];

    //dd.setStyle('display', 'none');

    dt.getElements('a')[0].addEvent('click', function() {
      var dd = this.getParent('dt').getNext('dd');
      this.toggleClass('active');
      if (this.hasClass('active')) {
        dd.setStyle('display', 'block');
        if (this.id.match('Description'))
          showDescription = true;
        if (this.id.match('Commentary'))
          showCommentary = true;
        if (this.id.match('Marks'))
          showMarks = true;
        if (this.id.match('Provenance'))
          showProvenance = true;
        if (this.id.match('Bibliography'))
          showBibliography = true;
        if (this.id.match('ExhibitionHistory'))
          showExhibitionHistory = true;
      }
      else {
        dd.setStyle('display', 'none');
        if (this.id.match('Description'))
          showDescription = false;
        if (this.id.match('Commentary'))
          showCommentary = false;
        if (this.id.match('Marks'))
          showMarks = false;
        if (this.id.match('Provenance'))
          showProvenance = false;
        if (this.id.match('Bibliography'))
          showBibliography = false;
        if (this.id.match('ExhibitionHistory'))
          showExhibitionHistory = false;
      }
      updateDetailNavLinks();
    });
    
  }
  updateDetailNavLinks();
}

function updateDetailNavLinks() {
  var paramString = "";
  if (showDescription == true)
    paramString = paramString + "&showDescription=y";
  else
    paramString = paramString + "&showDescription=n";
  if (showCommentary == true)
    paramString = paramString + "&showCommentary=y";
  else
    paramString = paramString + "&showCommentary=n";
  if (showMarks == true)
    paramString = paramString + "&showMarks=y";
  else
    paramString = paramString + "&showMarks=n";
  if (showProvenance == true)
    paramString = paramString + "&showProvenance=y";
  else
    paramString = paramString + "&showProvenance=n";
  if (showBibliography == true)
    paramString = paramString + "&showBibliography=y";
  else
    paramString = paramString + "&showBibliography=n";
  if (showExhibitionHistory == true)
    paramString = paramString + "&showExhibitionHistory=y";
  else
    paramString = paramString + "&showExhibitionHistory=n";

  var linkLis = $$('li.previous');
  linkLis.each(function(li,i){
    var link = li.getElement('a');
    // determine how to construct the new link based on whether the "&show" params 
    // are already there, and whether the "#details" anchor (for the lower ones) is there
    var indexShow = link.href.indexOf("&show");
    var indexHash = link.href.indexOf("#details");
    if (indexHash > 0 && indexShow < 0)
      link.href = link.href.substring(0, indexHash) + paramString + link.href.substr(indexHash, indexHash+8);
    else if (indexHash > 0 && indexShow > 0)
      link.href = link.href.substring(0, indexShow) + paramString + link.href.substr(indexHash, indexHash+8);
    else if (indexShow > 0)
      link.href = link.href.substring(0, indexShow) + paramString;
    else
      link.href = link.href + paramString;
  });
}

function initSearchResult() {
	
	var curTab = 0;
	
	if (!$$("div.resultContent") || $$("div.resultContent").length == 0)
		return;
	
	new paging({
		dataURL: 'tpl/searchResult' + (curTab + 1) + '.tpl',
		target: $$("div.resultContent")[0],
		results: $$("div.paging")[0],
		//data: "&keyword="+$F("searchKeyword").value,
		//resultPerpage: (combo[0]) ? combo[0].options[combo[0].selectedIndex].value : 16,
		onDataLoaded: function(){
			//fn.initAddButtons();
			//fn.initCompareButton();
		}
	});
	
	var resultNav = $$('ul.resultNav');	
	if (!resultNav || resultNav.length == 0)
		return;
	
	var arrLi = resultNav[0].getElements('li');
	
	arrLi.each(function(li, i) {	
		li.addEvent('click', function(event) {
			new Event(event).stop();	
			
			if (curTab != i) {
				this.addClass('active');				
				arrLi[curTab].removeClass('active');
				curTab = i;
				
				new paging({
					dataURL: 'tpl/searchResult' + (curTab + 1) + '.tpl',
					target: $$("div.resultContent")[0],
					results: $$("div.paging")[0],
					//data: "&keyword="+$F("searchKeyword").value,
					//resultPerpage: (combo[0]) ? combo[0].options[combo[0].selectedIndex].value : 16,
					onDataLoaded: function(){
						//fn.initAddButtons();
						//fn.initCompareButton();
					}
				}).loadData();				
			}	
		});
	});					
}

function initCalendarShow() {
	
	var arrCalendarShow =  $$('div.calendarShow');
	if (arrCalendarShow.length  == 0)
		return;	
	var calendarShow = arrCalendarShow[0];
	
	var arrPopup = $$('div.popup');
	if (arrPopup.length == 0)
		return;
	
	var popup = arrPopup[0];
	popup.setStyle('display', 'none');

	var arrTD = calendarShow.getElements('td');
	arrTD.each(function(element, index) {
		
		var tagP = element.getElement('p');	
		if (!tagP)
			return;
		
		var tagA = tagP.getElement('a');
		if (!tagA)
			return;
			
		if (tagA.hasClass('moreDetail')) {
		
		} else {		
			tagA.addEvent('mouseenter', function(evt) {		
						
				var event = new Event(evt);
				event.stop();
				
				var self = this;						
				self.popupTimeout = null;
				popup.setStyle('display', 'block');	
				
				var td = self.getParent().getParent();
				if (!td.get('tag') == 'td')
					return;
				
				var posX = td.offsetLeft + td.getCoordinates().width + 1;
				var posY = td.offsetTop + 34;
										
				if (posX + popup.getCoordinates().width > calendarShow.getCoordinates().width)
					posX = posX - td.getCoordinates().width - popup.getCoordinates().width - 3;
				
				if (posY + popup.getCoordinates().height > calendarShow.getCoordinates().height)
					posY = posY - popup.getCoordinates().height;
				
				popup.setStyle('left', posX);
				popup.setStyle('top', posY);							
				self.getParent().getParent().addClass('currentDay');			
				
				popup.addEvents({
					'mouseenter': function(evt) {
						new Event(evt).stop();
						try {
							clearTimeout(self.popupTimeout);
						} catch (e) {}
					},				
					'mouseleave': function(evt) {
						new Event(evt).stop();					
						try {
							popup.setStyle('display', 'none');	
							self.getParent().getParent().removeClass('currentDay');			
						} catch (e) {}
					}			
				});	
			});
			
			tagA.addEvent('mouseleave', function(event) {			
				new Event(event).stop();			
				var self = this;						
				try {
					clearTimeout(self.popupTimeout);
				} catch (e) {}			
				self.popupTimeout = setTimeout(function() {				
					popup.setStyle('display', 'none');	
					self.getParent().getParent().removeClass('currentDay');			
				}, 100);			
			});		
		}	
	});
}
function setActiveKeyBoard(keyBoard01,keyBoard02){
	var as02=$$(keyBoard01)[0].getElements('a');
		for(var i=0;i<as02.length;i++){
			if(as02[i].hasClass('active')){
				//active at position i
				var as=$$(keyBoard02)[0].getElements('a');
				for(var j=0;j<as.length;j++){
					if(i==j){
						as[j].addClass('active');
					}
					else{
						as[j].removeClass('active');
					}
				}
				i=as.length;
			}
		}
}
/*
function initExpand
use Expand and Narrow
*/
function initExpand(){
	var expandSec=$('expandSec');
	//var expand=$$('.expand')[0];
	var expandList = $$('.expand');
	if(!expandSec && expandList.length == 0) return true;
	//get position top of content
	var topContent=$$('.content')[0].getCoordinates().top;
	//big
	//click Expand
	expandList.each(function(expand,i){
	 if(i < expandList.length)
	  expand.addEvent('click',function(evt){
		new Event(evt).stop();
		//show expandSec
		expandSec.removeClass('noActive');
		
		//get position top of ExpandSec
		var topExpandSec=expand.getParent().getParent().getParent().getParent().getCoordinates().top-topContent;
		//set right and top for popup
		if($('popup')) $('popup').setStyles({
			right:'417px',
			top:topExpandSec+'px'
		});
		$('expandSec').setStyles({
				opacity:'1',
				top:topExpandSec+'px'
				});
		if($('popup'))
		if($('popup').hasClass('noActive')){
			$('popup').setStyles({opacity:'0',top:'-5000px'});
		}
		//set tag p of collectionsSearchFrm opacity 0
		var ps=$('collectionsSearchFrm').getElements('p')
		ps.each(function(el,i){
			if(i>1)	el.setStyle('opacity','0');
		});
		//set active for keyBoard
		setActiveKeyBoard('.keyBoardList','.keyBoardList02');
	});
       });
	//small
	//click Narrow
	//var narrow=$$('.narrow')[0];
       var narrowList = $$('.narrow');
       narrowList.each(function(narrow,i){
        if(i < narrowList.length)
	narrow.addEvent('click', function(evt){
		new Event(evt).stop();
		//hidden expandSec
		expandSec.addClass('noActive');
		$('expandSec').setStyle('opacity','0');
		//set right for popup
		//get position top of sidebarBox
		//var topSidebarBox=$$('.sidebarBox')[0].getCoordinates().top-topContent;
		var topSidebarBox=$$('.expand')[0].getParent().getParent().getParent().getParent().getCoordinates().top-topContent;

		if($('popup'))$('popup').setStyles({
			right:'236px',
			top:topSidebarBox+'px'
		});
		if($('popup'))if($('popup').hasClass('noActive')){
			$('popup').setStyles({opacity:'0',top:'-5000px'});
		}
		//set tag p of collectionsSearchFrm opacity 0
		var ps=$('collectionsSearchFrm').getElements('p')
		ps.each(function(el,i){
			if(i>1)	el.setStyle('opacity','1');
		});
		//set sidebarBox opacity 1
		//set active for keyBoard
		setActiveKeyBoard('.keyBoardList02','.keyBoardList');
	});
       });
}
/*
function initListArtists
open popup layer list artists
*/
function initListArtists(){
	var keyBoardList=$$('ul.keyBoardList');
	if(!keyBoardList[0]) return true;
	if($('popup'))$('popup').setStyles({
		opacity:'0',
		top:'-5000px',
		position: 'absolute'
	});
	$('expandSec').setStyle('opacity','0');
	//get position top of content
	var topContent=$$('.content')[0].getCoordinates().top;
	
	var lis=keyBoardList[0].getElements('li');
	lis.each(function(li,i){
		if(i<lis.length)
		li.addEvent('click', function(evt){
			new Event(evt).stop();
			//get position top of sidebarBox
			//var topSidebarBox=$$('.sidebarBox')[0].getCoordinates().top-topContent;
			//get position top of ExpandSec
			var topExpandSec=$$('.expand')[0].getParent().getParent().getParent().getParent().getCoordinates().top-topContent;

			for(var k=0;k<lis.length-1;k++){
				lis[k].getElements('a').removeClass('active');
			}
			//call method load ajax
			//var j=i+1;
			//url='tpl/listArtists'+j+'.tpl';
			//loadAjaxSearch(url);
			//getArtistNames(li.firstChild.text, "narrow"); // works in FF, not IE6
			//getArtistNames(li.getElementsByTagName('a')[0], "narrow"); // works both
			getArtistNames(li.firstChild.innerHTML, "narrow");
			$('popup').setStyles({opacity:'1',top:topExpandSec+'px'});
			$('popup').removeClass('noActive');
			li.getElements('a').addClass('active');
		});
		
	});
	var keyBoardList02=$$('ul.keyBoardList02');
	if(!keyBoardList02[0]) return true;
	var lis02=keyBoardList02[0].getElements('li');
	lis02.each(function(li,i){
		if(i<lis02.length)
		li.addEvent('click', function(evt){
			new Event(evt).stop();
			//get position top of expandSec
			var topExpandSec=$('expandSec').getCoordinates().top-topContent;
			for(var k=0;k<lis02.length-1;k++){
				lis02[k].getElements('a').removeClass('active');
			}
			//call method load ajax
			//var j=i+1;
			//url='tpl/listArtists'+j+'.tpl';
			//loadAjaxSearch(url);
			getArtistNames(li.firstChild.innerHTML, "expanded");
			$('popup').setStyles({opacity:'1',top:topExpandSec+'px'});
			$('popup').removeClass('noActive');
			li.getElements('a').addClass('active');
		});
		
	});
	//------------	
	var pClose=$('popup').getElements('p');
	pClose.addEvent('click',function(evt){
		new Event(evt).stop();
		$('popup').addClass('noActive');
		$('popup').setStyles({opacity:'0',top:'-5000px'});
	});
}

function initMicrositeNav()
{
	var micrositeNav = $('micrositeNav');
	if (!micrositeNav) return true;

	var lis = micrositeNav.getElements('li');
	lis.each(function(li,i) {
		if (i < lis.length) {
			var outerlink = li.getElement('a');
			if (outerlink != null) {
				var ol = outerlink.getNext('ol');
				var ul = outerlink.getNext('ul');
				if (ol == null && ul == null) {
				  // then this is just a link element
				  var qIdx = outerlink.href.indexOf('?');
				  var navParam;
				  if (li.id.length == 2)
					navParam = "l=" + li.id;
				  else if (li.id.length == 4)
					navParam = "s=" + li.id;
				  else if (li.id.length == 6)
					navParam = "d=" + li.id;

				  // if no parameters set, set them now
				  if (qIdx < 0)
					outerlink.href = outerlink.href + "?" + navParam;

				} else {
				  // then it's a link with list elements around it
				  // set up a click handler, which will grab all previous and next
				  // (sibling) li elements, hide any ol's or ul's under them,
				  // and then show the one we have now.  Also, find links under here
				  // and set the nav level params on their links as appropriate.
				  outerlink.addEvent('click', function(evt){
					new Event(evt).stop();
					// previous lis
					var prevLis = li.getAllPrevious('li');
					for (var i=0; i < prevLis.length; i++) {
					  var prevLi = prevLis[i];
					  var subols = prevLi.getElements('ol');
					  for (var s=0; s < subols.length; s++) {
						var subol = subols[s];
						subol.setStyles({display:'none'});
					  }
					  var subuls = prevLi.getElements('ul');
					  for (s=0; s < subuls.length; s++) {
						var subul = subuls[s];
						subul.setStyles({display:'none'});
					  }
					}
					// next lis
					var nextLis = li.getAllNext('li');
					for (var i=0; i < nextLis.length; i++) {
					  var nextLi = nextLis[i];
					  var subols = nextLi.getElements('ol');
					  for (var s=0; s < subols.length; s++) {
						var subol = subols[s];
						subol.setStyles({display:'none'});
					  }
					  var subuls = nextLi.getElements('ul');
					  for (s=0; s < subuls.length; s++) {
						var subul = subuls[s];
						subul.setStyles({display:'none'});
					  }
					}
					// now the ol or ul under here
					var sublist = ol;
					if (sublist == null)
					  sublist = ul;

					sublist.setStyles({display:'block'});
				  });

				  // and make the list visible now if the id is contained in 
				  // the request parameters
				  var sublist = ol;
				  if (sublist == null)
				    sublist = ul;
				  if (location.search.indexOf(li.id) > -1)
				    sublist.setStyles({display:'block'});

				} 

				// finally, regardless of the level, if this li's id is contained in the
				// request parameters, set an 'active' style on the a element
				// -- do this also if the li is the 1st one and NO req. params set.
				if (location.search.indexOf(li.id) > -1 || li.id == "l1" && location.search.length == 0)
				  outerlink.setStyles({color:'#FF00FF'});
			}
		}
	});
}

function getArtistNames(lastNameLetter, listtype)
{
	var doOutputNamesMarkup = {
	  callback: function(data) {
	    outputNamesMarkup(data, listtype);
	  }
	};

	// show a "please wait" message while the AJAX call is running.
	$('popup').getElements('ul')[0].innerHTML = "<li>Retrieving data, please wait...</li>";

	HUAMArtistNamesAjax.get(lastNameLetter, doOutputNamesMarkup);
}

function outputNamesMarkup(data, listtype)
{
	var names = data;
	var popup = $('popup');
	var markup = "";
	var artistid = "artist";
	
	// determine the correct form element ID based on whether the 
	// form was the 'narrow' or 'expanded' type
	if (listtype.match("expanded"))
	{
	  artistid = "artist1";
	}
	for (var i = 0; i < names.length; i++)
	{
	  var escapedName = names[i].replace(/'/g, "\\'");
	  escapedName = escapedName.replace(/\"/g, "&quot;");
	  markup = markup + ("<li><a href=\"#\" onclick=\"document.getElementById('" + artistid + "').value='" + escapedName + "'; javascript:closePopup(); document.getElementById('" + artistid + "').focus();\">" + names[i] + "</a></li>");
	}

	// replace the innerHTML with our new markup
	popup.getElements('ul')[0].innerHTML = markup;
}

function closePopup()
{
	$('popup').addClass('noActive');
	$('popup').setStyles({opacity:'0',top:'-5000px'});
	return;
}
	
function loadAjaxSearch(urltpl){
	var request = new Request({
		url: urltpl + '?rnd=' + $time(),
		method: 'get',
		encoding:'utf-8',
		//headers: {'X-Request': 'XML'},		
		onSuccess: function(responseText, responseXML){
			var popup=$('popup');
			popup.getElements('ul')[0].innerHTML=responseText;
		},
		onFailure:function(instance){
			//load return fasle
		}
	});	
	request.send();
	//fixed waring for validate
	return true;
}
function initIE6Fixes() {
	var ua = navigator.userAgent.toLowerCase();
	if (ua.indexOf("msie 6.0") != -1) {
		// set content05 width & margin, if followed by div.captionBoxTypical
		var content05 = $$('div.content05');
		if (content05 && content05.length != 0) {
			var captionBoxTypical = content05[0].getElement('div.captionBoxTypical');
			if (captionBoxTypical) {
			  var contentBox = content05[0];
			  contentBox.setStyles({width:'685px',margin:"0 15px 0 0"});
			}
		}
	}
}
function initMiscCSSFixes() {
	// Tracker #17110: add gray holding line beneath 3rd level nav, when present
	// to solve, look for particular child div's appearing beneath
	// content div's on pages where the 3rd level appears
	var content04 = $$('div.content04');
	if (content04 && content04.length != 0) {
		// in this case, must check whether 'div.horizontalPromo' is the first
		// non-whitespace child element
		var children = content04[0].getChildren();
		for (var i = 0; i < children.length; i++) {
		  if (children[i].nodeType == 3) { // skip whitespace
			continue;
		  }
		  if (children[i].tagName == "DIV" && children[i].className == "horizontalPromo") {
		  	var contentBox = content04[0];
		  	contentBox.setStyles({'border-top':'1px solid #CCCCCC','padding-top':'12px'});
		  }
		  // at this point, either we've found the DIV of interest as the first real child
		  // or not -- break either way
		  break;
		}
	}

	// also look for this div -- except when the page is the Busch-Reisinger page
	var content05 = $$('div.content05');
	if (content05 && content05.length != 0 && location.pathname.indexOf('/collection/busch-reisinger') < 0) {
		var captionBoxTypical = content05[0].getElement('div.captionBoxTypical');
		if (captionBoxTypical) {
		  var contentBox = content05[0];
		  contentBox.setStyles({'border-top':'1px solid #CCCCCC','padding-top':'12px'});
		}
	}
	
}
window.addEvent('domready', function() {
	initSearchResult();
	initToogleContent();
	initCalendarShow();
	initExpand();
	initListArtists();
	initIE6Fixes();
	initMiscCSSFixes();
	initMicrositeNav();
});





function displayEmailDiv(divID)
{ 
   // alert(divID);
   emailFriend = document.getElementById(divID);
   if(emailFriend.style.display == 'none')
   {
      emailFriend.style.display = 'block';
   }
   else
   {
      emailFriend.style.display = 'none';
   }
   
}

// this function checks the 'value' property of the element ID passed to it
// and returns false if it contains any illegal/HTML markup characters,
// otherwise it returns true.
function checkIllegalCharacters(element)
{
   var el = document.getElementById(element);
   if (el.value.indexOf("&") != -1) // this should cover HTML entities, too
     return false;
   else if (el.value.indexOf("<") != -1)
     return false;
   else if (el.value.indexOf(">") != -1)
     return false;
   else if (el.value.indexOf("\"") != -1)
     return false;
   else if (el.value.indexOf("'") != -1)
     return false;
   else if (el.value.indexOf("/") != -1)
     return false;

   else
     return true;
}

// this function is used by forms to check whether the Enter key was pressed
// Returns: true if Enter pressed, false otherwise
function checkEnter(e) { //e is event object passed from function invocation
   var characterCode = 0; //literal character code will be stored in this variable

   if (e && e.keyCode) {
     characterCode = e.keyCode;
   }

   if(characterCode == 13 || characterCode == 3){ 
//if generated character code is equal to ascii 13 (if enter key) or 3 (Enter on Mac numeric keypad)
     return true;
   }
   else{
     return false;
   }
}
