regexp_email = new RegExp('^[a-z0-9_|\.|-]+@[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*[\.]{1}[a-z]{2,6}$', 'i');

thereIsNoFlash = function()
{
	$('#bp_header h1').css( 'background', 'url(/img/bp_header/bp_logo.png) no-repeat top' );
};

// Au domReady
$(document).ready(function()
{
	// liens javascript pour non indexation des liens du site.
	$('.jsLink').each(function(){
		var rel = $(this).attr('data-rel');
		var title = $(this).attr('data-title');
		var href = $(this).attr('data-href');
		var cssclass = $(this).attr('class');
		var cssstyle = $(this).attr('style');
		var id = $(this).attr('id');
		var onclickEvent = $(this).attr('onclick');
		var content = $(this).html();

		var newA = '<a href="'+ href +'" ';
		
		if( rel != undefined && rel != "undefined" && rel.length > 0 )
			newA += ' rel="'+ rel +'" ';
		if( title != undefined && title != "undefined" && title.length > 0 )
			newA += ' title="'+ title +'" ';
		if( cssclass != undefined && cssclass != "undefined" && cssclass.length > 0 )
			newA += ' class="'+ cssclass +'" ';
		if( onclickEvent != undefined && onclickEvent != "undefined" && onclickEvent.length > 0 )
			newA += ' onclick="'+ onclickEvent +'" ';
		if( cssstyle != undefined && cssstyle != "undefined" && cssstyle.length > 0 )
			newA += ' style="'+ cssstyle +'" ';
		if( id != undefined && id != "undefined" && id.length > 0 )
			newA += ' id="'+ id +'" ';
		
		newA += '>';
		newA += content;
		newA += '</a>';
		
		$(this).replaceWith( newA );
	});
	
	// colorbox
	$("a[rel^='shadowbox']").colorbox({ maxWidth: '95%', maxHeight: '95%', scrolling: false });
	$("a[rel^='shadowbox'].flashmovie").colorbox({ iframe:true, maxWidth:"95%",maxHeight:"95%",innerWidth:"90%",innerHeight:"90%" });
	// cacher les objets (comme flash) quand on ouvre un colorbox
	var ahe = new maTools.AutoHideEmbeds();
	$("a[rel^='shadowbox']").bind("cbox_open", ahe.hide);
	$("a[rel^='shadowbox']").bind("cbox_closed", ahe.show);

	
	$('embed:visible,object:visible').each(function(){
		var elem = $(this);
		$().bind('dialogopen', function(event, ui){ $(elem).css("visibility", "hidden"); });
		$().bind('dialogclose', function(event, ui){ $(elem).css("visibility", "visible");	});
	});
	
	// pub flash
	$("#logo").flash({
		src: "/img/bp_header/bp_logo.swf",
		width: 343,
		height: 105,
		wmode: "transparent"
	},null,null,thereIsNoFlash);
	
	// tri recherche
	$('#tri_search').change(function()
	{
		var currentLocation =  document.location.href;
		var query = "?";
		
		// Parse the current page's querystring
		var qs = new Querystring()
		if(qs.contains("q"))
		{ 
			query += "q=" + qs.get("q");
		}
		
		if( !qs.contains("tri") || (qs.get("tri") != 'pertinence'))
		{
			if(query.length > 1)
			{
				query += "&";
			}
			query += "tri=" + $('#tri_search').val();
		}
		
		query += "&do=produit.recherche";

		window.location.href = query;
	});
	
	$('#form_search').submit(function()
	{
		var recherche = $('#search_field').val();
		
		if( recherche.length < 1 || recherche == " Chercher un jeu")
		{
			errors = "<ul><li style='margin-bottom: 5px;'>Merci de compléter le champ <strong>Chercher un jeu</strong>.</li></ul>";
			ShowErrorDialog(errors);
			return false;
		}
	});
	
	// init auto completion de la recherche
	$("#search_field").autocomplete( "index.cfm?do=ajax.search", {
		minChars: 2,
		width: 'auto',
		scroll: false,
		max: 10,
		autofill: false,
		matchContains: true,
		selectFirst: false
	});
	$('#search_field').result(function(event, data, formatted) {
		window.location.href = data[1];
		$('#search_field').val("");
		return false;
	});


	
	// affichage des messages optionnels
	if( $('#optionnalMessage') != undefined )
	{
		$('#optionnalMessage').dialog({
			bgiframe: true,
			buttons: { "Fermer": function() { $(this).remove(); } },
			modal: true,
			resizable: false,
			draggable: false
		});
	}
	
	// affichage des messages optionnels avec fermeture vers la home
	if( $('#optionnalMessageToHome') != undefined )
	{
		var url = "/";
		if( $('#optionnalMessageToHome').attr('rel') != undefined ){
			url = $('#optionnalMessageToHome').attr('rel');
		}
		$('#optionnalMessageToHome').dialog({
			bgiframe: true,
			buttons: { "Fermer": function() { window.location = url; } },
			modal: true,
			resizable: false,
			draggable: false
		});
	}
	
	
	initNewsletterManagement();

	// Effet d'highlight
	$(".highlight").hover(function(){
    	$(this).effect("highlight", {color: '#F3CADF'}, 300);
	});
	
	// Au clic sur "calendrier"
	$('.openCal').click(function()
	{
		
		// On construit (ou reconstruit) le div container
		initializeCalendarLayer();
		displayCal('now');
		
		// On l'affiche dans une fenetre modale
		$('#calendar').dialog({
			buttons: { "Fermer": function() { $(this).dialog("destroy"); } },
			bgiframe: true,
			width: 820,
			height: 640,
			modal: true,
			resizable: false,
			draggable: false
		});

		return false;
	});
	
	// vérifier si les cookies sont activés
	document.cookie = "checked";
	if (document.cookie == "")
		$("body").prepend(
				"<br /><div align='center'><div style='background-color:white; width:600px;'><br />" +
				"<strong>Attention, votre navigateur n'est pas configur&eacute; pour accepter les cookies.</strong><br />" +
				"Pour corriger le probl&egrave;me, reportez-vous &agrave notre aide." +
				"<br /><br /></div></div><br />"
				);
	
	// activer les rollover sur les liens
	$.rollimg.init();
	
});
// fin domready

function ShowErrorDialog(data)
{
	if ($("#errordialog").length <= 0)
	{
		$("<div id='errordialog' title='Attention' style='padding-top:15px;'></div>").dialog(
		{
			autoOpen: false, bgiframe: true, modal: true, width: 400,
			buttons: { "Fermer": function() { $(this).dialog("close"); } }
		});
	}
	$("#errordialog").html(data).dialog("open");
}

function initNewsletterManagement()
{
	$('.form_news').submit(function()
	{
		var mail_saisi = $(this).children('.input_text').val();
		if (regexp_email.exec(mail_saisi) == null || mail_saisi == "adresse@email.com")
		{
			errors = "L'adresse saisie est incorrecte.";
			ShowErrorDialog(errors);
			return false;
		}
		else
		{
			$('.newsletter_email').val( mail_saisi );
		}
	});
}

$.rollimg =
{
	init: function(n)
	{
		if (n == undefined)
			n = "";
		else
			n += " ";
		
		$(n + "a.rollimg").hover(
				function (){
					$("img", this).attr("src", $.rollimg.getOnSrc($("img", this).attr("src")));
				},
				function(){
					$("img", this).attr("src", $.rollimg.getOffSrc($("img", this).attr("src")));
				}
		);
		
		$(n + "input.rollimg").hover(
			function ()
			{
				$(this).attr("src", $.rollimg.getOnSrc($(this).attr("src")));
			},
			function()
			{
				$(this).attr("src", $.rollimg.getOffSrc($(this).attr("src")));
			}
		);
	},
	getOnSrc: function(s){
		return s.substring(0, s.search(/(\.[a-z]+)$/)) + "_on" + s.match(/(\.[a-z]+)$/)[0];
	},
	getOffSrc: function(s){
		return s.replace(/(_on){1,}\./, '.');
	}
};

var calendars = new Array();
calendars['now'] = "";
calendars['next'] = "";
calendars['previous'] = "";

function displayCal(type)
{
	if( calendars[type].length > 0 )
	{
		$('.calendarContent').html( calendars[type] );
	} else {
		$.ajax({
			type: "GET",
			url: "index.cfm?do=ajax.getCalendar&type="+type,
			success: function(msg){
				calendars[type] = msg;
				$('.calendarContent').html(msg);
			}
		});
	}

}

function initializeCalendarLayer()
{
	$('#layout').append('<div id="calendar" class="calendarContent" title="Calendrier 1 Jeu par Jour" style="width: 783px; height: 600px"></div>');
}





function lsCurrencyFormat(n)
{
	n = parseFloat(n).toFixed(2);
	n = n.replace(".", ",");
	n += " &euro;";
	return n;
}


// mettre à jour le nombre d'articles dans le header
function updateHeaderNbArticles()
{
	$.ajax(
	{
		type: "get",
		url: "/application/modeles/Panier.cfc?method=getNbArticles",
		success: function(rsp)
		{
			n = parseInt(rsp);
			if (isNaN(n)) return;
			setHeaderNbArticles(n);
		}
	});
}
function setHeaderNbArticles(n)
{
	s = n + " article";
	if (n > 1) s += "s";
	$("#cart_infos a").text(s);
}

/* Client-side access to querystring name=value pairs
Version 1.3
28 May 2008

License (Simplified BSD):
http://adamv.com/dev/javascript/qslicense.txt
*/
// optionally pass a querystring to parse
function Querystring(qs)
{ 
	this.params = {};

	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

	//Turn <plus> back to <space>
	//See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &

	//split out each name=value pair
	for (var i = 0; i < args.length; i++)
	{
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length == 2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_)
{
	var value = this.params[key];
	return (value != null) ? value : default_;
}
Querystring.prototype.contains = function(key)
{
	var value = this.params[key];
	return (value != null);
}
