function initThumbnailsAnimations() {
  jQuery("div.thumbnail_container").live('mouseenter mouseleave', function(event) {
    if (event.type == 'mouseover') {
      jQuery("img.corner_over", this).animate({width: 32, height: 31});
      var icons_container= jQuery(this).children("div.icons_container_over");
      if (icons_container.html() != '')
        icons_container.slideDown("fast");
    } else { 
      jQuery("img.corner_over", this).animate({width: 0, height: 0});
      jQuery(this).children("div.icons_container_over").slideUp("fast");
    }
  });
}

function initAjaxPaging() {
  jQuery("a.paging").live('click', function(e) {
    e.preventDefault();
    
    var parentDiv= jQuery(this).parents(".module");
    var href= jQuery(this).attr('href');
    
    jQuery.get(jQuery(this).attr('href'), {module : jQuery(parentDiv).attr('id')}, function(data) {
      //jQuery(parentDiv).find("ul.publications_listing").fadeOut("fast", function() {
      //window.location.hash= getUrlParam(href, 'page');
      jQuery(parentDiv).replaceWith(data);
      if (imgOndemand) imgOndemand(true);  
     // });
    });
  });
}

function openModal(href, callback) {
  var width= getUrlParam(href, 'w');
  if (!width) width= 400;
  
  var height= getUrlParam(href, 'h');
  if (!height) height= 300;

  $.modal('<iframe src="' + href + '" height="' + height + '" width="' + width + '" id="iframe_modal" frameborder="0">', {
    closeHTML:"",
		overlayClose:true,
		onClose: function() {
      if ($.isFunction(callback)) {
				callback.apply();
			}
      $.modal.close();
    }
  });
}

function initModals() {
  jQuery('a.modal, a[class^="modal"]').live('click', function(e) {
    e.preventDefault();
    
    var objClicked= this;
    var href= jQuery(this).attr('href');
    var callback= null;
    
    if ($(this).hasClass('modal_bookmark')) {
      callback= function() { 
        $.get("/ajax.php", 
              { action: 'getUserBookmarkInfo', pub: getUrlParam(href, 'pub'), page: getUrlParam(href, 'page')}, 
              function(data) { 
                var result= $('result', data).text();
                if (result == 'deleted') {
                  $(objClicked).parents('li:eq(0)').slideUp('slow', function() {$(this).remove()});
                } else if (result == 'pass') {
                  $('p.read_bookmark', jQuery(objClicked).parent()).html($('comment', data).text());
                } else {
                  alert(result);
                }
              }); 
            }    
    } else if ($(this).hasClass('modal_subscription')) {
      callback= function() { 
        $.get("/ajax.php", 
              { action: 'getUserSubscriptionInfo', publisher: getUrlParam(href, 'publisher')}, 
              function(data) { 
                var result= $('result', data).text();
                if (result == 'deleted') {
                  $(objClicked).parents('.subscription_container').slideUp('slow', function() {$(this).remove()});
                } else if (result == 'pass') {
                  // nothing to do for now...
                } else {
                  alert(result);
                }
              }); 
            }    
    } 
    
    openModal(href, callback);
  });
}

function initFiltersVisibility() {
  jQuery(".filter_listing li.group ul").hide();
  jQuery(".filter_listing li.group li.current").parent('ul').show();

  jQuery(".filter_listing li.group").click(function(e) {
    if (jQuery(e.target).children('ul').length > 0) {
      e.preventDefault();
      
      jQuery(".filter_listing li.group ul:visible").hide("fast");
      if (!jQuery(this).children('ul').is(":visible")) {
        jQuery(this).children('ul').slideToggle("fast");
      }
    }    
  });
}

function initFiltersPaging() {
  jQuery(".filter_listing").each(function(element) {
    var module= jQuery(this).parents('.module'),
        max_elements= parseInt(jQuery('.filter_nb_elements', module).html());
    
    if (jQuery(this).children('.group').length < 1 && jQuery(this).children().length > max_elements) {
      var current_index= jQuery(this).children().index(jQuery('li.current', this)),
          page= current_index != -1 ? Math.ceil((current_index + 1) / max_elements) : 1;
      
      jQuery(this).parent().find('.filter_navigation').show();
      changerFilterPage(module, page, max_elements);
    }

  });
  
  jQuery('.filter_previous_page, .filter_next_page, .filter_first_page, .filter_last_page').click(function() {
    var module= jQuery(this).parents('.module'),
        //container= jQuery('.filter_navigation', module),
        current_page= parseInt(jQuery('.filter_current_page', module).html()),
        nb_elements= jQuery('.filter_nb_elements', module).html();
    
    if (jQuery(this).hasClass('filter_previous_page')) {
      current_page= Math.max(current_page - 1, 1);
    } else if (jQuery(this).hasClass('filter_next_page')) {
      current_page= Math.min(current_page + 1, Math.ceil(jQuery('.filter_listing', module).children().length / nb_elements));
    } else if (jQuery(this).hasClass('filter_last_page')) {
      current_page= Math.ceil(jQuery('.filter_listing', module).children().length / nb_elements);
    } else {
      current_page= 1;
    }
    
    changerFilterPage(module, current_page, nb_elements);
  });  
}

function changerFilterPage(module, page, nb_elements) {
  jQuery('.filter_current_page', module).html(page);
  jQuery('.filter_listing', module).children().hide();
  jQuery('.filter_listing', module).children().slice((page - 1) * nb_elements, page * nb_elements).show();
}

function initFiltersSelect() {
  jQuery("select.filter").change(function() { 
    var href= jQuery("option:selected", this).attr('href');
    if (href) document.location.href= href;
  });
}

function initQuickSearch() {
  var orig_quick_search_text= jQuery(".input_quick_search").val();
  
  jQuery(".input_quick_search").bind({
    focusin: function() {
      if (jQuery(this).val() == orig_quick_search_text)
        jQuery(this).val('');
    },
    focusout: function() {
      if (jQuery(this).val() == '')
        jQuery(this).val(orig_quick_search_text);
    }
  });
}

function initSocials() {
  jQuery('.close-iframe-modal').click(function(e) {
    e.preventDefault();
    closeModal();  
  });

  jQuery(".share").click(function(e) {
    e.preventDefault();
    u= jQuery('#pub_url').val();
    t= jQuery('#pub_title').val();
    
    switch (jQuery(this).attr('id')) {
      case 'delicious' :  delicious(u, t); break;
      case 'stumbleupon' : stumbleupon(u, t); break;
      case 'digg' : digg(u, t); break;
      case 'facebook' : facebook(u, t); break;
      case 'myspace' : myspace(u, t); break;
      case 'twitter' : twitter(u, t); break;
    }
  });
}

function initCalendar() {
  if (!$.datepicker) return false;
  $.datepicker.setDefaults( $.datepicker.regional[ $("#datepicker_language").val() ] );
  $("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    defaultDate: $("#datepicker_default_date").val(),
    maxDate: 0,
   /* showOtherMonths: false,
		selectOtherMonths: false,*/
		onSelect: function(dateText, inst) { 
      document.location.href= $("#datepicker_base_url").val().replace("{temp_date}", dateText);
    }
  });
}

jQuery(document).ready(function() {
  initModals();
  initAjaxPaging();
  initThumbnailsAnimations();
  initFiltersVisibility();
  initFiltersPaging();
  initFiltersSelect();
  initQuickSearch();
  initSocials();
  initCalendar();
});


function getUrlParam(url, name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec(url);
  return results == null ? "" : results[1];
}
/*
parseUrl.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*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

function parseUrl(str) {
  var	o   = parseUrl.options,
  		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
  		uri = {},
  		i   = o.key.length;

  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;
}

function rebuildUrl(urlInfos) {
  var url= '';
 // for (i in urlInfos['queryKey']) alert(i + '=' + urlInfos['queryKey'][i]);
  alert(urlInfos['queryKey'].length);
  
  if (urlInfos['protocol']) url+= urlInfos['protocol'] + '://';
  if (urlInfos['user'] && urlInfos['password']) url+= urlInfos['user'] + ':' + urlInfos['password'] + '@';
  if (urlInfos['host']) url+= urlInfos['host'];
  if (urlInfos['port']) url+= ':' + urlInfos['port'];
  if (urlInfos['directory']) url+= urlInfos['directory'];
  if (urlInfos['file']) url+= urlInfos['file'];
  if (urlInfos['queryKey'].length) {
    
    var queryString= '';
    for (i in urlInfos['queryKey']) queryString += (queryString == '' ? '?' : '&') + i + '=' + urlInfos['queryKey'][i]; 
    url+= queryString;
  }
  if (urlInfos['anchor']) url+= '#' + urlInfos['anchor'];

  return url;
}
*/



// section pour le modal

function closeModal() {
  self.parent.$.modal.close();
}

function resizeIframe(newwidth, newheight) {
  $('#iframe_modal, #simplemodal-container', self.parent.document).width(newwidth).height(newheight);
  self.parent.$.modal.setPosition();
}

//SHARING

function delicious(u, t) {
	window.open('http://del.icio.us/post?v=4&noui&jump=close&url='+encodeURIComponent(u)+'&title='+encodeURIComponent(t), 'delicious','toolbar=no,width=700,height=400');
}

function stumbleupon(u, t) {
	window.open('http://www.stumbleupon.com/submit?url='+encodeURIComponent(u)+'&title='+encodeURIComponent(t));
}

function digg(u, t) {
	window.open('http://digg.com/submit?url='+encodeURIComponent(u)+'&title='+encodeURIComponent(t));
}

function facebook(u, t) {
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436')
}

function myspace(u, t){
	window.open('http://www.myspace.com/index.cfm?fuseaction=postto&' + 't=' + encodeURIComponent(t) + '&u=' + encodeURIComponent(u));
}

function twitter(u, t) {
	window.open("http://twitthis.com/twit?url="+encodeURIComponent(u)+"&title="+encodeURIComponent(t.replace(/^\s*|\s*$/g,'')), "TwitThisPop", "width=600, height=500, location, status, scrollbars, resizable");
}

