// Script Name: header.js
// Author: Martin Ma
// Purpose: Global Navigation for ABC.com - jQuery Version

//====================================================
//=== DEBUG ONLY =====================================
//
//try{ window.loadFirebugConsole(); } catch(e){}
//CDNRoot = 'http://abcpreview.go.com';
//
//====================================================
if (typeof CDNRoot == "undefined") {
	CDNRoot = 'http://a.abc.com';
}
if( typeof sAjaxCallPath != 'string' ) {
	sAjaxCallPath = 'misc/proxy.php?yws_path=/abc/ajax/nav/';
}
if( typeof sReloadPath != 'string' ) {
	sReloadPath = window.location.href;
}


// ABCCOM.header constructor
ABCCOM.header = function() {
	
	var self = this;
	var loggedInUser = '';
	var sNavImagePath = '/media/_global/images/nav/header/';
	var oPreloadImages = {
		aInternal: ['whatson', 'shows', 'fullepisodes', 'community'],
		aExternal: ['mobile', 'news', 'espn', 'shop']
	};
	var aImageCache = [];
	
	// Public Properties/Methods
	this.oNav = null;
	this.getUsername = ABCCOM.utils.getUsername;
	this.flashOpenLogin = flashOpenLogin;
	this.flashLoginCallback = flashLoginCallback;

	$('li a img', 'ul.nav').bind( 'mouseover mouseout', onNavMouse );
	imagePreload();
	setupDropDowns();
	
	function onNavMouse(e) {
		if( e ) e.preventDefault();
	    var obj = e.target;
		var sImageName = obj.id.substring( 3, obj.id.length ).toLowerCase();
		
		if( e.type == 'mouseover' ) {
			obj.preImageSource = obj.src;
			obj.src = CDNRoot + sNavImagePath + sImageName + '_rollover.gif';
		}else if( e.type == 'mouseout' ) {
			obj.src = obj.preImageSource || CDNRoot + sNavImagePath + sImageName + '_normal.gif';
			obj.preImageSource = null;
		}
	}
	
	function imagePreload() {
		$.each( oPreloadImages.aInternal, function(i, n){
			var oImage = new Image;
			oImage.src = CDNRoot + sNavImagePath + n + '_rollover.gif';
			aImageCache.push( oImage );
			
			oImage = new Image;
			oImage.src = CDNRoot + sNavImagePath + n + '_selected.gif';
			aImageCache.push(oImage);
		});
		$.each( oPreloadImages.aExternal, function(i, n){
			var oImage = new Image;
			oImage.src = CDNRoot + sNavImagePath + n + '_rollover.gif';
			aImageCache.push( oImage );
		});
	}
	
	function setupDropDowns() {
		self.oNav = new ABCCOM.header.nav();
		setupLogin();
		
		// Populate deeplinked dropdown
		if( sTab = ABCCOM.utils.getDeeplinkVar().tab ) {
			self.oNav.setScheduleUrl( sTab );
			self.oNav.open(0);
		}
	}
	
	function setupLogin( success, session, errors ) {
		return ABCCOM.utils.getUsername() ? setLogOut(ABCCOM.utils.getUsername()) : setLogIn();
	}

	function setLogIn() {
		$('#aSignin').html( 'Sign in' );
		$('#spanUsername').html();
		loggedInUser = '';
	}
	
	function setLogOut(name) {
		$('#aSignin').html( 'Sign out' );
		$('#spanUsername').html( 'Welcome ' + name + '! <a href="http://community.abc.go.com/username/'+ name +'"> My Profile</a> ' );
		loggedInUser = name;
	}
	
	// Flash external calls
	function flashOpenLogin( regType, sweepstakesName, connectionName, connectionFunction ) {
		if( !self.oNav ) return false;
		self.oNav.setRegOptions( regType, sweepstakesName, connectionName, connectionFunction );
		self.oNav.open(4);
	}
	
	function flashLoginCallback( success ) {
		if( success==true || success=='true' ) {
			//$(document).trigger( 'userLoggedIn' );
			//self.oNav.close();
			//setupLogin();
			//window.location.reload();
		
			if( sReloadPath=='profile' ) {
				var name=ABCCOM.utils.getUsername();
				var path= 'http://community.abc.go.com/';
				sReloadPath = name!='' ? path+'username/'+name : path+'profile';
			}
			window.location.href = sReloadPath;	
		} else {
			//TODO: handle login failed
			console.log( 'login failed... ');
		}
	}

};

ABCCOM.header.nav = function( options ) {
	var self = this;
	var contentCache = [];
	var iDuration = 200; //in ms
	var aNavImages = [ 'imgWhatson', 'imgShows', 'imgFullepisodes', 'imgCommunity', 'aSignin' ];
	var aAjaxCallPath = [ 'getSchedule?startDateOffset=0', 'getShows', 'getFEP', 'getCommunity', 'getSignIn'];
	var iOpen = -1;
	var iPreviewTimer = 0;
	var iTonightTimer = 0;
	var oScheduleUrl = {
			thisWeek: 'getSchedule?startDateOffset=0',
			nextWeek: 'getSchedule?startDateOffset=7'
	};
	var oRegOptions = {
		regType: 'lite',
		connectionName: '',
		connectionFunction: '',
		sweepstakesName: ''
	};
	
	// Public Properties/Methods
	this.cache = contentCache; //debug only
	this.iOpen = iOpen;
	this.setScheduleUrl = setScheduleUrl;
	this.setRegOptions = setRegOptions;
	this.open = open;
	this.close = close;
	
	// Setup Events
	$( 'li a', '#nav-left' ).bind( 'click', toggle );
	$( '#aSignin' ).click( toggle );
	$( '#aClose', '#global-header-dropdown' ).bind( 'click', close );
	
	function toggle(e) {
		if( e ) e.preventDefault();
		//console.log(e);
		var idx = jQuery.inArray( e.target.id, aNavImages );
		if( idx == iOpen ) {
			close();
		} else if( idx==4 && ABCCOM.utils.getUsername()!='' ) {
			ABCCOM.utils.logout();
		} else {
			open(idx);
		}
	}
	
	function open(idx) {
		var sUrl = aAjaxCallPath[idx];
		iOpen = idx;
		
		$('#global-header-wrapper').animate({
			height: '418px'
		}, iDuration );
		$('#global-header-dropdown').animate({
			height: '250px',
			marginTop: '0'
		}, iDuration );
		
		loadHTML(sUrl);
		setNav();
	}
	
	function close() {
		iOpen = -1;
		$('#global-header-wrapper').animate({
			height: '168px'
		}, iDuration );
		$('#global-header-dropdown').animate({
			height: '0',
			marginTop: '-246px'
		}, iDuration );
		
		setNav();
	}
	
	function loadHTML(sUrl) {
		if( !sUrl ) return false;
		sUrl = ABCCOM.utils.cacheBuster(sAjaxCallPath + sUrl);
		//console.log( 'sUrl: ' + sUrl );
		if( contentCache[sUrl] ) {
			$('#dropDownContent').html( contentCache[sUrl] );
			ajaxCallback();
		} else {
			jQuery.ajax({ url: sUrl,
				success: function(s) { $('#dropDownContent').html(contentCache[sUrl] = s); ajaxCallback(); }
			});
		}
		ABCCOM.utils.ieFlickerFix();
	}
	
	function setNav() {
		$.each( $('li a img', '#nav-left'), function(i, n) {
			if( i==iOpen ) {
				n.src = n.preImageSource = n.src.replace( '_normal.gif', '_selected.gif');
				n.src = n.preImageSource = n.src.replace( '_rollover.gif', '_selected.gif');
			} else {
				n.src = n.preImageSource = n.src.replace( '_selected.gif', '_normal.gif');
				n.src = n.preImageSource = n.src.replace( '_rollover.gif', '_normal.gif');
			}
		});
	}
	
	// Setters
	function setScheduleUrl(key) {
		//console.log( 'key: '+key+'     oScheduleUrl[key]: '+oScheduleUrl[key] );
		aAjaxCallPath[0] = oScheduleUrl[key];
	}
	
	function setRegOptions(regType, sweepstakesName, connectionName, connectionFunction) {
		oRegOptions.connectionName = connectionName;
		oRegOptions.connectionFunction = connectionFunction;
		oRegOptions.regType = regType ? regType : 'lite';
		oRegOptions.sweepstakesName = sweepstakesName;
	}
	
	function ajaxCallback() {
		switch( iOpen ) {
			case 0: // Schedule dropdown
				setupSchedule();
				break;
			case 1: // Shows dropdown
				setupSubTabs();
				break;
			case 2: // Full Episode dropdown
				//setupFEP(); // No setup necessary
				break;
			case 3: // Community dropdown
				setupSubTabs();
				break;
			case 4: // Registration dropdown
				setupReg();
				break;
		}
	}
	
	// Dropdown setup functions
	function setupSchedule() {
		// Setup deeplink
		var sTab = ABCCOM.utils.getDeeplinkVar().tab || 'thisWeek';
		$('#ulSchedule').addClass( sTab );
		$('#'+sTab).addClass( 'on' );
		
		$('a', '#ulSchedule').bind( 'mouseover mouseout click', function(e){
			if( e ) e.preventDefault();
			var obj = e.target;
			
			// Mouseover on the schedule grid
			if( e.type == 'mouseover' ) {
				if( iPreviewTimer ) { clearTimeout(iPreviewTimer); }
				iPreviewTimer = setTimeout( function(){
					if( $(obj).hasClass('newIcon') ) {
						$(obj).after( '<span class="rollover">'+obj.name+'</span>' );
						$(obj).siblings('span.rollover').css( 'left', $(obj).outerWidth()+$(obj).position().left+'px' )
														.css( 'bottom', 0 );
					}
					$('.wrapper', '#onabc').hide();
					$('#showWrapper'+obj.id).show();
					if( iTonightTimer ) { clearTimeout(iTonightTimer); }
				}, 200 );
				
			// Mouseout on the schedule grid
			}else if( e.type == 'mouseout' ) {
				//console.log( $(e.target).parent('li').eq(0) );
				$(obj).siblings('span.rollover').remove();
			
			// Click event on the grid 
			}else if( e.type == 'click' ) {
				// Fix schedule relative url
				window.location.href = 'http://abc.go.com' + obj.href.replace(window.location.protocol+'//'+window.location.host, '');
			}
		});

		$('#ulSchedule').mouseout( function(){
			if( iPreviewTimer ) { clearTimeout(iPreviewTimer); }
			if( iTonightTimer ) { clearTimeout(iTonightTimer); }
			iTonightTimer = setTimeout( function(){
				$('.wrapper', '#onabc').hide();
				$('#tonight', '#onabc').show();
			}, 3000 );
		});
		
		$('a', '#ulFootTab').click( function(e){
			if( e ) e.preventDefault();
			var sTab = $(e.target).parents('li')[0].id;
			ABCCOM.utils.setDeeplinkVar( 'tab', sTab );
			loadHTML( oScheduleUrl[sTab] );
		});

	}
	
	function setupSubTabs() {
		var sImagePath = '/media/_global/images/nav/shows/';
		var aImageCache = [];
		
		// Preload tab images
		$.each($('img', '#subWrapper'), function(i, n) {
			var oImage = null;
			var sImage = '_normal.gif';
			
			if(i==0) { n.src = n.src.replace(sImage, '_selected.gif'); }
			
			sImage = n.src.indexOf(sImage)!=-1 ? sImage:'_selected.gif'; 
			oImage = new Image;
			oImage.src = n.src.replace(sImage, '_rollover.gif');
			aImageCache.push( oImage );
			oImage = new Image;
			oImage.src = n.src.replace(sImage, '_selected.gif');
			aImageCache.push( oImage );
		});
		
		// Add tab events
		$('img', '#subWrapper').bind('mouseover mouseout click', function(e){
			if( e ) e.preventDefault();
			var obj = e.target;
			var sImage = '_normal.gif';
			sImage = obj.src.indexOf(sImage)!=-1 ? sImage:'_selected.gif'; 
			
			if( e.type=='mouseover' ) {
				obj.preImageSource = obj.src;
				obj.src = obj.src.replace(sImage, '_rollover.gif');
				
			}else if( e.type=='mouseout' ){
				obj.src = obj.preImageSource;
				
			}else if( e.type=='click' ){
				// Update subnav
				$.each( $('img[src$=\'_selected.gif\']', '#subWrapper'), function() {
					this.src = this.src.replace('_selected.gif', '_normal.gif');
				});
				obj.src = obj.src.replace('_rollover.gif', '_selected.gif');
				obj.preImageSource = obj.src.replace('_normal.gif', '_selected.gif');
				
				// Update content 
				$( '.divWrapper:visible', '#dropDownContent' ).hide();	
				$( '#'+obj.id.replace('img', 'divWrapper'), '#dropDownContent' ).show();
			}
		});
	}
	
	function setupReg() {
	
		if( typeof sNavRegSWF != 'string' ) {
			sNavRegSWF = 'drupal_registration.swf';
		}	
		var FP = { id: "registration_swf",
			movie: CDNRoot + "/media/_global/swf/registration/" + sNavRegSWF,
			width: "740", height: "200", majorversion: "9", build: "0", wmode: "transparent", majorversion: "9", allowscriptaccess: "always",
			flashvars: "regType=" + oRegOptions.regType + "&sweepstakesName=" + oRegOptions.sweepstakesName + "&connectionName=" + oRegOptions.connectionName + "&connectionFunction=" + oRegOptions.connectionFunction + "&isPreview=" + ABCCOM.utils.isPreview() };
		UFO.create(FP,"divReg");
	}
	
};


// Create abcNav on DOM Ready
$(document).ready( function(){
	window.oHeader = new ABCCOM.header();
});
