var animMenu1 = 0;
var activeModal = ''
var modalBoxPosTop = '100px';
var resizeTimer = null;
var mapLoaded = 0;
var lang = window.location.pathname.split('/')[1];
var modalElem = "modal-content";
var contactContent = [];
content['contact'] = '';
content['jobs'] = '';
var page;
//var activeLink = 0;

if(typeof removeSlideShowCat == 'undefined'){
  var removeSlideShowCat = '';
}

if(typeof initSlideExist == 'undefined'){
  var initSlideExist = 0;
}

if(typeof slideRandom == 'undefined'){
  var slideRandom = 0;
}


$(function() {

    var flashvars1 = {removeSlideShowCat: removeSlideShowCat,initSlideExist:initSlideExist,slideRandom:slideRandom};//,../videos/vdo2.flv,../videos/vdo3.flv
		var params1 = {wmode:"opaque"};
		var attributes1 = {};

    //log(flashvars1);
		swfobject.embedSWF("/swf/slide.swf", "slide-video", "910", "272", "8", null, flashvars1, params1, attributes1);

		swfobject.embedSWF("/swf/slide-small.swf", "slide-video-mini", "610", "272", "8", null, flashvars1, params1, attributes1);


    //var flashvars;
    //var flashvars = false;
		//var params = {wmode:"opaque"};
		//var attributes = {id:"menu-flash-home"};
		//swfobject.embedSWF("swf/menu-flash-home.swf", "menu", "980", "120", "8", null, flashvars, params, attributes);

  //$.history.init(callback);
  // taget blank for external link
  $('a.extern').attr("target", "_blank");

  modalElem = $("#"+modalElem);

  // on resize window actions
  $(window).resize(function() {
    if(activeModal!=''){
      if (resizeTimer) clearTimeout(resizeTimer);
      resizeTimer = setTimeout(adjustModalBox, 100);
    }

  });

  /* ============= contact - jobs ============== */
  //select all the a tag with id with modal

  $('a[href=#contact],a[href=#jobs]').click(function() {
  //$('#modal-contact, #modal-jobs').click(function() {
    // Make keys editable in loaded content
    if ( typeof(adminMode) != "undefined" ) {
      if ( typeof(modeEdit) != "undefined" ) {
        init_edit_mode();
      }
    }

    page = $(this).attr('href').split('#')[1];
    initLaunchModal(page);
    
  });

  // open contact or jobs
  anchor = getAnchor();
  if(anchor.length>0){
    initLaunchModal(anchor);
  }

  //if close button is clicked
  $('.window .close').click(function(e) {
    //Cancel the link behavior
    e.preventDefault();
    $('#e.mask').hide();
    $('.window').hide();
    activeModal = '';
    $("#close-modal").addClass('hidden');
  });

  //if mask is clicked
  $('#mask,#close-modal').click(function() {
    $("#mask").hide();
    $('.window').hide();
    activeModal = '';
    $("#close-modal").addClass('hidden');
    //log(window.location.hash);
    //window.location.hash = "";
    //log(window.location.hash);
    //location.hash.replace(/^#/, '');

  });
  /* =========== end contact - jobs ============ */


  $("#slide-menu-left").click(function(event) {
    //log("click menu left");
  });
  $("#slide-menu-right").click(function(event) {
    //log("click menu right");
  });

  // clean temp a
  $("a").each(function(e){
    if($(this).attr('href')=='#'){
      $(this).click(function(event) {
        return false;
    });
    }
  });

  // arrow for the slide 
  /*$("#slideshow-content,#slideshow-content-mini,#slide-menu-left,#slide-menu-right").mouseover(function() {
  $("#slide-menu-left,#slide-menu-right").removeClass("hidden");
  }).mouseout(function(){
  $("#slide-menu-left,#slide-menu-right").addClass("hidden");
  });*/

  // menu home page
  $("#menu1,#menu2,#menu3").mouseenter(function() {
    currElem = $(this);
    currElem.children(".menu-content").addClass("over-bt");
    currElem.children(".menu-content").children("ul.menu-links").children().addClass("over");
    currElem.children(".menu-bottom").addClass("over");
    currElem.children(".menu-content").children("div:first").html('<img src="/images/layout/anim-'+currElem.attr('id')+'.gif" />');

  }).mouseleave(function(){
    currElem = $(this);
    currElem.children(".menu-content").removeClass("over-bt");
    currElem.children(".menu-content").children("ul.menu-links").children().removeClass("over");
    currElem.children(".menu-bottom").removeClass("over");
    currElem.children(".menu-content").children("div:first").html('');
  });

  $("#menu1,#menu3,#menu2").each(function(e){
    currUrl = window.location.toString().replace(/^.*#/, '');
    var currObj = $(this);
    currObj.currUrl = currObj.find("a").attr('href');
    currH2 = currObj.find("h2");
    currObj.h2content = currH2.children("a").html();
    currH2.children("a").empty().before(currObj.h2content);
    //currH2.html(currObj.h2content);

    /*
     *currUrl = window.location.toString().replace(/^.*#/, '');
    var currObj = $(this);
    currObj.currUrl = currObj.find("a").attr('href');
    currH2 = currObj.find("h2");
    currObj.h2content = currH2.children("a").html();
    currH2.children("a").html('').before(currObj.h2content);
     */


    //currObj.currUrl = currObj.find("a").attr('href');
    //currObj.currUrl = currObj.find("a").attr('href',"#");
    //var tmpContent =
    //var currUrl = currObj.find("a").attr('href');
    $(this).click(function(){
      //if(activeLink !=1){

        //window.location.replace(currObj.currUrl);
        actuateLink(currH2.children('a')[0]);

        //activeLink = 1;
      //}
    });//.attr('href','return false;');*/
    //window.location.replace(currUrl);
    /*currObj.currUrl = currObj.find("a").click(function(){
      //if(activeLink !=1){
        
        window.location.replace(currObj.currUrl);
        
        //activeLink = 1;
      //}
    });//.attr('href','return false;');*/
    
    //return false
    /*currObj.click(function(){
      //$.history.load(currUrl);
      //log('link');
      //log(currUrl);
      /*window.location.assign = currUrl;
      window.location.href(currUrl);*/
      //window.location.assign = currUrl
      //$.history.load(this.href.replace(/^.*#/, ''));
      //if(activeLink !=1){
      /*log(currObj.currUrl);
        return false;
        window.location.replace(currObj.currUrl);
        //activeLink = 1;
     // }
      //window.location.replace(currObj.currUrl);
      //activeLink = 1;
      //log(currObj.currUrl);
    });*/
  });

  // menu content page
  /*$(".menu-content-mini:not(.separator-open)").mouseenter(function() {
    currElem = $(this);
    currElem.children("div:first").html('<img src="/images/layout/anim-'+currElem.children("div:first").attr('id')+'.gif" />');

  }).mouseleave(function(){
    currElem = $(this);
    currElem.children("div:first").html('');
  });*/

  var arrPreload = new Array("/images/layout/anim-menu1.gif","/images/layout/anim-menu2.gif","/images/layout/anim-menu3.gif");
  $.preloadImages(arrPreload);


})/*.keydown(function(e){

  switch(e.keyCode){
    case 37:
      //log('===> left');
      return false;
      break;
    case 39:
      //log('===> right');
      return false;
      break;
  }
});*/

function initLaunchModal(page){
  $("#general").intoViewport({duration:400,   easing:"swing" });
  // Get the page to load
  currContent = content[page];
  if(currContent==''){
    $.get('/' + lang + '/' + page, function(data) {
      content[page] = currContent = data;
      launchModal(page,currContent);
    })
  }else{
    launchModal(page,currContent);
  }
}

function adjustModalBox() {
  var winH = $(window).height();
  var winW = $(window).width();
  $('#mask').css({'width':winW,'height':winH});
  modalElem.css('left', winW/2 - modalElem.width()/2-10);
  var maskHeight = $(document).height();
  var maskWidth = $(window).width();

  //Set heigth and width to mask to fill up the whole screen
  $('#mask').css({'width':maskWidth,'height':maskHeight});

}

function getAnchor(){
  var url = window.location.toString();
  var anchor_index = url.indexOf('#');
  anchor = (anchor_index != -1) ? url.substring(anchor_index+1, url.length) : '' ;
  return anchor;
}

function launchModal(page,currContent){

  adjustModalBox();

  activeModal = 1;

  $('#modal-box-content').html(currContent);

  //Get the screen height and width
  var maskHeight = $(document).height();
  var maskWidth = $(window).width();

  //Set heigth and width to mask to fill up the whole screen
  $('#mask').css({'width':maskWidth,'height':maskHeight});

  //transition effect
  $('#mask').fadeIn(1000);
  $('#mask').fadeTo("slow",0.7);

  //Get the window height and width
  var winH = $(window).height();
  var winW = $(window).width();

  //Set the popup window to center
  modalElem.css('top',  modalBoxPosTop);
  modalElem.css('left', winW/2 - modalElem.width()/2-10);

  //transition effect
  $(modalElem).fadeIn(2000);
  if (page == 'contact') {
    initMap();
  }

  activeModal = modalElem.attr('id');

  // show close btn
  $("#close-modal").removeClass('hidden');
  //adjustModalBox();

}

function initMap() {
  var myLatlng = new google.maps.LatLng(50.84344061046842, 4.367966651916504);
  var myOptions = {
    zoom: 10,
    center: myLatlng,
    disableDefaultUI: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

  setMarkers(map);
  
}

function setMarkers(map) {

  var paName = 'Proactions SPRL';
  var paAddress = 'Avenue du Yorkshire 21';
  var paCodeCity = '1200 Bruxelles';
  var paUrl = 'http://www.proactions.be';
  var paUrlDisplay = 'www.proactions.be'; // URL affichée dans l'info-bulle
  var paLogo = '../images/layout/logo-small.png';
  var paLogoAlt = 'Proactions';
  var paLogoWidth = 168;
  var paLogoHeight = 80;
  var paLat = 50.85432617575676;
  var paLng = 4.431800544261932;

  // Add markers to the map

  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.

  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.
  var image = new google.maps.MarkerImage('../images/etoile-pushpin.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(30, 30),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 30));
  var shadow = new google.maps.MarkerImage('../images/etoile-pushpin-shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(46, 30),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 30));

    var myLatLng = new google.maps.LatLng(paLat, paLng);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        title: paName,
        zIndex: 11
    });

    // variables pour la redirection vers Google Maps si l'utilisateur veut un itinéraire
    var url = 'http://maps.google.com/maps?&amp;f=d&amp;ie=UTF8';
    var addr = escape(paName + ' @' + paLat + ',' + paLng);

    // content infoWinndow
    var contentString = '<div id="map-popup">' +
    '<strong>' + paName + '</strong><br/>' +
   // '<a href="' + paUrl + '">' + paUrlDisplay + '</a><br/>' +
    paAddress + ', ' + paCodeCity + '<br/>' +
   // '<img src="' + paLogo + '" alt="' + paLogoAlt + '" width="' + paLogoWidth + '" height="' + paLogoHeight + '" /><br/>' +
    '<br>Itinéraire : ' +
    '<a href="' + url + '&amp;daddr=' + addr + '" target="_blank">Vers ce lieu</a> - ' +
    '<a href="' + url + '&amp;saddr=' + addr + '" target="_blank">À partir de ce lieu</a>' +
    '</div>';

    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });

  //}
}

function menuOver(elem){
  elem.parent()
}

function log(data){
  if (typeof(console) != 'undefined' && typeof(console.log) == 'function'){
    console.log(data);
  }
}

/*
 * jQuery intoViewport Plugin
 * Scrolls an set of Elements into the browsers viewport, but only if neccesary and only minimum amount
 * @author Bernhard HÃ¤ussner
 * @version 1.0
 * @url
 * @licence http://www.gnu.org/licenses/gpl.html
 * @example $('a').eq(4).intoViewport(); // this ensures the 4th link on page is visible to user
 * Default Options: $('a').eq(4).intoViewport({duration:200,   easing:"swing" });
 * Example Options: $('a').eq(4).intoViewport({duration:"slow",easing:"linear"});
 * For all options see http://docs.jquery.com/Effects/animate#paramsoptions
 */

(function($){jQuery.fn.intoViewport=function(options){options=$.extend({duration:200,easing:"swing"},options||{});return this.each(function(){function scrTo(dest){$("html,body").stop().animate({scrollTop:dest},options);}var scr=$(document).scrollTop()||$(window).scrollTop(),wheight=$(window).height(),top=$(this).offset().top,eheight=$(this).outerHeight();if(scr>top){scrTo(top);}else if(scr!=top&&top+eheight>scr+wheight){scrTo(top+Math.min(eheight-wheight,0));}});};})(jQuery);

// http://blog.stchur.com/2010/01/15/programmatically-clicking-a-link-in-javascript/
function actuateLink(link)
{
   var allowDefaultAction = true;
      
   if (link.click)
   {
      link.click();
      return;
   }
   else if (document.createEvent)
   {
      var e = document.createEvent('MouseEvents');
      e.initEvent(
         'click'     // event type
         ,true      // can bubble?
         ,true      // cancelable?
      );
      allowDefaultAction = link.dispatchEvent(e);           
   }
         
   if (allowDefaultAction)       
   {
      var f = document.createElement('form');
      f.action = link.href;
      document.body.appendChild(f);
      f.submit();
   }
}
