// jQuery Document
jQuery(document).ready(function(){
    
    jQuery("form input, form select").live('keypress', function (e) {
        if (jQuery(this).parents('form').find('button[type=submit].default, input[type=submit].default').length <= 0)
        return true;

        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            jQuery(this).parents('form').find('button[type=submit].default, input[type=submit].default').click();
            return false;
        } else {
                return true;
        }
        });
 
    var newscrollHeight = jQuery("#chatbox").attr("scrollHeight") - 10;
    jQuery("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
 
    
	//If user submits the form
	jQuery("#submit_post").click(function(){	
		var clientmsg = jQuery("#message").val();
		jQuery.post("/chat/post", {message: clientmsg});				
		jQuery("#message").attr("value", "");
		return false;
	});
    
	//If admin submits the form
	jQuery("#submit_post_admin").click(function(){	
		var clientmsg = jQuery("#message").val();
		jQuery.post("/admin/chat/post", {message: clientmsg});				
		jQuery("#message").attr("value", "");
		return false;
	});    
	
	//Load the file containing the chat log
	function loadLog(){		
		var oldscrollHeight = jQuery("#chatbox").attr("scrollHeight") - 10;
		jQuery.ajax({
			url: "/chat/users.log",
			cache: false,
			success: function(html){		
				jQuery("#chatbox").html(html); //Insert chat log into the #chatbox div				
				var newscrollHeight = jQuery("#chatbox").attr("scrollHeight") - 10;
				if(newscrollHeight > oldscrollHeight){
					jQuery("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
				}		
                Colored(user);
		  	}
		});
	}
    if(jQuery("#chatbox").length)
	   setInterval (loadLog, 1500);	//Reload file every 1.5 seconds
	
	//If user wants to end session
	jQuery("#exit").click(function(){	   
		return confirm("Desea abandonar la sala?");      
	});
});


function Colored(user){
    jQuery("."+user).each(function(){
        jQuery(this).addClass('me');
    });
}
