/*
.---.-.----.-----.---.-.-----.---.-.--------.-----.----.
|  _  |   _|  -__|  _  |  _  |  _  |        |  -__|   _|
|___._|__| |_____|___._|___  |___._|__|__|__|_____|__|  
                       |_____| www.areagamer.net
*/
/*
function include(filename)
{
	var head = document.getElementsByTagName('head')[0];
	
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	
	head.appendChild(script)
}

include('/js/jquery.inlinefieldlabel.js');
include('/js/jquery.scrollto.js');
include('/js/jquery.jcarousel.js');
include('/js/jquery.simplemodal.js');
include('/js/jquery.jcrop.js');

include('/js/wysiwyg_editor.js');
include('/js/ag_admin.js');
// include('/js/tiny_mce/tiny_mce.js');
include('/js/init.js');*/



 var headline_count;
 var headline_interval;
 var old_headline = 0;
 var current_headline = 0;
 
 var unique_id = 1;
 
 function goMenuDefault() {
   goMenu(0);
 } 
 
 function goMenu(id) {
   // current_headline = (old_headline + 1) % headline_count; 
  current_headline = id;
  var speed = "fast";
  if (id == 0) speed = "slow";
  if (current_headline != old_headline) {
    $("div.headline:eq(" + old_headline + ")").stop(true, true).animate({top: -205},speed, function() {
      $(this).css('top','210px');
    });
    $("div.headline:eq(" + current_headline + ")").stop(true, true).show().animate({top: 5},speed);  
    old_headline = current_headline;
  }
 }
 
 

$(document).ready(function(){
 
   /* var ec = new agc();	
   ec.set("_ag_id", "12345");
   ec.get("_ag_id", function(value) { console.log("Cookie value is " + value) }); */

   headline_count = $("div.headline").size();
   $("div.headline:eq("+current_headline+")").css('top','5px');
 
   $('#scrollup').hover(function() {
     clearInterval(headline_interval);
   }, function() {
     headline_interval = setInterval(goMenuDefault,1000); //time in milliseconds
   });
    
   $('.post_left').hover(function() {
    $('.options', this).stop(true, true).fadeIn('slow');
   }, function() {
    $('.options', this).stop(true, true).fadeOut('slow');
   });
    
   $('a', '#main_menu').hover(function() {
     clearInterval(headline_interval);
   }, function() {
     headline_interval = setInterval(goMenuDefault,1000); //time in milliseconds
   });
   
   
  
  
  $(function() {  
     $("#gameslist input[type='button']").click(function(){  
       var arr = $(this).attr("name").split("2");  
       var from = arr[0];  
       var to = arr[1];  
       $("#" + from + " option:selected").each(function(){
         var idGN = $("#gn_" + $(this).val()).val();
         if (idGN)
         {
            if (to == "mygames")
            {
                if ($("#gn_"+idGN+"_data").is(":hidden"))
                    $("#gn_"+idGN+"_data").slideDown("fast");

                if (!gn_aux[idGN]) gn_aux[idGN] = 0;
                gn_aux[idGN]++;
            }
            else
            {
                gn_aux[idGN]--;                
                if ((gn_aux[idGN] == 0) && (!$("#gn_"+idGN+"_data").is(":hidden")))
                    $("#gn_"+idGN+"_data").slideUp("fast");
            }
         }
         $("#" + to).append($(this).clone());  
         $(this).remove();
      });  
    });  
  })  
  

  /* - - - - - - - - - - - - - - */
  
//  $(".autogrow").autoGrow();



  $('div[name=editNote]').dblclick(function() {
  
  
            
    if (!$("div[name=txt]", this).is(':hidden')) {
      $("div[name=txt]", this).css('display', 'none');
      $("div[name=txtarea]", this).css('display', 'block');
    }
    
    // alert('Handler for .dblclick() called.');
  });

  $('#body input[type="text"], #body input[type="password"], #body textarea').addClass("idleField");			
	$('#body input[type="text"], #body input[type="password"]').focus(function() {			
		$(this).removeClass("errorField").addClass("idleField");
       	$(this).removeClass("idleField").addClass("focusField");
		if(this.value == this.defaultValue){
	    	this.select();
	    }
  });

  $('#body textarea').focus(function() {
		$(this).removeClass("idleField").addClass("focusField");
		if(this.value == this.defaultValue){
	    	this.select();
    }
  });
			

  $('#body input[type="text"], #body input[type="password"], #body textarea').blur(function() {
    if (!$(this).is('.errorField')) $(this).removeClass("focusField").addClass("idleField");
      // $(this).removeClass("errorField").addClass("idleField");
  });
  
  /* quotes */
  quoteEvent();
  
	// login
	pm.bind("login", function(data) {
		var obj = jQuery.parseJSON(JSON.stringify(data));
        $.post('/login/', { id:  obj.id, code:  obj.code }, function(data) {
          location.reload();
        }); 
		return 'ok';		
	});
	
	// images
	pm.bind("images", function(data) {
		var obj = jQuery.parseJSON(JSON.stringify(data));
		imageUploaded(obj.img, obj.t, obj.id);
	});

	pm.bind("videos", function(data) {
		var obj = jQuery.parseJSON(JSON.stringify(data));
		editorInsertCode(obj.tag, obj.code, obj.id);
	});
  
  
});

var cached_quotes = new Array();
function quoteEvent() {
  $('.post_cnt .quote').unbind("click");
  $('.post_cnt .quote').click(function() {
    var id = $(this).attr('href').substring(1);
    var texto = '<span style="color:#aaa"><img src="/images/loading.gif" class="imgIco" /> Cargando...</span>';

    if ($(this).closest('div').attr('name') == "quoted") {
      $(this).closest('div').before('<a class="quote" href="'+$(this).attr('href')+'">'+$(this).attr('href')+'</a>');
      $(this).closest('div').remove();
    } else {
      $(this).after('<div style="display: inline;" name="quoted"><a class="quote" href="'+$(this).attr('href')+'">'+$(this).attr('href')+'</a><div name="quote_nid_'+id+'" class="rnd_white" style="padding: 10px; margin-bottom: 10px;">'+texto+'</div></div>');
      $(this).remove();

      if (cached_quotes[id]) {
          $('div[name=quote_nid_'+id+']').html(cached_quotes[id]);
      } else {
        url = $(location).attr('href');
//        var thread_id = url.match(/([0-9])+/)[0];

			// var thread_id = url.exec(/(.*)\/([0-9])+/);
			// alert(match[1]);  // abc

			var regexp = /(.*)\/([0-9]+)/;
			var thread_id = regexp.exec(url);
			

        // var thread_id = url.match()[0];
        var type = url.match(/(foros|mensajeria)+/)[0];
		if (type == "foros") type = "forum";
		else if (type == "mensajeria") type = "messaging";
		else return false;
      
        $.post('/json/'+type+'/quotes/', { thread_id: thread_id[2], nid: id }, function(data) {
          if (!data) data = "<b>#"+id+"</b> No existe o ha sido borrado";
          cached_quotes[id] = data;
          $('div[name=quote_nid_'+id+']').html(data);
          quoteEvent();
        });  
      }
  
    }
    
    quoteEvent();
    
    return false;
  });
}

function submitForm(form_id) 
{
	
  if ($('#'+form_id+' #is_tinyMCE').val() == 'true')  
    tinyMCE.triggerSave(true, true); // Para sacar la información de un textarea TinyMCE

  if ($('#'+form_id+' #is_WYSIWYG').val())
    doCheck($('#'+form_id+' #is_WYSIWYG').val());
    
  if ($('#'+form_id+' #is_mgames').val())
    $("#mygames").each(function(){$("#mygames option").attr("selected","selected"); });
    

    
  $("#"+form_id+" div[name=loading]").html('');
  $("#"+form_id+" div[name=loading]").append("<img class=\"imgIco\" src=\"/images/loading.gif\" />");

  var data = $("#"+form_id).serialize(); 
  if ($('#'+form_id+' #is_mgames').val())
    data = data.replace(/&mygames=/g, '&mygames[]=');
    
//  alert(data);

  // deshabilitamos todos los campos (excepto TinyMCE que no se puede)
  $('#'+form_id+' input, #'+form_id+' textarea, #'+form_id+' input, #'+form_id+' checkbox, #'+form_id+' radio').each(function(){
      $(this).attr("disabled", "true");
  });
  
  

  $.post($("#"+form_id).attr('action'), data, function(data) {
    // habilitamos todos los campos de nuevo (aunque vaya a borrarse luego, ya que sino si se hace f5 saldrían deshabilitados por defecto)
    $('#'+form_id+' input, #'+form_id+' textarea, #'+form_id+' input, #'+form_id+' checkbox, #'+form_id+' radio').each(function(){
        $(this).removeAttr("disabled");
    });

    if (data.ok === true) { // Todo correcto   
      
      $("#"+form_id+" div[name=loading]").html('');

	  if (data.alert) alert(data.alert);
      if (data.redirect) location.href = data.redirect;
      if (data.val) {
        if (!data.val_msg) data.val_msg = '';
        $("#"+form_id+" div[name=loading]").append(data.val_msg+' <img class="imgIco" src="/images/icons/accept.png" />');
      }
      if (data.msg) {
        $('#'+form_id).remove();
        $('div[name='+form_id+']').html('');
        $('div[name='+form_id+']').append(data.msg);
      }
      if (data.exe) {        
        var funcCall = data.exe + "(" + data.exe_params + ");";
        var ret = eval(funcCall);
      }

    } else { // Hubo algún error en el formulario    

      if (data.error) {
        $("#dialog").html('');
        $("#dialog").append('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span> '+data.error+'</p>');
        $("#dialog").dialog({
          modal: true,
          width: 600,
          buttons: {
            Ok: function() { $(this).dialog('close'); }
          }
        });
      }
  
      $("#"+form_id+" div[name=loading]").html('');
      if (data.val_msg) {
        $("#"+form_id+" div[name=loading]").append(data.val_msg+' <img class="imgIco" src="/images/icons/exclamation.png" />');
      } else {
        $("#"+form_id+" div[name=loading]").append("<img class=\"imgIco\" src=\"/images/icons/exclamation.png\" />");
      }
	  
	  if (data.alert) alert(data.alert);

      if (data.exe) {        
        var funcCall = data.exe + "(" + data.exe_params + ");";
        var ret = eval(funcCall);
      }
    }

  } , "json");

  return false;
}

function login(url) {
	$.modal('<iframe name="login" id="login" src="http://www.areagamer.net' + url + '" height="350" width="386" style="border:0">', {  
		containerCss:{
			height:350,
			width:386
		},	
		opacity:80,
		overlayClose:true
	});
}

function setSomethingFromProfile(url, finished, extra_height) {

	if (finished)
	{
		  parent.modalClose();		
	}
	else
	{
		if (extra_height) var height = 250;
		else var height = 180;
		$.modal('<iframe name="cs" id="cs" src="' + url + '" height="'+height+'" width="386" style="border:0">', {  
			containerCss:{
				height:height,
				width:386
			},	
			opacity:80,
			overlayClose:true
		});
	}
}

function doLogin() {
    $.post('/login/', { genCode: true }, function(data) {
        if (data.ok === true) 
		{
			pm({
				target: window.parent,
				type: "login", 
				data:{id:data.id, code:data.code}, 
				success: function(data) {
					$('#lg').css('display', 'none');
					$('#ld').css('display', 'block');
				}
			});
		}
     } , "json");
}

function loginSuccessful(id, code) {
  $('#login_buton').unbind();
  $('#login_buton').html('Cargando...');
  
	pm({
		target: window.parent,
		type: "login", 
		data:{id:id, code:code}, 
		success: function(data) {
            $('#lg').css('display', 'none');
            $('#ld').css('display', 'block');
		}
	});
}


function mycarousel_initCallback(carousel) {

    $('#crsl_next').bind('click', function() {
        carousel.next();
        return false;
    });

    $('#crsl_prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

function showQuote(type, id) {
  if (type == "forum") {
    alert("mostrando quote #"+id);
    alert($(this).html());
  }
}

function uploadImage(type, id) {
  if (id === undefined)
  {
    $.modal('<iframe src="/upload/image/?t='+type+'&id='+id+'" height="360" width="600" style="border:0">', {
      containerCss:{
        height:360,
        width:600
      },	
      opacity:80,
      overlayClose:true
    });
  }
  else
  {
    $.modal('<iframe src="/upload/image/?t='+type+'&id='+id+'" height="360" width="600" style="border:0">', {
    
      containerCss:{
        height:360,
        width:600
      },	
      opacity:80,
      overlayClose:true
    });
  }
  // alert(url);
}

function uploadVideo(id) {
    $.modal('<iframe src="/upload/video/?id='+id+'" height="360" width="600" style="border:0">', {
      containerCss:{
        height:360,
        width:600
      },	
      opacity:80,
      overlayClose:true
    });
}


function imageUploaded(img, type, id) {
  if (type == "avatar") 
  {
    $('#avatar').html('<img src="/images/upload/avatar/'+img+'" />');
  } else if (type == "photo") 
  {
    $('#photo').html('<img src="/images/upload/photo/'+img+'" />');
  } 
  else if (type == "news_promote") 
  {
    $('#news_promote').html(img+'<input type="hidden" name="image" value="'+img+'">');
  } 
  else if ((type == "forum_main_post") || (type == "forum_reply"))
  {
    AddTag(id, '[img]', '[/img]', '/images/upload/forum/'+img);
  }
  else alert("Imagen subida ("+type+"): " + img);
  
  $.modal.close();
}

function editorInsertCode(tag, code, id) {
  AddTag(id, '['+tag+']', '[/'+tag+']', code);
  $.modal.close();
}

function modalClose() {
	$.modal.close();
}

function addComment(id) {
  $('#comment_'+id).css('display', 'block');
  $('#ico_note_'+id).attr("src","/images/icons/note_add_bn.png");
}

function cancelComment(id) {
  if (!$('div[name=txt]', '#comment_'+id).html())
  {
    $('#comment_'+id).css('display', 'none');
    $('#ico_note_'+id).attr("src","/images/icons/note_add.png");
  } else {  
    $('div[name=txt]', '#comment_'+id).css('display', 'block');
    $('div[name=txtarea]', '#comment_'+id).css('display', 'none');
  }
}

function saveComment(id, html) {  
  $('div[name=txt]', '#comment_'+id).html(html);
  cancelComment(id);
}

function foiThread(action) {
  if (action == "cancel")
  {
    $('#foi_buttons').css('display', 'block');
    $('#foi_cancel_ignore').css('display', 'none');
    $('#foi_cancel_follow').css('display', 'none');
  } 
  else if (action == "follow")
  {
    $('#foi_buttons').css('display', 'none');
    $('#foi_cancel_ignore').css('display', 'none');
    $('#foi_cancel_follow').css('display', 'block');
  } 
  else if (action == "ignore") 
  {
    $('#foi_buttons').css('display', 'none');
    $('#foi_cancel_ignore').css('display', 'block');
    $('#foi_cancel_follow').css('display', 'none');
  }
}

function editPost(id, content, title) 
{
    if (content)
    {  
            $('#post_'+id+'_content').html('');
            $('#post_'+id+'_content').append(content);
            
            $('#ico_edit_'+id).attr("src","/images/icons/comment_edit.png");
            $('#post_'+id+'_container').css('display', 'block');
            $('#post_'+id+'_edit').css('display', 'none');
            
            if (title)
            {  
                $('#thread_title').html('');
                $('#thread_title').append('<h3 style="padding: 0px 10px ;">'+title+'</h3>');                
            }
                  
            quoteEvent();
    }
    else
    {
        var aux_id = 'txt_post_'+id;
        
        if ($('#post_'+id+'_container').is(':hidden'))
        {
            $('#ico_edit_'+id).attr("src","/images/icons/comment_edit.png");
            $('#post_'+id+'_container').css('display', 'block');
            $('#post_'+id+'_edit').css('display', 'none');
            
            /* doCheck(aux_id);
            ifm[aux_id].style.display = 'none';
            textboxelement[aux_id].style.display = '';
            editorVisible[aux_id] = false; */
        
        
            /* if (tinyMCE.getInstanceById('txt_post_'+id))
            tinyMCE.execCommand('mceRemoveControl', false, 'txt_post_'+id); */
        }
        else
        {
        
            /* if (enableWysiwyg[aux_id] && ifm[aux_id]) {
                ifm[aux_id].style.display = '';
                textboxelement[aux_id].style.display = 'none';
                ShowEditor(aux_id);
                editorVisible[aux_id] = true;
            } */
        /*
            if ($('#refreshed_post_'+id).val() == "true")
            {
                alert('cambiando...' + 'txt_post_' + id);
                if (!tinyMCE.getInstanceById('txt_post_'+id))
                {
                    tinyMCE.execCommand('mceAddControl', false, 'txt_post_'+id);
                    alert('cambiado!' + 'txt_post_' + id);
                }
                $('#refreshed_post_'+id).val('false');
            }*/
			
           /* if (!tinyMCE.getInstanceById('txt_post_'+id))
            tinyMCE.execCommand('mceAddControl', false, 'txt_post_'+id); */

			$('#ico_edit_'+id).attr("src","/images/icons/comment_edit_bw.png");
            $('#post_'+id+'_container').css('display', 'none');
            $('#post_'+id+'_edit').css('display', 'block');
        }   
    }
}

function toggleEditor(id) {
    if (!tinyMCE.getInstanceById(id))
        tinyMCE.execCommand('mceAddControl', false, id);
    else
        tinyMCE.execCommand('mceRemoveControl', false, id);
}


function deletePost(id, confirm)
{
    if (confirm)
    {
        $('#replies_counter').val(($('#replies_counter').val()-1));
        $("div#post_"+id).slideUp("slow");
        if ($('#replies_counter').val() == 0) {
            $("div#extra_pag").slideUp("slow");	// slideUp qda mejor, pero por tema de diseño va mal					
        }
    }
    else
    {
        $("#dialog").html('');
        $("#dialog").append('¿Seguro que deseas borrarlo? La acción será irreversible.');
        $("#dialog").dialog({
			modal: true,
            width: 400,
			buttons: {
				'Si': function() {
					submitForm('del_post_'+id);
                    $(this).dialog('close');
				},
				'No': function() {
					$(this).dialog('close');
				}
			}
		});
    }
}

function censorPost(id, msg, sys)
{
		if (msg)
		{
			if ($("div#post_"+id).is(":hidden"))
				$("div#post_"+id).slideDown("slow");
			else
				$("div#post_"+id).slideUp("slow");
		}
		
		if (sys)
		{
			if ($("div#post_"+id+"_censor").is(":hidden"))
			{
				$("#link_censor_"+id).css('display', 'inline-block');
				$("#link_uncensor_"+id).css('display', 'none');
				$("div#post_"+id+"_censor").slideDown("slow");
			}
			else
			{
				$("#link_censor_"+id).css('display', 'none');
				$("#link_uncensor_"+id).css('display', 'inline-block');
				$("div#post_"+id+"_censor").slideUp("slow");
			}
		}
}

function disableAD()
{
    if ($('input[name=disable_ad]').is(':checked'))
    {
        $("#dialog").html('');
        $("#dialog").append('<p style="text-align: center;"><img src="/images/gato_shrek.jpg" /></p><p>La publicidad es nuestra única manera de sobrevivir. <br />¿Seguro que quieres quitarla?</p>');
        $("#dialog").dialog({
			modal: true,
            width: 400,
			buttons: {
				'Si': function() {
                    $('input[name=disable_ad]').attr('checked', true);
                    $(this).dialog('close');
				},
				'No': function() {
                    $('input[name=disable_ad]').attr('checked', false);
					$(this).dialog('close');
				}
			}
		});
    }
}


function refreshReplies(url, nid) 
{
  $("#replies").html('');
  $("#replies").append("<p style=\"text-align: center\"><img src=\"/images/loading2.gif\" /><br /> Cargando, por favor, espere...</p>");
  $.post(url, { js: true }, function(data) {
    $("#replies").html('');
    $("#replies").append(data);
    quoteEvent();
    $.scrollTo('#'+nid, 300);    
  });  
}

function profileLoadContent(url, target, menu) {
  // alert("load: "+url);
  $("#"+target).html('');
  $("li", ".m_profile").removeClass("current");
  $("li[name="+menu+"]").addClass("current");  
  $("#"+target).append("<p style=\"text-align: center\"><img src=\"/images/loading2.gif\" /><br /> Cargando, por favor, espere...</p>");
  
  $.post(url, { js: true }, function(data) {
    $("#"+target).html('');
    $("#"+target).append(data);
  });  
}

function refreshVotes(type, id, votes) 
{
    if (type == 1) {
        var html = '<li class="votos"><span>+'+votes+'</span></li>' +
				   '<li class="corz"><img src="/images/icons/heart.png" class="imgIco" /></li>';
        $("div[name=vote_post_"+id+"]").html('');
        $("div[name=vote_post_"+id+"]").append(html);
    }
}

function selectProfileTab(id) 
{
    $("li", "#menu_profile").removeClass("current");
    $("#"+id, "#menu_profile").addClass("current");  
    
    var tabs = new Array("personal", "forums", "invites", "hardware", "gamer",  "config");
    for (i=0;i<tabs.length;i++){    
        $("#cnt_"+tabs[i]).css('display', 'none');
    } 
    $("#cnt_"+id).css('display', 'block');
}


/* otros */ 
/*
$.fn.passwordStrength = function( options ){
	return this.each(function(){
		var that = this;that.opts = {};
		that.opts = $.extend({}, $.fn.passwordStrength.defaults, options);
		
		that.div = $(that.opts.targetDiv);
		that.defaultClass = that.div.attr('class');
		
		that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100;

		 v = $(this)
		.keyup(function(){
			if( typeof el == "undefined" )
				this.el = $(this);
			var s = getPasswordStrength (this.value);
			var p = this.percents;
			var t = Math.floor( s / p );
			
			if( 100 <= s )
				t = this.opts.classes.length - 1;
				
			this.div
				.removeAttr('class')
				.addClass( this.defaultClass )
				.addClass( this.opts.classes[ t ] );
				
		})
		.next()
		.click(function(){
			$(this).prev().val( randomPassword() ).trigger('keyup');
			return false;
		});
	});

	function getPasswordStrength(H){
		var D=(H.length);
		if(D>5){
			D=5
		}
		var F=H.replace(/[0-9]/g,"");
		var G=(H.length-F.length);
		if(G>3){G=3}
		var A=H.replace(/\W/g,"");
		var C=(H.length-A.length);
		if(C>3){C=3}
		var B=H.replace(/[A-Z]/g,"");
		var I=(H.length-B.length);
		if(I>3){I=3}
		var E=((D*10)-20)+(G*10)+(C*15)+(I*10);
		if(E<0){E=0}
		if(E>100){E=100}
		return E
	}

};	
$.fn.passwordStrength.defaults = {
	classes : Array('is10','is20','is30','is40','is50','is60','is70','is80','is90','is100'),
	targetDiv : '#passwordStrengthDiv',
	cache : {}
} */



