/*  ------------------------------------------------------------------
    Language detector ------------------------------------------------ */ 
    var lang = window.location.href;
    if(lang.match("consommezassez")) {
        lang = "fr";
        url = "consommezassez";		
    }else {
        lang = "en";
		url = "getenough";
    }
    
$(function(){

/*  ------------------------------------------------------------------
    Remove default value on Focus ------------------------------------ */
	$("input[@type*='text'][title]:not('.required')")
	.bind("focus",function(){ if(this.value==this.title){ this.value=""; } })
	.bind("blur",function(){ if(this.value==""){ this.value=this.title; } });   
    
    
/*  ------------------------------------------------------------------
    External Link ---------------------------------------------------- */
    var allowedDomains = [location.hostname, 'getenough.ca', 'consommezassez.ca'];
    $("a[href^=http]:not(.internal)")
    .filter(function(el){
        for ( var i=0; i < allowedDomains.length; i++ ) {
            if ( this.href.indexOf(allowedDomains[i])>-1 ) return false;
        }
        return true;
    })
    .bind("click", function(){ return !window.open(this.href); });
    
    $('a[rel=external]').live('click', function(e){
        e.preventDefault(); 
        open(this.href);
    });
    
    
/*  ------------------------------------------------------------------
    Ask our dietitian ------------------------------------------------ */   
    $('#b_ask-your-question').click(function(e){
        e.preventDefault();
        swfobject.embedSWF('/' + url + "/flash/Preload.swf", "contentHTML", "668", "430", "9.0.0", '/' + url + "/flash/expressInstall.swf", flashvars, params, attributes);        
    });
        
        
/*  ------------------------------------------------------------------
    Activate FAQ functionality --------------------------------------- */    
    $('#faq_categories a').faqToggle(); 
    $('.faq_list').faqExpander();
    
    
/*  ------------------------------------------------------------------
    Homepage carousel ------------------------------------------------ */
    if($('#section_carousel').exists() || $('#didyouknow_carousel').exists()){
        $('#section_carousel').jcarousel({
            auto: 7,
            animation: 250,
            wrap: 'both',
            start: 3,
            scroll: 1,
            buttonNextHTML: null,
            buttonPrevHTML: null,
            initCallback: section_carousel_initCallback,
            itemVisibleInCallback: section_carousel_itemVisibleInCallback
        });
        
        $('#didyouknow_carousel').jcarousel({
            auto: 0,
            start: 1,
            scroll: 1,
            buttonNextHTML: null,
            buttonPrevHTML: null,
            initCallback: didyouknow_carousel_initCallback,
			itemVisibleInCallback: didyouknow_carousel_itemVisibleInCallback
        });
    }; 
    
    
/*  ------------------------------------------------------------------
    Why Milk products search ----------------------------------------- */   
    if($('#frm_search').exists()){
        $('#frm_search').submit(function(){
            action = $(this).attr('action') + '#' +$('#inp_search').val().toLowerCase();
            $(this).attr('action', action);       
        });  
        var terms = (lang == 'fr') ? indexTerms_fr : indexTerms; // load the corresponding keywords based on the lang
        $('#inp_search').autocomplete(terms, {
            width: 136,
            max: 6,
            highlight: false,
            multiple: true,
            multipleSeparator: " ",
            scroll: true,
            scrollHeight: 300
        });
    };

    
/*  ------------------------------------------------------------------
    AIGE submenu Flash interaction ----------------------------------- */ 
    $('#m_aige .subNav li:not(#sm_age) a').each(function() {
        $(this).click(function(e) {
            if(!$(this).parent().hasClass('disabled')) { // don't change section if the section clicked on is disabled
                section = $(this).parent().attr('id').substr(3);
                swfobject.getObjectById("contentFlash").mealSteps(section); // Flash listenner to send the Flash module to the right section
            }
            e.preventDefault();    
        });
    });
    
    
/*  ------------------------------------------------------------------
    SmartColumns for recipes footer ---------------------------------- */    
    $(window).resize(function (){         
        /*SmartColumns*/
        $("#list_recipes").smartColumns();
    }).resize();
        
    /* recipes footer navigation */
    $('#recipeNav a').each(function() {
        $(this).click(function(e) {
            $('#loader').show();
            $('#list_recipes').load('/' + url + '/ajax/'+$(this).parent().attr('id'), {}, function() {
                $('#list_recipes a').each(function(){
                    $(this).attr("rel", "external");
                });
                
                $('#list_recipes').smartColumns();
                $('#loader').hide();
            });
            $('#recipeNav li').each(function(){
                $(this).removeClass('selected');
            });
            
            $(this).parent().addClass('selected');
            e.preventDefault();    
        });   
    });
	
});


/*  ------------------------------------------------------------------
    YouTube player ready --------------------------------------------- */ 
	function onYouTubePlayerReady(playerId) {
		ytplayer = document.getElementById("myytplayer");
		
		$('#video_list a').each(function() {
			$(this).click(function(e) {	
				ytplayer.loadVideoById($(this).attr('rel'));
				$('#video_title').text($(this).attr('title'));
				e.preventDefault();    
			});   
		});
	}
	

/*  ------------------------------------------------------------------
    jQuery exists method --------------------------------------------- */ 
    jQuery.fn.exists = function(){return jQuery(this).length>0;}

/*  -------------------------------------------------------------------
    Vignettes recipes ------------------------------------------------- */
$(document).ready(function() {
			$('.content-vignette .tab-01:last-child').hide();
			$('.tabNav.vignette .first').addClass('selected')
			
			$('.tabNav.vignette .first').click(function(){
				$('.tabNav.vignette .second').removeClass('selected');
				$(this).addClass('selected')
				$('.content-vignette #tab-container .tab-01:last-child').hide();
				$('.content-vignette #tab-container .tab-01:first-child').fadeIn();
            return false;
			});
			
			$('.tabNav.vignette .second').click(function(){
				$('.tabNav.vignette .first').removeClass('selected');
				$(this).addClass('selected')
				$('.content-vignette #tab-container .tab-01:first-child').hide();
				$('.content-vignette #tab-container .tab-01:last-child').fadeIn();
            return false;
			});

});
/*  ------------------------------------------------------------------
    FAQ expander ----------------------------------------------------- */ 
    $.fn.faqToggle = function(options) {
        var status = 1; 
        $('#aod dl:not(#aod dl:first)').hide();
        return this.each(function() {
            $(this).click(function(e) {
                var index = $('#faq_categories a').index(this);
                e.preventDefault();
                $('.faq_list').hide();
                $('.faq_list:eq('+index+')').show();
                $('#faq_categories a').removeClass('selected');
                $(this).toggleClass('selected');
                // WebTrends : track the first time the user click on a FAQ category
                if(status) {
                    var eventKeyword = '';
                    if(lang == 'fr') {
                        eventKeyword = 'AskaDietitian/FaqFR';
                    }else{
                        eventKeyword = 'AskaDietitian/Faq';                 
                    }
                    dcsMultiTrack(
                        'DCS.dcsuri', eventKeyword,        // name/value pair for URL
                        'WT.ti', eventKeyword              // name/value pair for page title
                    );
                }
                status = 0;
            });                 
        });
    };
    
    $.fn.faqExpander = function(options) { 
        return this.each(function() {
            var dl_list = $(this);
            $('dd', $(this)).hide(); 
            $('dt', $(this)).click(function() {
                var status = $(this).next().css('display');     
                if(status != 'block') {     
                    $(this).next().slideDown();
                    $('.anchor', $(this)).text('-');
                }else {
                    $(this).next().slideUp();
                    $('.anchor', $(this)).text('+');
                }
            }).css('cursor', 'pointer').prepend('<span class="anchor">+</span>');                 
        });
    };


/*  ------------------------------------------------------------------
    Section carousel actions ----------------------------------------- */
    function section_carousel_initCallback(carousel) {
        $('#mainNav a.toplink').mouseover(function() {
            carousel.scroll($.jcarousel.intval($('#mainNav a.toplink').index(this)+1));
            carousel.options.auto = 0;
            carousel.options.animation = 0;
            $('#mainNav li').removeClass('active');
            $(this).parent().addClass('active');
            $('#mainNav').stopTime('autocarousel');
        });
        
         /* restart the carousel after 10 seconds of inactivity from the user */
        $('#mainNav').mouseleave(function() {
            $(this).oneTime('10s', 'autocarousel', function() {
                carousel.options.auto = 7;
                carousel.options.animation = 250;
                carousel.next();
            });    
        });
    };
    
    function section_carousel_itemVisibleInCallback(carousel, item, idx, state) {  
        if(carousel.options.auto != 0) {
            $('#mainNav li').removeClass('active');
            switch(idx) {
				case 1:
                  $('li#m_game').addClass('active');
                  break;
                case 2:
                  $('li#m_aige').addClass('active');
                  break;
                case 3:
                  $('li#m_wmp').addClass('active');
                  break;
                case 4:
                  $('li#m_wie').addClass('active');
                  break;
                case 5:
                  $('li#m_aod').addClass('active');
                  break;
                case 6:
                  $('li#m_makethepledge').addClass('active');
                  break;
            }                  
        }
    };   


/*  ------------------------------------------------------------------
    Did you know carousel controls ----------------------------------- */
    function didyouknow_carousel_initCallback(carousel) {
        $('#b_next').bind('click', function() {
            carousel.next();
            return false;
        });

        $('#b_previous').bind('click', function() {
            carousel.prev();
            return false;
        });        
    };
	
	function didyouknow_carousel_itemVisibleInCallback(carousel, item, idx, state) {
		switch(idx) {
			case 1:
				$('#b_previous').hide();
				$('#b_next').show();
				break;
			case 8:
				$('#b_previous').show();
				$('#b_next').hide();
				break;
			default:
				$('#b_next').show();
				$('#b_previous').show();
				break;
		} 
	};


/*  ------------------------------------------------------------------
    Smart Columns ---------------------------------------------------- */
    $.fn.smartColumns = function(options) {
        return this.each(function() {
            $list = $(this);
            $list.show();
            $list.css({'width':"100%"});
        
            var colWrap = $list.width();
            var colNum = Math.floor(colWrap / 240);
            var colFixed = Math.floor(colWrap / colNum);
            var rowFixed = Math.floor(colFixed / 1.36);
        
            //alert("colFixed:" + colFixed + "   rowFixed:" + rowFixed  +"   colWrap:" + colWrap);
        
            $list.css({'width':colWrap});
            $("li", $list).css({'width':colFixed, 'height':rowFixed });
            
            /*Rollover Block*/
            $("li", ".list_smartcolumns").hover(function(){
                $(this).children(".block_content").fadeIn(1);
            },
            function(){
                $(this).children(".block_content").fadeOut(200);
            });          
        });  
    };
    
    
/*  ------------------------------------------------------------------
    Flash interactions ----------------------------------------------- */       
    function changeSection(eventDescription){
        $('#m_aige .subNav').show();
        /* reset all states on submenu items */  
        $('#m_aige .subNav .disabled').removeClass('disabled');
        $('#m_aige .subNav .selected').removeClass('selected');
        
        /* add active state on current submenu item */
        $('#sm_' + eventDescription).addClass('selected');
        
        /* on Results section - disable every single submenu items except Age Group and Results */
        if(eventDescription == 'results') {
            $('#m_aige .subNav li:not(#sm_age, #sm_results)').each(function() {
                $(this).addClass('disabled');
            });         
        }
    }
    
    /* event tracking in Flash for WebTrends */    
    function webTrendsTracking(eventKeyword){
        dcsMultiTrack(
            'DCS.dcsuri', eventKeyword,            // name/value pair for URL
            'WT.ti', 'FlashEvent:' + eventKeyword  // name/value pair for page title
        );
    }
/*  ------------------------------------------------------------------
    HTML webtrends tracking ------------------------------------------ */       
    /* event tracking for HTML */    
    function webTrendsHtmlTracking(eventKeyword){
        dcsMultiTrack(
            'DCS.dcsuri', eventKeyword,            // name/value pair for URL
            'WT.ti', + eventKeyword  // name/value pair for page title
        );
    }
	
/*  -------------------------------------------------------------------
    Table Stripe ------------------------------------------------------ */

    $(function(){
         /*$("table.tb_stripe tr:even").addClass("stripe");	*/
         $("table.tb_stripe tr:first-child").addClass("head");
         $("table.tb_stripe tr:nth-child(2n-1)").addClass("stripe");
    });
	

