/*
* Ykone.com - JS
* @version 3.0
* @creation date 2009-07-03
* @update date 2009-07-21
* @author CUT HERE www.cut-here.net
* Description :
*/
$(document).ready
(
	function()
	{



/* TOP
--------------------------------------------------------------------------------------- */
// Rollover navs A REFAIRE
$('#nav > li').find('h2 > a')
.bind('mouseenter', function()
{
$(this).parents('li').find('> .subnav').css("display","block");
$(this).parents(".nav-first").find("h2").addClass("active");
textDefault = $(this).parents('li').find(".subnav-content").html();
$(this).parents('.nav-first').mouseout ( function()
{
$(this).find(".subnav-content").replaceWith("<div class=\"subnav-content\">" + textDefault + "</div>");
});
}).end()
.bind('mouseleave', function()
{
$(this).find("h2").removeClass("active");
$('.subnav', this).css("display","none");
});
// Rollover Subnavs
$('#nav > li li').find("#title3")
.bind('mouseenter', function()
{
$(this).parents('li').find(".subnav-content").replaceWith("<div class=\"subnav-content\">" + $(this).parents("li").find(".desc").html() + "</div>");

}).end();



/* A HREF
--------------------------------------------------------------------------------------- */
$("a[rel='external']").click( function(){
window.open( $(this).attr("href") );
return false;
});

$("span.display-all a[rel='ajax']").click( function(){
	if (navigator.appName == "Microsoft Internet Explorer" && parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf("MSIE",0)+5,navigator.appVersion.indexOf(";",navigator.appVersion.indexOf("MSIE",0))) ) <=6 )
	{
		$(this).parent().css("display","none");
		$(this).parent().parent().next().css("display","inline-block");
	}
	else
	{
		$(this).parent().hide("fast");
		$(this).parent().parent().next().fadeIn("fast");
	}
	return false;
});



/* FORMS
--------------------------------------------------------------------------------------- */
inputFocus();

/* Smooth Scroll with local link (anchor)
--------------------------------------------------------------------------------------- */
$("#comments blockquote p.who").find("a:eq(1)")
.click(function()
{
	$.scrollTo("#add-comment", 800 );
	return false;
});




/* TOP > USER SUGGEST
--------------------------------------------------------------------------------------- */
$("#user-suggest a#btn-close-suggest").live("click", function(){
	$("#user-suggest").slideUp("normal", function() { $(this).remove();});
});



/* TOP > LANG SELECTOR
--------------------------------------------------------------------------------------- */
$("#user-badge #lang-selector").hover(
function(){	$(this).addClass("deploy");},
function(){ $(this).removeClass("deploy");}
);
$("#user-badge #lang-selector li:last").hover(
function(){},
function(){ $(this).parent().removeClass("deploy");}
);
/*$("#user-badge #lang-selector").hover(function()
{}, function()
{
	$(this).children("li:not(:first)").slideUp('fast',
		function(){ $("#user-badge #lang-selector").removeClass("deploy");}
												);
});
*/
//FIX au cas où
//$("#user-badge #lang-selector li:last").hover(function()
//{
	//alert("DEBUG : hover")
/*},
function()
{
	$("#user-badge #lang-selector li:not(.current)").slideUp('fast',
		function(){$("#user-badge #lang-selector").removeClass("deploy");}
															 );
}
);
*/


/* PUSH DIRECTORY
--------------------------------------------------------------------------------------- */
$("#push-directory-content li a")
.live("mouseover", function()
{
	$(this).prev("img").fadeIn("fast");

})
.live("mouseout", function()
{
	$(this).prev("img").fadeOut("fast");
});









/* CONTENT > MODULES ASSOCIATES > COMMENTS
--------------------------------------------------------------------------------------- */
// juste pour demo, a dynamiser
//$("#form-comment-add input.btn-submit").click(function(){ $("#comment-user-offline").slideDown("fast"); return false; });



/* CONTENT > MODULES ASSOCIATES > PUSH DIRECTORY
--------------------------------------------------------------------------------------- */
/*if ( $("#push-directory-menu").length != 0 )
{
	$("#push-directory-menu").ykoneTabs({
	});
}

$("#push-directory-menu").ykoneSlider({
	template:"template-tabs",
	step:1
});*/


/*
 * Form authentification
 *----------------------------------------------------------------------*/

 // Display form
$("#connexion").click(function(){
  $('#form-login').fadeToggle('normal');
});

// Send Form
$('#form-login').find('.btn-ok').click(function(){
	var f 	= this.form;
	var url = f.action;

	$('#form-login-error').html('<div class="ajax-loading"></div>');
	$('.ajax-loading').fadeIn();

	$.post(f.action, {'login-mail':f.elements['login-mail'].value, 'login-pwd':f.elements['login-pwd'].value, 'action':'submitted'}, function(data)
	{
		if( !data.error )
			location.reload(true);
		else
			$('#form-login-error').html(data.msg);
	}, 'json');

  return false;
});

// Send Form
$('#form-login-int').find('.btn-sign-in').click(function(){
	var f 	= this.form;
	var url = f.action;

	$('#form-login-error-int').html('<div class="ajax-loading"></div>');
	$('.ajax-loading').fadeIn();

	$.post(f.action, {'login-mail':f.elements['login-mail'].value, 'login-pwd':f.elements['login-pwd'].value, 'action':'submitted'}, function(data)
	{
		if( !data.error )
			location.reload(true);
		else
			$('#form-login-error-int').html(data.msg);
	}, 'json');

  return false;
});


/* CONTENT > MODULES ASSOCIATES > COMMENTS
--------------------------------------------------------------------------------------- */
$("#form-comment-add").find("input.btn-submit").click(function()
  {
    // Authentificated ???
    var node = $("#comment-user-offline");

    if( node.length )
      node.slideDown("fast");
    else
    {
      var comment = $('#comment-txt').val();
      var form = this.form;
      var parent = parseInt(form.parent.value);

      $.post(  form.action,
              {
                'type':form.type.value,
                'id':form.id.value,
                'parent':parent,
                'comment':comment
              },
              function(data)
              {
                if( data.length )
                {
                  // Append comment
									var n = $(data).hide();

                  if( !parent )
                    $('#add-comment').before(n);
                  else
                    $('#comment-'+parent).append(n);

									n.slideDown('slow');

                  // Increment Comments count
                  var count = $("em[class$='stats-comments']");
                  var value = parseInt(count.html())+1;
                  count.fadeOut('normal', function(){$(this).html(value).fadeIn('normal')});
                }
              }
            );

      // Reinit parent
      form.parent.value = 0;
    }

    return false;
  });

 // user not authenticated !
$("#form-comment-login").find("input.btn-sign-in").click(function(){

  var comment = $('#comment-txt').val();
  var form    = this.form;
	var url     = form.action;
  var node_error = $('#fom-comment-error');

	$.post(form.action, {'login-mail':form.elements['login-mail'].value, 'login-pwd':form.elements['login-pwd'].value, 'action':'submitted'}, function(data)
	{
		if( !data.error )
    {
      node_error.html(data.msg).hide().fadeIn('normal');

      var comment = $('#comment-txt').val();
      var form_comment = $("#form-comment-add")[0];
      var parent = parseInt(form_comment.parent.value);

      $.post( form_comment.action,
              {
                'type':form_comment.type.value,
                'id':form_comment.id.value,
                'parent':parent,
                'comment':comment
              },
              function(data)
              {
                if( data.length )
                {
                  // Append comment
									var n = $(data).hide();
                  node_error.fadeOut('normal', function(){$(this).html(data.msg).fadeIn('normal')});

                  if( !parent )
                    $('#add-comment').before(n);
                  else
                    $('#comment-'+parent).append(n);

									n.slideDown('slow', function()
                  {
                    var url = window.location.href.split('#');
                    window.location.href = url[0]+'#comments';
                    location.reload(true);
                  });
                }
              }
            );

      // Reinit parent
      form_comment.parent.value = 0;
    }
		else
    {
      var value = node_error.html();
      node_error.html(data.msg).hide().fadeIn('normal');
      setTimeout(function(){node_error.fadeOut('normal', function(){$(this).html(value).fadeIn('normal')})}, '1500');
    }
	}, 'json');

  return false;
});

// Reply Comments
// TODO !!! Attention avec live, conflit avec l'evenement click du scrollTo #add-comment !!
$("a[href='#add-comment']").bind('click', function(){
  var id = parseInt($(this).attr('rel'));
  if( id )
    $("#form-comment-add > input[name='parent']").val(id);
});





/* I am a fan too !
-----------------------------------------*/
$("a[rel='fans-add-me']").click( function(){

  var node = $(this);
  var old_value = node.html();

	$.get(  node.attr('href'),
					function(data)
					{
						if( !data.length )
            {
              setTimeout(function(){node.fadeOut('normal', function(){node.html(value)})}, '2000');
            }
						else
						{
							// Append fan if count < 27
							if( $('#fans').find('li').length < 27 )
							{
								var n = $(data).hide();
								$('#fans').find('ul:first').prepend(n);

								n.fadeIn('slow');

                // Update fans label
                var nodes = $("a[rel='fans-add-me']");
                nodes.hide().html('success !').fadeIn();
                setTimeout(function(){nodes.fadeOut('normal', function(){$("a[rel='fans-add-me']").html('I\'m already fan !').fadeIn()})}, '2000');

                // Increment Fans count
                var count = $("em[class$='stats-fans']");
                var value = parseInt(count.html())+1;
                count.fadeOut('normal', function(){$(this).html(value).fadeIn('normal')});
							}
						}
					}
				);

	return false;
});


/*Remove fan too !
-----------------------------------------*/
$("a[rel='fans-del-me']").click( function(){

  var node = $(this);
  var old_value = node.html();

	$.get(  node.attr('href'),
					function(data)
					{
            var id = parseInt(data);

						if( !id )
            {
              setTimeout(function(){node.fadeOut('normal', function(){node.html(data)})}, '2000');
            }
						else
						{
              $('#fans').find('#fans-'+id).fadeOut('slow');

              // Update fans label
              var nodes = $("a[rel='fans-add-me']");
              nodes.hide().html('success !').fadeIn();

              // Increment Fans count
              var count = $("em[class$='stats-fans']");
              var value = parseInt(count.html())-1;
              count.fadeOut('normal', function(){$(this).html(value).fadeIn('normal')});
						}
					}
				);

	return false;
});




/* Rate
-----------------------------------------*/
$("#rate-me").click( function(){

  var node = $(this);

	$.getJSON(  $(this).attr('href'),
					function(data)
					{
            var count = node.nextAll(".stats").find(".stats-fans");
            var value = parseInt(count.html());

            if( !data.error )
              value++

            count.fadeOut('normal', function(){$(this).html(data.msg).fadeIn('normal')});
            setTimeout(function(){count.fadeOut('normal', function(){$(this).html(value).fadeIn()})}, '1500');
					}
				);

	return false;
});






/* Comment I like / I dislike
------------------------------------------------------------------------------------------*/
$(".comment-feedback").find("a").live('click', function(){
  var node  = $(this);
  var count = node.parent().find('.count-like');
  var value = parseInt(count.html());

  $.post( node.attr('href'), {},
          function(data)
          {
            if( !data.error )
            {
              if( node.attr('class').indexOf('dislike') >= 0 )
                value -= 1;
              else
                value += 1;
            }

            if( value > 0 ) value = '+'+value;

            count.fadeOut('normal', function(){$(this).html(data.msg).fadeIn('normal')});
            setTimeout(function(){count.fadeOut('normal', function(){$(this).html(value).fadeIn()})}, '1500');
          },
          "json"
        );

  return false;
});




/* CONTENT > TOOLBOX
--------------------------------------------------------------------------------------- */
$("#toolbox a#toolbox-print").click( function(){ window.print(); return false; } );
$("#toolbox a#toolbox-share").click( function(){ return addthis_sendto(); } )
                             .mouseover( function(){ return addthis_open(this, '', '[URL]', '[TITLE]') })
                             .mouseleave( function(){ return addthis_close(); });
$("#toolbox a#toolbox-send").click( function(){ alert("DEBUG : Send to a friend"); return false; } );
$("#toolbox a#toolbox-increase").click( function(){
	var currentFontSize = $('#article-content p').css("font-size");
	var currentFontSizeNum = parseFloat(currentFontSize, 10);
	var newFontSize = currentFontSizeNum*1.2;
	$('#article-content p').css("font-size", newFontSize);
	return false;
});
$("#toolbox a#toolbox-decrease").click( function(){
	var currentFontSize = $('#article-content p').css("font-size");
	var currentFontSizeNum = parseFloat(currentFontSize, 10);
	var newFontSize = currentFontSizeNum*0.8;
	$('#article-content p').css("font-size", newFontSize);
	return false;
});



/* FOOTER > IT'S ALSO ON YKONE
--------------------------------------------------------------------------------------- */
/*
$("#also-on-ykone ul").ykoneSlider({
	template:"template5",
	step:1
});
*/


/* Tabs
----------------------*/
$("ul.tabs.ajax").yTabs();

/* Slides Recents news */
//$('#recent-news').ySlides({position:'BottomRight'});

/* Push directory Access */
$('#push-directory > ul > li > a').click(function(){ $('#push-directory-content').attr('rel', $(this).attr('href').split('#')[0]); });
$("#push-directory-menu").yTabs(function(){$('#push-directory-content').wrapInner('<ul><li>').ySlides({position:'BottomRight'})});
$('#push-directory-content').ySlides({position:'BottomRight'});

});// END onReady

/* FUNCTIONS
--------------------------------------------------------------------------------------- */
// fonction qui gère les focus sur les champs textes
function inputFocus()
{

$("input[type=text], textarea, input[type=password], select")
.focus(function()
	{
		$(this).addClass("focus");
		if ( $(this).val() == $(this).attr("title") )
		{
			$(this).val( "" );
		}
	})
.blur(function()
	{
		$(this).removeClass("focus");
		if ( $(this).val() == "" )
		{
			$(this).val( $(this).attr("title") );
		}
	});

$("input[type=submit], input[type=button]").hover(function()
	{
		$(this).addClass("hover");
	},
	function()
	{
		$(this).removeClass("hover");
	});

} // end input focus



// fonction qui gère les autocomplete (chargés en ajax) sur les champs textes
function inputAutocomplete(element, url, inputWidth){
	var urlToLoad = url;
	//alert(element);
	element.autocomplete(urlToLoad,{
		width:inputWidth
	});
}


// Small Plugin Toggle fade
jQuery.fn.fadeToggle = function(speed, easing, callback) {return this.animate({opacity: 'toggle'}, speed, easing, callback);};

// reset form
$.fn.clearForm = function() {
	return this.each(function()
	{
 		var type = this.type, tag = this.tagName.toLowerCase();
 		if (tag == 'form')
		return $(':input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
		{
			this.value = '';
			$(this).val( $(this).attr("title") );
		}
		else if (type == 'checkbox' || type == 'radio')
		{
			this.checked = false;
		}
		else if (tag == 'select')
		{
			this.selectedIndex = -1;
		}
	});
};