// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
//     ie === undefined
// If you're in IE (>=5) then you can determine which version:
//     ie === 7; // IE7
// Thus, to detect IE:
//     if (ie) {}
// And to detect the version:
//     ie === 6 // IE6
//     ie > 7 // IE8, IE9 ...
//     ie < 9 // Anything less than IE9
// ----------------------------------------------------------

// UPDATE: Now using Live NodeList idea from @jdalton

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

if (ie != 7 && ie != 8) {
	Cufon.replace('.widget-wrapper h2', {hover: true});
	Cufon.replace('#bien-courant h1');
	Cufon.replace('#presentation-agence h1');
	Cufon.replace('h2');
	Cufon.replace('h3', {hover: true});
	Cufon.replace('legend');
	Cufon.replace('p.header-info');
	Cufon.replace('p.instruction');
}

String.prototype.trim = function()
	{
		var str = this.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
		while (ws.test(str.charAt(--i)));
			return str.slice(0, i + 1);
	};

String.prototype.startsWith = function(match)
	{
		return this.indexOf(match) === 0;
	};

Number.prototype.formatNumber = function() {
	var tReg = new RegExp('([0-9]+)([0-9]{3})'),
		str = ''+this;

	while( tReg.test(str) )
		str = str.replace(tReg, '$1 $2');
	return str;
}

function alea(min, max)
	{
		return Math.floor((max-(min-1))*Math.random()) + min;
	}

String.prototype.stripTags = function()
	{
		return this.toString().replace(/(<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>)|(<!--.*?-->)/gim, "");
	};

String.prototype.stripNonNumeric = function()
	{
		return this.toString().replace(/[^0-9]/g, '');
	};

var tooltipOpts =
	{
		showURL: false, fade: 250, track: true
	};


function envoiAnalytics(url)
	{
		// Compte analytics Arcadim (Fabrice Mettery)
		if ('object' == typeof firstTracker)
			firstTracker._trackPageview(url);

		// Compte analytics konfiture.arcadim
		if ('object' == typeof secondTracker)
			secondTracker._trackPageview(url);
	}


function startSlideShow()
	{
		if ( typeof slideImages !== 'undefined' )
			{
				$.each(slideImages, function()
					{
						var imgSrc = this;
						// Pas de doublons
						$('img[src=' + imgSrc + ']').remove();
						var html = '<img src="' + imgSrc + '"  width="320" height="350" alt="Panorama de la région" />';
						$('#slideshow-feature').append(html);
					});
				$('#slideshow-feature').cycle(
				{
					fx: 'fade',
					slideExpr: 'img'
				});
			}
	}

function refreshCart(itemAdded)
{
	var
		panier 	= $('#panier');
	
	var
		link 	= '/selection/voir';
	
	$.ajax ({
		cache: false,
		type: 'GET',
		url: link,
		success: function(data, status, xhr)
			{
				if (data == '') {
					panier.remove();
				} else if (!panier.length > 0) {
					$('body').append(data);
					addCartMovement(true);
					Cufon.refresh();
					$('#panier a.effacer').css('opacity', 0);
					$('#panier a').tooltip(tooltipOpts);
				} else {
					panier.html($(data).html());
					addCartMovement(true);
					Cufon.refresh();
					$('#panier a.effacer').css('opacity', 0);
					$('#panier a').tooltip(tooltipOpts);
				}

				if (itemAdded == 'added' && (!panier.length > 0 || data != '')) {
					computeFooterOffset();
					$('#panier #infobulle-panier')
						.stop()
						.show()
						.css({
							marginTop: '-400px',
							opacity: 0
						})
						.animate({ marginTop: '-70px', opacity: 1 }, 1000)
						.animate({opacity: 1}, 2000)
						.animate({opacity: 0}, function() {
							$(this).hide();
						});
				}
			},
		error: function(data, status, xhr)
			{
			}
	});
}

function computeFooterOffset()
{
	var
		panier 	= $('#panier'),
		footer 	= $('#footer');
	
	if (panier.length > 0)
		footer.css('paddingBottom', panier.outerHeight() + 'px');

}

function addCartMovement(refresh)
{
	$('#panier #panier-content').prepend('<div id="infobulle-panier"></div>');
	$('#panier #infobulle-panier').hide();
	$('#panier #entete-panier').append('<p class="afficher"><a href="">Afficher la sélection</a></p>');
	var
		showHideCart 	= $('#panier .afficher, #panier h2 a, #picto-selection'),
    	panier 			= $('#panier'),
    	link			= $('#panier .afficher a'),
		dim 			= panier.outerHeight() - 60;
	
	if (refresh) {
		panier.addClass('expanded');
		link.text('Masquer la sélection');
		if (panier.css('bottom') != '0px' || panier.css('bottom') != '0') {
			panier
				.stop()
				.animate({ bottom: 0 }, function() {
					computeFooterOffset();
				});	
		}
	} else {
		panier.css('bottom', '-'+dim+'px');
	}
	
	showHideCart
    	.click(function(event) {
    		
    		event.preventDefault();

    		var
    			dim 	= panier.outerHeight() - 60;
    		
    		if (panier.hasClass('expanded')) {
    			panier.stop()
    				.animate({ bottom: '-'+dim+'px'}, function() {
    					computeFooterOffset();
    				})
    			   	.removeClass('expanded');
    			link.text('Afficher la sélection');
    		} else {
    			panier
    				.stop()
    				.animate({ bottom: 0 }, function() {
    					computeFooterOffset();
    				})
    				.addClass('expanded');
    			link.text('Masquer la sélection');
    		}
    	});
}

$(document).ready(function()
	{
		var
			mobile_version = $('a.mobile-redirect');
		
		if (mobile_version.length == 1) {
			if (confirm("Nous avons détecté que vous utilisiez un terminal mobile.\nSouhaitez-vous consulter la version du site dédiée aux mobiles ?")) {
				window.location = mobile_version.attr('href');
				$('#container').css('opacity', 0.3);
			}
		}

		startSlideShow();
		$('a').tooltip(tooltipOpts);

		if (typeof noDiaporama == 'undefined')
			$('a[rel^=diaporama]').arcadimDiaporama();
		$('#critere-prix input').arcadimPrixInput();

		$('.nojsremove').removeClass('nojsremove');
		$('.nojsshow').remove();
		$('.jshide').css('display', 'none');

		$('.widget-thumbnail img[class$=lazy]').lazyload(
			{
				placeholder : dataRoot+'images/vignette-loading.jpg',
				effect      : 'fadeIn'
			});

		// Transition custom cycle

		$.fn.cycle.transitions.arcadrop = function ($cont, $slides, opts)
			{
				var $el = $($slides[0]);
				var h = $el.height();

				$slides.not(':eq('+opts.currSlide+')').css('opacity',0);
				opts.before.push(function(curr,next,opts) {
					$.fn.cycle.commonReset(curr,next,opts);
					opts.cssBefore.opacity = 0;
				});
				opts.animIn = { opacity: 1 };
				opts.animOut = { opacity: 0, top: h };
				opts.cssBefore = { top: 0, left: 0 };
			};

		// Même taille pour tous les éléments (alignée sur le plus grand)
		$.fn.sameHeight = function()
			{
				var theOne = 0;
				var doNotTouchMe; // IE8 fix
				var retVal = 0;
				$(this).each(function()
					{
						if ( $(this).height() > theOne )
							{
								doNotTouchMe = this;
								theOne = $(this).height();
								retVal = $(this).outerHeight();
							}
					});

				$(this).each(function()
					{
						if ( this != doNotTouchMe )
							{
								$(this).css('min-height', theOne + 'px');
								if ( $.browser.msie && $.browser.version <= 6)
									$(this).css('height', theOne + 'px');
							}
					});

				return retVal;
			}


			/*
			$('#criteres-plus input[type=checkbox')
				.click(function(){

					});
			*/


	    $('a[rel=confirm]').live('click', function(event) {
	        event.preventDefault();
	        var
	            action      = $(this).attr('title'),
	            link        = $(this).attr('href');

	        if (action == '')
	        	action = $(this).attr('tooltipText');
	        
	        var
	            question    = "Effectuer l'action suivante :<br/><strong>"+action+"</strong> ?";
	        
	        arcadimMsgBox.ask({
	            question    : question,
	            title       : 'Attention !',
	            answer      : function(reponse) {
	                if (reponse == 'yes') {
	                    $('#container').css('opacity', 0.5);
	                    window.location.replace(link);
	                }
	            }   
	        })
	    });

	    $('a[rel=add-selection]').live('click', function(event) {
	    	event.preventDefault();

	    	var
	    		linkEl			= $(this),
	    		link 			= linkEl.attr('href');
	    	
	    	linkEl.addClass('button-loading');
	    	$('body')
	    		.stop()
	    		.animate({ opacity: 0.5 });
	    	Cufon.refresh();
	    	
	    	$.ajax({
				cache: false,
				type: 'GET',
				url: link,
				success: function(data, status, xhr) {
					linkEl.removeClass('button-loading');
					$('body')
			    		.stop()
			    		.animate({ opacity: 1 }, 'fast');

					if (data.indexOf('déjà été') == -1) {
						refreshCart('added');
					} else {
						arcadimMsgBox.show({ message: 'Le bien a déjà été ajouté à votre sélection.' });
					}
				},
				error: function(data, status, xhr) {
					linkEl.removeClass('button-loading');
					$('body')
						.stop()
			    		.animate({ opacity: 1 }, 'fast');
				}
			});
	    });

	    $('a[rel=message]').live('click', function(event) {
	    	event.preventDefault();

	    	var
	    		link 			= $(this).attr('href'),
	    		doRefresh		= $(this).hasClass('modification-panier'),
	    		ajaxContentReg 	= new RegExp('<!--BEGIN:ajax-->([\\S\\s]*?)<!--END:ajax-->'),
				ajaxErrorReg 	= new RegExp('<!--BEGIN:ajaxError-->([\\S\\s]*?)<!--END:ajaxError-->'),
				loadingDlg 		= arcadimMsgBox.loading({message: 'Veuillez patienter, merci.' });
	    	
	    	$.ajax({
				cache: false,
				type: 'GET',
				url: link,
				success: function(data, status, xhr)
					{
						loadingDlg.dialog('close');
						var msg = ''; var isError = false;

						var matches = data.match(ajaxErrorReg);
						if ( matches != null )
							{
								msg = matches[0];
								isError = true;
							}

						matches = data.match(ajaxContentReg);
						if ( matches != null )
							msg = matches[0];

						if ( msg == '' )
							msg = 'L\'action a été correctement effectuée';

						if ( isError )
							arcadimMsgBox.error({message: msg});
						else
							{
								$('#popup-dialog').dialog('close');
								msg = msg.replace('<!--BEGIN:ajax-->', '');
								msg = msg.replace('<!--END:ajax-->', '');
								msg = msg.trim();

								if (doRefresh)
									refreshCart('prout');
								arcadimMsgBox.show({message: msg});
							}
					},
				error: function(data, status, xhr)
					{
						arcadimMsgBox.error({message:'Le lien n\' a pu être chargé suite à un problème réseau. Vérifiez votre connexion à internet'});
					}
	    	});
	    });

	    $('a[rel=confirm-message]').live('click', function(event) {
	    	event.preventDefault();

	        var
	            action      = $(this).attr('title'),
	            link        = $(this).attr('href'),
				doRefresh	= $(this).hasClass('modification-panier');

	        if (action == '')
	        	action = $(this).attr('tooltipText');
	        
	        var
	            question    = "Effectuer l'action suivante :<br/><strong>"+action+"</strong> ?";
	        
	        arcadimMsgBox.ask({
	            question    : question,
	            title       : 'Attention !',
	            answer      : function(reponse) {
	                if (reponse == 'yes') {
				    	var
				    		ajaxContentReg 	= new RegExp('<!--BEGIN:ajax-->([\\S\\s]*?)<!--END:ajax-->'),
							ajaxErrorReg 	= new RegExp('<!--BEGIN:ajaxError-->([\\S\\s]*?)<!--END:ajaxError-->'),
							loadingDlg 		= arcadimMsgBox.loading({message: 'Veuillez patienter, merci.' });
				    	
				    	$.ajax({
							cache: false,
							type: 'GET',
							url: link,
							success: function(data, status, xhr)
								{
									loadingDlg.dialog('close');
									var msg = ''; var isError = false;

									var matches = data.match(ajaxErrorReg);
									if ( matches != null )
										{
											msg = matches[0];
											isError = true;
										}

									matches = data.match(ajaxContentReg);
									if ( matches != null )
										msg = matches[0];

									if ( msg == '' )
										msg = 'L\'action a été correctement effectuée';

									if ( isError )
										arcadimMsgBox.error({message: msg});
									else
										{
											$('#popup-dialog').dialog('close');
											msg = msg.replace('<!--BEGIN:ajax-->', '');
											msg = msg.replace('<!--END:ajax-->', '');
											msg = msg.trim();

											if (doRefresh)
												refreshCart();
											arcadimMsgBox.show({message: msg});
										}
								},
							error: function(data, status, xhr)
								{
									arcadimMsgBox.error({message:'Le lien n\' a pu être chargé suite à un problème réseau. Vérifiez votre connexion à internet'});
								}
				    	});   
	                }
	            }   
	        })

	    });

	    computeFooterOffset();

	    $('#panier a.effacer').css('opacity', 0);

	    $('#panier a.miniature')
	    	.live('mouseenter', function() {
	    		$(this).parent().find('a.effacer').stop().animate({opacity:1});
	    	})
	    	.live('mouseleave', function() {
	    		$(this).parent().find('a.effacer').stop().animate({opacity:0});
	    	});

	    $('#panier a.effacer')
	    	.live('mouseenter', function() {
	    		$(this).stop().animate({opacity:1});
	    	})
	    	.live('mouseleave', function() {
	    		$(this).stop().animate({opacity:0});
	    	});
	    
	    addCartMovement();
	});


