// ****** start: misc ******

document.observe('dom:loaded', function(e){
// set a js enabled flag for css targeting of non-javascript users
    if (jQuery)
        jQuery.noConflict();
        
	var elHtml = $(document.documentElement);
	if(elHtml){elHtml.addClassName('js-enabled');}
	// primaryLevelCheck();

});



function printPage()
{
    if (window.print){window.print();}
}

function hide(element)
{
	document.getElementById(element).style.display = 'none';
	return;
}
function show(element)
{
	document.getElementById(element).style.display = 'block';
	return;		
}



// ****** end: misc ******

function primaryLevelCheck() {
    var location = document.location.toString().match(/\w+(?=\/)/ig)[1];

    var nav = $$('ul#primary_navigation li');
    
    for (var i=0; i< nav.length; i++) {
        navClass = nav[i].className;
 
        //console.log(navClass);
        //console.log(location);
        if (navClass.include(location)) {
            //console.log("i am on" + navClass);
            console.log(navClass);
           if($$('li.' + navClass)[0]) {            
             $$('li.' + navClass)[0].addClassName("on");
            } 
        };
        
    }
}
    

// *** start: popup links ***

function doPopups()
{

	if (document.getElementById('my_popup_link')) //example
	{
		var my_popup_link = document.getElementById('my_popup_link');
		var my_popup_link_Href = my_popup_link.getAttribute('href');
		my_popup_link.onclick = function()
		{
			return(popuplink(my_popup_link_Href, this, 600, 400, false));
		}
	}

}

// start: popup window
// usage: popuplink(['js-only url',] this[, w[, h[, scroll[, extras]]]])
// basic usage: <a href="popup.html" target="_blank" onclick="return(popuplink(this));">new pop</a>
// advanced usage: <a href="popup_nojs.html" target="_blank" onclick="return(popuplink('popup_yesjs.html', this, 200, 100, false));">new pop</a>
// site-wide defaults:
popup_w = 400;
popup_h = 300;
popup_scroll = true;
popup_extras = 'location=0,statusbar=0,menubar=0';
function popuplink() {
	var undef, i=0, args=popuplink.arguments;
	var url = (typeof(args[i])=='string') ? args[i++] : args[i].getAttribute('href');
	var target = args[i++].getAttribute('target') || '_blank';
	var w = args[i++];
	var h = args[i++];
	var s = (args[i]===undef) ? popup_scroll : args[i++];
	var features = 'width=' + (w || popup_w)
				 + ',height=' + (h || popup_h)
				 + ',scrollbars=' + (s ? 'yes,' : 'no,')
				 + (args[i] || popup_extras);
	var win = window.open(url, target, features);
	win.focus();
	return false;
}

//Event.observe(window, "load", doPopups);

// *** end: popup links ***



/*
addPrintLink function by Roger Johansson, www.456bereastreet.com
*/
var addPrintLink = {
	init:function(sTargetEl,sLinkText) {
		if (!document.getElementById || !document.createTextNode) {return;} // Check for DOM support
		if (!document.getElementById(sTargetEl)) {return;} // Check that the target element actually exists
		if (!window.print) {return;} // Check that the browser supports window.print
		var oTarget = document.getElementById(sTargetEl);
		var oLink = document.createElement('a');
		oLink.id = 'print'; // Give the link an id to allow styling
		oLink.href = '#'; // Make the link focusable for keyboard users
		oLink.appendChild(document.createTextNode(sLinkText));
		oLink.onclick = function() {window.print(); return false;} // Return false prevents the browser from following the link and jumping to the top of the page after printing
		oTarget.appendChild(oLink);
	},
/*
addEvent function included here for portability. Replace with your own addEvent function if you use one.
*/
/* addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html */
	addEvent:function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() {obj["e"+type+fn](window.event);}
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	}
};
addPrintLink.addEvent(window, 'load', function(){addPrintLink.init('print','print');});


var EnterClick = Class.create({
	relevantTypes: $w('text password checkbox radio'),
	initialize: function(element, button){
		this.element = $(element).addClassName("enterclick");
		this.button = $(button);
		this.element.observe('keypress', this.__keyPress.bindAsEventListener(this));
	},
	__keyPress: function(e){
		var elSrc = e.element();
		if((e.keyCode == Event.KEY_RETURN)
			&& (elSrc.nodeName == 'INPUT')
			&& (this.relevantTypes.include(elSrc.type))) {
				// prevent default form submittal
				e.stop();
				// fire associated button's click event
				//console.log('firing ' + this.button.id);
				this.button.click();
		}
	}
});
// Extend Element with enterclick
Element.addMethods({
	onEnterClick: function(element, button) {
		new EnterClick(element, button);
		return element;
	}
});


function loadShowFirst(currentLinks) {
    var queryString = location.search;
    queryString = queryString.replace('#.*', '');
    queryString = queryString.replace('?', '');

// load the querystring items
    var allQAItems = queryString.split('&');
    for (var itemIdx = 0; itemIdx < allQAItems.length; itemIdx++) {
        var eachPair = allQAItems[itemIdx].split('=');
        
        // if this is named tab
        if (eachPair[0] == 'tab' && eachPair.length > 1) {

            var tabIdx = parseInt(eachPair[1], 10);
            // verify the tab index is valid
            if (isNaN(tabIdx) == false && tabIdx >= 0 && tabIdx < currentLinks.length) {
                return currentLinks[tabIdx].hash.replace('#', '');
            }
        }
    }

    if (currentLinks.length > 0)
        return currentLinks[0].hash.replace('#', '');
        
    return false;
}

// start ContentSwitcher
var ContentSwitcher = Class.create(
{
    initialize: function(links, items, rotate, showfirst, monitorTab) {
        this.links = links;
        this.items = items;
        this.rotate = rotate || false;
        this.showfirst = loadShowFirst(links);
        this.top = $('top');
        this.num = 0;
        this.monitorTab = monitorTab || false;

        // custom: check the subnav for jump links
        this.sublinks = $$('div#subcolnavbox ul.subnav li a[href*=#]');

        // show different item every 8 seconds
        if (rotate) {
            this.interval = setInterval(function() {
                this.doRotate();
            } .bind(this), 5000);
        }

        // Loop through each and attach a click handler
        var handleClick = this.__Click.bindAsEventListener(this);
        for (var i = 0; i < this.links.length; i++) {
            Event.observe(this.links[i], 'click', handleClick);
        }

        // Show the first content item
        if (this.showfirst) {
            for (var i = 0; i < this.items.length; i++) {
                if (this.items[i].id == this.showfirst) {
                    this.doShowHide(i);
                }
            }
            this.top.scrollTo();
        }

        // custom: check the page for any other jump links
        this.anchors = $A($$('a[href*=#]'));
        var handleAllClick = this.__AllClick.bindAsEventListener(this);
        this.anchors.each(function(a) {
            if (!this.links.include(a)) {
                if (this.links.include(a.href)) {
                    $(a).observe('click', handleAllClick);
                }
            }
        } .bind(this));

    },

    __AllClick: function(e) {
        clearInterval(this.interval); // clear timer once link is clicked
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i = 0; i < this.anchors.length; i++) {
            this.anchors[i].ahash = this.anchors[i].hash.replace('#', '');
            if (this.anchors[i] == element) {
                for (var j = 0; j < this.items.length; j++) {
                    if (this.items[j].id == this.anchors[i].ahash) {
                        this.doShowHide(j);
                        break;
                    }
                }
            } else {

            }
        }

    },

    __Click: function(e) {
        clearInterval(this.interval); // clear timer once link is clicked
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i = 0; i < this.links.length; i++) {
            if (this.links[i] == element) {
                this.doShowHide(i);
                // track switch

                var anchorName = element.readAttribute('href').replace('#', '');

                if (this.monitorTab) {
                    if (anchorName == this.monitorTab) {
                        /* fire custom event if we are monitoring tabs and the defined tab is clicked */
                        this.links[i].fire("customTab:ClickTabAction");
                    } else {
                        /* fire custom event if we are monitoring tabs and the defined tab is not clicked */
                        this.links[i].fire("customTab:DefaultTabAction");
                    }
                }

                pop_trackEvent({ "object": 'tab', "action": 'click', "label": anchorName });
                break;
            }
        }
    },

    // Rotate thru items
    doRotate: function() {
        this.num++;
        if (this.num == this.links.length) {
            this.num = 0;
        }
        this.doShowHide(this.num);
    },

    // Show a specific item, hide the rest
    doShowHide: function(iWhich) {
        for (var i = 0; i < this.items.length; i++) {
            if (i == iWhich) {
                this.items[i].show();
                do_sIFR();
                this.links[i].className = 'in';
                this.doSublinksShowHide(this.items[i].id);

                // this is needed to set the correct url for Send to Friend
                if (typeof doSendUrlEmail != 'undefined') {
                    doSendUrlEmail.SetUrlWithTab(this.items[i].id);
                }
            } else {
                this.items[i].hide();
                this.links[i].className = '';
            }
        }
    },

    // custom: show a specific subnav item, hide the rest
    doSublinksShowHide: function(iID) {
        if (this.sublinks != '') {
            for (var i = 0; i < this.sublinks.length; i++) {
                this.sublinks[i].ahash = this.sublinks[i].hash.replace('#', '');
                if (this.sublinks[i].ahash == iID) {
                    this.sublinks[i].className = 'in';
                } else {
                    this.sublinks[i].className = '';
                }
            }
        }
    }

});
// end ContentSwitcher

// start AudioSwitcher
// note: SWFObject embed params are hard-coded
var AudioSwitcher = Class.create (
{
    initialize: function (player, data)
    {
        this.player         = player;
        // this.links          = links;
        //this.title          = title;
        //this.caption        = caption;
        //this.credit         = credit;
        this.data           = data;
        this.width          = '610';
        this.height         = '29';
        this.version        = '9.0.0';
        this.bgcolor        = '#E4DDC6';
        this.swf            = '/_inc/flash/_swf/LyricAudioPlayer_AS3Prod.swf';
        
        
        this.writeSwf(0);
    },
    writeSwf: function(i)
    {

        this.flashvars = {
          mp3Path: this.data[i].mp3Path
          
        };
        
        this.params = {
          bgcolor: this.bgcolor
        };
        this.attributes = {
          id: this.player,
          name: this.player
        };
        swfobject.embedSWF(this.swf, this.player, this.width, this.height, this.version, false, this.flashvars, this.params, this.attributes);
    }

});
// end AudioSwitcher


// start LargeVideoEmbed
var LargeVideoEmbed = Class.create (
{

    initialize: function(content, mp3)
    {
        this.content        = content;
        this.mp3            = mp3;
        this.swf            = '/_inc/flash/_swf/LyricAudioPlayer_AS3Prod.swf';
        this.width          = '610';
        this.height         = '29';
        this.version        = '9.0.0';
        this.bgcolor        = '#E4DDC6';
        this.writeSwf();
    },

    writeSwf: function()
    {
        this.flashvars = {
          mp3Path: this.mp3
        };
        this.params = {
          bgcolor: this.bgcolor
        };
        this.attributes = {
          id: this.content,
          name: this.content
        };
        swfobject.embedSWF(this.swf, this.content, this.width, this.height, this.version, false, this.flashvars, this.params, this.attributes);
    }

});
// end LargeVideoEmbed

// start VideoGallery
var VideoGallery = Class.create (
{

    initialize: function(videoThumbAnchors, targetElementID)
    {
        this.videoThumbs      = videoThumbAnchors;      // video thumbnails
        this.targetElementID  = targetElementID;        // target div to write video to
        
        if (this.videoThumbs[0]) {                      // if there are video thumbnail anchors
                         
            this.showFirst(this.videoThumbs[0]);        // show the first video by default
            
		    this.videoThumbs.invoke("observe", "click", this.__Click.bindAsEventListener(this));	     // watch click on video thumbs
		    
		}
    },
    
    showFirst: function(firstThumb) {      
        this.setSelectedThumb(firstThumb);                                                                  // set first video thumb div as selected
        this.videoData = firstThumb.readAttribute('rel').evalJSON();                                        // get video embed information from rel attribute
        this.embedVideoSWF(this.targetElementID, this.videoData.flvUrl, this.videoData.videoPreviewImg, this.videoData.gCategory, this.videoData.gAction, this.videoData.gLabel);    // send all data to embed
    },
    
    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        
        this.clickedThumb = Event.findElement(e, "A");                                                      // make sure to grab anchor
            
        // console.log(this.clickedThumb.up(1)); 
        
        this.setSelectedThumb(this.clickedThumb);                                                           // mark clicked thumb div as selected
                                                        
        this.videoData = this.clickedThumb.readAttribute('rel').evalJSON();                                 // get video embed information from rel attribute
        this.embedVideoSWF(this.targetElementID, this.videoData.flvUrl, this.videoData.videoPreviewImg, this.videoData.gCategory, this.videoData.gAction, this.videoData.gLabel);    // send all data to embed

    },
    
    setSelectedThumb: function(selectedThumb) {
        for(var i=0; i < this.videoThumbs.length; i++) {
            $(this.videoThumbs[i].parentNode).removeClassName("selected");                                     // remove selected class from all thumb divs
        }
    
        $(selectedThumb.parentNode).addClassName("selected");                                                  // apply selected class to current video
        
    },

    embedVideoSWF: function(targetElementID, flvUrl, videoPreview, gCategory, gAction, gLabel)
    {
        
		    var flashvars = {               // set flash vars
			    flvPath: flvUrl,
			    flvWidth: '610',
			    flvHeight: '343',
			    autoPlayBool: 'false',
			    imgPath: videoPreview,
			    hideControls: 'true',
			    googleCategory: gCategory,
			    googleAction: gAction,
			    googleLabel: gLabel				    
		    };    		
		    var params = {                  // set flash params
			    menu: false,
			    play: true,
			    loop: false,
			    scale: 'noscale',
			    wmode: 'window',
			    deviceFont: false,
			    allowScriptAccess: 'always',
			    bgcolor: '#000000', 
			    allowFullScreen: 'true'
		    };

		    swfobject.embedSWF("http://www.lyricopera.org/_inc/flash/_swf/LyricVideoPlayer_AS3Prod.swf?cacheKiller=" + new Date().getTime(), targetElementID, "610", "343", "9.0.0", false, flashvars, params, {});
	
    }
});
// end VideoGallery



// start ImageGallery
var ImageGallery = Class.create (
{

    initialize: function(imageThumbAnchors, targetElementID)
    {
        this.imageThumbs      = imageThumbAnchors;      // image thumbnails
        this.targetElementID  = targetElementID;        // target div to write image info to
                
  
        if (this.imageThumbs[0]) {                      // if there are image thumbnail anchors
                         
            this.showFirst(this.imageThumbs[0]);        // show the first image info by default
            
		    this.imageThumbs.invoke("observe", "click", this.__Click.bindAsEventListener(this));	     // watch click on image thumbs
		    
		}
    },
    
    showFirst: function(firstThumb) {      
        this.setSelectedThumb(firstThumb);              // set first image thumb div as selected 
                                                                                                  
        this.imageData = $(firstThumb).adjacent('span.relstuff').first().innerHTML.evalJSON();   // get associated image information from span

        this.showImage(this.imageData.Title, this.imageData.BrowseURL, this.imageData.Credit, this.imageData.Caption);    // send all data to showImage
        
    },
    
    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        
        this.clickedThumb = Event.findElement(e, "A");        // make sure to grab anchor                                                  
        
        this.setSelectedThumb(this.clickedThumb);            // mark clicked thumb div as selected
                                                        
        this.imageData = this.clickedThumb.adjacent('span.relstuff').first().innerHTML.evalJSON();                         // get associated image information from span
        this.showImage(this.imageData.Title, this.imageData.BrowseURL, this.imageData.Credit, this.imageData.Caption);    // send all data to showImage

    },
    
    setSelectedThumb: function(selectedThumb) {
        for(var i=0; i < this.imageThumbs.length; i++) {
            $(this.imageThumbs[i].parentNode).removeClassName("selected");  // remove selected class from all thumb divs
        }
    
        $(selectedThumb).parentNode.addClassName("selected");  // apply selected class to current image
        
    },

    showImage: function(imageTitle, browseUrl, credit, caption)
    {
       
       var writeDiv = $(this.targetElementID).childElements();  // write all image info to correct div, within correct html
       writeDiv[0].update(browseUrl);
       writeDiv[1].update(imageTitle);
       writeDiv[2].update(caption);
       writeDiv[3].update(credit);
		    
    }
});
// end ImageGallery


function embedPodcastSWF(targetElementID, sPodCastUrl, gCategory, gAction, gLabel) {
    var flashvars = {
	    mp3Path: sPodCastUrl,
	    loopBool: "false",
	    autoPlayBool: "false",
	    hideControlsBool: "false",
	    slideControlsBool: "true",
	    controlPadding: "5",
        controlSetup: "PlayPause,ProgressBar,VolumeControl,TimeDisplay",
        buffer: "5",
        googleCategory: gCategory,
        googleAction: gAction,
        googleLabel: gLabel	
    };    		
    var params = {
	    menu: false,
	    allowScriptAccess: 'sameDomain',
	    bgcolor: '#E4DDC6',
	    allowfullscreen: "true",
        salign: "tl",
        wmode: "window"
    };
	// console.log(flashvars.mp3Path);
    swfobject.embedSWF("http://www.lyricopera.org/_inc/flash/_swf/LyricAudioPlayer_AS3Prod.swf", targetElementID, "610", "29", "9.0.0", false, flashvars, params, {});
}

/* Centers the position of the DHTML Popup */
function setPos(dhtmlWin) {
    if (dhtmlWin.getHeight() >= document.viewport.getHeight()) {
        var topPos = document.viewport.getScrollOffsets().top;
    } else {
        var topPos = document.viewport.getScrollOffsets().top + ((document.viewport.getHeight() - dhtmlWin.getHeight()) / 2);
    }
    var leftPos = (document.viewport.getWidth() - dhtmlWin.getWidth()) / 2 - 100;
    
    dhtmlWin.setStyle({
        top: topPos+"px",
        left: leftPos+"px"
    });
}

