
// Grrrrrrrr
$.each($.browser, function(i) { msie = $.browser.msie ? true : false; });

// la position des zoom sur le plan de masse
var timer;
var planpos = [
  {'n':1, 't':151, 'l':245, 'y1':183, 'x1':277, 'w1':30, 'h1':30 }, // entrée
  {'n':1, 't':191, 'l':267, 'y1':217, 'x1':293, 'w1':25, 'h1':25}, // parking
  {'n':1, 't':181, 'l':282, 'y1':223, 'x1':329, 'w1':32, 'h1':42}, // place
  {'n':3, 't':91,  'l':329, 'y1':110, 'x1':383, 'w1':50, 'h1':35, 
                            'y2':186, 'x2':351, 'w2':40, 'h2':35, 
                            'y3':224, 'x3':362, 'w3':45, 'h3':45}, // hôtels
  {'n':1, 't':200, 'l':216, 'y1':245, 'x1':254, 'w1':75, 'h1':79}, // chipping land
  {'n':1, 't':202, 'l':327, 'y1':236, 'x1':354, 'w1':23, 'h1':24}, // spa
  {'n':1, 't':204, 'l':431, 'y1':229, 'x1':456, 'w1':25, 'h1':23}, // club house
  {'n':1, 't':121, 'l':351, 'y1':144, 'x1':406, 'w1':50, 'h1':85}, // practice
  {'n':1, 't':169, 'l':293, 'y1':199, 'x1':316, 'w1':30, 'h1':30}, // tennis
  {'n':1, 't':213, 'l':270, 'y1':247, 'x1':290, 'w1':35, 'h1':37}, // chip & putt
  {'n':1, 't':182, 'l':289, 'y1':213, 'x1':316, 'w1':15, 'h1':22}, // kids club
  {'n':1, 't':202, 'l':281, 'y1':235, 'x1':311, 'w1':20, 'h1':15}, // riad d'accueil 
  {'n':1, 't':45,  'l':616, 'y1':69,  'x1':640, 'w1':53, 'h1':35}  // amen corner
];


// les cases grises
$('.case, .detail').css({position:'absolute', textAlign:'left'}).each(function(){
  var case_w = parseInt($(this).css('width').replace('px',''));
  var case_h = parseInt($(this).css('height').replace('px',''));
  $(this).css({wdith: (case_w+20)+'px', height: (case_h+20)+'px', backgroundColor: 'transparent', padding: 0})
    .wrapInner('<div class="txt" style="position:absolute"></div>')
    .prepend('<div class="dropshadow"><img src="/images/generic/fond-case-gris-1.gif" ' + 
      ' width="' + case_w + '"' + 
      ' height="' + case_h +'"></div>');
  $(this).find('.txt').css({padding:'8px'});
});


if ($('#accueil').length != 0) {
  
  $('#accueil').show();
  if (!msie) $('#accueil_textes').css('opacity', 0.0).animate({opacity: 1.0}, 2000);
  $('#accueil_textes').show(); 
  $('#legendes').css('opacity',0.0).animate({opacity: 0.0}, 4000).animate({opacity: 1.0}, 1000); 
  $('#terre'   ).css('opacity',0.0).animate({opacity: 0.0}, 4000).animate({opacity: 1.0}, 1000);
  $('#golf'    ).css('opacity',0.0).animate({opacity: 0.0}, 4400).animate({opacity: 1.0}, 1000);
  $('#plantes' ).css('opacity',0.0).animate({opacity: 0.0}, 4800).animate({opacity: 1.0}, 1000);
  $('#atlas'   ).css('opacity',0.0).animate({opacity: 0.0}, 5200).animate({opacity: 1.0}, 1000);
  $('#eau'     ).css('opacity',0.0).animate({opacity: 0.0}, 5600).animate({opacity: 1.0}, 1000);

  tempo1 = setTimeout("makecycle()", 4000);  
  tempo2 = setTimeout("removeshit()", 6600);  

  function makecycle(){
    $.fn.cycle.defaults.timeout = 5000;
    $('#terre'   ).cycle({ fx: 'fade',        delay: 0    });
    $('#golf'    ).cycle({ fx: 'fade',        delay: 400  });
    $('#plantes' ).cycle({ fx: 'fade',        delay: 800  });
    $('#atlas'   ).cycle({ fx: 'fade',        delay: 1200 });
    $('#eau'     ).cycle({ fx: 'fade',        delay: 1600 });
    $('#legendes').cycle({ fx: 'fade',        delay: 1600 });
  }

  function removeshit(){
    $('#accueil_textes').hide();
    $('#accueil_h1').hide();
    $('.image').hide();
  }
}


$(document).ready(function() {
  i = 0;
  langfr = window.location.href.match(/\/fr\//);

  // le plan de masse
  plantxt = $('h2').text();
  $('#plan li').each(function(i){
    // création de hotspots sur le plan avec l'array
    for(a=1; a<=planpos[i]['n']; a++) {
      var cssPi = {
        //border: '1px solid red',
        position: 'absolute',
        opacity: 0.05,
        backgroundColor: '#725d50',
        top:    planpos[i]['y'+a]+'px',
        left:   planpos[i]['x'+a]+'px',
        width:  planpos[i]['w'+a]+'px',
        height: planpos[i]['h'+a]+'px'
      }
      $('#content').append('<div class="pi'+a+'-'+i+'"></div>');
      $('.pi'+a+'-'+i).css(cssPi).hoverIntent(
        function(){
          j = $(this).attr('class').replace(/pi\d-/, '');
          $('.li'+j).css('color', '#9fc204');
          $('h2').text($('.li'+j).text());
          showicon(j);
        },
        function(){
          $('.li'+$(this).attr('class').replace(/pi\d-/, '')).css('color', '#fff');
          $('h2').text(plantxt);
          showicon(false);
      }); // .html('pi'+a+'-'+i)
    }
    $(this).attr('class', 'li'+i).hoverIntent(
      function(){
      $(this).css('color', '#9fc204').css('cursor', 'pointer');
      $('h2').text($(this).text());
      showicon($(this).attr('class').replace('li', ''));
      },
      function(){
      $(this).css('color', '#fff').css('cursor', 'default');
      $('h2').text(plantxt);
      showicon(false);
    });
  });
  


  // les ombres
  $('.dropshadow').each(function(){
    var w = parseInt($(this).find('img').css('width').match(/[0-9]+/));
    var h = parseInt($(this).find('img').css('height').match(/[0-9]+/));
    $(this)
      .css('height', (h+18)+'px')
      .css('width', (w+18)+'px');
    $(this).prepend('<div class="wrap0">' +
    '<div class="wrap1" style="width: '+(w+8)+'px">' +
    '</div><div class="wrap00" style="width: '+(w+8)+'px">' +
    '<div class="wrap2" style="height: '+h+'px">' +
    '</div><div class="wrap3" style="width: '+w+'px; height: '+h+'px"></div></div></div>');
    if(msie) {
      $(this).find('img').css('margin-top', '-'+(h+8)+'px');
    } else {
      $(this).find('img').css('margin-left', '-'+(w+8)+'px');
    }
  });
  
  
  // les plans des villas
  i = 0;
  if($('#villa').length != 0) { // alert(pieces.cui);
    var over = '';
    var overTimer;
    var src = $('#villa .image').html().match(/src="([^"]+)"/);
    function allumepiece(t, onoff, liste) {
      var current_class = t.attr('class');
      if (onoff) { // on
        $('.image .'+current_class).find('img').fadeTo('fast', 1.0);
        if (over == current_class) clearTimeout(overTimer);  
        over = current_class;
        if (liste) {
          t.css('color', '#9fc204').css('cursor', 'pointer');
        } else {
          $('.pieces .'+current_class).css({color:'#9fc204'});
        }
      } else { // off
        //$('.image .'+current_class).find('img').fadeTo('fast', 0.1);
        // pour ne pas que la zone clignote uand elle est en plusieurs parties
        overTimer = setTimeout("$('.image ."+over+"').find('img').fadeTo('fast', 0.1)", 50);
        if (liste) {
          t.css('color', '#fff').css('cursor', 'default');
        } else {
          $('.pieces .'+current_class).css({color:'#fff'});
        }
      }
    }
    $('#villa .image img:first').fadeTo('slow', 0.5);
    // récupération des données de la liste
    var pieces = new Object();
    $('#villa').find('.pieces li').each(function(){
      // le text.replace pour cette &#!§$*¿ d'IE
      pieces[$(this).attr('class')] = $(this).text().replace(/^\s+|\s+$/g,'');
      $(this).hover(
        function(){
          allumepiece($(this), true, true);
        },
        function(){
          allumepiece($(this), false, true);
      });
    });
    $('#villa').find('area').each(function(i){
      var coords = $(this).attr('coords').split(',');
      var title = $(this).attr('title');
      var x1 = parseInt(coords[0]);
      var y1 = parseInt(coords[1]);
      var x2 = parseInt(coords[2]);
      var y2 = parseInt(coords[3]);
      var w = x2-x1;
      var h = y2-y1;
      var cssArea = {
        //border: '1px solid red',
        position: 'absolute',
        overflow: 'hidden',
        display: 'block',
        left:   x1+'px',
        top:    y1+'px',
        width:  w+'px',
        height: h+'px'
      }
      
      $('#villa .image').append('<div id="img_'+i+'"><img class="area" src="'+src[1]+'"></div>');
      var current_title = $(this).attr('title');
      $.each(pieces, function(key, val){
        if(current_title == val) $('#img_'+i).addClass(key); //.text(src);
      });
      // debug
      if ($('#img_'+i).attr('class') == '') {
        $('#img_'+i).css('border', '1px solid yellow').text($(this).attr('title'));
      }
      $('#img_'+i).css(cssArea).hover(
        function(){
          allumepiece($(this), true, false);
        },
        function(){
          allumepiece($(this), false, false);
      });
    $('#img_'+i).find('img')
      .css('position', 'absolute')
      .css('top', '0')
      .css('left', '0')
      .css('margin-left', (-x1)+'px')
      .css('margin-top', (-y1)+'px');
    });
    //$('#villa .image').attr('src', '').css('background-color', '#f00').fadeTo(0, 1); // test
    $('.area').fadeTo(0, 0.1);

    // le rappel de la norma marocaine
    detail = $('#villa .detail .txt').html();
    if(langfr != null) norme = "<p><br>La surface des villas <br>s'entend selon les <br>normes marocaines.</p>";
    else norme = "<p><br>Villas surface areas <br>are expressed according <br>to Morrocan regulations.</p>";
    
    $('#villa .detail').hover(
      function(){
        $('#villa .detail .txt').html(norme);
      },
      function(){
        $('#villa .detail .txt').html(detail);
    });
  }

  
  // l'accueil des 5 éléments
  if($('#elements').length != 0) {
    $('#elements').find('.eimage').fadeTo('slow', .3);
    $('#elements').find('.texte');
    $('#elements .panneau').hover(
      function(){
        $(this).find('.eimage').fadeTo('fast', 1.0);
      },
      function(){
        $(this).find('.eimage').fadeTo('fast', 0.3);
    });
    $('#menu li a').each(function(i){
      var txt = $(this).text().replace(/^\s*\.?|\s+$/g,'');
      $(this).hover(
        function(){
          $('#elements').find("img[@alt*="+txt+"]").fadeTo('fast', 1.0);
          if($(this).text().match(/5/)) $('.eimage').fadeTo('fast', 1.0);
        },
        function (){
          $('#elements').find("img[@alt*="+txt+"]").fadeTo('fast', 0.3);
          if($(this).text().match(/5/)) $('.eimage').fadeTo('fast', 0.3);
      });
    });
  }

    
    // l'accueil des villas
  if($('#accueil_villas').length != 0) {
    $('#accueil_villas .fond').fadeTo(0, 0.05).css('background-color', '#725d50');
    $('#accueil_villas .zone').css('cursor', 'pointer').click(
      function(){
        document.location = $("#menu a[@id*=m_"+$(this).attr('id')+"]").attr('href');
    }).hover(
      function(){
        $(this).find('.txt').css('background-color', '#9fc204');
      },
      function(){
        $(this).find('.txt').css('background-color', 'transparent');
    }).find('.txt').css({padding:'2px'});
  }

  
  // l'accueil des villas du golf
  if($('#villasgolf_legende').length != 0) {
    $('#villasgolf_legende .cols').css('cursor', 'pointer').hover(
      function(){
        $(this).css('background-color', '#9fc204');
        $('#niveau3 a#m_'+$(this).attr('id')).css('background-color', '#9fc204');
      },
      function(){
        $(this).css('background-color', 'transparent');
        $('#niveau3 a#m_'+$(this).attr('id')).css('background-color', 'transparent');
    }).click(function(){
      document.location = $("#niveau3 a[@id*=m_"+$(this).attr('id')+"]").attr('href');
    });
    $('#niveau3 a').hover(
      function(){
        $('#villasgolf_legende #'+$(this).attr('id').replace('m_', '')).css('background-color', '#9fc204');
      },
      function(){
        $('#villasgolf_legende #'+$(this).attr('id').replace('m_', '')).css('background-color', 'transparent');
    });
  }
  
  
  // le contact
  if($('#contact_form').length != 0) { 
    /*
    var validator = $("#contact_form").bind("invalid-form.validate", function() {
      //$("#summary").html('Les ' + validator.numberOfInvalids() + ' champs marqués <span class="must">*</span> doivent être renseignés.')
      $("#summary").html('<span class="must">Les champs marqués * doivent être renseignés.</span>')
        .find('.must').css('color', 'red').parents('#submit_field').css('background-color', '#88766b');
    }).validate({
      debug: true,
      errorPlacement: function(error) {
        $(error).appendTo($('#vide'));
      },
      highlight: function(element) {
        $(element).parents('#'+$(element).attr('id')+'_field').css('border-color', 'red')
         .find('.must').css('color', 'red');
      },
      unhighlight: function(element) {
        $(element).parents('#'+$(element).attr('id')+'_field').css('border-color', '#9fc204')
          .find('.must').css('color', '#fff');
        $('#summary').html().replace(/\d/, validator.numberOfInvalids());
        //label.text("ok!").addClass("success");
      }
    });
    */
    $('#contact_form input, #contact_form textarea').change(function(){
      $(this).val($(this).val().replace(/[<>]/, '').replace(/^\s+|\s+$/g,''));
    });
    $('#email').change(function(){
      $(this).val(stripVowelAccent($(this).val()));
    });
    $('#pays').change(function(){
      $('#pays_sel').val($(this).find('option[selected]').text());
    });
    $('#contact_form').validate({
      //debug: true, // DEBUG
      rules: {
        nom:      {required: true},
        prenom:   {required: true},
        pays:     {required: true},
        email:    {required: true, email: true},
        message:  {required: true}
      }, 
      messages: {
        nom:      {required: langfr != null ? ", votre nom"     : ", your name"},
        prenom:   {required: langfr != null ? ", votre prénom"  : ", your surname"},
        pays:     {required: langfr != null ? ", votre pays"    : ", your country"},
        email:    {required: langfr != null ? ", votre email"   : ", your email", 
                      email: langfr != null ? ", votre email (il n'est pas valide)" : ", your email (it isn't valid)"},
        message:  {required: langfr != null ? ", votre message" : ", your message"}
      },
      errorPlacement: function(error) {
        $(error).appendTo($('#vide'));
        //$('#vide').show();
      },
      highlight: function(element) {
        $(element).parents('#'+$(element).attr('name')+'_field').css('border-color', 'red')
          .find('.must').css('color', 'red');
        $('#summary').css('border-bottom', '1px solid red').find('.must').css('color', 'red');
      },
      unhighlight: function(element) {
        $(element).parents('#'+$(element).attr('name')+'_field').css('border-color', '#9fc204')
          .find('.must').css('color', '#fff');
        //$('#summary').html().replace(/\d/, validator.numberOfInvalids());
        //label.text("ok!").addClass("success");
      }
    });
  }
  
 /* // pour les navigateurs intelligents, on remplace le onmouseover-out des trous
  if (!msie) $('area').each(function() {
    $(this).attr('onmouseover', null).attr('onmouseout', null);
    $(this).hoverIntent(
      function(){
        mateletrou($(this), true);
      },
      function(){
        mateletrou($(this), false);
    });
  });*/
  
});

// les trous du parcours
function mateletrou(it, show, hole) {
   var num = hole;
 //num = parseInt($(it).attr('href').match(/\d+$/));
 parseInt(document.location.href.match(/\d+$/)) != num ? $('#trou_on').hide() : $('#trou_on').show();
  //parseInt(document.location.href.match(/\d+$/)) != num ? $('#trou_on').hide() : $('#trou_on').show();
  if (show) {
    $('#trou_n'+num).show();
    if (timer != null) clearTimeout(timer);
  } else {
    $('.trou').not('#trou_on').hide();
    if ($(it).attr('class') != 'trou_on') timer = setTimeout("$('#trou_on').fadeIn(250)", 500);
  }
}


// fonction pour afficher les zoom dans le plan de masse
function showicon(i) {
  if(i !== false) { // on affiche
    i = parseInt(i);
    var m = -i*200; 
    var cssObj = {
      top:    planpos[i]['t']+'px',
      left:   planpos[i]['l']+'px',
      width:  '200px',
      height: '200px' 
    }
  } else { // on masque
    var m = 0; 
    var cssObj = {
      top:    '0',
      left:   '0',
      width:  '1px',
      height: '1px'
    }
  }
  $('#icones').css(cssObj).find('img').css('margin-left', m+'px');
}
// fonction qui remplace caractères accentués, cédilles et espace (manque ñ) pour le mail
function stripVowelAccent(str){
  var s=str;
  var rExps=[
    /[\xC0-\xC4]/g, /[\xE0-\xE4]/g,
    /[\xC8-\xCB]/g, /[\xE8-\xEB]/g,
    /[\xCC-\xCF]/g, /[\xEC-\xEF]/g,
    /[\xD2-\xD6]/g, /[\xF2-\xF6]/g,
    /[\xD9-\xDC]/g, /[\xF9-\xFC]/g,
    /[\xC7]/g, /[\xE7]/g, /[ ]+/
  ];
  var repChar=['A','a','E','e','I','i','O','o','U','u','C','c',''];
  for(var i=0; i<rExps.length; i++) s=s.replace(rExps[i],repChar[i]);
  return s;
}

/*
  parseUri 1.2.1
  (c) 2007 Steven Levithan <stevenlevithan.com>
  MIT License
*/

function parseUri (str) {
  var o   = parseUri.options,
      m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
      uri = {},
      i   = 14;
  while (i--) uri[o.key[i]] = m[i] || "";
  uri[o.q.name] = {};
  uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
    if ($1) uri[o.q.name][$1] = $2;
  });
  return uri;
};

parseUri.options = {
  strictMode: false,
  key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
  q: {
    name:   "queryKey",
    parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  },
  parser: {
    strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
    loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  }
};

