/*
 * ENABLE JS-ONLY STYLES
 */
$('html').addClass('js-enabled');
if(typeof(swfobject) !== 'undefined' && swfobject.hasFlashPlayerVersion("9")) {
	$('html').addClass('flash-enabled');
}

/*
 * INITIALIZE SIFR
 */
//set basepath
var basepath = '';
$.each(['annual-reports','news-media','our-commitments','our-impact','products'], function(i, section){
	if(location.href.indexOf(section) !== -1) {
		basepath = '../';
	}
});
var inspira_pitch_sc = { src: basepath + '_files/swf/GE_Inspira_Pitch_SC.swf' };
var inspira_pitch = { src: basepath + '_files/swf/GE_Inspira_Pitch_Regular.swf' };
var inspira_book = { src: basepath + '_files/swf/GE_Inspira_Book.swf' };
var inspira_book_bold = { src: basepath + '_files/swf/GE_Inspira_Book_Bold.swf' };
sIFR.activate(inspira_pitch, inspira_pitch_sc, inspira_book, inspira_book_bold);


sIFR.replace(inspira_book, {
	selector: 'p.landing-headline'
	,css: '.sIFR-root { color: #76b900; leading: 8; }'
	,wmode: 'transparent'
	,offsetTop: 3
});
sIFR.replace(inspira_book_bold, {
	selector: 'p.special-article-headline'
	,css: '.sIFR-root { color: #76b900; leading: 1;}'
	,wmode: 'transparent'
	,offsetTop: -2
});
sIFR.replace(inspira_book, {
	selector: 'p.article-headline'
	,css: '.sIFR-root { color: #76b900; leading: 4;}'
	,wmode: 'transparent'
	,offsetTop: 3
});
sIFR.replace(inspira_pitch, {
	selector: 'h3.benefit-headline, .toc-headline'
	,css: '.sIFR-root { color: #76b900; }'
	,wmode: 'transparent'
});

//progress handling
function handleProgressOverlay() {

	//hide all but first
	$('.progress-image').not(':first').hide();
	
	//attach close event
	$('#our-progress a.close').click(function() {
		$('#overlay-container').empty();
		$.unblockUI();
		//add active video back
		if ($('body').hasClass('home')) {
			reembedActiveVideo();
		}
		return false;
	});	
	
	//attach map events
	$('#Map-Home-Emissions, #Map-Home-btnEmissions, #Map-Energy-Emissions').click(function() {
		$('.blockMsg').height('780px');	
		$('#Emissions_image').show().siblings().hide();
		return false;
	});
	$('#Map-Home-Energy, #Map-Home-btnEnergy, #Map-Emissions-Energy').click(function() {
		$('.blockMsg').height('600px');	
		$('#Energy_image').show().siblings().hide();
		return false;
	});
	$('#Map-Emissions-Home, #Map-Energy-Home').click(function() {
		$('.blockMsg').height('600px');	
		$('#Home_image').show().siblings().hide();
		return false;
	});
}



//video overlay

function prepareOverlay() {
	var $overlay = $('#overlay-container');
	if($overlay.length === 0) {
		$overlay = $('<div id="overlay-container" />');
		$overlay.prependTo('#content');
	} else {
		$overlay.empty();
	}
}

function doOverlay(_width, _height, _bkgd, _topOffset) {
	prepareOverlay();
	var $overlay = $('#overlay-container');
	var centerY = true;
	var topOffset;
	if(_topOffset) {
		centerY = false;
		topOffset = _topOffset;
	}
	//prepare blockUI
	$.blockUI({
		message: $('#overlay-container'),
		centerY: centerY,
		css: {
			width: _width + 'px'
			,height: _height + 'px'
			,backgroundColor: _bkgd
			,cursor: 'default'
			,border: '1px solid ' + _bkgd
			,top: topOffset ? topOffset : ($(window).height() - _height) /2 + 'px'
			,left: ($(window).width() - _width) / 2 + 'px'             
		},
		overlayCSS: {
			opacity: '0.8'
		}			
	});
	return $overlay;
}

/*
 * ONLOAD EVENTS
 */
$(document).ready(function() {

	/* nav hovers for IE */
	if($.browser.msie && parseInt($.browser.version) === 6) {
		$('#site-navigation > li').hover(
			function() {
				$(this).addClass('hover_');
			},
			function() {
				$(this).removeClass('hover_');
			}
		)
	}
	/* :n-child fixes for IE */	
	if($.browser.msie && parseInt($.browser.version) < 8) {
		//for first header on product detail pages
		$('body.products.article-page .article h3:first').css('margin-top','0');	
		//for last group on ads page
		$('.media-items .group:last-child').css('margin-bottom','0')
	}	
	/* open external urls in new window */
	$('a[href^=http], area[href^=http], a.doc').not('a[href^=http://files.gecompany.com], a#share-link, a#show-chatter-link').click(function() {
		window.open(this.href);
		return false;
	});
	//exception for enertainment category on ads and images page
	$('a.entertainment').click(function() {
		window.open(this.href);
		return false;
	});
	
	/* open external urls in new window */
	$('a.popup').click(function() {
		window.open(this.href, 'popup', 'height=520, width=740');
		return false;
	});
	
	/* activate search */
	$('form#site-search').submit(function() {
		location.href = basepath + 'search.html?term=' + htmlEncode($('input#textToSearch').val());
		return false;
	});	
	/* populate search input */
	$(function(){
		var _labeltext = $('label[for=textToSearch]').text();
		$('#textToSearch')
		.val(_labeltext)
		.focus(function() {
			if($(this).val() === _labeltext) {
				$(this).val(''); 
			}
		})
		.blur(function() {
			if($(this).val() === '') {
				$(this).val(_labeltext); 
			}
		});
	});
	
	/* OVERLAY
		============================= */
	$('a[type=video/x-flv], a[type=image/jpeg]').click(function() {
		var _isVideo = $(this).attr('type') === 'video/x-flv';
		//prepare container
		if($('#overlay-container').length === 0) {
			$('<div id="overlay-container" />').prependTo('#content');
		} else {
			$('#overlay-container').empty();
		}
		//video object will replace #player
		$('#overlay-container')
		.append($('<a href="#" id="close-video-link">close</a>').click(function() {
			$('#overlay-container').empty();
			$.unblockUI();
			return false;
		}))
		.append('<div id="player" />');
		//TODO: figure out dims :::::::::::::::::
		var _width, _height;
			_width = _isVideo ? 480 : 810;
			_height = _isVideo ? 265 : 520;		
			
		//prepare blockUI
		$.blockUI({
			message: $('#overlay-container'),
			css: {
				padding: 5	
				,width: _width + 'px'
				,height: _height + 45 + 'px'
				,backgroundColor: '#000'
				,border: '10px solid #000'
				,top: ($(window).height() - _height) /2 - 50 + 'px'
				,left: ($(window).width() - _width) /2 + 'px'
				,cursor: 'default'
			},
			overlayCSS: {
				opacity: '0.8'
			}			
		});
		if(_isVideo) {
			//embed video
			var flashvars = {};
			flashvars.playSt = $(this).attr('href');
			flashvars.flvPath = $(this).attr('href');
			
			var params = {};
			params.bgcolor = "#000000";
			params.menu = "false";
			params.allowfullscreen = "true";
			var attributes = {};
			attributes.id = "video-object";
			swfobject.embedSWF(basepath + "_files/swf/eco_video_player_small.swf", "player", "470", "265", "8", "expressInstall.swf", flashvars, params, attributes);
		} else {
			$('#player').html('<img src="'+ $(this).attr('href') +'" />');	
		}		
		return false;
	});
	
	/* IMAGE SLIDESHOW
		============================= */
	if($('#slideshow').length !== 0) {
		$(function(){
			if($.browser.msie && parseInt($.browser.version) === 6) {
				//fix positioning issue
				$('#slideshow').css({
					height: '300px'
					,position: 'absolute'
				});
				//expand height to keep from overlapping footer
				$('#content .media').css({
					height: '350px'
				});
			}
			// create hero img
			$('<img id="slideshow-hero" />')
				.attr('src', $('#slideshow .thumbs a:first').attr('href'))
				.prependTo('#slideshow');
			//activate slide links (remove thumbs if only 1))
			if($('#slideshow .thumbs img').length > 1) {
				$('#slideshow .thumbs a')
				.mouseover(function() {
					$('#slideshow-hero').attr('src', $(this).attr('href'))
					$('#slideshow .thumbs a').removeClass('current');
					$(this).addClass('current');
				})
				.click(function() { return false; })
				.filter(':first')
				.addClass('current');
			} else {
				$('#slideshow .thumbs').remove();
			}
		});
	}
	
	/* IMAGES AND ADS TABS
		============================= */
	if($('body#advertising-and-images').length !== 0) {
		$(function(){
			var _pagetitle = document.title;// = "Your site name here";
			if(location.hash) {
				_active = location.hash.substring(2);
				$('div.tab-panel').not('#' + _active).hide();
				$('.tab-links a[href=#'+ _active +']').addClass('current');
			} else {
				$('div.tab-panel').not(':eq(0)').hide();
				$('.tab-links a').filter(':first').addClass('current');
			}
			
			$('.tab-links a').click(function() {
				if($(this).hasClass('current')) {
					return false
				}
				var _targetId = $(this).attr('href');
				//display/hide tab panels
				$('div.tab-panel')
				.hide()
				.filter(_targetId)
				.show()
//must apply sifr again to hidden elements
sIFR.replace(inspira_pitch, {
	selector: '.toc-headline'
	,css: '.sIFR-root { color: #76b900; }'
	,wmode: 'transparent'
});				
				//set current link
				$('.tab-links a').removeClass('current');
				//basic state mgmt
				location.hash = '/' + _targetId.replace('#','');
				//stupid IE
				if($.browser.msie && parseInt($.browser.version) < 8) {
					document.title = _pagetitle;			
				}	
				$(this).addClass('current');
				return false;
			})
			
		});		
	}


	
	/* STORIES SLIDER
		============================= */
	if($('#stories-slider').length !== 0) {
		$(function(){
			//very basic state management
			var _activeIndex = 0;
			if(location.hash) {
			    //get page
			    _activeIndex = parseInt(location.hash.charAt(location.hash.length - 1)) - 1;
			    $('#stories-slider div.group').not(':eq('+ _activeIndex +')').hide();
			}
			//create paging -- if more than one page
			if($('#stories-slider div.group').length > 1) {
				var $pageLinks = $('<ul class="paging nav" />');
				//go through each group
				$('#stories-slider div.group').each(function(i) {
					var isLast = i+1 === $('#stories-slider div.group').length;
					$('<li />').addClass(isLast ? 'last_':'').append($('<a />').addClass(i === _activeIndex ? 'current':'').attr('href', '#'+$(this).attr('id')).html(i+1)).appendTo($pageLinks);
				});
				$('#stories-slider .header').append($pageLinks);
				//activate slider
				$('#stories-slider .paging a').click(function() {
					var $this = $(this);
					if($this.hasClass('current')) {
						return false;
					}
					//add hash for state management
					location.hash = '/' + $this.attr('href').replace('#','');
					//get target from href
					var $target = $($this.attr('href'));
					//hide/show page containers
					$target.animate({width: 'show'}).siblings('div.group').animate({width: 'hide'});
					//set current page link
					$('#stories-slider .paging a').removeClass('current');
					$this.addClass('current');			
					return false;
				});				
			}
		});
	}
	
	
});


/* PRESS RELEASES FEED
	(DO NOT RENAME - this function is called from within rss_feed_proxy.swf)
	============================= */

function getRSSData(_itemsArray){
	//set max items
	var _maxItems = 10;

	//build up html	
	var _html = '';	
	$.each((_itemsArray.slice(0,_maxItems)), function(i, item){
		_html += '<p>';
		_html += formatDate(item.date.value);
		_html += '<br />';
		_html += '<a href="'+item.link.value+'">'+item.title.value+'</a>';
		_html += '</p>';
	});
	$('#press-releases-items').prepend(_html);
	
	function formatDate(_date) {
		//make array from date like ["Thu,", "23", "Apr", "2009", "15:20:00", "EDT"]
		_date = _date.split(' ');
		//format each date item
		var _m = ($.inArray(_date[2], ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']) + 1).toString();
			_m = _m.length === 1 ? '0' + _m : _m;
		var _d = _date[1];
		var _y = _date[3].slice(2);
		
		return _m + '-' + _d + '-' + _y; 
	}
	
	// open external urls in new window
	$('#press-releases-items a').click(function() {
		window.open(this.href);
		return false;
	});
	
}

/* HTML ENCODING */
function htmlEncode(s) {
	return s.replace(/&(?!\w+([;\s]|$))/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}


/*
Executes proprietary command to force IE to cache all background images 
	which prevents the browser from fetching the same image repeatedly when using CSS hover background repositioning
(http://support.microsoft.com/?scid=kb;en-us;823727&spid=2073&sid=global)
*/
if($.browser.msie && parseInt($.browser.version) === 6) {
try {
	document.execCommand("BackgroundImageCache",false,true);
} catch(e) {
	// just in case
}
}
