var AJAX_PATH = ROOT_PATH +'ajax';

/**
 * Initialise event behaviours on the page element
 */
$(document).ready(function(){
  if($('.bio_audrey').length >  0){
    $('.bio_audrey').click(function(){ 
      Popup.createPopUp('bio_audrey'); 
      return false; 
    });
  }	
  
  // Tabs
  if($('.widget').length > 0){
    Tabs.Initialize();
  }
  
    // 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);
        }
      }
    );
  }
  
  // Send to a friend
  if($('.send').length > 0){
    $('.send').click(function(){ 
      Popup.createPopUp('send_friend'); 
      return false; 
    });
  } 
  
  // Invite a friend to a chat
  if($('.invite').length > 0){
    $('.invite').click(function(){ 
      Popup.createPopUp('invite_friend'); 
      return false; 
    });
  } 
  
  // Email reminder subscription for the chat
  if($('#chat_reminder').length > 0){
    $('#chat_reminder button').click(function(){ 
      if($('#chat_reminder #email')[0].value)
      {
        Popup.createPopUp('invite_reminder');  
      }
      return false;
    });
  } 
  
  /* must login */
 if($('.must_login').length > 0){
    $('.must_login').click(function(){ 
      Popup.createPopUp('must_login'); 
      return false; 
    });
  } 
  
  // Login
  if($('#login_comments').length > 0){
    $('#login_comments').click(function(){ 
      Popup.createPopUp('login'); 
      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;
      }
    );
  } 
  
  // 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; 
    });
  }
  
  // Search : remove 'rechercher'
  if($('#search_field').length > 0){
    $('#search_field').focus(function(){ 
      if(this.value == 'recherche')
      {
        this.value ='';
      }
    });
    
    $('#search_field').blur(function(){ 
      if(this.value == '')
      {
        this.value = 'recherche';
      }
    });
  } 
});

/** 
 * 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('widget_calendar').style.width = "295px";	
    }
    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);				
  },

/** 
 * Checks if an email address is valid
 */		  
  checkEmail: function(email) 
  {
    var reg = /^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,3}$/
    return (reg.exec(email) != null)
  },

/** 
 * 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(){
    $('.widget .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, .ad_banner',	
  
  Initialize: function(){
    if($('#login').length > 0){
      $('#login').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]);
    
    // show the select
    $('select').toggle();
    
    // show all the additional 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; });
      }
    );		
  },
  
  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; });
        }
      }			
    });			
  },
  
  loginCheck: function(){
    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{
          window.location.href = ROOT_PATH;
        }
      }			
    });		
  },  
   
/**
 * 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; });
      }
    );
  },
  
 /**
 * Bio_audrey : display a popup that display the bio
 */
  bio_audrey: function(el){
    $(el).load(AJAX_PATH +'/bio_audrey',
      function(){
        $('bio_audrey').click(function(){ Popup.destroy(); Popup.createPopUp('bio_audrey'); 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 });	
  },

/**
 * Invite reminder for the chat
 */
  invite_reminder: function(el){
    // We get the article values from the attributes, its not very clean but this avoid an additionnal db request
    var email = $('#chat_reminder #email')[0].value;
    var id = $('.invite')[0].id.split("_")[1];
    
    // Call the ajax method
    $(el).load(AJAX_PATH +'/invite_reminder', { email: email, id: id });		
  },

/**
 * Invite a friend to a chat
 */
  invite_friend: function(el){
    // We get the article values from the attributes, its not very clean but this avoid an additionnal db request
    var id = $('.invite')[0].id.split("_")[1];

    // Call the ajax method
    $(el).load(AJAX_PATH +'/invite_friend', { id: id },
      function(){
        if($('#popup_content button').length > 0){
          $('#popup button').click(function(){ PopupMethods.invite_friend_result(); return false; });
        }    	
      }
    );		
  },
  
  invite_friend_result: function(){  	
    var serialized = $('#popup input, #popup textarea').serialize();
    Popup.loader();
    
    $.ajax({type: "POST", url: AJAX_PATH +'/invite_friend_result', data: serialized +'&url='+ window.location.href, dataType: "html",
      success: function(data){
        $('#popup_content').html(data);
        if($('#popup_content button').length > 0){     		
          $('#popup button').click(function(){ PopupMethods.invite_friend_result(); return false; });
        }
      }  
    });	
  },

/**
 * 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; });
        }
      }  
    });	
  }
}

