// JavaScript Document
/***********************************************************************************************************************
 ** function login()                                                                                                   **
 ***********************************************************************************************************************/
function login(){
    var user = document.getElementById('form_login_user').value;
    var password = document.getElementById('form_login_password').value;
    jQuery.post('gestor/login.php', {
        user:user, 
        password:password
    }, function(data){
        if(data == '1'){
            jQuery("#popup_login").fadeOut("slow");
            window.location.href = 'index.php?sec=gestor';
        }
        if(data == '0'){
            jAlert('Tu nombre de usuario o contraseña son incorrectos.', 'LOGIN FAILED');
        }
    });
}
/***********************************************************************************************************************
 ** function addOrUpdateProducto()                                                                                       **
 ***********************************************************************************************************************/
function addOrUpdateProducto(){
    var id = document.getElementById('product_id').value;
    var nombre = document.getElementById('product_nombre').value;
    var imagen = document.getElementById('product_image_to_save').value;
    var precio = document.getElementById('product_precio').value;
    var descripcion = document.getElementById('product_descr').value;
    var descripcion_corta = document.getElementById('product_descr_corta').value;
	
    if(nombre == '' || nombre == 'Editar nombre...' || precio == '' || imagen == 'uploads/subir_foto.png'){
        jAlert('Comprueba que has rellenado todos los campos y subido una foto para el producto', 'CAMPO VACÍO');
    } else{ 
        if (descripcion == '' || descripcion_corta == '') {
            jConfirm('¿Estas seguro de que quieres dejar la descripción vacia?', 'Descripción o descripción corta vacios', function(r) {
                if (r) {  
                    var destacado = '0';
                    if(document.getElementById('check_destacado').checked){
                        destacado = '1';
                    }
                    var activo = '0';
                    if(document.getElementById('check_activo').checked){
                        activo = '1';
                    }
                    var categorias = "";
                    $("#product_categorias option:selected").each(function () {
                        categorias += $(this).text() + "*";
                    });
                    var select_marca = document.getElementById('select_marca');
                    var id_marca = select_marca.options[select_marca.selectedIndex].value;
                    
                    jQuery.post('gestor/GestorProductos.php', {
                        funcion:'addOrUpdateProducto', 
                        id:id, 
                        nombre:nombre, 
                        descripcion:descripcion, 
                        descripcion_corta:descripcion_corta, 
                        precio:precio, 
                        imagen:imagen, 
                        destacado:destacado, 
                        activo:activo, 
                        categorias:categorias
                    }, 
                    function(data){
                        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
                        if(data == '0'){
                            jAlert('No se ha podido guardar el producto correctamente', 'ERROR');
                        } else{
                            if(id_marca != ""){
                                asignarMarcaAProducto(data, id_marca);
                            } else{
                                borrarMarcaDeProducto(data);
                            }
                            jAlert('Se ha guardado el producto correctamente', 'ÉXITO');
                            if(id == -1){
                                document.getElementById('product_id').value = data;
                            }
                        }
                    });
                }
            });
        } else {
            var destacado = '0';
            if(document.getElementById('check_destacado').checked){
                destacado = '1';
            }
            var activo = '0';
            if(document.getElementById('check_activo').checked){
                activo = '1';
            }
            var categorias = "";
            $("#product_categorias option:selected").each(function () {
                categorias += $(this).text() + "*";
            });
			
            var select_marca = document.getElementById('select_marca');
            var id_marca = select_marca.options[select_marca.selectedIndex].value;
	
            jQuery.post('gestor/GestorProductos.php', {
                funcion:'addOrUpdateProducto', 
                id:id, 
                nombre:nombre, 
                descripcion:descripcion, 
                descripcion_corta:descripcion_corta, 
                precio:precio, 
                imagen:imagen, 
                destacado:destacado, 
                activo:activo, 
                categorias:categorias
            }, 
            function(data){
                data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
                if(data == '0'){
                    jAlert('No se ha podido guardar el producto correctamente', 'ERROR');
                } else{
                    if(id_marca != ""){
                        asignarMarcaAProducto(data, id_marca);
                    } else{
                        borrarMarcaDeProducto(data);
                    }
                    jAlert('Se ha guardado el producto correctamente', 'ÉXITO');
                    if(id == -1){
                        document.getElementById('product_id').value = data;
                    }
                }
            });
        }	
    }
}
/***********************************************************************************************************************
 ** function borrarProductoSafe(id)                                                                                        **
 ***********************************************************************************************************************/
function borrarProductoSafe(id){
    jConfirm('¿Estas seguro de que quieres borrar este producto?', 'Confirmación de borrado', function(r) {
        if (r) { 
            borrarProducto(id);
        }
    });
}
/***********************************************************************************************************************
     ** function borrarProducto(id)                                                                                        **
     ***********************************************************************************************************************/
function borrarProducto(id){
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'borrarProducto', 
        id:id
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        if(data == "0"){
            jAlert('No se ha podido borrar el producto correctamente', 'ERROR');
        } else if(data == '1'){
            jAlert('Se ha borrado el producto correctamente', 'ÉXITO');
            getProductosAEditar("", "", "", "", "");
            getPaginacion("", "", "", "");
        }
    });
}
/***********************************************************************************************************************
     ** function addCategoria()                                                                                  **
     ***********************************************************************************************************************/
function addCategoria(){
    var nombre = document.getElementById('input_addcategoria').value;
    if(nombre = ""){
        jAlert('No puedes añadir una categoría vacía', 'CAMPO VACÍO');
    } else{
        jQuery.post('gestor/GestorProductos.php', {
            funcion:'addCategoria', 
            nombre:document.getElementById('input_addcategoria').value
        }, function(data){
            data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
            if(data == "ERROR"){
                jAlert('No se ha podido añadir la categoría correctamente', 'ERROR');
            } else if(data == 'OK'){
                jAlert('Se ha añadido la categoria correctamente', 'ÉXITO');
                getCategoriasAEditar();
            }
        });
    }
}
/***********************************************************************************************************************
     ** function borrarCategoria(nombre_categoria)                                                                                  **
     ***********************************************************************************************************************/
function borrarCategoria(nombre_categoria){
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'borrarCategoria', 
        nombre_categoria:nombre_categoria
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        if(data == "ERROR"){
            jAlert('No se ha podido borrar la categoría correctamente', 'ERROR');
        } else if(data == 'OK'){
            jAlert('Se ha borrado la categoria correctamente', 'ÉXITO');
            getCategoriasAEditar();
        }
    });
}

/***********************************************************************************************************************
     ** function addMarca()                                                                                  **
     ***********************************************************************************************************************/
function addMarca(){
	
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'addMarca', 
        nombre:'Nueva marca...', 
        logo:'uploads/subir_foto.png'
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        if(data == "ERROR"){
            jAlert('No se ha podido añadir la marca correctamente', 'ERROR');
        } else if(data == 'OK'){
            jAlert('Se ha añadido la marca correctamente', 'ÉXITO');
            getMarcasAEditar();
        }
    });
}
/***********************************************************************************************************************
     ** function updateMarca(id, nombre, logo)                                                                                  **
     ***********************************************************************************************************************/
function updateMarca(id, nombre, logo){
	
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'updateMarca', 
        id:id, 
        nombre:nombre, 
        logo:logo
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        if(data == "ERROR"){
            jAlert('No se ha podido guardar la marca correctamente', 'ERROR');
        } else if(data == 'OK'){
            jAlert('Se ha guardado la marca correctamente', 'ÉXITO');
        }
    });
}
/***********************************************************************************************************************
     ** function borrarMarca(id_marca)                                                                                  **
     ***********************************************************************************************************************/
function borrarMarca(id_marca){
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'borrarMarca', 
        id_marca:id_marca
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        if(data == "ERROR"){
            jAlert('No se ha podido borrar la marca correctamente', 'ERROR');
        } else if(data == 'OK'){
            jAlert('Se ha borrado la marca correctamente', 'ÉXITO');
            getMarcasAEditar();
        }
    });
}
/***********************************************************************************************************************
     ** function asignarMarcaAProducto(id_producto, id_marca)                                                                                  **
     ***********************************************************************************************************************/
function asignarMarcaAProducto(id_producto, id_marca){
	
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'asignarMarcaAProducto', 
        id_producto:id_producto, 
        id_marca:id_marca
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        if(data == "ERROR"){
            jAlert('No se ha asignado la marca al producto correctamente', 'ERROR');
        }
    });
}

/***********************************************************************************************************************
     ** function borrarMarcaDeProducto(id_producto)                                                                                  **
     ***********************************************************************************************************************/
function borrarMarcaDeProducto(id_producto){
	
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'borrarMarcaDeProducto', 
        id_producto:id_producto
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
    });
}

/*********************************************************************************************************
function getProductosAEditar(categoria, marca, order, prod_per_page, page)
     **********************************************************************************************************/
function getProductosAEditar(categoria, marca, order, prod_per_page, page){
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'getProductosAEditar', 
        categoria:categoria, 
        marca:marca,
        order:order,
        prod_per_page:prod_per_page,
        page:page
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        jQuery('#gestor_table').html(data);
        jQuery("select[multiple]").asmSelect({
            addItemTarget: 'top',
            removeLabel:'[x]'
        });
    });
}

/*********************************************************************************************************
function getPaginacion(categoria, marca, prod_per_page, page)
     **********************************************************************************************************/
function getPaginacion(categoria, marca, prod_per_page, page){
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'getPaginacion',
        categoria:categoria,
        marca:marca, 
        prod_per_page:prod_per_page,
        page:page
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        aux = data.split('§§');
        var start_item_jcarousel = aux[0];
        if(start_item_jcarousel > 8){
            start_item_jcarousel -= 8;
        } else{
            start_item_jcarousel = 0;
        }
        jQuery('.paginas').html(aux[1]);
        jQuery(".paginas").jCarouselLite({
            btnNext: ".next",
            btnPrev: ".prev",
            circular: false,
            visible: 24,
            start:start_item_jcarousel
        });
    });
}

/*********************************************************************************************************
function getCategoriasAEditar()
     **********************************************************************************************************/
function getCategoriasAEditar(){
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'getCategoriasAEditar'
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        jQuery('#gestor_table').html(data);
    });
}
/*********************************************************************************************************
function getMarcasAEditar()
     **********************************************************************************************************/
function getMarcasAEditar(){
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'getMarcasAEditar'
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        jQuery('#gestor_table').html(data);
    });
}
/***********************************************************************************************************************
     ** function reordenar(campo)                                                                                  **
     ***********************************************************************************************************************/
function reordenar(campo, categoria, marca, prod_per_page, pagina){
    var start_item_jcarousel = pagina;
    if(start_item_jcarousel > 8){
        start_item_jcarousel -= 8;
    } else{
        start_item_jcarousel = 0;
    }
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'reordenar', 
        campo:campo, 
        categoria:categoria, 
        marca:marca,
        prod_per_page:prod_per_page,
        pagina:pagina
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        aux = data.split('§§');
        jQuery('.paginas').html(aux[0]);
        jQuery('#gestor_table').html(aux[1]);
        jQuery("select[multiple]").asmSelect({
            addItemTarget: 'top',
            removeLabel:'[x]'
        });
        jQuery(".paginas").jCarouselLite({
            btnNext: ".next",
            btnPrev: ".prev",
            circular: false,
            visible: 24,
            start: start_item_jcarousel
        });
    });
}
/***********************************************************************************************************************
     ** function filtrarProductosPorCategoriaYMarca()                                      **
     ***********************************************************************************************************************/
function filtrarProductosPorCategoriaYMarca(){
	
    selectedCategoryIndex = document.getElementById("filtro_categoria").selectedIndex;
    selectedCategoryValue = document.getElementById("filtro_categoria").options[selectedCategoryIndex].value;
    selectedMarcaIndex = document.getElementById("filtro_marca").selectedIndex;
    selectedMarcaValue = document.getElementById("filtro_marca").options[selectedMarcaIndex].value;
		
    var var_categoria = '';
    if(selectedCategoryValue != ''){
        var_categoria = '&categoria='+selectedCategoryValue;
    }
    var var_marca = '';
    if(selectedMarcaValue != ''){
        var_marca = '&marca='+selectedMarcaValue;
    }
	
    window.location.href = 'index.php?sec=productos'+var_categoria+var_marca;
}
/***********************************************************************************************************************
     ** function filtrarProductosPorCategoriaYMarcaGestor()                                      **
     ***********************************************************************************************************************/
function filtrarProductosPorCategoriaYMarcaGestor(){
	
    selectedCategoryIndex = document.getElementById("filtro_categoria").selectedIndex;
    selectedCategoryValue = document.getElementById("filtro_categoria").options[selectedCategoryIndex].value;
    selectedMarcaIndex = document.getElementById("filtro_marca").selectedIndex;
    selectedMarcaValue = document.getElementById("filtro_marca").options[selectedMarcaIndex].value;
		
    var var_categoria = '';
    if(selectedCategoryValue != ''){
        var_categoria = '&categoria='+selectedCategoryValue;
    }
    var var_marca = '';
    if(selectedMarcaValue != ''){
        var_marca = '&marca='+selectedMarcaValue;
    }
	
    window.location.href = 'index.php?sec=gestor&subsec=verproductos'+var_categoria+var_marca;
}
/***********************************************************************************************************************
     ** function cleanImages(root, folder)                                                                                  **
     ***********************************************************************************************************************/
function cleanImages(root, folder){
    jQuery.post('gestor/GestorProductos.php', {
        funcion:'cleanImages', 
        root:root,
        folder:folder
    }, function(data){
        data = data.replace(/\s*[\r\n][\r\n \t]*/g, ""); 
        if(data == "ERROR"){
            jAlert('No se han podido limpiar las imágenes correctamente', 'ERROR');
        } else if(data == 'OK'){
            jAlert('Se han limpiado las imágenes correctamente', 'ÉXITO');
        }
    });
}

