// JavaScript Document
var NUMACTU=0;
var DIR=1;
var LOCKP=false;
var KEY='';
var COLOR='';
var BGCOLOR='';
var PAGE='';
var SLIDE='';
var OFFSET=0;
var DEVIS_NEXT;
var DEVIS_PREV;
var DEVIS_ARRAY;
var TIMER_ACTU=600000;
var LOCKA=false;
var PAGE_NEXT=false;
var VAL_OBJ=false;
var ANIM_SPEED=0;
var SON=true;
jQuery.fx.interval = 16;
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24834874-1']);
_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);
	var gp = document.createElement('script'); gp.type = 'text/javascript';gp.textContent='{lang: \'fr\'}';gp.async = true;
    gp.src = 'https://apis.google.com/js/plusone.js';
    s.parentNode.insertBefore(gp, s);
	$('a','#loginbox').click(function(){
		getPage(linkToPage($(this).attr('href')));
		return false;
	});
	$('.ui_bt','#loginbox').button();
	bindDialog();
	bindLogForm();
	bindPage();
	//bindActu();
	bindLeftMenu();
	//bindSocial();
	//bindContact();
	//bindNewsletter();
	bindSMenu();
	bindFooter();
	bindScroll('#content-page-c');
	setTimeout('checkHist()',10);
	slideIt();
	changeColor();
});

function buy(article)
{
	document.location.href='process_paiement.php?art='+article;
}
function play_son()
{
	var titre=$('#jplayer').attr('title');
	if(titre && SON)
	{
		jplayer(titre);
	}
}
function jplayer(son,type)
{
	if(type==undefined)
		type='site';
	$('#jplayer').jPlayer( {
    ready: function () {
      $(this).jPlayer('setMedia', {
        oga: '/sons/'+type+'/'+son+'.oga',
        mp3: '/sons/'+type+'/'+son+'.mp3'
      }).jPlayer('play'); // Attempts to Auto-Play the media
    },
    solution: 'html, flash',
    supplied: 'oga, mp3',
	swfPath: '/js'
  });
}
function kill_jPplayer()
{
	$('#jplayer').jPlayer('destroy');
}
function listen(url)
{
	jPlayer('jplayer').loadAndPlay('/extraits/'+url);
}
function href(id)
{
	$(location).attr('href','musique-'+id+'.html');
}
var timerSlide;
function slideIt()
{
	if(PAGE=='index'||PAGE=='accueil')
	$.getJSON('/json/slide.json.php',function(data)
	{	
		$('#second_bg').css('background', 'url("/images/slides/'+data.img+'") no-repeat').fadeIn(2400, function(){
			$('#slide').css('background', 'url("/images/slides/'+data.img+'") no-repeat');
			$('#txtbox').animate({top:'-82px'},260, function() {
				$('#slide_h2').text(data.titre);
				$('#slide_txt').text(data.text);
				$('#txtbox').animate({top:'0px'},{queue:false,duration:520});
			});
	
			$(this).hide();
		});

		timerSlide=setTimeout(function(){slideIt();},5600);
    });
}

function chargement()
{
	dialogBox('Chargement en cour, cela peut prendre quelques secondes...<br />Merci de patienter!<div align="center"><img src="/images/animation/ajax-loader.gif" alt="" /></div>');
}


function bindLogForm(){
	$('#login-id').focus(function(){
		$(this).attr('value','').unbind();
	});
	$('#login-pass').focus(function(){
		$(this).remove();
		$('#pass-cont').append('<input type="password" id="login-pass" class="loginput" />');
	});
}
function lock()
{
	LOCKP=true;
}
function unlock()
{
	LOCKP=false;
	if(PAGE_NEXT && PAGE_NEXT!=PAGE)
	{
		getPage(PAGE_NEXT);
		return true;
	}
	else
		return false;
}
function checkHist()
{
	var hash=location.hash.substr(1);
	if(PAGE!=hash && hash.length>1)
	{
		getPage(hash);
	}
	setTimeout('checkHist()',1000);
}

function bindDialog()
{
	$('#dialog').dialog({
		bgiframe: true,
		modal: true,
		autoOpen:false,
		resizable: false,
		buttons:{
			Ok: function(){
				$(this).dialog('close');
			}
		}
	});
}
function bindSocial()
{
	return;
	var url=document.domain+'/'+PAGE+'.html';
	var style='';
	var style2='';
	var d=' style="display:none"';
	$('#content-page-c').append('<div id="social_box" '+style+'><a id="social_fb" target="_blank" title="Suivez-nous sur Facebook" href="http://www.facebook.com/pages/Android-addict/"'+d+'></a><a id="social_tw" target="_blank"  title="Suivez-nous sur Tweeter" href="http://twitter.com/#!/android-addict/"'+d+'></a><a id="social_via" target="_blank" title="Suivez-nous sur Viadeo" href="http://www.viadeo.com/fr/profile/android-addict"'+d+'></a><a id="social_fav" title="Ajouter en favoris" href="#"'+d+' rel="sidebar"></a><a id="social_sh" title="Envoyer à un ami" href="mailto:?subject=Android-Addict.com&body='+url+'"'+d+'></a></div><div id="social_bg" '+style2+'></div>');
	$('#social_fb').show('slide', { direction: 'down' }, 300,function(){
		$('#social_tw').show('slide', { direction: 'down' }, 300,function(){
			$('#social_via').show('slide', { direction: 'down' }, 300,function(){
				$('#social_fav').show('slide', { direction: 'down' }, 300,function(){
					$('#social_sh').show('slide', { direction: 'down' }, 300);
				});	
			});
		});
	});
	$('#social_fav').click(function(){
        var url = this.href;
        var title = this.title;
       
        if (window.sidebar) {
            window.sidebar.addPanel(title, url, '');
        } else if( window.external ) {
            window.external.AddFavorite( url, title);
        } else {
            dialogBox('Ce navigateur ne supporte pas la mise en favori à laide de ce bouton, vous devez le faire manuellement','Mettre en favori');
        }
	});
	$('#social_fb,#social_tw,#social_fav,#social_sh,#social_via').hover(function(){
		$(this).stop(true,true).animate({top:'-7px'});
	},function(){
		$(this).stop(true,true).animate({top:'0'});
	}).tipTip();
}

function img_change(id,lclass,ini_pos,hover_pos,content,offset)
{
	var pclass='.'+lclass;
	var did='#'+id;
	var oldbt=$(pclass,did);
	var newbt=$('<div class="'+lclass+'" style="background-position:'+ini_pos+'px '+offset+'px;">'+content+'</div>');
	newbt.hide();
	$(did).append(newbt);
	oldbt.fadeOut(1200);
	newbt.fadeIn(1200,function(){
		oldbt.remove();
	});
	newbt.hover(function(){
		$(this).css('background-position',hover_pos+'px '+offset+'px');
	},function(){
		$(this).css('background-position',ini_pos+'px '+offset+'px');
	});
}
function changeLogo(pos,pos2,pos3)
{
	var oldlogo=$('.logo','#logo-cont');
	var newlogo=$('<div class="logo" style="background-position:0 '+pos+'px;"><a href="/"></a></div>');
	newlogo.hide();
	$('#logo-cont').append(newlogo);
	oldlogo.fadeOut(1200);
	newlogo.fadeIn(1200,function(){
		oldlogo.remove();
	});
	$('#link_ico').attr('href','/images/logos/ico_mdw'+pos+'.png');
}

function bindScroll(context)
{
	$('a[href^=#]',context).click(function() {
		cible = $(this).attr('href');
		if($(cible).length>=1){
			hauteur=$(cible).offset().top;
		}
		else{
			hauteur=$("a[name="+cible.substr(1,cible.length-1)+"]").offset().top;
		}
		$('html,body').animate({scrollTop: hauteur}, 1000);
		return false;
	});
}
function linkToPage(lien)
{
	var start=lien.lastIndexOf('/');
	if(start==-1)
		start=0;
	else
		start++;
	return lien.substr(start,lien.lastIndexOf('.')-start);
}
function bindFooter()
{
	$('a','#plan_site').click(function(){
		if($(this).attr('href').indexOf('#')==-1)
			getPage(linkToPage($(this).attr('href')));
		return false;
	});
}
function bindLeftMenu()
{

	$('a','#menu-gauche-c').click(function(){
		if($(this).attr('href').indexOf('#')==-1)
			getPage(linkToPage($(this).attr('href')));
		return false;
	});
	bindScroll('#menu-gauche-c');
}
function bindPage()
{
	play_son();
	$('.ui_bt','#website').button();
	$('#tab_banque').tabs();
	$('a','#menu').click(function()
	{
		var lien=linkToPage($(this).attr('href'));
		if(lien!='')
		{	
			getPage(lien);
			return false;
		}
	});
	$('a','#content-page-c').click(function()
	{
		if($(this).attr('target')===undefined && $(this).attr('href').substr(0,1)!='#')
		{
			getPage(linkToPage($(this).attr('href')));
			return false;
		}
	});
	$('#tab_banque').tabs();
	$('#logo-cont').unbind().click(function()
	{
		getPage('index');
		return false;
	});
}

function bindAriane()
{
	$('a','#ariane').click(function()
	{
		getPage(linkToPage($(this).attr('href')));
		return false;
	});
}
function bindSMenu()
{
	$('a','#ss-menu').click(function()
	{
		getPage(linkToPage($(this).attr('href')));
		return false;
	});
}
function getPage(p)
{
	if(LOCKP)
	{
		PAGE_NEXT=p;
		return false;
	}
	else
	{
		if(PAGE!=p || PAGE=='membre')
		{
			lock();
			PAGE_NEXT=false;
			$.getJSON('/json/getpage.json.php?p='+p,function(json)
			{
				location.hash = '#' + p;
				PAGE=p;
				if(json.ok)
				{
					var dir=0;
					if(DIR>parseInt(json.dir))
						dir=1;
					DIR=parseInt(json.dir);
					var bo=0;
					
					
					$('.menu_active','#menu').removeClass('menu_active');
					if(p=='index')
						p='accueil';
					if(json.pnom!=undefined)
					{
						$('a[name="'+json.pnom+'-"]','#menu').parent().addClass('menu_active');
					}
					else
						$('a[name="'+p+'-"]','#menu').parent('li').addClass('menu_active');
					if(KEY!=json.key)
					{
						changeLeftMenu(json.leftmenu,true);
					}
					else
						changeLeftMenu(json.leftmenu,false);
					changePage(json.page,json.ariane);
					if($('#devis_form').length)
						bindDevis();
					if(SLIDE!=json.slide_id)
					{
						if(json.parent_id!=null)
							dir=3;
						SLIDE=json.slide_id;
						IS_SLIDE=true;
						changeSlide(json.slide,dir);
					}
					else
					{
						IS_SLIDE=false;
						setTimeout('bindSocial()',1000);
					}
					
					KEY=json.key;
					if(json.titre!=undefined)
					{
						document.title=json.titre;
					}
					changeTopMenu(json.topmenu);
					if(json.color!=undefined)
					{
						COLOR=json.color;
						BGCOLOR=json.bgcolor;
						changeLogo(json.logo_offset,json.bt_offset,json.btsmall_offset);
						changeColor();
						bo=json.barre_offset;
					}
				}
				else
				{
					err(json.err);
					unlock();
				}
			});
			return true;
		}
		return false;
	}
}

function changeColor(d)
{
	if(d==undefined)
		d=3000;
	var	c=COLOR;
	var	b=BGCOLOR;
	if(COLOR!='')
	{
		$('body').stop().animate({backgroundColor:b},d);
		$('.txt_color','#content').stop().animate({color:c},d);
		//$('a:not(.txt_color,#ariane a,#social_box a)','#content-page-c').animate({color:c},d);
	}
}
function readJSONactu(num,dir,dir2)
{
	LOCKA=true;
	$('#actu_cont').hide('slide', { direction: dir }, 600,function(){
		$.getJSON('/json/actu.json.php?num='+num,function(json){
			$('#actu_titre').attr('href',json.link).html(json.title);
			$('#actu_txt').html(json.description);
			if(json.enc_url!=undefined)
			{
				$('#actu_img').html('<a href="'+json.link+'" target="_blank"><img src="'+json.enc_url+'" alt="" width="70" /></a>');
			}
			else
				$('#actu_img').html('');
			$('#actu_cont').show('slide', { direction: dir2 }, 600,function(){LOCKA=false;});
			NUMACTU=parseInt(json.num);
		});
	});
}
function bindActu()
{
	$('#bt_actu_prev').click(function(){
		NUMACTU--;
		if(!LOCKA) readJSONactu(NUMACTU,'left','right');
	});

	$('#bt_actu_next').click(function(){
		NUMACTU++;
		if(!LOCKA) readJSONactu(NUMACTU,'right','left');
	});
	$('#a_rss').tipTip();
	timerActu();
}
function timerActu()
{
	NUMACTU++;
	if(!LOCKA) readJSONactu(NUMACTU,'right','left');
	setTimeout('timerActu()',TIMER_ACTU);
}
function changePage(page,ariane)
{
	_gaq.push(['_trackPageview', page]);
	$('#ariane').html(ariane);
	$('#content-page-c').fadeOut(ANIM_SPEED,function(){
		$(this).hide().html(page).fadeIn(ANIM_SPEED,function(){
			unlock();
			bindPage();
			if(PAGE!='index')
				$('#bg_slide').slideUp();
			else
			{
				$('#bg_slide').slideDown();
				clearTimeout(timerSlide);
				slideIt();
			}
		});

		//$('h1','#content-page').css('background-position','0 '+bo+'px');

		bindAriane();
		bindContact();
		bindNewsletter();
		bindScroll('#content-page-c');
		if($('#devis_form').length)
			bindDevis();

	});	
}
function changeLeftMenu(menu,anim)
{
	if(menu)
	{
		$('#col-gauche').css('display','block');
		$('#content-page').css('width','764px');
	}
	else
	{
		$('#col-gauche').css('display','none');
		$('#content-page').css('width','');
	}
	if(anim)
	{
	$('#menu-gauche-c').fadeOut(ANIM_SPEED,function(){
		$(this).hide().html(menu).fadeIn(ANIM_SPEED);
		bindLeftMenu();
	});
	}
	else
	{
		$('#menu-gauche-c').html(menu);
		bindLeftMenu();
	}
}
function changeTopMenu(menu)
{
	/* ! TODO bug jQuery!
	$('#ss-menu').fadeOut('slow',function(){
		$(this).html(menu).fadeIn('slow',function(){$(this).show();});
		bindSMenu();
		bindScroll('#ss-menu');
	});
	*/
	$('#ss-menu').html(menu);
	bindSMenu();
	bindScroll('#ss-menu');
}
function changeSlide(s,d)
{
	var dep=$(document).width();
	var sens='left';
	if(d!=undefined)
	{
		if(d==1)
		{
			dep=-dep;// >>>
		}
		//Sinon dep <<<
	}
	var dur_s=3000;//Durée de slide
	var dur_t=600;//Durée entre chaque affichage texte
	var content=$('#content_slide');
	var older_slide=content.find('.slide');
	var curent_slide=older_slide.first();
	older_slide=older_slide.slice(1);
	var new_slide=$('<div class="slide"></div>');
	content.append(new_slide);
	var anim={};
	anim[sens]=0;
	new_slide.css(sens,dep+'px').html(s).animate(anim,dur_s);
	var text_slide=$('.text_slide',new_slide);
	text_slide.stop(true,true).hide();
	anim[sens]=-dep;
		older_slide.animate(anim,dur_s,function(){
			older_slide.remove();
		});
	curent_slide.animate(anim,dur_s,function(){
		curent_slide.remove();
		//if(!unlock())
		{
			bindSocial();
			$('.argument_slide',new_slide).hide();
			$('.croix_slide',new_slide).fadeIn().click(function(){
				$('#bg_slide').slideUp('slow',function(){
					$('#ouverture-slide').show();
				});
			}).tipTip();
			text_slide.fadeIn(dur_t,function(){			
				$('.sld1',new_slide).fadeIn(dur_t,function(){
					$('.sld2',new_slide).fadeIn(dur_t,function(){
						$('.sld3',new_slide).fadeIn(dur_t,function(){
							$('.sld4',new_slide).fadeIn(dur_t);
						});
					});
				});
			});
		}
	});
}
function suppr(article)
{
	$.getJSON('/json/json_suppr_panier.php?id='+article+'&time='+(new Date()).getTime(), function(json){
		if(json.ok)
			$('#a'+article).remove();
		else
			dialogBox('Echec de la suppression de l\'article!');
	});
}
function garderSession()
{
	$.getJSON('/json/session.json.php',function(){});
}
function dialogBox(txt,tit,w)
{
	if(!w) w=300;
	$('#dialog').html('<img src="/images/logos/mmt-small.png" alt="" /><br />'+txt).dialog('option','title',tit).dialog('option','width',w).dialog('open');
}
function err(t)
{
	dialogBox(t,'Erreur');
}
function bindContact()
{
	$('#contact-form').submit(function(){
		$.getJSON('/json/contact.json.php?'+$(this).serialize(),function(json)
		{
			if(json.ok==1)
				dialogBox('Votre message à bien été envoyé!','Contact');
			else
				err(json.err);
		});
		return false;
	});
	$('#captcha').click(function(){
		$(this).attr('src','/securimage/securimage_show.php?'+Math.random());
		return false;
	}).tipTip();
}
function bindNewsletter()
{
	$('.bt_newsletter','#bt_ok_cont').click(function(){
		var mail=$('#email_newsletter').val();
		if(checkMail(mail))
		{
			$.getJSON('/json/newsletter.json.php?m='+encodeURI(mail),function(json){
				if(json.ok==1)
				{
					dialogBox('Merci votre inscription est bien validée','Inscription Newsletter');
					$('#email_newsletter').attr('disabled','disabled');
				}
				else if(json.ok==2)
				{
					err('Vous êtes déjà inscrit à notre newsletter!');
				}
				else
				{
					err('Email invalide!');
				}
			});
		}
		else
		{
			err('Email invalide!');
		}
	});
}
function checkMail(m)
{
	var f  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (f.test(m)) {
		return true;
	}
	return false;
}

 /*
 * TipTip
 * Version 1.3
 */
(function($){$.fn.tipTip=function(options){var defaults={activation:"hover",keepAlive:false,maxWidth:"200px",edgeOffset:3,defaultPosition:"bottom",delay:400,fadeIn:200,fadeOut:200,attribute:"title",content:false,enter:function(){},exit:function(){}};var opts=$.extend(defaults,options);if($("#tiptip_holder").length<=0){var tiptip_holder=$('<div id="tiptip_holder" style="max-width:'+opts.maxWidth+';"></div>');var tiptip_content=$('<div id="tiptip_content"></div>');var tiptip_arrow=$('<div id="tiptip_arrow"></div>');$("body").append(tiptip_holder.html(tiptip_content).prepend(tiptip_arrow.html('<div id="tiptip_arrow_inner"></div>')))}else{var tiptip_holder=$("#tiptip_holder");var tiptip_content=$("#tiptip_content");var tiptip_arrow=$("#tiptip_arrow")}return this.each(function(){var org_elem=$(this);if(opts.content){var org_title=opts.content}else{var org_title=org_elem.attr(opts.attribute)}if(org_title!=""){if(!opts.content){org_elem.removeAttr(opts.attribute)}var timeout=false;if(opts.activation=="hover"){org_elem.hover(function(){active_tiptip()},function(){if(!opts.keepAlive){deactive_tiptip()}});if(opts.keepAlive){tiptip_holder.hover(function(){},function(){deactive_tiptip()})}}else if(opts.activation=="focus"){org_elem.focus(function(){active_tiptip()}).blur(function(){deactive_tiptip()})}else if(opts.activation=="click"){org_elem.click(function(){active_tiptip();return false}).hover(function(){},function(){if(!opts.keepAlive){deactive_tiptip()}});if(opts.keepAlive){tiptip_holder.hover(function(){},function(){deactive_tiptip()})}}function active_tiptip(){opts.enter.call(this);tiptip_content.html(org_title);tiptip_holder.hide().removeAttr("class").css("margin","0");tiptip_arrow.removeAttr("style");var top=parseInt(org_elem.offset()['top']);var left=parseInt(org_elem.offset()['left']);var org_width=parseInt(org_elem.outerWidth());var org_height=parseInt(org_elem.outerHeight());var tip_w=tiptip_holder.outerWidth();var tip_h=tiptip_holder.outerHeight();var w_compare=Math.round((org_width-tip_w)/2);var h_compare=Math.round((org_height-tip_h)/2);var marg_left=Math.round(left+w_compare);var marg_top=Math.round(top+org_height+opts.edgeOffset);var t_class="";var arrow_top="";var arrow_left=Math.round(tip_w-12)/2;if(opts.defaultPosition=="bottom"){t_class="_bottom"}else if(opts.defaultPosition=="top"){t_class="_top"}else if(opts.defaultPosition=="left"){t_class="_left"}else if(opts.defaultPosition=="right"){t_class="_right"}var right_compare=(w_compare+left)<parseInt($(window).scrollLeft());var left_compare=(tip_w+left)>parseInt($(window).width());if((right_compare&&w_compare<0)||(t_class=="_right"&&!left_compare)||(t_class=="_left"&&left<(tip_w+opts.edgeOffset+5))){t_class="_right";arrow_top=Math.round(tip_h-13)/2;arrow_left=-12;marg_left=Math.round(left+org_width+opts.edgeOffset);marg_top=Math.round(top+h_compare)}else if((left_compare&&w_compare<0)||(t_class=="_left"&&!right_compare)){t_class="_left";arrow_top=Math.round(tip_h-13)/2;arrow_left=Math.round(tip_w);marg_left=Math.round(left-(tip_w+opts.edgeOffset+5));marg_top=Math.round(top+h_compare)}var top_compare=(top+org_height+opts.edgeOffset+tip_h+8)>parseInt($(window).height()+$(window).scrollTop());var bottom_compare=((top+org_height)-(opts.edgeOffset+tip_h+8))<0;if(top_compare||(t_class=="_bottom"&&top_compare)||(t_class=="_top"&&!bottom_compare)){if(t_class=="_top"||t_class=="_bottom"){t_class="_top"}else{t_class=t_class+"_top"}arrow_top=tip_h;marg_top=Math.round(top-(tip_h+5+opts.edgeOffset))}else if(bottom_compare|(t_class=="_top"&&bottom_compare)||(t_class=="_bottom"&&!top_compare)){if(t_class=="_top"||t_class=="_bottom"){t_class="_bottom"}else{t_class=t_class+"_bottom"}arrow_top=-12;marg_top=Math.round(top+org_height+opts.edgeOffset)}if(t_class=="_right_top"||t_class=="_left_top"){marg_top=marg_top+5}else if(t_class=="_right_bottom"||t_class=="_left_bottom"){marg_top=marg_top-5}if(t_class=="_left_top"||t_class=="_left_bottom"){marg_left=marg_left+5}tiptip_arrow.css({"margin-left":arrow_left+"px","margin-top":arrow_top+"px"});tiptip_holder.css({"margin-left":marg_left+"px","margin-top":marg_top+"px"}).attr("class","tip"+t_class);if(timeout){clearTimeout(timeout)}timeout=setTimeout(function(){tiptip_holder.stop(true,true).fadeIn(opts.fadeIn)},opts.delay)}function deactive_tiptip(){opts.exit.call(this);if(timeout){clearTimeout(timeout)}tiptip_holder.fadeOut(opts.fadeOut)}}})}})(jQuery);
