function mktime () {
    var no=0, i = 0, ma=0, mb=0, d = new Date(), dn = new Date(), argv = arguments, argc = argv.length;

    var dateManip = {
        0: function (tt){ return d.setHours(tt); },
        1: function (tt){ return d.setMinutes(tt); },
        2: function (tt){ var set = d.setSeconds(tt); mb = d.getDate() - dn.getDate(); return set;},
        3: function (tt){ var set = d.setMonth(parseInt(tt, 10)-1); ma = d.getFullYear() - dn.getFullYear(); return set;},
        4: function (tt){ return d.setDate(tt+mb);},
        5: function (tt){
            if (tt >= 0 && tt <= 69) {
                tt += 2000;
            }
            else if (tt >= 70 && tt <= 100) {
                tt += 1900;
            }
            return d.setFullYear(tt+ma);
        }
    };

    for (i = 0; i < argc; i++){
        no = parseInt(argv[i]*1, 10);
        if (isNaN(no)) {
            return false;
        } else {
            if (!dateManip[i](no)){
                return false;
            }
        }
    }
    for (i = argc; i < 6; i++) {
        switch (i) {
            case 0:
                no = dn.getHours();
                break;
            case 1:
                no = dn.getMinutes();
                break;
            case 2:
                no = dn.getSeconds();
                break;
            case 3:
                no = dn.getMonth()+1;
                break;
            case 4:
                no = dn.getDate();
                break;
            case 5:
                no = dn.getFullYear();
                break;
        }
        dateManip[i](no);
    }

    return Math.floor(d.getTime()/1000);
}

function time () {
    return Math.round(new Date().getTime()/1000);
}


function placingCarto() {
    var dim = {width: 0, height: 0};
        if (document.documentElement) {
            dim = document.documentElement.offsetWidth;
        } else if (window.innerWidth && window.innerHeight) {
            dim = window.innerWidth;
        }

        var scroll=document.documentElement.scrollTop;

        $('#workspace_carto').css({
            'left':(dim-813)/2,
            'top':0
            });
    }  
    
function bgrotate()
    {
    img_val++;
    if(img_val>10){img_val=2;}
    
    $('#rotate_acc').animate({'opacity':0},
        {
        duration:1000,
        complete:function(){
            $(this).css('backgroundImage','url("/download/site-principal/charte/fond'+img_val+'.jpg")');
            }
        }).animate({'opacity':1},500);    
    
    }
    
function offre_rotate() {
    offre_id++;
    if(offre_id>=$('#listing li').length){offre_id=1;}
    
    var html = $('#listing li:eq('+offre_id+')').html(); 
	
	$('#sejours > div').animate({'marginTop':'-90px'},{duration:250,queue:false}).fadeOut('normal',function(){
		$('.fiche:eq(0)').html(html)
		$(this).css({'marginLeft':'400px','marginTop':'0px'});
		
		if($('#listing li:eq('+offre_id+') div').hasClass('fiche_bleu')){var color='fiche_bleu';}
    	else                                                            {var color='fiche_rose';}    
    
    	$('#sejours').removeClass('fiche_bleu fiche_rose').addClass(color);   
    	$('#sejours div:eq(0)').removeClass('fiche_bleu fiche_rose').addClass(color);
    	$('#sejours div:eq(0) h2').after('<span class="toute_offre"><a href="#">Afficher toutes les offres</a></span>');
    	
		$(this).animate({'marginLeft':0},{duration:500,queue:false}).fadeIn(1500);		
		
	});   
     
    
      
    }
    
    
function redisdead(what,color) {
  $('#'+what).css('background',color);
  if(color=='red'){$('#'+what).css('color','white');}
  else            {$('#'+what).css('color','black');}
  }


function send_game(e) {

var erreur='';

var new_string = new String($('#email').attr('value'));  
if($('#email').attr('value').length<2 || !new_string.match("^[_\.0-9a-zA-Z-]*@[-_\.0-9a-zA-Z-]*[\.][0-9a-zA-Z]{2,5}$"))
  {
  var erreur=erreur+'- Votre Email est invalide\r\n';
  redisdead('email','red');
  }
else
  {
  redisdead('email','white');
  }
  
  
if($('#ville').attr('value').length<2)
  {
  var erreur=erreur+'- Votre Ville est invalide\r\n';
  redisdead('ville','red');
  }
else
  {
  redisdead('ville','white');
  }
  
if($('#reglement').attr('checked')!=true)
  {
  var erreur=erreur+'- Merci de prendre connaissance du règlement du concours et de cocher la case correcpondante\r\n';
  }

if(erreur){alert(erreur);}
else {

var data=$("#myform").serialize();
$.post('/jouer.php', data, 

function(d){
    if(d.ok){var message=d.ok;}
    else{var message="<p>une erreur est survenue lors de votre inscription.<br />Merci de ré-essayer plus tard</p>";}
    $('#jeu_form').html(message);
    }

, "json");

}
return false;
}


function game(){

	var info = {
	'img': new Array()
	};
	
	$('.form_jeu').scrollTop(0);

	var flashVer=-1;
	if(navigator.plugins!=null&&navigator.plugins.length>0){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]){var swVer2=navigator.plugins["Shockwave Flash 2.0"]?" 2.0":"";var flashDescription=navigator.plugins["Shockwave Flash"+swVer2].description;var descArray=flashDescription.split(" ");var tempArrayMajor=descArray[2].split(".");var versionMajor=tempArrayMajor[0];var versionMinor=tempArrayMajor[1];var versionRevision=descArray[3];if(versionRevision==""){versionRevision=descArray[4]}if(versionRevision[0]=="d"){versionRevision=versionRevision.substring(1)}else{if(versionRevision[0]=="r"){ersionRevision=versionRevision.substring(1);if(versionRevision.indexOf("d")>0){versionRevision=versionRevision.substring(0,versionRevision.indexOf("d"))}}}var flashVer=versionMajor+"."+versionMinor+"."+versionRevision}}else{if($.browser.msie){var version;var axo;var e;try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");version=axo.GetVariable("$version")}catch(e){}flashVer=version.replace("WIN ","").replace(",",".")}}flashVer=flashVer.split(".")[0];if(jQuery){(function(a){a.extend(a.fn,{fileUpload:function(b){if(flashVer>=9){a(this).each(function(){settings=a.extend({uploader:"uploader.swf",script:"uploader.php",folder:"",height:30,width:110,cancelImg:"cancel.png",wmode:"opaque",scriptAccess:"sameDomain",fileDataName:"Filedata",displayData:"percentage",onInit:function(){},onSelect:function(){},onCheck:function(){},onCancel:function(){},onError:function(){},onProgress:function(){},onComplete:function(){}},b);var d=location.pathname;d=d.split("/");d.pop();d=d.join("/")+"/";var f="&pagepath="+d;if(settings.buttonImg){f+="&buttonImg="+escape(settings.buttonImg)}if(settings.buttonText){f+="&buttonText="+escape(settings.buttonText)}if(settings.rollover){f+="&rollover=true"}f+="&script="+settings.script;f+="&folder="+escape(settings.folder);if(settings.scriptData){var g="";for(var c in settings.scriptData){g+="&"+c+"="+settings.scriptData[c]}f+="&scriptData="+escape(g)}f+="&btnWidth="+settings.width;f+="&btnHeight="+settings.height;f+="&wmode="+settings.wmode;if(settings.hideButton){f+="&hideButton=true"}if(settings.fileDesc){f+="&fileDesc="+settings.fileDesc+"&fileExt="+settings.fileExt}if(settings.multi){f+="&multi=true"}if(settings.auto){f+="&auto=true"}if(settings.sizeLimit){f+="&sizeLimit="+settings.sizeLimit}if(settings.simUploadLimit){f+="&simUploadLimit="+settings.simUploadLimit}if(settings.checkScript){f+="&checkScript="+settings.checkScript}if(settings.fileDataName){f+="&fileDataName="+settings.fileDataName}if(a.browser.msie){flashElement='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+settings.width+'" height="'+settings.height+'" id="'+a(this).attr("id")+'Uploader" class="fileUploaderBtn"><param name="movie" value="'+settings.uploader+"?fileUploadID="+a(this).attr("id")+f+'" /><param name="quality" value="high" /><param name="wmode" value="'+settings.wmode+'" /><param name="allowScriptAccess" value="'+settings.scriptAccess+'"><param name="swfversion" value="9.0.0.0" /></object>'}else{flashElement='<embed src="'+settings.uploader+"?fileUploadID="+a(this).attr("id")+f+'" quality="high" width="'+settings.width+'" height="'+settings.height+'" id="'+a(this).attr("id")+'Uploader" class="fileUploaderBtn" name="'+a(this).attr("id")+'Uploader" allowScriptAccess="'+settings.scriptAccess+'" wmode="'+settings.wmode+'" type="application/x-shockwave-flash" />'}if(settings.onInit()!==false){a(this).css("display","none");if(a.browser.msie){a(this).after('<div id="'+a(this).attr("id")+'Uploader"></div>');document.getElementById(a(this).attr("id")+"Uploader").outerHTML=flashElement}else{a(this).after(flashElement)}a("#"+a(this).attr("id")+"Uploader").after('<div id="'+a(this).attr("id")+'Queue" class="fileUploadQueue"></div>')}a(this).bind("rfuSelect",{action:settings.onSelect},function(j,h,i){if(j.data.action(j,h,i)!==false){var k=Math.round(i.size/1024*100)*0.01;var l="KB";if(k>1000){k=Math.round(k*0.001*100)*0.01;l="MB"}var m=k.toString().split(".");if(m.length>1){k=m[0]+"."+m[1].substr(0,2)}else{k=m[0]}if(i.name.length>20){fileName=i.name.substr(0,20)+"..."}else{fileName=i.name}a("#"+a(this).attr("id")+"Queue").append('<div id="'+a(this).attr("id")+h+'" class="fileUploadQueueItem"><div class="cancel"><a href="javascript:$(\'#'+a(this).attr("id")+"').fileUploadCancel('"+h+'\')"><img src="'+settings.cancelImg+'" border="0" /></a></div><span class="fileName">'+fileName+" ("+k+l+')</span><span class="percentage">&nbsp;</span><div class="fileUploadProgress" style="width: 100%;"><div id="'+a(this).attr("id")+h+'ProgressBar" class="fileUploadProgressBar" style="width: 1px; height: 3px;"></div></div></div>')}});if(typeof(settings.onSelectOnce)=="function"){a(this).bind("rfuSelectOnce",settings.onSelectOnce)}a(this).bind("rfuCheckExist",{action:settings.onCheck},function(m,l,j,k,o){var i=new Object();i.folder=d+k;for(var h in j){i[h]=j[h];if(o){var n=h}}a.post(l,i,function(r){for(var p in r){if(m.data.action(m,l,j,k,o)!==false){var q=confirm("Do you want to replace the file '"+r[p]+"'?");if(!q){document.getElementById(a(m.target).attr("id")+"Uploader").cancelFileUpload(p)}}}if(o){document.getElementById(a(m.target).attr("id")+"Uploader").startFileUpload(n,true)}else{document.getElementById(a(m.target).attr("id")+"Uploader").startFileUpload(null,true)}},"json")});a(this).bind("rfuCancel",{action:settings.onCancel},function(j,h,i,k){if(j.data.action(j,h,i,k)!==false){a("#"+a(this).attr("id")+h).fadeOut(250,function(){a("#"+a(this).attr("id")+h).remove()})}});a(this).bind("rfuClearQueue",{action:settings.onClearQueue},function(){if(event.data.action()!==false){a("#"+a(this).attr("id")+"Queue").contents().fadeOut(250,function(){a("#"+a(this).attr("id")+"Queue").empty()})}});a(this).bind("rfuError",{action:settings.onError},function(k,h,j,i){if(k.data.action(k,h,j,i)!==false){a("#"+a(this).attr("id")+h+" .fileName").text("Erreur : "+i.type+" - "+j.name);a("#"+a(this).attr("id")+h).css({border:"3px solid #FBCBBC","background-color":"#FDE5DD"})}});a(this).bind("rfuProgress",{action:settings.onProgress,toDisplay:settings.displayData},function(j,h,i,k){if(j.data.action(j,h,i,k)!==false){a("#"+a(this).attr("id")+h+"ProgressBar").css("width",k.percentage+"%");if(j.data.toDisplay=="percentage"){displayData=" - "+k.percentage+"%"}if(j.data.toDisplay=="speed"){displayData=" - "+k.speed+"KB/s"}if(j.data.toDisplay==null){displayData=" "}a("#"+a(this).attr("id")+h+" .percentage").text(displayData)}});a(this).bind("rfuComplete",{action:settings.onComplete},function(k,h,j,i,l){if(k.data.action(k,h,j,unescape(i),l)!==false){a("#"+a(this).attr("id")+h).fadeOut(250,function(){a("#"+a(this).attr("id")+h).remove()});a("#"+a(this).attr("id")+h+" .percentage").text(" - Completed")}});if(typeof(settings.onAllComplete)=="function"){a(this).bind("rfuAllComplete",settings.onAllComplete)}})}},fileUploadSettings:function(b,c){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").updateSettings(b,c)})},fileUploadStart:function(b){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").startFileUpload(b,false)})},fileUploadCancel:function(b){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").cancelFileUpload(b)})},fileUploadClearQueue:function(){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").clearFileUploadQueue()})}})})(jQuery)};
	

	$('#fileUL').fileUpload({
		'uploader': '/lib/uploadify/uploader.swf',
		'cancelImg': '/lib/uploadify/cancel.png',
		'script': '/lib/uploadify/upload.php',
		'folder': '/download/site-principal/jeu/upload',
		'fileDesc': 'Image Files',
		'fileExt': '*.jpg;*.jpeg',
		'multi': false,
		'auto': true,
		'sizeLimit': 750000,
		'buttonText':'Choisir une photo',
		'onComplete': function(event, z, a,data,c) {
			
			var nb = info.img.length;	
			info.img[nb] = {}		
		
			eval('var php = '+data);
			
			info.img[nb].file = php.file;	
			info.img[nb].titre = $('#title').val();
			info.img[nb].pdv = $('#pdv').val();
			
			$('#upload_message').html('<p>Télécharger votre <strong>photo n°2</strong></p><p>ou <strong style="color:orange">validez directement votre participation</strong></p>');
			
			var type = ($('#couleur').attr('checked') == true)? 'couleur': 'noir et blanc';
			info.img[nb].type = type;
			
			var html = '<img src="'+info.img[nb].file+'" class="img"><p>'+info.img[nb].titre+'</p><p>'+info.img[nb].pdv+'</p><p>'+info.img[nb].type+'</p><p><a href="#">effacer</a></p>';
			$('.photo'+(nb+1)).html(html);
			$('#title,#pdv').val('');
			
			if(nb==1){
				$('.photo2, .ending').css('display','block');
				$('#upload_form, #fileUL, #fileULUploader').css('display','none');
			}
		}
	});

	$('.one').live('click',function(){		
		
		var error='';
		
		if($('#nom').val().length<2){
			error += '- Nom est invalide\n';
		}
		if($('#prenom').val().length<2){
			error += '- Prénom est invalide\n';
		}
		if($('#age').val()<0 && $('#age').val()>90 && isNaN($('#age').val()) && $('#age').val().length<1){
			error += '- Age est invalide\n';
		}
		if($('#adresse1').val().length<10){
			error += '- Adresse est invalide\n';
		}
		if($('#cp').length<5 && isNaN($('#cp').val())){
			error += '- Code postal est invalide\n';
		}
		if($('#ville').val().length<2){
			error += '- Ville est invalide\n';
		}
		var new_string = new String($('#email').val()); 
		if($('#email').attr('value').length<2 || !new_string.match("^[_\.0-9a-zA-Z-]*@[-_\.0-9a-zA-Z-]*[\.][0-9a-zA-Z]{2,5}$")){
			error += '- Email est invalide\n';
		}
		if($('#tel').val().length<10){
			error += '- Téléphone est invalide\n';
		}
		if($('#reglement').attr('checked')==false){
			error += '- Veuillez prendre connaissance du règlement et cochez la case correspondante\n';
		}
		
		
		
		if(error==''){
			move('+');
			$('.step1_1').addClass('step1_2').removeClass('step1_1');
			$('.step2_1').addClass('step2_2').removeClass('step2_1');
			$(this).addClass('two').removeClass('one');			
			
		}
		else {
			alert(error);
		}
	});
	
	$('.two').live('click',function(){
			
		var nb = info.img.length;
		if(nb >0) {
		
			data = {
			
				nom : $('#nom').val(),
				prenom : $('#prenom').val(),
				prenom : $('#prenom').val(),
				age : $('#age').val(),
				adresse1 : $('#adresse1').val(),
				adresse2 : $('#adresse2').val(),
				cp : $('#cp').val(),
				ville : $('#ville').val(),
				email : $('#email').val(),
				tel : $('#tel').val(),
				img1 : info.img[0].file,
				titre1 : info.img[0].titre,
				pdv1 : info.img[0].pdv,
				type1 : info.img[0].type			
			};
			
			
			if(typeof info.img[1] == 'object') {
				data.img2 = info.img[1].file;
				data.titre2 = info.img[1].titre;
				data.pdv2 = info.img[1].pdv;
				data.type2 = info.img[1].type;
			}
			
			data.newsletter = ($('#newsletter').attr('checked')==true)? 'on' : 'off';
			
				$.post('/jouer.php',data,function(d){
				if(typeof d.ok == 'string'){
					move('+');
					$('.step').css('display','none');
				}
				else {
					alert(d.error);
				}
			},'json');			
			
		}
		else {
			alert('Veuillez au moins présenter une photo');
		}

	});
	
	
	$('#close').live('click',function(){
		$('#jeu2').css('display','none');
    	$('#flash_top_left').css('display','block');
    	$('#meteo_flash').css('display','block'); 
	});
	
	$('.regle').live('click',function(){
	
		display = ($('#info_reglement').css('display')=='block' ) ? 'none' : 'block';
		
		$('#info_block').css('display',display);
		$('#info_reglement').css('display',display);
		$('#info_lot').css('display','none');
	});
	
	$('.lot').live('click', function(){
	
		display = ($('#info_lot').css('display')=='block') ? 'none' : 'block';
		
		$('#info_block').css('display',display);
		$('#info_lot').css('display',display);
		$('#info_reglement').css('display','none');
	});
	
	$('.doubleClose').live('click', function(){
		
		$('#info_block').css('display','none');
		$('#info_lot').css('display','none');
		$('#info_reglement').css('display','none');
	});

	
	$('.photo1 a, .photo2 a').live('click',function(e){
		e.preventDefault();
		var id = $(this).parent('p').parent('div').attr('class').replace(/photo/g,'');
		id = parseInt(id)-1;
		
		id = (id==1) ? 0 : 1;
		
		var tmp = '';
		if(typeof info.img[id] == 'object'){
			var tmp = info.img[id];
			info.img = new Array();
			info.img[0] = tmp;
		}
		else {
			info.img = new Array();
			$('#upload_message').html('<p>Télécharger votre <strong>photo n°1</strong></p>');
		}		
				
		var nb = info.img.length;

		if(nb>0) {
			var html = '<img src="'+info.img[0].file+'" class="img"><p>'+info.img[0].titre+'</p><p>'+info.img[0].pdv+'</p><p><a href="#">effacer</a></p>';
			}
		else {
			var html ='';
			}
		$('.photo1').html(html);	
		
		$('.photo2,.ending').css('display','none');
		$('#upload_form,#fileULUploader').css('display','block');

	});
	
	$('.step1_2').live('click',function(){
		move('-');
		$('.step1_2').addClass('step1_1').removeClass('step1_2');
		$('.step2_2').addClass('step2_1').removeClass('step2_2');
		$('.two').addClass('one').removeClass('two');
	});
	
	var mtime = mktime(0, 0, 0, 8, 26, 2009);
	if(mtime>time()) {
		$('#flash_top_left').live('click',function(){		
			clic_campagne();
		});
	}
	else {
		$('#flash_top_left').remove();
	}
	
	var move = function(sens){	
		var scroll = parseInt($('.form_jeu').scrollTop());
		var val = (sens=='-')? (scroll-380)+'px' : (scroll+380)+'px';
			
		$('.form_jeu').animate({'scrollTop':val},200);
	}
	
}

function clic_campagne() {
    $('#jeu2').css('display','block');
    $('#flash_top_left').css('display','none');
    $('#meteo_flash').css('display','none');   
	//window.open('http://www.vinsdeloire.fr/','Jeux','toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes'); 
    
	}
    
function clic_campagne_close() {
    $('#jeu2').css('display','none');
    $('#flash_top_left').css('display','block');
    $('#meteo_flash').css('display','block');    
    }
    
    
function linkStat(){

	$('.wysi').click(function(e){	
		var rel = $(this).attr('rel');	
		stat('loire_atlantique','','','','Réservation;'+rel);
	});
}

$(document).ready(function() {
 
    if($.browser.msie==true && $.browser.version<7) {
    DD_belatedPNG.fix('.pngfix'); 
    superfish('.fish');    
    }
    
    linkStat();
    
    //menu correctif
    $('#we').mouseover(function(){
    	var ul = $('ul',this);
		var height = -(ul.height() + 80);
		ul.css('margin-top',height);
	});
    
    //jeu
    var g = new game();
	    
    // carto
    $('#guide a').click(function(e){
        e.preventDefault();
        generate_validate();
        });
    
    $('#sejours #listing').data('height',$('#sejours #listing').height()).css({'height':0,'margin-top':0,'display':'none'});
    
    $('.toute_offre a').live('click',function(e){    
        e.preventDefault();        
        $('#sejours #listing').css({'height':0,'margin-top':0,'display':'block'});
        $('#sejours #listing').animate({'height':$('#sejours #listing').data('height'),marginTop:'-'+($('#sejours #listing').data('height')-1)},{duration:1000,queue:false}).css({'height':0,'margin-top':0,'display':'block'});
    	clearInterval(sejour);
	});
    
    $('#closer').click(function(e){
        e.preventDefault();
        $('#sejours #listing').css('display','none'); 
        $('#sejours #listing').animate({'height':0,marginTop:0},{duration:1000,queue:false,complete:function(){
            $(this).css({'display':'none'});
            }
        }); 
		sejour =  setInterval(offre_rotate,6000);
        
    });
    
    $('#prevision_open').click(function(){
    
       if( $('#prevision_win').css('display')!='none'){$('#prevision_win').css('display','none');}
       else{$('#prevision_win').css('display','block');}
        
    });
    
    $('#close_meteo').click(function(){
    
       $('#prevision_win').css('display','none');
        
    });
    
    
img_val=2; 
$('#mainspace').bind('loaded',function(){

    $('#rotate_acc').css('backgroundImage','url("/download/site-principal/charte/fond2.jpg")');
    setInterval(bgrotate,10000);    
    }).prepend('<div id="rotate_acc" style="opacity:1;position:absolute;margin-top:23px;height:481px;width:926px;background-position: 0 -23px;background-repeat: no-repeat;"></div>');

for(var i = 2; i<=10; i++)
    {
    var a=$('<img>').attr('src', '/download/site-principal/charte/fond'+i+'.jpg').css('display','none').appendTo('body');
    
    if(i==10){    
        $(a).load(function(){
            $('#mainspace').css('backgroundImage','url("/download/site-principal/charte/fond_noir.png")');
            $('#mainspace').trigger('loaded');
            
            });
        }
    }
    
offre_id=1;    
if($('#sejours #listing li').length>2){
	sejour = setInterval(offre_rotate,6000);
}

$('#myform').submit(function(e){return send_game(e);});    
}); 

$(window).resize(function(){if($('#div_result_layer').css('display')=='block'){placingCarto();}});