
// We use the same length than in our old python script: keep_gymglish_cookies.py
var COOKIES_MAX_AGE=3*365; // in days
var DURATION_ANIMATION_HOME_PLANE = 10000; // In milliseconds
var DURATION_ANIMATION_HOME_BUBBLE = 3000; // In milliseconds


// overwrite the required function to support default value validation
$.tools.validator.fn("[required]", "Please complete this mandatory field.", function(el, v) {
    if (el.is(":checkbox")) { return el.is(":checked"); }
    var default_value = el.data('default_value');
    if (typeof default_value != 'undefined' && el.val() == default_value)
        return false;
    return !!v;             
});


  function updateActiveTabAndSubMenu(menu, submenu){
    $('.sub-menu').removeClass('active active-without-sub-menu');
    $('.menu li').removeClass('active active-without-sub-menu');
    if(submenu){
      $(menu).addClass('active');
      $(submenu).addClass('active');
    }
    else
      $(menu).addClass('active-without-sub-menu');
  }


  function mouseEnterInTab(menu, submenu){
    updateActiveTabAndSubMenu(menu, submenu);
  }


  function setCurrentTabAsActiveTab(){
      // We are not over a 'ul' tag so we assume that we are not over the menu nor the submenu
      var menu = $('.menu .current')
      var obj = $('.sub-menu-container .current');
      var submenu = (obj.length == 1)?obj[0]: null;
    
      updateActiveTabAndSubMenu(menu, submenu);
  }

  function mouseLeaveTab(event){
    if (event.relatedTarget.nodeName != 'UL' && $(event.relatedTarget).parents("ul").length == 0){
      setCurrentTabAsActiveTab();
    }
  }


  function loadTopMenu(){

      // Add events on all the tabs
      $('.menu li').each(function(index) {

        $(this).find('a').each(function(){
            $(this).removeAttr('title');
        });
        // Get the submenu (if we have it)
        var obj = $('#sub-'+ this.id);
        var submenu = (obj.length ==1)?obj[0]:null;

        $(this).mouseenter(function(){mouseEnterInTab(this, submenu)});
        $(this).mouseleave(function(event) {mouseLeaveTab(event, this, submenu)});
        if (submenu)
          $(submenu).mouseleave(function(event){mouseLeaveTab(event, this, submenu)});

        // All the part of the tab should be clickable
        $(this).click(function(){window.location.href = $('a', this).attr('href');});
      });
  }

  
  function prepareLinksForTooltip(obj){
    // Update the links which should be display in a tooltip. This links should target to an image, we prefer to display it in a tooltip
    //
    obj.each(function(){
      var elt = $('<span class="tooltip-image-to-add">'+$(this).html()+'</span>');
      elt.attr('title', '<div class="tooltip-to-use-content"><img src="'+ this.href+'" border="0" /></div>');
      $(this).replaceWith(elt);
    });
  }


  function onLoad(){
    loadTopMenu();
    setCurrentTabAsActiveTab();
    updateSiteVersion();
    initDefaultValueFields();
    setMiniformValidator();
    addOnclickEventOnRedirectLink();
    setCookiesAccordingToQueryString();
    initImageRotator(".images-rotator2");
    initImageRotator(".images-rotator");
    initGuidedTour();
    initGuidedTourV2();
    initGuidedTourV3();
    addEventsOnInterests();
    initFormValidator();
    initCallUsToolTip();
    initCallUsForm();
    initAddmoretesters();
    homeAnimationDelavigne(); /* only add animation callback if we have id #gg-animated-home' on the page */
    if(jQuery().pngFix)
        $(document).pngFix();
    // Init the tooltip (use for lemonde.fr)
    prepareLinksForTooltip($('a.link-tooltip'));
    $(".tooltip-to-add").tooltip({ position: "bottom middle", relative: true, offset: [0, -30]});
    $(".tooltip-image-to-add").tooltip({ position: "bottom right", relative: false, effect :'fade'});

    // Prevent the double click on all our forms
    $('form').each(function(){
        if ($(this).attr('id') == 'miniform'){
            // Special case, we should call a tracking function for the miniform
            $(this).preventDoubleClick(function(){miniformSucessTracking(); return true;});
        }
        else{
            $(this).preventDoubleClick();
        }
    });
  }

  $(document).ready(function() {
    onLoad();
    })


function initImageRotator(param){
    $(param+" .tabs").tabs(param+" .images > div", {
    //
	// enable "cross-fading" effect
	effect: 'fade',
	fadeOutSpeed: "slow",

	// start from the beginning after the last tab
	rotate: true

    // use the slideshow plugin. It accepts its own configuration
    }).slideshow({clickable: false,  autoplay: true});
}


function initGuidedTour(){
    $(".guided-tour .guided-tour-middle .more").toggle(false);
    $(".guided-tour .guided-tour-middle .more-text").bind({click: function() {
        $(this).parent().children('.more').toggle();
    }});

    $(".guided-tour .tabs").tabs(".items > div", {
            //
	// enable "cross-fading" effect
	effect: 'fade',
	// fadeOutSpeed: "slow",

	// start from the beginning after the last tab
	rotate: false

    // use the slideshow plugin. It accepts its own configuration
    }).slideshow({clickable: false});
}


function initGuidedTourV2(){
    function setEventOnGuidedTourMoreLink(event,index){
      var divs = $("#more-menu div");
      divs.attr("style","display:none");
      $("#more").unbind().click(function(){ $(divs[index]).toggle(); });
    }

    $("#browsable").scrollable({"onSeek":setEventOnGuidedTourMoreLink}).navigator();
    setEventOnGuidedTourMoreLink(null,0);
    $('.navi a:first').addClass("active");
}


function initGuidedTourV3(){
    // Only use the guided tour on lemonde.fr
    $("#lemonde-browsable .more").attr("style","display:none");

    function updateScrollableHeight(){
      var api = $("#lemonde-browsable").data('scrollable');
      var item = $(api.getItems()[api.getIndex()]);
      $('.scrollable').height(item.height() + 20);
    }

    function setEventOnGuidedTourMoreLink(event,index){
      updateScrollableHeight();
      $('.more').hide();
    }

    if($("#lemonde-browsable").length){
      $('.more-link').click(function(){$(this).next('.more').toggle(); updateScrollableHeight();});
      $("#lemonde-browsable").scrollable({"onSeek":setEventOnGuidedTourMoreLink}).navigator();
      setEventOnGuidedTourMoreLink(null,0);
      $('.navi a:first').addClass("active");
    }
}


function initFormValidator(){

    $.tools.validator.addEffect("wall", function(errors, event) {
    
      var conf = this.getConf();
      // "show" function
      $.each(errors, function(index, error) {
        // erroneous input
        var input = error.input;
    	input.addClass(conf.errorClass);
    	input.removeClass('isValidated');
      });
    
    }, function(inputs)  {
      // "hide" function
        var conf = this.getConf();
    	inputs.removeClass(conf.errorClass);
        if(inputs.attr('required') == 'required')
    	    inputs.addClass('isValidated');
    });
}

function checkInputText(inputObj, defaultValue, color){
    color = color || '#999999';
    if (inputObj.value == "" ) {
	    inputObj.value = defaultValue;
	    inputObj.style.color = color;
        $(inputObj).removeClass('isValidated');
        $(inputObj).removeClass('invalid');
    }
    else
	    inputObj.value = inputObj.value;
}

function clearInputText(inputObj, defaultValue){
    if (inputObj.value == defaultValue ) {
	inputObj.value="";
	inputObj.style.color = 'black';
    }
}

function addEventsOnInterests(){
    // Add onchange event on all the interest checkboxes
    $(".field_interests input:checkbox").change(function() {
        showOrHideContactInformation();
    });

    $("#cinfo_who_are_you").change(function() {
        showOrHideContactInformationV2();
    });

    $("#cinfo_training_financed_by").change(function() {
        showOrHideContactInformationV2();
    });
    
    // Set default display
    if ($("#cinfo_who_are_you").length)
        showOrHideContactInformationV2();
    else if ($(".field_interests").length)
        showOrHideContactInformation();
}


function shouldShowContactInformation(){
    // Returns bool
    //
    // Returns true : if we should display the contact information
    //         false: otherwise
    //
    // We hide the contact information if training_financed_by is for 'myself' 
    // or if the who_are_you is for 'other-gp', 'unemployed', 'a student']

    var cinfo_who_are_you = $('#cinfo_who_are_you').val();
    var cinfo_training_financed_by = $('#cinfo_training_financed_by').val();

    // This value are defined in register_webcontact
    var non_ok_cinfo_who_are_you = ['', 'other-gp', 'unemployed', 'a student'];
    var non_ok_cinfo_training_financed_by = ['', 'myself'];

    if (cinfo_who_are_you == undefined || cinfo_training_financed_by == undefined)
        return false;

    var ok=true;
    for (var i=0; i < non_ok_cinfo_who_are_you.length; i++)
        if (cinfo_who_are_you == non_ok_cinfo_who_are_you[i]){
            ok=false;
            break;
        }

    if (!ok)
        return false;

    var ok=true;
    for (var i=0; i < non_ok_cinfo_training_financed_by.length; i++)
        if (cinfo_training_financed_by == non_ok_cinfo_training_financed_by[i]){
            ok=false;
            break;
        }

    return ok;
}


function isTelephonRequired(isShow){
    // Returns bool
    //
    // Returns true if the telephon field is required
    // It is not required if the field is not displayed.

    if (! isShow)
        return false;

    var cinfo_who_are_you = $('#cinfo_who_are_you').val();
    // This value are defined in register_webcontact
    var ok_cinfo_who_are_you = ["an HR Director", "a company Director", "self-employed", "a language school representative", "a university representative"]

    for (var i=0; i < ok_cinfo_who_are_you.length; i++)
        if (cinfo_who_are_you == ok_cinfo_who_are_you[i])
            return true;

    return false;
}


function updateTelephonField(isShow){
    // Returns nothing
    //
    // Update the telephon field and label.

    var label = $(".field_cinfo_telephone label span");
    var input = $(".field_cinfo_telephone #cinfo_telephone");
    if (isTelephonRequired(isShow)){
        addRequiredStarIfNeeded(label);
        input.attr('required' ,'required');
    }
    else{
        removeRequiredStarIfNeeded(label);
        input.removeAttr('required');
        input.removeClass('invalid');
    }
}

function updateCompanyField(isShow){
    // Returns nothing
    //
    // Update the company field and label.

    var label = $(".field_cinfo_companyname label span");
    var input = $(".field_cinfo_companyname #cinfo_companyname");
    if (isShow){
        addRequiredStarIfNeeded(label);
        input.attr('required' ,'required');
    }
    else{
        removeRequiredStarIfNeeded(label);
        input.removeAttr('required');
        input.removeClass('invalid');
    }
}


function addRequiredStarIfNeeded(obj){
    //Returns nothing
    //
    // Remove the '*' at the end of the given obj if it already has one.
    if (obj.length){
        var label = obj.html();
        if (label[label.length-1] != '*')
            obj.html(label + ' *');
    }
}


function removeRequiredStarIfNeeded(obj){
    // Returns nothing
    //
    // Add a '*' at the end of the given obj if it already doesn't have one.
    if (obj.length){
        var label = obj.html();
        if (label[label.length-1] == '*')
            obj.html(label.substring(0, label.length-2));
    }
}


function showOrHideContactInformation(){
    // Show or hide the contact information according to the interest checkboxes status
    var fieldIds = ['cinfo_companyname', 'cinfo_fonction', 'cinfo_telephone', 'address', 'cinfo_postalcode', 'cinfo_city', 'cinfo_countrycode', 'cinfo_contactme'];
    if($(".field_interests input:checked[name!=field_personaluse][name!=field_student]").length > 0)
        $.each(fieldIds, function(index, value){$('.field_'+value).show()});
    else
        $.each(fieldIds, function(index, value){$('.field_'+value).hide()});
}


function showOrHideContactInformationV2(){
    // 
    // Show or hide the contact information according to the who_are_you and training_financed_by fields
    //
    // See shouldShowContactInformation() to know when we should show or hide the contactinformation
    //

    var fieldIds = ['cinfo_companyname', 'cinfo_fonction', 'cinfo_telephone', 'address', 'cinfo_postalcode', 'cinfo_city', 'cinfo_countrycode', 'cinfo_contactme'];
    if ( shouldShowContactInformation()){
        $.each(fieldIds, function(index, value){$('.field_'+value).show()});
        updateTelephonField(true);
        updateCompanyField(true);
    }
    else{
        $.each(fieldIds, function(index, value){$('.field_'+value).hide()});
        updateCompanyField(false);
        updateTelephonField(false);
    }
}

function hideOrShowSiteVersionLanguages(container){
    // Toggle the display and add the good css class according to the display
    container.find('.languages').toggle();
    if(container.find('.languages').css('display') == 'none')
        container.find('.current').removeClass('current-opened');
    else
        container.find('.current').addClass('current-opened');
}

function updateSiteVersion(){
    // Added event on the site version
    $('.site-version-languages a.current').unbind().click(
        function (event){
            hideOrShowSiteVersionLanguages($(this).parentsUntil('.site-version-languages').parent());
            event.stopPropagation();
            $(document).click(
                function () {
                   $('.site-version-languages .languages').css('display', 'none');
                   $('.site-version-languages .current').removeClass('current-opened');
                   $(document).unbind('click');
                }
            );
    });
}

function addOnclickEventOnRedirectLink(){
    // Add onlick event on all elements which have for css class redirect_link
    $('.redirect_link').click(
        function(event){
            putCookiesInUrlAndRedirectTo(this.href);
            return false;
        });
}

function putCookiesInUrlAndRedirectTo(url){
    // Put the google and gymgish cookies in the url as query string 
    // and redirect to this generated url
    var params = {};
    if (typeof(COOKIE_NAMES_TO_KEEP_ON_REDIRECT) != 'undefined')
    $(COOKIE_NAMES_TO_KEEP_ON_REDIRECT).each(function() {
        value = $.cookie(this);
        if(value){
            // Remove " at the begin and end of value
            // since zope add some because IE4 ignores cookies with
            // quoted cookie attr values, so only the value part
            // of name=value pairs may be quoted.
            value = value.replace(/^"/, '').replace(/"$/, '');
            params['keep_cookie_' + this] = value;
        }
    });
    pagetracker = getAllDomainsTracker();
    document.location.href=pagetracker._getLinkerUrl(url)+ '&' + $.param(params);
}

function setCookiesAccordingToQueryString(){
    // Get the cookies from the query string and store it
    if (typeof(COOKIE_NAMES_TO_KEEP_ON_REDIRECT) != 'undefined')
    $(COOKIE_NAMES_TO_KEEP_ON_REDIRECT).each(function() {
        var pattern = new RegExp("keep_cookie_" + this + "=([^&]+)");
        var match = pattern.exec(window.location.href);
        if(match){
            $.cookie(this, match[1], { expires: COOKIES_MAX_AGE, path: '/'});
        }
    });
}


function handleVideoShare(playStatus){
  // Display the share modal box
  if ($("#share-form").length == 0){
    $.get('share_video', function(data) {
      $('body').append(data);
      $("#share-form").dialog({modal: true, width: 604});
      $('.ui-widget-overlay').click(function() { $("#share-form").dialog("close"); });
      }
    );
  }
  else{
     $("#share-form").dialog("open");
     $('.ui-widget-overlay').click(function() { $("#share-form").dialog("close"); });
  }
}

function validate_share_form(){
  // Return bool
  // We just check is required values are set.
  
  var isValid = true;

  if(! $('#share-firstname').val()){
    $('#share-firstname').css('border', "2px solid red");
    isValid = false;
  }
  
  if (! $('#share-cerises').val()){
    $('#share-cerises').css('border', "2px solid red");
    isValid = false;
  }
  return isValid
}


function share(){
  // Call when we click on the share button in the form.

  // Initial border (If one or more emails are not valid this border will be red)
  $('#share-firstname').removeAttr('style');
  $('#share-cerises').removeAttr('style');
  
  // Check if all required fields are set
  if ( ! validate_share_form())
    return 

  $('#share_button').attr('disabled',' disabled');

  $.ajax({
    url: 'recommend_share_video',
    data: $('#share-form form').serialize(),
    success: function(data, textStatus, jqXHR){
        var reponseSplit = data.split(',');

        if (reponseSplit[0] == '1'){
            $('#share-cerises').val('');
            $("#share-form").dialog("close");
        }
        else{
            $('#share-cerises').css('border', "2px solid red");
            $('#share-cerises').val(reponseSplit[1]);
        }
        $('#share_button').removeAttr('disabled');
    }
  });
}

function initCallUsToolTip(){

  $(document).ready(function() {

    var triggers = $("#callus-popup-link").overlay({
        // some mask tweaks suitable for modal dialogs
        mask: {
            color: '#ebecff',
            loadSpeed: 100,
            opacity: 0.8
        },
        closeOnClick: true,

        onBeforeLoad: function(){
            $('.callus-content form').show();
            for (var i = 0; i < $('.callus-content form input[type="text"]').length; i++)
            {
                elem = $('.callus-content form input[type="text"]')[i];
                elem.value = '';
                elem.className = '';
            }
            $('.callus-content .confirmation-message').hide();
        }
    });
  });
}

function initCallUsForm() {

$('#callus-popup form ').validator({'effect': 'wall', 'inputEvent': 'blur'}).bind('onSuccess', function(e) {
     if (e.originalEvent.type == 'submit') {
      $.ajax({
        url: $('#callus-popup-link').attr('href') + '/doer_json',
             type: 'POST',
             data: $(this).serialize(),
             dataType: 'json',
             success: function(data){
                  $('.confirmation-message').html(data.message).show();
                  $('#callus-popup form').hide();
             },
            error: function(jqXHR, textStatus, errorThrown){
                alert('Error');
            }
          });
      return false;
     }
  });
}




function initAddmoretesters() {
    $('.addmoretesters').click(function(){
        $(this).before($('#onemoretester').html());
        $("form").addClass("asblock");
     })
}

function homeAnimationDelavigne(){
    /* only add animation callback if we have id #gg-animated-home' on the page */
    idAnimated = $('img#gg-animated-home');
    if(idAnimated.length){
        idAnimated.hide();

        htmlAnimation = '<div class="gg-animation-home">\
                        <div id="sine">&nbsp;</div>\
                        <img class="gg-animation-home-plane" src="/images/gg-animation-home-plane.png" alt="" />\
                        <img class="gg-animation-home-characters" src="/images/gg-animation-home-characters.png" alt="" />\
                        </div>';

        idAnimated.after(htmlAnimation);

        $(document).ready(function() {
          var start_x = 0;
          var start_y = 0;
          var end_x   = 670;
          var end_y   = 0;

          var SineWave = function() {
            this.css = function(p) {
              var s = Math.sin(p*20)
              //      start and end
              var y = 175 + p * 100
              var x = s * -10 + 50
              var o = (100)
              return {top: y + "px", left: x + "px", opacity: o}
            }
          };

          /*** plane animation ***/
          var bezier_params = {
            start: {
              x: 305,
              y: 185,
              angle: -45
            },
            end: {
              x:670,
              y:30,
              angle: 45,
              length: 0.25
            }
          }

          counterPlane = 0;

          function animationPlane(){
              counterPlane ++;
              var cssObj = {
                'width' : '10px',
                'display' : 'inline'
              }
              $("img.gg-animation-home-plane").css(cssObj);
              $("img.gg-animation-home-plane").animate({
                  path : new $.path.bezier(bezier_params),
                  width: '50'
                  }, DURATION_ANIMATION_HOME_PLANE,'linear', function(){
                      if(counterPlane < 7){
                          animationPlane();
                      }
                  });
          }


          animationPlane();
          /*** end plane animation ***/


          var Paths = {"arc":[], "bezier":[], "sine": []}

            var path_fns = {
              arc: function(i) {
                return new $.path.arc({
                  center: [285,185],
                  radius: 100,
                  start: -i*20,
                  end: i*100,
                  dir: (i%2) ? 1 : -1
                })
              },
              bezier: function(i) {
                var x = i%2 ? 1 : -1
                return new $.path.bezier({
                  start: { x:185, y:185, angle: i*20 * x},
                  end: {x:540,y:110, angle: i*10, length: i / 4.0}
                })
              },
              sine : function(i) {
                return new SineWave;
              }
          }

          for(var type in Paths) {

            for(var i=0; i<10; i++ ) {
              if(i != 9 && type == "sine")
                continue

              var path = path_fns[type](i)
              Paths[type].push(path)

              var $$ = $('<span class="gg-animation-home-bubble"></span>');
              $$.css(path.css(1))
              $("#" + type).append($$)
            }
          }


          var i = 0;
          counterBubble = 0;
          function animationBubble(){
              counterBubble++;
              bubble = $("#" + "sine" + " .gg-animation-home-bubble");
              bubble.removeClass('gg-animation-home-bubble-step-02');
              bubble.addClass('gg-animation-home-bubble-step-01');
              bubble.animate({path: Paths[type][i]}, DURATION_ANIMATION_HOME_BUBBLE, 'linear', function(){
                $(this).removeClass('gg-animation-home-bubble-step-01');
                $(this).addClass('gg-animation-home-bubble-step-02');
                if(counterBubble < 20){
                    setTimeout(animationBubble, 1000);
                }
            })
          }
          animationBubble();
        });
    }
}

function setMiniformValidator(){
    var form = $('#miniform.gg-form');
    if (! form.length)
        // No minifrom on this page
        return false;
    form.validator({'effect': 'wall', 'inputEvent': 'blur', 'messageClass': 'gg-form-error-message'});
}

function initDefaultValueFields(){
    $('.gg-default-value').each(function(){
        var $this = $(this);
        var default_value = $this.find('label:first-child').find('span:first').text();
        var input = $this.find('input:last-child');
        input.data('default_value', default_value);
        input.focus(function(){
            if ($(this).val() == default_value){
                $(this).val('');
                $(this).addClass('gg-default-value-filled');
            }
        }).blur(function(){
            if ($(this).val() == ''){
                $(this).val(default_value);
                $(this).removeClass('gg-default-value-filled');
            }
        });
    });
}

