var pageList = ['/home','/about','/tickets','/team','/press'];
var pages = [];
var currentPage = 0;
var setHeight;
var currentScroll;
var currentSlide = 0;
var rotateTimeout = 5000;
var totalHtml;
var aboutPlayer = 0;
var moving = 0;
var startyear;
var startmonth;
var nextdate;
var calendarHeight=605;
var currentStars = 5;

var langs = [];
langs[0] = "<div class='title'>HORAIRE DES REPRÉSENTATIONS:</div>Pour afficher notre calendrier des représentations, cliquez <a href='#' id='perf-sched'>ICI</a>.<br /><br /><div class='title'>ACHAT DE BILLETS:</div>Achat en ligne: cliquez <a href='/redirect/tickets' target='_blank'>ICI</a>.<br /><br />Pour acheter vos billets sur place, veuillez vous rendre au théâtre Foxwoods:<br /><br />Théâtre Foxwoods<br />213 West 42nd Street, between 7th and 8th Avenues.<br /><br />Horaires d’ouverture des guichets : de 10 h 00 à 20 h 00, du lundi au samedi et le dimanche, de 12 h 00 à 18 h 00.<br /><br />Modes de paiement acceptés : espèces, principales cartes de crédit et chèque de voyage.<br /><ul><li><div class='title'>BILLETS DE DERNIÈRE MINUTE:</div>Il est possible d’acheter des billets de dernière minute, au prix de $30, chaque matin au guichet du Théâtre Foxwoods. Deux billets par personne maximum. Espèces uniquement. Sous réserve de disponibilité et suivant les spectacles.  Horaires d’ouverture du guichet mentionnés ci-dessus.</li></ul><div class='title'>COMMENT S’Y RENDRE:</div>Cliquez <a href='http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=213+W+42nd+St,+New+York%E2%80%8E&sll=40.756425,-73.987298&sspn=0.005372,0.011362&ie=UTF8&hq=&hnear=213+W+42nd+St,+New+York,+10036&z=16' target='_blank'>ici</a> pour voir le plan.<br /><br /><div class='title'>PLAN DE LA SALLE:</div>Orchestre (Orchestra): idéal pour voir tout ce qui se passe sur la scène et pour vous mettre dans l’action.<br /><br />Corbeille (Flying Circle): pour un spectacle de cette envergure, ces places sont parfaites. Elles vous permettront d'avoir une vue d'ensemble sur le spectacle.<br /><br />Balcon (Balcony): ces sièges vous donnent une excellente vue sur le spectacle.<br /><br /><div class='title'>ÂGE RECOMMANDÉ:</div>Le spectacle Spider-Man Turn Off The Dark est recommandé aux enfants de 8 ans et plus.<br /><br /><div class='title'>PRODUITS:</div>Une grande sélection de produits liés au spectacle Spider-Man Turn Off The Dark en vente au théâtre. <br /><br /><div class='title'>BOISSONS ET SNACKS:</div>Une grande choix de boissons non alcoolisées et alcoolisées (bières, vins, liqueurs) ainsi que de snacks à emporter dans la salle du théâtre pendant le spectacle.";

langs[1] = "<div class='title'>VERANSTALTUNGSKALENDER:</div>Um unseren Veranstaltungskalender anzuzeigen, klicken Sie <a href='#' id='perf-sched'>HIER</a>.<br /><br /><div class='title'>KARTEN BESTELLEN:</div>Online bestellen: <a href='/redirect/tickets' target='_blank'>HIER</a> klicken.<br /><br />Sie können Karten auch direkt an der Hauptkasse des Foxwoods Theatre kaufen:<br /><br />Hauptkasse des Foxwoods Theatre<br />213 West 42nd Street, between 7th and 8th Avenues.<br />Öffnungszeiten: Mo – Sa von 10 bis 20 Uhr; So von 12 bis 18 Uhr.<br /><br />An der Hauptkasse können Sie in bar, mit gängigen Kreditkarten und mit Travellerschecks zahlen.<br /><ul><li><div class='title'>RESTKARTEN:</div>Restkarten sind immer vormittags für 30 USD an der Hauptkasse des Foxwoods Theatre erhältlich.  Maximal 2 Eintrittskarten pro Person.  Nur Barzahlung. Abhängig von der Verfügbarkeit und möglicherweise nicht für jede Vorstellung. Es gelten die Öffnungszeiten oben.</li></ul><div class='title'>WEGBESCHREIBUNG:</div>Klicken Sie <a href='http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=213+W+42nd+St,+New+York%E2%80%8E&sll=40.756425,-73.987298&sspn=0.005372,0.011362&ie=UTF8&hq=&hnear=213+W+42nd+St,+New+York,+10036&z=16' target='_blank'>hier</a>, um eine Umgebungskarte des Foxwoods Theatre anzuzeigen.<br /><br /><div class='title'>SITZPLATZ-Informationen:</div>Orchester (Orchestra): Im Parkett haben Sie eine sehr gute Sicht auf die Bühne und befinden sich mitten im Geschehen.<br /><br />Mezzanin (Flying Circle):  Auf diesen Plätzen können Sie das Geschehen optimal überblicken und auch die Flugeinlagen sehen.<br /><br />Balkon (Balcony):  Auf diesen Plätzen haben Sie die beste Sicht auf die Flugeinlagen.<br /><br /><div class='title'>ALTERSEMPFEHLUNG:</div>Spider-Man Turn Off The Dark ist für Kinder ab 8 Jahren geeignet.<br /><br /><div class='title'>FANARTIKEL:</div>Im Theater wird eine große Auswahl an \"Spider-Man Turn Off The Dark\"-Fanartikeln zum Kauf angeboten.<br /><br /><div class='title'>GETRÄNKE UND SNACKS:</div>Verschiedene Konzessionäre bieten im Foxwoods Theater Snacks, Bier, Wein und Spirituosen an. Alle Snacks und Getränke können während der Vorstellung mit in den Saal genommen werden.";

langs[2] = "<div class='title'>PROGRAMMA DELLO SPETTACOLO:</div>Per visualizzare il calendario dello spettacolo, cliccate <a href='#' id='perf-sched'>QUI</a>.<br /><br /><div class='title'>PER ACQUISTARE I BIGLIETTI:</div>Per l’acquisto online, cliccate <a href='/redirect/tickets' target='_blank'>QUI</a>.<br /><br />Per l’acquisto diretto, vi preghiamo di presentarvi alla biglietteria del teatro Foxwoods:<br /><br />Foxwoods Theatre Box Office (biglietteria del teatro Foxwoods)<br />213 West 42nd Street, between 7th and 8th Avenues.<br />Orari della biglietteria: dal lunedì al sabato dalle 10.00 alle 20.00; domenica dalle 12.00 alle 18.00.<br /><br />Si accettano contanti, tutte le principali carte di credito e gli assegni di viaggio.<br /><ul><li><div class='title'>BIGLIETTI LAST MINUTE (“RUSH TICKETS”):</div>questi biglietti da 30 $ sono disponibili tutte le mattine presso la biglietteria del teatro Foxwoods. Massimo 2 biglietti per persona. Solo contanti. Biglietti secondo disponibilità e non garantiti per ogni spettacolo. Gli orari della biglietteria sono indicati qui sopra.</li></ul><div class='title'>COME RAGGIUNGERE IL TEATRO:</div>Cliccate <a href='http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=213+W+42nd+St,+New+York%E2%80%8E&sll=40.756425,-73.987298&sspn=0.005372,0.011362&ie=UTF8&hq=&hnear=213+W+42nd+St,+New+York,+10036&z=16' target='_blank'>qui</a> per visualizzare la mappa che vi condurrà al teatro Foxwoods.<br /><br /><div class='title'>Informazioni sull’UBICAZIONE DEI POSTI A SEDERE:</div>Platea (Orchestra): una poltrona vicina è l’ideale per vedere i dettagli sul palco e per immergersi nell’azione.<br /><br />Flying Circle: per uno show di questa portata, le poltrone che si trovano in una zona intermedia sono perfette per ammirare le grandi scenografie e le acrobazie.<br /><br />Galleria (Balcony): queste poltrone offrono una prospettiva straordinaria sulle acrobazie.<br /><br /><div class='title'>ETÀ IDEALE:</div>Spider-Man Turn Off The Dark è consigliato ai ragazzi di età non inferiore agli 8 anni.<br /><br /><div class='title'>GADGET:</div>Presso il teatro è disponibile una vasta gamma di gadget Spider-Man Turn Off The Dark.<br /><br /><div class='title'>SNACK E BEVANDE:</div>Presso il teatro Foxwoods potrete trovare un ampio assortimento di spuntini, snack, birre, vini e liquori da portare in sala durante lo spettacolo.";

langs[3] = "<div class='title'>公演スケジュール</div><a href='#' id='perf-sched'>公演スケジュール表をご覧になるには、ここをクリックしてください。</a><br /><br /><div class='title'>チケットの購入方法</div><a href='/redirect/tickets' target='_blank'>オンラインでのご購入は、ここをクリックしてください。</a><br /><br />窓口でのご購入は、フォックスウッズ劇場のチケットボックスに直接お越しください。<br /><br />フォックスウッズ劇場チケットボックス<br />213 West 42nd Street, between 7th and 8th Avenues.<br />チケットボックス営業時間：月曜日から土曜日は午前10時から午後8時、日曜日は正午から午後6時<br /><br />お支払いは、現金、主要クレジットカード、トラベラーズチェックで行えます。<br /><ul><li><div class='title'>ラッシュチケット:</div>毎朝劇場のチケットボックスで当日券を30ドルで販売します。ご購入は、お一人様2枚までとさせていただきます。お支払いは、現金のみです。  ラッシュチケットは、チケットの販売状況によりご希望に添えない場合があります。また、各公演でラッシュチケットを販売するわけではありません。チケットボックスの営業時間は、上記を御覧ください。</li></ul><div class='title'>地図</div><a href='http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=213+W+42nd+St,+New+York%E2%80%8E&sll=40.756425,-73.987298&sspn=0.005372,0.011362&ie=UTF8&hq=&hnear=213+W+42nd+St,+New+York,+10036&z=16' target='_blank'>ここを</a>クリックすると、フォックスウッズ劇場の地図が表示されます。<br /><br /><div class='title'>座席情報 </div>オーケストラ (Orchestra)：舞台の様子がよくわかる理想的な席です。<br /><br />フライングサークル (Flying Circle)：このスケールのショーの場合は、中程の座席が大型のピクチャーやフライングを楽しむのに最適です。<br /><br />バルコニー (Balcony)：空中のショーを思う存分楽しめます。<br /><br /><div class='title'>観劇推奨年齢</div>スパイダーマン： ターン・オフ・ザ・ダークは、8歳以上に適しています。<br /><br /><div class='title'>お土産グッズ</div>劇場では、スパイダーマン： ターン・オフ・ザ・ダークの各種お土産グッズを取り揃えております。<br /><br /><div class='title'>お飲み物とスナック</div>劇場では各種スナック、ビール、ワイン、アルコール飲料を取り揃えており、公演中に観客席にお持ち込みいただけます。";

langs[4] = "<div class='title'>PROGRAMA DE FUNÇÕES:</div>Clique <a href='#' id='perf-sched'>AQUI</a> para ver o nosso calendário de funções..<br /><br /><div class='title'>PARA COMPRAR INGRESSOS:</div>Para compra on-line clique <a href='/redirect/tickets' target='_blank'>AQUI</a>.<br /><br />Para comprar pessoalmente, venha à bilheteria do Foxwoods Theatre:<br /><br />Bilheteria do Foxwoods Theatre<br />213 West 42nd Street, between 7th and 8th Avenues.<br />Horário de atendimento da bilheteria:   De segundo-feira ao sábado, das 10h00 às 20h00; domingos, das 12h00 às 18h00.<br /><br />A bilheteria aceita o pagamento em dinheiro, cartões de crédito importantes e cheques de viagem.<br /><ul><li><div class='title'>INGRESSOS COM DESCONTO (RUSH TICKETS):</div>Todas as manhãs, na bilheteria do Foxwoods Theatre, poderão encontrar ingressos com desconto de $30.  O limite é de 2 ingressos por pessoa.  Única forma de pagamento é em dinheiro.  Ingressos sujeitos à disponibilidade e podem não estar disponíveis para todas as funções.  O horário de atendimento da bilheteria está acima indicado.</li></ul><div class='title'>INDICAÇÕES:</div>Clique <a href='http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=213+W+42nd+St,+New+York%E2%80%8E&sll=40.756425,-73.987298&sspn=0.005372,0.011362&ie=UTF8&hq=&hnear=213+W+42nd+St,+New+York,+10036&z=16' target='_blank'>aqui</a> para obter um mapa do Foxwoods Theatre.<br /><br /><div class='title'>Informação sobre a LOCALIZAÇÃO DO ASSENTO:</div>Plateia (Orchestra): sentar-se perto é muito conveniente para ver os detalhes do palco, integrando-se à ação.<br /><br />Plateia Alta (Flying Circle): para uma representação deste tipo, para poder ter uma visão de conjunto e em especial dos vôos, os melhores assentos são os situados na metade do teatro.<br /><br />Galeria ou mezanino (Balcony): nestes assentos poder-se-á ter uma excelente perspectiva dos vôos. <br /><br /><div class='title'>RECOMENDAÇÕES QUANTO À IDADE:</div>Spider-Man Turn Off The Dark é recomendado para crianças de 8 anos ou mais.<br /><br /><div class='title'>ARTIGOS PROMOCIONAIS:</div>Poderá encontrar uma grande variedade de artigos promocionais de Spider-Man Turn Off The Dark para comprá-los no teatro. <br /><br /><div class='title'>BEBIDAS E LANCHES:</div>O Foxwoods Theatre  dispõe de uma linha completa de concessionários, lanches, cerveja, vinho  e bebidas que poderão ser levados  para o auditório durante a função.";

langs[5] = "<div class='title'>PROGRAMA DE FUNCIONES:</div>Para ver nuestro calendario de funciones, haga clic <a href='#' id='perf-sched'>AQUÍ</a>.<br /><br /><div class='title'>PARA COMPRAR BOLETOS:</div>Para comprar en línea: haga clic <a href='/redirect/tickets' target='_blank'>AQUÍ</a>.<br /><br />Para comprar personalmente, venga la boletería del  Foxwoods Theatre:<br /><br />Boletería del Foxwoods Theatre<br />213 West 42nd Street, between 7th and 8th Avenues.<br />Horario de atención de la boletería: 10am a 8pm lunes  a sábado; 12pm a 6pm los domingos.<br /><br />En la boletería se acepta el pago en efectivo, tarjetas de crédito importantes y cheques de viajero.<br /><ul><li><div class='title'>BOLETOS CON DESCUENTO (RUSH TICKETS):</div>En la boletería de Foxwoods Theatre podrá encontrar boletos con descuento de $30 todas las mañanas. El límite es de 2 boletos por persona.  Solo se acepta efectivo.  Están sujetos a disponibilidad y pueden no estar disponibles para todas las funciones.  El horario de atención de la boletería se indica arriba.</li></ul><div class='title'>INDICACIONES:</div>Haga clic <a href='http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=213+W+42nd+St,+New+York%E2%80%8E&sll=40.756425,-73.987298&sspn=0.005372,0.011362&ie=UTF8&hq=&hnear=213+W+42nd+St,+New+York,+10036&z=16' target='_blank'>aquí</a> para obtener un mapa del Foxwoods Theatre.<br /><br /><div class='title'>Información sobre la UBICACIÓN DE LOS ASIENTOS:</div>Platea (Orchestra): sentarse cerca es muy conveniente para ver los detalles del escenario e integrarse a la acción.<br /><br />Platea Alta (Flying Circle): para una representación de este tipo, los asientos ubicados a la mitad del teatro son perfectos para ver todo el conjunto y la parte de vuelos.<br /><br />Galería o mezzanine (Balcony): estos asientos le dan una perspectiva excelente sobre los vuelos.<br /><br /><div class='title'>RECOMENDACIONES DE EDAD:</div>Spider-Man Turn Off The Dark se recomienda para niños de 8 años y mayores.<br /><br /><div class='title'>ARTICULOS PROMOCIONALES:</div>Podrá encontrar una amplia selección de artículos promocionales de  Spider-Man Turn Off The Dark para comprar en el teatro.<br /><br /><div class='title'>BEBIDAS Y REFRIGERIOS:</div>En el Foxwoods Theatre podrá adquirir una variedad de refrigerios, cerveza, vino y licores que puede consumir dentro del auditorio durante la función.";

$(document).ready(function(){
	
	$('#footerbar div input').click(function(){
		if($(this).val() == 'Enter your email for news alerts'){
			$(this).val('');
		}
	});
	
	$('#newslettersubmit').click(function(){
		if(!$('#footerbar div input').val().match(/^([a-z]+[\w-]*\.?)+@([\w-]+\.)+[a-z]{2,4}$/i)){
			alert('Please enter your email address.');
		} else {
			$.ajax({
				type: 'POST',
				url: '/newsletter.php',
				data: 'email=' + $('#footerbar div input').val(),
				success: function(msg){
					window.open('marvel.php?e=' + $('#footerbar div input').val(),'marvel','height=400,width=400,resizeable=yes,scrollbars=yes');
					$("#newslettersubmit").remove();
					$('#footerbar div input').replaceWith('<div id="success">Thanks for signing up</div>');
				}
			});
		}
	});

	
	$('.enableHover').unbind('hover').hover(
		function() {
			$(this).siblings().not('.active').children('img').each(function() {
				$(this).attr("src",$(this).attr('src').replace(/_on/i, '_off'));
			});
			
			if($(this).hasClass('active'))
				return false;
			$(this).children('img').attr("src",$(this).children('img').attr('src').replace(/_off/i, '_on'));
		},
		function() {
			if($(this).hasClass('active'))
				return false;
			$(this).children('img').attr("src",$(this).children('img').attr('src').replace(/_on/i, '_off'));
		}
	);

	/* PERF SCHED */
	$('#perf-sched').live("click",function(){
		perfPop();
		return false;
	});
	
	$('#popBG').live("click",function(){
		closePerfPop();
	});
	
	$('#perf-schedule,#calendar').click(function(e){
		e.stopPropagation();
	});

	/*
if(rotateTimeout == 0){
		rotateTimeout = setTimeout('rotator()',5000);
	}
	
	$('#rotator #buttons img').unbind('click').click(function(){
		current = $('#rotator #buttons img').index($(this));
		clearTimeout(rotateTimeout);
		$('#rotator #buttons img').eq(currentSlide).attr({src: '/images/rotator' + (currentSlide+1) + '_off.png'});
		$('#rotator #buttons img').eq(current).attr({src: '/images/rotator' + (current+1) + '_on.png'});
		switch(current-currentSlide){
			case -2:
			case 1:
				j=1;
				break;
			case 0:
				j=0;
				break;
			case -1:
			case 2:
				j=2;
				break;
		}
		rotateSlides(j);
		currentSlide=current;
	});
*/
	
	if($('#gallery-3').length > 0){
		SlideShowPro({
			attributes: {
				id: "gallery-3",
				width: 617,
				height: 421
			},
			mobile: {
				auto: false,
				showBackButton: true
			},
			params: {
				bgcolor: "#000000",
				allowfullscreen: true,
				wmode: "opaque"
			},
			flashvars: {
				xmlFilePath: "http://video.situationinteractive.com/images.php?gallery=3",
				startup: "Open Gallery",
				galleryColumns: "2",
				galleryRows: "3",
				permalinks: "On",
				contentScale: "Proportional",
				navAppearance: "Visible",
				albumPreviewSize: "90,90"
			}
		});
	}
	
	$('#share_facebook').click(function(){
		$.ajax({
			type: 'GET',
			url: 'shorten.php?u=' + escape(window.location.href),
			success: function(msg){
				window.open('http://www.facebook.com/sharer.php?u=' + msg + '&t=Spider-Man on Broadway');
			}
		});
	});
	
	$('#share_twitter').click(function(){
		$.ajax({
			type: 'GET',
			url: 'shorten.php?u=' + escape(window.location.href),
			success: function(msg){
				window.open('http://www.twitter.com/home?status=Spider-Man+on+Broadway+' + msg);
			}
		});
	});
	
	if(navigator.userAgent.indexOf('Firefox') > 0){
		$('#allreviews').css({marginTop: '-6px'});
	}
	
	$('#reviewstars img').click(function(){
		var stars = $('#reviewstars img').index($(this));
		$('#reviewstars img').each(function(){
			if($('#reviewstars img').index($(this)) > stars){
				$(this).attr({src: '/images/reviews_star_off.png'});
			} else {
				$(this).attr({src: '/images/reviews_star_on.png'});
			}
		});
		currentStars = stars + 1;
	});
	
	$('#review').click(function(){
		if($(this).val() == 'Type your review here'){
			$(this).val('');
		}
	});
	
	$('#reviewname').click(function(){
		if($(this).val() == 'Your name'){
			$(this).val('');
		}
	});
	
	$('#submit_review').click(function(){
		var message = '';
		
		if($('#review').val() == '' || $('#review').val() == 'Type your review here'){
			message += "Please enter your review.\n";
		}
		
		if($('#reviewname').val() == '' || $('#reviewname').val() == 'Your name'){
			message += "Please enter your name.\n";
		}
		
		if(message == ''){
			$.post('/submit_review.php',{name: $('#reviewname').val(), rating: currentStars, review: $('#review').val()},function(){
				var dither = $('<div>').attr({ id: 'dither' }).css({ opacity: 0.0, height: $('#container').innerHeight() + 'px' });
				if(currentStars > 3){
					var popover = $('<div>').attr({id: 'rp'}).css({position: 'absolute', top: '100px', left: '50%', marginLeft: '-222px', width: '444px', zIndex: '20000'}).html("<img src='/images/popup_lang_x.png' id='closepop' style='cursor: pointer; position: absolute; top: -5px; left: 425px; border: 0; margin: 0;' /><img src='/images/reviews_popup.png' border='0' usemap='#reviewmap' /><map name='reviewmap'><area shape='rect' coords='96,112,340,141' href='http://theater.nytimes.com/show/23982/Spider-Man-Turn-Off-the-Dark/overview' target='_blank' /><area shape='rect' coords='157,186,260,228' href='http://www.yelp.com/biz/spider-man-turn-off-the-dark-new-york' target='_blank' /></map>");
				} else {
					var popover = $('<div>').attr({id: 'rp'}).css({position: 'absolute', top: '100px', left: '50%', marginLeft: '-222px', width: '444px', zIndex: '20000'}).html("<img src='/images/popup_lang_x.png' id='closepop' style='cursor: pointer; position: absolute; top: -5px; left: 425px; border: 0; margin: 0;' /><div style='background-image: url(/images/popup_return.png); padding-top: 85px; width: 443px; height: 194px; text-align: center; font-family: Futura, Helvetica, sans-serif;'><a href='' style='color: #000;'>Click here to read more fan reviews.</a></div>");
				}
				$('body').append(popover).append(dither);
				$('#dither').fadeTo(400, 0.6);
				$('#rp').fadeTo(400, 1.0);
				$("#closepop").click(function(){
					$('#dither').fadeOut(400);
					$('#rp').fadeOut(400, function(){
						$("#dither").remove();
						$("#rp").remove();
					});
				});
				$("#dither").click(function(){
					$('#dither').fadeOut(400);
					$('#rp').fadeOut(400, function(){
						$("#dither").remove();
						$("#rp").remove();
					});
				});
			});
		} else {
			alert("The following errors have occured:\n\n" + message);
		}
	});
	
	$('.cast').unbind('click').click(function(){
		var dither = $('<div>').attr({ id: 'dither' }).css({ opacity: 0.0, height: $('#container').innerHeight() + 'px' });
		var popover = $('<div>').attr({id: 'popover'}).css({opacity: 0.0, top: ($(window).scrollTop()+150) + 'px'}).html('<img src="http://www.gokashproductions.com/images/cast_popover_top.png" /><div id="castpop"><img src="http://www.gokashproductions.com/images/cast_popover_close.png" id="closepop" />' + $('#' + $(this).attr('id') + 'full').html() + '</div><img src="http://www.gokashproductions.com/images/cast_popover_bottom.png" />');
		$('body').append(popover).append(dither);
		$('#dither').fadeTo(400, 0.6);
		$('#popover').fadeTo(400, 1.0);
		$("#closepop").click(function(){
			$('#dither').fadeOut(400);
			$('#popover').fadeOut(400, function(){
				$("#dither").remove();
				$("#popover").remove();
			});
		});
		$("#dither").click(function(){
			$('#dither').fadeOut(400);
			$('#popover').fadeOut(400, function(){
				$("#dither").remove();
				$("#popover").remove();
			});
		});
	});
	
	$('#flags img').click(function(){
		var num = $('#flags img').index($(this));
		var dither = $('<div>').attr({ id: 'dither' }).css({ opacity: 0.0, height: ($('#container').innerHeight()+200) + 'px' });
		var popover = $('<div>').attr({id: 'poplang'}).html("<img src='/images/popup_lang_x.png' id='closepop' /><img src='/images/popup_lang_top.png' /><div id='poplangin'><img src='" + $(this).attr('src') + "' /><br />" + langs[num] + "</div><img src='/images/popup_lang_bottom.png' />");
		$('body').append(popover).append(dither);
		$('#dither').fadeTo(400, 0.6);
		$('#popover').fadeTo(400, 1.0);
		$("#closepop").click(function(){
			$('#dither').fadeOut(400);
			$('#poplang').fadeOut(400, function(){
				$("#dither").remove();
				$("#poplang").remove();
			});
		});
		$("#dither").click(function(){
			$('#dither').fadeOut(400);
			$('#poplang').fadeOut(400, function(){
				$("#dither").remove();
				$("#poplang").remove();
			});
		});
	});
	
	if(aboutPlayer != 0){
		aboutPlayer.toggleDisplayMode('Manual');
	}
	$('#moreStoriesBtn').unbind('click').click(function(){
		$('#moreStoriesBtn img').attr({src: '/images/loadbar.gif'});
		var id = $('.newsInner .newsRow').last().attr('id').substr(2);
		$.ajax({
			type: 'GET',
			url: '/news/' + id,
			success: function(msg){
				$('#moreStoriesBtn').remove();
				$('.newsInner').last().append(msg);
				pageSpecific(4);
			}
		});
	});
	
	$('#perf-sched').live("click",function(){
		perfPop();
		return false;
	});
	
	$('#popBG').live("click",function(){
		closePerfPop();
	});
	
	$('#perf-schedule,#calendar').click(function(e){
		e.stopPropagation();
	});
	
	jQuery.each(jQuery.browser, function(i) {
		if($.browser.msie){
			if($('#aboutcontent').length > 0 && $('body').attr('id') != 'about-page'){
				$('#container').css({width: '1600px', marginLeft: '-350px'});
			}
		}
	});
});

function scrollToPageNumber(p,path){
	$(window).unbind('scroll');
	if(navigator.platform == 'iPad' || navigator.userAgent.toLowerCase().indexOf('ipad') > 0){
		currentPage = p
		myScroll.scrollToElement('#' + pageList[p].substr(1) + 'content',5000);
	} else if(navigator.platform == 'iPhone' || navigator.platform == 'iPod' || navigator.userAgent.toLowerCase().indexOf('android') > 0 || navigator.userAgent.toLowerCase().indexOf('iphone') > 0){
		window.location.href = pageList[p];
	} else {
		var height = 0;
		currentPage = p;
		h=0;
		for(i=0;i<currentPage;i++){
			h += $('#' + pageList[i].substr(1) + 'content').innerHeight();
		}
		$('html,body').animate({scrollTop: h},2500,function(){
			if(path != null){
				$.pathchange.changeTo(path);
			} else {
				$.pathchange.changeTo('/#' + pageList[currentPage].substr(1));
			}
			setTimeout('pageSpecific(' + currentPage +')',2500);
		});
		//window.scrollTo(0,h);
	}
	
	track(currentPage,'click');
	bindEvents();
	return false;
}

function bindEvents(){
	$(window).unbind('scroll').scroll(function(){
		var top = $(window).scrollTop();
		var height = window.innerHeight ? window.innerHeight - $('#nav').innerHeight() : document.documentElement.clientHeight - $('#nav').innerHeight();
		h = 0;
		for(i = 0; i<pageList.length;i++){
			h += $('#' + pageList[i].substr(1) + 'content').innerHeight();
			if(top + height/2 < h){
				if(currentPage != i){
					currentPage = i;
					$.pathchange.changeTo('/#' + pageList[currentPage].substr(1));
					//unBindJS();
					track(currentPage,'scroll');
					pageSpecific(currentPage);
				}
				i=pageList.length;
			}
		}
	});
	
	$('a.external').unbind('click').click(function(){
		if($(this).attr('target') == '_blank'){
			window.open($(this).attr('href'));
		} else {
			window.location.href = $(this).attr('href');
		}
		return false;
	});
	
	if(window.innerWidth < 1600){
		$('img.header').css({width: (window.innerWidth + 70) + 'px'});
	}
}

function unBindJS(){
	clearTimeout(rotateTimeout);
	if(aboutPlayer!=0){
		aboutPlayer.pauseMedia();
	}
}

function pageSpecific(p){
	if(isNumeric(p)){
		switch(p){
			case 0:
				/*
if(rotateTimeout == 0){
					rotateTimeout = setTimeout('rotator()',5000);
				}
				

				$('#rotator #buttons img').unbind('click').click(function(){
					current = $('#rotator #buttons img').index($(this));
					clearTimeout(rotateTimeout);
					$('#rotator #buttons img').eq(currentSlide).attr({src: '/images/rotator' + (currentSlide+1) + '_off.png'});
					$('#rotator #buttons img').eq(current).attr({src: '/images/rotator' + (current+1) + '_on.png'});
					switch(current-currentSlide){
						case -2:
						case 1:
							j=1;
							break;
						case 0:
							j=0;
							break;
						case -1:
						case 2:
							j=2;
							break;
					}
					.rotateSlides(j);
					currentSlide=current;
				});

*/
				break;
			case 1:
					/*
SlideShowPro({
						attributes: {
							id: "album-5",
							width: 617,
							height: 421
						},
						mobile: {
							auto: false,
							showBackButton: true
						},
						params: {
							bgcolor: "#000000",
							allowfullscreen: true,
							wmode: "opaque"
						},
						flashvars: {
							xmlFilePath: "http://video.situationinteractive.com/images.php?album=5",
							paramXMLPath: "http://video.situationinteractive.com/m/params/spider.xml",
							navAppearance: "Visible",
							contentScale: "Proportional",
							videoAutoStart: "Off",
							permalinks: "On",
							navButtonsAppearance: "Hide Gallery",
							useExternalInterface: "true"
						}
					});
*/
						SlideShowPro({
							attributes: {
								id: "gallery-2",
								width: 617,
								height: 421
							},
							mobile: {
								auto: false,
								showBackButton: true
							},
							params: {
								bgcolor: "#000000",
								allowfullscreen: true,
								wmode: "opaque"
							},
							flashvars: {
								xmlFilePath: "http://video.situationinteractive.com/images.php?gallery=2",
								startup: "Open Gallery",
								galleryColumns: "2",
								galleryRows: "2",
								permalinks: "On",
								contentScale: "Proportional",
								navAppearance: "Visible",
								albumPreviewSize: "100,100"
							}
						});
				
				$('#share_facebook').click(function(){
					$.ajax({
						type: 'GET',
						url: 'shorten.php?u=' + escape(window.location.href),
						success: function(msg){
							window.open('http://www.facebook.com/sharer.php?u=' + msg + '&t=Spider-Man on Broadway');
						}
					});
				});
				
				$('#share_twitter').click(function(){
					$.ajax({
						type: 'GET',
						url: 'shorten.php?u=' + escape(window.location.href),
						success: function(msg){
							window.open('http://www.twitter.com/home?status=Spider-Man+on+Broadway+' + msg);
						}
					});
				});
				break;
			case 2:
				break;
			case 3:
				$('.cast').unbind('click').click(function(){
					var dither = $('<div>').attr({ id: 'dither' }).css({ opacity: 0.0, height: $('#container').innerHeight() + 'px' });
					var popover = $('<div>').attr({id: 'popover'}).css({opacity: 0.0, top: ($(window).scrollTop()+200) + 'px'}).html('<img src="/images/cast_popover_top.png" /><div id="castpop"><img src="/images/cast_popover_close.png" id="closepop" />' + $('#' + $(this).attr('id') + 'full').html() + '</div><img src="/images/cast_popover_bottom.png" />');
					$('body').append(popover).append(dither);
					$('#dither').fadeTo(400, 0.6);
					$('#popover').fadeTo(400, 1.0);
					$("#closepop").click(function(){
						$('#dither').fadeOut(400);
						$('#popover').fadeOut(400, function(){
							$("#dither").remove();
							$("#popover").remove();
						});
					});
					$("#dither").click(function(){
						$('#dither').fadeOut(40);
						$('#popover').fadeOut(400, function(){
							$("#dither").remove();
							$("#popover").remove();
						});
					});
				});
				break;
			case 4:
				if(aboutPlayer != 0){
					aboutPlayer.toggleDisplayMode('Manual');
				}
				$('#moreStoriesBtn').unbind('click').click(function(){
					$('#moreStoriesBtn img').attr({src: '/images/loadbar.gif'});
					var id = $('.newsInner .newsRow').last().attr('id').substr(2);
					$.ajax({
						type: 'GET',
						url: '/news/' + id,
						success: function(msg){
							$('#moreStoriesBtn').remove();
							$('.newsInner').last().append(msg);
							pageSpecific(4);
						}
					});
				});
				break;
		}
	} else {
	
	}
}

function track(p,type){
	var pageTracker = _gat._getTracker("UA-7616935-1");
	if(isNumeric(p)){
		pageTracker._trackEvent(type, pageList[p]);
	} else {
		pageTracker._trackEvent(type, p);
	}
}

function isNumeric(s){
	var validChars = "0123456789.";
	var isNumber=true;
	var char;
	
	
	for (i = 0; i < s.length && isNumber == true; i++) { 
		char = s.charAt(i); 
		if (validChars.indexOf(char) == -1){
			isNumber = false;
		}
	}
	return isNumber;
}

/* NEW ROTATOR */
var locked = false;
var curPos = 0;
var next;
$('.slide:eq(0)').addClass('inview');

function advanceSlide(next){
	if(!locked){
		locked=true;	
		
		if(next == 'auto'){
			next = ++curPos;
			
			if(next > 2){
				next = 0;
				curPos = 0;
			}
			$('#rotator #buttons img').each(function(){
				$(this).attr({src: $(this).attr('src').replace("_on","_off")}).removeClass('activeBtn');
			});
	
			$('#rotator #buttons img:eq('+next+')').attr({src: $('#rotator #buttons img:eq('+next+')').attr('src').replace("_off","_on")}).addClass('activeBtn');
				
		}else{
			curPos = next;
		}
		$('.inview').animate({left:"-964px"},{queue:false,duration:500,complete:function(){$(this).removeClass('inview').css({left:"964px"})}});
			$('.slide:eq('+next+')').animate({left:0},{queue:false,duration:500,complete:function(){
				$(this).addClass('inview');
				locked=false;
				rotateT = setTimeout(function(){advanceSlide('auto')},rotateTimeout);
			}
		});
	}
}

rotateT = setTimeout(function(){advanceSlide('auto')},rotateTimeout);

$('#rotator #buttons img').unbind("click").click(function(){
	if(!$(this).hasClass('activeBtn') && !locked){
		clearTimeout(rotateT);
		$('#rotator #buttons img').each(function(){
			$(this).attr({src: $(this).attr('src').replace("_on","_off")}).removeClass('activeBtn');
		});
		
		$(this).attr({src: $(this).attr('src').replace("_off","_on")}).addClass('activeBtn');
		
		var n = $('#rotator #buttons img').index($(this));
		advanceSlide(n);
	}
});

/* END NEW ROTATOR */

/*
function rotator(){
	$('#rotator #slides').append('<div class="slide">' + $('#rotator #slides .slide').eq(0).html() + '</div>');
	$('#rotator #slides .slide').eq(0).animate({width: '0px', marginRight: '0px'},1000,function(){
		$('#rotator #buttons img').eq(currentSlide).attr({src: '/images/rotator' + (currentSlide+1) + '_off.png'});
		currentSlide=(currentSlide+1)%3;
		$('#rotator #buttons img').eq(currentSlide).attr({src: '/images/rotator' + (currentSlide+1) + '_on.png'});
		$('#rotator #slides .slide').eq(0).remove();
		rotateTimeout = setTimeout('rotator()',5000);
	});
}
*/

function changeHeight() {
	var headerH = document.getElementById('nav').offsetHeight;
	var footerH = document.getElementById('footer').offsetHeight;
	var wrapperH = window.innerHeight - headerH - footerH;
	document.getElementById('container').style.height = wrapperH + 'px';
}

function checkPageJS(yPos){
	var top = -yPos;
	var height = window.innerHeight - $('#nav').innerHeight();
	h = 0;
	for(i = 0; i<pageList.length;i++){
		h += $('#' + pageList[i].substr(1) + 'content').innerHeight();
		if(top + height/2 < h){
			if(currentPage != i){
				currentPage = i;
				$.pathchange.changeTo('/#' + pageList[currentPage].substr(1));
				//unBindJS();
				//track(currentPage,'scroll');
				pageSpecific(i);
			}
			i=pageList.length;
		}
	}
}

function respondToUrl(){
	if(moving == 0){
		moving = 1;
		var newPath = '/' + location.hash.substr(1);
		for(i=0;i<pageList.length;i++){
			if(pageList[i] == newPath){
				//scrollToPageNumber(i);
			}
		}
		moving = 0;
	}
}

function slideChangePage(url){
	$.pathchange.changeTo(url);
	var path = '/' + url.substr(1);
	for(i=0;i<pageList.length;i++){
		if(pageList[i] == path){
			scrollToPageNumber(i);
		}
	}
	return false;
}

function shortenUrl(url){
	$.ajax({
		type: 'GET',
		url: 'shorten.php?u=' + escape(url),
		success: function(msg){
			return msg;
		}
	});
}

function onSlideShowProReady(swf){
	if(swf){
		aboutPlayer = document.getElementById(swf);
	}
}

function checkLoad(){
	var done = true;
	$('#homecontent img').each(function(){
		if(!this.complete){
			done = false;
		}
	});
	if(done){
		$('#spin').remove();
		$('#dither').remove();
	} else {
		setTimeout('checkLoad()',500);
	}
}

function rotateSlides(j){
	if(j>0){
		$('#rotator #slides').append('<div class="slide">' + $('#rotator #slides .slide').eq(0).html() + '</div>');
		$('#rotator #slides .slide').eq(0).animate({width: '0px', marginRight: '0px'},1000,function(){
			$('#rotator #slides .slide').eq(0).remove();
			rotateSlides(j-1);
		});
	}
}

/* functions for popup performance calendar */

function bindArrows(){
	$('#nextmonth').unbind('click').click(function(){
		function getTable(restart){
			$.ajax({
				type: "GET",
				url: '/get_calendar/',
				data: (restart ? '' : 'date='+nextdate),
				success: function(msg){
					//if(msg.search('fail')<0){
						$('#perf-schedule').html(msg);
						//$('#prevmonth').show();
						bindArrows();
					//}else{
						//getTable(true);
					//}
				}
			});
		}
		getTable(false);
		return false;
	});
	
	$('#prevmonth').unbind('click').click(function(){
		$.ajax({
			type: "GET",
			url: '/get_calendar/',
			data: 'date=' + $('#prevdate').text(),
			success: function(msg){
				//if(msg.search('fail')<0){
					$('#perf-schedule').html(msg);
					//$('#nextmonth').show();
					bindArrows();
				//}else{
					//$('#prevmonth').hide();
				//}
			}
		});
		
		return false;
	});
	
	$('#close_calendar').click(function(){
		closePerfPop();
	});
}

function perfPop() {
//alert('open sched');
    $("#popBG").css({
        height: ($(window).height()>$(document).height() ? $(window).height() : $(document).height() ),
        display: 'block',
        opacity: 0.0
    }).animate( { opacity: 0.7 }, 200 );
    
    $.ajax({
		type: 'GET',
		url: '/get_calendar/',
		success: function(msg){
			$('#perf-schedule').html(msg);
			var h=$(window).height();
		    var w=$(window).width();
		    var popHeight=$('#calendar').height();
		    var topHeight=(h-calendarHeight)/2;
		    var leftWidth=(w-712)/2;
		    $("#perf-schedule").css({
		        display: 'block',
		        top:topHeight,
		        left:leftWidth
		    });
			bindArrows();
		}
	});
    
    $(window).unbind("resize").resize(function(){
    	var h=$(window).height();
    	var w=$(window).width();
   		var popHeight=$('#calendar').height();
   		var topHeight=(h-calendarHeight)/2;
    	var leftWidth=(w-712)/2;
    	$("#perf-schedule").stop();
    	$("#perf-schedule").animate({"left":leftWidth,"top":topHeight},500);
    });
    
    return false;
}

function closePerfPop() {
    $("#popBG").css({"display":"none","color":"#000"});
    $("#perf-schedule").css("display","none");
    return false;
}