var requestType = "";
var requestWait = false;
var isIE;
var xmlHttp;

//we call this method each time the application is submitted
function cXMLHttpRequest() {
    if (window.XMLHttpRequest) {//in case that browser be Mozilla or Netscape // IE7, FF, Opera, ...
        xmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {//if the browser is IE // <=IE6
        isIE = true;
        try{
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(othermicrosoft){
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
    }
    if(!xmlHttp)alert("NO SE PUEDE INICIALIZAR REQUEST");
    requestWait = true;
}

var modal;
function sRequest(url) {    
    //showLayer('image_loading');
    //showLoadingLayer('Cargando datos...');
    //$("#resdiv").mask("Buscando...");
    cXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChangeLoad;
    xmlHttp.open("POST", url, true);
    xmlHttp.send(null);
    requestWait = false;
}

function handleStateChangeLoad() {    
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            if( requestType == "cities" ){
                rOptions('selectCiudad');
            }
            if( requestType == "type" ){                
                rOptions('form_geocoder:equipment_list');
            }
            if( requestType == "district" ){                
                rOptions('selectBarrio');
            }
            if( requestType == "gotoDistrict" ){
                gotoPointGoogleMap();
            }
            if( requestType == "search" ){
                parserResultSearch();
                $("#Pagination2").addClass("pagination");
                //document.location.href ='#anchor';
            }
            if( requestType == "wellpoint" ){                
                wellpoitInfo();
            }
            enableButton("selectDepto");
            enableButton("selectCiudad");
            enableButton("selectBarrio");
            enableButton('search');
            enableButton('gotoMap');
        }
        //hideLayer('image_loading');
       // $("#resdiv").unmask();
        //hideLoadingLayer();
    }
}

/* Function that load wellpoint information */
function wellpoitInfo(){
    var row, row2, row3, row4
    initVars();
    clearData();
    setOffsets();
    
    var xmlDoc = xmlHttp.responseXML;    
    var type = xmlDoc.getElementsByTagName("type");    
    var city = xmlDoc.getElementsByTagName("city");
    // var district = xmlDoc.getElementsByTagName("district");
    var name = xmlDoc.getElementsByTagName("name");    
    var data = "Ciudad: "+city[0].firstChild.data;
    var data2 = "Tipo: "+type[0].firstChild.data;
    var data3 = "Nombre: "+name[0].firstChild.data;
    var row = createRow(data);
    var row2 = createRow(data2);    
    //var row2 = createRow(district[0].firstChild.data);
    var row3 = createRow(data3);        
    dataTableBody.appendChild(row);
    dataTableBody.appendChild(row2);
    dataTableBody.appendChild(row3);   
}

/* Function that reload city list */
function rOptions( idLista ) {
    var xmlDoc = xmlHttp.responseXML;
    var selectList = document.getElementById(idLista);    
    clearDataList( selectList );    
    var op = document.createElement("option");
    op.appendChild( document.createTextNode("---") );
    op.value = "";                                      
    selectList.appendChild(op);  
    var currenCity = null;
    //var ma = xmlDoc.getElementsByTagName("response");
    var allOptions = xmlDoc.getElementsByTagName("option");    
    if(  allOptions.length == 0){
        allOptions = xmlDoc.getElementsByTagName("text");
    }
    var allValues = xmlDoc.getElementsByTagName("value");
    for(var i = 0; i < allOptions.length; i++) {
        currenCity = allOptions[i];
        var responseText = document.createTextNode(currenCity.firstChild.data);
        var opt = document.createElement("option");
        opt.appendChild(responseText);
        if( allValues == null || allValues[i] == null ){
            opt.value = currenCity.firstChild.data;
        }else{
            opt.value = allValues[i].firstChild.data;
        }
        selectList.appendChild(opt);
    }
}

function clearDataList( data ) {    
    if( data != null && data.childNodes != null ){
        var ind = data.childNodes.length;            
        for (var i = ind - 1; i >= 0 ; i--) {        
            data.removeChild(data.childNodes[i]);       
        }
    }
}

/* Function to execute search  */
function search(){    
    requestType = "search";
    var validAction = false;    
    // verificar campos de acuerdo ha formulario    
    validAction = checkform("streetOne","Debe de insertar calle a buscar.");
    //if( validAction )
    //validAction = checkform("streetTwo","Debe de insertar el nombre calle a intersectar");
    if( validAction ){
        if(!checkform("selectDepto","Debe de seleccionar un Departamento.")){
            return;
        }
        disableButton("selectDepto");
        disableButton("selectCiudad");
        disableButton("selectBarrio");
        disableButton('search');
        disableButton('clearForm');
        var deptoSearch = document.getElementById("selectDepto");
        var w = deptoSearch.selectedIndex;
        var depto = deptoSearch.options[w].text;
        var cityList =document.getElementById("selectCiudad");
        var district =document.getElementById("selectBarrio");
        var streetOne =document.getElementById("streetOne");
        var streetTwo =document.getElementById("streetTwo");    
        var queryString = "GeocoderServlet?action=search&typeSearch=2&f=xml&start="+start+"&limit="+limit;
        queryString += "&departament="+depto+"&city=" +cityList.value
            + "&neighbourhood="+district.value + "&name=" + streetOne.value + "&streetTwo="+streetTwo.value
            + "&timeStamp=" + new Date().getTime();
        sRequest(queryString);
    }
}

//Funcion para buscar barrio y ubicar en el mapa
function barrioSearch(name,city,depto){
    $.post('GeocoderServlet?action=neighbourhood',{
        neighbourhood: name,           
        city:city,
        depto:depto,
        f:'xml'
    },
    function(data) {    
        //alert($(data).find('POINT').text());
        MapUtil.parseWKT($(data).find('wkt').text());
    });
}

/* Funtion to get wellpoint */
function wellpoint(e){
    getXY(e);
    var layerRequest = "ptointeres";
    requestType = "wellpoint";
    var queryString = "GeocoderServlet?";    
    queryString += "layer="+ layerRequest + "&action=wellpoint"
        + "&coordX=" + geograficX +"&coordY="+ geograficY
        + "&timeStamp=" + new Date().getTime();
    sRequest(queryString);
}

/* Function to create not exist row data in table */
function createRowForColumnMessage(message,col) {
    var row, cell,txtNode;
    row = document.createElement("tr");
    cell = document.createElement("td");
    txtNode = document.createTextNode(message);
    cell.colSpan=col;
    cell.appendChild(txtNode);
    row.appendChild(cell);
    return row;
}

/* Function to create row data in table */
function createRowOneColumn(wkt,data2,data3,data4,data5) {
    var row, cell,cell2,cell3,cell4,txtNode,txtNode2,txtNode3,txtNode4;
    row = document.createElement("tr");
    cell = document.createElement("td");
    
    /*
    row.setAttribute("bgcolor", "#FFFAFA");
    row.setAttribute("border", "0");
     */
    var func = "GeocoderServlet?";
    //func += "geom=" +data+ "&action=gotoMap";
    var url = "#";
    //var link = document.createElement("A");
    //createLink(url,data4,func);
    txtNode = document.createTextNode("CIUDAD: "+data2);
    txtNode2 = document.createTextNode("BARRIO: "+data3);
    txtNode3 = document.createTextNode(data4+": ");
    txtNode4 = createButtonZoonWKTGoogleMap(wkt);
    var txtNode5 = document.createTextNode(data5+" ");
    cell.appendChild(txtNode3);
    cell.appendChild(txtNode5);
    cell.appendChild(txtNode4);
    cell.appendChild(document.createElement("br"));
    cell.appendChild(txtNode2);
    cell.appendChild(document.createElement("br"));
    cell.appendChild(txtNode);
    cell.onmousedown = function(){
        if(MapUtil.cornerMark != null){
            map.removeOverlay(MapUtil.cornerMark);
        }
        MapUtil.parseWKT(wkt);
        MapUtil.clearNearPoints();
        MapUtil.cornerMark = null;
        //Si es una esquina coloca un cuadro de dialogo para buscar puntos cercanos.
        if(MapUtil.geom[0] instanceof GMarker){
            var content = 'Puede Arrastrar este marcador<br><a id="nearPointsLink" onclick="showNearPointsForm(false)">Buscar empresas cercanas a este punto</a>';
            MapUtil.cornerMark = MapUtil.geom[0];
            MapUtil.cornerMark.enableDragging();
            MapUtil.cornerMark.openInfoWindowHtml(content);
            GEvent.addListener(MapUtil.cornerMark, "click", function() {
                MapUtil.cornerMark.openInfoWindowHtml(content);    
            });
            GEvent.addListener(MapUtil.cornerMark, "dragend", function() {
                map.setCenter(MapUtil.cornerMark.getLatLng());    
            });
        }
    }
    cell.onmouseover = function(){
        cell.style.background='#FADE7C';
        cell.style.color='black';
        cell.style.cursor='hand';
    }
    cell.onmouseout = function(){
        cell.style.background='';
        cell.style.color='white';
        cell.style.cursor='pointer';
    }
    row.appendChild(cell);    
    return row;
}
/* Function to create row data in table */
function createRowTreeColumn2(wkt,data2,data3,data4,data5) {
    var row, cell,cell2,cell3,cell4,txtNode,txtNode2,txtNode3,txtNode4;
    row = document.createElement("tr");
    cell = document.createElement("td");
    cell2 = document.createElement("td");
    cell3 = document.createElement("td");
    cell4 = document.createElement("td");
    /*
    row.setAttribute("bgcolor", "#FFFAFA");
    row.setAttribute("border", "0");
     */
    var func = "GeocoderServlet?";
    //func += "geom=" +data+ "&action=gotoMap";
    var url = "#";
    //createLink(url,data4,func);
    txtNode = document.createTextNode(data2);
    txtNode2 = document.createTextNode(data3);
    txtNode3 = document.createTextNode(data4);
    txtNode4 = createButtonZoonWKTGoogleMap(wkt);
    var txtNode5 = document.createTextNode(data5);
    cell.appendChild(txtNode);
    cell2.appendChild(txtNode2);
    cell3.appendChild(txtNode3);
    cell4.appendChild(txtNode4);
    cell4.appendChild(txtNode5);

    row.appendChild(cell);
    row.appendChild(cell2);
    row.appendChild(cell3);
    row.appendChild(cell4);
    return row;
}

/* Function to create row data in table */
function createRowForColumnHeader(data0,data1,data2,data3) {
    var row, cell,cell2,cell3,cell4,txtNode,txtNode2,txtNode3,txtNode4;   
    row = document.createElement("tr");
    cell = document.createElement("th");
    cell2 = document.createElement("th");
    cell3 = document.createElement("th");
    cell4 = document.createElement("th");
    
    txtNode = document.createTextNode(data0);
    txtNode2 = document.createTextNode(data1);
    txtNode3 = document.createTextNode(data2);
    txtNode4 = document.createTextNode(data3);
    
    cell.appendChild(txtNode);
    cell2.appendChild(txtNode2);
    cell3.appendChild(txtNode3);
    cell4.appendChild(txtNode4);
    
    row.appendChild(cell);
    row.appendChild(cell2);
    row.appendChild(cell3);    
    row.appendChild(cell4);
    return row;  
}
/* Function to create row data in table */
function createRowOneColumnHeader(data0,num) {
    var row, cell,txtNode;
    row = document.createElement("tr");
    cell = document.createElement("th");
    cell.style.fontWeight = "bold";
    cell.style.color = "#FFFFFF";//202020
    cell.style.background = "#3E4A6A";
    txtNode = document.createTextNode(data0+num);
    cell.appendChild(txtNode);    
    row.appendChild(cell);
    return row; 
}

function createButtonZoonWKTGoogleMap(wkt){
    //var boton = document.createElement("input");
    //boton.setAttribute("type","button");
    //boton.onclick=function(){gotoLocation(lat,lon,info);}
    var image = new Image();
    image.setAttribute("alt","Ir a mapa");
    image.src="./images/zoomto.gif";
    image.onmousedown = function(){
        MapUtil.parseWKT(wkt);
    }
    return image;
}
function createButtonZoonGoogleMap(lat,lon,info){
    //var boton = document.createElement("input");
    //boton.setAttribute("type","button");    
    //boton.onclick=function(){gotoLocation(lat,lon,info);}
    var image = new Image();
    image.setAttribute("alt","Ir a mapa");
    image.src="./images/zoomto.gif";
    image.onmousedown = function(){
        gotoLocation(lat,lon,17,info);
    }
    return image;
}

/* Funtion to create link for action */
function createLink(url,text,func){
    var temp = document.createElement('a');
    temp.setAttribute('href', url);
    temp.appendChild(document.createTextNode(text));
    return temp;
}
function pageselectCallback(page_index, jq){
    document.location.href ='#anchor2';
    start = (page_index*limit);        
    if(!reaload){        
        search();        
    }
    reaload=false;    
}
var countRes, press=false;
function parserResultSearch() {
    initVars();
    clearData();    
    var lon;
    var lat;
    var index;
    //setOffsets();
    var xmlDoc = xmlHttp.responseXML;
    var counter = xmlDoc.getElementsByTagName("totalCount");
    var id = xmlDoc.getElementsByTagName("g");
    var coord = xmlDoc.getElementsByTagName("wkt");
    var city = xmlDoc.getElementsByTagName("city");
    var district = xmlDoc.getElementsByTagName("neighbourhood");
    var type = xmlDoc.getElementsByTagName("type");
    var name = xmlDoc.getElementsByTagName("name");
    if(counter.length>0){
        dataTableBody.appendChild( createRowOneColumnHeader("Resultados: ", counter[0].firstChild.data) );
        countRes=counter[0].firstChild.data;
        //paging(countRes);
        if( press ){
            press = false;
            $("#Pagination2").pagination(countRes, {
                num_edge_entries: 2,
                num_display_entries: 5,
                callback: pageselectCallback,
                items_per_page: limit,
                prev_text: 'Ant.',
                next_text: 'Sig.'
            });
        }
    }else{
        $("#Pagination2").pagination(0, {
            num_edge_entries: 2,
            num_display_entries: 8,
            callback: null,
            items_per_page: limit
        });
    }
    for( var i = 0; i < coord.
        length; i++ ){
        //index = coord[i].firstChild.data.indexOf(" ");
        //lon = coord[i].firstChild.data.substring(0,index);
        //lat = coord[i].firstChild.data.substring(index+1);
        var row = createRowOneColumn( coord[i].firstChild.data, city[i].firstChild.data, district[i].firstChild.data, type[i].firstChild.data, name[i].firstChild.data);
        dataTableBody.appendChild(row);
    }
    if( coord == null || coord.length == 0 ){
        var row = createRowForColumnMessage( "No se tienen resultados",4);
        dataTableBody.appendChild(row);
    }
}

/* Method to reload city when change depto */
function changeDepto(){    
    var depto = document.getElementById("selectDepto");    
    if( depto != null ){
        //disableButton("selectDepto");
        disableButton("selectCiudad");
        disableButton("selectBarrio");
        disableButton('searchBoton02');
        disableButton('searchBoton');
        disableButton('gotoMap');        
        var cityList = document.getElementById("selectCiudad");
        clearDataList( cityList );
        var selectList = document.getElementById( "selectBarrio" );
        clearDataList( selectList );
        requestType = "cities";
        var queryString = "GeocoderServlet?";
        queryString += "departament=" +depto.value + "&action=rc&f=xml"
            + "&timeStamp=" + new Date().getTime();
        sRequest(queryString);        
    }
}

/* Method to reload barrios when change city */
function changeCity(){
    var cityList = document.getElementById("selectCiudad");
    if( cityList != null ){
        disableButton("selectDepto");
        disableButton("selectCiudad");
        disableButton("selectBarrio");
        disableButton('searchBoton02');
        disableButton('searchBoton');
        disableButton('gotoMap');
        requestType = "district";
        var queryString = "GeocoderServlet?";
        queryString += "city=" +cityList.value + "&action=rn&f=xml"
            + "&timeStamp=" + new Date().getTime();   
        sRequest(queryString);
    }
}

function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
    else
        return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
        
    }
    return "";
}

// toggle layer to invisible
function hideLayer(name) {		
    var layer = getLayer(name);
    if( layer != null )
        layer.visibility = "hidden";
}

// toggle layer to visible
function showLayer(name) {
    var layer = getLayer(name);
    if(layer)
        layer.visibility = "visible";
}

function getLayer(name) {
    var theObj = document.getElementById(name);
    if (theObj!=null) {
        return theObj.style
    }  else {
        return(null);
    }
}

var dataDiv;
var dataTable;
var dataTableBody;
var offsetEl;

function initVars() {
    dataTableBody = document.getElementById("courseDataBody");
    dataTable = document.getElementById("courseData");
    dataDiv = document.getElementById("popup");
}
function clearData() {
    if( dataTableBody != null ){
        var ind = dataTableBody.childNodes.length;
        for (var i = ind - 1; i >= 0 ; i--) {
            dataTableBody.removeChild(dataTableBody.childNodes[i]);
        }
        if( dataDiv )
            dataDiv.style.border = "none";
    }
}

// Validate field form
function checkform( idObject, message) {
    var obj = document.getElementById( idObject );
    if (obj.value == "") {
        alert( "Aviso: " + message );
        obj.focus();
        return false ;
    }
    return true ;
}

function getDistrictLocation(){
    var cityList = document.getElementById("form_geocoder:select_city");
    var depto = document.getElementById("form_geocoder:depto_list");
    var barrios = document.getElementById("select_barrio");
    if( checkform("select_barrio","Debe de seleccionar un barrio") && cityList != null ){
        requestType = "gotoDistrict";
        var queryString = "GeocoderServlet?";
        queryString += "depto=" +depto.value +"&city=" +cityList.value +"&district="+barrios.value+ "&action=gotoDistrict"
            + "&timeStamp=" + new Date().getTime();   
        sRequest(queryString);
    }
}

function gotoPointGoogleMap(){
    var index;
    var xmlDoc = xmlHttp.responseXML;
    var coord = xmlDoc.getElementsByTagName("coord");
    var data = xmlDoc.getElementsByTagName("data");
    var current,lon=0,lat=0;
    for(var i = 0; i < coord.length; i++) {
        index = coord[i].firstChild.data.indexOf(" ");
        lon = parseFloat(coord[i].firstChild.data.substring(6,index));
        lat = parseFloat(coord[i].firstChild.data.substring(index+1));
        var description = data[i].firstChild.data;
        description = "Barrio: " + description;
        gotoLocation(lat,lon,16, description);
    }
}
function validateFloat(o){
    switch (isFinite(o.value)){
        case true:
            break;
        case false:
            alert("Ingrese coordenadas validas");
    }
}

var m2;
function gotoPoint(){
    var lt=document.getElementById( "Latitud" );
    if( lt && lt.value){
        lt.value = lt.value.replace(',','.');
    }
    var lg=document.getElementById( "Longitud" );
    if( lg && lg.value){
        lg.value = lg.value.replace(',','.');
    }
    validateFloat(lt);
    validateFloat(lg);
    var g = new GLatLng(lt.value,lg.value);
    if(m2){
        map.removeOverlay(m2);
    }
    m2 = new GMarker(g);
    map.addOverlay(m2);
    map.setCenter(g);
}
function disableButton(obj) {
    var but=document.getElementById( obj );
    if( but != null )
        but.disabled=true;
}

function enableButton(obj) {
    var but=document.getElementById( obj );
    if( but != null )
        but.disabled=false;
}

function cOptionList( values, options ){
    var selectList = document.createElement("select");
    for( var i=0; i < values.length;  i++ ){
        var value = values[i];
        var op1=document.createElement("OPTION");
        var textOp1=document.createTextNode(value);
        if( options ){
            op1.setAttribute("value",options[i]);
        }else{
            op1.setAttribute("value",value);
        }
        op1.appendChild(textOp1);
        selectList.appendChild(op1);
    }
    return selectList;
}
function cRow( label, obj ){
    var tr=document.createElement("tr");
    var td1=document.createElement("td");
    //td1.style.fontSize='10px';
    var td2=document.createElement("td");
    var text=document.createTextNode(label);
    td1.style.textAlign = "right";
    td1.appendChild(text);
    td2.appendChild(obj);
    tr.appendChild(td1);
    tr.appendChild(td2);
    return tr;
}

function cRow2( label, obj, obj2 ){
    var tr=document.createElement("tr");
    var td1=document.createElement("td");
    //td1.style.fontSize='10px';
    var td2=document.createElement("td");
    var text=document.createTextNode(label);
    td1.style.textAlign = "right";
    td1.appendChild(text);
    td1.appendChild(obj);
    td2.appendChild(obj2);
    tr.appendChild(td1);
    tr.appendChild(td2);
    return tr;
}

var start=0,limit=10,reaload=false;
function cForm(){
    var width=240;
    var height = 200;
    borderStyle = '1px solid #E9F3B4';
    var href = "blockForm";
    var boxdiv = document.getElementById(href);
    if (boxdiv != null) {
        if (boxdiv.style.display=='none') {
            // Show existing box, move it
            // if document changed layout
            boxdiv.style.display='block';
        }
        else
        // Hide currently shown box.
            boxdiv.style.display='none';
        return false;
    }
    // Create box object through DOM
    boxdiv = document.createElement('div');
    // var loading = document.createTextNode("Cargando")
    // Assign id equalling to the document it will show
    boxdiv.setAttribute('id', href);

    boxdiv.style.display = 'block';
    //boxdiv.style.left = 5+'px';
    //boxdiv.style.top = 70+'px';
    //boxdiv.style.position = 'relative';
    boxdiv.style.width = width + 'px';
    // boxdiv.style.height = height + 'px';
    //boxdiv.style.border = borderStyle;
    boxdiv.style.color = "white";
    boxdiv.style.fontFamily = "\"Trebuchet MS\", Tahoma, Verdana, Arial, Helvetica, sans-serif";
    boxdiv.style.textAlign = 'left';
    boxdiv.style.fontSize = '1em';
    boxdiv.style.paddingTop = '1%';
    //boxdiv.style.valign="buttom"
    boxdiv.style.background = '#5A595A';//'#cccccc'; //'#a5c728';
    boxdiv.style.zIndex ='5';
    //boxdiv.appendChild(loading);
    if( boxdiv != null ){
        var topop=80;        
    }

    var formGeo=document.createElement("form");
    formGeo.setAttribute("id","formGeocoder");
    var t=document.createElement("TABLE");
    t.cellSpacing="0px";
    t.cellPadding="0px";
    var tb=document.createElement("TBODY");
    
    var selectDepto = cOptionList(["-","BENI","CHUQUISACA","COCHABAMBA","LA PAZ","PANDO","POTOSI","ORURO","SANTA CRUZ","TARIJA"],
    ["0","8","1","3","2","9","5","4","7","6"]);
    selectDepto.setAttribute("id","selectDepto");    
    selectDepto.setAttribute("class","textField");
    selectDepto.onchange=changeDepto;
    tb.appendChild( cRow('(*)Departamento:',selectDepto));
    var selectCiudad = cOptionList([]);
    selectCiudad.setAttribute("id","selectCiudad");
    selectCiudad.setAttribute("class","textField");
    selectCiudad.onchange=changeCity;    
    tb.appendChild( cRow('Ciudad:',selectCiudad));
    var selectBarrio = cOptionList([]);
    selectBarrio.setAttribute("id","selectBarrio");
    selectBarrio.setAttribute("class","textField");   
    tb.appendChild(cRow('Barrio:',selectBarrio));

    var calle1=document.createElement("input");
    calle1.setAttribute("id","streetOne");
    calle1.setAttribute("class","textField");    
    var calle2=document.createElement("input");
    calle2.setAttribute("id","streetTwo");
    calle2.setAttribute("class","textField");    
    tb.appendChild(cRow('(*)Calle:',calle1));
    tb.appendChild(cRow('Esquina:',calle2));
    //paging.onclick=search;
    var but=document.createElement("input");
    but.setAttribute("class","Bsearch");
    but.setAttribute("type", "button");
    but.setAttribute("value", "Buscar");
    but.style.fontSize = '1em';
    but.style.height = '22px';
    
    var resdiv = document.createElement('div');    
    resdiv.style.overflow_x='hidden';
    resdiv.style.overflow_y='auto';
    resdiv.style.overflow='auto';
    resdiv.setAttribute("id", "resDiv");
    
    but.onclick = function(){
        start=0;
        reaload=true;
        press = true;
        //boxdiv.appendChild(resdiv);
        //$('#searchDiv').attr('style','{height:320px}');
        $('#blockForm div').remove();        
        $('#blockForm').append(resdiv);        
        search();
        return false;
    };
    
    var but2=document.createElement("input");
    but2.setAttribute("class","Bsearch");
    but2.setAttribute("type", "button");
    but2.setAttribute("value", "Ir al barrio");
    but2.style.fontSize = '1em';
    but2.style.height = '22px';
    but2.onclick = function(){
        if($('#selectBarrio').val() != null || $('#selectCiudad').val() != null){
            if($('#selectBarrio').val().length > 0 && $('#selectCiudad').val().length > 0){        
                barrioSearch($('#selectBarrio').val(),$('#selectCiudad').val(),'');            
            }else{
                alert('Coloque el nombre del barrio.');
            }
        }
        return false;
    };    
    
    //var anchor = document.createElement("a");
    //anchor.setAttribute("id", "anchor");
    //formGeo.appendChild(anchor);
    //but.setAttribute("onclick", "javascript:search();");
    tb.appendChild(cRow2('',but,but2));
    t.appendChild(tb);
    formGeo.appendChild(t);    
    boxdiv.appendChild(formGeo);
    
    //resdiv.style.height='10px';
    resdiv.setAttribute('id', 'resdiv');
    //resdiv.style.border='1px solid blue';
    var pag=document.createElement("div");
    pag.setAttribute('id', 'Pagination2');
    pag.setAttribute('class', 'pagination');

    //var anchor2 = document.createElement("a");
    //anchor2.setAttribute("id", "anchor2");
    //resdiv.appendChild(anchor2);
    var rt=document.createElement("TABLE");
    var rtb=document.createElement("TBODY");
    rt.style.border='0';
    rt.style.cellspacing='0';
    rt.style.cellpadding='0';
    rt.setAttribute('id', 'dataBody');
    rt.style.width='230px';
    rtb.setAttribute('id', 'courseDataBody');
    rtb.style.fontSize = '1em';
    rt.appendChild(rtb);    
    resdiv.appendChild(rt);
    resdiv.appendChild(pag);    
    
    var searchDiv = document.getElementById("searchDiv");
    searchDiv.appendChild(boxdiv);
    $('#blockForm').append('<div>Para realizar una búsqueda, puede introducir únicamente el departamento y parte del nombre de la calle.<div>');
    return false;
}

function redirectIndex(){
    var header = new String("index.jsp");
    self.location.href=header;
}
function closeSession(){
    alert( 'Sesion finalizada:\n'+
        'Por favor vuelva a iniciar una nueva sesion.');
    redirectIndex();
}

var formShowed = 0;//Guarda el Form actualmente mostrada
function changeForm( idDiv, flag ){
    formShowed = idDiv;
    var boxdiv = document.getElementById('form_'+idDiv);
    if (boxdiv != null) {
        if (boxdiv.style.display=='none' || flag) {
            // Show existing box, move it
            // if document changed layout
            //boxdiv.style.display='block';
            $(boxdiv).show();
        }else{
            // Hide currently shown box.
            //boxdiv.style.display='none';
            $(boxdiv).hide();
        }
        for(var i = 1; i <= 4; i++) {
            var d = i + "";
            if( d != idDiv ){
                var boxdiv2 = document.getElementById('form_'+i);
                if( boxdiv2 != null )
                //boxdiv2.style.display='none';
                    $(boxdiv2).hide();
            }
        }
        return false;
    }
    return false;
}
