var isIE;
var current = -1;
var targetId = -1;
var size = 40;

//var urlServ = "http://localhost:8082/circulomobiliario-webapp/";

var urlServ = "http://cateweb.aidima.es/circulomobiliario-webapp2/";

var navigation = new Navigation();

function testBrowser() {
    /* no funciona con ie7 */
    /*if (window.XMLHttpRequest)
        isIE = false;
    else
        isIE = true;*/
    var navegador = navigator.appName
    if (navegador == "Microsoft Internet Explorer") 
        isIE = true
    else
        isIE = false

}

function IsNumeric(sText) {
    var ValidChars = "0123456789."; 
    var IsNumber=true ;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) 
    { 
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) 
            IsNumber = false;
    }
    return IsNumber;
}

function normalize(cadena) {
    var aux = cadena.toLowerCase();

    var a = /[á|à|â|ä]/g;
    var e = /[é|è|ê|ë]/g;
    var i = /[í|ì|î|ï]/g;
    var o = /[ó|ò|ô|ö]/g;
    var u = /[ú|ù|û|ü]/g;

    aux = aux.replace(a, "a");
    aux = aux.replace(e, "e");
    aux = aux.replace(i, "i");
    aux = aux.replace(o, "o");
    aux = aux.replace(u, "u");

    return aux;
}


function normalize_icon(cadena ) {

    var aux = cadena.toLowerCase();

    var a = /[á|à|â|ä]/g;
    var e = /[é|è|ê|ë]/g;
    var i = /[í|ì|î|ï]/g;
    var o = /[ó|ò|ô|ö]/g;
    var u = /[ú|ù|û|ü]/g;

    aux = aux.replace(a, "a");
    aux = aux.replace(e, "e");
    aux = aux.replace(i, "i");
    aux = aux.replace(o, "o");
    aux = aux.replace(u, "u");

    var aux_trim = "";
    for (j=0;j<aux.length; j++) {
        var c = aux.charAt(j);
        if (c != " ") aux_trim += c ;
    }

    return aux_trim;
}


function go_back(seccion) {
    //history.back();

    switch (seccion) {
        case "PRODUCTOS":    //desde COATING2D
            navigate("espacios", "FROM_COATING2D", false);
            break ;
        case "COATING2D":    //desde PRESUPUESTO
            navigate("coating2D", "FROM_PRESUPUESTO", false);
            break;
        default:
            break;
    }
}

function loadDialog(id, params ) {

    var url = "DIALOG/" + id + ".html";
    new Ajax.Request(url, {
        method: 'post',
        onSuccess: function(transport) {
            prLoadDialog(transport.responseText, id, params);
        },
        onFailure: function(transport) {
            alert('Error LOADDIALOG');
            alert("\n\n" + transport.responseText);
        }
    });
}

function prLoadDialog(content, id, params){
    document.getElementById("dialog_javascript").innerHTML=content;

    switch (id) {
        case "dialog_coating2D_wait":
            new Dialog.ModalBox("dialog_javascript");
            $("dialog_javascript").show();
            break;
        case "dialog_sending_wait":
            new Dialog.ModalBox("dialog_javascript");
            $("dialog_javascript").show() ;
            break;
        case "dialog_coating2D_zoom_l1":
            new Dialog.Box("dialog_javascript");
            $("dialog_javascript").show();
            prZoomImageRev();
            break;
        case "dialog_coating2D_zoom_l2":
            new Dialog.Box("dialog_javascript");
            $("dialog_javascript").show();
            prZoomImageRev();
            break;
        case "dialog_coating2D_zoom_l3":
            new Dialog.Box("dialog_javascript");
            $("dialog_javascript").show();
            prZoomImageRev();
            break;
        case "dialog_coating2D_zoom_l4":
            new Dialog.Box("dialog_javascript");
            $("dialog_javascript").show();
            prZoomImageRev();
            break;
        case "dialog_texture":
            new Dialog.Box("dialog_javascript");
            $("dialog_javascript").show();
            mostrarTextura(params[0]);
            break;
        case "dialog_user":
            new Dialog.Box("dialog_user");
            $("dialog_javascript").show();
            //prZoomImageRev();
            break;
        case "dialog_referencias":
            new Dialog.Box("dialog_javascript");
            $("dialog_javascript").show();
            mostrarReferencias();
            break;
        case "dialog_coating2D_images":
            new Dialog.Box("dialog_javascript");
            $("dialog_javascript").show();
            loadImagenesRevestiblesProducto(params[0],params[1]);
            break;
        case "dialog_cart":
            new Dialog.Box("dialog_javascript");
            $("dialog_javascript").show();
            load_cart();
            break;
        default:
            break;
    }

}

function hideDialog() {
    $("dialog_javascript").hide();
}

function getY_Element(oElement)
{
    var iReturnValue = 0;
    while( oElement != null ) {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

function getX_Element(oElement)
{
    var iReturnValue = 0;
    while( oElement != null ) {
        iReturnValue += oElement.offsetLeft;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

function scrollDiv(/*idDiv, orientation, direction, increment*/) {
    /*
    if (orientation == "horizontal")
    {
        if (direction == "left")
            document.getElementById(idDiv).scrollLeft -= increment
        else if (direction == "right")
            document.getElementById(idDiv).scrollLeft += increment
    }
    else if (orientation == "vertical")
    {
        if (direction == "up") 
            document.getElementById(idDiv).scrollTop -= increment;
        else if (direction == "down")
            document.getElementById(idDiv).scrollTop += increment;
    }
    */

    //Position.prepare();
    //container_y = Position.cumulativeOffset($(container))[1];
    //element_y = Position.cumulativeOffset($(element))[1];
    //new Effect.Scroll(container, {x:0, y:(element_y-container_y)});

    new Effect.Move($('prueba_scroll'),{x: 0, y: 100, duration: 1, mode:'relative'})
    //Event.stop(event);

    //var eff = new Effect.ScrollTo("div_bottom");

    var a = 0;

}

function generateCoatingLinks() {
    var links = "";
    for (i=0; i<products.productos.length; i++)
    {
        for (j=0; j<products.productos[i].imagenes.length; j++)
        {
            if (products.productos[i].imagenes[j].revestible == true)
            {
                var url = urlServ + "vestir.jsp" +
                            "?usuario=" + user.username +
                            "&codigo=" + user.codigo +
                            "&nombre=" + products.productos[i].nombre +
                            "&fabricante=" + products.productos[i].fabricante +
                            "&ficheroImagen=" + products.productos[i].imagenes[j].fichero;
               links += url + "\n"; 
            }
        }
    }
    alert(links);
}

function clearDiv(opcion) {
    var scrollElementName = "";
    var divElementName = "";
    switch (opcion) {
        case "contenido":
            scrollElementName = "scroll_contenido";
            divElementName = "contenido";
            break;
        case "body_derecha_aditional":
            scrollElementName = "scroll_body_derecha_aditional";
            divElementName = "body_derecha_aditional";
            break;
        case "contenedor_fichas":
            scrollElementName = "scroll_fichas";
            divElementName = "contenedor_fichas";
            break;
        case "pagination":
            scrollElementName = "scroll_pagination";
            divElementName = "pagination";
            break;
            /* coating 2D */
        case "divCoatingAppletPagination":
            scrollElementName = "divScrollCoatingAppletPagination";
            divElementName = "divCoatingAppletPagination";
            break;
        case "divCoatingAppletTextures":
            scrollElementName = "divScrollCoatingAppletTextures";
            divElementName = "divCoatingAppletTextures";
            break;
        case "divCoatingAppletCategories":
            scrollElementName = "divScrollCoatingAppletCategories";
            divElementName = "divCoatingAppletCategories";
            break;
        case "divCoatingAppletImageParts":
            scrollElementName = "divScrollCoatingAppletImageParts";
            divElementName = "divCoatingAppletImageParts";
            break;
        case "divProductBrowser":
            scrollElementName = "divScrollProductBrowser";
            divElementName = "divProductBrowser";
            break;
        case "divProveedores":
            scrollElementName = "divScrollProveedores";
            divElementName = "divProveedores";
            break;
        case "contenedor_config":
            scrollElementName = "div_mismuebles_scroll_config";
            divElementName = "div_mismuebles_contenedor_config";
            break;
        case "dialog_coating2D_images":
            scrollElementName = "dialog_coating2D_images_scroll"  ;
            divElementName = "dialog_coating2D_images" ;
            break;
        case "contenedor_config_cart":
            scrollElementName = "div1_cart";
            divElementName = "divScrollConfigurations";
            break;

        default:
            break;
    }

    var scrollElement = document.createElement("div")
    scrollElement.setAttribute('id', scrollElementName)

    var divElement = document.getElementById(divElementName);
    divElement.replaceChild(scrollElement, document.getElementById(scrollElementName));
}

function redirect(url) {
    window.location.href = url;
}

//function llamarasincrono(url, id_contenedor){
//    var pagina_requerida = false
//    if (window.XMLHttpRequest) {// Si es Mozilla, Safari etc
//        pagina_requerida = new XMLHttpRequest()
//    }
//    else if (window.ActiveXObject){ // pero si es IE
//    try {
//        pagina_requerida = new ActiveXObject("Msxml2.XMLHTTP")
//    }
//    catch (e) { // en caso que sea una versión antigua
//        try {
//            pagina_requerida = new ActiveXObject("Microsoft.XMLHTTP")
//        }
//        catch (e){}
//        }
//        }
//    else return false
//    pagina_requerida.onreadystatechange=function(){ // función de respuesta
//        cargarpagina(pagina_requerida, id_contenedor)
//    }
//    pagina_requerida.open('GET', url, true) // asignamos los métodos open y send
//    pagina_requerida.send(null)
//}

function loadHtml(page, container, section, params) {

    var url = "HTML/" + page;
    new Ajax.Request(url, {
        method: 'post',
        onSuccess: function(transport) {
            prLoadHtml(transport.responseText, container, section, params);
        },
        onFailure: function(transport) {
            alert('Error LOADHTML');
            alert("\n\n" + transport.responseText);
        }
    }); 
}

function prLoadHtml(content, container, section, params)  {

    var divElementContainer = document.getElementById(container);

    divElementContainer.innerHTML = " ";
    divElementContainer.style.display = "none";
    divElementContainer.innerHTML = content;
    
    $(container).appear({ duration: 1.5 }) ;
    
    switch (section) {
        case "inicio":
            actualizar_instrucciones("INICIO") ;
            if (user.username == "circulo")
                navigate("login_component", null, false);
            break;
        case "familias":
            document.getElementById("IMG_step_select_product").src = "IMG/step_select_product_on.png";
            document.getElementById("IMG_step_config_product").src = "IMG/step_config_product.png";
            document.getElementById("IMG_step_solicitar").src = "IMG/step_solicitar.png";
            document.getElementById("IMG_bodybar").src = "IMG/bodybar_product_family.png";
            actualizar_instrucciones("FAMILIA");
            mostrarFamilias();
            break;
        case "espacios":
            document.getElementById("IMG_step_select_product").src = "IMG/step_select_product_on.png";
            document.getElementById("IMG_step_config_product").src = "IMG/step_config_product.png";
            document.getElementById("IMG_step_solicitar").src = "IMG/step_solicitar.png";
            document.getElementById("IMG_bodybar").src = "IMG/bodybar_space_config.png";
            actualizar_instrucciones("ESPACIO");
            if (params == null)
                generarEspacios_Estilo();
            else
            {
                if (params == "FROM_COATING2D")
                    loadPagination("PRODUCTO", selectedNElem);
            }
//            mostrarEspacios();
            break;
        case "coating2D":
            document.getElementById("IMG_step_select_product").src = "IMG/step_select_product.png";
            document.getElementById("IMG_step_config_product").src = "IMG/step_config_product_on.png";
            document.getElementById("IMG_step_solicitar").src = "IMG/step_solicitar.png";
            document.getElementById("IMG_bodybar").src = "IMG/bodybar_product_config.png";
            actualizar_instrucciones("COATING2D");
            loadProduct();
            break;
        case "coating2D_parts_presupuesto":
            actualizar_instrucciones("PRESUPUESTO");
            getConfigurationTree(section) ;
            break;
        case "coating2D_parts":
            getConfigurationTree(section);
            break;
        case "login_component":
            break;
        case "acceder":
            actualizar_instrucciones("ACCEDER");
            break;
        case "mismuebles":
            actualizar_instrucciones("MISMUEBLES") ;
            //cargar_configuraciones();
            loadPagination_config() ;
            break;
        case "datos":
            actualizar_instrucciones("USUARIO");
            document.getElementById("IMG_bodybar").src = "IMG/bodybar_user_datos.png";
            cargar_datos();
            break;
        case "presupuesto":
            actualizar_instrucciones("PRESUPUESTO");
            cargar_presupuesto();  
            break;
        default:
            break;
    }
}

function getParams() {
    var idx = document.URL.indexOf('?');
    var tempParams = new Object();
    if (idx != -1) {
        var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
        for (var i=0; i<pairs.length; i++) {
            nameVal = pairs[i].split('=');
            tempParams[nameVal[0]] = nameVal[1];
        }
    }
    return tempParams;
}

function navigate(section, params, from_navigation) {

    if ((section != "login_component") && (section != "coating2D_parts")
        && (section != "coating2D") && from_navigation == false) {
        var pantalla = new Pantalla();
        pantalla.nombre = section;
        pantalla.params = params;
        register_navigation(pantalla);
    }

    switch (section) {
        case "inicio":
            clearDiv("body_derecha_aditional");
            loadHtml("inicio.html","central",section,params);
            /*loadHtml("inicio.html","body_centro",section,params) ;*/
            break;
        case "familias":
            clearDiv("body_derecha_aditional");
            loadHtml("productos.html","central",section,params);
            break;
        case "espacios":
            clearDiv("body_derecha_aditional");
            loadHtml("productos.html","central",section,params) ;
            break;
        case "coating2D":
            loadHtml("coating2D.html","central",section,params);
            break;
        case "coating2D_parts":
            clearDiv("body_derecha_aditional");
            loadHtml("coating2D_parts.html","scroll_body_derecha_aditional",section,params);
            break;
        case "login_component":
            clearDiv("body_derecha_aditional");
            loadHtml("login_component.html","scroll_body_derecha_aditional",section,params);
            break;
        case "acceder":
            clearDiv("body_derecha_aditional");
            loadHtml("user.html","central",section,params);
            break;
        case "datos":
            clearDiv("body_derecha_aditional");
            loadHtml("datos.html","central",section,params) ;
            break;  
        case "presupuesto":
            clearDiv("body_derecha_aditional");
            loadHtml("presupuesto.html","central",section,params);
            break;
        case "mismuebles":
            clearDiv("body_derecha_aditional");
            loadHtml("mismuebles.html","central",section,params );
            break;
        case "mostrar_estilos":
//            clearDiv("body_derecha_aditional");
//            loadHtml("mismuebles.html","central",section,params );
            mostrarEstilos(params);
            break;
        case "mostrar_productos":
//            clearDiv("body_derecha_aditional");
//            loadHtml("mismuebles.html","central",section,params );
            mostrarProductos(params);
            break;
        case "load_producto":
            clearDiv("body_derecha_aditional");
            loadHtml("mismuebles.html","central",section,params ) ;
            loadProducto(params);
            break;

        default:
            break ;
    }
}

function eraseNull(object) {

    if (object == null)
        return ("");
    if (object == "null")
        return("");
    else
        return (object)
}

function search() {

    alert("No implementada");
}


function actualizar_instrucciones(paso) {
    
    var texto = "";
    document.getElementById("body_derecha_instrucciones").style.visibility="visible";

    switch (paso) {
        case "INICIO":
            texto = "El contenido de esta columna le ayuda a navegar más fácilmente por los contenidos del sitio. " +
                "Si tiene alguna duda lea las instrucciones para obtener una pequeña guía de navegación.";
            break;
        case "FAMILIA":
            texto = "Seleccione la familia de productos sobre la que desea trabajar.";
            break;
        case "ESPACIO":
            texto = "Seleccione el tipo de espacio sobre el que desea trabajar.";
            break;
        case "PRODUCTO":
            texto = "Seleccione el producto que deseae configurar.";
            break;
        case "COATING2D":
            texto = "1. Pinche sobre la tela o acabado que desea aplicar.<br>"+
                    "2. Pinche sobre la parte del producto donde desea aplicarlo.";
            break;
        case "PRESUPUESTO":
            texto = "Seleccione la provincia más cercana a donde resida de aquellas donde el modelo está disponible "+
                "y seleccione las tiendas a las que desea solicitar presupuesto. Puede introducir observaciones adicionales.";
            break ;
        case "MISMUEBLES":
            texto = "Desde 'Mis muebles' puede visualizar los muebles y espacios que haya configurado. " +
                "Puede navegar por el listado de elementos, editar sus configuraciones y solicitar presupuestos.";
            break;
        case "USUARIO":
            texto = "Desde aquí puede editar sus datos de usuario y de contacto. " +
                "También puede solicitar la baja en el sistema. Recuerde que si solicita la baja " +
                "se borrarán todos sus datos y configuraciones guardadas. ";
        case "ACCEDER":
            texto = "Si es usuario registrado utilice el formulario de la izquierda. Si aún no es usuario registrado " +
                "solicite el alta a través del formulario de la derecha.";
            break;
        default:
            texto = "";
            break;
    }
    document.getElementById("instrucciones").innerHTML = texto;

    /***** ***/
}

function enableTopmenu (){

    var topmenu_boton_inicio = document.getElementById("topmenu_boton_inicio");
    Event.observe(topmenu_boton_inicio, 'click', function()  {
        navigate('inicio', null, false);
    }, false);

    var topmenu_boton_exclusivo = document.getElementById("topmenu_boton_exclusivo");
    Event.observe(topmenu_boton_exclusivo, 'click', function() {
        cargar_catalogo_exclusivo();
    }, false);

    var topmenu_boton_general = document.getElementById("topmenu_boton_general");
    topmenu_boton_general.className = "boton_disabled";
//    Event.observe(topmenu_boton_general, 'click', function() {
//        cargar_catalogo_general();
//    }, false);

    var topmenu_boton_mismuebles = document.getElementById("topmenu_boton_mismuebles");
    Event.observe(topmenu_boton_mismuebles, 'click', function()  {
        enter_mismuebles();

    }, false);

    var topmenu_boton_acceder = document.getElementById("topmenu_boton_acceder") ;
    if (user.username == "circulo")
    {
        topmenu_boton_acceder.innerHTML = "<img id=\"img_boton_acceder\" src=\"IMG/bar_acceder.png\" onclick=\"javascript:navigate('acceder', null, false)\" onmouseout=\"this.src='IMG/bar_acceder.png'\" onmouseover=\"this.src='IMG/bar_acceder_over.png'\" />";
        Event.observe(topmenu_boton_acceder, 'click', function() {
            navigate('acceder', null, false);
        }, false);        
    }
    else
    {
        topmenu_boton_acceder.innerHTML = "<img id=\"img_boton_acceder\" src=\"IMG/bar_datos.png\" onclick=\"javascript:navigate('datos', null, false)\" onmouseout=\"this.src='IMG/bar_datos.png'\" onmouseover=\"this.src='IMG/bar_datos_over.png'\"/>";
        Event.observe(topmenu_boton_acceder, 'click', function() {
            navigate('datos', null, false);
        }, false);
    }
    
}

function redirect() {
    var url = urlServ + "Redirect";

    new Ajax.Request(url, {
        method: 'post',
//        parameters: {
//            action: "obtenerTree",
//            escena: escena,
//            imagenBase: imagenBase,
//            fabricante: fabricante
//        },
        onSuccess: function(transport) {
            prRedirect(transport.responseXML, section);
        },
        onFailure: function(transport) {
            alert('Error REDIRECT');
            alert("\n\n" + transport.responseText);
        }
    });
}


function prRedirect(data) {
    
}

function register_navigation(pantalla) {

	if (navigation.pos == 3) {
		for(i=1; i<4; i++) {
			navigation.pantallas[i-1] = navigation.pantallas[i];
		}
	}
	else
		navigation.pos = navigation.pos +1;

    var new_pantalla = new Pantalla();
    new_pantalla = pantalla ;

	navigation.pantallas[navigation.pos] = new_pantalla;

	for (i=navigation.pos +1; i<4; i++) {
		navigation.pantallas[i] = null;
	}

    var a = 0;
}


function prev_navigation() {

	if (navigation.pos > 0) {
		navigation.pos = navigation.pos -1;
		navigate(navigation.pantallas[navigation.pos].nombre, navigation.pantallas[navigation.pos].params,true);
	}
}

function next_navigation() {

	if ( (navigation.pantallas[navigation.pos +1] != null) && ( navigation.pos < 3) )
	{
		navigation.pos = navigation.pos + 1 ;
		navigate(navigation.pantallas[navigation.pos].nombre, navigation.pantallas[navigation.pos].params,true);
	}

}

