/*
	Global Javascript for:
		Museum of Science and Industry
	
	Authors:
	
		Aaron Clinger (aaron@odopod.com)
	
	Updated:
	
		02/28/2008
	
*/

window.addEvent('domready', function () {
	
	// Get wrapper and set it to each page
	var cssCookie = readCookie("csswrapper");
	
	if(cssCookie==null) {	
		// If no wrapper is found read available ones
		if (avWrappers) {			
			// Randomly select one and assign it
			var wrappersArray =  avWrappers.split('|');			
			var randomWrapper = wrappersArray[Math.floor(Math.random()*wrappersArray.length)];
			//var curWrapperPath = $('wrapper').getProperty('href');
			//var randomWrapperPath = curWrapperPath.replace(/\w*\.css/, randomWrapper);
			var randomWrapperPath = 'fileadmin/templates/css/general_wrappers/'+randomWrapper;
			createCookie('csswrapper', randomWrapperPath);
			if($('wrapper')) {
				$('wrapper').setProperty('href', randomWrapperPath);
			}
		} 
	} else {
		if($('wrapper')) {
			$('wrapper').setProperty('href', cssCookie);
		}
	}
	
	// Add Print Links
	if ($('pageActions')) {
		var printLi = new Element('li');
		printLi.addClass('print');
		printLi.setProperty('id', 'printLink');
		
		$('pageActions').adopt(printLi);
		
		addPrintLink('printLink', 'Print Page');
	}
	if ($('printPage')) {
		var printPageDiv = new Element('div');
		printPageDiv.setProperty('id', 'printPageLink');
		$('printPage').adopt(printPageDiv);
		
		addPrintLink('printPageLink', 'Print Page');
	}

	// Write Flash Embeds
	writeRequestedFlashEmbeds();
	
	// Make Submit Buttons Links
	$ES('input.plain').each(function (input) {
		var subLink = new Element('a');
		subLink.setProperty('href', '#');
		subLink.setText(input.value);
		subLink.addEvent('click', function (e) {
			e = new Event(e);
			// CML code - start. check if form validation is required - affects only forms
			if ($E('.validate')) {
				submitValidParentForm(this);
			} else {// CML code - end
				submitParentForm(this);
			}
			e.stop();
		});
		input.replaceWith(subLink);
	});
	
	// Add open in new window functionality
	$E('html').getElements('a[rel=external]').each(function(a) {
		a.addEvent('click', function(e) {
			e = new Event(e);
			window.open(a.href);
			e.stop();
		})
	})
		
	// Removes Guide Text in Inputs
	$ES('.guide').each(function (input) {
		if (input.getTag() == 'input' || input.getTag() == 'textarea') {
			if (input.value != '') {
				input.defaultText = input.value;
				input.addEvent('click', function () {
					if (this.value == this.defaultText) {
						this.value = '';
					}
				});
				input.addEvent('blur', function () {
					if (this.value == '' && this.defaultText) {
						this.value = this.defaultText;
					}
				});
			}
		}
	});
	
	$ES('.guidetext').each(function (input) {
		if (input.getTag() == 'input' || input.getTag() == 'textarea') {
			if (input.title != '') {
				input.defaultText = input.title;
				if (input.value == "") {
					input.value = input.defaultText;
				}				
				input.addEvent('click', function () {
					if (this.value == this.defaultText) {
						this.value = '';
					}
				});
				input.addEvent('blur', function () {
					if (this.value == '' && this.defaultText) {
						this.value = this.defaultText;
					}
				});
			}
		}
	});	
	
	// Arrow Links
	$ES('a.laquoLink').each(function (link) {
		createArrowLink(link, false);
	});
	$ES('a.raquoLink').each(function (link) {
		createArrowLink(link, true);
	});
	
	// Replace Horz Rules
	$$('hr').each(function (hr) {
		var span = new Element('span');
		span.addClass('hr');
		span.injectBefore(hr);
		span.adopt(hr);
	});
	
	// Add Separators
	addSeparatorsToUl($('legal'), '|');
	addSeparatorsToUl($('sectionNav'), '|');
	addSeparatorsToUl($E('ul.socialNetwork'), '|');
	addSeparatorsToUl($E('#howToFooter ul'), '|');
	addSeparatorsToUl($E('dl.pageNumbers dd ul'), '|');
	addSeparatorsToUl($E('#calendarControls ul'), '|');
	addSeparatorsToUl($E('.pagination ul.pageTurn'), '|');
	addSeparatorsToUl($E('.details', 'mainExhibitPromo'), '|');
	$ES('.seeShow ul').each(function (ul) {
		addSeparatorsToUl(ul, '|');
	});
	$ES('ul.separatorList').each(function (ul) {
		addSeparatorsToUl(ul, '|');
	});
		
	// Tab Module (Happing Now/Coming Soon)
	$ES('dl.eventsScheduleModule').each(function (tabModule) {
		var isFirstTab = true;
		var firstTab;
		
		tabModule.addClass('eventsScheduleModuleJS');
		
		tabModule.getChildren().each(function (tab) {
			if (tab.getTag() == 'dt') {
				tab.addEvent('click', function (e) {
					var activeContent = false;
					
					this.getParent().getChildren().each(function (child) {
						switch (child.getTag()) {
							case 'dt' :
								if (child == tab) {
									activeContent = true;
									child.removeClass('inactive');
									child.removeClass('hand');
								} else {
									child.addClass('inactive');
									child.addClass('hand');
								}
								break;
							case 'dd' :
								if (activeContent) {
									child.removeClass('hide');
									activeContent = false;
								} else {
									child.addClass('hide');
								}
								break;
						}
					});
				});
				
				if (isFirstTab) {
					firstTab   = tab;
					isFirstTab = false;
					tab.addClass('first');
				} else {
					tab.addClass('second');

				}
			}
		});
		
		firstTab.fireEvent('click');
	});
	
	// Calendar Select
	if ($('calendarModule')) {
		$E('form input', 'calendarModule').addClass('hide');
		$E('form select', 'calendarModule').addEvent('change', function (e) {
			location.href = this.value;
		});
	}
	
	// Adds Check/Uncheck controls to e-newsletter
	if ($('checkUncheckControls')) {
		var checkUl   = new Element('ul');
		var checkLi   = new Element('li');
		var uncheckLi = new Element('li');
		var checkA    = new Element('a');
		var uncheckA  = new Element('a');
		
		checkA.setProperty('href', '#');
		uncheckA.setProperty('href', '#');
		checkA.setText('check all');
		uncheckA.setText('uncheck all');
		
		checkA.addEvent('click', function (e) {
			e = new Event(e);
			checkAllInForm(this, true);
			e.stop();
		});
		uncheckA.addEvent('click', function (e) {
			e = new Event(e);
			checkAllInForm(this, false);
			e.stop();
		});
		
		checkLi.adopt(checkA);
		uncheckLi.adopt(uncheckA);
		checkUl.adopt(checkLi);
		checkUl.adopt(uncheckLi);
		$('checkUncheckControls').adopt(checkUl);
		
		addSeparatorsToUl(checkUl, '|');
	}
	
	// Logo Rollover
	var logo = $E('h1 span a');
	var home = $E('ul li.home a', 'nav');
	if (logo) {
		logo.addEvent('mouseover', function () {
			home.addClass('hover');
		});
		logo.addEvent('mouseout', function () {
			home.removeClass('hover');
		});
	}
	
	// Add last class to last li in ul#mainsubnav
	if ($E('ul#mainSubNav', 'main')) {
		$E('ul#mainSubNav', 'main').getLast().addClass('last');
	}
	
	// Updates How-To Controls
	if ($('howToControls')) {
		var isAfter = false;
		$ES('ol li', 'howToControls').each(function (li) {
			if (isAfter) {
				li.getFirst().addClass('jsAfterActive');
				isAfter = false;
			} else if (li.getFirst().hasClass('active')) {
				isAfter = true;
			}
		});
		
		var howToTips = new Tips($ES('ol li a', 'howToControls'), {offsets:{x:0, y:22}});
	}
	
	// CML addition - set HTTP_REFERER value to hidden field of send to a friend form
	if ($('suggest_page')) {
		$('suggest_page').value = readCookie('HTTP_REFERER');
	}
	
	if ($('rootLineWrapper')) {}
	else {
		writeLogo();
	}
	
});

function writeLogo() {
	// New Logo
	var msiLogoDiv = new Element('h1', { id : 'msiLogo' });
	msiLogoDiv.setHTML('<h1><span class="msiLogoImage"><a accesskey="h" href="../../.." title="Return to the home page">Museum of Science and Industry</a></span><div id="msiLogoHide" class="hide"></div>');
	$('body').getElement('h1').replaceWith(msiLogoDiv);
	
	var logoSWF = new SWFObject("http://www.msichicago.org/fileadmin/templates/swf/msi_header.swf", "msiLogo", "600", "130", "9.0.0", "#DFD9D2");
	logoSWF.addVariable('num_days', '10');
	logoSWF.addParam("wmode", "transparent");
	logoSWF.addParam("allowScriptAccess", "always");
	logoSWF.addParam("allowFullScreen", "true");
	logoSWF.write("msiLogo");
}

var requestedFlashEmbeds = new Array();
function requestFlashEmbed(swfObj, kind) {
	requestedFlashEmbeds.push({obj:swfObj, type:kind})
}

function writeRequestedFlashEmbeds() {
	requestedFlashEmbeds.each(function (request) {
		var embed = request.obj;
		embed.addParam('quality', 'high');
		embed.addParam('menu', 'false');
		embed.addParam('salign', 'tl');
		
		switch (request.type.toLowerCase()) {
			case 'altertheoutcome':
				embed.write('alterTheOutcome');
				break;
			case 'promo' :
				embed.addVariable('jsCallbackMethod', 'updateFeatureInformation');
				embed.write('mainExhibitPromoImage');
				break;
			case 'polltrivia' :
				formatPollTrivia(embed.write('museumInfoContent'));
				break;
			case 'planyourvisit' :
				embed.addVariable('selectedItem', getPlanVisitorType());
				embed.addVariable('jsCallbackMethod', 'updatePlanYourVisitValue');
				formatPlanYourVisit(embed.write('planYourVisitHeader'));
				break;
			case 'timeline' :
				embed.addVariable('jsCallbackMethod', 'updateTimelineCaption');
				formatTimeline(embed.write('flashTimeline'));
				break;
			case 'timelinelarge' :
				$E('#focusedContent').addClass('timelineLarge');
				
				embed.addVariable('jsCallbackMethod', 'updateTimelineCaption');
				formatTimeline(embed.write('flashTimelineLarge'));
				break;
			case 'slideshow' :
				embed.addVariable('jsCallbackMethod', 'updateSlideImageCaption');
				formatSlideshow(embed.write('flashSlideshow'));
				break;
			case 'slideshowlarge' :
				$E('#slideshowContent').addClass('large');
				
				embed.addVariable('jsCallbackMethod', 'updateSlideImageCaption');
				formatSlideshow(embed.write('flashSlideshowLarge'));
				break;
			case 'map' :
				$E('li#printLink', 'pageActions').addClass('hide');
			
				embed.write('map');
				break;
			case 'videolarge' :
				embed.addVariable('isEmbeddedOnMSISite', 'true');
				embed.write('flashVideoPlayerLarge');
				break;
			case 'videomedium' :
				embed.addVariable('isEmbeddedOnMSISite', 'true');
				embed.write('flashVideoPlayerMedium');
				break;
			case 'flashswf' :
				embed.write('flashSWF');
				break;
		}
	});
}

function updateFeatureInformation(name, desc, dateRange, location, detailsLinkTitle, detailsLinkUrl, link1Title, link1Url, link2Title, link2Url) {
	var detailsLink = $E('ul.details li a.raquoLink', 'focusedContent');
	var details     = $ES('ul.details li', 'focusedContent');
	var links       = $ES('ul', 'focusedContent')[1];
	var li;
	var a;
	
	$('mainExhibitPromoImage').addClass('jsHasFlash');
	
	h3a = new Element('a');
	h3a.setProperty('href', link1Url);
	h3a.setText(name);
	
	$E('h3').setText('');
	$E('h3').appendChild(h3a);

	$E('p', 'focusedContent').setText(desc);
	
	if (dateRange != "null") {
		details[0].setText(dateRange);
		details[0].removeClass('hide');
		details[1].removeClass('hide');
	} else {
		details[0].addClass('hide');
		details[1].addClass('hide');
	}
	details[2].setText(location);
	detailsLink.setText(detailsLinkTitle);
	detailsLink.setProperty('href', detailsLinkUrl);
	createArrowLink($E('ul.details li a.raquoLink', 'focusedContent'), true);
	
	links.empty();
	
	if (link1Title) {
		li = new Element('li');
		a  = new Element('a');
		a.setText(link1Title);
		a.setProperty('href', link1Url);
		createArrowLink(a, true);
		li.appendChild(a);
		links.appendChild(li);
	}
	if (link2Title) {
		li = new Element('li');
		a  = new Element('a');
		a.setText(link2Title);
		a.setProperty('href', link2Url);
		createArrowLink(a, true);
		li.appendChild(a);
		links.appendChild(li);
	}
}

function formatSlideshow(hasFlash) {
	$E('dt', 'slideshowContent').addClass('hide');
	
	$ES('dd ol li', 'slideshowContent').each(function (slide) {

		if(slide.getFirst().getText().length > 1) {
			var p   = new Element('p');
			var em  = new Element('em');
			var img = new Element('img');

			em.setText(slide.getFirst().getText());
			img.setProperty('src', slide.getFirst().getProperty('href'));
			img.setProperty('alt', slide.getFirst().getText());
			p.appendChild(em);
			p.addClass('caption');

			slide.empty();

			if (hasFlash) {
				slide.addClass('hide');
				slide.addClass('jsHasFlash');
			} else {
				slide.appendChild(img);
			}

			slide.appendChild(new Element('hr'));
			slide.appendChild(p);
			slide.appendChild(new Element('hr'));
			
		} else {
			$ES('dd ol li a', 'slideshowContent').addClass('hide');
			slide.appendChild(new Element('hr'));
			
		}
	});
	
	if (hasFlash) {
		if ($('flashSlideshow')) {
			$('flashSlideshow').addClass('jsHasFlash');
		} else if ($('flashSlideshowLarge')) {
			$('flashSlideshowLarge').addClass('jsHasFlash');

		}
	} else {
		$E('dd ol li img', 'slideshowContent').addClass('first');
	}
}

function formatTimeline(hasFlash) {
	if (hasFlash) {

		$('focusedContent').addClass('jsHasFlash');
		$('timeline').addClass('jsHasFlash');
		
		$ES('dd.timelineContent', 'timeline').each(function (dd) {
			dd.addClass('hide');
		});
		$E('dd.timelineContent', 'timeline').removeClass('hide');
	} else {
		$ES('div.imageLink', 'timeline').each(function (linkWrapper) {
			var img = new Element('img');
			img.setProperty('src', linkWrapper.getFirst().getProperty('href'));
			linkWrapper.replaceWith(img);
		});
	}
}

function updateTimelineCaption(index) {
	var i = -1;
	$ES('dd.timelineContent', 'timeline').each(function (dd) {
		if (++i == index) {
			dd.removeClass('hide');
		} else {
			dd.addClass('hide');
		}
	});
}

var planVisitFormFade;
function formatPlanYourVisit(hasFlash) {
	if (hasFlash) {
		$('who').addClass('hide');
		$('visitPlanner').addClass('hide');
		$E('p', 'mainHeader').addClass('hide');
		$E('.headSep', 'mainHeader').addClass('hide');
		$('planYourVisitHeader').addClass('jsHasFlash');
		planVisitFormFade = new Fx.Style('visitPlanner', 'opacity', {duration: 900});
	}
}

function getPlanVisitorType() {
	var i        = -1;
	var selected = -1;
	$ES('dl dt input', 'who').each(function (radio) {
		i++;
		if (radio.getProperty('checked')) {
			selected = i;
		}
	});
	
	return selected;
}

function updatePlanYourVisitValue(index, isCompact) {
	$('visitPlanner').removeClass('hide');
	$('planYourVisitHeader').addClass('jsFlashCompressed');
	$ES('dl dt input', 'who')[index].setProperty('checked', true);
	
	if (isCompact == false) {
		planVisitFormFade.set(0);
		planVisitFormFade.start(0, 1);
	}
}

function formatPollTrivia(hasFlash) {
	if (hasFlash) {
		$('museumInfo').setProperty('id', 'jsPollTrivia');
	}
}

function createArrowLink(el, right) {
	if (right) {
		el.setHTML(el.firstChild.nodeValue + ' <span class="raquo">&raquo;</span>');
	} else {
		el.setHTML('<span class="laquo">&laquo;</span> ' + el.firstChild.nodeValue);
	}
}

function updateSlideImageCaption(index) {
	var i = -1;
	$ES('dd ol li', 'slideshowContent').each(function (caption) {
		if (++i == index) {
			caption.removeClass('hide');
		} else {
			caption.addClass('hide');
		}
	});
}

function addSeparatorsToUl(ulEl, sep) {
	if (!ulEl)
		return;
	
	var first = true;
	
	$ES('li', ulEl).each(function (li) {
		if (first) {
			first = false;
			return;
		}
		if (!li.hasClass('printOnly')) {
			var pipe = new Element('li');
			pipe.addClass('separatorLi');
			pipe.setText(sep);
			pipe.injectBefore(li);
		}
	});
}

function checkAllInForm(formChild, check) {
	var formEl = formChild.getParent();
	while (formEl.getTag() != 'form') {
		formEl = formEl.getParent();
	}
	
	$ES('input', formEl).each(function (input) {
		if (input.getProperty('type').toLowerCase() == 'checkbox') {
			if (check) {
				input.setProperty('checked', 'checked');
			} else {
				input.removeProperty('checked');
			}
		}
	});
}

function addPrintLink(el, text) {
	var link = new Element('a');
	link.setProperty('href', '#');
	link.setText(text);
	link.addEvent('click', function (e) {
		e = new Event(e);
		window.print();
		e.stop();
	});
	
	$(el).appendChild(link);
}

function submitParentForm(el) {
	var parent = el.getParent();
	while (parent.getTag() != 'form') {
		parent = parent.getParent();
	}
	parent.submit();
}

// CML Code - start same as submitParentForm just added validation before submit - affects only forms
function submitValidParentForm(el) {
	var parent = el.getParent();
	while (parent.getTag() != 'form') {
		parent = parent.getParent();
	}
	if(formValid.validate()){
		parent.submit();
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// Get the page url and store it in a session cookie. First make sure that the page is not send-to-a-friend or home page
var sPath = window.location.pathname;
if (sPath.match('index.php')==null && sPath.match('send-to-a-friend')==null) {

	//Store HTTP_REFERER for the entire sesion
	createCookie('HTTP_REFERER','http://'+window.location.hostname+sPath);
} 


// CML Code - end