

/***************************************************************************************************
Namespace
***************************************************************************************************/

if(window.sita == undefined) {
	sita = new Object();
}


/***************************************************************************************************
Webcams
***************************************************************************************************/
sita.webcams = function() {

	var CAMERA_REFRESH_INTERVAL = 3000; // milliseconds
	
	// Onload handler
	var camImageOnload = function() {
		var img = jq(this);
		cacheDefeat = (new Date().getTime()*Math.random() + "").replace('.','')
		var closure = function() {
		
			img.attr('src', img.attr('src').replace(/\d+$/, cacheDefeat))
			
			
			/*
			// Test while throttling with a sequence of three images
			img.attr('src', img.attr('src').replace(/cam(\d)\.jpg\?c=([\d\.]+)/, function(str, p1){
				var i = p1 === "3" ? "1" : (parseInt(p1)+1)+"";
				return "cam" + i + ".jpg?c=" + Math.random();
			}))
			//console.log(img.attr('src'))
			*/
		}
		setTimeout(closure, CAMERA_REFRESH_INTERVAL);
	};
	
	// For each webcam image
	jq('div.camimage').each(function(){
	
		// Hide the refresh link
		jq(this).find('div.refresh').hide();
		
		// Bind the image to the onload handler
		var img = jq(this).find('img');
		var src = img.attr('src');
		
		// IE wion't bind the handler unless the src is emptied first
		var clearSrcBeforeBinding = navigator.userAgent.match(/MSIE \d/) !== null;
		if(clearSrcBeforeBinding) {
			img.attr('src', '');
			img.load(camImageOnload);
			img.attr('src', src);
		}
		else {
			img.load(camImageOnload);
		}
	});
}

/***************************************************************************************************
Search
***************************************************************************************************/
sita.search = function() {
	jq('div#searchbox input:submit')
	.css({position:'absolute',left:-9999})
	.parent().append('<img id="pe-search-button" src="/++resource++sita.theme.images/search-icon.gif" width="18" height="18"/>')
	.find('img#pe-search-button')
	.click(function() {
		jq('div#searchbox form')[0].submit();
	})
}

/***************************************************************************************************
Links portlet heading
***************************************************************************************************/

/* Add class names to boxouts to style with particular icon */
sita.linksPortletHeadings = function() {

	jq('div#portal-column-two div.links-portlet').each(function() {
	
		// Make title CSS class firendly and then look for certain values
		var title = jq(this).find('h2').text()
		.replace(/^\s+|\s+$/g, '')
		.replace(/\s/,'-')
		.toLowerCase()
		
		// If white-list found, add as a class name
		if(title == 'downloads' || title == 'see-also') {
			jq(this).addClass(title + '-boxout');
		}
	});
}


/***************************************************************************************************
Home page banners and flash overlay
***************************************************************************************************/

/* Overlay a flash banner on the home page */

sita.homePageBanners = function() {

	// If player 9 is not available
	if(!swfobject.hasFlashPlayerVersion('9.0.0')) {
	
		// Add a class to the banner to identify as non-replaced
		jq('div#global-nav').addClass('no-flash');
		
		// Do nothing more
		return;
	}

	/*
	The location of the main movie, note that '+' has been replaced with '_'. Flash has an issue 
	with '+' symbols in URLs, and so Apache has been set up to translate '__resource__' to 
	'++resource++'
	*/
	// Default to overlay
	var mainMovieLocation = '/__resource__sita.theme.swf/banners/circles.swf';
	
	// If this is the home page
	if(jq('body').hasClass('section-front-page')) {
		mainMovieLocation = '/__resource__sita.theme.swf/banners/main.swf';
	}
	
	// Inject positional and target div into DOM
	jq('div#global-nav')
	
		// Add a wrapper and nested target for swfobject
		.append('<div id="home-flash-banner"><div id="home-flash-banner-inner"></div></div>')

	// use swfobject to replace alternate content
	
	swfobject.embedSWF(
		mainMovieLocation,
		'home-flash-banner-inner',
		894,
		240,
		'9.0.0',
		{},
		{location:'/__resource__sita.theme.swf/banners/'},
		{
			wmode:'transparent'
		}
	);
	
	
	// If this is NOT the home page, move the H1 above the banner
	moveH1 = function() {
		jq('body').not(jq('body.section-front-page')).find('div#frame').prepend(jq('h1')).find('h1').addClass('topOfBanner');
	}
	//setTimeout(moveH1, 1000);
	moveH1();
}

/***************************************************************************************************
Em measurement poll
***************************************************************************************************/

sita.emMeasurementPoll = function() {
	jq('body').append('<p style="position:absolute;z-index:100;left:-9999px;top:0;font-size:10em;" id="em-measurement">M</p>');
	setInterval(sita.measureEm, 500);
	sita.lastEmMeasurement = jq('p#em-measurement').width();
}
sita.measureEm = function() {
	var thisEmMeasurement = jq('p#em-measurement').width();
	if(thisEmMeasurement != sita.lastEmMeasurement) {
		openc.eventMediator.dispatchEvent('emMeasurementChange', {msg: 'Em measurement changed from ' + sita.lastEmMeasurement + " to " + thisEmMeasurement});
	}
	sita.lastEmMeasurement = thisEmMeasurement;
}

/***************************************************************************************************
Log em measurement change
***************************************************************************************************/

sita.logEmMeasurementChange = function(arg) {
	//openc.log(arg.msg);
}
openc.eventMediator.addEventListener('emMeasurementChange', sita.logEmMeasurementChange);


/***************************************************************************************************
Equal height columns ready, safari has settled down
***************************************************************************************************/

sita.setPageAsEqualHeightColumnsReady = function() {
	sita.pageIsEqualHeightColumnsReady = true;
	sita.equalHeightColumns();
}

/***************************************************************************************************
Equal height columns (TODO: abstract?)
***************************************************************************************************/
sita.equalHeightColumns = function() {

	sita.ieLt8 = jq.browser.msie && navigator.appVersion.match(/MSIE 6|MSIE 7/) != null;

	// If page hasn't settled, do nothing (this script may be called at any time if em measurements change)
	
	if(!sita.pageIsEqualHeightColumnsReady) {
		return false;
	}

	// Home page only for now
	if(!jq('body').hasClass('section-front-page')) {
		return;
	}
	
	
	// If the page hasn't been set up
	if(!sita.pageEqualHeightPrepared) {
	
		// Create balloons
		sita.columnOneBalloon = jq('div#below-content-portlets').before('<div class="balloon"></div>').parent().find('div.balloon');
		sita.columnTwoBalloon = jq('div#portal-column-one').append('<div class="balloon"></div>').find('div.balloon');
		
		// Store reference to height indicators
		sita.c1Indicator = 'div#portal-column-content';
		sita.c2Indicator = 'div#portal-column-one';
		
		sita.pageEqualHeightPrepared = true;
	}
	
	
	// Collapse balloons
	sita.columnOneBalloon.css('height', '1px');
	sita.columnTwoBalloon	.css('height', '1px');
	
	// Column heights
	var c1Height = jq(sita.c1Indicator)[0].offsetHeight;
	var c2Height = jq(sita.c2Indicator)[0].offsetHeight;
	
	// If column i is taller
	if(c1Height > c2Height) {
		var height = c1Height - c2Height + 1;
		
		sita.columnTwoBalloon.css('height', height + 'px');
	// Otherwise
	} else {
		height = c2Height - c1Height + 1;
		
		// If IE 6 or 7
		if(sita.ieLt8) {
			height += 9;
			jq("body").prepend('<div style="position:absolute;" id="wiggleIE"></div>').find('#wiggleIE').css('opacity',0.8); 
		}
		sita.columnOneBalloon.css('height', height + 'px');
	}
}

// Listen for em measurement changes */
openc.eventMediator.addEventListener('emMeasurementChange', sita.equalHeightColumns);

/***************************************************************************************************
Measure page consistency and invoke p/e when ready
***************************************************************************************************/
sita.pageReady = function() {
	sita.webcams();
	sita.search();
	sita.linksPortletHeadings();
	sita.homePageBanners();
	
	// Equal height columns (call when column two's (last in source) height has settled in Safari)
	openc.callWhenPropertyConsistent(
		!jq.browser.safari && !jq.browser.mozilla, 
		sita.setPageAsEqualHeightColumnsReady, 
		jq('div#portal-column-one')[0], 
		'offsetHeight', 30, 20, false
	);
	
	// Create em measuement poll
	sita.emMeasurementPoll();
}

/**
 * On DOM loaded
*/
jq(function() {
	if(openc.IS_RIA_CLIENT && !openc.IS_EDIT_PAGE && openc.IS_DESKTOP) {
		sita.pageReady();
	}

});

