$(document).ready(function(){
    //$("a[rel^='show']").prettyPhoto({social_tools:false,default_width: 620,allow_resize: false,keyboard_shortcuts:false});
    //$('a[rel*=show]').facebox() ;
    var $register = $('#registerFormContainer')
		.dialog({
			autoOpen: false,
			title: 'Registrar nuevo usuario',
            resizable: false,
            modal: true,
            show: 'blind',
            hide: 'blind',
            width: 670,
            buttons: {
				'Crear nueva cuenta': function() {
                    registerUser();
                },
                'Salir':function() {
                    $(this).dialog('close');
                    $('button').removeClass( 'ui-state-disabled ui-state-focus ui-state-hover' );
                }
            },
            closeOnEscape: false
		});
    
    $("#loadingScreen").dialog({
		autoOpen: false,	// set this to false so we can manually open it
		dialogClass: "loadingScreenWindow",
		closeOnEscape: false,
		draggable: false,
		width: 250,
		minHeight: 30,
		modal: true,
		buttons: {},
		resizable: false,
		open: function() {
			// scrollbar fix for IE
			$('body').css('overflow','hidden');
		},
		close: function() {
			// reset overflow
			$('body').css('overflow','auto');
		}
	}); // end of dialog
     
	$('#registerB').click(function() {
		$register.dialog('open');
		return false;
    });
    
    $('#usermail').focus(function (e) {
        e.preventDefault();
        $(this).next("div").fadeIn(100);
    });
    $('#usermail').focusout(function (e) {
        e.preventDefault();
        $(this).next("div").fadeOut(0);
    });
    $('#usertelephone').focus(function (e) {
        e.preventDefault();
        $(this).next("div").fadeIn(100);
    });
    $('#usertelephone').focusout(function (e) {
        e.preventDefault();
        $(this).next("div").fadeOut(0);
    });
     $('#usercode').focus(function (e) {
        e.preventDefault();
        $(this).next("div").fadeIn(100);
    });
     $('#usercode').focusout(function (e) {
        e.preventDefault();
        $(this).next("div").fadeOut(0);
    });
    $('#userpass').focus(function (e) {
        e.preventDefault();
        $(this).next("div").fadeIn(100);
    });
    $('#userpass').focusout(function (e) {
        e.preventDefault();
        $(this).next("div").fadeOut(0);
    });
    $('#userdescrip').focus(function (e) {
        e.preventDefault();
        $(this).next("div").fadeIn(100);
    });
    $('#userdescrip').focusout(function (e) {
        e.preventDefault();
        $(this).next("div").fadeOut(0);
    });
    $('#updateUserInfo').submit(function(event) {
        event.preventDefault();
        edit_profile();
    });
    $('#updateDescript').submit(function(event) {
        event.preventDefault();
        edit_personaldescript();
    });
    $('#updateMyPage').submit(function(event) {
        event.preventDefault();
        edit_mypage();
    });
    $('#upload_button1').click(function() {
		subirImagen();
		return false;
    });
    $('#newTopic').submit(function(event) {
        event.preventDefault();
        new_topic();
    });
    $('#replyPost').submit(function(event) {
        event.preventDefault();
        new_reply();
    });
    $('#formSemiAsociado').submit(function(event) {
        event.preventDefault();
        add_payment('formSemiAsociado');
    });
    $('#formAsociado').submit(function(event) {
        event.preventDefault();
        add_payment('formAsociado');
    });
    $('#formVIP').submit(function(event) {
        event.preventDefault();
        add_payment('formVIP');
    });
    $('.barracentro a').tipsy({gravity: 's'});
        
    $('.deletePost').click(function(e){
        e.preventDefault();
        var idToLoad = $(this).attr('href'); 
        if (confirm('Seguro que quieres eliminar este tema?'))
        {
            waitingDialog({title: "", message: "Cargando... Por favor espere..."});
        
            $.ajax({
                    url: 'includes/delete_post.php?id='+idToLoad,
                    type: 'POST',
                    cache: false,
                    success: function(data) {
                        closeWaitingDialog();
                        if (data == 'success') {
                            show_message('','Tema eliminado de manera satisfactoria!.','Exito');
                            setTimeout(function(){
                                $('#'+idToLoad).hide(150);
                            },1500);       
                        } else {
                            var titleshow = 'Error al intentar eliminar el tema';
                            if (data == 1){
                                show_message('','Error inesperado.',titleshow)
                            }
                        }                        
                }
            });
        }
    });
    $('.deleteComment').click(function(e){
        e.preventDefault();
        var idToLoad = $(this).attr('href'); 
        if (confirm('Seguro que quieres eliminar este comentario?'))
        {
            waitingDialog({title: "", message: "Cargando... Por favor espere..."});
        
            $.ajax({
                    url: 'includes/delete_comment.php?id='+idToLoad,
                    type: 'POST',
                    cache: false,
                    success: function(data) {
                        closeWaitingDialog();
                        if (data == 'success') {
                            show_message('','Comentario eliminado de manera satisfactoria!.','Exito');
                            setTimeout(function(){
                                location.reload(true);
                            },1500);       
                        } else {
                            var titleshow = 'Error al intentar eliminar el comentario.';
                            if (data == 1){
                                show_message('','Error inesperado.',titleshow)
                            }
                        }                   
                }
            });
        }
    });
});
function waitingDialog(waiting) { // I choose to allow my loading screen dialog to be customizable, you don't have to
	$("#loadingScreen").html('&nbsp;'+waiting.message);
	$("#loadingScreen").dialog('option', 'title', waiting.title);
	$("#loadingScreen").dialog('open');
}
function closeWaitingDialog() {
	$("#loadingScreen").dialog('close');
}
function registerUser(){
    $(":button:contains('Crear nueva cuenta')").attr("disabled","disabled").addClass( 'ui-state-disabled' );
    $(":button:contains('Salir')").attr("disabled","disabled").addClass( 'ui-state-disabled' );
    $('tr').fadeOut(100, function(){
        $('caption').html('Registrando nuevo usuario... Por favor espere.<br /><br /><img src="images/loading.gif" alt="cargando..." />');  
    });
    $.ajax({
        url: 'includes/register.php',
        data: $('#registerForm').serialize(),
        type: 'POST',
        cache: false,
        success: function(data) {
            if (data == 'success') {
                var $registerDone = $('#message')
        		.dialog({
        			autoOpen: false,
        			title: 'Registro exitoso',
                    resizable: false,
                    modal: true,
                    show: 'blind',
                    hide: 'blind',
                    width: 500,
                    buttons: {
        				'Aceptar':function() {
                            $(this).dialog('close');
                            $('button').removeClass( 'ui-state-disabled ui-state-focus ui-state-hover' );
                        }
                    },
                    close: function(){
                        $('button').removeAttr('disabled'); // To enable  
                        $('button').removeClass( 'ui-state-disabled ui-state-focus ui-state-hover' );
                        $('tr').show();
                        $('caption').html('Formulario de reg&iacute;stro');
                        $('#registerForm input').val('');
                    }
        		});
                
                $('#registerFormContainer').dialog("close");
           	    $('#message').removeClass("hidden");
                $registerDone.dialog('open');
            }
            else {
                var titleshow = 'Error al intentar registrar cuenta';
                if (data == 0){
                    show_error('Nombres','Campo obligatorio, no debe poseer caracteres especiales y estar comprendido entre 3 y 25.',titleshow)
                }
                if (data == 1){
                    show_error('Apellidos','Campo obligatorio, no debe poseer caracteres especiales y estar comprendido entre 3 y 25.',titleshow)
                }
                if (data == 2){
                    show_error('Tel&eacutefono','Campo obligatorio, debe tener el siguiente formato 0000-0000000 .',titleshow)
                }
                if (data == 3){
                    show_error('Correo electronico','Campo obligatorio, no debe poseer caracteres especiales.',titleshow)
                }
                if (data == 4){
                    show_error('Nombre de usuario','Campo obligatorio, no debe poseer caracteres especiales y estar comprendido entre 3 y 25.',titleshow)
                }
                if (data == 5){
                    show_error('Contrase&ntilde;a','Campo obligatorio, debe estar comprendido entre 6 y 25.',titleshow)
                }
                if (data == 6){
                    show_error('Repetir Contrase&ntilde;a','Campo obligatorio, debe ser igual al campo <span class="bold">Contrase&ntilde;a</span>.',titleshow)
                }
                if (data == 7){
                    show_error('Nombre de usuario no disponible',',Por favor elija uno diferente.',titleshow)
                }
                if (data == 8){
                    show_error('Token error: ','Problemas chequeando la validez de los datos, por favor recarga la pagina con la tecla F5 de tu teclado si el problema persiste.',titleshow)
                }
                if (data == 9){
                    show_error('Correo ya utilizado en otra cuenta','Por favor elija uno diferente. Solo 1 correo por cuenta.',titleshow)
                }
                if (data == 10){
                    show_error('Ip detectada','Fue detectada una cuenta en esta ip, solo se permite 1 cuenta por direcci&oacute;n IP.',titleshow)
                }
            }
        }
    }); 
}
function show_error(field, description,title){
    var $error = $('<div><span class="bold">'+ field + '</span> - ' + description + '</div>')
        .dialog({
			autoOpen: false,
			title: title,
            resizable: false,
            draggable: false,
            modal: true,
            width: 350,
            buttons: {
                'Aceptar':function() {
                    $(this).dialog('close');
                }
            },
            close: function(){
                    $('button').removeAttr('disabled'); // To enable  
                    $('button').removeClass( 'ui-state-disabled ui-state-focus ui-state-hover' );
                    $('tr').show();
                    $('caption').html('Formulario de reg&iacute;stro'); 
            }
		});
        $error.dialog('open');
}
function show_message(field,description,title,funcion){
    var $message = $('<div id="mensaje"><span class="bold">'+ field + '</span> - ' + description + '</div>')
            .dialog({
    			autoOpen: false,
    			title: title,
                resizable: false,
                draggable: false,
                modal: true,
                show: 'blind',
                hide: 'blind',                
                width: 350,
                buttons: {
                    'Aceptar':function() {
                        $(this).dialog('close');
                    }
                },
                close: function(){
                    if(funcion === true){
                        location.href='login.php'
                    }
                }
    		});
            $message.dialog('open');    
}
function edit_profile(){
    $('#updateInfob').attr("disabled", true); 
    waitingDialog({title: "", message: "Cargando... Por favor espere..."});
    $.ajax({
            url: 'includes/editprofile.php',
            data: $('#updateUserInfo').serialize(),
            type: 'POST',
            cache: false,
            success: function(data) {
                closeWaitingDialog();
                if (data == 'success') {
                    show_message('','Perfil actualizado de manera exitosa!.','Actualizaci&oacute;n exitosa');
                    $('#updateInfob').attr("disabled", false);
                } else {
                    var titleshow = 'Error al intentar actualizar la cuenta';
                    if (data == 1){
                        show_message('Email','Campo obligatorio, no debe poseer caracteres especiales.',titleshow)
                    }
                    if (data == 2){
                        show_message('Tel&eacutefono','Campo obligatorio, debe tener el siguiente formato 0000-0000000 .',titleshow)
                    }
                    if (data == 3){
                        show_message('Contrase&ntilde;a','Campo obligatorio, debe estar comprendido entre 6 y 25.',titleshow)
                    }
                    if (data == 4){
                        show_message('Repetir Contrase&ntilde;a','Campo obligatorio, debe ser igual al campo <span class="bold">Contrase&ntilde;a</span>.',titleshow)
                    }
                    if (data=='successPass'){
                        var $callback = true;
                        show_message('','Contrase&ntilde;a actualizada de manera exitosa!.','Actualizaci&oacute;n exitosa', $callback);
                    }
                    $('#updateInfob').attr("disabled", false);
                }
        }
    });    
}
function edit_personaldescript(){
    $('#updateDescriptb').attr("disabled", true); 
    waitingDialog({title: "", message: "Cargando... Por favor espere..."});
    $.ajax({
            url: 'includes/editpersonalinfo.php?from=profile',
            data: $('#updateDescript').serialize(),
            type: 'POST',
            cache: false,
            success: function(data) {
                closeWaitingDialog();
                if (data == 'success') {
                    show_message('','Perfil actualizado de manera exitosa!.','Actualizaci&oacute;n exitosa');
                    $('#updateDescriptb').attr("disabled", false);
                } else {
                    var titleshow = 'Error al intentar actualizar la cuenta';
                    if (data == 1){

                    }
                    if (data == 2){
                        show_message('Descripci&oacute;n','No debe poseer m&aacute;s de 255 caracteres.',titleshow)
                    }
                    $('#updateDescriptb').attr("disabled", false);
                }
        }
    });    
}
function new_reply(){
    $('#submitPageb').attr("disabled", true); 
    waitingDialog({title: "", message: "Cargando... Por favor espere..."});
                    var Url = location.href;
                    Url = Url.replace(/.*\?(.*?)/,"$1");
                    Variables = Url.split ("&");
                    for (i = 0; i < Variables.length; i++) {
                           Separ = Variables[i].split("=");
                           eval ('var '+Separ[0]+'="'+Separ[1]+'"');
                    }
    if(window.tinyMCE){
        tinyMCE.get("contentpage").save();        
    }
    $.ajax({
            url: 'includes/forumanager.php?do=reply&topic='+topic,
            data: $('#replyPost').serialize(),
            type: 'POST',
            cache: false,
            success: function(data) {
                closeWaitingDialog();
                if (data == 'success') {
                    $('#submitPageb').attr("disabled", false);
                    location.reload(true);
                } else {
                    var titleshow = 'Error al intentar responder el tema';
                    if (data == 1){
                         show_message('','La respuesta debe poseer entre 3 y 500 caracteres.',titleshow)
                    }
                    if (data == 2){
                         show_message('','Los usuarios BANEADOS no tienen derecho a responder ning&uacute;n tema.',titleshow)
                    }
                    if (data == 3){
                         show_message('','Tu cuenta no esta activada, debes activarla a trav&eacute;s del link enviado a tu correo electr&oacute;nico.',titleshow)
                    }
                    $('#submitPageb').attr("disabled", false);
                }
        }
    });    
}
function new_topic(){
    $('#submitPageb').attr("disabled", true); 
    waitingDialog({title: "", message: "Cargando... Por favor espere..."});
    if(window.tinyMCE){
        tinyMCE.get("contentpage").save();        
    }
    $.ajax({
            url: 'includes/forumanager.php?do=new',
            data: $('#newTopic').serialize(),
            type: 'POST',
            cache: false,
            success: function(data) {
                closeWaitingDialog();
                if (data == 'success') {
                    show_message('','Nuevo tema creado de manera exitosa!.','Felicitaciones');
                    $('#submitPageb').attr("disabled", false);
                    var Url = location.href;
                    Url = Url.replace(/.*\?(.*?)/,"$1");
                    Variables = Url.split ("&");
                    for (i = 0; i < Variables.length; i++) {
                           Separ = Variables[i].split("=");
                           eval ('var '+Separ[0]+'="'+Separ[1]+'"');
                    }
                    location.href='forum.php?sid='+sid;
                } else {
                    var titleshow = 'Error al intentar crear el nuevo tema';
                    if (data == 2){
                         show_message('T&iacute;tulo','El t&iacute;tulo debe poseer entre 3 y 200 caracteres.',titleshow)
                    }
                    if (data == 3){
                        show_message('Descripci&oacute;n','El tema debe poseer entre 3 y 65000 caracteres.',titleshow)
                    }
                    if (data == 4){
                        show_message('','Los usuarios normales estan limitados a 1 tema diario.',titleshow)
                    }
                    if (data == 5){
                        show_message('','Los usuarios SMS estan limitados a 5 temas diarios.',titleshow)
                    }
                    if (data == 6){
                        show_message('','Los usuarios BANEADOS no tienen derecho a realizar nuevos temas.',titleshow)
                    }
                    if (data == 7){
                        show_message('','Tu cuenta no esta activada, debes activarla a trav&eacute;s del link enviado a tu correo electr&oacute;nico',titleshow)
                    }
                    $('#submitPageb').attr("disabled", false);
                }
        }
    });    
}
function edit_mypage(){
    $('#submitPageb').attr("disabled", true); 
    waitingDialog({title: "", message: "Cargando... Por favor espere..."});
    if(window.tinyMCE){
        tinyMCE.get("contentpage").save();        
    }
    $.ajax({
            url: 'includes/editpersonalinfo.php?from=mypage',
            data: $('#updateMyPage').serialize(),
            type: 'POST',
            cache: false,
            success: function(data) {
                closeWaitingDialog();
                if (data == 'success') {
                    show_message('','P&aacute;gina actualizada de manera exitosa!.','Actualizaci&oacute;n exitosa');
                    $('#submitPageb').attr("disabled", false);
                } else {
                    var titleshow = 'Error al intentar actualizar la cuenta';
                    if (data == 1){

                    }
                    if (data == 2){
                        show_message('Descripci&oacute;n','No debe poseer m&aacute;s de 255 caracteres.',titleshow)
                    }
                    $('#submitPageb').attr("disabled", false);
                }
        }
    });    
}
function add_payment(form){
    $('#'+form+' #insert').attr("disabled", true); 
    waitingDialog({title: "", message: "Cargando... Por favor espere..."});
    
    $.ajax({
            url: 'includes/add_payment.php',
            data: $('#'+form).serialize(),
            type: 'POST',
            cache: false,
            success: function(data) {
                closeWaitingDialog();
                if (data == 'success') {
                    show_message('','Datos enviados correctamente, en un lapso no mayor a 24Hs su cuenta sera activada con el nuevo rango!.','Exito');
                    $('#'+form+' #insert').attr("disabled", false);
                    $(':input', '#'+form).each(function() {
                        var type = this.type;
                        if (type == 'text'){
                            this.value = '';   
                        }
                    });                    
                } else {
                    var titleshow = 'Error al intentar enviar los datos';
                    if (data == 1){
                        show_message('Deposito','Campo obligatorio, no debe poseer mas de 10 caracteres.',titleshow)
                    }
                    if (data == 2){
                        show_message('Fecha','Campo obligatorio.',titleshow);
                    }
                    if (data == 3){
                        show_message('Monto','Campo obligatorio, no debe poseer mas de 3 caracteres.',titleshow);
                    }
                    $('#'+form+' #insert').attr("disabled", false);
                }
        }
    });    
}
function counterChars(maximo,texta){
    var total_letras = maximo;
    $('#resto').html(total_letras);
    $(texta).keyup(function() {
        var longitud = $(this).val().length;
        var resto = total_letras - longitud;
        $('#resto').html(resto);
        if(resto <= 0){
            $(texta).attr("maxlength", total_letras);
            return false;
        }
    });
}
function myListener(mytextarea,myfunction){   
     tinyMCE.addEvent(tinyMCE.getInstanceById(mytextarea).getDoc(), 'keyup',myfunction);
     return;
}
