/**
 * MS Dynamics homepage hero non-Silverlight alternative experience
 * @requires jQuery 1.3.2 +
 * @version 3.0 (12 OCT 2009)  Updated to include Tab pre-selection functionality.
 * @author v-spsund
 */

/* test for jQuery */
if (typeof $ != 'undefined'){

	/**
	 * Silverlight helper functions
	 * Initialized by dynNonSLhero.onloadSelect(), which gets called via the master dynNonSLhero.init() method.
	 */
		/* If a Tab is pre-selected, set a global var Silverlight can read */
		var SilverlightTabRequest; /* default: Null */
		var setSilverlightTabRequest = function(TargetId){
			if (!TargetId || TargetId=='' || TargetId===false) { return false; }
			TargetId = TargetId.slice(TargetId.length -1);
			if (isNaN(parseInt(TargetId))==false) {
				/* it's numeric: concatenate tab ID */
				SilverlightTabRequest = TargetId;
			} else {
				/* Set to False so we know we were here. */
				/* SilverlightTabRequest = false; */
			}
		} /* End setSilverlightTabRequest() */


var dynNonSLhero = {

	/**
	 * @note To configure referrer presets, see dynHeroTabConfig.js
	 */
	 
	settings: {
		/**
		 * this.settings.imagePath
		 * Path to the image directory used by the non-Silverlight hero.  Used by TAB1 methods.
		 */
		imagePath: 			'/global/dynamics/en/us/RichMedia/HomeHero/nonSLassets/images/',
		/**
	 	 * this.settings.queryStringValue
		 * What querystring var to look for to hard-set a tab onload.
		 * @example  If default.aspx?YourVar=3, then this.queryStringValue = 'YourVar'
		 */
		queryStringValue: 	'tab',
		/**
	 	 * this.settings.tabIdPrefix
		 * Prefix used in ID names for each tab
		 * @example If <div id="dynHeroNonSL-tab1"></div>, then this.settings.tabIdPrefix = 'dynHeroNonSL-tab'
		 */
		tabIdPrefix: 		'dynHeroNonSL-tab'
	},


	queryStringValue: 'tab',


	tabIdPrefix: 'dynHeroNonSL-tab',
	
	dom: {}, /* required empty array */
	pageUrl: false,
	referrer: false,

	/**
	 * this.init
	 * Initialize ALL necessary behaviors and functionality. Points to member methods.
	 * @note All intervals are in milliseconds.
	 */
	init: function(){
		
		/* Ease the load by gathering oft-referenced DOM elements into properties, via jQuery */
		this.dom.tabs 		= $('#'+this.settings.tabIdPrefix+'1, #'+this.settings.tabIdPrefix+'2, #'+this.settings.tabIdPrefix+'3');
		this.dom.navLi		= $('ul#dynHeroNonSL-tabs li');
		this.dom.navLinks	= $('ul#dynHeroNonSL-tabs a');
		
		$('#dynHeroNonSL-container a.overlay').click(function(){
			if (typeof dynSilverlightOverlay == 'function'){
				dynSilverlightOverlay(this.href);
				return false;
			}
		});
		
		this.NAV.init();
		
		this.TAB1.settings.availableBGs 	= 4;
		this.TAB1.settings.filePrefix 		= 'hero_tab1_';
		this.TAB1.settings.imgExtension 	= '.jpg';
		this.TAB1.init();
		
		/* this.TAB3.settings.availableBGs 	= 4; */
		this.TAB3.settings.interval 		= 3000; 
		
		this.tabCycle.settings.enableWebTrends = true;
		this.tabCycle.webTrendsTitles = {
			'dynHeroNonSL-tab1': 'Hero-HTML: What is Microsoft Dynamics',
			'dynHeroNonSL-tab2': 'Hero-HTML: Everyone Gets It',
			'dynHeroNonSL-tab3': 'Hero-HTML: Dynamic Business'
		};
		this.tabCycle.settings.interval		= 11000; /* edit, or remove this line to use default */
		this.tabCycle.settings.stopEvent	= 'mouseover'; /* mouseover || click */
		this.tabCycle.init();
				
		this.onload();
	
	},

/* BEGIN ONLOAD ROUTINES */
	onload: function(){
		this.setReferrer();
		this.pageUrl = ''+window.location || false;
		this.onloadSelect();
	},
	setReferrer: function(){
		if ( document.referrer && document.referrer != '' ){
			this.referrer = document.referrer
		}
	},
	/**
	 * this.onloadSelect
	 * Check query string and Referrer Catalog to see if a specific Tab should be displayed.
	 */
	onloadSelect: function(){
		var target;
		var query = this.checkQuery();
		/* querystring always takes precedence */
		if (query && query!==false) {
			target = query;
		} else {
			var ref = this.checkReferrers();
			if (ref!==false) {
				target = ''+ dynNonSLhero.settings.tabIdPrefix + ref;
			}
		}
		if (!target) { return false; }
		
		/* Hand off Tab info to Silverlight interface function */
		setSilverlightTabRequest(target);
		
		/* Confirm our target actually exists... */
		if ($('#'+ target).length == 0) { return false; }
		/* ...then proceed */		
		dynNonSLhero.tabCycle.stop();
		dynNonSLhero.NAV.toggle(target);

	},
	/**
	 * this.checkQuery
	 * Check URL for instructions to select a specific tab.
	 * Query string var's value can be numeric or a specific ID.
	 */
	checkQuery: function(Silverlight){
		if (!this.pageUrl || this.pageUrl===false) { return false; }
		if ( this.pageUrl.indexOf('?') < 0 ) { return false; } /* no querystring */
		var queryString = this.pageUrl.split('?');
		if (!queryString.length || queryString.length <=0) { return false; }
		queryString = queryString[1].split('&');		
		var target;
		var len = queryString.length;
		for (var i=0; i<len; i++) {
			var arr = queryString[i].split('=');
			if (arr[0] == this.settings.queryStringValue) {
				if (arr[1] && arr[1]!=null && arr[1]!='') {
					target = arr[1];
				}
			}
		}
		if (!target){ return false; }
		else if (isNaN(parseInt(target))==false) {
			/* it's numeric: concatenate tab ID */
			target = ''+ this.settings.tabIdPrefix + target;
		}
		return target;
		
	},
	checkReferrers: function(){
		if (this.referrer == false || !dynHeroReferers.catalog || dynHeroReferers.catalog.length==0) { return false; }
		var out = false;
		var len = dynHeroReferers.catalog.length;
		for (var i=0; i<len; i++){
			if (dynHeroReferers.catalog[i].url == this.referrer) {
				out = dynHeroReferers.catalog[i].tab;
			}
		}
		return out;
	},

/* End ONLOAD ROUTINES */
	
	
	/* utility method */
	randomizeArray: function(arr){
		if (!arr) { return false; }
		var i = arr.length;
		if (i==0) { return false; }
		while (--i) {
			var j = Math.floor(Math.random()*(i+1));
			var ti = arr[i];
			var tj = arr[j];
			arr[i] = tj;
			arr[j] = ti;
		}
	},
	
	/**
	 * this.NAV
	 * Methods related to the main tab navigation.
	 * To initialize: this.NAV.init();
	 */
	NAV: {
		
		/**
		 * nav.init
		 * Set up bottom tab-nav functionality.
		 */
		init: function(){
			dynNonSLhero.dom.navLinks.click(function(){
				dynNonSLhero.tabCycle.stop();
				dynNonSLhero.NAV.toggle(this);
				return false;
			});
		},
		/**
		 * nav.toggle
		 * Display the designated tab, hiding the others (and resetting any process associated with the hidden tabs).
		 * @param {string} showId  ID of the tab to display (no leading # char)
		 */
		toggle: function(obj){
			if (!obj) { return false; }
			var showID = false;
			/* obtain required objects */
			if (typeof obj == 'string') {
				/* an ID text string has been passed: pass string to showID then obtain corresponding tab nav link */
				showID = obj;
				var tmp = obj.split('-');
				if (tmp[1]) { 
					obj = $('li.'+ tmp[1] +' a');
					if (typeof obj[0] != 'undefined') {
						obj = obj[0]; 
					} else {
						obj = false;
					}
				} else {
					obj = false;
				}
			} else if (typeof obj == 'object' && obj.tagName == 'A') {
				/* obj is a link: obtain hash from its HREF */
				showID = obj.hash.substr(1);
			} else {
				alert('Error: toggle method is missing required value');
				return false;
			}
			if (!showID || !obj) { return false; }
			/* OK: proceed */
			dynNonSLhero.dom.tabs.each(function(){
				div = $(this);
				if (this.id == showID) {
					div.removeClass('hide').addClass('show');
					if (this.id=='dynHeroNonSL-tab1') {
						/* dynNonSLhero.TAB1.cycle(); */
						dynNonSLhero.TAB3.stop();
					} else if (this.id=='dynHeroNonSL-tab3') {
						/* dynNonSLhero.TAB1.stop(); */
						dynNonSLhero.TAB3.rotate();
					} else {
						/* dynNonSLhero.TAB1.stop(); */
						dynNonSLhero.TAB3.stop();
					}
				} else {
					div.removeClass('show').addClass('hide');
				}
			});
			dynNonSLhero.dom.navLi.removeClass('here').removeClass('here2');
			if (showID=='dynHeroNonSL-tab2') {
				$(obj).parent().addClass('here2');
			} else {
				$(obj).parent().addClass('here');
			}
		}
	},

	
	/**
	 * tabCycle
	 * Causes the tabs to cycle into view sequentially.  See tabCycle.init method for "stopper" code.
	 * To initialize:  this.tabCycle.init();
	 */
	tabCycle: {
		
		/* default settings: can override in dynNonSLhero.init */
		settings: {
			interval: 			10000, /* (milliseconds) Default timing - may be overridden in master init method.  */
			stopEvent:			'mouseover',
			stopInterval:		1000,  /* (milliseconds) Default timing - may be overridden in master init method.  */
			enableWebTrends:	true
		},
	
		timer:		null,
		count:		0,
		
		
		/**
		 * stopper
		 * Helper methods for killing tab cycling behavior when using tabCycle.settings.stopEvent='mouseover'
		 * Adds a timeout, which is itself cancelled if mouseout occurs Before tabCycle.settings.stopInterval expires.
		 * Set "hesitation" interval in tabCycle.settings.stopInterval property (can customize in dynNonSLhero.init method).
		 */
		stopper: {
			timer: null,	
			set: function(){
				this.timer = setTimeout("dynNonSLhero.tabCycle.stopper.stop()", dynNonSLhero.tabCycle.settings.stopInterval);
			},
			cancel: function(){
				if (this.timer != null) {
					clearTimeout(this.timer);
				}
			},
			stop: function(){
				dynNonSLhero.tabCycle.stop();
				$('#dynHeroNonSL-container').unbind('mouseover');
			}
		},
		
		
		init: function(){
			
			/* set the stopevent: kills the tab cycling to allow normal use */
			switch(this.settings.stopEvent){
				case 'mouseover':
					$('#dynHeroNonSL-container')
						.bind('mouseout', function(){
							dynNonSLhero.tabCycle.stopper.cancel();
						})
						.bind('mouseover', function(){
							dynNonSLhero.tabCycle.stopper.set();
						})
						.bind('click', function(){
							dynNonSLhero.tabCycle.stop();
						});
					break;
				
				case 'click':
					$('#dynHeroNonSL-container').click(function(){
						dynNonSLhero.tabCycle.stop();
					});	
					break;
				
				default: /* click */
					$('#dynHeroNonSL-container').click(function(){
						dynNonSLhero.tabCycle.stop();
					});	
			}
			this.cycle();
		},
		
		cycle: function(){
			if (dynNonSLhero.dom.tabs.length == 0) { return false; }
			dynNonSLhero.NAV.toggle( dynNonSLhero.dom.tabs[this.count].id );
			
			if (this.settings.enableWebTrends === true) {
				this.webTrends(dynNonSLhero.dom.tabs[this.count].id);
			}
			this.timer = setTimeout("dynNonSLhero.tabCycle.cycle()",this.settings.interval);
			this.count= (this.count < (dynNonSLhero.dom.tabs.length -1)) ? this.count+1 : 0;
		},
		stop: function(){
			if (this.timer != null){
				clearTimeout(this.timer);
				this.count = 0;
			}
		},
		
		webTrendsTitles: {},
		webTrends: function(id){
			if (typeof dcsMultiTrack != 'function' || !id || id == '') { return false; }
			if (typeof this.webTrendsTitles[id] == 'undefined') { 
				/* failsafe: at least provide the tab's ID */
				this.webTrendsTitles[id] = 'Hero: '+ id;
			}
			dcsMultiTrack(
				"WT.ria_a", this.webTrendsTitles[id], 
				"WT.ria_f", "Rotate", 
				"DCS.dcsuri", "/dynamics/en/us/heroRotate.aspx", 
				"WT.ti", "Hero Rotate", 
				"DCSext.wtNavigation", "Hero", 
				"WT.dl", "5"
			);
		}
		
	},

	TAB1: {
		
		/* default settings: can override in dynNonSLhero.init */
		settings: {
			availableBGs:	4,
			interval: 		3000, /* milliseconds: used by tab1.cycleInit and tab1.cycle */
			filePrefix: 	'hero_tab1_',
			target:			'#dynHeroNonSL-tab1 div.heroWrapper',
			imgExtension:	'.jpg'
		},
		
		timer: 			null,
		stuff: 			[],
		count:			0,
		
		/**
		 * TAB1.init
		 * Set up basic click functionality for Tab 1's content layers.
		 */
		init: function(){
		
			/* Randomize the background */
			this.randomizeBGs();
			
			/* Attach needed click events */
			$('li#erp a').click(function(){
				/*	dynNonSLhero.TAB1.stop(); */
				dynNonSLhero.tabCycle.stop();
				$('li#erp').addClass('here');
				$('li#crm').removeClass('here');
				$('#erpBox').css('display', 'block');
				$('#crmBox').css('display', 'none');
				return false;
			});
			$('li#crm a').click(function(){
				/*	dynNonSLhero.TAB1.stop(); */
				dynNonSLhero.tabCycle.stop();
				$('li#crm').addClass('here');
				$('li#erp').removeClass('here');
				$('#crmBox').css('display', 'block');
				$('#erpBox').css('display', 'none');
				return false;
			});
			$('div.close a').click(function(){
				$('#crmBox').css('display', 'none');
				$('#erpBox').css('display', 'none');
				$('li#erp, li#crm').removeClass('here');
				return false;
			});
			
		},

		randomizeBGs: function(num){
			var rand = Math.floor(Math.random() * this.settings.availableBGs); 
			rand++; /* don't use zero-based count */
			$(this.settings.target).css('background-image', 'url('+ dynNonSLhero.settings.imagePath + this.settings.filePrefix + rand + this.settings.imgExtension +')');
		},
		
		/** 
		 * TAB1.cycleInit
		 * Causes Tab 1's bg images to cycle.
		 */
		cycleInit: function(){
			for (var i=1; i<=this.settings.availableBGs; i++){
				this.stuff.push(
					''+ this.settings.path + i + this.settings.imgExtension
				);
			}
			/* this.randomizeArray(this.tab1Stuff) */
			this.holder = $(this.settings.target);
			this.cycle();
			
		},
		cycle: function(){
			if (this.stuff.length == 0) { this.cycleInit(); }
			this.holder.css('background-image','url('+ this.stuff[this.count] +')');
			this.count= (this.count < (this.settings.availableBGs -1)) ? this.count+1 : 0;
			this.timer = setTimeout("dynNonSLhero.TAB1.cycle()",this.settings.interval);
		},
		stop: function(){
			if (this.timer != null){
				clearTimeout(this.timer);
				this.count = 0;
			}
		}

	},
	
	
	TAB3: {
		/* default settings: can override in dynNonSLhero.init */
		settings: {
			backgroundIdPrefix:	'dynHeroNonSL-tab3-Slide',
			availableBGs:		4, /* (not zero-based) */
			interval:			2400 /* milliseconds */
		},
		count:	1, /* preset */
		timer:	null,
	
		toggle: function() {
			var idPrefix = this.settings.backgroundIdPrefix;
			$('#'+ idPrefix + this.count).css('display', 'block');
			for (var i=1; i <= this.settings.availableBGs; i++) {
				if (i != this.count) {
					$('#'+ idPrefix + i).css('display', 'none');
				}
			}
			this.count= (this.count< (this.settings.availableBGs)) ? this.count+1 : 1;
		},
		
		rotate: function() {
			this.toggle();
			this.timer = setTimeout("dynNonSLhero.TAB3.rotate()",dynNonSLhero.TAB3.settings.interval);
		},
		
		stop: function(){
			if (this.timer != null){
				clearTimeout(this.timer);
				this.count = 1;
			}
		}
		
	}, /* end this.TAB3 */

	/**
 	 * this.getHeroXMLConfig()
	 * DEV: Not quite working, may not be needed
	 */
	getHeroXMLConfig: function(){
		if (!dynNonSLhero.referrer || dynNonSLhero.referrer==false) { return false; }
		var out = false;
		$.get('/global/dynamics/en/us/RichMedia/HomeHero/dynHeroTabConfig.xml',{}, function(xml){
			$('entry',xml).each(function(i){
				var url = $(this).find('url').text();
				if (url == dynNonSLhero.referrer) {
					var tmp = $(this).find('tab').text();
					out = tmp;
				}
			})
		});
		return (out);
	}

}


/**
 * Add initialization to page load queue
 */
$(document).ready(function(){
	dynNonSLhero.init();
});


		
/* On unload, forcibly unbind All events bound through jQuery */
$(window).trigger('unload');

/* ------------------------------- */
} /* NO DELETE:  Close jQuery test */
/* ------------------------------- */


