/*
loading the required Javascript based on what's present in the DOM. Loading scripts not loaded in the head.
Notes: please place universally needed js at the top, followed by short conditional logic, followed by includes there are examples in the comments and marked sections.
setTimeout calls were added per: http://henrytapia.com/archives/2008/04/22/load-only-the-jquery-plugins-you-need-when-you-need-them/
"in Firefox 3 and Safari Webkit, objects loaded via $.getScript() aren’t instantly available when called via the callback function."
*/

$(document).ready(function(){

	try { var wr = $.cakephp.webroot || '/'; } catch(e) { var wr = '/'; }

	///////////////////////////////////////////////
	// ie placeholder polyfil
	///////////////////////////////////////////////
	
	$('#FormPCS01Search').placeholder();
	
	///////////////////////////////////////////////
	// Utility Functions
	///////////////////////////////////////////////
	
	//Match heights for specific objects
	$.fn.equalHeight = function() {
        var tallest = 0;
        this.each(function() {
                var thisHeight = $(this).height();
                if(thisHeight > tallest) {
                        tallest = thisHeight;
                }
        });
        this.height(tallest);
        
        return this;
	}

	///////////////////////////////////////////////
	// youtube universal video lightbox
	///////////////////////////////////////////////
	
	$('a.lightbox-youtube').click(function(e){
		e.preventDefault();
		var href = this.href;
		var title = this.title || '';
		href.toLowerCase();
		
		//Is youtube link
		if(href.indexOf('youtube') >= 0 || href.indexOf('youtu.be') >= 0){
			if(href.indexOf('youtube') >= 0){
				//Change to embed code
				href = href.replace("watch?v=",'embed/').split('&');
				href = href[0];
			} else if(href.indexOf('youtu.be') >= 0) {
				
				//Change to embed code
				href = href.replace("youtu.be/",'www.youtube.com/embed/');
			}
			//Load lightbox
			$.openDOMWindow({
				windowSource:'inline',
				windowSourceURL: '',
				width: 560,
				height: 345,
				overflow:'hidden',
				windowPadding:5,
				borderSize: 0,
				borderColor: '#ffffff',
				functionCallOnOpen: function(){
					$('#DOMWindow').append( '<p class="domwindow-title">'+ title +'&nbsp;</p><iframe width="560" height="315" src="'+ href  +'" frameborder="0" allowfullscreen></iframe><a class="domwindow-close" href="javascript:$.closeDOMWindow();">Close</a>' ).prepend('');
				}
			});			
		} else {
			//Just go to the link
			return false;
		}
	});

	///////////////////////////////////////////////
	// Custom Page Functionality 
	///////////////////////////////////////////////

	//Checking to see if jCarouselLite is loaded
	if ( !!$.fn.jCarouselLite ) 
	{ 
		//simpleScroller for home hero
		if( $('.js-scroller-home').length) {						
			//auto generate an array for the carousel items			
			var externalControlsArray = new Array();
			var externalControlCount = $('.home-carousel-controls a').length;
			
			for (var i = 1; i <= externalControlCount; i++)
			{
				externalControlsArray.push('.home-carousel-controls .' + String(i) );
			}
			
			$('.js-scroller-home').jCarouselLite({				
				btnNext: null,
				btnPrev: null,
				auto: 7000,
				speed: 0,
				circular: true,
				visible: 1,
				btnGo: externalControlsArray,
				beforeStart: function(a){					
					//$(a).parent().fadeTo(1000, 0);					
					//Cufon.replace('h1:not(.no-cufon)');					
					if($.browser.msie && parseInt($.browser.version) <= 8){
						
					} else {
						$(a).parent().fadeOut(1000);
					}
					
				},
				afterEnd: function(a) {
					//$(a).parent().fadeTo(1000, 1);					
					if($.browser.msie && parseInt($.browser.version) <= 8){
						
					} else {
						$(a).parent().fadeIn(1000);
					}
					
					var promoId = a[0].id;
					var chicletId = a[0].id.replace('promo','promoButton');					
					$('.home-carousel-controls a').removeClass('active');				
					$('#' + chicletId).addClass('active');				
				}				
			});
			
			//Replace Specific Home Promo Tags
			Cufon.replace('#home_promo_scroller h1');
			
			/*
			$('.home-carousel-controls a').click(function() {															
				var clickedItem = $(this).attr('id');
				$('.home-carousel-controls a').removeClass('active');				
				$('#' + clickedItem).addClass('active');				
			});
			*/
			
		}
		
		//simpleScroller for why dex one hero
		if( $('.js-scroller-why-dex').length) {						
			//auto generate an array for the carousel items			
			var externalControlsArray = new Array();
			var externalControlCount = $('.why-dex-carousel-controls a').length;
			
			for (var i = 1; i <= externalControlCount; i++)
			{
				externalControlsArray.push('.why-dex-carousel-controls .' + String(i) );
			}
			
			$('.js-scroller-why-dex').jCarouselLite({				
				btnNext: null,
				btnPrev: null,
				auto: 7000,
				speed: 0,
				circular: true,
				visible: 1,
				btnGo: externalControlsArray,
				beforeStart: function(a){					
					//$(a).parent().fadeTo(1000, 0);					
					//Cufon.replace('h1:not(.no-cufon)');					
					if($.browser.msie && parseInt($.browser.version) <= 8){
					} else {
						$(a).parent().fadeOut(1000);
					}
				},
				afterEnd: function(a) { 
					//$(a).parent().fadeTo(1000, 1);					
					if($.browser.msie && parseInt($.browser.version) <= 8){
					} else {
						$(a).parent().fadeIn(1000);
					}
					var promoId = a[0].id;
					var chicletId = a[0].id.replace('whyDex','whyDexButton');		
					$('.why-dex-carousel-controls a').removeClass('active');				
					$('#' + chicletId).addClass('active');					
				}		
			});
			
		}
		
		//simpleScroller for social feed
		/* TODO uncomment this section to activate the social feed
		if( $('.js-scroller-dex1-social-feed').length) {	
			var socialExternalControlsArray = [
			                             	".dex1-social-menu .1",
			                             	".dex1-social-menu .2",
			                             	".dex1-social-menu .3"
			                            ];
			$('.js-scroller-dex1-social-feed').jCarouselLite({				
				btnNext: null,
				btnPrev: null,
				auto: 7000,
				speed: 1000,
				circular: true,
				visible: 1,
				btnGo: socialExternalControlsArray,
				beforeStart: function(a){					
					if($.browser.msie && parseInt($.browser.version) <= 8){
						$(a).parent().toggle(1000);
					} else {
						$(a).parent().fadeOut(1000);
					}
				},
				afterEnd: function(a) { 					
					if($.browser.msie && parseInt($.browser.version) <= 8){
						$(a).parent().toggle(1000);
					} else {
						$(a).parent().fadeIn(1000);
					}
					var promoId = a[0].id;
					var chicletId = a[0].id.replace('social-feed-module','social-feed');	
					$('.dex1-social-menu a').removeClass('active');				
					$('#' + chicletId).addClass('active');
				}		
			});
			//console.log(socialExternalControlsArray);
		}
		*/
		
		//simpleScroller();
		if( $('.js-scroller').length  ){
			$('.js-scroller').jCarouselLite({
				btnNext: ".js-rightArrow",
				btnPrev: ".js-leftArrow",
				circular: true,
				visible: 3
			});
		}
		
		//simpleScroller();
		if( $('.js-scroller-4').length  ){
			$('.js-scroller-4').jCarouselLite({
				btnNext: ".js-rightArrow",
				btnPrev: ".js-leftArrow",
				circular: true,
				visible: 4
			});
		}
		
		//Scroller for Learning Modules
		if( $('.js-scroller-modules').length  ){
			$('.js-scroller-modules').jCarouselLite({
				circular:true,
				visible:5,
				vertical:true,
				btnNext: '.js-rightArrow',
				btnPrev: '.js-leftArrow',
				speed:0
			});
		}
		
		//Toggle Code and Carousel for the Top Search Ticker
		if( $('.jcarousel-top-search-list').length && $('.jcarousel-top-search-list li').length ){
			
			//Top Search Ticker Toggle
			$('a.topsearch-toggle').bind('click', function(e){
				e.preventDefault();
				$('a.topsearch-toggle').toggleClass('open');
				var dataType = jQuery(this).attr('data-type');
			
				$('li.dex1-top-search-ticker-carousel .jcarousel-top-search-list li').each(function(index){
					var item$ = $(this);
					item$.text( item$.attr('data-index')  + '. ' + item$.attr('data-' + dataType));
				});
			});
		
			//Top Search Ticker Carousel
		    $('.jcarousel-top-search-list').jCarouselLite({
		        vertical: true,
		        visible:1,
		        circular:true,
		        btnPrev: '.jcarousel-prev',
		        btnNext: '.jcarousel-next'
		    });
		}		
		
	}

	//DOMWindow for the premium downloads
	if( $('.js-download').length ){
		$('.js-download').openDOMWindow({
			eventType:'click',
			windowSource:'iframe',
			width:650,
			height:575,
			overflow:'hidden',
			windowPadding:0,
			borderSize: 0,
			functionCallOnOpen: function(){
				$('#DOMWindow').append( '<a class="domwindow-close" href="javascript:$.closeDOMWindow();">Close</a>' );
			}
		});
	}
	
	//Search Box for Premium Downloads
	if( $('.dex1-pcs01').length ){
		var onPCS01Submit = function(e){
			var searchText = encodeURIComponent( $('#FormPCS01Search').val() );
		
			var newLocation = wr + "downloads/index/All/" + searchText;
			try {
				DexGoogleTracking('Content Search - ' + searchText);
			} catch(e) { }
			document.location = newLocation;
			return false;
		}
		
		$('#FormPCS01Submit').click(onPCS01Submit);
		$('#FormPCS01').submit(onPCS01Submit);
	}
	
	//Category Box for Premium Downloads
	if( $('.dex1-pcf01').length ){
		$('#SelectPCF01').change(function(e){
			var searchText = encodeURIComponent( $(this).val() );
		
			var newLocation = wr + "downloads/index/" + searchText;
			document.location = newLocation;
			return false;
		});
	}
	
	if($('.js-accordion').length ){
		$.getScript( wr+'js/ajax/accordion.js', function()
		{
			setTimeout(function()
			{
				$('.js-accordion').accordion('init',{ buttonText: ["CLOSE -","OPEN +"], buttonClosedClass: 'dex1-closed' });
			}, 200);	
		});
	};

	//Any Lightboxes on the page
	if ( $('.js-modal-trigger').length ) { 
		$('.js-modal-trigger').click( function(e){
			e.preventDefault();
			var this$ = $(this);
			$.openDOMWindow({
				windowSource:'ajax',
				windowSourceURL: this$.attr('href'),
				width: this$.attr('data-width') || 640,
				height: this$.attr('data-height') || 550,
				overflow:'hidden',
				windowPadding:5,
				borderSize: 0,
				borderColor: '#ffffff',
				functionCallOnOpen: function(){
					$('#DOMWindow').append( '<a class="domwindow-close" href="javascript:$.closeDOMWindow();">Close</a>' );
				}
			});
		});
	};
	
	//Set up Ticker
	if( $('#questionsTicker').length){
		
		var ticker_url = $('#questionsTicker').attr('data-url'); //'RotatingQuestions';
		$.getJSON(ticker_url, function(d){
			
			var max_question_text_length = 365;
			var max_answer_text_length = 1000;
			//Populate Ticker
			var questions = '';
			var answers   = '';
			var length	= 0;
			$.each(d,function(i,v){
				//alert ('test..'+v.RotatingQuestion.question_text);
				questions += '<h1 data-index="'+i+'">Q: ' + ( (v.RotatingQuestion.question_text.length > max_question_text_length)?v.RotatingQuestion.question_text.substr(0, max_ticker_text_length)+'...':v.RotatingQuestion.question_text )  + '</h1>'
				answers += '<p data-index="'+i+'">A: ' + ( (v.RotatingQuestion.answer_text.length > max_answer_text_length)?v.RotatingQuestion.answer_text.substr(0, max_answer_text_length)+'...':v.RotatingQuestion.answer_text )  + '</p>'
				length = length+1;
			});
			$('.question_text').empty().append(questions);
			$('.answer_text').empty().append(answers);
			//alert(length);
			$('#questionsTicker').data('ticker',{
				question$: $('div.question_text'),
				answer$: $('div.answer_text'),
				button_next$: $('.dex1-your-questions-btns  .next'),
				button_prev$: $('.dex1-your-questions-btns .prev'),
				length: length,
				index: -1,
				interval: null,
				onInterval: null,
				onNext: null,
				onPrev: null,
				goTo: null
			});
			
			var ticker = $('#questionsTicker').data('ticker');
			
			ticker.goTo = function(i) {
				//alert(ticker.index);
				ticker.answer$.find('p').eq(ticker.index).hide();
				ticker.question$.find('h1').eq(ticker.index).hide();
				ticker.index = i;
				ticker.question$.find('h1').eq(ticker.index).show();
				ticker.answer$.find('p').eq(ticker.index).show();
			};
			
			ticker.onNext = function(e,isLoop){ 
				if(isLoop == undefined){
					//alert('next');
					//This was not a loop trigger
					//clearInterval(ticker.interval);
					//ticker.interval = setInterval(ticker.onInterval,5000);
				}//alert('go');
				ticker.goTo( (ticker.index+1) % ticker.length );
				return false;
			}
			
			ticker.onPrev = function(e,isLoop){ 
				if(isLoop == undefined){
				//	alert('prev');
					//This was not a loop trigger
				//	clearInterval(ticker.interval);
				//	ticker.interval = setInterval(ticker.onInterval,5000);
				}
				ticker.goTo ( ((ticker.index==0)?ticker.length:ticker.index)-1 );//  Math.max(ticker.index-1) % ticker.length;
				return false;
			}
			
			ticker.onInterval = function() {
				ticker.button_next$.triggerHandler('click',true);
			}
			
			//Wire Buttons
			ticker.button_next$.click( ticker.onNext );
			ticker.button_prev$.click( ticker.onPrev );
			
			//Initially Hide all other items
			ticker.question$.find('h1:gt(0)').hide();
			ticker.answer$.find('p:gt(0)').hide();
			//Start Auto Ticker
		//	ticker.button_next$.trigger('click');
			
		});
		
	}
	
	if(navigator.platform == 'iPad') {
    	(function(){
			feedback$ = $('.dex1-site-feedback');
			document$ = $(document);
			window$ = $(window);
			
			var calcPos = function(){
				var winHeight = window$.height();
				var winOffset = window$.scrollTop();
				var feedbackHeight = feedback$.height();
				var setTop = (winOffset + winHeight) - (feedbackHeight);
				
				feedback$.css({position:'absolute', top: setTop + 'px', right: '0px'});
			};
			
			document$.bind('touchmove', function(event) {
		    	feedback$.hide();
		    });
		    document$.bind('touchend touchcancel', function(event) {
		    	setTimeout(function(){
		    		calcPos(); 
		    		feedback$.fadeIn('fast');
	    		},500);
		    });
			window$.bind('orientationchange scroll', function(){
		    	setTimeout(function(){
		    		calcPos(); 
	    		},500);				
			});
			
    	})();
	};
	
	///////////////////////////////////////////////
	// Social ticker menu
	///////////////////////////////////////////////
	$('.dex1-social-feed').jCarouselLite({
		auto: 		100,
		speed: 		100,
		circular: 	true,
		btnGo: 		[
		       		 ".dex1-social-menu .1", 
					 ".dex1-social-menu .2",
					 ".dex1-social-menu .3"
					],
		visible: 	1
	});
	
	///////////////////////////////////////////////
    // Marketing Tools Tabs
    ///////////////////////////////////////////////
    if($(".dex1-marketing-tools-tabs").length > 0) {
    	$(".dex1-marketing-tools-tabs").organicTabs();
    }
	
	///////////////////////////////////////////////
	// select box
	///////////////////////////////////////////////
	if($('.dropdown').length > 0){ //test for targeted selectbox elements
		(function($){
			$dropdowns = $('.dropdown');
			$dropdowns.selectbox({ //initialize the selectbox plugin
				onChange: function (val, inst) { //select change event callback
					location.href = val; //redirect the browser to the selected element address
				}
			});
			$('html').live('mousedown', function(e){ //catch all clicks 
				e.stopPropagation(); //prevent action from click
				$dropdowns.selectbox('close'); //close selectbox
			});
			$('.sbHolder, .sbSelector').mousedown(function(e){ //seperate general clicks from clicks withing selectbox
				e.stopPropagation(); //prevent action from click
			});
		})(jQuery);
	};
	
});

//Execute any functions after the page load is complete
$(window).load( function() {
	//Set Equal Column Heights
	if($('.dex1-bifurcation').length){
		$('.dex1-bifurcation').equalHeight();
	}
	
	//Trying to fix for header
	//console.log( $('h1:not(.no-cufon)').length  );
	//Cufon.now();
	//Cufon.replace('h1:not(.no-cufon)');
});

