/*jslint 
browser:true 
*/

/*global
window,
jq,
console,
swfobject,
GBrowserIsCompatible, GIcon, GLargeMapControl, GLatLng, GLatLngBounds, GMap2, GMapTypeControl, GMarker, GSize, G_DEFAULT_ICON
*/

/*members
is_iPhone
console, log,
match, apply, push, toString, max, min, submit, replace,
document, write, body, style, overflowY, appVersion, indexOf, execCommand,
swfobject, hasFlashPlayerVersion, embedSWF, wmode, allowscriptaccess,
jq, attr, addClass, focus, blur, after, click, length, remove, prepend, 
	append, each, parents, parent, find, text, clone, mouseover, mouseout, 
	width, height, css, inArray, animate, position, left, opacity,
	wrapAll, prev, next, slideToggle, hide, html, serialize, ajax, url, dataType, success,
addControl, setCenter, iconSize, extend, icon, bindInfoWindowHtml, addOverlay, getCenter, getBoundsZoomLevel, setZoom, 
*/

var is_iPhone = navigator.appVersion.match(/iPhone/) !== null;

var jq = jQuery.noConflict();

/**
 * Console
 */
if(console === undefined) {
	var console = {};
	console.log = new Function();
}

/**
 * Progressive enhancement styles
 */

if(swfobject.hasFlashPlayerVersion("9.0.0")) {
	document.write('<link rel="stylesheet" type="text/css" href="/css/fp9.css"/>');
}
if(window.GBrowserIsCompatible && GBrowserIsCompatible() && !is_iPhone) {
	
	var mapsJs = "google-maps";
	// An alternative maps js may be specified to help debug deployment issues
	var matchedQS = document.location.search.match(/mapsJs=(.+)/);
	if(matchedQS !== null) {
		mapsJs = matchedQS[1];
	}
	document.write('<link rel="stylesheet" type="text/css" href="/css/googlemaps.css"/>');
	document.write('<script type="text/javascript" src="/script/' + mapsJs + '.js"></script>');
}

/** 
* Special styles
*/
jq(function() {
	if(navigator.appVersion.match(/MSIE/) === null) {
		document.body.style.overflowY = 'scroll';
	}
});

/**
 * Embed links to oEmbed media
 */
jq(function() {
	jq('p.oembed>a').embedLinks({
		maxwidth:440, 
		youtube_querystring:{rel:00,fs:1},
		controlerHeight: 21
	});
});

/**
 * Twisty for landfills
 */
jq(function(){
	jq("div.landfills").attr('id', 'peLandfills').find('div.landfill')
			.wrapAll('<div id="landfill-wrapper"></div>').parent().hide()
			.prev().click(function() {
				jq(this).next().slideToggle();
			});
});

/**
 * Alt tags to captions
 */
jq(function() {
    jq('div#main-content img.image-inline').each(function() {
        var img = jq(this);
        alt = img.attr('alt');
        if(alt != '') {
            img.after('<p class="caption">' + alt + '</p>');
        }
    });
});

/**
 * Search field
 * Use value of search button as value of search input. Set handlers to hide on 
 * focus.
 */

jq(function() {
	//var siteSearch = jq('#site-search');
	var siteSearchInput = jq('input#site-search-input');
	var defaultLabel = jq('input#site-search-submit')
		.attr('value');
	var focusFunction = function() {
		if(jq(this).attr('value') === defaultLabel) {
			jq(this).attr('value', '');
		}
	};
	var blurFunction = function() {
		if(jq(this).attr('value') === '') {
			jq(this).attr('value', defaultLabel);
		}
	};
	blurFunction.apply(siteSearchInput);	
	siteSearchInput.focus(focusFunction);
	siteSearchInput.blur(blurFunction);
});
 
 
 /**
  * Replace buttons with images with click handlers
  */
 jq(function() {
	 var targetsString = "input:submit";
	 
	jq(targetsString).each(function(i, obj){
		
		var button= jq(obj);
		var floatRight = button.css('float') == 'right';
		var form = button.parents('form:first');
		form.addClass('pe');
		button.addClass('access');
		var label = button.attr('id') === 'site-search-submit' ? '' : button.attr('value');
		var peButton = button.after('<div class="pe-button"></div>').parent().find('div.pe-button');
		if(floatRight) {
			peButton.css('float', 'right');
		}
		
		// MSIE 6 doesn't like "Go", the entire browser crashes. Pad with space and mysteriously completely stable
		label = label == "Go" ? " Go " : label;
		peButton.text(label);
		peButton.addClass(button.attr('id'));
		peButton.click(function(cForm, cButton) {
			return function() {
				
				// Create a hidden input element matching the buttons name and value
				cForm.append(
					'<input class="pe-inserted" type="hidden" name="' + 
					cButton.attr('name') + 
					'" value="' + 
					cButton.attr('value') + 
					'"/>'
				);
				// Submit the form
				cForm.submit();
				
			};
		}(form, button));
	});
 });
 

/**
 * Home page banners
 */
jq(function() {
	
	// If the right version of Flash is aailable, and this is the home page
	if(swfobject.hasFlashPlayerVersion("9.0.0") && jq('body.home').length == 1) {
		
		// Insert a placeholder after all the columns
		jq('div#frame').prepend('<div id="home-banners"></div>');
		
		// Replace the alternative content with the Flash movie
		swfobject.embedSWF(
			"/swf/openc_swfslideshow.swf?resourcesDirectory=/home-banners",
			"home-banners", "930", "300", "9.0.0", null, null, {wmode:'transparent'}
		);
	}
});

/**
 * News ticker
 */
jq(function() {
	var latestNews = jq('div#latest-news');
	if(latestNews.length === 1) {
		latestNews.attr('id', 'latest-news-pe');
		jq('div#global-nav').after(latestNews);
		// RSS icon
		var rssLink = jq('li#siteaction-news-rss a');
		if(rssLink.length === 1) {
			latestNews.prepend(rssLink.clone().attr('id', 'peRSS'));
		}
		// Constants
		var TICKER_START_OFFSET = 20;// Place the first item right, pixels
		var TICKER_OFFSET = 1; // Pixels moved on each iteration
		var TICKER_INTERVAL = 30; // Iteration interval, ms
		var TICKER_ITEM_SPACING = 10; // ms
		var TICKER_FADE_IN_TIME = 1000; // ms
		// State
		var over = false;
		var leftMostIndex = 0;
		var currentTickerOffset = TICKER_OFFSET;
		var measured = [];
		var ul = latestNews.find('ul:first')
			.mouseover(function() {over = true;})
			.mouseout(function() {over = false;});
		var lis = ul.find('li');
		var iteration = function() {
			if(over) {
				currentTickerOffset = Math.max(currentTickerOffset-0.25, 0);
			}
			else {
				currentTickerOffset = Math.min(currentTickerOffset+0.25, TICKER_OFFSET);
			}
			lis.each(function(index){
				var li = jq(this);
				// If not yet measured
				if(jq.inArray(index, measured) === -1) {
					measured.push(index);
					// Stretch to defeat wrap, then shrink wrap an hide
					li.width(9999).width(li.find('a').width() + 1).css('opacity', 0);
					// If first, position at TICKER_START_OFFSET
					if(index === 0) {
						li.css('left', TICKER_START_OFFSET);
					}
				}
				// If this is hidden, show it
				if(li.css('opacity').toString() === "0") {
					li.animate({'opacity': 0.99}, TICKER_FADE_IN_TIME);
				}
				// If this is the left most and is in view moved left
				if(index === leftMostIndex && (li.position().left + li.width() > 0)) {
					li.css('left', li.position().left - currentTickerOffset);
				}
				else {
					// Move to the right of previous in stack
					var previousLi = jq(index === 0 ? lis[lis.length-1] : lis[index-1]);
					li.css('left', previousLi.position().left + previousLi.width() + TICKER_ITEM_SPACING);
					// If this was previously left most
					if(index === leftMostIndex) {
						// it may not be off screen so set to fade in
						li.css('opacity', 0);
						// Update left most
						leftMostIndex = leftMostIndex === lis.length-1 ? 0 : index+1;
					}
				}
			});
		};
		iteration(); // Immediately place
		setInterval(iteration, TICKER_INTERVAL);
	}
});



/**
 * Miscellaneous
 */
//Prevent flickering on image hover in MSIE

if(navigator.appVersion.indexOf('MSIE') > -1){
	try {
		document.execCommand("BackgroundImageCache", false, true);
	} catch(err) {}
}




