/**
 * CartoVisor.js
 * Instituto Geográfico Nacional 
 * http://www.ign.es/ign/es/IGN/home.jsp
 */
function CartoVisor(element_id,longitud_p,latitud_p,zoom_p) 
{
    this.SEARCH_TAB = 0;
    this.PATH_TAB = 1;
    this.SETTINGS_TAB = 2;
    
    this.cv_paused = false;
    this.carto_element = null;
    this.component_id = null;
    this.urlid = null;
    this.urlbase = "";
    this.longitud = -5.6935;
    this.latitud = 40.5308;
    this.zoom = 1;
    this.loadedmodules = null;
    this.onloading_any = null;

    this.getURLfromElement = function getURLfromElement(element)
    {
        var scripts = element.getElementsByTagName("script");
        for (var i=0;i<scripts.length;i++) 
        {
            var src = scripts[i].getAttribute("src");
            if (src)
                if ((src.indexOf("CartoVisor.js") != -1) && (src.indexOf("CartoVisor.jsp") == -1))
                    return src.replace("CartoVisor.js","");
        }
	return "";
    }
    
    this.getURL = function getURL()
    {
        var head = document.getElementsByTagName("head")[0];
	var url = this.getURLfromElement(head);
	if (url == "")
            url = this.getURLfromElement(document.body);
	return url;
    }
 
    this.isJSLibraryInstalled = function isJSLibraryInstalled(library)
    {
        var addNode=true;
        var nodes=document.getElementsByTagName('script');
        for(var i=0;i<nodes.length;++i)
                if (this.getOnlyName(nodes.item(i).src) == this.getOnlyName(file))
                        return true;
        return false;
    }
    
    this.getOnlyName = function getOnlyName(file)
    {
        var parts = file.split('/');
        return parts[parts.length-1];    
    }
    
    this.addJSFile = function addJSFile(file)
    {
        var retval = true;
        var addNode=true;
        var nodes=document.getElementsByTagName('script');
        for(var i=0;i<nodes.length;++i)
        {
                if (this.getOnlyName(nodes.item(i).src) == this.getOnlyName(file))
                {
                        addNode=false;
                        break;
                }
        }                           
        if (addNode)
        {
            document.write("<script src='" + file + "' type='text/javascript'></script>");
            nodes=document.getElementsByTagName('script');
            for(i=0;i<nodes.length;++i)
                    if (this.getOnlyName(nodes.item(i).src) == this.getOnlyName(file))
                    {
                            if (nodes.item(i).parentNode.tagName.toLowerCase() == 'head')
                                retval = false;
                            break;
                    }
        }
        return retval;
    }
    
    this.addCSSFile = function addCSSFile(file)
    {
        var addNode=true;
        var nodes=document.getElementsByTagName('link');
        for(var i=0;i<nodes.length;++i)
                if (nodes.item(i).href.toLowerCase() == file)
                        addNode=false;
        if(addNode)
        {	
            var cssNode=document.createElement('link');
            cssNode.setAttribute('rel','stylesheet');
            cssNode.setAttribute('type','text/css');
            cssNode.setAttribute('href',file);
            document.getElementsByTagName('head')[0].appendChild(cssNode);
        }
    }
    
    this.addBodyJSFile = function addBodyJSFile(file)
    {
        var addNode=true;
        var nodes=document.getElementsByTagName('script');
        for(var i=0;i<nodes.length;++i)
        {
                if (this.getOnlyName(nodes.item(i).src) == this.getOnlyName(file))
                {
                        addNode=false;
                        break;
                }
        }
        if(addNode)
        {	
            var newScript = document.createElement('script');
            newScript.type = 'text/javascript';
            newScript.src = file;
            document.body.appendChild(newScript);
        }
    }    
    
    this.alertCallMessage = function alertCallMessage()
    {
        alert("Cartovisor Script Error Message:\n\n" + 
               "The script that creates the CartoVisor object must be inside the <BODY> tag!!\n" +
                "Example:\n\n" +             
                "<html>\n" + 
                "\t<head>\n" + 
                "\t\t<script src='http://www....../CartoVisor.js' type='text/javascript'></script>\n" + 
                "\t</head>\n" + 
                "\t<body>\n" + 
                "\t\t<div id='mapa'></div>\n" + 
                "\t\t<script type='text/javascript'>\n" + 
                "\t\t\tvar map = new CartoVisor('mapa',-3.71,40.41,2);\n" + 
                "\t\t</script>\n" + 
                "\t</body>\n" + 
                "</html>\n");
    }
    
    this.includeFiles = function includeFiles(loaded)
    {
       
        if (loaded)
        {
            this.addBodyJSFile(this.urlbase + "CartoVisor.jsp?Element=" + this.getUniqueElID() + 
                                                                           "&pagelet_id=" + this.getPageletId() +
                                                                           "&lon=" + this.longitud +
                                                                           "&lat=" + this.latitud +
                                                                           "&zoom=" + this.zoom);
        }
        else
        {
            this.addCSSFile(this.urlbase + "css/screen.css");
            this.addCSSFile(this.urlbase + "css/cv-ol-controls.css");
            this.addCSSFile(this.urlbase + "css/cartovisor.css");	           
            if (!this.addJSFile(this.urlbase + "js/wp_cookie/wp_Cookie.js"))
            {
                this.alertCallMessage();
                return;
            }
            this.addJSFile(this.urlbase + "js/openlayers/OpenLayers.js");
            this.addJSFile(this.urlbase + "js/addopenlayers/ScaleBar.js");
            this.addJSFile(this.urlbase + "js/addopenlayers/CartovisorText.js");   
            this.addJSFile(this.urlbase + "js/addopenlayers/CartovisorMousePosition.js");   
            this.addJSFile(this.urlbase + "js/ajast/ox.ajast.js"); 
            this.addJSFile(this.urlbase + "js/cartovisor/cartovisor-utils.js");       
            this.addJSFile(this.urlbase + "js/cartovisor/cv-dialog.js");    
            this.addJSFile(this.urlbase + "js/cartovisor/cv-search.js"); 
            this.addJSFile(this.urlbase + "js/cartovisor/vc-mailing-address-suggestions.js");    
            this.addJSFile(this.urlbase + "js/cartovisor/vc-mailing-address-control.js");    
            this.addJSFile(this.urlbase + "js/cartovisor/vc-rule-guide.js");
            this.addJSFile(this.urlbase + "js/levenshtein/levenshtein.js");
            this.addJSFile(this.urlbase + "js/wz_tooltip/wz_tooltip.js");
            this.addJSFile(this.urlbase + "CartoVisor.jsp?Element=" + this.getUniqueElID() + 
                                                                           "&pagelet_id=" + this.getPageletId() +
                                                                           "&lon=" + this.longitud +
                                                                           "&lat=" + this.latitud +
                                                                           "&zoom=" + this.zoom);
        }        
    }
    
    this.setActiveTab = function setActiveTab(tab)
    {
        try
        {
            eval(this.component_id +"_setActiveTab(" + tab + ");");
        }
        catch(e)
        {
            eval(this.component_id +"_command_buffer +=\""+  this.component_id +"_setActiveTab(" + tab + ");\"");            
        }
    }
    
    this.hideTab = function hideTab(tab)
    {
        try
        {
            eval(this.component_id +"_setDisplayTab(" + tab + ",false);");
        }
        catch(e)
        {
            eval(this.component_id +"_command_buffer +=\""+  this.component_id +"_setDisplayTab(" + tab + ",false);\"");
        }
    }
    
    this.activateLayerSwitcherControl = function activateLayerSwitcherControl(value)
    {
        try
        {
            eval(this.component_id +"_activateLayerSwitcherControl(" + value + ");");
        }
        catch(e)
        {
            eval(this.component_id +"_command_buffer +=\""+  this.component_id +"_activateLayerSwitcherControl(" + value + ");\"");
        }
    }    
    
    this.setSizeOption = function setSizeOption(option)
    {
        try
        {
            eval(this.component_id +"_setSizeOption(" + option + ");");
        }
        catch(e)
        {   
            eval(this.component_id +"_size_option_buffer = " + option + ";");
        }
    }
    
    this.showTab = function showTab(tab)
    {
        try
        {
            eval(this.component_id +"_setDisplayTab(" + tab + ",true);");
        }
        catch(e)
        {
            eval(this.component_id +"_command_buffer +=\""+  this.component_id +"_setDisplayTab(" + tab + ",true);\"");
        }
    }
    
    this.setOnLoadFunction = function setOnLoadFunction(onloadfunction)
    {        
         eval(this.component_id +"_onload_function = " + onloadfunction + ";");
    }
    
    this.setCustomHelpFunction = function setCustomHelpFunction(helpfunction)
    {        
         eval(this.component_id +"_customHelpFunction = " + helpfunction + ";");
    }    
    
    this.setActiveLanguage = function setActiveLanguage(language)
    {
        try
        {
            eval(this.component_id +"_setActiveLanguage('" + language + "');");
        }
        catch(e)
        {
            eval(this.component_id +"_command_buffer +=\""+  this.component_id +"_setActiveLanguage('" + language + "');\"");
        }
    }
    
    this.getOpenLayersMap = function getOpenLayersMap()
    {
        try
        {
            var openlayersmap=null;
            eval("openlayersmap = " + this.component_id +"_getOpenLayersMap();");
            return openlayersmap;
        }
        catch(e)
        {
            alert("The component has not loaded yet.\nYou must use : CartoVisor.setOnLoadFunction");
            return null;
        }      
    }
    
    this.doSearch = function doSearch(value)
    {
        try
        {
            eval(this.component_id +"_doAPISearch('" + value + "');");
        }
        catch(e)
        {
            eval(this.component_id +"_command_buffer +=\""+  this.component_id +"_doAPISearch('" + value + "');\"");
        }    
    }
    
    this.doComputePath = function doComputePath(value1,value2)
    {
        try
        {
            eval(this.component_id +"_doAPIComputePath('" + value1 + "','" + value2 + "');");
        }
        catch(e)
        {
            eval(this.component_id +"_command_buffer +=\""+  this.component_id +"_doAPIComputePath('" + value1 + "','" + value2 + "');\"");
        }    
    }
    
    this.setZoom = function setZoom(lon,lat,zoomvalue)
    {
        var flon = parseFloat(lon);
        var flat = parseFloat(lat);
        var fzoom = parseInt(zoomvalue);
        fzoom = fzoom < 0 ? 0 : fzoom;
        fzoom = fzoom > 14 ? 14 : fzoom;
        try
        {
            eval(this.component_id +"_setAPICenter(" + flon + "," + flat + "," + fzoom + ");");
        }
        catch(e)
        {
            eval(this.component_id +"_command_buffer +=\""+  this.component_id +"_setAPICenter(" + flon + "," + flat + "," + fzoom + ");\"");
        }    
    }
        
    this.setToolbarButtons = function setToolbarButtons(help,save,load)
    {
        try
        {
            eval(this.component_id +"_reloadToolbar(" + help + "," + save + "," + load + ");");
        }
        catch(e)
        {
            eval(this.component_id +"_command_buffer +=\""+  this.component_id +"_reloadToolbar(" + help + "," + save + "," + load + ");\"");
        }    
    } 
    
    this.getUrlId = function getUrlId()    
    {
        var num = 0;
        var url = document.URL.toString();
        for (var i=0;i<url.length;i++)
            num += url.charCodeAt(i);
        return num.toString();
    }
        
    this.getUniqueElID = function getUniqueElID()    
    {
        return this.carto_element.getAttribute("id");
    }  
    
    this.getPageletId = function getPageletId()    
    {
        return this.getUniqueElID() + "_"+ this.urlid;
    }    
    
    this.getComponentId = function getComponentId()    
    {
        var cid =  "vc_" + this.getPageletId();
        return cid;
    }
        
    this.continueLoading = function continueLoading()    
    {
        document.body.setAttribute("onloading_any",true);
        this.cv_paused = false;        
        this.urlbase = this.getURL();
        this.loadedmodules = document.body.getAttribute("loadedmodules");
        if (!this.loadedmodules)
            document.body.setAttribute("loadedmodules",true);
        this.includeFiles(this.loadedmodules);
    }
            
    if (element_id == undefined)
    {
        alert("CartoVisor:\nRequired parameter 'element id'");
        return;
    }
    
    if (element_id == undefined)
    {
        alert("CartoVisor:\nRequired parameter 'element id'");
        return;
    }
    
    if (longitud_p != undefined)
        this.longitud = parseFloat(longitud_p);
    
    if (latitud_p != undefined)
        this.latitud = parseFloat(latitud_p);
    
    if (zoom_p != undefined)
    {
        this.zoom = parseInt(zoom_p); 
        this.zoom = this.zoom < 0 ? 0 : this.zoom;
        this.zoom = this.zoom > 14 ? 14 : this.zoom;
    }
    
    this.carto_element = document.getElementById(element_id);
    if (!this.carto_element)
    {
        alert("Cannot find '" + element_id + "' element!");
        return;
    }
    
    this.urlid = this.getUrlId();
    this.component_id = this.getComponentId();
    
    eval(this.component_id +"_command_buffer=''");
    eval(this.component_id +"_size_option_buffer = null;");
    eval(this.component_id +"_onload_function = null;");
    
    if (!document.body['cv_document_maps'])
        document.body['cv_document_maps'] = [];
    document.body['cv_document_maps'].push(this);
         
    // Vemos si en esos instantes hay otro cargandose.
    this.onloading_any = document.body.getAttribute("onloading_any");
    if (!this.onloading_any)
        this.continueLoading();
    else
        this.cv_paused = true; 
}