
/* Generic functions
--------------------------------------------------------------- */
	
_ = function(p){
    if(window.console) {
        console.log(p);
    }
}
	
/* Pseudo target blank on class="blank" links
    ----------------------------------------------------------- */
$.fn.addTargetBlank = function() {
    $(this).click(function(){
        window.open(this.href);
        return false;
    });
};
// same stuff on sIFR
$.fn.sifrTargetBlank = function() {
    $(this).children('a.blank').attr("target","_blank");
    return false;
};
	
/* Navigation
	----------------------------------------------------------- */
	
function switch_tabs(obj) {
    $('.tab-content').hide();
    $('.tabs a').removeClass("selected");
    var id = obj.attr("rel");
    $('#'+id).show();
    obj.addClass("selected");
}
	
/* Mixed content rollover
    ----------------------------------------------------------- */
$.fn.prepareLinks = function() {
    $(this).live('click',function(){
        var href = $(this).find('a').attr("href");
        document.location.href = href;
        return false;
    });
		
    $(this).live('mouseover',function(){
        $(this).addClass('hover');
    });
    $(this).live('mouseout',function(){
        $(this).removeClass('hover');
    });
};
	
/* Inputs setup (empty onfocus, fill onblur
    ----------------------------------------------------------- */
$.fn.prepareFields = function() {
    this.labelEl = $("label[for='"+$(this).attr('name')+"']");
    this.oldval;
    this.newVal = this.labelEl.html();
			
    if(this.newVal != null) $(this).val(this.newVal);
    this.labelEl.addClass('hide');
		
    $(this).focus(function(){
        this.oldval = $(this).val();
        $(this).val('');	
			
        $(this).blur(function(){
            if($(this).val() == ''){
                $(this).val(this.oldval);		
            }
        });	
    });
};

/* JS drop-downs
    ----------------------------------------------------------- */
$.fn.prepareDD = function() {
    var dd = $(this);
		
    dd.each(function(){
        var cur = $(this);
        cur.sel = $(this).find('span');
        cur.ul = $(this).find('ul');
			
        cur.openDD = function(e){
            cur.addClass('active');
            cur.ul.removeClass('hide');
            $('#pageContent input.remove').addClass('hide');
            return false;
        };
        cur.closeDD = function(e){
            cur.removeClass('active');
            cur.ul.addClass('hide');
            $('#pageContent input.remove').removeClass('hide');
            return false;
        };
			
        cur.sel.hover(
            function(){
                cur.addClass('rollin');
            },
            function(){
                cur.removeClass('rollin');
            }
            );
        cur.sel.bind('click',function(){
            cur.openDD();
        });
        cur.children('.list').bind('mouseleave',function(){
            cur.closeDD();
        });
		
        cur.find('a').click(function(e){
            txt = $(this).text();
            cur.sel.attr('class', $(this).attr('id')) ;
            cur.sel.text(txt);
            cur.closeDD();
            return false;
        });
			
    });
}	


/* HOMEPAGE
--------------------------------------------------------------- */
	
/* JW Player setup
    ----------------------------------------------------------- */
// variables initialization
if($('#home')){
    var player = null;
    var oldContent = '';
    var playing = false;
    var videoLink = '.slider a.video';
    var fvideo = Object();
}
	
function setFlash(el){
    var fId = el.find('a').attr('rel');
    var params = {
        'wmode':'transparent'
    };
    var flashvars = {};	
		
    url = String(window.location);
    flashvars.lang = (url.indexOf('/en/') != -1)? "en" : "fr";
		
    flashvars.categorie = el.find('a').attr('class');
		
    flashvars.texte = el.find('.txt1').html();
    flashvars.texte2 = el.find('.texte2').html();
    flashvars.reponse = el.find('.reponse').html();
		
    //_(flashvars.texte);
    flashvars.duree = el.find('.duree').html();
    flashvars.image_url = el.find('.bg').html();
    flashvars.target_url = el.find('a').attr('href');
		
    // remplacement flash
    el.find('a').html('<div id="'+fId+'"><\/div>');
    swfobject.embedSWF("/js/module-accueil.swf", fId, "570", "426", "9.0.0", false, flashvars, params, false);
}
	
// dymanically replaces the content of a link with a video player
function startVideo(){
    if(playing && !this.current){
        stopAll(); // let us stop running videos before starting a new one
    }
    if(!playing){
        this.current = true;
        playing = true;
        oldContent = $(this).html();
        var filename = $(this).attr('href');
        $(this).html('<div id="flash_holder"><\/div>');
        // swfobject replacement -- controlbar:'none'
        var videovars = {
            id:'flash_holder',
            skin:"/js/stylish_slim.swf",
            autostart:false,
            file:filename,
            playerready:playerReady
        };
        var videoparams = {
            wmode:'transparent',
            play:'true',
            allowscriptaccess:'always',
            bgcolor:'#000000'
        };		
        swfobject.embedSWF("/js/player.swf", "flash_holder", "569", "426", "9", "/Commun/js/swfobject/2.1/expressInstall.swf", videovars, videoparams);
    }
    return false;
}
	
// stops the video and replaces it with the original content
function stopAll(obj){
    playing = false;
    cur = $(player).parents('.bloc');
    cur.empty().append($(fvideo.oldContent).html());
    setFlash(cur);
}
	
// callback for jw player instanciation
function playerReady(obj){
    //alert('the videoplayer '+obj['id']+' has been instantiated');
    player = document.getElementById(obj['id']);
		
    player.sendEvent('PLAY', true);
    player.addModelListener('STATE', 'stateMonitor');
		
//$(videoLink).bind('mouseleave',stopAll);
}

	
// event monitoring
function stateMonitor(obj){
    switch(obj.newstate){
        case 'COMPLETED': // if the video ended, put back the original content
            stopAll();
            break;
    /* Ha Ah! I knew we'd put the pause function back in :P
			case 'PAUSED': // someone asked to remove the pause function
				player.sendEvent('PLAY', true);
				break;
			*/
    }
}

function isCodePostalValid(codePostal) {
    var reg = /^[A-Za-z][0-9][A-Za-z][0-9][A-Za-z][0-9]$/
    return reg.test(codePostal);
}

function isPhoneValid(phone) {
    var reg = /^\d{3}-\d{3}-\d{4}$/
    return reg.test(phone);
}
	
function isEmailAddr(email) {
    var result = false
    var theStr = new String(email)
    var index = theStr.indexOf("@");
    if (index > 0)
    {
        var pindex = theStr.indexOf(".",index);
        if ((pindex > index+1) && (theStr.length > pindex+1))
            result = true;
    }
    return result;
}

	
/* JS drop-downs
    ----------------------------------------------------------- */
$.fn.prepareDD = function() {
    var dd = $(this);
		
    dd.each(function(){
        var cur = $(this);
        cur.sel = $(this).find('span');
        cur.ul = $(this).find('ul');
			
        cur.openDD = function(e){
            cur.addClass('active');
            cur.ul.removeClass('hide');
            $('input.remove').addClass('hide');
            return false;
        };
        cur.closeDD = function(e){
            cur.removeClass('active');
            cur.ul.addClass('hide');
            $('input.remove').removeClass('hide');
            return false;
        };
			
        cur.sel.hover(
            function(){
                cur.addClass('rollin');
            },
            function(){
                cur.removeClass('rollin');
            }
            );
        cur.sel.bind('click',function(){
            cur.openDD();
        });
        cur.children('.list').bind('mouseleave',function(){
            cur.closeDD();
        });
		
        cur.find('a').click(function(e){
            txt = $(this).text();
            cur.sel.attr('class', $(this).attr('id')) ;
            cur.sel.text(txt);
            cur.closeDD();
            return false;
        });
			
    });
};




	
/* GLOBAL FUNCTION CALLS
--------------------------------------------------------------- */
	
	
$(document).ready(function() {
	
    $('body').addClass('js-active'); // graceful degradation of some advanced functionalities
    $('a.blank').addTargetBlank(); 	 // calls $.fn.addTargetBlank
    $('#pageContent .rollover').prepareLinks(); // calls $.fn.addTargetBlank
		
    // calls $.fn.prepareFields for each field
    $('input.text, input.datepicker').each(function(){
        $(this).prepareFields();
    });
		
		
    $('#newsletter').submit(function(e){
        var succes = true;
        var msg = '';
        var fullname = $('#fullname').val();
        var courriel = $('#email').val();
        if (fullname == 'Nom' || fullname == '') {
            succes = false;
            msg += "- Veuillez inscrire votre nom\n";
        }
        if (courriel == '' || courriel == 'Courriel') {
            succes = false;
            msg += "- Veuillez inscrire votre courriel\n";
        } else {
            if (!isEmailAddr(courriel)) {
                succes = false;
                msg += "- Veuillez inscrire un courriel valide\n";
            }
			 	
        }
        if (succes) {
            Shadowbox.open({
                player:'iframe',
                content:$(this).attr('action'),
                width:600
            });
            e.preventDefault();
        } else {
            alert(msg);
            return false;
        }
    });
		
    $('.tabs a').hover(function(){
        switch_tabs($(this));
    });
 
    switch_tabs($('.defaulttab'));
		
    $('#rollout').mouseout(function(){
        switch_tabs($('.defaulttab'));
    }
    );
		
	
    // setup ul.tabs to work as tabs for each div directly under div.panes
    $("ul.jq-tabs").tabs("div.panes > .tabs-div");
				
		
    // initialize tooltip JQUERY TOOLS
    $(".popup[title]").tooltip({
		
        position: 'top center',
        effect: 'slide'
		
    // add dynamic plugin with optional configuration for bottom edge
    }).dynamic({
        bottom: {
            direction: 'down', 
            bounce: true
        }
    });

		
    // permet la recherche simple et avancé
    $('.advancedSearch').hide();
		
    $('.closed').click(function(){
        $('.simpleSearch').hide();
        $('.advancedSearch').css('display','block');
    });
		
    $('.opened').click(function(){
        $('.advancedSearch').hide();
        $('.simpleSearch').css('display','block');
    });
		
    $('#RSSbtn').click(function(e){
        e.preventDefault();
        $("#popupFooter").fadeIn(400);
    });
		
    $('#popupFooter').mouseenter(function(e){
        $(this).mouseleave(function(e){
            $(this).fadeOut(400);
        });
    });
		
		
});

