﻿//outside links
$(document).ready( function(){fixLinks('body')} );
function fixLinks(root){
	var myhost = location.protocol + '//' + location.host;
	
	$(root).find('a[href^=http]').not('[href^=' + myhost+']').each( function(){
		var $this = $(this);
		if( $this.is('.youtube') ){
			var match = this.href.match("[\\?&]v=([^&#]*)");
			if( match.length > 1 ){
				var vid = match[1];
				var title = $this.text();
				$this.prepend( $('<img src="http://img.youtube.com/vi/' + vid + '/2.jpg" alt="Watch video"/>') );
				$('body').append( 
					'<div id="y_' + vid + '" class="hidden"><div style="padding:0" id="' + vid + '"></div></div>' );
				$this.colorbox( {
				    width:562, height:414, inline:true, resize:false, href:"#" + vid,
				    onOpen:function(){ gaTrackingHandler( "youtube", "start video", title ); },
                    onClosed:function(){ gaTrackingHandler( "youtube", "stop video", title ); }
				    },
					function(){
						swfobject.embedSWF(
							'http://www.youtube.com/v/' + vid + '&hl=en&fs=0&rel=0&autoplay=1',
							vid, /* div id */
							560, 340, /* w,h */ 
							"8.0.0", /* flash version */
							false, /* no express install */
							{}, /*flashvars*/
							{allowFullScreen:true,play:true,allowscriptaccess:true}, /*params*/
							{} /*attributes*/
						);
						$('#' + vid).show();
					}
				)
				$this.parents('.abstract').css( 'height','90px' );
			}
		}
		else{ //track outbound non-youtube links:
		    var gaObj = "outbound-link";
		    var gaAction = $this.attr("href");
		    $this.click( function(){ gaTrackingHandler( gaObj, gaAction ) } );
		}
		this.target = (this.target) ? this.target : '_blank';
	} );
	$('a[target]').not('.youtube').addClass('external');
	
	//track download links:
	var regexDownloads = new RegExp(".pdf$|.jpg$|.gif$|.png$|.zip$|.doc$|.xls$|.ppt$|.mpg$");
	$(root).find('a[href]').each( function(){
	    var $this = $(this);
	    if($this.attr("href").toLowerCase().match(regexDownloads)){
	        $this.click( function(){ gaTrackingHandler( "download-link", $this.attr("href") ) } );
	    }
	});
	
	//track email links:
	$(root).find('a[href^=mailto]').each( function(){
	    var $this = $(this);
	    $this.click( function(){ gaTrackingHandler( "email-link", $this.attr("href").substr(7) ) } );
	});
	
}
$().bind('cbox_complete',
	function(x){
		$('body').css('overflow','hidden');
	}
);		
$().bind('cbox_closed',
	function(x){
		$('body').css('overflow','visible');
	}
);
//top nav
 $(document).ready(function() {
    $('div.topNav div.t1').hoverIntent(
        function(){
            $('div.t2s').hide();
            $(this).find('div.t2s').slideDown("fast");
        },
        function(){
            $(this).find('div.t2s').hide();
        }
    );
});

//sIFR replacements -- before page loads
(initSifr = function(){
	try{
		var helv = { src: '/Includes/Flash/HelveticaNeueLTStdTh.swf' };
		sIFR.activate(helv);
		// Read more about styling at <http://wiki.novemberborn.net/sifr3/Styling>.
		sIFR.replace(helv, {
		  selector: '.rightContent > h4',
		  css: { '.sIFR-root': { 'color': '#216e8e' } },
		  ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01],
		  tuneHeight: -6,
		  offsetTop: 1,
		  wmode: 'transparent'
		});
		sIFR.replace(helv, {
		  selector: '.artistBanner > h1',
		  css: { '.sIFR-root': { 'color': '#ffffff' } },
		  ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01],
		  tuneHeight: -6,
		  offsetTop: 1,
		  wmode: 'transparent'
		});
		sIFR.replace(helv, {
		  selector: 'h1',
		  css: { '.sIFR-root': { 'color': '#216e8e' } },
		  ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01],
		  tuneHeight: -6,
		  offsetTop: 1,
		  wmode: 'opaque'
		});
	}
	catch(e){
	}
})();

//tabs
function initTabNav( whichTabs, whichContent ){
    $(whichTabs).find("li").click(
        function(){
			location.hash = this.id.substr(4); // don't want to use the real id, else the page jumps to that element
            updateTabNav(whichTabs, whichContent);
            $(this).find("a").blur();
            gaTrackingHandler( "tab", "click", $(this).text() );  
            return false;
        }
    );
    updateTabNav(whichTabs, whichContent);
}

function updateTabNav(whichTabs, whichContent){
    var hash = location.hash.replace('#','');
    var li = null;
    
    $(whichTabs).find("li").each(
		function(){
			if( hash.indexOf( this.id.substr(4) ) > -1 ){ // tab-
				li = $(this);
			}
			$(this).removeClass("at");
		}
    );
    if( ! li ){ 
		li = $(whichTabs + " li:first-child");
	}
	if( li && li.length ){
		li.addClass("at"); //set current
		getTabContent(li.find("a").attr("href"), whichContent, li.find("a").text());
		initExpDivs();
	}
}

function getTabContent( url, whichContent, tabLabel ){
	url = url + (( url.indexOf('?')== -1 ) ? '?' : '&') + 'bodyOnly';
	$(whichContent)
     .html('<span class="loadingText">Loading Content</span>')
     .load( url, null, function(){ initTabContent(whichContent); } );
}

function initTabContent(whichContent){
	$(whichContent).find("form#aspnetForm").ajaxForm(
		function(s){ 
			$(whichContent).html(s); 
			initTabContent(whichContent); 
		}
	);
	fixLinks(whichContent);
	initExpDivs(); // expanding divs
}

//forms
function submitForm( btn ){
	if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate('') ){
		if( ! btn.hasBeenClicked ){
			btn.value = "Processing..."
			btn.className='buttonClicked';
			btn.blur();
			btn.hasBeenClicked = true;
			return true;
		}
		btn.disabled=true;
		return false;
	}	
}

function validateDonationBlank(){
	$('div.supportCallout :text').each( 
		function(){
			if( isNaN( parseFloat( $(this).val().replace(/[^0-9\.]/g, '') ) ) ){
				return true;
			}
			else if( confirm("You didn't add your tax deductible donation. Would you like to include it?\n\nPress OK to add your donation, CANCEL to checkout without the donation.") ){
				$('div.supportCallout :button').click();
				return false;
			}
		}
	);
	return true;
}

// donation form
 $(document).ready(function() {
	$('div.supportCallout :button')
		.click( function(){
			var amt = $(this).parent().parent().find(':text').val().replace( /[^0-9\.]/g, '' );
			if( isNaN(parseFloat( amt )) ){
				alert( "Please enter an amount to donate." );
				$(this).parent().parent().find(':text').focus();
				return false;
			}
			else{
				$(this).parent().parent().html('<span class="loadingText">Submitting Donation</span>');
				$.getScript( '/Includes/JS/donate.js.ashx?amount=' + amt );
			}
		} );
 });

//casting table
function initCastingTable(){
    if($("select#performanceSelector")){
        $("select#performanceSelector").change( function(){ updateCastingTable($(this).val()) } );
        updateCastingTable(1);
    }
}
currCastingCol = null;
function updateCastingTable(col){
    col = parseInt(col)+1;
    if(currCastingCol!=null) $("table#castingData td:nth-child("+currCastingCol+")").hide(); 
    $("table#castingData td:nth-child("+col+")").show();
    currCastingCol = col;
}

//expanding content
$(document).ready(function(){
    initExpDivs();
});
var expDivsOrigContent = new Array();
var expDivsOrigHeights = new Array();
function initExpDivs(){
    $("div.expandable div").each(
        function(i){
            expDivsOrigContent.push($(this).html()); //store all original content
            expDivsOrigHeights.push($(this).height());
            var trimmedHtml = expDivClipHtml( $(this).html(), i );
            $(this).html( trimmedHtml );
        }
    );
}
function expDivClipHtml( html, i ){
    var expDivsWidth = $("div.expandables").parent().width();
    var closers = '</a></i></em></b></strong>'; //in case one was opened
    return html.substr(0,expDivsWidth/3) + closers + '... <a href="#more" onclick="return expDivOpen('+i+');">more</a></p>';
}
function expDivOpen(index){
    var expDiv = $("div.expandables div:nth-child("+ (index+1) +") div");
    jQuery.each(expDivsOrigContent, function(i) { expDivClose(i); }); //collapse all others
    expDiv.html( expDivsOrigContent[index] ); //replace trimmed content with full content
    expDiv.parent().animate({ height : expDivsOrigHeights[index]+50 }, 300, null, function(){
        expDiv.parent().css( "overflow", "visible" )    
    }); //animate open
    
    return false;
}
function expDivClose(index){
    var expDiv = $("div.expandables div:nth-child("+ (index+1) +") div");
    expDiv.html( expDivClipHtml( expDivsOrigContent[index], index ) )
    expDiv.parent().css({ "overflow" : "hidden", "height" : "115px"});
    return false;
}

//gallery
GalleryImg = function( src, desc ){
    if(galleryLoaded)return; //suppress dupes on ajaxy pages
    this.src = src;
    this.desc = desc;
    GalleryImg.all[ GalleryImg.all.length ] = this;
}
GalleryImg.all = new Array();

var preloads = new Array();
jQuery.preloadImages = function() {
    var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
	for(var i = 0; i<a.length; i++){
		eval( 'img'+i+'=document.createElement("img")' );
		eval( 'img'+i+'.onload=function(){preloads['+i+'] = true;};' );
		eval( 'img'+i+'.setAttribute( "src", ""+a['+i+'].src )' );
	}
}

var galleryCurrImg;
var galleryLoaded = false;
function initGallery(optidx){
    //set optional start index
    optidx = ( optidx == undefined ) ? 0 : parseInt(optidx)-1;
    //build gallery
    var galleryNav = (GalleryImg.all.length > 1) ? '<div id="gallerynav"><a href="#prev" onclick="return updateGalleryImg(\'prev\')"><img src="/images/prev.gif" /></a>&nbsp;<span id="currImg"></span> of <span id="totalImgs"></span>&nbsp;<a href="#next" onclick="return updateGalleryImg(\'next\')"><img src="/images/next.gif" /></a></div>' : '';
    $.preloadImages(GalleryImg.all);
    $('#galleryholder').html('<table cellpadding="0" cellspacing="0"><tr><td>'+ galleryNav +'<img id="galleryimg" src="/images/ajax-loader.gif" /><cite id="gallerydesc"></cite></td></tr></table>');
    img0 = document.createElement("img");
    img0.onload=function(){ $("#galleryimg").attr("src", GalleryImg.all[optidx].src ).hide().fadeIn(); };
    img0.setAttribute( "src", GalleryImg.all[optidx].src );
    
    galleryCurrImg = optidx;
    updateGalleryTxt(optidx);
    galleryLoaded = true;
}
function updateGalleryTxt(which){
    $('span#currImg').text(galleryCurrImg+1);
	$('span#totalImgs').text(GalleryImg.all.length);
	$("#gallerydesc").html(GalleryImg.all[which].desc);
}

var retry = null;
function updateGalleryImg(dir){
    var galleryimg = $('#galleryimg');
	galleryimg.hide();
	
	var nextImg = galleryCurrImg+1;
	if( nextImg == GalleryImg.all.length ) nextImg = 0;
	var prevImg = galleryCurrImg-1;
	if( prevImg == -1 ) prevImg = GalleryImg.all.length-1;

	//retry if not loaded yet
	clearTimeout(retry);
	if( preloads[nextImg]!=true || preloads[prevImg]!=true ){
		galleryimg.attr( "src", "/images/ajax-loader.gif" ).show();
		retry = setTimeout( "updateGalleryImg('" + dir + "')", 1000 );
		return false;
	}
	
	if( dir=="next" ) galleryCurrImg = nextImg;
	else if(dir=="prev") galleryCurrImg = prevImg;
	
	galleryimg.attr('src', ""+GalleryImg.all[galleryCurrImg].src ).fadeIn();
	updateGalleryTxt(galleryCurrImg);

	return false;
}

//artist photo gallery
function initArtistGallery(){
    registerArtistNav();
    makeThumbs("Biography");
}
function registerArtistNav(){
    $("div.artistNav").find("a").click(
        function(){
            ahref = $(this).attr('href');
            link = ahref.substr(1,ahref.length);
            $("div.artist"+link).show();
            artistNavClick(link);
            $(this).blur();
        }
    );
}
function artistNavClick(which,num){
    $("div.artistNav").find("a").removeClass("at");
    $("a#link"+which).addClass("at");
    jQuery.each( artistNavItems, function(i){ $("#artist"+artistNavItems[i]).hide(); } );
    $("#artist"+which).show();
    makeThumbs(which);
    if(which=="PhotoGallery") initGallery(num);
}
function makeThumbs(which){
    var div = $("#thumbs"+which);
    div.html("");
    for(var i=0; i<GalleryImg.all.length; i++){
        div.append('<a href="#PhotoGallery-'+ (i+1) +'"><img src="'+ GalleryImg.all[i].src +'" /></a>');
        $(div).find("a").click( function(){
                ahref = $(this).attr('href');
                num = ahref.substr( (ahref.indexOf("-")+1), ahref.length );
                artistNavClick("PhotoGallery",num);
            }
        );
    }
}


/* buyTickets links */
$(document).ready(function(){
	var zIndex=100;
	$('a.buyTickets')
		.wrap( '<div class="buyTicketsWrapper" style="display:none"></div>' )
		.each(
			function(){
				var url = this.href;
				$(this).parent()
						 .css( 'zIndex', --zIndex )
						 .hoverIntent( 
							function(){
								$('div.choosePerf').hide();
								$(this).find('div.choosePerf').fadeIn("fast");
							},
							function(){
								$(this).find('div.choosePerf').fadeOut("normal");
							}
						 )
						 .append( '<div class="choosePerf hidden"><span class="loadingText">Loading Performance Dates</span></div>' )
						 .find('div.choosePerf')
							.load( '/Season/Reserve/ChoosePerformance.aspx?url=' + url, null, 
								function(s){
									if( ! s.match(/[a-z]/) ){
										$(this).parent().hide();
									}
									else{
										$(this)
										 .parent()
										   .show()
										   .end()
										 .height( Math.min($(this).height(),253) )
										 .css( 'overflow', 'auto' )
									}
								}
							);
			}
		);
});

/* patron mail */
$(document).ready(function(){
    $("a#JoinEmailList").colorbox({
        width:"400px", inline:true, href:"#patronMailFormDiv", 
        onComplete:function(){ gaTrackingHandler( "mailing-list", "open form" ); },
        onClosed:function(){ gaTrackingHandler( "mailing-list", "close form" ); }
    });
});
function submitPatronMailForm(frm){
    frm.submit();
    $("#patronForm").hide();
    $("#patronThanks").show();
    setTimeout( '$("a#JoinEmailList").colorbox.close()', 4000 );
    setTimeout( 'resetPatronMailForm()', 4000 );
    gaTrackingHandler( "mailing-list", "submit form" );
    return true;
}
function resetPatronMailForm(){
    $("#patronForm").show();
    $("#patronThanks").hide();
}
function closePatronMailForm(){
    $("a#JoinEmailList").colorbox.close();
    return false;
}

/* css browser selector */
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3')?g+' ff3':is('gecko/')?g:/opera(\s|\/)(\d+)/.test(ua)?'opera opera'+RegExp.$2:is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);