/* Shorcut jQuery pour no conflict avec Prototype.js */
var $j = jQuery.noConflict();



/* Cookies */
function set_cookie(name, value, nDays, path, domain, secure) {
	var cookie_string = name + "=" + escape(value);

	if (nDays) {
		var today = new Date();
		var expire = new Date();
		expire.setTime(today.getTime() + 3600000 * 24 * nDays);
    	cookie_string += "; expires=" + expire.toGMTString();
	}

	cookie_string += (path)   ? "; path=" + escape(path) : "";
    cookie_string += (domain) ? "; domain=" + escape(domain) : "";
	cookie_string += (secure) ? "; secure" : "";

	document.cookie = cookie_string;
}

function get_cookie(cookie_name) {
	var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');

	if (results)
		return unescape(results[2]);
	else
		return null;
}

function delete_cookie(cookie_name, path, domain) {
	var cookie_date = new Date ();	
	cookie_date.setTime(cookie_date.getTime() - 1);
	cookie_name += "=; expires=" + cookie_date.toGMTString();
	
	cookie_name += (path)   ? "; path=" + escape(path) : "";
    	cookie_name += (domain) ? "; domain=" + escape(domain) : "";	
	
	document.cookie = cookie_name;
}


function getViewport() {
	var elem = window
	var prop = 'inner';
	
	if (!('innerWidth' in window)) {
		elem = document.documentElement || document.body;
		prop = 'client';
	}
	
	return { width: elem[prop+'Width'], height: elem[prop+'Height'] }
}


function printThisPage() {
	window.print();
}

/**
 * Set max-height universel
 */
function setMaxHeight(jElement, height) {
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		// setExpression ne semble pas marcher avec les popups
		jElement.css("height", height);
	} else {
		jElement.css("max-height", height);
	}
}



/**
 * Functions pour le rollover des images
 */
var Rollover = {
    restorationHolder : new Array(),

    /**
     * onmouseout
     *
     * Plusieurs swap peut arriver en meme temps, on les restore tous
     */
    restore: function() {
		$j.each(Rollover.restorationHolder, function(index, item){
			var jElement = $j("#"+item);
			var imageSrc = jElement.data("normal");
			jElement.attr("src", imageSrc);
		});

		Rollover.restorationHolder = new Array();
    },


    /**
     * onmouseover
     *
     * imageSrc est optionnel, si elle n'est pas inclus, on fais un rollover
     * avec l'image qui a le meme nom avec "-over" de append.
     */
    swap: function(elemId, imageSrc) {
    	var jElement = $j("#"+elemId);
    	var currentImg = jElement.attr("src");

    	jElement.data("normal", currentImg);
    	jElement.attr("src", imageSrc);

    	Rollover.restorationHolder.push(elemId);
    }
}


/**
 * Changer le cursor
 */
var Cursor = {
	toDefault: function() {
		document.body.style.cursor = 'default';
	},

	toWait: function() {
		document.body.style.cursor = 'wait';
	}

}


/**
 * Le popup pour attendre le traitement
 */
var AjaxMessage = {
	message: null,
	image: null,
	initialised: false,

	init: function() {
	//	if (this.message == null || this.image == null) {
	//		alert("AjaxMessage not defined");
	//	}
		if (this.initialised == false) {
			$j("body").append("" +
				"<div id=\"loading\">" +
				"  <div class=\"label\">" + this.message + "</div>" +
				"  <div class=\"image\"><img src=\"" + this.image + "\" alt=\"Loading\" /></div>" +
				"</div>");
			this.initialised = true;
		}
	},

	show: function() {
		this.init();
		$j("#loading").show();
	},

	hide: function() {
		this.init();
		$j("#loading").hide();
	}
}


var ChannelInfoPopup = {
	title: null,
	url: null,
	elementId: "tv-channel-popup",	// ID du container principal
	elementBodyId: "tv-channel-popup-body",	// ID du container Ajax
	initialised: false,

	init: function() {
		if (this.initialised == false) {
			createOverlay(this.elementId, {'onclose': 'ChannelInfoPopup.close()', 'title': this.title, 'width': '500px'});
			$j("#" + this.elementId).css("z-index", 1000);

			this.initialised = true;
		}
	},

	load: function(articleID) {
		this.init();

		// Disable Le message
		Cursor.toWait();
		var myAjax = new jQuery.ajax({
			url: this.url,
			type: 'get',
			data: 'article=' + articleID,
			success: function(resp) {
				var jElement     = $j("#" + ChannelInfoPopup.elementId);
				var jElementBody = $j("#" + ChannelInfoPopup.elementBodyId);

				jElementBody.html(resp);

				jElement.pngFix(); // on refix la transparence pour IE6
				centerElement(ChannelInfoPopup.elementId); // on re-center l'element qui a change de dimension

				jElement.show();
			},
			error: function(resp) {
				alert("Errors: " + resp);
			},
			complete: function(resp) {
				Cursor.toDefault();
			}
		});
	},


	'close': function() {
		$j("#" + ChannelInfoPopup.elementId).hide();
	}
}


var CheckAvailabilityPopup = {
	title: "Check availability",
	elementId: "check-av-popup",	// ID du container principal
	elementBgId: "check-av-popup-bg",	// ID du container background
	elementBodyId: "check-av-popup-body",	// ID du container Ajax
	initialised: false,

	init: function() {
		if (this.initialised == false) {
			createOverlayBackground(this.elementBgId);
			createOverlay(this.elementId, {onclose: "CheckAvailabilityPopup.close()", disableCloseButton: true, 'title': this.title});
			$j("#" + this.elementId).css("z-index", 1000);

			this.initialised = true;
		}

	},

	load: function(url, params) {
		this.init();
		AjaxMessage.show();
		var myAjax = new jQuery.ajax({
			url: url,
			type: 'get',
			data: params,
			success: function(resp) {
				var jElement     = $j("#" + CheckAvailabilityPopup.elementId);
				var jElementBody = $j("#" + CheckAvailabilityPopup.elementBodyId);
				var jElementBg   = $j("#" + CheckAvailabilityPopup.elementBgId);

				jElementBody.html(resp);

				jElement.pngFix(); // on refix la transparence pour IE6
				centerElement(CheckAvailabilityPopup.elementId); // on re-center l'element qui a change de dimension

				jElementBg.show();
				jElement.show();
			},
			error: function(resp) {alert("Errors: " + resp);},
			complete: function(resp) {AjaxMessage.hide();}
		});
	},

	'close': function() {
	},

	'initClose': function() {
		$j("#" + CheckAvailabilityPopup.elementId).hide();
		$j("#" + CheckAvailabilityPopup.elementBgId).hide();
		window.location = top.location;
	}
}


var ShoppingCartRebatePopup = {
	title: "",
	elementId: "shoppingcart-rebate-popup",				// ID du container principal
	elementBgId: "shoppingcart-rebate-popup-bg",	// ID du container background
	elementBodyId: "shoppingcart-rebate-popup-body",	// ID du container Ajax
	initialised: false,

	init: function() {
		if (this.initialised == false) {
			createOverlayBackground(this.elementBgId);
			createOverlay(this.elementId, {onclose: "ShoppingCartRebatePopup.close()", 'title': this.title, width: '700px'});

			this.initialised = true;
		}
	},

	load: function(url, params) {
		this.init();

		//Cursor.toWait();
		$j("#" + this.elementBgId).show();
		var myAjax = new jQuery.ajax({
			url: url,
			type: 'get',
			data: params,
			success: function(resp) {
				var jElement     = $j("#" + ShoppingCartRebatePopup.elementId);
				var jElementBody = $j("#" + ShoppingCartRebatePopup.elementBodyId);
				var jElementBg   = $j("#" + ShoppingCartRebatePopup.elementBgId);

				jElementBody.html(resp);

				jElement.pngFix(); // on refix la transparence pour IE6
				centerElement(ShoppingCartRebatePopup.elementId); // on re-center l'element qui a change de dimension

				jElementBg.show();
				jElement.show();
			},
			error: function(resp) {
				alert("Errors: " + resp);
			},
			complete: function(resp) {
				//Cursor.toDefault();
			}
		});
	},

	close: function() {
		$j("#" + ShoppingCartRebatePopup.elementId).hide();
		$j("#" + ShoppingCartRebatePopup.elementBgId).hide();
	}
}


function changeFontSize(size) {
	$j(".font-size").removeClass("font-size-selected");

	if (size == 'small') {
		set_cookie("fontSize", size, '', '/', '' ,'');
		jQuery("body").css("font-size", "11px");
		$j("#fontSizeSmall").addClass("font-size-selected");
	}
	if (size == 'normal') {
		delete_cookie("fontSize",'/','');
		jQuery("body").css("font-size", "12px");
		$j("#fontSizeNormal").addClass("font-size-selected");
	}
	if (size == 'large') {
		set_cookie("fontSize", size, '', '/', '' ,'');
		jQuery("body").css("font-size", "13px");
		$j("#fontSizeLarge").addClass("font-size-selected");

	}
}



/**
 * Function pour centrer un element au centre de la fenetre
 */
function centerElement(elementId) {
	var jElement = jQuery("#" + elementId);

	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		/**
		 * IE6 ne supporte pas position fixed;
		 * note: on le place dans le body a cause de position:absolute doit etre par rapport au body
		 */
		jElement.prependTo($j("body"));
		jElement.css("position", "absolute");
		jElement.get(0).style.setExpression('top', 'document.documentElement.scrollTop + (document.documentElement.clientHeight - this.clientHeight) / 2');
		jElement.get(0).style.setExpression('left', 'document.documentElement.scrollLeft + (document.documentElement.clientWidth - this.clientWidth) / 2');
	} else {
		jElement.css("position", "fixed");
		jElement.css("left", "50%");
		jElement.css("top", "50%");
		jElement.css("margin-top", jElement.height() / 2 * -1);
		jElement.css("margin-left", jElement.width() / 2 * -1);
	}
}


function keepElementInViewport(elementId) {
	// Keep inside viewport
	viewport = getViewport();
	
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		var dims = getElementDimensions(elementId);
		// setExpression ne semble pas marcher avec les popups
		if (dims.height > viewport.height - 50) {
			$j("#" + elementId + "-body").css("height", viewport.height - 100);
			$j("#" + elementId + "-body").css('overflow', 'auto');
		}
		if (dims.width > viewport.width - 50) {
			$j("#" + elementId).css("width", viewport.width - 50);
		}
	} else {
		$j("#" + elementId + "-body").css("max-height", viewport.height - 100);
		$j("#" + elementId).css("max-width", viewport.width - 50);
		$j("#" + elementId + "-body").css('overflow', 'auto');
	}
}


/**
 * Contourner les elements qui ont un style display:none, qui n'ont pas de dimension tant qu'il ne sont pas encore visible
 */
function getElementDimensions(elementId) {
	var jElement = $j("#" + elementId);
	if (jElement.css('display') == 'none') {
		jElement.css({visibility: 'hidden', display: 'block'});
		var dims = {width: jElement.width(), height: jElement.height()};
		jElement.css({display: 'none', visibility: 'visible'});
	} else {
		var dims = {width: jElement.width(), height: jElement.height()};
	}
    return dims;
}


function createOverlayBackground(elementId, options) {
	var jElement;

	// Test si ca existe, si non, on le cree
	jElement = $j("#" + elementId);
	if (jElement.size() == 0) {
		// ligne du body
		$j("body").prepend("<div id=\"" + elementId + "\" style=\"display: none\"></div>");

		jElement = $j("#" + elementId);
		if (jQuery.browser.msie && jQuery.browser.version < 7) {
			jElement.css("position", "absolute");
			jElement.css("left", "0");
			jElement.css("top", "0");
			jElement.css("height", document.body.offsetHeight);
		} else {
			jElement.css("position", "fixed");
			jElement.css("left", "0");
			jElement.css("top", "0");
			jElement.css("height", "100%");
		}
		jElement.css("background", "#000");
		jElement.css("opacity", "0.5");
		jElement.css("width", "100%");
		jElement.css("z-index", 99);
	}
}


/**
 * Si le id n'existe pas deja, la function cree lui-meme un wrapper autour.
 *
 * options:
 *   onclose : (hide|remove|disabled) or javascriptString; default is hide
 *   body : string
 *   className : string (Style class name)
 */
function createOverlay(elementId, options) {
	this.jElement = null;

	var str = "";
	var testExistId = false;

	options           = options           || {};
	options.onclose   = options.onclose   || "hide";
	options.disableCloseButton = options.disableCloseButton   || "false";
	options.className = options.className || "rp-darkblue";
	options.body      = options.body      || " ";
	options.title     = options.title     || " ";
	options.center    = Boolean(options.center)  || null;
	options.visible   = Boolean(options.visible) || null;
	options.width     = options.width     || null;
	options.height    = options.height    || null;
	

	// Strings
	var overlayCloseBtn  = overlayCloseBtn   || "Close";

	
	// Test si ca existe
	this.jElement = $j("#" + elementId);
	if (this.jElement.size() > 0) {
		testExistId = true;
		options.body = this.jElement.html();
	}

	// ligne du body
	if (testExistId != true) {
		$j("body").prepend("<div id=\"" + elementId + "\" class=\"" + options.className + "\" style=\"display: none\"></div>");
	}

	this.jElement = $j("#" + elementId);


	// Si c'est deja initialized on ne la recree pas.
	init = jElement.data("initialized");
	if (init == true) {
		return; // On a deja cree le overlay
	} else {
		jElement.data("initialized", true);
	}


    // Gestion du Close
	var closeAction = null;
	if (options.onclose != "disabled") {
		if (options.onclose == "remove")      { closeAction = "$j('#" + elementId + "').remove()"; }
		else if (options.onclose == "hide")   { closeAction = "$j('#" + elementId + "').hide()"; }
		else                                  { closeAction = options.onclose; }
	}

	str +=  "<table class=\"rp\">" +
			"<tr>" +
			"	<td class=\"rp-tl\"></td>" +
			"	<td class=\"rp-top\">";

			if (closeAction) {
				str += "<div class=\"rp-close\" onclick=\"" + closeAction + "\" />";
			}

	str +=  "<h1>" + options.title + "</h1>" +
			"</td>" +
			"	<td class=\"rp-tr\"></td>" +
			"</tr><tr>" +
			"	<td class=\"rp-left\"></td>" +
			"	<td class=\"rp-middle\"><div id=\"" + elementId + "-body\" class=\"rp-body\">" + options.body + "</div>";

			if (closeAction && !options.disableCloseButton) {
				str += "<div style=\"text-align:right; padding: 5px;\">";
				str += "<a href=\"javascript:void(0)\" onclick=\"" + closeAction + "\" class=\"rbtn rbtn-blue\"><span>"+ overlayCloseBtn +"</span></a>";
				str += "</div>";
			}

	str +=  "   </td>" +
			"	<td class=\"rp-right\"></td>" +
			"</tr><tr>" +
			"	<td class=\"rp-bl\"></td>" +
			"	<td class=\"rp-bottom\"></td>" +
			"	<td class=\"rp-br\"></td>" +
			"</tr></table>";


	this.jElement.html(str);

	$j(".rp-body").css('position', 'relative');

	// Width
	if (options.width != null) {
		this.jElement.width(options.width);
	}

	// Height
	if (options.height != null) {
		$j("#" + elementId + "-body").css('height', options.height);
		$j("#" + elementId + "-body").css('overflow', 'auto');
	}

	// Keep inside viewport
	keepElementInViewport(elementId);
	
	
	// Centering
	if (options.center == true) {
		centerElement(elementId);
	}

	// Visible
	if (options.visible == true) {
		this.jElement.show();
	} else {
		this.jElement.hide();
	}
	
	
	jElement.css("z-index", 1000);

	this.jElement.draggable({handle: $j("#" + elementId + " .rp-top")});

	return this;
}


function showPopupItem(mainContainerId, itemId) {
	var popupElement = $j("#"+ mainContainerId);
	
	if (popupElement.data("lastOpen") != null){
		$j("#" + popupElement.data("lastOpen")).hide();
	} 
	
	$j('#' + itemId).show();
	popupElement.data("lastOpen", itemId);
	popupElement.show();
}






function applyStyles() {
	// Pour IE6 seulement
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		// Transparent PNG
		$j(document).pngFix();
    	// Fix les div qui sont vide
		$j('.clear:empty').css("font-size", '0px');
	}
}

function beforeAjaxRequest() {}

function afterAjaxRequest() {
	applyStyles();
}

function initAjax4JSF() {
	try {
		A4J.AJAX.onError = function(req,status,message) {
			alert("Ajax error!! = req=" + req + ", status=" + status + ", message=" + message);
		};
	}
	catch(error) {}
}


function initTopnavSubmenuEvent() {
    // hide menu when user clicks anywhere but the dropdown
    $j(document).mouseup(function(event) {
        var fromDropdown = $j(event.target).parents(".topnav-submenu").length;
        // 0 means the event is not originated from the dropdown
        if (fromDropdown == 0) {
        	$j(".topnav-submenu").hide(200);
        }
    });

    // Les elements qui ont la class 'submenu-handler' sert a faire apparaitre les submenu
    $j(".topnav li").click( function(){
        if ($j(".topnav-submenu", this).css("display") != "block") {
        	$j(".topnav-submenu", this).show(150);
        }
    });
}


/*
function constraintShoppingCartInViewport() {
	jQuery(window).scroll(function(){
		var jElement = $j("#shoppingcart");

		// si on retrouve le shopping cart
		if (jElement.size() > 0) {
			var oShoppingCartTop = jElement.offset().top;

			jElement.css("width", "230px");
			jElement.css("z-index", "3");
			jElement.css("background", "#ffffff");
			jElement.css("top", 0);

			if (document.documentElement) {
				var dTop = document.documentElement.scrollTop;
			}

			if (dTop > oShoppingCartTop) {
				jElement.css("position", "fixed");
			} else {
				jElement.css("position", "absolute");
			}
		}
	});
}
*/

//shwhide
function showHide(shID) {
	if (document.getElementById(shID)) {
	
	 if (document.getElementById(shID+'-show').style.display != 'none')
 {

		 document.getElementById(shID+'-show').style.display = 'none';
		 document.getElementById(shID+'-hide').style.display = 'inline';
		 document.getElementById(shID).style.display = 'block';
 	}
	 else if (document.getElementById(shID+'-show').style.display != 'inline')
	 {

		 document.getElementById(shID+'-show').style.display = 'inline';
		 document.getElementById(shID+'-hide').style.display = 'none';
		 document.getElementById(shID).style.display = 'none';
	 }

 else {
	 document.getElementById(shID+'-show').style.display = 'inline';
	 document.getElementById(shID+'-hide').style.display = 'none';
	 document.getElementById(shID).style.display = 'none';
 }
 }
}
//window.onload=montre;
function montre(id) {
	var d = document.getElementById(id);
	for (var i = 1; i<=10; i++) {
		if (document.getElementById('smenu'+i)) {document.getElementById('smenu'+i).style.display='none';}
	}
	if (d) {d.style.display='block';}
	}

$j(document).ready(function(){
	  montre('');
	});
jQuery(document).ready(function(){
	initAjax4JSF();
	applyStyles();
	initTopnavSubmenuEvent();
});



/*! Copyright (c) 2008 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*/
 
/**
* Swaps out one element with another. It can take either a DOM element,
* a selector or a jQuery object. It only swaps the first matched element.
*/
jQuery.fn.swapElements = function(b) {
	b = jQuery(b)[0];
	var a = this[0],
	a2 = a.cloneNode(true),
	b2 = b.cloneNode(true),
	stack = this;
	 
	a.parentNode.replaceChild(b2, a);
	b.parentNode.replaceChild(a2, b);
	 
	stack[0] = a2;
	return this.pushStack( stack );
};

  //New Google Analytics tracking (2011-03-10)
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-21595156-1']);
  _gaq.push(['_setDomainName', 'none']);
  _gaq.push(['_setAllowLinker', true]);
  _gaq.push(['_addIgnoredRef', 'cogeco'], ['_addIgnoredRef', 'connexioncomplete'], ['_addIgnoredRef', 'completeconnection']);
  _gaq.push(['_trackPageview']);
 
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

