/*global jQuery, sIFR, swfobject, pageTracker */
/*JSLint Strict */

$('html').addClass('js');

// swfObject 2.1
if (typeof(window.swfobject) !== "undefined") {
	swfobject.registerObject("video", "9.0.28", "");
	swfobject.registerObject("grille", "9.0.28", "");
}

// sIFR v3 r436
if (typeof(window.sIFR) !== "undefined") {
	var memphis = {
		src: '/swf/memphis.swf'
	};
	sIFR.activate(memphis);
	sIFR.replace(memphis, {
		selector: 'h1:not(.animateur)',
		css: {
			'.sIFR-root': {
				'color': '#096273',
				'font-size': '16px',
				'leading': '-6px',
				'letter-spacing': '+1',
				'text-transform': 'uppercase'
			},
			'.lite': {
				'color': '#159bb9'
			},
			'.big': {
				'font-size': '23px',
				'color': '#159bb9'
			},
			'.bigo': {
				'font-size': '23px'
			}
		},
		tuneHeight: -5,
		wmode: 'opaque'
	});
	sIFR.replace(memphis, {
		selector: 'strong.section',
		css: {
			'.sIFR-root': {
				'color': '#096273',
				'font-size': '13px',
				'leading': '-6px',
				'letter-spacing': '+1',
				'text-transform': 'uppercase'
			},
			'.lite': {
				'color': '#159bb9'
			},
			'.big': {
				'font-size': '20px',
				'color': '#159bb9'
			}
		},
		tuneHeight: -5,
		wmode: 'opaque'
	});
	sIFR.replace(memphis, {
		selector: 'h3:not(.link)',
		css: {
			'.sIFR-root': {
				'color': '#D19357',
				'font-size': '13px',
				'leading': '-5px',
				'letter-spacing': '+1',
				'text-transform': 'uppercase'
			},
			'.grey': {
				'color': '#666666'
			}
		},
		wmode: 'transparent',
		tuneHeight: -3
	});
}

// On DOM Ready
jQuery(function ($) {

/*  -------------------------------------------------------
    Ajax
    ------------------------------------------------------- */
	/**
	 * Apply changes from a xml
	 * @param {String} xml
	 * @param {Object} context
	 */
    function applyXMLChanges(xml, context) {
        $(xml).find('change').each(function () {
            var selector = $(this).find('target').text();
            var value = $(this).find('value').text();

			// prevent the accidental selection of document root.
            if (!selector) {
				return false;
			}
			
			// Allow the modification of the container
            var $target = selector === ':context' ? $(context) : $(selector, context);
            switch ($(this).attr('type'))
            {
            case 'append':
                $target.append(value);
                break;

			case 'prepend':
                $target.prepend(value);
                break;
			
            case 'replace':
                $target.replaceWith(value);
                break;

			case 'remove':
                $target.remove();
                break;

            case 'attr':
                var attr = $(this).find('attr').text();
                $target.attr(attr, value);
                break;
            }
			return true;
        });
		$('ul.errors a')
			.unbind('click.focusTool')
			.bind('click.focusTool', function () {
				$(this.hash).focus();
				return false;
			});
    }

	/* Gestion des formulaires en ajax */
	function ajaxSubmit() {
		var form = this;
		$.ajax({
			type: 'post',
			url: this.action,
			dataType: 'xml',
			data: $(this).serialize() + '&isAjax=1',
			success: function (xml) {
				applyXMLChanges(xml);
				pageTracker._trackPageview(this.action+'/submit');
			},
			error: function (err, data) {
				console.log(err, data);
			}
		});
		return false;
	}
	
	// Survey on accueil
	$('#frm_sondage, #frm_subscribe').submit(ajaxSubmit);
	
/*  -------------------------------------------------------
    Fonctions pour les popins
    ------------------------------------------------------- */	
	/**
	 * Effectue tout les opérations requises pour afficher un popin passé en paramètre
	 * @param {String} html
	 */
	function buildPopin(html)
    {
        var $popin = $(html).appendTo('#wrap').verticalCenter();

        if (!$('#bgcover').size()) {
            var $cover = $('<div id="bgcover">&nbsp;</div>').appendTo('#wrap').css('opacity', '0.6');
            if ($.browser.msie && $.browser.version <= 6) {
                $cover.before($('<iframe id="bgiframe"></iframe>').css('opacity', '0'));
            }
        }

        $('body').addClass('with_popin');
		
		$('form', $popin).submit(ajaxSubmit);
		
		$('a.b_close', $popin).click(function () {
			$(this).parents('div.popin').remove();
	        $('#bgcover, #bgiframe').remove();
	        $('body').removeClass('with_popin');
	        return false;
		});
		
        return $popin;
    }
	
	/* Extension jQuery
    * Place un popin au centre de l'écran */
    $.fn.verticalCenter = function () {
        return $(this).each(function () {
            var innerHeight;
            if (typeof window.innerWidth === 'number') {
                innerHeight = window.innerHeight;
            }
			else {
                innerHeight = $(window).height();
            }
            var minTop = $().scrollTop() + 36;
            var top = $().scrollTop() + innerHeight / 2 - $(this).height() / 2;
            if (top < minTop)
            {
                top = minTop;
            }
            $(this).css('top', top + 'px');
        });
    };
	
	$('a.b_popin').click(function (e) {
		sHref = this.href;
		$('div.popin a.close').click();
        $.ajax({
            url: sHref,
			data: 'isAjax=1',
            type: 'post',
            success: function (resp)
            {
				pageTracker._trackPageview(sHref);
                var $popin = buildPopin(resp);
            }
        });
        return false;
	});

/*  -------------------------------------------------------
    Other functions
    ------------------------------------------------------- */
	// Link click on row click
	$('#enonde tr').addClass('js').click(function () {
		window.location = $('a', this).attr('href');
	});
	
	// Remove accessibility items
	//$('.nojs').hide(); // fallback if "html.js .nojs" css fail.
	$('.nojs').remove();
	
	// Show js only items
	$('a.b_print').show();
	
	// Open external links in new window
	$('a[@rel=external]')
		.click(function () {
			return !window.open(this.href);
		})
		.attr('title', 'ouvre dans une nouvelle fenêtre');
	
	// Gérer les dropdown switcher en ajax
	$('form.switcher select').change(function () {
		var form = $(this).parents('form').get(0);
		var val = $(this).val();
		if (val !== '') {
			location = form.action + '/' + this.name + '/' + val;
		}
		else {
			location = form.action;
		}
	});
	
	// Rollover sur boutton
	$('input:image, img.rollover').bind('mouseover focus', function () {
		this.src = this.src.replace(/(?:_o)?\.([a-z]*)$/i, "_o.$1");
	}).bind('mouseout blur', function () {
		this.src = this.src.replace(/_o\./i, ".");
	});
	
	// Changer le video dans une page d'épisode
	$('a.switchVideo').click(function (ev) {
		ev.preventDefault();
		var video = $(this).attr('href');
		pageTracker._trackPageview('/video/' + video);
		scrollTo(0,150);
		if ($('#video')[0].switchVideo) {
			$('#video')[0].switchVideo(video);
		}
		else if ($('#video2')[0].switchVideo) {
			$('#video2')[0].switchVideo(video);
		}
	});
	
	/* Focus on errors link click */
	$('ul.errors a').bind('click.focusTool', function () {
		$(this.hash).focus();
		return false;
	});
	
	/* Emissions popin menu */
	if (typeof($().hoverIntent) === "function") {
		$('#nav_emissions').hoverIntent(
			function () {
				$('#subnav').slideDown('fast');
			},
			function () {
				$('#subnav').slideUp('fast');
			}
		);
	}
	
	// Rollover sur menu navigation de premier niveau
	$('#nav > li > a').addClass('js').css('opacity', 0).bind('mouseover focus', function () {
		$(this).stop().animate({
			opacity: 1
		}, 500);
	}).bind('mouseout blur', function () {
		$(this).stop().animate({
			opacity: 0
		}, 500);
	});
	
	$('#cta_share a').bind("click", function (event) {
		event.preventDefault();
	    var size, which = this.className.replace('b_', '');
	    switch (which) {
	    case 'facebook':
	        size = "width=620,height=436";
	        break;
	    case 'google':
	        size = "width=740,height=724";
	        break;
	    case 'delicious':
	        size = "width=725,height=400";
	        break;
	    case 'reddit':
	        size = "width=670,height=560";
	        break;

	    default:
	        size = "width=500,height=500";
	    }
	    var my_popup = window.open($(this).attr("href"), "share_" + which, "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no," + size);
	    if (my_popup) {
	        my_popup.focus();
	    }
	    return !my_popup;
    });
});
