var PARAM_openPopupOnCenter = false;
var PARAM_TElemControl_title = 'Control de visualización de capas';
var PARAM_TElemSelector_title = 'Control de centrado de elementos';

var MSIE  = document.all;
var oldNS = document.layers;
var newNS = !document.all && document.getElementById;
var opera = window.opera;

var now     = new Date();
var lMaps   = new Array();

var AnchorType = { T_VERTICAL_ANCHOR:1, T_HORIZONTAL_ANCHOR:2, T_DIAGONAL_ANCHOR:3 };
var T_VERTICAL_ANCHOR   = AnchorType.T_VERTICAL_ANCHOR;
var T_HORIZONTAL_ANCHOR = AnchorType.T_HORIZONTAL_ANCHOR;
var T_DIAGONAL_ANCHOR   = AnchorType.T_DIAGONAL_ANCHOR;


//actualiza todos los mapas
function updateData() {
    for( i = 0; i < lMaps.length; i++) lMaps[i].updateData();
}

function load(fileConf) {
    if (GBrowserIsCompatible()) {
        GDownloadUrl(fileConf+'?'+now.getTime(), function(data, responseCode) {
            var m  = GXml.parse(data).documentElement.getElementsByTagName("MAP");
            for (var i = 0; i < m.length; i++) lMaps.push(new TMap(m[i]));
            window.setInterval("updateData()",1000);
        });
    }
}

function setOpacity(t,x) {
    if (MSIE)
        t.filter = 'alpha(opacity = '+x+' )';
    else
        t.opacity  = x/100+'';
}

function setClassName(o, n) {
    if(MSIE){
        o.className = n;
    } else {
        o.setAttribute('class', n);
    }
}

//
// TControlBase da servicio a los controles anclados a la esquina superior-derecha del mapa
// (e.g.: control de visualización de capas-TElemControl y centrado de elementos-TElemSelector)
//

function TControlBase(printable, selectable) {  
    GControl.call(this, printable, selectable);
    this.l     = new Array();
    this._map  = false;
}

TControlBase.prototype = new GControl();
TControlBase.prototype.setMap             = function(m)  { this._map = m ; };
TControlBase.prototype.getDefaultPosition = function()   { return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,0)); }


TControlBase.prototype.show = function(){
    this.d.style.backgroundColor = 'white';
    this.d.style.border          = '1px black solid';
    this.d.firstChild.firstChild.setAttribute('src', 'dev/images/close.gif');
    for (var c = this.d.firstChild.nextSibling; c; c = c.nextSibling) c.style.visibility = 'visible';
    this.moveAnchoredControl();
}

TControlBase.prototype.hide = function() {
    this.d.style.backgroundColor = '';
    this.d.style.border          = '';
    this.d.firstChild.firstChild.setAttribute('src', 'dev/images/open.gif');
    for (var c = this.d.firstChild.nextSibling; c; c = c.nextSibling) c.style.visibility = 'hidden';
    this.moveAnchoredControl();
}

TControlBase.prototype.showMenu = function(id) {
    if ( !document.getElementById(id) ) return;
    if (this.d.lastChild.style.visibility == 'hidden') 
  	this.show();
    else
  	this.hide();
}
TControlBase.prototype.getChildrenAnchors = function() {
    var r = new Array();
    if (this.anchored) r.push(this);
    if (this.anchor) {
        for (var i = 0; i < this.anchor.length; i++) {
            y = this.anchor[i].C.getChildrenAnchors();
            for(var j=0; j < y.length; j++)
                r.push(y[j]);
        }
    }
    return r; 
}

TControlBase.prototype.addAnchoredControl = function(x,a) {
    var out = false;
  	  
    if (x.anchored) {
        alert('Control can not be anchored because it is anchored yet');
	out = true;
    }
    if (!this.anchorable || !x.anchorable)
    {
        alert('Elements are not anchorable)');
  	out = true;  
    } else if (this.getDefaultPosition().anchor!=x.getDefaultPosition().anchor) {
  	alert('Control to be anchored do not has the same anchor type');
  	out = true;
    }
  
    if (!a || ((a&T_DIAGONAL_ANCHOR)!=a)) {
  	alert('Anchor movement type incorrect');
        out = true;
    }
  
    var ft = this.anchored;
    var fx = x.anchored;
    x.anchored = this.anchored = true;
    var lanchors = x.getChildrenAnchors();
    if (lanchors.length)
    {
        //Check autoanchoring, reflexive, bijective o transitibly
        this.anchored = false;
        for (var i = 0; i < lanchors.length; i++)
  	    if (!lanchors[i].anchored) {
                alert('Control autoanchoring, direct or not, do not permitted');
                out = true; 
	    }
    }

    this.anchored = ft; // return to old value;
    x.anchored    = fx; // return to old value;
    if (out) return false;
    x.anchored    = true;
    if (!this.anchor)
  	this.anchor = new Array();

    this.anchor.push({C:x,A:a});
    this.moveAnchoredControl();
    return true;
}
TControlBase.prototype.moveAnchoredControl = function() {
    if (!this.anchor) return;
    for(var i = 0; i < this.anchor.length; i++) {
  	var e = this.anchor[i];
  	var d = this.d;
  	var b = d.style.border?1:0;
  	var f = d.firstChild;
  	var l = d.lastChild;
  	var o = e.C.getDefaultPosition();
        if (MSIE) {
            if (e.A&T_HORIZONTAL_ANCHOR) {
                if ((o.anchor==G_ANCHOR_TOP_RIGHT)||(o.anchor==G_BOTTOM_TOP_RIGHT)) {
                    ;
                } else {
                    ;
                }
            }
            if (e.A&T_VERTICAL_ANCHOR) {
 	  	if ((o.anchor==G_ANCHOR_TOP_RIGHT)||(o.anchor==G_BOTTOM_TOP_LEFT)) {
                    var c = l;while ( c.style.visibility == 'hidden' ) c = c.previousSibling;
                    var lbottom = c.getBoundingClientRect().bottom-this._map.getContainer().getBoundingClientRect().top;
                } else {
                    ;
                }
            }
        } else {
            if (e.A&T_HORIZONTAL_ANCHOR) {
                if ((o.anchor==G_ANCHOR_TOP_RIGHT)||(o.anchor==G_BOTTOM_TOP_RIGHT)) {
                    ;
                } else {
                    var elem = (l.sytle == 'hidden'?f.firstChild:f);
                    var elemBox= elem.getBoundingClientRect();
                    var elemWidth=elemBox.right-elemBox.left
                    var lright= b+elemWidth;
                }
            }
            if (e.A&T_VERTICAL_ANCHOR) {
 	  	if ((o.anchor==G_ANCHOR_TOP_RIGHT)||(o.anchor==G_BOTTOM_TOP_LEFT)) {
                    var lbottom = d.getBoundingClientRect().top-this._map.getContainer().getBoundingClientRect().top+b;
                    for (var c = f; c; c = c.nextSibling) {
                        if (c.style.visibility != 'hidden') {
                            lbottom+=(c.getBoundingClientRect().bottom-c.getBoundingClientRect().top);
                        }
                    }
                } else {
                    ;
                }
            }
        }
        if (lbottom) e.C.d.style.top  = (lbottom + o.offset.height)+'px';
        if (lright)  e.C.d.style.left = (lright  + o.offset.width )+'px';
	e.C.moveAnchoredControl();
    }
}


TControlBase.prototype.initialize = function(map,id,c,limit,altText) {
    this._map = map;
    this.anchorable = true;

    var d = document.createElement('div'); //main div 
    var h = document.createElement('div'); //header  (Open/Close Dialog)

  
    setClassName(d, 'ElemControl');
    d.ElemControl = this;

    d.style.border = "1px black solid";
    d.style.backgroundColor = 'white';
    d.style.width  = 'auto';
    setOpacity(d.style,80);

    h.style.align = "right";
    h.style.textAlign = "right";
    if (MSIE)
        h.style.height = "auto";
    else
        h.style.height = "15px";
    h.style.width  = 'auto';

    c.style.height   = 'auto';
    c.style.width    = 'auto';
    c.style.padding  = '5px';

    if(MSIE){
        // special code only for Microsoft Internet Explorer... sigh
        var img = document.createElement(
        '<img alt = "'+altText+'" '
            + 'id = "'+id+'" '
            + 'onclick = "this.parentNode.parentNode.ElemControl.showMenu(\''+id+'\');" '
            + 'src = "dev/images/close.gif"'
            + '>');
    } else {
        // code for the rest
        var img = document.createElement('img');
        img.id = id;
        img.setAttribute('title', altText);
        img.setAttribute('onclick', 'this.parentNode.parentNode.ElemControl.showMenu(\''+id+'\');');
        img.setAttribute('src', 'dev/images/close.gif');
        img.style.cursor = "pointer;hand";
	
    }
    //  h.appendChild(document.createTextNode('HOLA'));
    h.appendChild(img);
  
    d.appendChild(h); // Add Header 
    d.appendChild(c); // Add Body
    map.getContainer().appendChild(d);
    this.d = d;
    this.limit = limit;
    if (c.childNodes.length > this.limit) {
	if (MSIE) {
            var bcr = h.getBoundingClientRect();
            var hh  = bcr.bottom - bcr.top;
            var bcr = c.firstChild.getBoundingClientRect();
            var hc  = bcr.bottom - bcr.top;

            d.style.height   = (this.limit*hc+hh)+'px';
            d.style.overflow = 'auto';
            var self = this;
            d.onresize = function () { self.resize(); }
 	} else {
            var box=c.firstChild.getBoundingClientRect()
            var boxHeight=box.bottom-box.top
            c.style.height   = (this.limit*boxHeight) +'px';
            c.style.overflow = 'auto';
  	}
    }

    this.moveAnchoredControl();
    return d;
}


if (MSIE) {
    TControlBase.prototype.resize = function() {
        var bcr = this.d.getBoundingClientRect();
        var w   = bcr.right - bcr.left;
        this.d.onresize = '';
        this.d.style.width = w + 16 + 'px';
        this.d.style.overflow = 'hidden';
        this.d.lastChild.style.overflow = 'auto';
        var bcr = this.d.lastChild.firstChild.getBoundingClientRect();
        var h   = bcr.bottom - bcr.top;
        this.d.lastChild.style.height   = (this.limit*h) +'px';
        this.d.lastChild.style.width    = this.d.style.width;
    }
}

//
// TElemControl: Control con el árbol de tipos de elementos
//

function TElemControl(printable, selectable) {
    TControlBase.call(this,printable,selectable);
}

TElemControl.prototype = new TControlBase();
TElemControl.prototype.addElem            = function(e)  { this.l.push(e); return e; }

TElemControl.prototype.initialize = function(map) {

    var c = document.createElement('div'); //body    (Chosse elements visibility)
    setClassName(c, 'mapElemControl');

    for(var i = 0; i < this.l.length; ++i){
        var layer = this.l[i];
        var cb   = 'this.parentNode.parentNode.parentNode.ElemControl.selectElem(event,'+i+',\''+layer.tag+'\');';

//    if (jslog) jslog.debug("TElemControl.initialize: layer="+layer.nom+", flag="+layer.flag);
        if (layer.selectable)
        {
		    if(MSIE)
		    {
	                var rb  = document.createElement(
	                    '<input alt=""'
	                    + (layer.flag?'CHECKED ':'')
	                    + 'onclick="'+cb+'" '
	                    + 'type="checkbox" class="checkbox" id="'+layer.tag+'" '
	                    + '>');
		    } else
		    {
	                var rb = document.createElement('input');
	                rb.setAttribute('type', 'checkbox');
	                rb.id = layer.tag;
	                rb.setAttribute('value', (layer.flag?"1":"0"));
	                rb.setAttribute('onclick', cb);
	                if (layer.flag)
	                    rb.setAttribute('CHECKED','');
	        }
            rb.style.marginLeft = '5px';
        }
	
        var img = document.createElement('img');
        img.style.height = '16px';
        img.style.width  = '16px';
        img.setAttribute('src', layer.icon);

        var div = document.createElement('div');
        if (layer.hasAncestor) {
            div.style.marginLeft = '20px';
        }

        if (layer.selectable) {
            div.appendChild(rb);
        }
        else {
            img.style.marginLeft = '25px';
        }
    
        div.appendChild(img);
        div.appendChild(document.createTextNode(' '+layer.nom));
        c.appendChild(div);
    }
  
    //inicializa el control de visualización de capas
    return TControlBase.prototype.initialize.call(this,map,'doViewElement',c,15,PARAM_TElemControl_title);
}

TElemControl.prototype.selectElem = function(evt,i,id) {
    evt = (evt) ? evt : ((window.event) ? window.event : "");
    if (!evt) return;

    var checkbox = document.getElementById(id);
    if ( !checkbox ) return;

    this.l[i].flag = checkbox.checked;
    for (ndx=0; ndx<this.l[i].sublayerList.length; ndx++) {
    	this.l[i].sublayerList[ndx].flag=checkbox.checked;
    	var subcheckbox = document.getElementById(this.l[i].sublayerList[ndx].tag);
    	if (subcheckbox) subcheckbox.checked=checkbox.checked;
    }
    this.updateData(false);

}


TElemControl.prototype.updateData = function(f) {
    var m = this._map;
    var x = m.getInfoWindow();
    m.OpenedInfoWindowPos=x.isHidden()?false:x.getPoint();
    if (f)  m.clearOverlays();
    var l = this.l;
    for(var i = 0; i < l.length; i++) if (l[i].hasMarkers) l[i].show(m,f);
}

//
// TElemSelector: Implementa el Control de Centrado de Iconos
//

TElemSelector.idCounter = 0;
TElemSelector.hiddenIcon = null;
function TElemSelector(printable, selectable) {
    TControlBase.call(this,printable,selectable);
    this.id = ++TElemSelector.idCounter;
}

TElemSelector.prototype = new TControlBase();

TElemSelector.prototype.initialize = function(map) {
    var c = document.createElement('div'); //body    (Choose layers' visibility)
    setClassName(c, 'mapElemSelector');
    id = map.TMap.id;
    if(MSIE){
  	var s = document.createElement(
        '<select name="'+id+'_ElemSelector" id="'+id+'_ElemSelector" size="1" '
            + 'onchange="this.parentNode.parentNode.ElemControl.selectElem(\''+id+'_ElemSelector\');"></select>');
    } else {
        var s = document.createElement('select');
        s.id = id+'_ElemSelector';
        s.setAttribute('name', id+'_ElemSelector');
        s.setAttribute('size', '1');
        s.setAttribute('onchange','this.parentNode.parentNode.ElemControl.selectElem(\''+id+'_ElemSelector\');');
    }
  
    for(var i = 0; i < this.l.length; ++i){
        var layer = this.l[i];
        if (layer.xmltag!="LNK")
        {
        	var o = document.createElement('option');
        	o.appendChild(document.createTextNode(layer.nom));
        	s.appendChild(o);
        }
    }
    c.appendChild(s);
    TControlBase.prototype.initialize.call(this,map,id+'doSelectElement'+this.id,c,5, PARAM_TElemSelector_title);
    this.d.appendChild(document.createElement('div')); // To Be replaced when options
    return this.d;
}

TElemSelector.prototype.addElem    = function(e,f) {
    if (f.length) { e.setMarkers(f); }
    this.l.push(e);
    return e;
}

TElemSelector.prototype.updateData = function(b) {
    if (!this._map || !b) return;
    this.selectElem(this._map.TMap.id+'_ElemSelector');
}

TElemSelector.prototype.applySelection = function (x) {
    if (this.d) { 
        var c = document.createElement('div');
        c.style.width = '175px';
    
        var cb = 'this.parentNode.parentNode.ElemControl.';
    } else {
  	var c = document.getElementById(this._map.TMap.id+'_ElemList');
  	var cb = 'javascript:lMenuSel[\''+this._map.TMap.id+'\'].';
  	c.innerHTML = '';
    }
  
    setClassName(c, 'mapElemSelector');

    var tl = !this.l[x].hasMarkers? this.l[x].lElems:[this.l[x]];
    var n = 0;
    for(var i = 0; i < tl.length; i++) {
  	n+=tl[i].lMarkers.length;
        for (var j = 0; j < tl[i].lMarkers.length; j++) {
            var e = tl[i].lMarkers[j];
            if (MSIE)
            {
                var o = document.createElement(
                '<div onClick="'+cb+'doAction('+x+','+i+','+j+');"></div>');
            } else {
  	  	var o = document.createElement('div');
  	  	o.setAttribute('onClick',cb+'doAction('+x+','+i+','+j+');');
            }
            var img = document.createElement('img');
            img.style.height = '16px';
            img.style.width  = '16px';
            img.setAttribute('src', e.icon?e.icon:tl[i].icon);
            o.appendChild(img);
            o.appendChild(document.createTextNode(' '+e.uname));
            o.style.cursor = 'pointer';
            o.title="Centrar Elemento";
            c.appendChild(o);
        }
    }
    if (!this.d) return

    c.style.visibility = this.d.lastChild.style.visibility;
    this.d.style.height = 'auto';
    this.d.style.width  = 'auto';
    this.d.replaceChild(c,this.d.lastChild);
  
    if (c.childNodes.length > this.limit) {
        if (MSIE) {
            var s = this.d.firstChild;
            var bcr = s.getBoundingClientRect();
            var hh  = bcr.bottom - bcr.top;
            s = s.nextSibling;
            var bcr = s.getBoundingClientRect();
            hh += bcr.bottom - bcr.top;
            var bcr = c.firstChild.getBoundingClientRect();
            var hc  = bcr.bottom - bcr.top;
            var self = this;
            this.d.style.height   = (this.limit*hc)+(hh)+'px';
            this.d.style.overflow = 'auto';
            this.d.onresize = function () { self.resize(); }
        } else {
            var bcr = c.firstChild.getBoundingClientRect();
            c.style.height   = (this.limit*(bcr.bottom - bcr.top)) +'px';
            c.style.overflow = 'auto';
        }
    }
    this.moveAnchoredControl();
}

TElemSelector.prototype.selectElem = function(id) {
    var combo = document.getElementById(id);
    if ( !combo ) return;

    var index = combo.selectedIndex;
    if (index<0 || index>this.l.length) return;
    this.applySelection(index);
}


TElemSelector.prototype.doAction = function(x,y,z) {
    if (!this.l[x].hasMarkers)
    {
        var e = this.l[x].lElems[y].lMarkers[z];
		this._map.setCenter(e.getPoint());
        if (PARAM_openPopupOnCenter) e.doOpenWindow()
	} else {
        var e = this.l[x].lMarkers[z];
		this._map.setCenter(e.getPoint());
    }
    hilitIconStart(e, 6);
}

var hilitIcon;
var hilitIconCounter;

function hilitIconStart(e, c) {
    if (hilitIcon!=null) {
    	return;
    }
    hilitIconCounter=c;
    hilitIcon=e;
    window.setTimeout(hilitIconCycle, 250);
}


function hilitIconCycle() {
    hilitIconCounter=hilitIconCounter-1;
    if (hilitIconCounter % 2 == 0) {
    	 hilitIcon.show();
    }
    else {
    	hilitIcon.hide();
    }  
    if (hilitIconCounter > 0) {
    	window.setTimeout(hilitIconCycle, 250);
    }
    else {
        hilitIcon=null;	
    }
}
