if ( typeof(window.mb)=="undefined"){ mb={}; }

/**
 * Core AMG
 */
mb = new (function($){
	
	var APPLICATION_ID = "swf";
	
	// private vars
	var me = this;
	var appWidth = -1;
	var appHeight = -1;
	
	var documents = new Array();
	
	me.broadcaster = new EventBroadcaster();

	/**
	 * called on application startup
	 * determines some base sizes, including browser viewport and then embeds
	 * the swf application with swfobject
	 */
	me.init = function(){
		
		//current browser size
		var width = $(window).width();
		var height = $(window).height();

	    mb.logger.info("browser dimensions: "+width+"x"+height);
	    mb.logger.info("app dimensions: "+appWidth+"x"+appHeight);

		appWidth = width;
		appHeight = height;

		initSubSystems();

		// attach a resize listener
		me.onResize();
		$(window).resize( function() { mb.onResize(); } );
		
		// pull the page properties
		var props = new Object();		
        props.contextPath = $(".page-properties .pp-context-path").text();
        props.section = $(".page-properties .pp-section").text();
        props.subsection = $(".page-properties .pp-subsection").text();
        props.embed = $.cookie('embed');
        
        me.generateCookies(props);
        
		// create the root Document and pass along as part of the page loaded event
		var d = new mb.Document($("#wrapper"));
		d.setProperties( props );
		documents.push(d);
		
		me.broadcaster.dispatchEvent( mb.events.PAGE_LOADED, d );
	}
	
	/**
	 * initSubSystems -
	 *
	 * if there are any subsystems that need to be initialized in specific order, do
	 * here before dispatching the system wide "inited" event
	 */
	var initSubSystems = function()
	{
		mb.logger.info("mb.initSubSystems()");

		me.broadcaster.dispatchEvent( mb.events.INITED );

	}
	
	me.generateCookies = function(props) {
    	/*
    	 * Special code here for persisting some values into cookies.
    	 * This is largely here to support when the site is embedded in an
    	 * iframe.  Since the iframe embed src can be _any_ entry point,
    	 * there are certain query string parameters that must be captured
    	 * in cookies (that would otherwise be discarded), in order for 
    	 * these values to be read later on during the user's session.
    	 * 
    	 * More specifically, when iframe'd, we want to capture the following
    	 * query string parameters:
    	 * 
    	 * chc - 		campaign codes
    	 * dealerId - 	the dealerId that's doing the embedding
    	 * zipCode - 	the zipCode of that the dealer is located in 
    	 * embed - 		to mark that we are indeed embedded and that this 
    	 * 				is an embedded session
    	 * 
    	 * We are using cookies here to persist these values (as opposed to using
    	 * server sessions) so that it plays nicely with the Akamai CDN. 
    	 */
    	
    	var sticky = ["chc", "id", "embed","dealerCode"];
    	
    	var url = document.URL;
    	if(url.indexOf("?") > 0) {
    		var index = url.indexOf("?");
    		var params = url.substring(index+1);
    		params = params.split("&");
    		for(var i=0;i<params.length;i++) {
    			var param = params[i];
    			param = param.split("=");
    			var name = param[0];
    			var value = param[1];
    			
    			if($.inArray(name, sticky) >= 0) {
    				$.cookie(name, value, {path:"/"});
    			}	
    		}
    	}
    	
        // Frame-bust code in case we came from a dealer embed.
        if (window.top == window.self) {
        	//We aren't in a frame, do we need to bust out?
        	if(props.embed == "true") {
        		//Yes, bust out.
        		
        		//Delete the cookie
        		$.cookie("embed", null, {path:"/"});
            	
            	if ( url.indexOf("embed=false") < 0 ) {
            		if(url.indexOf("?") > 0) {
            			url += "&embed=false";
            		} else {
            			url += "?embed=false";
            		}
	        		//Do the refresh
	        		window.location.href = url;
            	}
        	}
        } else {
        	//We're in a frame.
        	//Do we already have an embed cookie set to true?
        	if ( props.embed != "true" ) {	
        		$.cookie("embed", "true", {path:"/"});
        	}
        }
    }
    	
	/**
	 * handle events when the browser is resized. In these cases the application
	 * should be notified about the new size, to determine how to handle the
	 * new dimensions. 
	 *
	 * the flash app will then request a new embed size if necessary
	 */
	me.onResize = function(){
		mb.logger.log( "mb.onResize()");

		//current browser size
		var width = $(window).width();
		var height = $(window).height();
		
		width = Math.max(width,920);
		height = Math.max(height,700);
		
		me.resizeApplication( width, height );
	}

	me.getApplication = function(){
		if (navigator.appName.indexOf("Microsoft") != -1){
			return window[APPLICATION_ID];
		} else {
			return document[APPLICATION_ID];
		}
	}
	
	me.getCurrentPage = function() {
		return documents[0];
	}
	
	me.resizeApplication = function( width, height ){
		$("#"+APPLICATION_ID).height( height );
		$("#"+APPLICATION_ID).width( width );
	}

})(jQuery);

mb.utils = new (function($){
	var me = this;
	me.resizeFlash = function( width, height ){
		mb.logger.log("resize("+width+"x"+height+")");
	};
	me.doAtlas = function(){
		$.get("http://view.atdmt.com/iaction/MBU_BrandHalo_Drives_" + $('#atlas_tag').text().toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()}).replace(/ /gi,""));
	};
})(jQuery);

mb.nonswf = new (function($){
	var me = this;

	me.init = function(){
	    
		var current_stories = [];
		var current_drive;
		
		$('body').css({backgroundImage:'url("'+ bgurl +'")', backgroundPosition:'center center', backgroundRepeat:'no-repeat'});
		
		if($('#alt').length != 0){
			mb.logger.log("page : index");
			$('#drives a').hover(function() {
				current_drive = $(this);
				$('.story').css('opacity','0.2');
				current_stories = $('.story_links', this);
				current_stories.each(function(){
					$('#' + $(this).text()).css('opacity','1');
					$('#' + $(this).text() + ' img').animate({'height':'425px', 'top':'-40'}, {duration:200});
				});
				current_drive.find('div').css("z-index","1");
				current_drive.find('div').stop(false,true).animate({'width':'216px', 'height':'139px', 'top':'-7px', 'left':'-10px'}, {duration:200});
				$('#drives a').not(this).find('span').css('opacity','0.5');
			},
			function() {
				current_drive.find('div').stop(false,true).animate({'width':$('#drives a').width(), 'height':$('#drives a').height(), 'top':'0', 'left':'0'}, {duration:100});
				current_drive.find('div').css("z-index","0");
				$('#drives a span').css('opacity','1');
				current_stories.each(function(){
					$('#' + $(this).text() + ' img').animate({'height':'345px', 'top':'5px'}, {duration:200});
				});
			});			
			$('#drives').hover(function(e){
				$('.story').stop(false, true).animate({'width':'80px', 'height':'335px'}, {duration:500});
				$('.story img').stop(false, true).animate({'width':'80px', 'height':'335px', 'top':'5px'}, {duration:500});
				$('.story').css('opacity','0.2');
				try{current_stories.each(function(){ $('#' + $(this).text()).css('opacity','1'); });}catch(err){}
				e.stopPropagation();
			},
			function(e){
				$('.story').stop(false, true).animate({'width':'88px','height':'345px'}, {duration:200});
				$('.story').css({'opacity':'1', 'z-index':'0'});
				$('.story img').stop(false, true).animate({'width':'88px','height':'345px', 'top':'0px'}, {duration:200});
				e.stopPropagation();
			});
		} //close #alt if
		
		if($('#alt2').length != 0){
			mb.logger.log("page : drive");
			$('.story').hover(function(e){
				$(this).css({'z-index':'2'});
				$('div', this).stop(false, true).fadeIn('slow');
				$('img', this).stop(false, true).animate({'width':'124px', 'left':'-5px', 'top':'-10px', 'height':'485px'}, {duration:300});
			},
			function(e){
				$(this).css({'z-index':'0'});
				$('div', this).stop(false, true).fadeOut('fast');
				$('img', this).stop(false, true).animate({'width':'114px', 'left':'0', 'top':'0', 'height':'465px'}, {duration:150});
			});
			$('.container').click(function(e){
				if($(e.target).is('.container')) window.location = $('#header :first').attr('href');
			});
		}//close #alt2 if
		
		if($('#alt3').length != 0){
			mb.logger.log("page : story");
			$('.story#prev').mouseover(function(e){
				$('.container .prev').stop(false, true).fadeIn('fast');
				$('.container .arrow#prev').stop(false, true).animate({'left':'-14px'}, {duration:200});
				$(this).parent().stop(false, true).animate({'opacity':'1'}, {duration:250});
			});
			$('.story#next').mouseover(function(e){
				$('.container .next').stop(false, true).fadeIn('fast');
				$('.container .arrow#next').stop(false, true).animate({'left':'131px'}, {duration:200});
				$(this).parent().stop(false, true).animate({'opacity':'1'}, {duration:250});
			});
			$('#stage').mouseover(function(e){
				e.stopPropagation();
				$('.container .arrow#prev').css({'left':'0'});
				$('.container .arrow#next').css({'left':'116px'});
				$('.container .small').css({'display':'none'});
				$('.story').parent().stop(false, true).animate({'opacity':'0.5'}, {duration:150});
				//$('#copy_box').stop(false, true).css('top','492px');
			});
			$('.container').mouseleave(function(e){
				e.stopPropagation();
				$('.container .arrow#prev').css({'left':'0'});
				$('.container .arrow#next').css({'left':'116px'});
				$('.container .small').css({'display':'none'});
				$('.story').parent().stop(false, true).animate({'opacity':'0.5'}, {duration:150});
			});
			//fix for story next button mouseout
			$('.container #fix').mouseover(function(e){
				e.stopPropagation();
				$('.container .arrow#next').css({'left':'116px'});
				$('.container .small').css({'display':'none'});
				$('.story').parent().stop(false, true).animate({'opacity':'0.5'}, {duration:150});
			});
			$('#copy_box').hover(function(e){
				$(this).stop(false, true).animate({'top':'354px', 'height':'187px', 'opacity':'0.9'}, {duration:300});
				$('#social_box').stop(false, true).animate({opacity: 1}, 300).animate({'width':'130px'}, {duration:300});
				e.stopPropagation();
			},
			function(e){
				$(this).stop(false, true).animate({opacity: 0.7}, 150).animate({'top':'492px', 'height':'49px'}, {duration:150});
				$('#social_box').stop(false, true).animate({'width':'0px'}, {duration:150});
			});
		}//close #alt3 if
		
	}; //close init
	
})(jQuery);

/**
 * The **ONLY** page load handler, initialize the amg application
 */

$().ready(function(){
    swfobject.addLoadEvent(function(){
    	if(document.getElementById("swf").tagName != "OBJECT") mb.nonswf.init();
    	else mb.init();
    });
});
