var AJAX_PATH = ROOT_PATH +'ajax';

// LinkedIn Api Key
//var API_KEY = 'l5y0t0pptqfr';    //  dev server
//var API_KEY = '8e9e9l8jhyz3';    //  www.dev-mm.com
//var API_KEY = 'e9xkjwrez0fz';    // local mistral
//var API_KEY = 'awgxrcl1lqua';    // Local server 

//var API_KEY = '9afz3thbar8y'    // API for preprod server domain
var API_KEY = 'za5l1i797p08'    // API for prod server domain
   
/**

 * Initialise event behaviours on the page element

 */

$(document).ready(function(){
  var AJAX_PATH = ROOT_PATH +'ajax';

  // Bourse Redirect Links
  $('.ms_redirect').click(function(event){
    event.preventDefault();

    $.ajax({
      type: "GET",
      url: $(this).attr('href'),
      dataType: "html",
      success: function(data){
        $('body').append('<div>'+data+'</div>');
      }
    });

  });

  $('.ms_form_redirect').submit(function(event){
    event.preventDefault();

    $.ajax({
      type: "GET",
      url: $(this).attr('action'),
      data: 'portefeuille_redirect[username]='+$(this).find('#portefeuille_redirect_username').val()+
           '&portefeuille_redirect[password]='+$(this).find('#portefeuille_redirect_password').val(),
      dataType: "html",
      success: function(data){
        $('body').append('<div>'+data+'</div>');
      }
    });

  });

  // Portofeuille JS
  $('.portefeuille_choice_box input[name="link_portefeuille"]').click(function(event){
    var checked = $(this).is(':checked');

    $('.portefeuille_checkbox').attr('checked', false);
    $('.portefeuille_choice_option').hide();

    if (checked){
      $(this).attr('checked', true);
      $('.portefeuille_link').css('display', 'inline-block');
    }
  });

  $('.portefeuille_choice_box input[name="create_portefeuille"]').click(function(event){
    var checked = $(this).is(':checked');

    $('.portefeuille_checkbox').attr('checked', false);
    $('.portefeuille_choice_option').hide();

    if (checked){
      $(this).attr('checked', true);
      $('.portefeuille_create').css('display', 'inline-block');
    }
  });

  $('.portefeuille_choice_box #has_portefeuille_1').click(function(event){
    $('.portefeuille_choice_box').hide();
    $('.portefeuille_link').show();
  });

  $('.portefeuille_choice_box #has_portefeuille_0').click(function(event){
    $('.portefeuille_choice_box').hide();
    $('.portefeuille_create').show();
  });

  $('.portefeuille_add_cancel').click(function(event){
    event.preventDefault();
    $('.portefeuille_add').hide();
    $('.portefeuille_list').show();
  });

  $('.back_button').click(function(event){
    event.preventDefault();
    window.location = $(this).attr('href');
  });

  $('.add_globe_user').click(function(event){
    event.preventDefault();
    $('.portefeuille_list').hide();
    $('.portefeuille_add').show();
  });

  $('.portefeuille_list .edit_part').click(function(event){
    event.preventDefault();
    $('.portefeuille_list').hide();

    var li = $(this).parents('li');
    $('.portefeuille_edit #portefeuille_edit_id').attr('value', li.find('.id_part').html());
    $('.portefeuille_edit #portefeuille_edit_username').attr('value', li.find('.left_part').html());
    $('.portefeuille_edit #portefeuille_edit_password').attr('value', li.find('.password_part').html());

    $('.portefeuille_edit').show();
  });

  // Linkedin export

  if ($('#linkedin_export').length > 0){
    $.getScript("http://platform.linkedin.com/in.js?async=true", function success() {
      IN.init({
        authorize: true,
        api_key: API_KEY,
        onLoad: linkedinExport()
      });
    });
  }

  if ($('.linkedin_status').length > 0){
    $.getScript("http://platform.linkedin.com/in.js?async=true", function success() {
      IN.init({
        authorize: false,
        api_key: API_KEY,
        onLoad: changeProfileButton() 
      });
    });
  }

  // Submenu closing button behaviour

  if($('.close-submenu').length > 0){

    $('.close-submenu').click(function(){ $('#submenu').addClass('submenu_hide'); });

  }

// toggle

  $(".toggle-rel").click(function () {
    id = $(this).attr("rel");
    $("#"+id).slideToggle("slow");
  });


  // Ford Carousel
  
  if ($('#ford_slideshow').length > 0){
    
    function getFordTabId(classes){
      classStr = classes.split('ford_');
      if (classStr.length == 1) return classStr[0];
      else {
        classStr = classStr[1].split(' ');
        return classStr[0];  
      } 
    }

    tabId = getFordTabId($('#ford_slideshow .slideshow_menu li.active').attr('class'));  
    $('.ford_tab_' + tabId).show();
       $('#ford_slideshow .slideshow_menu').animate({
          marginLeft: '-=180.933'
        }, 500);
  
    $('#ford_slideshow .slideshow_menu li').click(function(){
      $('#ford_slideshow .slideshow_menu li').removeClass('active');  
      $(this).addClass('active');  
      tabId = getFordTabId($(this).attr('class'));  
      $('#ford_slideshow').css('background',"url('" + ROOT_PATH + $('.ford_tab_' + tabId + ' .slideshow_background').text() + "') no-repeat");
      $('#ford_slideshow .slideshow_tab').hide();
      $('.ford_tab_' + tabId).show();
    });

    var number_of_photos = $('#ford_slideshow .slideshow_menu li').size();
    var current = getFordTabId($('#ford_slideshow .slideshow_menu li.active').attr('class'));  ;
    
    $('#ford_slideshow .slideshow_left_button').click(function(event){
      event.preventDefault();
      if (current>6){
        $('#ford_slideshow .slideshow_menu').animate({
          marginLeft: '+=90.933'
        }, 500);
        current-=1;
      }
    })

    $('#ford_slideshow .slideshow_right_button').click(function(event){
      event.preventDefault();  
      if (current<number_of_photos){
        $('#ford_slideshow .slideshow_menu').animate({
          marginLeft: '-=90.933'
        }, 500);
        current+=1;
      }
    })
    
  }

  // Carrousel

  if($('#carrousel').length > 0){

    $('#carrousel').jcarousel({

       scroll: 1, 

       buttonNextHTML: '<a></a>', 

       buttonPrevHTML: '<a></a>'

    });  	

  } 

  

  // Tabs

  if($('.statistics').length > 0){

    Tabs.Initialize();

  }



  // Question reponses filter

  if($('.QR_filter').length > 0){

    $('.QR_filter').change(function(){

    	

      if(this.value == 'all'){

        document.location.href = document.location.href +'?filter=all'

      }else{

        document.location.href =  this.value; 		

      }

    });

  }

  

  /*

  // Pub inside article

  if($('#article_detail .content_pub').length > 0){

    var containers = $('#article_detail .content div, #article_detail .content p');

    $(containers[3]).append($('#article_detail .content_pub')[0]);   

  }

  */



  // Login

  if($('.popup').length > 0){

    Popup.Initialize('login');

  }  



  /*

  // Comments : checks if the user is logged in, if not blocks the redirection and display a popup

  if($('.options .comment').length > 0){

    if($('#login').length > 0){

      $('.options .comment').click(function(){ 

        Popup.createPopUp('must_login'); 

        return false; 

      });

    }

  } 

  */



  /* must login */

 if($('.must_login').length > 0){

    $('.must_login').click(function(){ 

      Popup.createPopUp('must_login'); 

      return false; 

    });

  } 
  
  /* check login */

 if($('.check_login').length > 0){

    $('.check_login').click(function(){ 

      if($('#login').length > 0){ 
        Popup.createPopUp('must_login'); 

        return false;
      }

    });

  } 


  // Register

  if($('.register_popup').length > 0){

    $('.register_popup').click(function(){ 

      Popup.createPopUp('register'); 

      return false;

    });

  }  

  
   /* why register */

 if($('.whyregister').length > 0){

    $('.whyregister').click(function(){ 

      Popup.createPopUp('whyregister'); 

      return false; 

    });

  } 

 

  /* cancel event */

 if($('.cancelevent').length > 0){

    $('.cancelevent').click(function(){ 

      Popup.createPopUp('cancelevent'); 

      return false; 

    });

  } 

 

 

  // Send to a friend

  if($('.send').length > 0){

    $('.send').click(function(){ 

      Popup.createPopUp('send_friend'); 

      return false; 

    });

  } 

   

  // Share

  if($('.share').length > 0){

    $('.share').parent().mouseover(function(){$(this).children('.share_links').show();});

    $('.share').mouseout(function(){$('.share_links').hide();});

    $('.share_links').mouseout(function(){$('.share_links').hide();});

  } 

  

  // Print popup

  if($('.print').length > 0){

    $('.print').click(

      function(){

        window.open (this.href, 'Imprimer', config='toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, directories=no, status=no');

        return false;

      }

    );

  } 

  

  

  // Raw print

  if($('.print_page').length > 0){

    $('.print_page').click(

      function(){

        window.print();

        return false;

      }

    );

  } 

  

  // Reset input values

  if($('.resetValue').length > 0){

    ResetValue.initialize();

  }

  

  // dummy

  if($('#dummy').length > 0 && $('#account')[0].value){

    $('#dummy')[0].checked = true;
    var parent = $('#dummy').parentNode;

    $('.toggle_content', parent).show();

  }  
  
  if($('#dummy_premium').length > 0 && $('#premium')[0].value){

    $('#dummy_premium')[0].checked = true;
    var parent = $('#dummy_premium').parentNode;

    $('.toggle_content', parent).show();

  }  

  

  if($('#dummy').length > 0 && !$('#account')[0].value){

    $('#dummy')[0].checked = false;

  } 
  
  if($('#dummy_premium').length > 0 && !$('#premium')[0].value){

    $('#dummy_premium')[0].checked = false;

  } 

  

  // Toggle

  if($('.toggle').length > 0){

    $('.toggle').change(function(){     

      $('.toggle_content', $(this.parentNode)).toggle(); 

    });

  }

  

  // Save articles

  if($('.save').length > 0){

      $('.save').click(function(){ 

        Popup.createPopUp('save_article'); 

        return false; 

      });

  }

  

  // Save articles

  if($('.QR_question').length > 0){

      $('.QR_question').click(function(){ 

        Popup.createPopUp('QR_question'); 

        return false; 

      });

  }
  
   // Save articles

  if($('.QR_export').length > 0){

      $('.QR_export').click(function(){ 

        Popup.createPopUp('QR_export'); 

        return false; 

      });

  }
  
   
   // Convertisseur

  if($('.convertisseur').length > 0){

      $('.convertisseur').click(function(){ 

        Popup.createPopUp('convertisseur'); 

        return false; 

      });

  }
  
     // archives popup

  if($('.archiveshelp').length > 0){

      $('.archiveshelp').click(function(){ Popup.createPopUp('archiveshelp'); return false; });

  }
  

  // CdromSNI popup

  if($('.cederom').length > 0){

      $('.cederom').click(function(){ 

        PopupMethods.clicked = this;

        Popup.createPopUp('cederom'); 

        return false; 

      });

  }

  

  // redirect with a select

  if($('.select_to_link').length > 0){

    $('.select_to_link').change(

      function(){

        if(this.value){

          window.open(this.value);

        }

      }

    );

  }
  
   // redirect with a select internally with self

  if($('.select_to_self_link').length > 0){

    $('.select_to_self_link').change(

      function(){

        if(this.value){

          window.open(this.value,'_self');

        }

      }

    );

  }

});



/** 

 * Abstract class including a bunch of usefull methods

 */

var Utils = {

  isResized: 0,

  

  initialize: function(){		

  },

  

  getSiteHeight: function (){	

    var container = $('body')[0];

    

    // Check the size if we are on windows or not

    var height = container.offsetHeight;

    var docHeight = (document.all && !window.opera) ? window.innerHeigh : document.documentElement.clientHeight;



    return (docHeight > height) ? docHeight +"px" : height +"px";

  },



  getSiteWidth: function (){

    return (document.all && !window.opera) ? document.documentElement.clientWidth +"px" : "100%";

  },



  FlashResize: function(height){

    try{

      Utils.isResized = Utils.isResized + 1;

      var additionnal = (Utils.isResized <= 1) ? 600 : 0;

      

      document.getElementById('widget_calendar').style.height = Math.floor(height) + additionnal +"px";

      document.getElementById('flash_calendar').style.height = Math.floor(height) + additionnal +"px";

      

    }

    catch(e){}

  },
    
    FlashRSSResize: function(height){

    try{

      Utils.isResized = Utils.isResized + 1;

      var additionnal = 0;

      

      document.getElementById('widget_rss_regions').style.height = Math.floor(height) + additionnal +"px";

      document.getElementById('rss_regions').style.height = Math.floor(height) + "px";

      

    }

    catch(e){}

  },


/** 

 * Adds a js file to the dom

 */		

  addJsFile: function(name){

    var oScript = document.createElement('script');

    oScript.setAttribute('src', ROOT_PATH +'/js/front/'+ name);

    oScript.setAttribute('type','text/javascript');

    $('body')[0].appendChild(oScript);				

  },



/** 

 * Removes html tags from a string

 */	

  stripTags: function (el){

    return el.replace(/<\/?[^>]+>/gi, '');

  },

  

  getElementsByClassName: function(element, MyClass){

    var childs = element.getElementsByTagName('*');

    var hasClass = [];

    var a = 0;

    

    for(var i = 0; i < childs.length; i++){

      if($(childs[i]).hasClass(MyClass)){

        hasClass[a] = childs[i];

        a++;

      }

    }

    

    return hasClass;

  }

}



// TABS

var Tabs = {

  Initialize: function(){

    $('.statistics .tabs li').click(function(){ Tabs.SwitchTab(this); });

  },

  

  SwitchTab: function(element){

    // remove the selected tag from other elements

    var li = element.parentNode.getElementsByTagName('li');

    var ol = Utils.getElementsByClassName(element.parentNode.parentNode, 'panel');

    $(li).removeClass('selected');

    $(ol).removeClass('selected');

    

    // Add the selected class on the selected element

    $(element).addClass('selected');

    

    // Make the corresponding container visible

    $(ol).each(

      function(){

        if($(element).hasClass(this.id)){

          $(this).addClass('selected');

        }

      }

    );

  }

}





// POPUP



var Popup = {

  // ELements to hide when the lightbox is clicked

  toggles: 'object, #banner, .subscription_home, subscription',

  

  Initialize: function(){

    if($('#login').length > 0){

      $('#login').click(function(){ 

        Popup.createPopUp('login'); 

        return false; 

      });

    } 

 if($('.login').length > 0){

      $('.login').click(function(){ 

        Popup.createPopUp('login'); 

        return false; 

      });

    } 
    

    if($('#login_comments').length > 0){

      $('#login_comments').click(function(){ 

        Popup.createPopUp('login'); 

        return false; 

      });

    } 

  },

  

/** 

 * Creates the popup background layer

 */	

  createLayer: function(){		

    // Create the container

    var div = document.createElement('DIV');

    div.id = 'popup_layer';

    $('body')[0].appendChild(div);

    

    // set the container styles

    div.style.display = "block";

    div.style.width = Utils.getSiteWidth();

    div.style.height = Utils.getSiteHeight();

    div.style.opacity = 0;

    

    // Fixes the ie fadeto opacity bug

    if(document.all){

      div.style.filter = 'alpha(opacity=1)';

    }

    

    // Go to the top of the page

    scrollTo(0, 0);

    

    // Hide all the select to avoid the overlaying bug

    $('select').toggle();	

    

    // Display the layer with a fading effect

   $(div).fadeTo("slow", 0.5);

  },



/** 

 * Creates the popup container

 *

 * @author  Guillaume Pousseo

 */		

  createPopUp: function(method){

    // hide all the additional elements

    if(this.toggles) $(this.toggles).hide();

    

    // If the layer is not yet present, create it

    if($('#popup_layer').length == 0){

      this.createLayer();	

    }	



    // Create the popup container

    var container = document.createElement('DIV');

    container.id = 'popup_container';

    $('body')[0].appendChild(container);

        

    // Create the popup

    var div = document.createElement('DIV');

    div.id = 'popup';

    div.className = method;

    container.appendChild(div);

    

    // Add the extra stuffs, like the close button

    this.addCloseButton(div);

    var container = this.addContainer(div);

    

    // Call the accurate method to fill the popup content

    PopupMethods[method](container);		

  },



/** 

 * Creates the popup close button

 */		

  addCloseButton: function(el){

    var close = document.createElement('A');

    close.src = '';

    close.alt = 'fermer';

    $(close).addClass('close');

    $(close).click(function(){

      Popup.destroy();
      

    });

    el.appendChild(close);			

  },	



/** 

 * Creates the container where to display the content gotten through ajax

 */		

  addContainer: function(el){

    // Create the popup

    var div = document.createElement('DIV');

    div.id = 'popup_content';

    

    var content = 	 '<div class="spinner">'

            +'<p>chargement...</p>'

            +'</div>';

    

    $(div).html(content);

    el.appendChild(div);

    

    return div;	

  },

  

/** 

 * Display the error message

 */	

  errorDisplay: function(msg){

    // if ther eis no error container yet, build it

    if($('#popup_content .error').length == 0){

      var div = document.createElement('DIV');

      $(div).addClass('error');

      $('#popup_content form')[0].insertBefore(div, $('#popup_content form')[0].firstChild);

    }

    

    // Display the message

    $('#popup_content .error').html(msg);		

  },



/** 

 * Display an animation while the popup content is loading

 */	  

  loader: function(){

    $('#popup_content')[0].innerHTML = '<div class="spinner">'

                                      +'<img src="'+ ROOT_PATH +'/web/images/spinner.gif" />'

                                      +'<p>chargement...</p>'

                                      +'</div>';

  },



/** 

 * Shut down every action taken during the op up creation process

 */	

  destroy: function(){

    $('#popup_layer').fadeTo("slow", 1);
    // remove the layer
    $('body')[0].removeChild($('#popup_layer')[0]);

    // remove the popup container and its content
    $('body')[0].removeChild($('#popup_container')[0]);
    //$('body')[0].removeChild($('#popup_container')[0]);

    // show the select
    $('select').toggle();



    // show additionnal elements

    if(this.toggles) $(this.toggles).show();

  }

}



// Records the different methods for the popups





var PopupMethods = {

  // Element that has been clicked

  clicked: '',

  

/** 

 * LOGIN

 */		

  login: function(el){

    $(el).load(AJAX_PATH +'/login', {},

      function(){

        $('#forgotten_password').click(function(){ PopupMethods.ForgottenPassword(el); return false; });

        $('#popup_container form').submit(function(){ PopupMethods.loginCheck(); return false; });

        $('#popup_container .linkedin_custom_button').click(function(){ PopupMethods.simpleLogin(el); return false; });
        
        if ($('.IN-widget').length > 0){
          $('.IN-widget:first').clone(true).insertAfter('.right_part').show()
                               .find('a span span:last').html("S'identifier avec LinkedIn");
        } else {
          $.getScript("http://platform.linkedin.com/in.js?async=true", function success() {
            IN.init({
              authorize: false,
              api_key: API_KEY,
              onLoad: changeDefaultButton() 
            });
          });
        }

      }

    );		

  },

  

  simpleLogin: function(el){

    $(el).load(AJAX_PATH +'/simpleLogin', {},

      function(){
        $('#popup').css('width', '300px'); 

        $('#forgotten_password').click(function(){ PopupMethods.ForgottenPassword(el); return false; });

        $('#popup_container form').submit(function(){ PopupMethods.loginCheck('profil/info'); return false; });
        
      }

    );		

  },

  

  ForgottenPassword: function(el){

    Popup.loader();

    

    $(el).load(AJAX_PATH +'/forgotten_password',

      function(){

        $('#popup button').click(function(){ PopupMethods.ForgottenPasswordResult(); return false; });

      }

    );		

  },

  

  ForgottenPasswordResult: function(){

    var serialized = $('#popup_container form input').serialize();

    

    $.ajax({type: "POST", url: AJAX_PATH +'/forgotten_password_result', data: serialized, dataType: "html",

      success: function(data){

        $('#popup_content').html(data);

        if($('#popup_content button').length > 0){     		

          $('#popup button').click(function(){ PopupMethods.ForgottenPasswordResult(); return false; });

        }

      }			

    });			

  },

  
  // redirect is optional
  loginCheck: function(redirect){

    var serialized = $('#popup_container form input').serialize();	

    

    $.ajax({type: "POST", url: AJAX_PATH +'/checkLogin', data: serialized, dataType: "json",

      success: function(data){

        if(data.error){

          Popup.errorDisplay(data.error);

        }else{

          if (redirect){
            window.location.href = redirect;
          } else {
            window.location.reload();
          }

        }

      }			

    });		

  },


/**

 * Save article

 */

  save_article: function(el){

    var save = $('.save')[0];



    // Call the ajax method

    $(el).load(AJAX_PATH +'/save_article', { article: save.id.split('_')[2] },

      function(){

        $('#access_login').click(function(){ Popup.destroy(); Popup.createPopUp('login'); return false; });

      }

    );	

  },

  

  

/**

 * Must login : display a popup that indicates the user he musts login to access a feature

 */

  must_login: function(el){

    $(el).load(AJAX_PATH +'/must_login',

      function(){

        $('#access_login').click(function(){ Popup.destroy(); Popup.createPopUp('login'); return false; });

      }

    );

  },


  
/** 

 * Register

 */		

  register: function(el){

    $(el).load(AJAX_PATH +'/register', {},

      function(){

        $('.whyregister').click(function(){ PopupMethods.whyregister(el); return false; });
        
        if ($('.IN-widget').length > 0){
          $('.IN-widget:first').clone(true).insertAfter('.pre_register').show();
          changeDefaultButton();
        } else {
          $.getScript("http://platform.linkedin.com/in.js?async=true", function success() {
            IN.init({
              authorize: false,
              api_key: API_KEY,
              onLoad: changeDefaultButton() 
            });
          });
        }

      }

    );		

  },

  

/** 

 * Register with linkedin profile

 */		

  registerWithLinkedin: function(data){
    
    $('#popup_content').load(AJAX_PATH +'/registerWithLinkedin', {},

      function(){

        var values = data.values[0];
        
        $('.welcome_message').text('Bienvenue ' + values.firstName + ',');
        $('#display_newsletter').live('click', function(){
          $('.newsletter_checkboxes').toggle();
        });
        $('#close_popup').click(function(event){
          event.preventDefault();
          Popup.destroy();   
        });
        
        // On submit send ajax request to register the user.
        
        $('#linkedin_form #register_with_linkedin').live('click', function(event){

          event.preventDefault();
          var countryCode = values.location.country.code.toUpperCase();
          
          var ajaxData = { 
            linkedin_id:         values.id,
            username:            $('#linkedin_form #username').val(),
            password:            $('#linkedin_form #password').val(),
            password_confirm:    $('#linkedin_form #password_confirm').val(),
            email:               $('#linkedin_form #email').val(),
            firstname:           values.firstName,
            lastname:            values.lastName,
            country:             countryCode,
            zip:                 $('#linkedin_form #zip').val(),
            secret:              'Votre num&eacute;ro de t&eacute;l&eacute;phone',
            account:             '',
            premium:             ''
          };
            
          // Newsletter
          if ($('#linkedin_form #display_newsletter').is(':checked')){
            ajaxData['newsletter'] = 'on';
          }
          
          $('#linkedin_form input:checked').each(function(){
            ajaxData[$(this).attr('name')] = 'on';
          })
          
          $.ajax({
             type:    'POST',
             url:     $('#linkedin_form').attr('action'),
             data: ajaxData,
             success: function(response) {
               if (response.success){
                 PopupMethods.registerConfirmation();
               } else {
                 form = response.content;
                 $('#popup_content').html(form);
               }
             },
             dataType: 'json'
          });
          
        })
        
      }

    );		

  },


  

/** 

 * Link with linkedin profile

 */		

  linkWithLinkedin: function(data){

    if (data.values != undefined) {
        
      $('#popup_content').load(AJAX_PATH +'/linkWithLinkedin', {},

        function(){

          var values = data.values[0];
        
          $('#link_profiles_form #link_profile_with_linkedin').live('click', function(event){

            event.preventDefault();
            var countryCode = values.location.country.code.toUpperCase();
          
            $('#register form #firstname').val(values.firstName);
            $('#register form #lastname').val(values.lastName);
            $('#register form #email').val($('#link_profiles_form input[name="email"]').val());
            $('#register form #zip').val($('#link_profiles_form input[name="zip"]').val());
            $('#register form #country option').attr('selected', false);          
            $('#register form #country option[value="' + countryCode + '"]').attr('selected', 'selected');
            $('#register form #linkedin_id').val(values.id);

            $('.subscription').show();
            Popup.destroy();
           
          })
         
        }

      );		
    
    }

  },


  

/** 

 * Registration confirmation

 */		

  registerConfirmation: function(){
    
    $('#popup_content').load(AJAX_PATH +'/registerConfirmation', {},

      function(){

        $('#popup').css('width', '400px'); 

      }

    );		

  },


  

/**

 * why register : display a popup that indicates the user he musts login to access a feature

 */

  whyregister: function(el){

    $(el).load(AJAX_PATH +'/whyregister',

      function(){

        $('#whyregister').click(function(){ Popup.destroy(); Popup.createPopUp('whyregister'); return false; });

      }

    );

  },






/**

 * cancel event : display a popup that indicates the user he musts login to access a feature

 */

  cancelevent: function(el){

    $(el).load(AJAX_PATH +'/cancelevent',

      function(){

        $('#access_login').click(function(){ Popup.destroy(); Popup.createPopUp('login'); return false; });

      }

    );

  },

  

  

/**

 * Ask a question

 */

  QR_question: function(el){

    // Call the ajax method

    $(el).load(AJAX_PATH +'/QR_question', {},

      function(){

        if($('#access_login').length > 0){

          $('#access_login').click(function(){ Popup.destroy(); Popup.createPopUp('login'); return false; });

        }

        

        if($('#popup_content button').length > 0){     		

          $('#popup button').click(function(){ PopupMethods.QR_result(); return false; });

        }    	

      }

    );	

  },

  

  QR_result: function(){

    var serialized = $('#popup input, #popup select, #popup textarea').serialize();

    Popup.loader();

    

    $.ajax({type: "POST", url: AJAX_PATH +'/QR_result', data: serialized, dataType: "html",

      success: function(data){

        $('#popup_content').html(data);

        if($('#popup_content button').length > 0){     		

          $('#popup button').click(function(){ PopupMethods.QR_result(); return false; });

        }

      }  

    });		

  },

  /**

 * Ask a question

 */

  QR_export: function(el){

    // Call the ajax method

    $(el).load(AJAX_PATH +'/QR_export', {},

      function(){

        if($('#access_login').length > 0){

          $('#access_login').click(function(){ Popup.destroy(); Popup.createPopUp('login'); return false; });

        }

        

        if($('#popup_content button').length > 0){     		

          $('#popup button').click(function(){ PopupMethods.QR_exportresult(); return false; });

        }    	

      }

    );	

  },

  

  QR_exportresult: function(){

    var serialized = $('#popup input, #popup select, #popup textarea').serialize();

    Popup.loader();

    

    $.ajax({type: "POST", url: AJAX_PATH +'/QR_exportresult', data: serialized, dataType: "html",

      success: function(data){

        $('#popup_content').html(data);

        if($('#popup_content button').length > 0){     		

          $('#popup button').click(function(){ PopupMethods.QR_exportresult(); return false; });

        }

      }  

    });		

  },
  /**

 * Converter

 */

  convertisseur: function(el){

    // Call the ajax method

    $(el).load(AJAX_PATH +'/currencyconverter', {},

      function(){

        if($('#popup_content button').length > 0){     		

          $('#popup button').click(function(){ PopupMethods.QR_exportresult(); return false; });

        }    	

      }

    );	

  },
  
    /**

 * Archives

 */

  	archiveshelp: function(el){

    // Call the ajax method
   $(el).load(AJAX_PATH +'/archiveshelp', {},

     function(){
        $('#popup_container form').submit(function(){ PopupMethods.loginCheck(); return false; });
      }

    );	
  },

/**

 * CdRomSNI

 */

  cederom: function(el){

    // Get the element url

    var CdRomUrl = this.clicked.href;

    

    // Call the ajax method

    $(el).load(AJAX_PATH +'/cederom', { url: CdRomUrl });	

  },

  

/**

 * Send to a friend

 */

  send_friend: function(el){

    // We get the article values from the attributes, its not very clean but this avoid an additionnal db request

    var title = $('.send')[0].title;

    var href = $('.send')[0].href;

    var id = $('.send')[0].id.split("_")[2];



    // Call the ajax method

    $(el).load(AJAX_PATH +'/send_friend', { title: title, url: href, id: id },

      function(){

        if($('#popup_content button').length > 0){

          $('#popup button').click(function(){ PopupMethods.send_friend_result(); return false; });

        }    	

      }

    );	

  },

  

  send_friend_result: function(){  	

    var serialized = $('#popup input, #popup textarea').serialize();

    Popup.loader();

    

    $.ajax({type: "POST", url: AJAX_PATH +'/send_friend_result', data: serialized, dataType: "html",

      success: function(data){

        $('#popup_content').html(data);

        if($('#popup_content button').length > 0){     		

          $('#popup button').click(function(){ PopupMethods.send_friend_result(); return false; });

        }

      }  

    });	

  }

}



/** 

 * Used to reset some input values

 *

 * @author  Guillaume Pousseo

 */

var ResetValue = {

  // Saves the input former values

  formerValues: [],	

  

  initialize: function(){

    // Store each former value in an array

    if($('.resetValue').length > 0){

      for(var i = 0; i < $('.resetValue').length; i++)

      {

        var element = $('.resetValue')[i];

        

        // save the element value only if its not an email address

        ResetValue.formerValues[i] = (!element.value.match('@')) ? element.value : '';

        

        $(element).focus(function(){ ResetValue.focusInput(this); })

        $(element).blur(function(){ ResetValue.blurInput(this); })

      }

    }

  },

  

  focusInput: function(element){	

    // Get the elements index

    var index = this.getIndex(element);	

    

    if(element.value == this.formerValues[index]){

      element.value = '';	

    }

  },

  

  blurInput: function(element){	

    // Get the elements index

    var index = this.getIndex(element);	

    

    if(element.value == ''){

      element.value = this.formerValues[index];	

    }

  },

  

  getIndex: function(element){	

    for(var i = 0; i < $('.resetValue').length; i++)

    {

      if($('.resetValue')[i] == element){

        return i;	

      }

    }

  }

}

// Linkedin Functions

function registerWithLinkedinProfile(){
  IN.API.Profile("me")
    .fields(["id", "first-name", "last-name", "location:(country:(code))"])
    .result(function(result) {
      PopupMethods.registerWithLinkedin(result);
    })
}

function linkWithLinkedinProfile(){
  IN.API.Profile("me")
    .fields(["id", "first-name", "last-name", "location:(country:(code))"])
    .result(function(result) {
      Popup.createPopUp('linkWithLinkedin'); 
      $('#banner').css('display', 'block');
      $('.subscription').hide();
      PopupMethods.linkWithLinkedin(result);
    })
}

function linkedinExport(){

  IN.Event.on(IN, 'auth', function(){
    $('.linkedin_login').hide();
    
    var items = $('.linkedin_discussions').attr('id');
    getLastDiscussions(items);
    
    $('.linkedin_data').show();
  })
  
  $('#linkedin_export_login_button').hide();
  changeDefaultButton()

}

function getLastDiscussions(items){
  IN.API.Raw("/groups/3712410/posts:(id,title,creator,site-group-post-url)?count=" + items + "&start=0&order=recency")
    .result(function(result) {
      var values = result.values;
      var content = '';
      var pictureUrl = $('.lesaffaires_group_logo').attr('src');

      for(var key in values) {
        if (!values[key].creator){
          values[key].creator = {
            'pictureUrl': pictureUrl,
            'firstName':  'LesAffaires Groupe',
            'lastName':   ''
          };
        }

        content = content + 
        '<div class="linkedin_post">' + 
          '<div class="post_image">' +
            '<img src="' + values[key].creator.pictureUrl + '" />' + 
          '</div>' +
          '<div class="post_content">' + 
            '<p class="post_author">' + 
              '<span>' + values[key].creator.firstName + ' ' + values[key].creator.lastName + '</span> a lanc&eacute; une discussion :' + 
            '</p>' +
            '<p class="post_title">' +
              '<a href="' + values[key].siteGroupPostUrl + '">' + values[key].title + '</a>' + 
            '</p>' +
          '</div>' +
        '</div>';
      }

      $('.linkedin_discussions .linkedin_content').html(content);
    })
}

function changeProfileButton(){
  IN.Event.on(IN, 'systemReady', function(){
    $('.IN-widget a span span').html('Lier votre profil &agrave; LinkedIn');
  })
}

function changeDefaultButton(){
  IN.Event.on(IN, 'systemReady', function(){
    $('.IN-widget a span span:last').html("S'identifier avec LinkedIn");
    $('.IN-widget').clone(true).hide().appendTo('body');
  })
}

function loginWithLinkedin(){
  IN.API.Profile("me")
    .fields(["id"])
    .result(function(result) {
      $.ajax({
        type:    'POST',
        url:     AJAX_PATH +'/loginWithLinkedin',
        data:    {
          id:  result.values[0].id
        },
        success: function(response) {
          if (response.success){
            window.location.reload();
          } else {
            Popup.errorDisplay(response.error);
          }
        },
        dataType: 'json'
      });
    })
}

