// script.aculo.us scriptaculous.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Scriptaculous = {
  Version: '1.8.1',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
  },
  REQUIRED_PROTOTYPE: '1.6.0',
  load: function() {
    function convertVersionString(versionString){
      var r = versionString.split('.');
      return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
    }
 
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       (convertVersionString(Prototype.Version) < 
        convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
       throw("script.aculo.us requires the Prototype JavaScript framework >= " +
        Scriptaculous.REQUIRED_PROTOTYPE);
    
    $A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
       function(include) { Scriptaculous.require(path+include+'.js') });
    });
  }
}

Scriptaculous.load();// script.aculo.us slider.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Marty Haught, Thomas Fuchs 
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

if (!Control) var Control = { };

// options:
//  axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
//  onChange(value)
//  onSlide(value)
Control.Slider = Class.create({
  initialize: function(handle, track, options) {
    var slider = this;
    
    if (Object.isArray(handle)) {
      this.handles = handle.collect( function(e) { return $(e) });
    } else {
      this.handles = [$(handle)];
    }
    
    this.track   = $(track);
    this.options = options || { };

    this.axis      = this.options.axis || 'horizontal';
    this.increment = this.options.increment || 1;
    this.step      = parseInt(this.options.step || '1');
    this.range     = this.options.range || $R(0,1);
    
    this.value     = 0; // assure backwards compat
    this.values    = this.handles.map( function() { return 0 });
    this.spans     = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
    this.options.startSpan = $(this.options.startSpan || null);
    this.options.endSpan   = $(this.options.endSpan || null);

    this.restricted = this.options.restricted || false;

    this.maximum   = this.options.maximum || this.range.end;
    this.minimum   = this.options.minimum || this.range.start;

    // Will be used to align the handle onto the track, if necessary
    this.alignX = parseInt(this.options.alignX || '0');
    this.alignY = parseInt(this.options.alignY || '0');
    
    this.trackLength = this.maximumOffset() - this.minimumOffset();

    this.handleLength = this.isVertical() ? 
      (this.handles[0].offsetHeight != 0 ? 
        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : 
      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : 
        this.handles[0].style.width.replace(/px$/,""));

    this.active   = false;
    this.dragging = false;
    this.disabled = false;

    if (this.options.disabled) this.setDisabled();

    // Allowed values array
    this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
    if (this.allowedValues) {
      this.minimum = this.allowedValues.min();
      this.maximum = this.allowedValues.max();
    }

    this.eventMouseDown = this.startDrag.bindAsEventListener(this);
    this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
    this.eventMouseMove = this.update.bindAsEventListener(this);

    // Initialize handles in reverse (make sure first handle is active)
    this.handles.each( function(h,i) {
      i = slider.handles.length-1-i;
      slider.setValue(parseFloat(
        (Object.isArray(slider.options.sliderValue) ? 
          slider.options.sliderValue[i] : slider.options.sliderValue) || 
         slider.range.start), i);
      h.makePositioned().observe("mousedown", slider.eventMouseDown);
    });
    
    this.track.observe("mousedown", this.eventMouseDown);
    document.observe("mouseup", this.eventMouseUp);
    document.observe("mousemove", this.eventMouseMove);
    
    this.initialized = true;
  },
  dispose: function() {
    var slider = this;    
    Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
    Event.stopObserving(document, "mouseup", this.eventMouseUp);
    Event.stopObserving(document, "mousemove", this.eventMouseMove);
    this.handles.each( function(h) {
      Event.stopObserving(h, "mousedown", slider.eventMouseDown);
    });
  },
  setDisabled: function(){
    this.disabled = true;
  },
  setEnabled: function(){
    this.disabled = false;
  },  
  getNearestValue: function(value){
    if (this.allowedValues){
      if (value >= this.allowedValues.max()) return(this.allowedValues.max());
      if (value <= this.allowedValues.min()) return(this.allowedValues.min());
      
      var offset = Math.abs(this.allowedValues[0] - value);
      var newValue = this.allowedValues[0];
      this.allowedValues.each( function(v) {
        var currentOffset = Math.abs(v - value);
        if (currentOffset <= offset){
          newValue = v;
          offset = currentOffset;
        } 
      });
      return newValue;
    }
    if (value > this.range.end) return this.range.end;
    if (value < this.range.start) return this.range.start;
    return value;
  },
  setValue: function(sliderValue, handleIdx){
    if (!this.active) {
      this.activeHandleIdx = handleIdx || 0;
      this.activeHandle    = this.handles[this.activeHandleIdx];
      this.updateStyles();
    }
    handleIdx = handleIdx || this.activeHandleIdx || 0;
    if (this.initialized && this.restricted) {
      if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
        sliderValue = this.values[handleIdx-1];
      if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
        sliderValue = this.values[handleIdx+1];
    }
    sliderValue = this.getNearestValue(sliderValue);
    this.values[handleIdx] = sliderValue;
    this.value = this.values[0]; // assure backwards compat
    
    this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = 
      this.translateToPx(sliderValue);
    
    this.drawSpans();
    if (!this.dragging || !this.event) this.updateFinished();
  },
  setValueBy: function(delta, handleIdx) {
    this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, 
      handleIdx || this.activeHandleIdx || 0);
  },
  translateToPx: function(value) {
    return Math.round(
      ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * 
      (value - this.range.start)) + "px";
  },
  translateToValue: function(offset) {
    return ((offset/(this.trackLength-this.handleLength) * 
      (this.range.end-this.range.start)) + this.range.start);
  },
  getRange: function(range) {
    var v = this.values.sortBy(Prototype.K); 
    range = range || 0;
    return $R(v[range],v[range+1]);
  },
  minimumOffset: function(){
    return(this.isVertical() ? this.alignY : this.alignX);
  },
  maximumOffset: function(){
    return(this.isVertical() ? 
      (this.track.offsetHeight != 0 ? this.track.offsetHeight :
        this.track.style.height.replace(/px$/,"")) - this.alignY : 
      (this.track.offsetWidth != 0 ? this.track.offsetWidth : 
        this.track.style.width.replace(/px$/,"")) - this.alignX);
  },  
  isVertical:  function(){
    return (this.axis == 'vertical');
  },
  drawSpans: function() {
    var slider = this;
    if (this.spans)
      $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
    if (this.options.startSpan)
      this.setSpan(this.options.startSpan,
        $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
    if (this.options.endSpan)
      this.setSpan(this.options.endSpan, 
        $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
  },
  setSpan: function(span, range) {
    if (this.isVertical()) {
      span.style.top = this.translateToPx(range.start);
      span.style.height = this.translateToPx(range.end - range.start + this.range.start);
    } else {
      span.style.left = this.translateToPx(range.start);
      span.style.width = this.translateToPx(range.end - range.start + this.range.start);
    }
  },
  updateStyles: function() {
    this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
    Element.addClassName(this.activeHandle, 'selected');
  },
  startDrag: function(event) {
    if (Event.isLeftClick(event)) {
      if (!this.disabled){
        this.active = true;
        
        var handle = Event.element(event);
        var pointer  = [Event.pointerX(event), Event.pointerY(event)];
        var track = handle;
        if (track==this.track) {
          var offsets  = Position.cumulativeOffset(this.track); 
          this.event = event;
          this.setValue(this.translateToValue( 
           (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
          ));
          var offsets  = Position.cumulativeOffset(this.activeHandle);
          this.offsetX = (pointer[0] - offsets[0]);
          this.offsetY = (pointer[1] - offsets[1]);
        } else {
          // find the handle (prevents issues with Safari)
          while((this.handles.indexOf(handle) == -1) && handle.parentNode) 
            handle = handle.parentNode;
            
          if (this.handles.indexOf(handle)!=-1) {
            this.activeHandle    = handle;
            this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
            this.updateStyles();
            
            var offsets  = Position.cumulativeOffset(this.activeHandle);
            this.offsetX = (pointer[0] - offsets[0]);
            this.offsetY = (pointer[1] - offsets[1]);
          }
        }
      }
      Event.stop(event);
    }
  },
  update: function(event) {
   if (this.active) {
      if (!this.dragging) this.dragging = true;
      this.draw(event);
      if (Prototype.Browser.WebKit) window.scrollBy(0,0);
      Event.stop(event);
   }
  },
  draw: function(event) {
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    var offsets = Position.cumulativeOffset(this.track);
    pointer[0] -= this.offsetX + offsets[0];
    pointer[1] -= this.offsetY + offsets[1];
    this.event = event;
    this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
    if (this.initialized && this.options.onSlide)
      this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
  },
  endDrag: function(event) {
    if (this.active && this.dragging) {
      this.finishDrag(event, true);
      Event.stop(event);
    }
    this.active = false;
    this.dragging = false;
  },  
  finishDrag: function(event, success) {
    this.active = false;
    this.dragging = false;
    this.updateFinished();
  },
  updateFinished: function() {
    if (this.initialized && this.options.onChange) 
      this.options.onChange(this.values.length>1 ? this.values : this.value, this);
    this.event = null;
  }
});
// script.aculo.us effects.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/ 

// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';
  if (this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if (this.slice(0,1) == '#') {  
      if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if (this.length==7) color = this.toLowerCase();  
    }  
  }  
  return (color.length==7 ? color : (arguments[0] || this));  
};

/*--------------------------------------------------------------------------*/

Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
};

Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
};

Element.setContentZoom = function(element, percent) {
  element = $(element);  
  element.setStyle({fontSize: (percent/100) + 'em'});   
  if (Prototype.Browser.WebKit) window.scrollBy(0,0);
  return element;
};

Element.getInlineOpacity = function(element){
  return $(element).style.opacity || '';
};

Element.forceRerendering = function(element) {
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
  } catch(e) { }
};

/*--------------------------------------------------------------------------*/

var Effect = {
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
  Transitions: {
    linear: Prototype.K,
    sinoidal: function(pos) {
      return (-Math.cos(pos*Math.PI)/2) + 0.5;
    },
    reverse: function(pos) {
      return 1-pos;
    },
    flicker: function(pos) {
      var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
      return pos > 1 ? 1 : pos;
    },
    wobble: function(pos) {
      return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
    },
    pulse: function(pos, pulses) { 
      pulses = pulses || 5; 
      return (
        ((pos % (1/pulses)) * pulses).round() == 0 ? 
              ((pos * pulses * 2) - (pos * pulses * 2).floor()) : 
          1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
        );
    },
    spring: function(pos) { 
      return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); 
    },
    none: function(pos) {
      return 0;
    },
    full: function(pos) {
      return 1;
    }
  },
  DefaultOptions: {
    duration:   1.0,   // seconds
    fps:        100,   // 100= assume 66fps max.
    sync:       false, // true for combining
    from:       0.0,
    to:         1.0,
    delay:      0.0,
    queue:      'parallel'
  },
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
    
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if (child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            new Element('span', {style: tagifyStyle}).update(
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if (((typeof element == 'object') || 
        Object.isFunction(element)) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || { });
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
    }, arguments[2] || { });
    Effect[element.visible() ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create(Enumerable, {
  initialize: function() {
    this.effects  = [];
    this.interval = null;    
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = Object.isString(effect.options.queue) ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'with-last':
        timestamp = this.effects.pluck('startOn').max() || timestamp;
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);
    
    if (!this.interval)
      this.interval = setInterval(this.loop.bind(this), 15);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if (this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    for(var i=0, len=this.effects.length;i<len;i++) 
      this.effects[i] && this.effects[i].loop(timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if (!Object.isString(queueName)) return queueName;
    
    return this.instances.get(queueName) ||
      this.instances.set(queueName, new Effect.ScopedQueue());
  }
};
Effect.Queue = Effect.Queues.get('global');

Effect.Base = Class.create({
  position: null,
  start: function(options) {
    function codeForEvent(options,eventName){
      return (
        (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
        (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
      );
    }
    if (options && options.transition === false) options.transition = Effect.Transitions.linear;
    this.options      = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn+(this.options.duration*1000);
    this.fromToDelta  = this.options.to-this.options.from;
    this.totalTime    = this.finishOn-this.startOn;
    this.totalFrames  = this.options.fps*this.options.duration;
    
    eval('this.render = function(pos){ '+
      'if (this.state=="idle"){this.state="running";'+
      codeForEvent(this.options,'beforeSetup')+
      (this.setup ? 'this.setup();':'')+ 
      codeForEvent(this.options,'afterSetup')+
      '};if (this.state=="running"){'+
      'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
      'this.position=pos;'+
      codeForEvent(this.options,'beforeUpdate')+
      (this.update ? 'this.update(pos);':'')+
      codeForEvent(this.options,'afterUpdate')+
      '}}');
    
    this.event('beforeStart');
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if (timePos >= this.startOn) {
      if (timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if (this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / this.totalTime,
          frame = (pos * this.totalFrames).round();
      if (frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  cancel: function() {
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if (this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    var data = $H();
    for(property in this)
      if (!Object.isFunction(this[property])) data.set(property, this[property]);
    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
});

Effect.Parallel = Class.create(Effect.Base, {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if (effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Tween = Class.create(Effect.Base, {
  initialize: function(object, from, to) {
    object = Object.isString(object) ? $(object) : object;
    var args = $A(arguments), method = args.last(), 
      options = args.length == 5 ? args[3] : null;
    this.method = Object.isFunction(method) ? method.bind(object) :
      Object.isFunction(object[method]) ? object[method].bind(object) : 
      function(value) { object[method] = value };
    this.start(Object.extend({ from: from, to: to }, options || { }));
  },
  update: function(position) {
    this.method(position);
  }
});

Effect.Event = Class.create(Effect.Base, {
  initialize: function() {
    this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
  },
  update: Prototype.emptyFunction
});

Effect.Opacity = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    // make this work on IE on elements without 'layout'
    if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
      this.element.setStyle({zoom: 1});
    var options = Object.extend({
      from: this.element.getOpacity() || 0.0,
      to:   1.0
    }, arguments[1] || { });
    this.start(options);
  },
  update: function(position) {
    this.element.setOpacity(position);
  }
});

Effect.Move = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
    this.element.makePositioned();
    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
    if (this.options.mode == 'absolute') {
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    this.element.setStyle({
      left: (this.options.x  * position + this.originalLeft).round() + 'px',
      top:  (this.options.y  * position + this.originalTop).round()  + 'px'
    });
  }
});

// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element, 
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
};

Effect.Scale = Class.create(Effect.Base, {
  initialize: function(element, percent) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or { } with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || { });
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');
    
    this.originalStyle = { };
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%','pt'].each( function(fontSizeType) {
      if (fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if (this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if (/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if (!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if (this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = { };
    if (this.options.scaleX) d.width = width.round() + 'px';
    if (this.options.scaleY) d.height = height.round() + 'px';
    if (this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if (this.elementPositioning == 'absolute') {
        if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if (this.options.scaleY) d.top = -topd + 'px';
        if (this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});

Effect.Highlight = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if (this.element.getStyle('display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = { };
    if (!this.options.keepBackgroundImage) {
      this.oldStyle.backgroundImage = this.element.getStyle('background-image');
      this.element.setStyle({backgroundImage: 'none'});
    }
    if (!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
    if (!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = function(element) {
  var options = arguments[1] || { },
    scrollOffsets = document.viewport.getScrollOffsets(),
    elementOffsets = $(element).cumulativeOffset(),
    max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();  

  if (options.offset) elementOffsets[1] += options.offset;

  return new Effect.Tween(null,
    scrollOffsets.top,
    elementOffsets[1] > max ? max : elementOffsets[1],
    options,
    function(p){ scrollTo(scrollOffsets.left, p.round()) }
  );
};

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  var options = Object.extend({
    from: element.getOpacity() || 1.0,
    to:   0.0,
    afterFinishInternal: function(effect) { 
      if (effect.options.to!=0) return;
      effect.element.hide().setStyle({opacity: oldOpacity}); 
    }
  }, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Appear = function(element) {
  element = $(element);
  var options = Object.extend({
  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
  to:   1.0,
  // force Safari to render floated elements properly
  afterFinishInternal: function(effect) {
    effect.element.forceRerendering();
  },
  beforeSetup: function(effect) {
    effect.element.setOpacity(effect.options.from).show(); 
  }}, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { 
    opacity: element.getInlineOpacity(), 
    position: element.getStyle('position'),
    top:  element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height
  };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) {
        Position.absolutize(effect.effects[0].element)
      },
      afterFinishInternal: function(effect) {
         effect.effects[0].element.hide().setStyle(oldStyle); }
     }, arguments[1] || { })
   );
};

Effect.BlindUp = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      } 
    }, arguments[1] || { })
  );
};

Effect.BlindDown = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  return new Effect.Appear(element, Object.extend({
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { 
          effect.element.makePositioned().makeClipping();
        },
        afterFinishInternal: function(effect) {
          effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
        }
      })
    }
  }, arguments[1] || { }));
};

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left'),
    opacity: element.getInlineOpacity() };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) {
          effect.effects[0].element.makePositioned(); 
        },
        afterFinishInternal: function(effect) {
          effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
        } 
      }, arguments[1] || { }));
};

Effect.Shake = function(element) {
  element = $(element);
  var options = Object.extend({
    distance: 20,
    duration: 0.5
  }, arguments[1] || {});
  var distance = parseFloat(options.distance);
  var split = parseFloat(options.duration) / 10.0;
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left') };
    return new Effect.Move(element,
      { x:  distance, y: 0, duration: split, afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
        effect.element.undoPositioned().setStyle(oldStyle);
  }}) }}) }}) }}) }}) }});
};

Effect.SlideDown = function(element) {
  element = $(element).cleanWhitespace();
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: window.opera ? 0 : 1,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
    }, arguments[1] || { })
  );
};

Effect.SlideUp = function(element) {
  element = $(element).cleanWhitespace();
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, window.opera ? 0 : 1,
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().show();
    },  
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    },
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
    }
   }, arguments[1] || { })
  );
};

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, { 
    restoreAfterFinish: true,
    beforeSetup: function(effect) {
      effect.element.makeClipping(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping(); 
    }
  });
};

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01, 
    beforeSetup: function(effect) {
      effect.element.hide().makeClipping().makePositioned();
    },
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) {
               effect.effects[0].element.setStyle({height: '0px'}).show(); 
             },
             afterFinishInternal: function(effect) {
               effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); 
             }
           }, options)
      )
    }
  });
};

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned().makeClipping(); 
         },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
       }, options)
  );
};

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || { };
  var oldOpacity = element.getInlineOpacity();
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 2.0, from: 0,
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    }, options), {transition: reverser}));
};

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  element.makeClipping();
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping().setStyle(oldStyle);
      } });
  }}, arguments[1] || { }));
};

Effect.Morph = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      style: { }
    }, arguments[1] || { });
    
    if (!Object.isString(options.style)) this.style = $H(options.style);
    else {
      if (options.style.include(':'))
        this.style = options.style.parseStyle();
      else {
        this.element.addClassName(options.style);
        this.style = $H(this.element.getStyles());
        this.element.removeClassName(options.style);
        var css = this.element.getStyles();
        this.style = this.style.reject(function(style) {
          return style.value == css[style.key];
        });
        options.afterFinishInternal = function(effect) {
          effect.element.addClassName(effect.options.style);
          effect.transforms.each(function(transform) {
            effect.element.style[transform.style] = '';
          });
        }
      }
    }
    this.start(options);
  },
  
  setup: function(){
    function parseColor(color){
      if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
      color = color.parseColor();
      return $R(0,2).map(function(i){
        return parseInt( color.slice(i*2+1,i*2+3), 16 ) 
      });
    }
    this.transforms = this.style.map(function(pair){
      var property = pair[0], value = pair[1], unit = null;

      if (value.parseColor('#zzzzzz') != '#zzzzzz') {
        value = value.parseColor();
        unit  = 'color';
      } else if (property == 'opacity') {
        value = parseFloat(value);
        if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
          this.element.setStyle({zoom: 1});
      } else if (Element.CSS_LENGTH.test(value)) {
          var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
          value = parseFloat(components[1]);
          unit = (components.length == 3) ? components[2] : null;
      }

      var originalValue = this.element.getStyle(property);
      return { 
        style: property.camelize(), 
        originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), 
        targetValue: unit=='color' ? parseColor(value) : value,
        unit: unit
      };
    }.bind(this)).reject(function(transform){
      return (
        (transform.originalValue == transform.targetValue) ||
        (
          transform.unit != 'color' &&
          (isNaN(transform.originalValue) || isNaN(transform.targetValue))
        )
      )
    });
  },
  update: function(position) {
    var style = { }, transform, i = this.transforms.length;
    while(i--)
      style[(transform = this.transforms[i]).style] = 
        transform.unit=='color' ? '#'+
          (Math.round(transform.originalValue[0]+
            (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
          (Math.round(transform.originalValue[1]+
            (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
          (Math.round(transform.originalValue[2]+
            (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
        (transform.originalValue +
          (transform.targetValue - transform.originalValue) * position).toFixed(3) + 
            (transform.unit === null ? '' : transform.unit);
    this.element.setStyle(style, true);
  }
});

Effect.Transform = Class.create({
  initialize: function(tracks){
    this.tracks  = [];
    this.options = arguments[1] || { };
    this.addTracks(tracks);
  },
  addTracks: function(tracks){
    tracks.each(function(track){
      track = $H(track);
      var data = track.values().first();
      this.tracks.push($H({
        ids:     track.keys().first(),
        effect:  Effect.Morph,
        options: { style: data }
      }));
    }.bind(this));
    return this;
  },
  play: function(){
    return new Effect.Parallel(
      this.tracks.map(function(track){
        var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
        var elements = [$(ids) || $$(ids)].flatten();
        return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
      }).flatten(),
      this.options
    );
  }
});

Element.CSS_PROPERTIES = $w(
  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 
  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
  'fontSize fontWeight height left letterSpacing lineHeight ' +
  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
  'right textIndent top width wordSpacing zIndex');
  
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

String.__parseStyleElement = document.createElement('div');
String.prototype.parseStyle = function(){
  var style, styleRules = $H();
  if (Prototype.Browser.WebKit)
    style = new Element('div',{style:this}).style;
  else {
    String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
    style = String.__parseStyleElement.childNodes[0].style;
  }
  
  Element.CSS_PROPERTIES.each(function(property){
    if (style[property]) styleRules.set(property, style[property]); 
  });
  
  if (Prototype.Browser.IE && this.include('opacity'))
    styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);

  return styleRules;
};

if (document.defaultView && document.defaultView.getComputedStyle) {
  Element.getStyles = function(element) {
    var css = document.defaultView.getComputedStyle($(element), null);
    return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
      styles[property] = css[property];
      return styles;
    });
  };
} else {
  Element.getStyles = function(element) {
    element = $(element);
    var css = element.currentStyle, styles;
    styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
      results[property] = css[property];
      return results;
    });
    if (!styles.opacity) styles.opacity = element.getOpacity();
    return styles;
  };
};

Effect.Methods = {
  morph: function(element, style) {
    element = $(element);
    new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
    return element;
  },
  visualEffect: function(element, effect, options) {
    element = $(element)
    var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
    new Effect[klass](element, options);
    return element;
  },
  highlight: function(element, options) {
    element = $(element);
    new Effect.Highlight(element, options);
    return element;
  }
};

$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
  'pulsate shake puff squish switchOff dropOut').each(
  function(effect) { 
    Effect.Methods[effect] = function(element, options){
      element = $(element);
      Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
      return element;
    }
  }
);

$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( 
  function(f) { Effect.Methods[f] = Element[f]; }
);

Element.addMethods(Effect.Methods);
// script.aculo.us controls.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
//           (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
// Contributors:
//  Richard Livsey
//  Rahul Bhargava
//  Rob Wills
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

// Autocompleter.Base handles all the autocompletion functionality 
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least, 
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method 
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most 
// useful when one of the tokens is \n (a newline), as it 
// allows smart autocompletion after linebreaks.

if(typeof Effect == 'undefined')
  throw("controls.js requires including script.aculo.us' effects.js library");

var Autocompleter = { }
Autocompleter.Base = Class.create({
  baseInitialize: function(element, update, options) {
    element          = $(element)
    this.element     = element; 
    this.update      = $(update);  
    this.hasFocus    = false; 
    this.changed     = false; 
    this.active      = false; 
    this.index       = 0;     
    this.entryCount  = 0;
    this.oldElementValue = this.element.value;

    if(this.setOptions)
      this.setOptions(options);
    else
      this.options = options || { };

    this.options.paramName    = this.options.paramName || this.element.name;
    this.options.tokens       = this.options.tokens || [];
    this.options.frequency    = this.options.frequency || 0.4;
    this.options.minChars     = this.options.minChars || 1;
    this.options.onShow       = this.options.onShow || 
      function(element, update){ 
        if(!update.style.position || update.style.position=='absolute') {
          update.style.position = 'absolute';
          Position.clone(element, update, {
            setHeight: false, 
            offsetTop: element.offsetHeight
          });
        }
        Effect.Appear(update,{duration:0.15});
      };
    this.options.onHide = this.options.onHide || 
      function(element, update){ new Effect.Fade(update,{duration:0.15}) };

    if(typeof(this.options.tokens) == 'string') 
      this.options.tokens = new Array(this.options.tokens);
    // Force carriage returns as token delimiters anyway
    if (!this.options.tokens.include('\n'))
      this.options.tokens.push('\n');

    this.observer = null;
    
    this.element.setAttribute('autocomplete','off');

    Element.hide(this.update);

    Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
    Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
  },

  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
    if(!this.iefix && 
      (Prototype.Browser.IE) &&
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update, 
       '<iframe id="' + this.update.id + '_iefix" '+
       'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
       'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
      this.iefix = $(this.update.id+'_iefix');
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  },
  
  fixIEOverlapping: function() {
    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
    this.iefix.style.zIndex = 1;
    this.update.style.zIndex = 2;
    Element.show(this.iefix);
  },

  hide: function() {
    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);
  },

  startIndicator: function() {
    if(this.options.indicator) Element.show(this.options.indicator);
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
  },

  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         Event.stop(event);
         return;
      }
     else 
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
         (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer = 
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },

  activate: function() {
    this.changed = false;
    this.hasFocus = true;
    this.getUpdatedChoices();
  },

  onHover: function(event) {
    var element = Event.findElement(event, 'LI');
    if(this.index != element.autocompleteIndex) 
    {
        this.index = element.autocompleteIndex;
        this.render();
    }
    Event.stop(event);
  },
  
  onClick: function(event) {
    var element = Event.findElement(event, 'LI');
    this.index = element.autocompleteIndex;
    this.selectEntry();
    this.hide();
  },
  
  onBlur: function(event) {
    // needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;     
  }, 
  
  render: function() {
    if(this.entryCount > 0) {
      for (var i = 0; i < this.entryCount; i++)
        this.index==i ? 
          Element.addClassName(this.getEntry(i),"selected") : 
          Element.removeClassName(this.getEntry(i),"selected");
      if(this.hasFocus) { 
        this.show();
        this.active = true;
      }
    } else {
      this.active = false;
      this.hide();
    }
  },
  
  markPrevious: function() {
    if(this.index > 0) this.index--
      else this.index = this.entryCount-1;
    this.getEntry(this.index).scrollIntoView(true);
  },
  
  markNext: function() {
    if(this.index < this.entryCount-1) this.index++
      else this.index = 0;
    this.getEntry(this.index).scrollIntoView(false);
  },
  
  getEntry: function(index) {
    return this.update.firstChild.childNodes[index];
  },
  
  getCurrentEntry: function() {
    return this.getEntry(this.index);
  },
  
  selectEntry: function() {
    this.active = false;
    this.updateElement(this.getCurrentEntry());
  },

  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
    
    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;
    this.element.focus();
    
    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      if(this.update.firstChild && this.update.down().childNodes) {
        this.entryCount = 
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else { 
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.index = 0;
      
      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  },

  addObservers: function(element) {
    Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
    Event.observe(element, "click", this.onClick.bindAsEventListener(this));
  },

  onObserverEvent: function() {
    this.changed = false;   
    this.tokenBounds = null;
    if(this.getToken().length>=this.options.minChars) {
      this.getUpdatedChoices();
    } else {
      this.active = false;
      this.hide();
    }
    this.oldElementValue = this.element.value;
  },

  getToken: function() {
    var bounds = this.getTokenBounds();
    return this.element.value.substring(bounds[0], bounds[1]).strip();
  },

  getTokenBounds: function() {
    if (null != this.tokenBounds) return this.tokenBounds;
    var value = this.element.value;
    if (value.strip().empty()) return [-1, 0];
    var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
    var offset = (diff == this.oldElementValue.length ? 1 : 0);
    var prevTokenPos = -1, nextTokenPos = value.length;
    var tp;
    for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
      tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
      if (tp > prevTokenPos) prevTokenPos = tp;
      tp = value.indexOf(this.options.tokens[index], diff + offset);
      if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
    }
    return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
  }
});

Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
  var boundary = Math.min(newS.length, oldS.length);
  for (var index = 0; index < boundary; ++index)
    if (newS[index] != oldS[index])
      return index;
  return boundary;
};

Ajax.Autocompleter = Class.create(Autocompleter.Base, {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  },

  getUpdatedChoices: function() {
    this.startIndicator();
    
    var entry = encodeURIComponent(this.options.paramName) + '=' + 
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams) 
      this.options.parameters += '&' + this.options.defaultParams;
    
    new Ajax.Request(this.url, this.options);
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
  }
});

// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
//                    text only at the beginning of strings in the 
//                    autocomplete array. Defaults to true, which will
//                    match text at the beginning of any *word* in the
//                    strings in the autocomplete array. If you want to
//                    search anywhere in the string, additionally set
//                    the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
//                   a partial match (unlike minChars, which defines
//                   how many characters are required to do any match
//                   at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
//                 Defaults to true.
//
// It's possible to pass in a custom function as the 'selector' 
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.

Autocompleter.Local = Class.create(Autocompleter.Base, {
  initialize: function(element, update, array, options) {
    this.baseInitialize(element, update, options);
    this.options.array = array;
  },

  getUpdatedChoices: function() {
    this.updateChoices(this.options.selector(this));
  },

  setOptions: function(options) {
    this.options = Object.extend({
      choices: 10,
      partialSearch: true,
      partialChars: 2,
      ignoreCase: true,
      fullSearch: false,
      selector: function(instance) {
        var ret       = []; // Beginning matches
        var partial   = []; // Inside matches
        var entry     = instance.getToken();
        var count     = 0;

        for (var i = 0; i < instance.options.array.length &&  
          ret.length < instance.options.choices ; i++) { 

          var elem = instance.options.array[i];
          var foundPos = instance.options.ignoreCase ? 
            elem.toLowerCase().indexOf(entry.toLowerCase()) : 
            elem.indexOf(entry);

          while (foundPos != -1) {
            if (foundPos == 0 && elem.length != entry.length) { 
              ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" + 
                elem.substr(entry.length) + "</li>");
              break;
            } else if (entry.length >= instance.options.partialChars && 
              instance.options.partialSearch && foundPos != -1) {
              if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
                partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
                  elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
                  foundPos + entry.length) + "</li>");
                break;
              }
            }

            foundPos = instance.options.ignoreCase ? 
              elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
              elem.indexOf(entry, foundPos + 1);

          }
        }
        if (partial.length)
          ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
        return "<ul>" + ret.join('') + "</ul>";
      }
    }, options || { });
  }
});

// AJAX in-place editor and collection editor
// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).

// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function(field) {
  setTimeout(function() {
    Field.activate(field);
  }, 1);
}

Ajax.InPlaceEditor = Class.create({
  initialize: function(element, url, options) {
    this.url = url;
    this.element = element = $(element);
    this.prepareOptions();
    this._controls = { };
    arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
    Object.extend(this.options, options || { });
    if (!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + '-inplaceeditor';
      if ($(this.options.formId))
        this.options.formId = '';
    }
    if (this.options.externalControl)
      this.options.externalControl = $(this.options.externalControl);
    if (!this.options.externalControl)
      this.options.externalControlOnly = false;
    this._originalBackground = this.element.getStyle('background-color') || 'transparent';
    this.element.title = this.options.clickToEditText;
    this._boundCancelHandler = this.handleFormCancellation.bind(this);
    this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
    this._boundFailureHandler = this.handleAJAXFailure.bind(this);
    this._boundSubmitHandler = this.handleFormSubmission.bind(this);
    this._boundWrapperHandler = this.wrapUp.bind(this);
    this.registerListeners();
  },
  checkForEscapeOrReturn: function(e) {
    if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
    if (Event.KEY_ESC == e.keyCode)
      this.handleFormCancellation(e);
    else if (Event.KEY_RETURN == e.keyCode)
      this.handleFormSubmission(e);
  },
  createControl: function(mode, handler, extraClasses) {
    var control = this.options[mode + 'Control'];
    var text = this.options[mode + 'Text'];
    if ('button' == control) {
      var btn = document.createElement('input');
      btn.type = 'submit';
      btn.value = text;
      btn.className = 'editor_' + mode + '_button';
      if ('cancel' == mode)
        btn.onclick = this._boundCancelHandler;
      this._form.appendChild(btn);
      this._controls[mode] = btn;
    } else if ('link' == control) {
      var link = document.createElement('a');
      link.href = '#';
      link.appendChild(document.createTextNode(text));
      link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
      link.className = 'editor_' + mode + '_link';
      if (extraClasses)
        link.className += ' ' + extraClasses;
      this._form.appendChild(link);
      this._controls[mode] = link;
    }
  },
  createEditField: function() {
    var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
    var fld;
    if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
      fld = document.createElement('input');
      fld.type = 'text';
      var size = this.options.size || this.options.cols || 0;
      if (0 < size) fld.size = size;
    } else {
      fld = document.createElement('textarea');
      fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
      fld.cols = this.options.cols || 40;
    }
    fld.name = this.options.paramName;
    fld.value = text; // No HTML breaks conversion anymore
    fld.className = 'editor_field';
    if (this.options.submitOnBlur)
      fld.onblur = this._boundSubmitHandler;
    this._controls.editor = fld;
    if (this.options.loadTextURL)
      this.loadExternalText();
    this._form.appendChild(this._controls.editor);
  },
  createForm: function() {
    var ipe = this;
    function addText(mode, condition) {
      var text = ipe.options['text' + mode + 'Controls'];
      if (!text || condition === false) return;
      ipe._form.appendChild(document.createTextNode(text));
    };
    this._form = $(document.createElement('form'));
    this._form.id = this.options.formId;
    this._form.addClassName(this.options.formClassName);
    this._form.onsubmit = this._boundSubmitHandler;
    this.createEditField();
    if ('textarea' == this._controls.editor.tagName.toLowerCase())
      this._form.appendChild(document.createElement('br'));
    if (this.options.onFormCustomization)
      this.options.onFormCustomization(this, this._form);
    addText('Before', this.options.okControl || this.options.cancelControl);
    this.createControl('ok', this._boundSubmitHandler);
    addText('Between', this.options.okControl && this.options.cancelControl);
    this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
    addText('After', this.options.okControl || this.options.cancelControl);
  },
  destroy: function() {
    if (this._oldInnerHTML)
      this.element.innerHTML = this._oldInnerHTML;
    this.leaveEditMode();
    this.unregisterListeners();
  },
  enterEditMode: function(e) {
    if (this._saving || this._editing) return;
    this._editing = true;
    this.triggerCallback('onEnterEditMode');
    if (this.options.externalControl)
      this.options.externalControl.hide();
    this.element.hide();
    this.createForm();
    this.element.parentNode.insertBefore(this._form, this.element);
    if (!this.options.loadTextURL)
      this.postProcessEditField();
    if (e) Event.stop(e);
  },
  enterHover: function(e) {
    if (this.options.hoverClassName)
      this.element.addClassName(this.options.hoverClassName);
    if (this._saving) return;
    this.triggerCallback('onEnterHover');
  },
  getText: function() {
    return this.element.innerHTML;
  },
  handleAJAXFailure: function(transport) {
    this.triggerCallback('onFailure', transport);
    if (this._oldInnerHTML) {
      this.element.innerHTML = this._oldInnerHTML;
      this._oldInnerHTML = null;
    }
  },
  handleFormCancellation: function(e) {
    this.wrapUp();
    if (e) Event.stop(e);
  },
  handleFormSubmission: function(e) {
    var form = this._form;
    var value = $F(this._controls.editor);
    this.prepareSubmission();
    var params = this.options.callback(form, value) || '';
    if (Object.isString(params))
      params = params.toQueryParams();
    params.editorId = this.element.id;
    if (this.options.htmlResponse) {
      var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
      Object.extend(options, {
        parameters: params,
        onComplete: this._boundWrapperHandler,
        onFailure: this._boundFailureHandler
      });
      new Ajax.Updater({ success: this.element }, this.url, options);
    } else {
      var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
      Object.extend(options, {
        parameters: params,
        onComplete: this._boundWrapperHandler,
        onFailure: this._boundFailureHandler
      });
      new Ajax.Request(this.url, options);
    }
    if (e) Event.stop(e);
  },
  leaveEditMode: function() {
    this.element.removeClassName(this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
    this.element.style.backgroundColor = this._originalBackground;
    this.element.show();
    if (this.options.externalControl)
      this.options.externalControl.show();
    this._saving = false;
    this._editing = false;
    this._oldInnerHTML = null;
    this.triggerCallback('onLeaveEditMode');
  },
  leaveHover: function(e) {
    if (this.options.hoverClassName)
      this.element.removeClassName(this.options.hoverClassName);
    if (this._saving) return;
    this.triggerCallback('onLeaveHover');
  },
  loadExternalText: function() {
    this._form.addClassName(this.options.loadingClassName);
    this._controls.editor.disabled = true;
    var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
    Object.extend(options, {
      parameters: 'editorId=' + encodeURIComponent(this.element.id),
      onComplete: Prototype.emptyFunction,
      onSuccess: function(transport) {
        this._form.removeClassName(this.options.loadingClassName);
        var text = transport.responseText;
        if (this.options.stripLoadedTextTags)
          text = text.stripTags();
        this._controls.editor.value = text;
        this._controls.editor.disabled = false;
        this.postProcessEditField();
      }.bind(this),
      onFailure: this._boundFailureHandler
    });
    new Ajax.Request(this.options.loadTextURL, options);
  },
  postProcessEditField: function() {
    var fpc = this.options.fieldPostCreation;
    if (fpc)
      $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
  },
  prepareOptions: function() {
    this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
    Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
    [this._extraDefaultOptions].flatten().compact().each(function(defs) {
      Object.extend(this.options, defs);
    }.bind(this));
  },
  prepareSubmission: function() {
    this._saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  registerListeners: function() {
    this._listeners = { };
    var listener;
    $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
      listener = this[pair.value].bind(this);
      this._listeners[pair.key] = listener;
      if (!this.options.externalControlOnly)
        this.element.observe(pair.key, listener);
      if (this.options.externalControl)
        this.options.externalControl.observe(pair.key, listener);
    }.bind(this));
  },
  removeForm: function() {
    if (!this._form) return;
    this._form.remove();
    this._form = null;
    this._controls = { };
  },
  showSaving: function() {
    this._oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    this.element.addClassName(this.options.savingClassName);
    this.element.style.backgroundColor = this._originalBackground;
    this.element.show();
  },
  triggerCallback: function(cbName, arg) {
    if ('function' == typeof this.options[cbName]) {
      this.options[cbName](this, arg);
    }
  },
  unregisterListeners: function() {
    $H(this._listeners).each(function(pair) {
      if (!this.options.externalControlOnly)
        this.element.stopObserving(pair.key, pair.value);
      if (this.options.externalControl)
        this.options.externalControl.stopObserving(pair.key, pair.value);
    }.bind(this));
  },
  wrapUp: function(transport) {
    this.leaveEditMode();
    // Can't use triggerCallback due to backward compatibility: requires
    // binding + direct element
    this._boundComplete(transport, this.element);
  }
});

Object.extend(Ajax.InPlaceEditor.prototype, {
  dispose: Ajax.InPlaceEditor.prototype.destroy
});

Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
  initialize: function($super, element, url, options) {
    this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
    $super(element, url, options);
  },

  createEditField: function() {
    var list = document.createElement('select');
    list.name = this.options.paramName;
    list.size = 1;
    this._controls.editor = list;
    this._collection = this.options.collection || [];
    if (this.options.loadCollectionURL)
      this.loadCollection();
    else
      this.checkForExternalText();
    this._form.appendChild(this._controls.editor);
  },

  loadCollection: function() {
    this._form.addClassName(this.options.loadingClassName);
    this.showLoadingText(this.options.loadingCollectionText);
    var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
    Object.extend(options, {
      parameters: 'editorId=' + encodeURIComponent(this.element.id),
      onComplete: Prototype.emptyFunction,
      onSuccess: function(transport) {
        var js = transport.responseText.strip();
        if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
          throw 'Server returned an invalid collection representation.';
        this._collection = eval(js);
        this.checkForExternalText();
      }.bind(this),
      onFailure: this.onFailure
    });
    new Ajax.Request(this.options.loadCollectionURL, options);
  },

  showLoadingText: function(text) {
    this._controls.editor.disabled = true;
    var tempOption = this._controls.editor.firstChild;
    if (!tempOption) {
      tempOption = document.createElement('option');
      tempOption.value = '';
      this._controls.editor.appendChild(tempOption);
      tempOption.selected = true;
    }
    tempOption.update((text || '').stripScripts().stripTags());
  },

  checkForExternalText: function() {
    this._text = this.getText();
    if (this.options.loadTextURL)
      this.loadExternalText();
    else
      this.buildOptionList();
  },

  loadExternalText: function() {
    this.showLoadingText(this.options.loadingText);
    var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
    Object.extend(options, {
      parameters: 'editorId=' + encodeURIComponent(this.element.id),
      onComplete: Prototype.emptyFunction,
      onSuccess: function(transport) {
        this._text = transport.responseText.strip();
        this.buildOptionList();
      }.bind(this),
      onFailure: this.onFailure
    });
    new Ajax.Request(this.options.loadTextURL, options);
  },

  buildOptionList: function() {
    this._form.removeClassName(this.options.loadingClassName);
    this._collection = this._collection.map(function(entry) {
      return 2 === entry.length ? entry : [entry, entry].flatten();
    });
    var marker = ('value' in this.options) ? this.options.value : this._text;
    var textFound = this._collection.any(function(entry) {
      return entry[0] == marker;
    }.bind(this));
    this._controls.editor.update('');
    var option;
    this._collection.each(function(entry, index) {
      option = document.createElement('option');
      option.value = entry[0];
      option.selected = textFound ? entry[0] == marker : 0 == index;
      option.appendChild(document.createTextNode(entry[1]));
      this._controls.editor.appendChild(option);
    }.bind(this));
    this._controls.editor.disabled = false;
    Field.scrollFreeActivate(this._controls.editor);
  }
});

//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
//**** This only  exists for a while,  in order to  let ****
//**** users adapt to  the new API.  Read up on the new ****
//**** API and convert your code to it ASAP!            ****

Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
  if (!options) return;
  function fallback(name, expr) {
    if (name in options || expr === undefined) return;
    options[name] = expr;
  };
  fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
    options.cancelLink == options.cancelButton == false ? false : undefined)));
  fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
    options.okLink == options.okButton == false ? false : undefined)));
  fallback('highlightColor', options.highlightcolor);
  fallback('highlightEndColor', options.highlightendcolor);
};

Object.extend(Ajax.InPlaceEditor, {
  DefaultOptions: {
    ajaxOptions: { },
    autoRows: 3,                                // Use when multi-line w/ rows == 1
    cancelControl: 'link',                      // 'link'|'button'|false
    cancelText: 'cancel',
    clickToEditText: 'Click to edit',
    externalControl: null,                      // id|elt
    externalControlOnly: false,
    fieldPostCreation: 'activate',              // 'activate'|'focus'|false
    formClassName: 'inplaceeditor-form',
    formId: null,                               // id|elt
    highlightColor: '#ffff99',
    highlightEndColor: '#ffffff',
    hoverClassName: '',
    htmlResponse: true,
    loadingClassName: 'inplaceeditor-loading',
    loadingText: 'Loading...',
    okControl: 'button',                        // 'link'|'button'|false
    okText: 'ok',
    paramName: 'value',
    rows: 1,                                    // If 1 and multi-line, uses autoRows
    savingClassName: 'inplaceeditor-saving',
    savingText: 'Saving...',
    size: 0,
    stripLoadedTextTags: false,
    submitOnBlur: false,
    textAfterControls: '',
    textBeforeControls: '',
    textBetweenControls: ''
  },
  DefaultCallbacks: {
    callback: function(form) {
      return Form.serialize(form);
    },
    onComplete: function(transport, element) {
      // For backward compatibility, this one is bound to the IPE, and passes
      // the element directly.  It was too often customized, so we don't break it.
      new Effect.Highlight(element, {
        startcolor: this.options.highlightColor, keepBackgroundImage: true });
    },
    onEnterEditMode: null,
    onEnterHover: function(ipe) {
      ipe.element.style.backgroundColor = ipe.options.highlightColor;
      if (ipe._effect)
        ipe._effect.cancel();
    },
    onFailure: function(transport, ipe) {
      alert('Error communication with the server: ' + transport.responseText.stripTags());
    },
    onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
    onLeaveEditMode: null,
    onLeaveHover: function(ipe) {
      ipe._effect = new Effect.Highlight(ipe.element, {
        startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
        restorecolor: ipe._originalBackground, keepBackgroundImage: true
      });
    }
  },
  Listeners: {
    click: 'enterEditMode',
    keydown: 'checkForEscapeOrReturn',
    mouseover: 'enterHover',
    mouseout: 'leaveHover'
  }
});

Ajax.InPlaceCollectionEditor.DefaultOptions = {
  loadingCollectionText: 'Loading options...'
};

// Delayed observer, like Form.Element.Observer, 
// but waits for delay after last key input
// Ideal for live-search fields

Form.Element.DelayedObserver = Class.create({
  initialize: function(element, delay, callback) {
    this.delay     = delay || 0.5;
    this.element   = $(element);
    this.callback  = callback;
    this.timer     = null;
    this.lastValue = $F(this.element); 
    Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
  },
  delayedListener: function(event) {
    if(this.lastValue == $F(this.element)) return;
    if(this.timer) clearTimeout(this.timer);
    this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
    this.lastValue = $F(this.element);
  },
  onTimerEvent: function() {
    this.timer = null;
    this.callback(this.element, $F(this.element));
  }
});
// JavaScript Document
var map_2_0,map_UTM_Obj;
var layer_base_chile,layer_rutas,layer_satelite_chile,layer_guia_chile, layer_label_chile,layer_base_chile_ov,layer_label_comunas_chile,layer_label_comunas_mexico;
var layer_base_argentina,layer_base_brasil,layer_base_mexico,layer_redbank;
var markers_fotos, markers_busqueda,markers_post, markers_publicidad,win_foto,win_post,win_celular,markers_servicios,markers_info,markers_distancia;
var idCiudad;
var popup_medicion;
var popup_publicidada_hars
var popup_busqueda;
var popup_busqueda2;
var popupFotoDir;
var markers_publicidades,markers_servipag;
var v_numZoomLevels,v_maxResolution,x_left,y_bottom,x_right,y_top;
var id_timeout,id_timeout2,id_timeout_pub,id_timeout_pub_close,click_icono=false;
var ctlMousePosition,idCiudad;
var actualScale,id_icono_tooltip,existe_tooltip_pendiente,icon_object;
var lonlat_medicion,data_medicion,opt_print;
var lonlat_publicidad='',lonlat_servicio='',singleTile_const,estado_controles,controls_map_2_0;
var desactivarControl=false;
var camaraEncendida=true;
var srid;
var fac_x;
var fac_y;
var street,puntoStreet;
var controlStreet,controlline,controlpoly;
estado_controles='drag';
var sobreCruz=false,sobreCruzPolygon,sobrePaneo=false;
var idActualControl;
var blogState=false; 
var blogIn=false;
var fotos_cargadas=0;
var jg,jg_ruta;
var puntoAntX = new Array();
var puntoAntY = new Array();
var puntoAntXcoord = new Array();
var puntoAntYcoord = new Array();
var puntoAntX_ruta = new Array();
var puntoAntY_ruta = new Array();
var puntoAntXcoord_ruta = new Array();
var puntoAntYcoord_ruta = new Array();
var arrIdToolTips = new Array();
var layersBase2MapFile="";
var sDisplayTimer = null;
var inicio=true;

function stopTimer2() {
	 clearTimeout(sDisplayTimer);
}

var finLinea;
var xmin,ymin,xmax,ymax;
var mapFilePrinter; // Se define map file para impresion

var zIndexMapa=10;
var zIndexRutaCanvas=750;
var zIndexFotos=760;
var zIndexServicios=760;
var zIndexPublicidad=770;
var zIndexEstrella=780;

var zIndexCanvasMedicion=800;
var zIndexFlechas=810;
var zIndexHerramientas=820;
var zIndexWinPrototype=1830;
var zIndexToolTps=840;

var proxy ="http://mapa1.mapcity.com/fcgi-bin";
var proxy1="http://mapa2.mapcity.com/fcgi-bin";
var proxy2="http://mapa3.mapcity.com/fcgi-bin";
var proxy3="http://mapa4.mapcity.com/fcgi-bin";
var ovActivo=false;

var guia_open=false;
function MM_preloadImages() { //v3.0
  var d=document;
	if(d.images){ 
		if(!d.MM_p){ 
			d.MM_p=new Array();
		}
		var i,j=d.MM_p.length,a=MM_preloadImages.arguments; 
		for(i=0; i<a.length; i++){
			if (a[i].indexOf("#")!=0){ 
				d.MM_p[j]=new Image; 
				d.MM_p[j++].src=a[i];
			}
		}
	}
}

function init_2_0(idCity){
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
	MM_preloadImages();
	switch ($('ciudad').value) 
	{ 
		case "baires" : 
			srid = 22195;
			fac_x = 0;
			fac_y = 0;
			mapFilePrinter = "argentina_tiled_printer.map";
			break;
		case "riojaneiro" : 
			srid = 29183;
			fac_x = 0;
			fac_y = 0;
			mapFilePrinter = "brasil_tiled_printer.map";
			break; 
		case "saopaulo" : 
			srid = 22523;
			fac_x = 0;
			fac_y = 0;
			mapFilePrinter = "brasil_tiled_printer.map";
			break; 
		case "mexicodf" : 
			srid = 32614;
			fac_x = 0;
			fac_y = 0;
			mapFilePrinter = "mexico_tiled_printer.map";
			break; 
		case "lima" : 
			srid = 32718;
			fac_x = 0;
			fac_y = 0;
			mapFilePrinter = "peru_tiled_printer.map";
			break; 
		default : 
			srid = 29179;
			fac_x = -62;
			fac_y = -40;
			mapFilePrinter = "chile_tiled_printer.map";
	}

	idCiudad = idCity;
	
	init_map();	
	
	init_tools('map_2_0');
	addFlechas('map_2_0');
	addCamara('map_2_0');
	//Inicializaci&oacute;n de elementos sobre el mapa
	addImage('mapcity_2_0/images/flecha_NORTE.gif','norte','map_2_0');
	addImage('images/LogoMapcity3.gif','logo','map_2_0');
	eventos(); //evento de boton ventana overview
	//addLoadEvent();
//	setTimeout("puntosActivos();", 3000);

}

//-----------------------init_map----------------------
//Funci?n que inicializa el mapa y las diferentes capas
//--------------------------------------------------------
function init_map(){
	var x_left,y_bottom,x_right,y_top;
	var v_maxResolutionDeg,v_maxResolutionPx;


	size=new OpenLayers.Size(500,500);
	sizeOverview=new OpenLayers.Size(200,200);
	//	Opciones del Mapa que se va a crear
	//	maxExtent: new OpenLayers.Bounds(-100.58170678, -57.89023087, -99.05026778, 21.82700252)
	if ((navigator.userAgent.indexOf('MSIE 6.0') > -1)
	||(navigator.userAgent.indexOf('MSIE 5.0') >-1)
	||(navigator.userAgent.indexOf('MSIE 4.0') >-1)
	||(navigator.userAgent.indexOf('MSIE 3.0') >-1)){
		singleTile_const=true;
	}else{
		singleTile_const=false;
	}

	OpenLayers.Util.MISSING_TILE_URL = "/images/none.png";
	OpenLayers.Util.onImageLoadError = function() {
		this.src = OpenLayers.Util.MISSING_TILE_URL;
	};

	OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
	OpenLayers.Util.onImageLoadErrorColor = "transparent";

	switch(idCiudad){
		//santiago
		case 1:
			//alert('aa');
			x_left   = -91.04770;
			y_bottom = -58.0000;
			x_right  = -43.23819;
			y_top    = -16.95350;
			v_numZoomLevels = 14;
			v_maxResolutionDeg = 2;
			v_maxResolutionPx = 2048;
			v_maxResolution = 0.07902398403828125;
			//v_maxResolutionDeg / v_maxResolutionPx;
			map_2_0 = new OpenLayers.Map( $('map_2_0'),
			{
				controls: [
					new OpenLayers.Control.PanZoomBar(),
					new OpenLayers.Control.Navigation({zoomWheelEnabled:false})
				]
				/*controls: [
					new OpenLayers.Control.MouseDefaults(),
					new OpenLayers.Control.PanZoomBar()
				]*/
				,maxResolution: v_maxResolution
				,tileSize:new OpenLayers.Size(400,400)
				,maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top)
				,numZoomLevels:v_numZoomLevels
			});
			
			//map_2_0.addControl(new OpenLayers.Control.MousePosition());
			//map_2_0.addControl(new OpenLayers.Control.ScaleLine());
			//map_2_0.addControl(new OpenLayers.Control.Navigation({zoomWheelEnabled:false}));
			
			opt_print ={
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					controls: [new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Scale()]
					,buffer:0
					,numZoomLevels: v_numZoomLevels
					,maxResolution: v_maxResolution
					,tileSize:size
			};


			layer_base_chile =  new OpenLayers.Layer.TileCache( "Chile",
						[
						"http://mapa1.mapcity.com/tiles/2_0/"
						,"http://mapa2.mapcity.com/tiles/2_0/"
						,"http://mapa3.mapcity.com/tiles/2_0/"
						,"http://mapa4.mapcity.com/tiles/2_0/"
						]
						,'chile_base'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/jpeg'}
						);
			
			
			layer_base_chile_ov =  new OpenLayers.Layer.TileCache( "Chile OV",
						[
						"http://mapa1.mapcity.com/tiles/2_0/"
						,"http://mapa2.mapcity.com/tiles/2_0/"
						,"http://mapa3.mapcity.com/tiles/2_0/"
						,"http://mapa4.mapcity.com/tiles/2_0/"
						]
						,'chile_base'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/jpeg'}
					
			);
			
			map_2_0.addLayers([layer_base_chile]);

			layer_base_chile.setIsBaseLayer(true);
			layer_base_chile.setVisibility(true);

			// Over View
			ovMap = new OpenLayers.Control.OverviewMap({
				size:sizeOverview, 
				minRatio: 10,
				maxRatio: 50,
				mapOptions:{
					maxResolution: v_maxResolution,
					tileSize:new OpenLayers.Size(400,400),
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					numZoomLevels:v_numZoomLevels
				}, 
				layers:[layer_base_chile_ov]
			})
			map_2_0.addControl(ovMap);
			
			break;
	
		//vregion
		case 2:
			//alert('aa');
			x_left   = -91.04770;
			y_bottom = -58.0000;
			x_right  = -43.23819;
			y_top    = -16.95350;
			v_numZoomLevels = 14;
			v_maxResolutionDeg = 2;
			v_maxResolutionPx = 2048;
			v_maxResolution = 0.07902398403828125;
			//v_maxResolutionDeg / v_maxResolutionPx;
			map_2_0 = new OpenLayers.Map( $('map_2_0'),
			{
				controls: [
					new OpenLayers.Control.PanZoomBar(),
					new OpenLayers.Control.Navigation({zoomWheelEnabled:false})
				]
				/*controls: [
					new OpenLayers.Control.MouseDefaults(),
					new OpenLayers.Control.PanZoomBar()
				]*/
				,maxResolution: v_maxResolution
				,tileSize:new OpenLayers.Size(400,400)
				,maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top)
				,numZoomLevels:v_numZoomLevels
			});
			
			//map_2_0.addControl(new OpenLayers.Control.MousePosition());
			//map_2_0.addControl(new OpenLayers.Control.ScaleLine());
			//map_2_0.addControl(new OpenLayers.Control.Navigation({zoomWheelEnabled:false}));
			
			opt_print ={
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					controls: [new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Scale()]
					,buffer:0
					,numZoomLevels: v_numZoomLevels
					,maxResolution: v_maxResolution
					,tileSize:size
			};

			layer_base_chile =  new OpenLayers.Layer.TileCache( "VMap0",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'chile_base'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/jpeg'}
						);
			map_2_0.addLayers([layer_base_chile]);
			layer_base_chile.setIsBaseLayer(true);
			layer_base_chile.setVisibility(true);

			layer_base_chile_ov =  new OpenLayers.Layer.TileCache( "Chile OV",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'chile_base'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/jpeg'}
					
			);

			// Over View
			ovMap = new OpenLayers.Control.OverviewMap({
				size:sizeOverview, 
				minRatio: 10,
				maxRatio: 50,
				mapOptions:{
					maxResolution: v_maxResolution,
					tileSize:new OpenLayers.Size(400,400),
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					numZoomLevels:v_numZoomLevels
				}, 
				layers:[layer_base_chile_ov]
			})
			map_2_0.addControl(ovMap);

			break;
			
		//baires
		case 3:
			v_numZoomLevels = 9;//7;25
			v_maxResolutionDeg = 2;//0.6;300
			v_maxResolutionPx = 2048;
			v_maxResolution = v_maxResolutionDeg / v_maxResolutionPx;
			
			x_left   = -58.97719;
			y_bottom = -35.10000;
			x_right  = -58.00086;
			y_top    = -34.30000;


			//x_left   = -76.0199836653;
			//y_bottom = -56.2163458289;
			//x_right  = -66.8402961623;
			//y_top    = -17.4712286414;
			map_2_0 = new OpenLayers.Map( $('map_2_0'),
			{
				controls: [
					new OpenLayers.Control.PanZoomBar(),
					new OpenLayers.Control.Navigation({zoomWheelEnabled:false})
				]
				/*controls: [
					new OpenLayers.Control.MouseDefaults(),
					new OpenLayers.Control.PanZoomBar()
				]*/
				,maxResolution: v_maxResolution
				,tileSize:new OpenLayers.Size(400,400)
				,maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top)
				,numZoomLevels:v_numZoomLevels
			});
			
			//map_2_0.addControl(new OpenLayers.Control.MousePosition());
			//map_2_0.addControl(new OpenLayers.Control.ScaleLine());
			//map_2_0.addControl(new OpenLayers.Control.Navigation({zoomWheelEnabled:false}));
			
			opt_print ={
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					controls: [new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Scale()]
					,buffer:0
					,numZoomLevels: v_numZoomLevels
					,maxResolution: v_maxResolution
					,tileSize:size
			};
			//Capa Base del Mapa
		
			// Argentina 

			layersBase2MapFile='Boundaries,Park,Hidrography,Calles,Avenidas,Autopistas,america,bound_limit';
			
			layer_base_argentina = new OpenLayers.Layer.TileCache( "Argentina",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'ba_base'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'}
			);
			
	
			map_2_0.addLayers([layer_base_argentina]);//,layer_label_comunas_argentina]);
	
			layer_base_argentina.setIsBaseLayer(true);
	
			layer_base_argentina.setVisibility(false);
			
			layer_base_argentina_ov =  new OpenLayers.Layer.TileCache( "Argentina OV",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'ba_base'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'}
					
			);

			// Over View
			ovMap = new OpenLayers.Control.OverviewMap({
				size:sizeOverview, 
				minRatio: 10,
				maxRatio: 50,
				mapOptions:{
					maxResolution: v_maxResolution,
					tileSize:new OpenLayers.Size(400,400),
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					numZoomLevels:v_numZoomLevels
				}, 
				layers:[layer_base_argentina_ov]
			})
			map_2_0.addControl(ovMap);

			break;
			
		//saopaulo
		case 4:
			v_numZoomLevels = 7;
			v_maxResolutionDeg = 2;
			v_maxResolutionPx = 2048;
			v_maxResolution = v_maxResolutionDeg / v_maxResolutionPx;
			
			/*x_left	 = -46.8196429421;
			y_bottom = -24.0229411449;
			x_right  = -46.3609637429;
			y_top	 = -23.3637614574;*/
			
			x_left	 = -47.03757;
			y_bottom = -23.89144;
			x_right  = -46.26054;
			y_top	 = -23.39359;
			
			map_2_0 = new OpenLayers.Map( $('map_2_0'),
			{
				controls: [
					new OpenLayers.Control.PanZoomBar(),
					new OpenLayers.Control.Navigation({zoomWheelEnabled:false})
				]
				/*controls: [
					new OpenLayers.Control.MouseDefaults(),
					new OpenLayers.Control.PanZoomBar()
				]*/
				,maxResolution: v_maxResolution
				,tileSize:new OpenLayers.Size(400,400)
				,maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top)
				,numZoomLevels:v_numZoomLevels
			});
			
			//map_2_0.addControl(new OpenLayers.Control.MousePosition());
			//map_2_0.addControl(new OpenLayers.Control.ScaleLine());
			//map_2_0.addControl(new OpenLayers.Control.Navigation({zoomWheelEnabled:false}));
			
			opt_print ={
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					controls: [new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Scale()]
					,buffer:0
					,numZoomLevels: v_numZoomLevels
					,maxResolution: v_maxResolution
					,tileSize:size
			};

		  	// Brasil
			layer_base_brasil_sao = new OpenLayers.Layer.TileCache( "Sao Paulo",
			[
			 "http://mapa1.mapcity.com/tiles/"
			,"http://mapa2.mapcity.com/tiles/"
			,"http://mapa3.mapcity.com/tiles/"
			,"http://mapa4.mapcity.com/tiles/"
			]
			,'brasil_saobase'
			,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'} );

			map_2_0.addLayers([layer_base_brasil_sao]);
			layer_base_brasil_sao.setIsBaseLayer(true);				
			layer_base_brasil_sao.setVisibility(false);

			layer_base_brasil_sao_ov =  new OpenLayers.Layer.TileCache( "Sao Paulo OV",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'brasil_saobase'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'}
					
			);

			// Over View
			ovMap = new OpenLayers.Control.OverviewMap({
				size:sizeOverview, 
				minRatio: 10,
				maxRatio: 50,
				mapOptions:{
					maxResolution: v_maxResolution,
					tileSize:new OpenLayers.Size(400,400),
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					numZoomLevels:v_numZoomLevels
				}, 
				layers:[layer_base_brasil_sao_ov]
			})
			map_2_0.addControl(ovMap);

			break;
			
		//riojaneiro
		case 5:
			v_numZoomLevels = 9;
			v_maxResolutionDeg = 2;
			v_maxResolutionPx = 2048;
			v_maxResolution = v_maxResolutionDeg / v_maxResolutionPx;
			
			/*
			x_left   = -43.8;
			y_bottom = -23.1;
			x_right  = -43.5;
			y_top	 = -23;
			*/
			
			
			x_left   = -43.79771;
			y_bottom = -23.07949;

			x_right  = -43.14746;
			y_top	 = -22.80187;
			
			map_2_0 = new OpenLayers.Map( $('map_2_0'),
			{
				controls: [
					new OpenLayers.Control.PanZoomBar(),
					new OpenLayers.Control.Navigation({zoomWheelEnabled:false})
				]
				/*controls: [
					new OpenLayers.Control.MouseDefaults(),
					new OpenLayers.Control.PanZoomBar()
				]*/
				,maxResolution: v_maxResolution
				,tileSize:new OpenLayers.Size(400,400)
				,maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top)
				,numZoomLevels:v_numZoomLevels
			});
			
			//map_2_0.addControl(new OpenLayers.Control.MousePosition());
			//map_2_0.addControl(new OpenLayers.Control.ScaleLine());
			//map_2_0.addControl(new OpenLayers.Control.Navigation({zoomWheelEnabled:false}));
			
			opt_print ={
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					controls: [new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Scale()]
					,buffer:0
					,numZoomLevels: v_numZoomLevels
					,maxResolution: v_maxResolution
					,tileSize:size
			};
		  // Brasil
			layer_base_brasil = new OpenLayers.Layer.TileCache( "VMap0",
			[
			 "http://mapa1.mapcity.com/tiles/"
			,"http://mapa2.mapcity.com/tiles/"
			,"http://mapa3.mapcity.com/tiles/"
			,"http://mapa4.mapcity.com/tiles/"
			]
			,'brasil_riobase_png'
			,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'} );
		  
			layer_base_brasil_ov = new OpenLayers.Layer.WMS( "Brasil OV",
				proxy+"/mapserv?map=/var/www/mapcity_2_0/map/brasil_tiled_ov.map",
				{layers: 'Boundaries,Park,Elevation,Calles,Avenidas,Autopistas,america,bound_limit',format: 'image/jpeg'}
				,{singleTile:true,buffer:0});

			map_2_0.addLayers([layer_base_brasil]);
			layer_base_brasil.setIsBaseLayer(true);				

			layer_base_brasil.setVisibility(false);

			layer_base_brasil_rio_ov =  new OpenLayers.Layer.TileCache( "Rio OV",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'brasil_riobase_png'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'}
					
			);

			// Over View
			ovMap = new OpenLayers.Control.OverviewMap({
				size:sizeOverview, 
				minRatio: 10,
				maxRatio: 50,
				mapOptions:{
					maxResolution: v_maxResolution,
					tileSize:new OpenLayers.Size(400,400),
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					numZoomLevels:v_numZoomLevels
				}, 
				layers:[layer_base_brasil_rio_ov]
			})
			map_2_0.addControl(ovMap);

			break;
		case 6:
			v_numZoomLevels = 8;
			v_maxResolutionDeg = 2;
			v_maxResolutionPx = 2048;
			v_maxResolution = v_maxResolutionDeg / v_maxResolutionPx;
			x_left	 = -101.40028;
			y_bottom =  18.03785;
			x_right  = -98.26161;
			y_top	 =  20.64918;

			map_2_0 = new OpenLayers.Map( $('map_2_0'),
			{
				controls: [
					new OpenLayers.Control.PanZoomBar(),
					new OpenLayers.Control.Navigation({zoomWheelEnabled:false})
				]
				/*controls: [
					new OpenLayers.Control.MouseDefaults(),
					new OpenLayers.Control.PanZoomBar()
				]*/
				,maxResolution: v_maxResolution
				,tileSize:new OpenLayers.Size(400,400)
				,maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top)
				,numZoomLevels:v_numZoomLevels
			});
			
			//map_2_0.addControl(new OpenLayers.Control.MousePosition());
			//map_2_0.addControl(new OpenLayers.Control.ScaleLine());
			//map_2_0.addControl(new OpenLayers.Control.Navigation({zoomWheelEnabled:false}));
			
			opt_print ={
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					controls: [new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Scale()]
					,buffer:0
					,numZoomLevels: v_numZoomLevels
					,maxResolution: v_maxResolution
					,tileSize:size
			};
			//Capa Base del Mapa			
			// Mexico
			layersBase2MapFile='Boundaries,Calles,Avenidas,bound_limit';
			layer_base_mexico = new OpenLayers.Layer.TileCache( "Mexico",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'mexico_base_png'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'}
			);
	
			map_2_0.addLayers([layer_base_mexico]);//,layer_label_comunas_mexico]);
			
			layer_base_mexico.setIsBaseLayer(true);				
			layer_base_mexico.setVisibility(false);
			
			layer_base_mexico_ov =  new OpenLayers.Layer.TileCache( "Mexico OV",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'mexico_base_png'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'}
					
			);

			// Over View
			ovMap = new OpenLayers.Control.OverviewMap({
				size:sizeOverview, 
				minRatio: 10,
				maxRatio: 50,
				mapOptions:{
					maxResolution: v_maxResolution,
					tileSize:new OpenLayers.Size(400,400),
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					numZoomLevels:v_numZoomLevels
				}, 
				layers:[layer_base_mexico_ov]
			})
			map_2_0.addControl(ovMap);

			break;			
		//Peru
		case 7:
			v_numZoomLevels = 9;
			v_maxResolutionDeg = 2;
			v_maxResolutionPx = 2048;
			v_maxResolution = v_maxResolutionDeg / v_maxResolutionPx;
			x_left	 = -77.24;
			y_bottom =  -12.35;
			x_right  = -76.27;
			y_top	 =  -11.38;

			map_2_0 = new OpenLayers.Map( $('map_2_0'),
			{
				controls: [
					new OpenLayers.Control.PanZoomBar(),
					new OpenLayers.Control.Navigation({zoomWheelEnabled:false})
				]
				/*controls: [
					new OpenLayers.Control.MouseDefaults(),
					new OpenLayers.Control.PanZoomBar()
				]*/
				,maxResolution: v_maxResolution
				,tileSize:new OpenLayers.Size(400,400)
				,maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top)
				,numZoomLevels:v_numZoomLevels
			});
			
			//map_2_0.addControl(new OpenLayers.Control.MousePosition());
			//map_2_0.addControl(new OpenLayers.Control.ScaleLine());
			//map_2_0.addControl(new OpenLayers.Control.Navigation({zoomWheelEnabled:false}));
			
			opt_print ={
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					controls: [new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Scale()]
					,buffer:0
					,numZoomLevels: v_numZoomLevels
					,maxResolution: v_maxResolution
					,tileSize:size
			};
			//Capa Base del Mapa			
			// Peru
			layersBase2MapFile='Boundaries,Park,Lakes,Calles,Avenidas,america,bound_limit';
			layer_base_peru = new OpenLayers.Layer.TileCache( "Peru",
			[
			 "http://mapa1.mapcity.com/tiles/"
			,"http://mapa2.mapcity.com/tiles/"
			,"http://mapa3.mapcity.com/tiles/"
			,"http://mapa4.mapcity.com/tiles/"
			]
			,'peru_base_png'
			,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'} );

			map_2_0.addLayers([layer_base_peru]);//,layer_label_comunas_peru]);
			layer_base_peru.setIsBaseLayer(true);
			layer_base_peru.setVisibility(false);
			
			layer_base_peru_ov =  new OpenLayers.Layer.TileCache( "Chile OV",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'peru_base_png'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'}
					
			);

			// Over View
			ovMap = new OpenLayers.Control.OverviewMap({
				size:sizeOverview, 
				minRatio: 10,
				maxRatio: 50,
				mapOptions:{
					maxResolution: v_maxResolution,
					tileSize:new OpenLayers.Size(400,400),
					maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top),
					numZoomLevels:v_numZoomLevels
				}, 
				layers:[layer_base_peru_ov]
			})
			map_2_0.addControl(ovMap);

			break;	

	}


	OpenLayers.Feature.Vector.style['default']['fillColor'] = '#FF0000';
	OpenLayers.Feature.Vector.style['default']['strokeColor'] = '#FF0000';
	OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '3';
	OpenLayers.Feature.Vector.style['default']['strokeOpacity'] = '0.5';
	OpenLayers.Feature.Vector.style['default']['strokeLinecap'] = 'round';
	OpenLayers.Feature.Vector.style['default']['pointRadius'] = '0';

	loadControl('map_2_0');	

	centerMap(v_numZoomLevels);
	
	$$('.olControlOverviewMapExtentRectangle').each(function(elem){
		elem.setStyle({
			background:'#FFAAAA',
			opacity:'0.6',
			border:'2px #FF0000 solid'
		});
	});
	$$('.olControlOverviewMapElement').each(function(elem){
		elem.setStyle({
			background:'#666666',
			border:'4px #FFFFFF solid'
		});
	});
	$$('.olControlOverviewMapMaximizeButton').each(function(elem){
		elem.setStyle({
			top:'-22px',
			border:'#AAAAAA 0px solid'
		});
	});
	$$('.olControlOverviewMapMinimizeButton').each(function(elem){
		elem.setStyle({
			top:'210px',
			//border:'#AAAAAA 2px solid'
			border:'none'
		});
	});

	//REGISTRO DE EVENTOS SOBRE EL MAPA
	map_2_0.events.register("click", map_2_0, function(e) {
		
		clearTimeout(id_timeout);
		if($('serv_tooltip')) cerrar_label('serv_tooltip');
		if($('pub_tooltip')) cerrar_label('pub_tooltip');
		if($('busq_tooltip')) cerrar_label('busq_tooltip');
		if($('busq_tooltip2')) cerrar_label('busq_tooltip2');

		if (estado_controles=='zoomout' && !sobrePaneo){
			map_2_0.zoomOut();
		}
		click_icono=false;

		map_2_0.events.register("click", map_2_0, function(e) {return false;});
	});

	map_2_0.events.register("movestart", map_2_0, function(e) {
		clearTimeout(id_timeout);
		removeLabels();
		resetJGRuta();
		resetJGMedicion();
		finLinea = false;
		if(popup_medicion){
			map_2_0.removePopup(popup_medicion);
		}

		map_2_0.events.register("movestart", map_2_0, function(e) {return false;});
	});

	
	map_2_0.events.register("moveend", map_2_0, function(e) 
	{
		//alert(camaraEncendida);
//		if (!inicio)
//		{
			addScalebar(map_2_0.getScale());
			//addLabelMedicion();
			if ($('id_tooltip_foto')) {
				cerrar_label('id_tooltip_foto');
			}
			
			if ($('Producto').value != "COMERCIO") {
				if (camaraEncendida) {
					//init_publicidad('recuperarPublicidad.asp');
					init_publicidad('recuperarPublicidadDinamica.asp');
					init_fotos();
				}
			}
			else {
				$('camaraFoto').update('<img src="/mapcity_2_0/images/utilidades/camara_foto_off.png" title="Enciende capa de fotografias" style="z-index: 10000; width: 24px; height: 21px; cursor:hand;"/><span  class="arial-11-bld" style="top: -5px; position:relative;">&nbsp;Activar&nbsp;Puntos</span>');
			}
			

			if (!guia_open)	{
				redibujarServicios();
			}
//		}
		
		inicio=false;
		if (map_2_0.getLayersByName("layer_callesn").length > 0 ) {
				var laySn = map_2_0.getLayersByName("layer_callesn");
				if(featureSN) {
					laySn[0].removeFeatures(laySn[0].features);
					laySn[0].addFeatures([featureSN]);
				}
			}
			
		if(map_2_0.getScale() > 50000 && map_2_0.getLayersByName("transito").length > 0){
			 layer_transito.setVisibility(false);
		}else if(map_2_0.getLayersByName("transito").length > 0){
			 layer_transito.setVisibility(true);
		}
		
		map_2_0.events.register("moveend", map_2_0, function(e) {return false;});
		
		if(idCiudad == 1){
			muestraComunaCalzada('CL');
		} else if(idCiudad == 3){
			muestraComunaCalzada('AR');
		} else if(idCiudad == 7){
			muestraComunaCalzada('PE');
		} else if(idCiudad == 6){
			muestraComunaCalzada('MX');
		}
	});
	
	map_2_0.events.register("mouseup", map_2_0, function(e) { 
		if($('mousePosition') && !ovActivo){
			var position = this.events.getMousePosition(e);
			var lonlat = map_2_0.getLonLatFromLayerPx(new OpenLayers.Pixel(position.x,position.y));
			if(lonlat){
				var lon = new Number(lonlat.lon);
				var lat = new Number(lonlat.lat);			
				$('mousePosition').update('Lon:'+lon.toFixed(5)+' Lat:'+lat.toFixed(5));
			}
		}else{
			if($('mousePosition')) $('mousePosition').setStyle({'display': 'none'});
		}
		map_2_0.events.register("mousemove", map_2_0, function(e) {return false;});
	});	
	
}

var markers = [];

function muestraComunaCalzada(pais){
	if(map_2_0.getLayersByName("ComunasExtent").length!=0){
		map_2_0.getLayersByName("ComunasExtent")[0].clearMarkers();
//	 for(var i =0; i< markers.length;i++)
//		map_2_0.getLayersByName("ComunasExtent")[0].removeMarker(markers[i]);
	}
          var opt={ method:'post',onComplete:function(transport){
                var comerciosLayer;
                var objJSON = transport.responseText.evalJSON();
                if(objJSON.status == 200){
                if(map_2_0.getLayersByName("ComunasExtent").length==0){
                    comerciosLayer = new OpenLayers.Layer.Markers("ComunasExtent");
                    map_2_0.addLayer(comerciosLayer);
                }else{
                    comerciosLayer = map_2_0.getLayersByName("ComunasExtent")[0];
                }
		
                objJSON.comunas.each(function(comuna){
                    var w = comuna.nombre.length * 25;
                    var h = 50 ;
                    var lonlat = new OpenLayers.LonLat(comuna.longitud,comuna.latitud);
                    var sizeIcon = new OpenLayers.Size(w,h);
                    var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
                    var iconObj = new OpenLayers.Icon(comuna.foto,sizeIcon,offset);
                    var markerObj = new OpenLayers.Marker(lonlat,iconObj);
                    comerciosLayer.addMarker(markerObj);
                    markerObj.setOpacity(0.5);
		    markers.push(markerObj);
                });
	       }
            },onFailure:function(){}
        };

	var objBound = map_2_0.getExtent();
        if(map_2_0.getScale()<85000)
          new Ajax.Request('labelComunas.asp?xmin='+objBound.left+'&ymin='+objBound.bottom+'&xmax='+objBound.right+'&ymax='+objBound.top+'&pais='+pais,opt);   
}


//-----------------------addImage----------------------
//Funci?n que agrega una imagen sobre el mapa
//imagen		:	ruta de la imagen
//class_imagen	:	clase CSS para posicionar la imagen
//--------------------------------------------------------
function addImage(imagen,id_imagen,objMap){
	if(id_imagen != 'scalebar'){
		img = new Element('img', {'id': id_imagen, 'src':imagen});
		$(objMap).insert(img, {position: "content" });
	}
	else{	
		var display = '';
		if($(id_imagen)){ 
			display =  $(id_imagen).getStyle('display');
			$(id_imagen).remove();
		}
		
		img = new Element('img', { 
				'id': id_imagen,
				'src':imagen
			});
		
		if(display == 'none') img.setStyle({'display':'none'}); 
		$(objMap).insert(img, { position: "content" });
		$(id_imagen).setStyle({'zIndex':'1000'});
	}
}

//-----------------------init_tools----------------------
//Funci?n que inicializa los paneles de herramientas 
//y servicios
//--------------------------------------------------------
function init_tools(mapa){
	//Panel Herramientas
	var opt = {
		method:'post',
		onComplete:function(transport){
			$('lenguetas').update(transport.responseText);
			var opt = {
				method:'post',
				onComplete:function(transport){
					$('paneles').update(transport.responseText);
					$('lenguetas').setStyle({'zIndex':zIndexHerramientas});
					$('paneles').setStyle({'zIndex':zIndexHerramientas});
					loadControl(mapa);
				},
				onFailure:function(){
					alert('Lo sentimos, el panel de herramientas no pudo ser generado');
				}
			};
			new Ajax.Request('generaBotones.asp?id='+idCiudad+'&mapa='+mapa+'&ciudad='+$('ciudad').value,opt);
			$('tab_botonera').setStyle({'zIndex':zIndexHerramientas});
		},
		onFailure:function(){
			alert('Lo sentimos, el panel de herramientas no pudo ser generado');
		}
	};
	new Ajax.Request('generaLenguetas.asp?id='+idCiudad,opt);
}


//-----------------ver_panel_content----------------------
//Funci?n que activa o desactiva los paneles de herramientas 
//servicios
//tipo	:	tipo de panel('servicios' o 'herramientas')
//--------------------------------------------------------
function ver_panel_content(tipo){
	if(tipo == 'herramientas'){
		$('tab_servicios_content').setStyle({'visibility':'hidden'});
		if($('tab_herramientas_content').getStyle('visibility')=='visible')
		{
			$('tab_herramientas_content').setStyle({'visibility':'hidden'});
			$('norte').setStyle({'right':'60px'});
		}
		else
		{
			$('tab_herramientas_content').setStyle({'visibility':'visible'});
			
			$('norte').setStyle({'right':'130px'});
		}
	}
	else if(tipo == 'servicios'){
		
			if($('tab_servicios_content').getStyle('visibility')=='hidden'){
			$('tab_herramientas_content').setStyle({'visibility':'hidden'});
			$('tab_servicios_content').setStyle({'visibility':'visible'});
			$('tab_servicios').setStyle({'background':'#006699'});
			//alert(222);
			$('tab_herramientas').setStyle({'background':'#999999'});
			$('norte').setStyle({'right':'130px'});
			$('tab_servicios_content').setStyle({'opacity':'0.7'});
			alert(tipo);
		}
		else{
			$('tab_servicios_content').setStyle({'visibility':'hidden'});
			$('tab_servicios').setStyle({'background':'#999999'});
			$('norte').setStyle({'right':'40px'});
		}
	}
}

function addCamara(mapa) {

//	var div = new Element('div', { 'id': 'camaraFoto'});
//	$(mapa).insert(div, { position: "content" });

//	$('camaraFoto').update('<img src="/mapcity_2_0/images/utilidades/camara_foto.gif" title="Apaga capa de fotografias" style="width: 29px; height: 24px; cursor:hand;"/>');

	Event.observe($('camaraFoto') ,'mouseover',function(e){
		sobreCruz=true;
		Event.stop(e);
	});

	Event.observe($('camaraFoto') ,'mouseout',function(e){
		sobreCruz=false;
		Event.stop(e);
	});

	Event.observe($('camaraFoto') ,'click',function(e){
		sobreCruz=true;
		setOnClick('camaraFoto','/mapcity_2_0/images/utilidades/');
		Event.stop(e);
	});
}

function eventos() {

	$$('.olControlOverviewMapMaximizeButton').each(function(elem){
		Event.observe(elem,'click',function(e){
			$('scalebar').setStyle({'display': 'none'});
			$('mousePosition').setStyle({'display': 'none'});
			ovActivo = true;	
			Event.stop(e);
		});
	});

	$$('.olControlOverviewMapMinimizeButton').each(function(elem){
		Event.observe(elem,'click',function(e){
			$('scalebar').setStyle({'display': 'block'});
			$('mousePosition').setStyle({'display': 'block'});
			ovActivo = false;
			Event.stop(e);
		});
	});
}
// JavaScript Document
// b15

var win_prototype;
var win_prototype_iframe;
//-----------------addMarkerLabel----------------------
//Funci?n gen?rica para la generaci?n de Markers
//lonlat	: obj OL con coordenadas geogr?ficas
//label		: Etiqueta para el marker
//icon		: ruta de la imagen para el icono
//layer		: objeto OpenLayers.Layer.Markers
//class		: Clase CSS para la etiqueta
//-----------------------------------------------------
var popup,feature,lonlat_dir;
function CambiaCursor(tool,mapa){
	switch (tool){
		case "zoombox":
		$(mapa).setStyle({
			cursor:"Crosshair"
		});
		break;
		case "zoomout":
		$(mapa).setStyle({
			cursor:"Crosshair"
		});
		break;
		case "drag":
		$(mapa).setStyle({
			cursor:"Move"
		});
		break;
		case "street":
		$(mapa).setStyle({
			cursor:"help"
		});
		break;
		case "block":
		$(mapa).setStyle({
			cursor:"help"
		});
		break;
		case "line":
		$(mapa).setStyle({
			cursor:"Crosshair"
		});
		break;
		case "polygon":
		$(mapa).setStyle({
			cursor:"Crosshair"
		});
		break;
		default:
		$(mapa).setStyle({
			cursor:"Default"
		});
		break;
	}
}

function addMarkerLabel(lonlat,label,icon,layer,class_marker,w,h){	
	
	var sizeIcon = new OpenLayers.Size(w,h);
	var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
	var iconObj = new OpenLayers.Icon(icon,sizeIcon,offset);
	if (label.length>0){
		var element = new Element('div', { 'class': class_marker}).update(label);
		$(iconObj.imageDiv).insert(element, { position: "content" });
	}	
	var markerObj = new OpenLayers.Marker(lonlat,iconObj);
	//markerObj.events.register('mousedown',markerObj,function(e){alert('over')});	
	layer.addMarker(markerObj);	
}

function removeLabels()
{
	if($('id_tooltip')) cerrar_label('id_tooltip');
	if($('id_tooltip2')) cerrar_label('id_tooltip2');
	if($('post_tooltip')) cerrar_label('post_tooltip');
}



//-----------------addMarkerLabelFotos----------------------
//Funci?n para la generaci?n de Markers de Fotos
//lonlat	: obj OL con coordenadas geogr?ficas
//label		: Etiqueta para el marker
//icon		: ruta de la imagen para el icono
//layer		: objeto OpenLayers.Layer.Markers
//class		: Clase CSS para la etiqueta
//idFoto	: ID de la fotos
//idFoto	:	id de la foto
//direccion	:	direcci?n (nombrevia, altura, comuna)
//alias	:	alias del usuario que ingres? la foto
//x_left	:	referente al mapa
//y_bottom	:	referente al mapa
//x_right	:	referente al mapa
//y_top		:	referente al mapa
//w_Imagen	:	tama?o en pixeles del mapa
//h_Imagen	:	tama?o en pixeles del mapa
//-----------------------------------------------------
function addMarkerLabelFotos(elemento,icon,w,h,idFoto,direccion,comuna,alias,lonlat,crear_nuevo,id_marker){	
	try {
		//var div_evento = '';
		var Foto = idFoto;
		//if(crear_nuevo){
		var sizeIcon = new OpenLayers.Size(w,h);
		var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
		var iconObj = new OpenLayers.Icon(icon,sizeIcon,offset); 
		
		$(iconObj.imageDiv).setStyle({'cursor':'pointer', 'border':'1px Solid #c0c0c0'});
		var markerObj = new OpenLayers.Marker(lonlat,iconObj);
		markers_fotos.addMarker(markerObj);
		var div_evento = iconObj.imageDiv;
		var newImg = new Image();
	        newImg.src = 'http://fotos.mapcity.com/fachadas/'+idFoto+'.jpg';
		//	alert(newImg.src);
		Event.observe(div_evento ,'mouseover',function(e){
			var p = new Pause(0.125, showOverFoto(elemento, idFoto, direccion, comuna, alias, newImg));
			Event.stop(e);
		});
		
		Event.observe(div_evento,'mouseout',function(e){
			clearTimeout(sDisplayTimer);
			if(popup_medicion){
				map_2_0.removePopup(popup_medicion);
			}
			Event.stop(e);
		});
	} catch(e) { 
		alert(e.message); 
	}
}
   /** constructor 
   
       @param duration integer seconds
       @param <optional> function to run while waiting.
       
    */

   /** pause method 
   
       @param duration: integer in seconds
       
    */
   Pause.prototype.pause = function(duration){
      if ( (duration == null) || (duration < 0)) {return;}

      var later = (new Date()).getTime() + duration;

      while(true){
         if ((new Date()).getTime() > later) {
            break;
         }

         this.runner++;

         if (this.busywork != null) {
            this.busywork(this.runner);
         }

      } // while

   } // pause method


function addMarkerLabelBusqueda(lonlat,label,icon,layer,class_marker,w,h)
{
	var sizeIcon = new OpenLayers.Size(w,h);
	var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
	var iconObj = new OpenLayers.Icon(icon,sizeIcon,offset);
	var markerObj = new OpenLayers.Marker(lonlat,iconObj);
	layer.addMarker(markerObj);
	$(iconObj.imageDiv).setStyle({cursor:'pointer'});
	Event.observe($(iconObj.imageDiv),'click',function(ev){
		if (estado_controles=='drag'){
			click_icono=true;
			clearTimeout(id_timeout_pub_close);
			addLabelBusqueda();
		}
		Event.stop(ev);	
	});

}

function addMarkerLabelBusqueda2(lonlat,label,icon,layer,class_marker,w,h)
{
	var sizeIcon = new OpenLayers.Size(w,h);
	var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
	var iconObj = new OpenLayers.Icon(icon,sizeIcon,offset);
	var markerObj = new OpenLayers.Marker(lonlat,iconObj);
	layer.addMarker(markerObj);
	$(iconObj.imageDiv).setStyle({cursor:'pointer'});
	Event.observe($(iconObj.imageDiv),'click',function(ev){
		if (estado_controles=='drag'){
			click_icono=true;
			clearTimeout(id_timeout_pub_close2);
			addLabelBusqueda2();
		}
		Event.stop(ev);	
	});
}

function cerrar_label(ID){
	if($(ID)){
		if($(ID).getStyle('visibility')=='visible'){
			$(ID).setStyle({'visibility':'hidden'});
		}
	}
	puntosActivos();

}
function setTooltipPhotoStyle(idPhoto, win_foto) {
	widthPhoto     = document.getElementById(idPhoto).width;
	heightPhoto    = document.getElementById(idPhoto).height;
	widthPortrait  = 280;
	heightPortrait = 274;
	widthPhotoAux  = widthPhoto;
	heightPhotoAux = heightPhoto;
	if ((widthPortrait <= widthPhoto) || (heightPortrait <= heightPhoto)) {
		for (percent = 100; percent >= 0; percent--) {
			if ((widthPortrait >= widthPhotoAux) && (heightPortrait >= heightPhotoAux)) break;
			widthPhotoAux  = widthPhoto  * (percent / 100);
			heightPhotoAux = heightPhoto * (percent / 100);
		}
	} else {
		for (percent = 100; percent <= 1000; percent++) {
			if ((widthPortrait <= widthPhotoAux) || (heightPortrait <= heightPhotoAux)) break;
			widthPhotoAux  = widthPhoto  * (percent / 100);
			heightPhotoAux = heightPhoto * (percent / 100);
		}
	}
	document.getElementById(idPhoto).style.height = heightPhotoAux;
	document.getElementById(idPhoto).style.width  = widthPhotoAux;
	if (heightPhotoAux <= heightPortrait) {
		win_foto.setSize(300, heightPhotoAux + 3 * 19 + 12);
	}
}
var foto_estado =0;
function getImgSize(imgSrc)
{
	var newImg = new Image();
	newImg.src = imgSrc;
	var height = newImg.height;
	var width = newImg.width;
	alert ('The image size is '+width+'*'+height);
}

function showOverFoto(elemento, idFoto, direccion, comuna, alias, newImg)
{
	var tbl_contenido="";
	var espacios="&nbsp;&nbsp;&nbsp;";
	var px = new OpenLayers.Pixel(45,10);
	var LonLatElem = new OpenLayers.LonLat(elemento.X,elemento.Y);
	pxElem = map_2_0.getViewPortPxFromLonLat(LonLatElem);
	if (pxElem.x < ($('map_2_0').getWidth()/2))
	{
		px.x  = $('map_2_0').getWidth()-35;
		if ($('tab_servicios_content')){
			if ($('tab_servicios_content').getStyle('visibility') == 'visible') px.x  = $('map_2_0').getWidth()-155;
		}
	}
	tbl_contenido = ContenidoFotos(idFoto,direccion,comuna,alias);
	if(popup_medicion){
		map_2_0.removePopup(popup_medicion);
	}
	if(!newImg){ 
		newImg=new Image();
		newImg.src="http://fotos.mapcity.com/fachadas/"+idFoto+".jpg";
	}
	height = eval(newImg.height)+150;
	width = eval(newImg.width)+45;
        if (height==150 || width==45) return false;
//alert(width);
	if (width<200){
		 height= eval(height)+20;
		width = eval(width)+100;
	}
//    alert(newImg.height + ', ' + newImg.height);
        popup_medicion = new OpenLayers.Popup.AnchoredBubble('id_popupFramedCloud',map_2_0.getLonLatFromPixel(px),new OpenLayers.Size(width,height),tbl_contenido,null,false);
	map_2_0.addPopup(popup_medicion);
}

function showover(elemento, idFoto, direccion, comuna, alias){
	if (foto_estado==0)
	{
		foto_estado=1;
		if(!win_foto){
			win_foto = new Window({
			id:"div_win_foto",
			className: "alphacube", 
			resizable:true,
			minimizable:false,
			maximizable:false,
			draggable:false,
			closable:true,
			width:300,
			height:350,
			zIndex: zIndexWinPrototype,
			parent:$('map_2_0'),
			destroyOnClose:false,
			opacity:1.0
			});
		}

		boundsMap=map_2_0.getExtent();
		x_map_left = boundsMap.left;
		y_map_bottom = boundsMap.bottom;
		x_map_right = boundsMap.right;
		y_map_top = boundsMap.top;
		
		
		var lonlat1 = new OpenLayers.LonLat(elemento.X,elemento.Y);
		posLon = lonlat1.lon;
		dif = Math.abs((x_map_left - x_map_right));
		dif = dif / 2;
		dif1 = Math.abs(posLon - x_map_left);
		if(win_foto){
			contenidoHTML = ContenidoFotos(idFoto,direccion,comuna,alias);
			$('div_win_foto_content').update(contenidoHTML);
		}
		
		if (dif1 > dif){
			//la foto debe ir a la izquierda
			if(win_foto){
				win_foto.showCenter(false,5,5);
			}
		}else{
			//la foto debe ir a la derecha
			if(win_foto){
				win_foto.showCenter(false,5,$('map_2_0').getWidth()-345);
			}
		}
		win_foto.refresh();
		setTooltipPhotoStyle("Foto", win_foto);
	}
}
function hideout()
{
	if((win_foto) && (foto_estado==1)){
		win_foto.hide();
		foto_estado=0;
	}
}

function pausecomp(millis){
	var date = new Date();
	var curDate = null;	
	do { curDate = new Date(); }
	while(curDate-date < millis);
} 

//-----------------ContenidoFotos----------------------
//Funci?n que genera el html del popup de las fotos
//idFoto	:	id de la foto
//direccion	:	direcci?n (nombrevia, altura, comuna)
//alias	:	alias del usuario que ingres? la foto
//-----------------------------------------------------
function ContenidoFotos(idFoto,direccion,comuna,alias){
	MM_preloadImages('./fachadas/' + idFoto + '.jpg');
	out="<table width='100%' cellspacing='0' cellpadding='0'>";
	out+="<tr>";
	out+="<td align='center' ><span class='dir_foto'>"+direccion+"</span></td>";
	out+="</tr>";
	out+="<tr>";
	out+="<td align='center'><span class='comuna_tooltip'>"+comuna+"</span></td>";
	out+="</tr>";
	out+="<tr>";
	out+="<td align='center'><img src='http://fotos.mapcity.com/fachadas/" + idFoto + ".jpg' name='Foto' id='Foto' ></td>";
	out+="</tr>";
	out+="<tr>";
	out+="<td align='center' class='aliasFoto'>Gentileza de "+alias+"</td>";
	out+="</tr>";
	out+="</tr>";
//	out+="<tr>";
//	out+="<td  align='center' ><img  src='./images/nokia.gif'  border='0'></td>";
//	out+="</tr>";
	out+="<tr>";
	out+="<td align='center' class='textoFoto'>Suba sus propias fotos haciendo click <br>en el ";
	out+="&iacute;cono<img src='./images/CamaraSinFoto.gif' height='20' width='20' border='0'>bajo el recuadro <br>inferior del mapa</td>";
	out+="</tr>";
	out+="</table>";
	return out;
}
//-----------------verComuna----------------------
//Obtiene la comuna correspondiente al centro del mapa
//y genera una etiqueta en la esquina superior izquierda
//-----------------------------------------------------
function verComuna(){
	lonlat=map_2_0.getCenter();
	var opt={
		method:'post',
		onComplete:function(transport){
			var comunaObj=transport.responseText.evalJSON(true);
			var labelComuna = new Element('div', { 'id': 'label_comuna'});
			$('map_2_0').insert(labelComuna,{position:"content"});
			$('label_comuna').update(comunaObj.COMUNA);
		},
		onFailure:function(){
			//alert('Lo sentimos, su consulta (label comuna) no pudo ser procesada');
		}
	};
	new Ajax.Request('obtieneComuna.asp?x='+lonlat.lon+'&y='+lonlat.lat+'&id='+idCiudad,opt);
}
// para blog
var idTimeOutPost;
function createPost(){
	$('LoginPost').setStyle({'width':'0px','height':'0px','position':'absolute'});
	$('LoginPost').src=proxy+'/wordpress/mc-login.php';
	$('tab_herramientas_content').setStyle({'visibility':'hidden'});
	blogIn=true;
	SizeObj = map_2_0.getSize();
	w_Imagen = SizeObj.w;
	h_Imagen = SizeObj.h;
	if(   $('map_2_0').getStyle('display')   =='none')  {
		$('map_blog').setStyle({'display':'none'});
		$('map_2_0').setStyle({'display': 'block'});
		$('cerrarBlog').setStyle({'display': 'block'});	
	}else {
		$('map_2_0').setStyle({'display': 'none'});
		$('map_blog').setStyle({'display': 'block'});
		blogState=true;
		$('map_blog').setStyle({'width':w_Imagen,'height':h_Imagen,'left':'0','position':'relative'});
		abrirVentanaPost();
	}
}
function abrirVentanaPost(){
	var extent = map_2_0.getExtent();
	$('map_blog').src=proxy+'/wordpress/wp-admin/entrada.php?'+'NombreVia1='+$('NombreVia1').value+'&TipoVia1='+$('TipoVia1').value+'&Altura1='+$('Altura1').value+'&Comuna1='+$('Comuna1').value+'&Punto_X='+$('lon').value+'&Punto_Y='+$('lat').value;
}
function cerrarPost(){
	win_post.getContent().update("");
	win_post.close();
	win_post = null;
}
//-----------------centerMap----------------------
//Genera el proceso de Centrado del Mapa de acuerdo al
//producto consultado por el usuario
//-----------------------------------------------------
function centerMap(v_numZoomLevels){
	switch ($('ciudad').value)
	{ 
		case "baires" : 
			srid = 22195;
			fac_x = 0;
			fac_y = 0;
			layer_base_argentina.setVisibility(true);
			//layer_base_argentina_ov.setIsBaseLayer(true);
			//layer_label_comunas_argentina.setVisibility(true);
			break;
		case "riojaneiro" : 
			var srid = 29183;
			var fac_x = 0;
			var fac_y = 0;
			layer_base_brasil.setVisibility(true);
			//layer_base_brasil_ov.setIsBaseLayer(true);
			//layer_label_comunas_brasil.setVisibility(true);
			break; 
		case "saopaulo" : 
			srid = 22523;
			fac_x = 0;
			fac_y = 0;
			layer_base_brasil_sao.setVisibility(true);
			//layer_base_brasil_ov.setIsBaseLayer(true);
			//layer_label_comunas_brasil.setVisibility(true);
			break; 
		case "mexicodf" : 
			srid = 32614;
			fac_x = 0;
			fac_y = 0;
			layer_base_mexico.setVisibility(true);
			//layer_base_mexico_ov.setIsBaseLayer(true);
			//layer_label_comunas_mexico.setVisibility(true);
			break; 

		case "lima" : 
			srid = 32718;
			fac_x = 0;
			fac_y = 0;
			layer_base_peru.setVisibility(true);
			//layer_base_peru_ov.setIsBaseLayer(true);
			//layer_label_comunas_peru.setVisibility(true);
			break; 

		default : 
			srid = 29179;
			fac_x = -62;
			fac_y = -40;
			layer_base_chile.setVisibility(true);
			//layer_label_comunas_chile.setVisibility(true);
			//layer_transito.setVisibility(true);
	}
	if ($('Producto').value=='RUTA' || ($('Producto').value=='CERCANO' && $('IdRuta').value!='' ) ){
		var id_ruta=$('IdRuta').value;
		var optruta={
			method:'post',
			onSuccess:function(transport){
				//alert('aca 11');
				//alert(transport.responseText);
				respObj=transport.responseText.evalJSON(true);
				var style_orange = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
				style_orange.strokeColor = "#FF0000";
				style_orange.strokeWidth=6;
				style_orange.strokeOpacity=0.8;
				style_orange.strokeLinecap="round";
				style_orange.hoverStrokeColor = "#CC2200";
				style_orange.hoverStrokeOpacity=1;
				style_orange.hoverStrokeWidth=10;
				style_orange.pointerEvents="visiblePainted";
				var layer_ruta = new OpenLayers.Layer.Vector("layer_ruta");
				
				respObj.RUTAS.each(function(elem){
					coords_bound=elem.BOUND.replace('POLYGON((','');
					coords_bound=coords_bound.replace('))','');
					coords_bound_array=coords_bound.split(',');
					min_lonlat_bound_array=coords_bound_array[0].split(' ');
					max_lonlat_bound_array=coords_bound_array[2].split(' ');
					var boundObj = new OpenLayers.Bounds(min_lonlat_bound_array[0],min_lonlat_bound_array[1],max_lonlat_bound_array[0],max_lonlat_bound_array[1]);
					map_2_0.zoomToExtent(boundObj);
					coords=elem.RUTA_GEOM.replace('LINESTRING(','');
					coords=coords.replace(')','');
					coords_array=coords.split(',');
					var puntos_array = new Array();
					var punto_ini = coords_array[0].split(' ');
					puntos_array.push(new OpenLayers.Geometry.Point(punto_ini[0],punto_ini[1]));
					for(i=2;i<coords_array.length;i++){
						var punto = coords_array[i].split(' ');
						puntos_array.push(new OpenLayers.Geometry.Point(punto[0],punto[1]));	
					}
					var line = new OpenLayers.Geometry.LineString(puntos_array);
					var lineFeature = new OpenLayers.Feature.Vector(line,{},style_orange);
					layer_ruta.addFeatures([lineFeature]);
					$('td_detalle_ruta').update(elem.RECORRIDO);
				});
				layer_ruta.setVisibility(true);
				map_2_0.addLayer(layer_ruta);
				var utm_x=eval($('Punto_X').value) + eval(fac_x);
				var utm_y=eval($('Punto_Y').value) + eval(fac_y);
				var utm_x2=eval($('Punto_X2').value) + eval(fac_x);
				var utm_y2=eval($('Punto_Y2').value) + eval(fac_y);
				var opt={
					method:'post',
					onSuccess:function(transport){
						//alert(transport.responseText);
						resObj=transport.responseText.evalJSON(true);
						var LonLat1= new OpenLayers.LonLat(resObj.X,resObj.Y);
						$('lon').value=resObj.X;
						$('lat').value=resObj.Y;
						var opt={
							method:'post',
							onSuccess:function(transport){
								resObj=transport.responseText.evalJSON(true);
								var LonLat2= new OpenLayers.LonLat(resObj.X,resObj.Y);
								$('lon2').value=resObj.X;
								$('lat2').value=resObj.Y;
								if (!markers_busqueda) markers_busqueda = new OpenLayers.Layer.Markers("Busqueda");
								fac_y = 0;
								map_2_0.addLayer(markers_busqueda);
								map_2_0.setLayerIndex(markers_busqueda,zIndexEstrella);
								addMarkerLabelBusqueda(LonLat1,'','mapcity_2_0/images/inicio.gif',markers_busqueda,'label_test',30,30);
								addLabelBusqueda();
								addMarkerLabelBusqueda2(LonLat2,'','mapcity_2_0/images/fin.gif',markers_busqueda,'label_test',30,30);
								addLabelBusqueda2();
								addMousePosition(LonLat2.lon,LonLat2.lat);
							},
							onFailure:function(){
								alert('Lo sentimos, La direcci&oacute;n no pudo ser encontrada');
							}
						};
						new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+utm_x2+' '+utm_y2+')'+'&id='+idCiudad,opt);
					},
					onFailure:function(){
						alert('Lo sentimos, La direcci&oacute;n no pudo ser encontrada');
					}
				};
				new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+utm_x+' '+utm_y+')'+'&id='+idCiudad,opt);	
				
			},
			onFailure:function(){
				var utm_x=eval($('Punto_X').value) + eval(fac_x);
				var utm_y=eval($('Punto_Y').value) + eval(fac_y);
				var utm_x2=eval($('Punto_X2').value) + eval(fac_x);
				var utm_y2=eval($('Punto_Y2').value) + eval(fac_y);
//alert(utm_x+' '+utm_y+' '+utm_x2+' '+utm_y2);
				var opt={
					method:'post',
					onSuccess:function(transport){
						resObj=transport.responseText.evalJSON(true);
						var LonLat1= new OpenLayers.LonLat(resObj.X,resObj.Y);
						$('lon').value=resObj.X;
						$('lat').value=resObj.Y;
						var opt={
							method:'post',
							onSuccess:function(transport){
								resObj=transport.responseText.evalJSON(true);
								var LonLat2= new OpenLayers.LonLat(resObj.X,resObj.Y);
								$('lon2').value=resObj.X;
								$('lat2').value=resObj.Y;

								if(eval($('lon').value) > eval($('lon2').value)){
									xmin = $('lon2').value;
									xmax = $('lon').value;
								}else{ 
									xmin = $('lon').value;
									xmax = $('lon2').value;
								}

								if (eval($('lat').value) > eval($('lat2').value)){
									ymin = $('lat2').value;
									ymax = $('lat').value;
								}else{
									ymin = $('lat').value;
									ymax = $('lat2').value;
								}



						                var boundObj = new OpenLayers.Bounds(xmin,ymin,xmax,ymax);
                                                                map_2_0.zoomToExtent(boundObj);
                                                                if (!markers_busqueda)
	                                                                markers_busqueda = new OpenLayers.Layer.Markers("Busqueda");
                                                                fac_y = 0;
                                                                map_2_0.addLayer(markers_busqueda);
                                                                map_2_0.setLayerIndex(markers_busqueda,zIndexEstrella);
                                                                addMarkerLabelBusqueda(LonLat1,'','mapcity_2_0/images/inicio.gif',markers_busqueda,'label_test',30,30);
                                                               addLabelBusqueda();
                                                               addMarkerLabelBusqueda2(LonLat2,'','mapcity_2_0/images/fin.gif',markers_busqueda,'label_test',30,30);
                                                               addLabelBusqueda2();

								addMousePosition(LonLat2.lon,LonLat2.lat);
							},
							onFailure:function(){
								alert('Lo sentimos, La direcci&oacute;n no pudo ser encontrada');
							}
						};
						new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+utm_x2+' '+utm_y2+')'+'&id='+idCiudad,opt);

					},
					onFailure:function(){
						alert('Lo sentimos, La direcci&oacute;n no pudo ser encontrada');
					}
				};
				new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+utm_x+' '+utm_y+')'+'&id='+idCiudad,opt);
				//alert('Lo sentimos, la ruta no pudo ser generada.');
			}
		};

		/*		alert('aqui ruta'); */
		//alert('recuperaRuta.asp?id_ruta='+id_ruta+'&id='+idCiudad);
		new Ajax.Request('recuperaRuta.asp?id_ruta='+id_ruta+'&id='+idCiudad,optruta);
	}
	else if($('Producto').value=='COMUNA'){
		var nombre_comuna=$('Comuna1').value;
		var opt={
			method:'post',
			onComplete:function(transport){
				respObj=transport.responseText.evalJSON(true);
				
				respObj.COMUNAS.each(function(elem){
					//Centrado del mapa
					coords_bound=elem.BOUND.replace('POLYGON((','');
					coords_bound=coords_bound.replace('))','');
					coords_bound_array=coords_bound.split(',');
					min_lonlat_bound_array=coords_bound_array[0].split(' ');
					max_lonlat_bound_array=coords_bound_array[2].split(' ');
					
					var boundObj = new OpenLayers.Bounds(min_lonlat_bound_array[0],min_lonlat_bound_array[1],max_lonlat_bound_array[0],max_lonlat_bound_array[1]);
					map_2_0.zoomToExtent(boundObj);
					//init_servicios(31);//METRO
					//Calculando coordenada central					
					var utm_x=eval($('Punto_X').value) + eval(fac_x);
					var utm_y=eval($('Punto_Y').value) + eval(fac_y);
					var opt={
						method:'post',
						onSuccess:function(transport){
							resObj=transport.responseText.evalJSON(true);
							var LonLat= new OpenLayers.LonLat(resObj.X,resObj.Y);
							$('lon').value=resObj.X;
							$('lat').value=resObj.Y;
							addMousePosition(LonLat.lon,LonLat.lat);
						},
						onFailure:function(){
							alert('Lo sentimos, La direcci&oacute;n no pudo ser encontrada');
						}
					};
					new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+utm_x+' '+utm_y+')'+'&id='+idCiudad,opt);					
										
					//Dibujar ruta
						
					coords=elem.GEOM.
					fac_y = 0;replace('MULTILINESTRING((','');
					coords=coords.replace('))','');
					coords_array=coords.split(',');
					pointArray = new Array();
					lonlat_array = coords_array[0].split(' ');

		
					pointArray[0] = new OpenLayers.Geometry.Point(lonlat_array[0],lonlat_array[1]);
					for(i=2;i<coords_array.length;i++){
						lonlat_array = coords_array[i].split(' ');
						pointArray[i-1] = new OpenLayers.Geometry.Point(lonlat_array[0],lonlat_array[1]);
					}

					var geomObj = new OpenLayers.Geometry.LineString(pointArray);
					var style_orange = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
            		style_orange.strokeColor = "#FF0000";
					style_orange.strokeWidth=12;
					style_orange.strokeOpacity=0.2;
					style_orange.strokeLinecap="round";
					style_orange.hoverStrokeColor = "#CC2200";
					style_orange.hoverStrokeOpacity=1;
					style_orange.hoverStrokeWidth=10;
					style_orange.pointerEvents="visiblePainted";
					
					var featObj = new OpenLayers.Feature.Vector(geomObj,{},style_orange);
					layer_rutas.addFeatures([featObj]);
				} );
			},
			onFailure:function(){
				alert('Lo sentimos, su consulta por comuna no pudo ser procesada');
			}
		};
		new Ajax.Request('recuperaComuna.asp?comuna='+nombre_comuna+'&id='+idCiudad,opt);
	}
	else if ($('Producto').value=='CALLESN'){
		var opt={
			method:'post',
			onComplete:function(transport){
				
				respObj=transport.responseText.evalJSON(true);

				pointArray = new Array();
				// Extraemos en Extent
				coords_bound=respObj.BOUND.replace('POLYGON((','');
				coords_bound=coords_bound.replace('))','');
				coords_bound_array=coords_bound.split(',');
				min_lonlat_bound_array=coords_bound_array[0].split(' ');
				max_lonlat_bound_array=coords_bound_array[2].split(' ');
				
				var utm_x=eval($('Punto_X').value) + eval(fac_x);
				var utm_y=eval($('Punto_Y').value) + eval(fac_y);
				//Centrado del mapa
				var boundObj = new OpenLayers.Bounds(min_lonlat_bound_array[0],min_lonlat_bound_array[1],max_lonlat_bound_array[0],max_lonlat_bound_array[1]);

				var opt={
					method:'post',
					onSuccess:function(transport){
						resObj=transport.responseText.evalJSON(true);
						var LonLat= new OpenLayers.LonLat(resObj.X,resObj.Y);
						$('lon').value=resObj.X;
						$('lat').value=resObj.Y;
						map_2_0.zoomToExtent(boundObj);
						//Calculando coordenada central
						addMousePosition(LonLat.lon,LonLat.lat);
						//Dibujar ruta
						puntoAntXcoord_ruta = new Array();
						puntoAntYcoord_ruta = new Array();
						puntoAntX_ruta = new Array();
						puntoAntY_ruta = new Array();
						var style_orange = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
						style_orange.strokeColor = "#FF0000";
						style_orange.strokeWidth=6;
						style_orange.strokeOpacity=0.8;
						style_orange.strokeLinecap="round";
						style_orange.hoverStrokeColor = "#CC2200";
						style_orange.hoverStrokeOpacity=1;
						style_orange.hoverStrokeWidth=10;
						style_orange.pointerEvents="visiblePainted";
						var layer_ruta = new OpenLayers.Layer.Vector("layer_ruta");
						respObj.CALLE.each(function(elem){
							//Recupera ruta	
							coords=elem.PUNTOS.replace('MULTILINESTRING((','');
							coords=coords.replace('))','');
							coords_array=coords.split(',');
							puntos_array = new Array();
							coords_array.each(function(coord){
								var punto = coord.split(' ');
								puntos_array.push(new OpenLayers.Geometry.Point(punto[0],punto[1]));	
							});
							var line = new OpenLayers.Geometry.LineString(puntos_array);
							var lineFeature = new OpenLayers.Feature.Vector(line,{},style_orange);
							layer_ruta.addFeatures([lineFeature]);
						});
						layer_ruta.setVisibility(true);
						map_2_0.addLayer(layer_ruta);
					},
					onFailure:function(){
						alert('Lo sentimos, La direcci&oacute;n no pudo ser encontrada');
					}
				};
				new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+utm_x+' '+utm_y+')'+'&id='+idCiudad,opt);
			},
			onFailure:function(){
				alert('Lo sentimos, su no fue posible pintar la calle');
			}
		};
		new Ajax.Request('recuperaCalle.asp?ciudad='+$('ciudad').value+'&tipovia='+$('TipoVia1').value+'&nombrevia='+$('NombreVia1').value+'&comuna='+$('Comuna1').value+'&id='+idCiudad,opt);
	}
	else if ($('Producto').value=='CODIGOPOSTAL'){
		var utm_x=eval($('Punto_X').value) + eval(fac_x);
		var utm_y=eval($('Punto_Y').value) + eval(fac_y);
		
		var opt={
			method:'post',
			onComplete:function(transport){
				resObj=transport.responseText.evalJSON(true);
				var LonLat= new OpenLayers.LonLat(resObj.X,resObj.Y);
				$('lon').value=resObj.X;
				$('lat').value=resObj.Y;
				new Ajax.Request(
				'recuperaInfo.asp?punto=POINT('+LonLat.lon+' '+LonLat.lat+')&tipo=street&id='+idCiudad,
				{
					method:'get',
					onComplete: function(transport){var response = transport.responseText;
						var datos = response.evalJSON();
						var geom = datos.POLYGON;
						var arrxy = splitStreet(geom);
						var puntos = [];
						for(var i=0; i<arrxy.length ; i++){
							var point = arrxy[i].replace(" ",",");
							var spliti = point.split(",");
							var point = new OpenLayers.Geometry.Point(parseFloat(spliti[0]),parseFloat(spliti[1]));
							puntos.push(point);
						}
						var style_orange = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
						style_orange.strokeColor = "#FF0000";
						style_orange.strokeWidth=4;
						style_orange.strokeOpacity=1;
						style_orange.strokeLinecap="round";
						style_orange.hoverStrokeColor = "#CC2200";
						style_orange.hoverStrokeOpacity=1;
						style_orange.hoverStrokeWidth=10;
						style_orange.pointerEvents="visiblePainted";

						var linestring = new OpenLayers.Geometry.LineString(puntos);
						var linestrings = [];
						
						linestrings.push(new OpenLayers.Feature.Vector(linestring,{},style_orange));
						street.addFeatures(linestrings);

						zoom = eval(v_numZoomLevels-3);
						map_2_0.setCenter(LonLat,zoom);
						addMousePosition(LonLat.lon,LonLat.lat);
						addLabelBusqueda();
					},
					onFailure:function(){
						alert('Lo sentimos, La direcciÃ³n no pudo ser encontrada');
					}
				});
			},
			onFailure:function(){
				alert('Lo sentimos, La direcciÃ³n no pudo ser encontrada');
			}
		};
		new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+utm_x+' '+utm_y+')'+'&id='+idCiudad,opt);

	}
	else{
		if ( (($('ciudad').value=="santiago") || ($('ciudad').value=="vregion")) && ($('CoreTipoCon').value != "ZOOM5001") ) {
			var utm_x = $('Punto_X').value;
			var utm_y = $('Punto_Y').value;
			
			//alert(utm_x + '-' + utm_y);
			//alert($('Producto').value);
			$('lon').value=utm_x;
			$('lat').value=utm_y;
	
			var LonLat= new OpenLayers.LonLat(utm_x, utm_y);
			if ( $('CoreTipoCon').value=="COMUNA" ) {
				zoom = 9;
			}
			else  {
				zoom = eval(v_numZoomLevels-2);
			}
			
			if ( ($('Producto').value == "DIRCOMERCIO") || ( ($('Producto').value == "COMERCIO") && ($('CoreTipoCon').value=="COMUNA") ) ) {
				var tmOut = setTimeout("check_comercio(1, 15);", 1000);
				}
			else {
				if ( $('Producto').value == "COMERCIO" ) {
					check_comercio($('pagina').value, $('limite').value);
					}
				}
			
			if ($('escala').value != "50000" ){
				map_2_0.setCenter(LonLat,zoom);
			}
			
			if ( $('CoreTipoCon').value!="CALLESN" && $('Producto').value != "COMERCIO" && $('CoreTipoCon').value != "COMUNA"  ) {
				cargaEstrella(LonLat,'mapcity_2_0/images/estrella.gif',map_2_0);
				addLabelBusqueda();
			}

			cargaReferenciaGuia(utm_x.replace(" ",""),utm_x.replace(" ",""));
			addMousePosition(LonLat.lon,LonLat.lat);
			addScalebar(map_2_0.getScale());
		}
		else {
			var utm_x=eval($('Punto_X').value) + eval(fac_x);
			var utm_y=eval($('Punto_Y').value) + eval(fac_y);
			//alert(utm_x + '-' + utm_y) ;
			//alert(srid);
			var opt={
				method:'post',
				onComplete:function(transport){
					resObj=transport.responseText.evalJSON(true);
					var LonLat= new OpenLayers.LonLat(resObj.X,resObj.Y);
					$('lon').value=resObj.X;
					$('lat').value=resObj.Y;
					//alert(resObj.X + '-' + resObj.Y) ;
					zoom = eval(v_numZoomLevels-2);
					map_2_0.setCenter(LonLat,zoom);
					cargaEstrella(LonLat,'mapcity_2_0/images/estrella.gif',map_2_0);
	
					//alert('a');				
					if(!$('id_tooltip')) addLabelBusqueda();
					cargaReferenciaGuia(resObj.X.replace(" ",""),resObj.Y.replace(" ",""));
					addMousePosition(LonLat.lon,LonLat.lat);
	
					/*if ( $('ciudad').value=="santiago" )
					{
						//$('check_95').checked=checked;
						check_servicio($('check_95'));
					};*/
					
				},
				onFailure:function(){
					alert('Lo sentimos, La direcciÃ³n no pudo ser encontrada');
				}
			};
			new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+utm_x+' '+utm_y+')'+'&id='+idCiudad,opt);
		}	
	}	
		//alert($('ciudad').value);
	if (($('ciudad').value=="santiago" || $('ciudad').value=="baires" || $('ciudad').value=="vregion" ) && (($('Producto').value=='DIRECCION') || ($('Producto').value=='INTERSECCION')))
	{
		var opt={
			method:'post',
			onSuccess:function(transport_entorno){
				respObj=transport_entorno.responseText.evalJSON(true);
				$('td_entorno').update(respObj.ENTORNO);
				try{
					document.getElementById('idEntorno').value = respObj.ENTORNO;
				}catch(e){}
				//cargaBannerCostado(map_2_0);
				cargaBannerLateral(map_2_0);
			},
			onFailure:function(){
				//alert('Lo sentimos, su no fue posible recuperar entorno');
				cargaBannerLateral(map_2_0);
			}
		};
		new Ajax.Request('recuperaEntorno.asp?ciudad='+$('ciudad').value+'&idArco='+$('idarco').value+'&comuna='+$('Comuna1').value+'&este='+$('Punto_X').value+'&norte='+$('Punto_Y').value+'&id='+idCiudad,opt);
		//alert('recuperaEntorno.asp?ciudad='+$('ciudad').value+'&idArco='+$('idarco').value+'&comuna='+$('Comuna1').value+'&este='+$('Punto_X').value+'&norte='+$('Punto_Y').value+'&id='+idCiudad);
	}

	if ($('Producto').value=='TELEFONO'){
		var utm_x=eval($('Punto_X').value) + eval(fac_x);
		var utm_y=eval($('Punto_Y').value) + eval(fac_y);
		var opt={
			method:'post',
			onComplete:function(transport){
				resObj=transport.responseText.evalJSON(true);
				var LonLat= new OpenLayers.LonLat(resObj.X,resObj.Y);
				$('lon').value=resObj.X;
				$('lat').value=resObj.Y;
				zoom = eval(v_numZoomLevels-2);
				map_2_0.setCenter(LonLat,zoom);
				
				cargaEstrella(LonLat,'mapcity_2_0/images/estrella.gif',map_2_0);
				cargaReferenciaGuia(resObj.X.replace(" ",""),resObj.Y.replace(" ",""));
				addMousePosition(LonLat.lon,LonLat.lat);

				addScalebar(map_2_0.getScale());

				var entorno = 'El Tel&eacute;fono ' + $('Telefono1').value + ' se encuentra a nombre de ' + $('Titular').value;
				$('td_entorno').update(entorno);
				document.getElementById('idEntorno').value = entorno;
			},
			onFailure:function(){
				alert('Lo sentimos, La direcciÃ³n no pudo ser encontrada');
			}
		};
		new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+utm_x+' '+utm_y+')'+'&id='+idCiudad,opt);
	}

}

var featureSN;
function dibujaCalle(szMultiCalle){
    var parser;
    var bounds;
    var opcion = "5";
    var contenido;

	var result_style =  {
		fillColor: "#FFFF33",
		fillOpacity: 0.0,
		strokeColor: "#0000FF",
		strokeOpacity: 1,
		strokeWidth: 2,
		pointRadius: 6,
		pointerEvents: "visiblePainted",
		cursor: "pointer",
		zindex: 10
	};

	var layer_callesn = new OpenLayers.Layer.Vector("layer_callesn");

	parser = new OpenLayers.Format.WKT();
	featureSN = parser.read(szMultiCalle);
	featureSN.style = result_style;

	layer_callesn.addFeatures([featureSN]);
	layer_callesn.setVisibility(true);
	map_2_0.addLayer(layer_callesn);    

	var boundObj = featureSN.geometry.getBounds();
	map_2_0.zoomToExtent(boundObj);
}

function dibujaManzana(szManzana){
    var parser;
    var bounds;
    var opcion = "5";
    var contenido;
	
	var result_style =  {
		fillColor: "#FF0000",
		fillOpacity: 0.5,
		strokeColor: "#FF0000",
		strokeOpacity: 1,
		strokeWidth: 2,
		pointRadius: 6,
		pointerEvents: "visiblePainted",
		cursor: "pointer",
		zIndex: 10
	};

	parser = new OpenLayers.Format.WKT();
	featureMnz = parser.read(szManzana);
	featureMnz.style = result_style;

	block.addFeatures([featureMnz]);
	block.setVisibility(true);

	//var boundObj = featureMnz.geometry.getBounds();
	//map_2_0.zoomToExtent(boundObj);
}

function puntosActivos() {
	init_publicidad('recuperarPublicidad.asp');
	init_publicidad('recuperarPublicidadDinamica.asp');
 if (camaraEncendida) {
	setTimeout("init_fotos()", 1000);
	}
}

function cargaReferenciaGuia(lon,lat){
	var opt={
		onSuccess:function(transport){
			var referencia="<a onClick=' verGuiaReferencia("+lon+","+lat+"); return false;' href='#'>"+transport.responseText+"</a>";
			$('ref_guia').update(referencia);
		},
		onFailure:function(){
			alert('Lo sentimos, No fue posible recuperar la referencia de la guÃ­a');
		}
	};
	new Ajax.Request('recuperaRefGuia.asp?lon='+lon+'&lat='+lat,opt);
}
function verGuiaReferencia(lon,lat){
	click_guia(); 
	ver_layer('guia',true);
}

function cargaBannerLateral(mapa)
{
	var iframe=	document.getElementById("banner_costado");
	if(!iframe)
		iframe=getObj('banner_costado');

	iframe.src = 'banner_costado.asp?ciudad='+$('ciudad').value+'&sAltura1='+$('Altura1').value+'&sNombreVia1='+$('NombreVia1').value+'&Producto=DIRECCION&'+'xcentro='+mapa.center.lon+'&ycentro='+mapa.center.lat+'&xmin='+mapa.getExtent().left+'&xmax='+mapa.getExtent().right+'&ymin='+mapa.getExtent().bottom+'&ymax='+mapa.getExtent().top+'&xPosPubRight='+$('xPosPubRight').value;
//	alert('banner_costado.asp?ciudad='+$('ciudad').value+'&sAltura1='+$('Altura1').value+'&sNombreVia1='+$('NombreVia1').value+'&Producto=DIRECCION&'+'xcentro='+mapa.center.lon+'&ycentro='+mapa.center.lat+'&xmin='+mapa.getExtent().left+'&xmax='+mapa.getExtent().right+'&ymin='+mapa.getExtent().bottom+'&ymax='+mapa.getExtent().top+'&xPosPubRight='+$('xPosPubRight').value);

}

function cargaBannerCostado(mapa) {
	var opt={
		method:'post',
		onSuccess:function(transport){
			$('capa').update(transport.responseText);
		},
		onFailure:function(){
		}
	};
	new Ajax.Request('banner_costado.asp?ciudad='+$('ciudad').value+'&sAltura1='+$('Altura1').value+'&sNombreVia1='+$('NombreVia1').value+'&Producto=DIRECCION&'+'xcentro='+mapa.center.lon+'&ycentro='+mapa.center.lat+'&xmin='+mapa.getExtent().left+'&xmax='+mapa.getExtent().right+'&ymin='+mapa.getExtent().bottom+'&ymax='+mapa.getExtent().top+'&xPosPubRight='+$('xPosPubRight').value, opt);
}

function cargaEstrella(LonLat,icon,objMap)
{
	if(!markers_busqueda)
	{
		markers_busqueda = new OpenLayers.Layer.Markers("Busqueda");
		objMap.addLayer(markers_busqueda);
		objMap.setLayerIndex(markers_busqueda,zIndexEstrella);
	}
	addMarkerLabelBusqueda(LonLat,'',icon,markers_busqueda,'label_test',47,42);
}

//-----------------init_fotos----------------------
//Genera los markers para la capa de fotos seg?n el extent
//-----------------------------------------------------
function init_fotos(){
//alert('init_fotos');
//alert(camaraEncendida);
	if (!camaraEncendida)
	{
		return false;
	}

	boundsObj=map_2_0.getExtent();
	var x_left,y_bottom,x_right,y_top;
	var limit = 20;

	x_left = boundsObj.left;
	y_bottom = boundsObj.bottom;
	x_right = boundsObj.right;
	y_top = boundsObj.top;

	SizeObj = map_2_0.getSize();
	w_Imagen = SizeObj.w;
	h_Imagen = SizeObj.h;
//if(cargandoFotos) return false;

cargandoFotos = true;

//	if(map_2_0.getLayersByName("Fotos").length < 1){
		var opt={
			method:'post',
			onComplete:function(transport){
				fotosObj=transport.responseText.evalJSON();
//				alert('ajax');
				if(markers_fotos){
					markers_fotos.markers.each(function(mk){
							mk.destroy();
					});
					
					markers_fotos.clearMarkers();
					map_2_0.removeLayer(markers_fotos);
					markers_fotos.destroy();
					markers_fotos=null;
				}

				if (map_2_0.getScale()<7000){
					if(map_2_0.getLayersByName("Fotos").length < 1){
						markers_fotos = new OpenLayers.Layer.Markers( "Fotos");
						map_2_0.addLayer(markers_fotos);
					}
					var crear_nuevo=true;
					if(markers_fotos.markers.length==limit) crear_nuevo=false;
					id_foto=0;
					fotosObj.FOTOS.each(function(elem){
						var LonLat= new OpenLayers.LonLat(elem.X,elem.Y);
						addMarkerLabelFotos(elem,'http://fotos.mapcity.com/fachadas/'+elem.ID+'.jpg',14,9,elem.ID,elem.DIR,elem.COMUNA,elem.ALIAS,LonLat,crear_nuevo,id_foto);
						LonLat=null;
						//i++;
						id_foto++;
					});
					markers_fotos.setOpacity(1.0);
				}
				fotos_cargadas=1;
				CambiaCursor(estado_controles,"map_2_0");
				cargandoFotos=false;
			},
			onFailure:function(){
				//alert('lo sentimos, su consulta (fotos) no pudo ser procesada');
			}
		};
		centro=map_2_0.getCenter();
		new Ajax.Request('recuperaFotos.asp?dir='+ $('Str_Direccion').value + ' ' + $('Comuna1').value + '&xmin='+boundsObj.left+'&ymin='+boundsObj.bottom+'&xmax='+boundsObj.right+'&ymax='+boundsObj.top+'&limit='+limit+'&id='+idCiudad+'&xcentro='+centro.lon+'&ycentro='+centro.lat,opt);
//	}
}

function addScalebar(scale){
	if(scale!=actualScale){
		var map_Extent=map_2_0.getExtent();
		var map_Size=map_2_0.getSize();
		
		var url = 'http://mapa.mapcity.com';
		switch ($('ciudad').value)
		{ 
			case "baires" : 
				url+='/tiles/escalas/AR/';
				break;
			case "riojaneiro" : 
				url+='/tiles/escalas/BZ_RIO/';				
				break; 
			case "saopaulo" : 
				url+='/tiles/escalas/BZ_SAO/';
				break; 
			case "mexicodf" : 
				url+='/tiles/escalas/MX/';
				break; 
			case "lima" : 
				url+='/tiles/escalas/PE/';
				break; 
			default : 
				url+='/tiles/escalas/CL/';
		}		
		
		url += map_2_0.getZoom()+'.jpeg';
		addImage(url,'scalebar','map_2_0');
		actualScale=scale;
	}
}
function addMousePosition(x,y)
{
	var lon = new Number(x);
	var lat = new Number(y);			
	if (!$('mousePosition'))
	{
		div = new Element('div', { 'id': 'mousePosition'});
		div.setStyle({
			 'border-bottom':'1px solid #000000'
			,'border-left':'1px solid #000000'			
			,'background':'#eae3d3'
			,'height':'16px'
			,'zIndex':'10000'
		});
		$('map_2_0').insert(div, { position: "content" });
		if ($('mousePosition')) $('mousePosition').update('Lon:'+lon.toFixed(5)+' Lat:'+lat.toFixed(5));
	}
	else
		$('mousePosition').update('Lon:'+lon.toFixed(5)+' Lat:'+lat.toFixed(5));
}


function addLabelBusqueda()
{
	var lonlat_dir=new OpenLayers.LonLat($('lon').value,$('lat').value);
	var timeOutHide="6000";
	var codigoPostal="";
	var tbl_contenido="";
	var id_tbl_contenido="tbl_tooltip";
	var espacios="&nbsp;&nbsp;&nbsp;";
	var titular='';
	var pixel_pos;
	var height = 100;
	var width = 100;

	if ( $('CodigoPostal1').value.length>0 && $('CodigoPostal1').value != "0")
		 codigoPostal="CP "+$('CodigoPostal1').value;
	
	if ($('Producto').value=="TELEFONO") {
		titular=$('Titular').value;
	}

	tbl_contenido='<table bgcolor="#FFFFFF" id="'+id_tbl_contenido+'" border="0" cellspacing="0" cellpadding="0">';
	tbl_contenido+='<tr><td align="center" valign="middle"><span class="dir_tooltip">'+espacios+$('Str_Direccion').value+espacios+'</span></td></tr>';
	if ($('TxtPer1').value.length > 0)
		tbl_contenido+='<tr><td align="center" valign="middle">'+espacios+$('TxtPer1').value+espacios+'</td></tr>';
	if ($('Comuna1').value.length > 0)
		tbl_contenido+='<tr><td align="center" valign="middle"><span class="comuna_tooltip">'+espacios+$('Comuna1').value+espacios+'</span></td></tr>';
	
	if($('Producto').value!='RUTA' && $('Producto').value!='CERCANO' && $('CoreTipoCon').value != "CALLESN" && $('CoreTipoCon').value != "COMUNA"  && $('CoreTipoCon').value != "INTER"   )
	{
		if (codigoPostal.length > 0)
			tbl_contenido+='<tr><td align="center" valign="middle">'+espacios+codigoPostal+espacios+'</td></tr>';
		if (titular.length > 0)
			tbl_contenido+='<tr><td align="center" valign="middle">'+espacios+titular+espacios+'</td></tr>';

		if($('idFoto').value.length > 0)
		{
			tbl_contenido+='<tr><td align="center" valign="middle">';
			tbl_contenido+='<img id="id_tooltip_foto_dire" class="foto_tooltip"';
			tbl_contenido+=' src="http://fotos.mapcity.com/fachadas/'+$('idFoto').value+'.jpg"';
			var newImg= new Image();
			newImg.src ="http://fotos.mapcity.com/fachadas/"+$('idFoto').value+".jpg";
			tbl_contenido+='onMouseOver="showOverFoto(\'{X:'+lonlat_dir.lon+',Y:'+lonlat_dir.lat+'}\', \''+$('idFoto').value+'\',\''+$('Str_Direccion').value+'\' , \''+$('Comuna1').value+'\', \''+$('alias').value+'\')" ';
			tbl_contenido+='onMouseOut="map_2_0.removePopup(popup_medicion);"';
			tbl_contenido+='width="100px" height="100px"></td></tr>';
		}
		else{
			//alert('<tr><td align="center" valign="bottom" height="25"><img src="/images/CamaraSinFoto.gif" height="20" border="0" width="20" alt="Click aqui para subir una foto a esta direccion" title="Click aqui para subir una foto a esta direccion" onClick="javascript:AgregarFoto(\'Santiago\',\''+$('TipoVia1').value+'\',\''+$('NombreVia1').value+'\',\''+$('Altura1').value+'\',\''+$('Comuna1').value+'\',\''+$('Punto_X').value+'\',\''+$('Punto_Y').value+'\',\''+$('idarco').value+'\');" style=" cursor: pointer;" ></td></tr>')	;
			tbl_contenido+='<tr><td align="center" valign="bottom" height="25"><img src="/images/CamaraSinFoto.gif" height="20" border="0" width="20" alt="Click aqui para subir una foto a esta direccion" title="Click aqui para subir una foto a esta direccion" onClick="javascript:AgregarFoto(\'Santiago\',\''+$('TipoVia1').value+'\',\''+$('NombreVia1').value+'\',\''+$('Altura1').value+'\',\''+$('Comuna1').value+'\',\''+$('Punto_UTM_X').value+'\',\''+$('Punto_UTM_Y').value+'\',\''+$('idarco').value+'\');" style=" cursor: pointer;" ></td></tr>';
		}
	}
	tbl_contenido+='</table>';
	if(popup_busqueda){
		map_2_0.removePopup(popup_busqueda);
	}

	
	popup_busqueda = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud',lonlat_dir ,new OpenLayers.Size(100,100),tbl_contenido,null,true);
	map_2_0.addPopup(popup_busqueda);
	
	if($('idFoto').value.length>0)
	{
		var newImg = new Image();
		newImg.src = $('id_tooltip_foto_dire').src; //'http://fotos.mapcity.com/fachadas/'+$('idFoto').value+'.jpg';
		height = eval(newImg.height);
		width = eval(newImg.width);
		height = eval(height*0.5);
		width = eval(width*0.5);
		if (height==0 || width==0)
		{
			height = 100;
			width = 100;
		}
		$('id_tooltip_foto_dire').setStyle({'width':width+'px','height':height+'px'});
	}
	
	if ($('Producto').value != "COMERCIO" && $('Producto').value != "DIRCOMERCIO") {
		if (camaraEncendida) {
			puntosActivos();
		}
	}
	else {
			camaraEncendida=false;
			$('camaraFoto').update('<img src="/mapcity_2_0/images/utilidades/camara_foto_off.png" title="Enciende capa de fotografias" style="z-index: 10000; width: 24px; height: 21px; cursor:hand;"/><span  class="arial-11-bld" style="top: -5px; position:relative;">&nbsp;Activar&nbsp;Puntos</span>');

			if (markers_fotos){
				markers_fotos.setVisibility(false);
			}
			
			if (markers_publicidades){
				markers_publicidades.setVisibility(false);
			}		
		}
	
//	var p = new Pause(60, map_2_0.removePopup(popup_busqueda));

	var id_timeout_pub_close = setTimeout("map_2_0.removePopup(popup_busqueda)", 7000);

	if(popup_medicion){
		var id_timeout_fot_close = setTimeout("map_2_0.removePopup(popup_medicion);", 7000);
	}
		
}



function addLabelBusqueda2()
{
//alert('label2');
	var lonlat_dir=new OpenLayers.LonLat($('lon2').value,$('lat2').value);
	var timeOutHide="4000";
	var codigoPostal="";
	var tbl_contenido="";
	var id_tbl_contenido="tbl_tooltip2";
	var espacios="&nbsp;&nbsp;&nbsp;";
	var titular='';
	tbl_contenido='<table bgcolor="#FFFFFF" id="'+id_tbl_contenido+'" border="0">';
	tbl_contenido+='<tr><td align="center" valign="middle"><span class="dir_tooltip">'+espacios+$('Str_Direccion2').value+espacios+'</span></td></tr>';
	if ($('TxtPer2').value.length > 0)
		tbl_contenido+='<tr><td align="center" valign="middle">'+espacios+$('TxtPer2').value+espacios+'</td></tr>';
	if ($('Comuna2').value.length > 0)
		tbl_contenido+='<tr><td align="center" valign="middle"><span class="comuna_tooltip">'+espacios+$('Comuna2').value+espacios+'</span></td></tr>';
	tbl_contenido+='</table>';
	if(popup_busqueda2){
		map_2_0.removePopup(popup_busqueda2);
	}
	popup_busqueda2 = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud2',lonlat_dir ,new OpenLayers.Size(100,100),tbl_contenido,null,true);
	map_2_0.addPopup(popup_busqueda2);
	id_timeout_pub_close2=setTimeout("map_2_0.removePopup(popup_busqueda2)",7000);
}
function cerrar_tool_busqueda(tool){
	if($(tool)){
		if($(tool).getStyle('visibility')=='visible'){
			$(tool).setStyle({'visibility':'hidden'});
		}
	}
}	
//funcion que se ejecuta al clickear mapa
function click_mapa()
{
	$('map_2_0').setStyle({'display': 'block'});
	$('map_UTM').setStyle({position: 'absolute' }); 
}
//funcion que se ejecuta al clickear guia mapcity
function click_guia() 
{
	$('map_UTM').setStyle({position: 'relative' });
	$$('.txt_slider').each(function(elem) {
		elem.setStyle({'visibility':'hidden'});
	});
	$('slider_track').setStyle({'visibility':'hidden'});
}
//funcion que se ejecuta al clickear mapa satelital
function click_satelital() {
	$('map_2_0').setStyle({'display': 'block'});
	$('map_UTM').setStyle({position: 'absolute' });
	$$('.txt_slider').each(function(elem) {
		elem.setStyle({'visibility':'visible'});
	});
	$('slider_track').setStyle({'visibility':'visible'});
}
function purge(d) {
	try {
		var a, i, l, n;
		a = d.childNodes;
		if (a) {
			l = a.length;
			for (i = 0; i < l; i += 1) {
				purge(d.childNodes[i]);
			}
		}
		a = d.attributes;
		if (a) {
			l = a.length;
			for (i = 0; i < l; i += 1) {
				n = a[i].name;
				if (typeof d[n] === 'function') d[n] = null;
			}
		}
		
	} catch(e) { alert(e.message); alert(a[i].name); alert(typeof d[n]); }
}

function verVentanaPrototypeIFrame(ventana,url){
	if(win_prototype)
		win_prototype.hide();

	var w=320;
	var h=500;
	if(!win_prototype_iframe){
		win_prototype_iframe = new Window({
			className: "alphacube", 
			width:w, 
			height:h,
			top:220,
			left:5,
			destroyOnClose: false, 
			recenterAuto:false,
			resizable:false,
			minimizable:false,
			maximizable:false,
			draggable:true,
			closable:true,
			id:"window_form_iframe",
			zIndex:zIndexWinPrototype
		});
		win_prototype_iframe.setURL(url);
		win_prototype_iframe.show();
	}else{
		win_prototype_iframe.setSize(w,h);
		win_prototype_iframe.setURL(url);
		win_prototype_iframe.show();
	}
	win_prototype_iframe.setZIndex(zIndexWinPrototype);

}

function verVentanaPrototype(ventana,url){
	//COMERCIO ADD
	if(win_prototype_iframe)
		win_prototype_iframe.hide();

	var w=200;
	var h=470;
	var tit="";
	switch (ventana) 
	{ 
		case "celular" : 
			w=450;
			h=450;
			break;
		case "mail" : 
			w=340;
			h=230;
			break;
		case "censo" : 
			w=300;
			h=470;
			tit="Informaci&oacute;n Censal";
			break;
		default : 
			w=280;
			h=460;
			switch ($('ciudad').value) 
			{ 
				case "vregion" : 
					w=280;
					h=450;
					break;
				case "baires" : 
					w=180;
					h=400;
					break;
				case "riojaneiro" : 
					w=180;
					h=400;	
					break; 
				case "saopaulo" : 
					w=180;
					h=400;	
					break; 
				case "mexicodf" : 
					w=210;
					h=308;
					break; 
				case "lima" : 
					w=180;
					h=370;	
					break; 
				default : 
					w=240;
					h=450;
			}
			break;
	}

	var opt = { method:'post' ,
		onComplete: function (transport) {
			//alert(transport.responseText);
			if(!win_prototype){
				win_prototype = new Window({
					className: "alphacube", 
					title: tit, 
					width:w, 
					height:h,
					top:220,
					left:5,
					destroyOnClose: false, 
					recenterAuto:false,
					resizable:false,
					minimizable:false,
					maximizable:false,
					draggable:true,
					closable:true,
					id:"window_form_buscador",
					zIndex:zIndexWinPrototype
				});
				win_prototype.getContent().update(transport.responseText);
				win_prototype.show();
			}else{
				win_prototype.setZIndex(zIndexWinPrototype);
				win_prototype.setSize(w,h);
				win_prototype.getContent().update(transport.responseText);
				win_prototype.show();
			}
			if (ventana.indexOf('celular')>-1)
			{	
				//alert('|'+ventana+'|');
				//alert(AjaxObjGetCodigo);
				//if (AjaxObjGetCodigo.codigoEstaCargado==false)
				//{
					AjaxObjGetCodigo.init('direcc');
					AjaxObjGetCodigo.startRequest();
				//}
			}
		},
			onFailure:	function () {alert('Error al cargar formulario');}
		};
		new Ajax.Request(url,opt);
}

function checkMail()
{
	var x = document.form.EmailOrigen.value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)) 
	{
		x = document.form.EmailDestino.value;
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (filter.test(x)) 
		{
			url = 'EnviarEMail.asp?'+$('form_email').serialize()+'&'+$('direcc').serialize();
			//alert(url);
			var opt = 
			{	
				method:'GET' ,
				onComplete: function (transport) 
				{
					if (transport.responseText == 0)
					{
						win_prototype.hide();
						alert('El email fue enviado con exito.');
					}
					else
					{
						alert('Se produjo un error al enviar el mail.');
					}
				},
					onFailure:	function () {alert('Error no fue posible enviar su Email');
				}
			};
			new Ajax.Request(url,opt);
			
			return true;
		}
		else 
		{
			alert('El email de destino no es valido');
			document.form.EmailDestino.focus();
			return false;
		}
	}
	else 
	{
		alert('El email de origen no es valido');
		document.form.EmailOrigen.focus();
		return false;
	}
}

function openToolTipsRicoOld(x,y,tbl_contenido,timeHideToolTips)
{
	var espacios="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	var tbl="";
	if ($('id_tooltip')) $('id_tooltip').remove();

	tooltip_element = new Element('div', { 'class':'tooltip_pub','id':'id_tooltip'} );
	$('map_2_0').insert(tooltip_element, { position: "content" });
	tooltip_element.setStyle({'zIndex':zIndexToolTps});

	var ancho=$('map_2_0').getWidth();
	var alto=$('map_2_0').getHeight();

	if ( parseInt(x) > parseInt(ancho/2) )
	{
		var celda1='<td width="20" valign="top" align="center"><img src="/mapcity_2_0/images/utilidades/cerrar.gif" class="cerrar_tooltip" onClick="cerrar_label(\'id_tooltip\');resetJGMedicion();" onMouseOver="sobreCruz=true" onMouseOut="sobreCruz=false"></td>';
		var celda2='<td width="20"></td>';
	}
	else
	{
		var celda1='<td width="20"></td>';
		var celda2='<td width="20" valign="top" align="center"><img src="/mapcity_2_0/images/utilidades/cerrar.gif" class="cerrar_tooltip" onClick="cerrar_label(\'id_tooltip\');resetJGMedicion();" onMouseOver="sobreCruz=true" onMouseOut="sobreCruz=false"></td>';
	}

	var id_tbl_contenido="id_tbl_tooltips";
	var tbl='<table id="id_tbl_tooltips" cellpadding="0" cellspacing="0" bgcolor="#f9ffee" border="0"><tr>';
	tbl+=celda1;
	tbl+='<td>'+tbl_contenido+'</td>';
	tbl+=celda2;
	tbl+='</tr></table>';

	tooltip_element.update(tbl);


	var ancho_tooltip=$('id_tooltip').getWidth();
	var alto_tooltip=$('id_tooltip').getHeight();
	var defCorner="all";
	var ancho_icon = 10;
	var offsetx=10;
	var offsety=10;
	if ( parseInt(x) > parseInt(ancho/2) )
	{
		if ( parseInt(y) > parseInt(alto/2) )
		{
			// Cuadrante  Inferior Derecho Bottom Right
			defCorner = "tl tr bl";
			x = x - ancho_tooltip;
			y = y - alto_tooltip - ancho_icon;
			x = x - offsetx;
			y = y - offsety;
		}
		else
		{
			// Cuadrante  Superior Derecho Top Right
			defCorner = "tl bl br";
			x = x - ancho_tooltip;
			x = x - offsetx;
			y = y + offsety;
		}
	}
	else
	{
		if ( parseInt(y) > parseInt(alto/2) )
		{
			// Cuadrante  Inferior Izquierdo
			defCorner = "tl tr br";
			y = y - alto_tooltip;
			x = x + offsetx;
			y = y - offsety;
		}
		else
		{
			// Cuadrante  Superior Izquierdo
			defCorner = "tr bl br";
			x = x + offsetx;
			y = y + offsety;
		}
	}

	$('id_tooltip').setStyle({'left':x+'px'});
	$('id_tooltip').setStyle({'top':y+'px'});
	$('id_tooltip').setStyle({'visibility':'visible'});
	$('id_tooltip').setStyle({'width':eval($(id_tbl_contenido).getWidth())+'px'});

	// Asignamos  Api Rico
	OpenLayers.Rico.Corner.round($('id_tooltip'), {corners:defCorner,
													bgColor: "transparent", 
													color: "#f9ffee", 
													blend: false, 
													compact:false});

	id_timeout_pub_close=setTimeout("if($('id_tooltip')) cerrar_label('id_tooltip');lonlat_publicidad=''",timeHideToolTips);
}

function openToolTipsRico(x,y,tbl_contenido,timeHideToolTips)
{
	var espacios="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	var tbl="";
	if ($('id_tooltip')) $('id_tooltip').remove();

	tooltip_element = new Element('div', { 'class':'tooltip_pub','id':'id_tooltip'} );
	$('map_2_0').insert(tooltip_element, { position: "content" });
	tooltip_element.setStyle({'zIndex':zIndexToolTps});

	var ancho=$('map_2_0').getWidth();
	var alto=$('map_2_0').getHeight();

	if ( parseInt(x) > parseInt(ancho/2) )
	{
		var celda1='<td width="20" valign="top" align="center"><img src="/mapcity_2_0/images/utilidades/cerrar.gif" class="cerrar_tooltip" onClick="cerrar_label(\'id_tooltip\');resetJGMedicion();" onMouseOver="sobreCruz=true" onMouseOut="sobreCruz=false"></td>';
		var celda2='<td width="20"></td>';
	}
	else
	{
		var celda1='<td width="20"></td>';
		var celda2='<td width="20" valign="top" align="center"><img src="/mapcity_2_0/images/utilidades/cerrar.gif" class="cerrar_tooltip" onClick="cerrar_label(\'id_tooltip\');resetJGMedicion();" onMouseOver="sobreCruz=true" onMouseOut="sobreCruz=false"></td>';
	}

	var id_tbl_contenido="id_tbl_tooltips";
	var tbl='<table id="id_tbl_tooltips" cellpadding="0" cellspacing="0" bgcolor="#f9ffee" border="0"><tr>';
	tbl+=celda1;
	tbl+='<td>'+tbl_contenido+'</td>';
	tbl+=celda2;
	tbl+='</tr></table>';

	tooltip_element.update(tbl);

	var ancho_tooltip=$('id_tooltip').getWidth();
	var alto_tooltip=$('id_tooltip').getHeight();
	var defCorner="all";
	var ancho_icon = 10;
	var offsetx=10;
	var offsety=10;

	if ( parseInt(x) > parseInt(ancho/2) )
	{
		if ( parseInt(y) > parseInt(alto/2) )
		{
			// Cuadrante  Inferior Derecho Bottom Right
			defCorner = "tl tr bl";
			x = parseInt(x)-ancho_tooltip;
			y = parseInt(y)-alto_tooltip-ancho_icon;
			x = parseInt(x)-offsetx;
			y = parseInt(y)-offsety;
		}
		else
		{
			// Cuadrante  Superior Derecho Top Right
			defCorner = "tl bl br";
			x = parseInt(x)-ancho_tooltip;
			x = parseInt(x)-offsetx;
			y = parseInt(y)+offsety;
		}
	}
	else
	{
		if ( parseInt(y) > parseInt(alto/2) )
		{
			// Cuadrante  Inferior Izquierdo
			defCorner = "tl tr br";
			y = parseInt(y)-alto_tooltip;
			x = parseInt(x)+offsetx;
			y = parseInt(y)-offsety;
		}
		else
		{
			// Cuadrante  Superior Izquierdo
			defCorner = "tr bl br";
			x = parseInt(x)+offsetx;
			y = parseInt(y)+offsety;
		}
	}
	$('id_tooltip').setStyle({'left':x+'px'});
	$('id_tooltip').setStyle({'top':y+'px'});
	$('id_tooltip').setStyle({'visibility':'visible'});
	$('id_tooltip').setStyle({'width':eval($(id_tbl_contenido).getWidth())+'px'});
	// Asignamos  Api Rico
	OpenLayers.Rico.Corner.round($('id_tooltip'), {corners:defCorner,
													bgColor: "transparent", 
													color: "#f9ffee", 
													blend: false, 
													compact:false});

	id_timeout_pub_close=setTimeout("if($('id_tooltip')) cerrar_label('id_tooltip');lonlat_publicidad=''",timeHideToolTips);
}

function openToolTipsRico2(lonlat,tbl_contenido,timeHideToolTips)
{
	
	lonlat_publicidad=lonlat;
	clearTimeout(id_timeout);
	var espacios="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	var tbl="";
	if ($('id_tooltip2')) $('id_tooltip2').remove();

	tooltip_element = new Element('div', { 'class':'tooltip_pub','id':'id_tooltip2'} );
	$('map_2_0').insert(tooltip_element, { position: "content" });
	tooltip_element.setStyle({'zIndex':zIndexToolTps});

	pixel_pos=map_2_0.getPixelFromLonLat(lonlat);
	x=pixel_pos.x;
	y=pixel_pos.y;
	var ancho=$('map_2_0').getWidth();
	var alto=$('map_2_0').getHeight();

	if ( parseInt(x) > parseInt(ancho/2) )
	{
		var celda1='<td width="20" valign="top" align="center"><img src="/mapcity_2_0/images/utilidades/cerrar.gif" class="cerrar_tooltip" onClick="cerrar_label(\'id_tooltip2\')"></td>';
		var celda2='<td width="20"></td>';
	}
	else
	{
		var celda1='<td width="20"></td>';
		var celda2='<td width="20" valign="top" align="center"><img src="/mapcity_2_0/images/utilidades/cerrar.gif" class="cerrar_tooltip" onClick="cerrar_label(\'id_tooltip2\')"></td>';
	}

	var id_tbl_contenido="id_tbl_tooltips2";
	var tbl='<table id="id_tbl_tooltips2" cellpadding="0" cellspacing="0" bgcolor="#f9ffee" border="0"><tr>';
	tbl+=celda1;
	tbl+='<td>'+tbl_contenido+'</td>';
	tbl+=celda2;
	tbl+='</tr></table>';

	tooltip_element.update(tbl);

	var ancho_tooltip=$('id_tooltip2').getWidth();
	var alto_tooltip=$('id_tooltip2').getHeight();
	var offsetx=20;
	var offsety=20;
	var defCorner="all";
	var ancho_icon = 10;
	if ( parseInt(x) > parseInt(ancho/2) )
	{
		if ( parseInt(y) > parseInt(alto/2) )
		{
			// Cuadrante  Inferior Derecho Bottom Right
			defCorner = "tl tr bl";
			x = x - ancho_tooltip;
			y = y - alto_tooltip - ancho_icon;
			x = x - offsetx;
			y = y - offsety;
		}
		else
		{
			// Cuadrante  Superior Derecho Top Right
			defCorner = "tl bl br";
			x = x - ancho_tooltip;
			x = x - offsetx;
			y = y + offsety;
		}
	}
	else
	{
		if ( parseInt(y) > parseInt(alto/2) )
		{
			// Cuadrante  Inferior Izquierdo
			defCorner = "tl tr br";
			y = y - alto_tooltip;
			x = x + offsetx;
			y = y - offsety;
		}
		else
		{
			// Cuadrante  Superior Izquierdo
			defCorner = "tr bl br";
			x = x + offsetx;
			y = y + offsety;
		}
	}

	$('id_tooltip2').setStyle({'left':x+'px'});
	$('id_tooltip2').setStyle({'top':y+'px'});
	$('id_tooltip2').setStyle({'visibility':'visible'});
	$('id_tooltip2').setStyle({'width':eval($(id_tbl_contenido).getWidth())+'px'});
	// Asignamos  Api Rico
	OpenLayers.Rico.Corner.round($('id_tooltip2'), {corners:defCorner,
													bgColor: "transparent", 
													color: "#f9ffee", 
													blend: false, 
													compact:false});
	id_timeout2=setTimeout("if($('id_tooltip2')) cerrar_label('id_tooltip2');lonlat_publicidad=''",timeHideToolTips);
}

function openToolTipsFotoRico(x,y,tbl_contenido)
{
	//alert('rico');
	var espacios="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	var tbl="";
	if ($('id_tooltip')) $('id_tooltip').remove();
	tooltip_element = new Element('div', { 'class':'tooltip_pub','id':'id_tooltip'} );
	$('map_2_0').insert(tooltip_element, { position: "content" });
	tooltip_element.setStyle({'zIndex':zIndexToolTps});

	var ancho=$('map_2_0').getWidth();
	var alto=$('map_2_0').getHeight();

	var celda1='<td width="20"></td>';
	var celda2='<td width="20"></td>';

	var id_tbl_contenido="id_tbl_tooltips_foto";
	var tbl='<table id="id_tbl_tooltips_foto" cellpadding="0" cellspacing="0" bgcolor="#f9ffee" border="0"><tr>';
	tbl+=celda1;
	tbl+='<td>'+tbl_contenido+'</td>';
	tbl+=celda2;
	tbl+='</tr></table>';

	tooltip_element.update(tbl);

	var ancho_tooltip=$('id_tooltip').getWidth();
	var alto_tooltip=$('id_tooltip').getHeight();
	var defCorner="all";
	var ancho_icon = 10;
	if ( parseInt(x) > parseInt(ancho/2) )
	{
		if ( parseInt(y) > parseInt(alto/2) )
		{
			// Cuadrante  Inferior Derecho Bottom Right
			defCorner = "tl tr bl";
			x = parseInt(x) - ancho_tooltip;
			y = parseInt(y) - alto_tooltip - ancho_icon;
		}
		else
		{
			// Cuadrante  Superior Derecho Top Right
			defCorner = "tl bl br";
			x = parseInt(x) - ancho_tooltip;
		}
	}
	else
	{
		if ( parseInt(y) > parseInt(alto/2) )
		{
			// Cuadrante  Inferior Izquierdo
			defCorner = "tl tr br";
			y = parseInt(y) - alto_tooltip;
		}
		else
		{
			// Cuadrante  Superior Izquierdo
			defCorner = "tr bl br";
		}
	}
	var defCorner="all";

	$('id_tooltip').setStyle({'left':x+'px'});
	$('id_tooltip').setStyle({'top':y+'px'});
	$('id_tooltip').setStyle({'visibility':'visible'});
	$('id_tooltip').setStyle({'width':eval($(id_tbl_contenido).getWidth())+'px'});
	// Asignamos  Api Rico
	alert('rico');
	OpenLayers.Rico.Corner.round($('id_tooltip'), {corners:defCorner,
													bgColor: "transparent", 
													color: "#f9ffee", 
													blend: false, 
													compact:false});
	
}

function resetJGMedicion()
{
	if(jg) jg.clear();
	puntoAntX = new Array();
	puntoAntY = new Array();
}

function resetJGRuta()
{
	if(jg_ruta) jg_ruta.clear();
	puntoAntX_ruta = new Array();
	puntoAntY_ruta = new Array();
}


function loadFrameImprimeMapa(strFrameName){	
	var strURL = 'ImprimeMapa.asp'
	+ '?mapa=http://beta.mapcity.com/Temp/temp_c691ced8A80c9A429fA9559Ae29d8533c79f.gif'
	+ '&GrillaPagina='+document.getElementById('GrillaPagina').value
	+ '&GrillaFila='+document.getElementById('GrillaFila').value
	+ '&GrillaColumna='+document.getElementById('GrillaColumna').value
	+ '&Str_Direccion='+document.getElementById('Str_Direccion').value
	+ '&comuna='+getObjFromForm('direcc', 'Comuna1',true).value;		
	
	document.getElementById(strFrameName).src = strURL;
}

function PrintThisFrame(strFrameName) 
{  
  document.ImprimeMapa.focus();
  document.ImprimeMapa.print();

} 
function ver_layer(tipo,centrar){
	switch (tipo){
		case 'mapa':
			guia_open=false;
			satelite_open=false;
			if (map_UTM_Obj)
			{
				if($('map_UTM')) $('map_UTM').setStyle({'width':'0px','height':'0px'});
				var bound=map_UTM_Obj.getExtent();
				var center=map_UTM_Obj.getCenter();
				var zoom=map_UTM_Obj.getZoom();
				var opt={
					method:'post',
					onComplete:function(transport){
						var coord=transport.responseText.evalJSON(true);
						var lonlat_center = new OpenLayers.LonLat(coord.X,coord.Y);
						if($('map_2_0').getStyle('width')=='0px'){
							$('map_2_0').setStyle({
								width:'100%',
								height:'700px'
							});
							$('logo').setStyle({'bottom':'0px'});
							$('norte').setStyle({'top':'0px', 'right':'40px'});
							init_tools('map_2_0');
							addFlechas('map_2_0','map_UTM');
							map_2_0.layers.each(function(layer){
								if(layer.name.indexOf('check_')>-1) map_2_0.removeLayer(layer);
							});
//alert(lon+' '+lat);
						}
						map_2_0.setCenter(new OpenLayers.LonLat(coord.X+62,coord.Y+40),zoom);

						//map_UTM_Obj.destroy();
						//map_UTM_Obj=null;


					},
					onFailure:function(){
						alert('Lo sentimos, no se pudo obtener xmax,ymax');
					}
				};
				new Ajax.Request('FuncionesGIS.asp?codEntrada=29179&codSalida=4326&geometry=POINT('+center.lon+' '+center.lat+')&id='+idCiudad,opt);

			}

			if($('map_2_0').getStyle('width')=='0px'){
				$('map_2_0').setStyle({
					width:'100%',
					height:'700px'
				}); 
				$('logo').setStyle({'bottom':'0px'});
				$('norte').setStyle({'top':'0px', 'right':'40px'});

				init_tools('map_2_0');
				addFlechas('map_2_0','map_UTM');
				map_2_0.layers.each(function(layer){
					if(layer.name.indexOf('check_')>-1) map_2_0.removeLayer(layer);
				});

			}


			//loadControl('map_2_0');
			if(map_2_0.getLayerIndex(layer_satelite_chile) > -1){
				slider.setEnabled();
				slider.setValue(0);
			}

			if(layer_guia_chile) layer_guia_chile.destroy();
			//if(layer_satelite_chile) layer_satelite_chile.destroy();

			hideFormBuscador();
			change_style('mapa_1','menu_map_off');
			change_style('mapa_0','mapa-on');
			change_pest('mapa','1','mapa-on');
			changeImage('menu_mapa_0','idx-busq02d.gif');
			changeImage('menu_mapa_1','idx-busq03.gif');

			//Para que aparesca nuevamente slider
			$$('.txt_slider').each(function(elem) {
				elem.setStyle({'visibility':'visible'});
			});
			$('slider_track').setStyle({'visibility':'visible'});
			
			//if ($('Producto').value == "DIRECCION" || $('Producto').value == "TELEFONO" || $('Producto').value == "INTERSECCION") map_2_0.setLayerIndex(markers_busqueda,zIndexEstrella);
		
			break;
		
		case 'satelite':
			layer_base_chile.setVisibility(false);
			guia_open=false;
			satelite_open = true;

			

			if($('map_UTM').getStyle('width')!='0px'){
				$('map_UTM').setStyle({
					width:'0px',
					height:'0px'
				});
				/*map_UTM_Obj.destroy();
				map_UTM_Obj=null;*/
			}
			if($('map_2_0').getStyle('width')=='0px'){
				$('map_2_0').setStyle({
					width:'100%',
					height:'700px'
				});
				ctlMousePosition=new OpenLayers.Control.MousePosition();
				map_2_0.addControl(ctlMousePosition);
				$('logo').setStyle({'bottom':'0px'});
				$('norte').setStyle({'top':'0px', 'right':'40px'});

				init_tools('map_2_0');
				addFlechas('map_2_0','map_UTM');
			}


			
			if(map_2_0.getLayerIndex(layer_satelite_chile) == -1){
				layer_satelite_chile = new OpenLayers.Layer.TileCache( "Chile Satelital",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'chile_satelital'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'}
				);
				map_2_0.addLayer(layer_satelite_chile);
				map_2_0.setLayerIndex(layer_satelite_chile,1);
			}
			layer_satelite_chile.setIsBaseLayer(false);
			layer_satelite_chile.setVisibility(true);
			
			if(layer_guia_chile) layer_guia_chile.destroy();
			
			hideFormBuscador();
			change_style('mapa_1','mapa-on');
			change_style('mapa_0','menu_mapa_off');
			change_pest('mapa','3','mapa-on');
			changeImage('menu_mapa_0','idx-busq03.gif');
			changeImage('menu_mapa_1','idx-busq04d.gif');
			slider.setEnabled();
			slider.setValue(1);
			
			if ($('Producto').value == "DIRECCION" || $('Producto').value == "TELEFONO" || $('Producto').value == "INTERSECCION") map_2_0.setLayerIndex(markers_busqueda,zIndexEstrella);
			
		break;
		case 'guia':

			guia_open=true;
			if($('map_UTM').getStyle('width')!='0px'){
				$('map_UTM').setStyle({
					width:'0px',
					height:'0px'
				});
				/*map_UTM_Obj.destroy();
				map_UTM_Obj=null;*/
			}
			if($('map_2_0').getStyle('width')=='0px'){
				$('map_2_0').setStyle({
					width:'100%',
					height:'700px'
				});
				ctlMousePosition=new OpenLayers.Control.MousePosition();
				map_2_0.addControl(ctlMousePosition);
				$('logo').setStyle({'bottom':'0px'});
				$('norte').setStyle({'top':'0px', 'right':'40px'});

				init_tools('map_2_0');
				addFlechas('map_2_0','map_UTM');
			}


			
			if(map_2_0.getLayerIndex(layer_guia_chile) == -1){
				layer_guia_chile = new OpenLayers.Layer.TileCache( "Chile Guia",
						[
						 "http://mapa1.mapcity.com/tiles/"
						,"http://mapa2.mapcity.com/tiles/"
						,"http://mapa3.mapcity.com/tiles/"
						,"http://mapa4.mapcity.com/tiles/"
						]
						,'chile_guia'
						,{singleTile:false,buffer:0,transitionEffect: 'resize',format:'image/png'}
				);
				map_2_0.addLayer(layer_guia_chile);
				map_2_0.setLayerIndex(layer_guia_chile,1);
			}
			layer_guia_chile.setIsBaseLayer(false);
			layer_guia_chile.setVisibility(true);
			
			if(layer_satelite_chile) layer_satelite_chile.destroy();
			
			hideFormBuscador();
			change_style('mapa_1','menu_mapa_off');
			change_style('mapa_0','menu_mapa_off');
			change_pest('mapa','2','mapa-on');
			changeImage('menu_mapa_0','idx-busq04d.gif');
			changeImage('menu_mapa_1','idx-busq02d.gif');
			slider.setDisabled();

			//REGISTRO DE EVENTOS SOBRE EL MAPA
		break;
	}
	
}
var win,clean;
var controls_map_UTM_Obj;
var gif_on_off;
var draw,block;
var popup_medicion,popup_medicion2;
var destuir_draw = false;
var pointsArray = new Array();
var pointsString = "";
var tramo = 0;
function loadControl(mapa){
//alert(mapa);
        //CAPA PA CONTROLES DE DIBUJO
		if (mapa=='map_UTM')
		{
			zoombox_map_UTM_Obj = new OpenLayers.Control.ZoomBox();
			var panel_map_UTM_Obj = new OpenLayers.Control.Panel({defaultControl: zoombox_map_UTM_Obj});
			panel_map_UTM_Obj.addControls([zoombox_map_UTM_Obj]);
			controls_map_UTM_Obj = {
				drag: new OpenLayers.Control.DragFeature(draw),
				zoombox: panel_map_UTM_Obj //Para zoomin y pan
			};
			//AGREGO TODAS LAS HERRAMIENTAS AL MAPA
			for(var key in controls_map_UTM_Obj) {
				map_UTM_Obj.addControl(controls_map_UTM_Obj[key]);
			}
			zoombox_map_UTM_Obj.deactivate();
		}else{
			//FUNCION PARA MEDIR DISTANCIAS Y AREAS
			var optDraw = {
				preFeatureInsert:function(feat){}
			};
				/*
				draw = new OpenLayers.Layer.Vector("Draw Features Layer",optDraw);
				draw.displayInLayerSwitcher=false;
				map_2_0.addLayer(draw);
				*/
				
				draw = new OpenLayers.Layer.Vector("Draw Features Layer");					
				draw.displayInLayerSwitcher=false;
				map_2_0.addLayer(draw);

			//CONTROL DE ZOOMBOX PARA EL MAPA
				zoombox_map_2_0 = new OpenLayers.Control.ZoomBox();
			//PANEL QUE CONTIENE AL ZOOMBOX
			var panel_map_2_0 = new OpenLayers.Control.Panel({defaultControl: zoombox_map_2_0});
				panel_map_2_0.addControls([zoombox_map_2_0]);
			//CAPA QUE CAPTURA LAS CORDENANAS DE LA MANZANA
				puntoBlock = new OpenLayers.Layer.Vector("Punto Block Layer");
				puntoBlock.displayInLayerSwitcher=false;
			//CALLBACK QUE SE HACE CUANDO SE CONSULTA UNA MANZANA
				puntoBlock.onFeatureInsert=function(feature) { 
					viewConsulta(feature,"block"); 
				};
			map_2_0.addLayer(puntoBlock);
			puntoBlock.setVisibility(false);
			
			//CAPA DONDE SE PINTA LA MANZANA
				block = new OpenLayers.Layer.Vector("Block Layer");
				block.displayInLayerSwitcher=false;
				map_2_0.addLayer(block);
				block.setVisibility(false);	
			//CAPA QUE CAPTURA LAS CORDENADAS DE LA CALLE
				puntoStreet = new OpenLayers.Layer.Vector("Punto Street Layer");
				puntoStreet.displayInLayerSwitcher=false;
			//CALLBACK QUE SE HACE CUANDO SE CONSULTA UNA CALLE
				puntoStreet.onFeatureInsert=function(feature) {
					viewConsulta(feature,"street");
				};
			map_2_0.addLayer(puntoStreet);
			
			//CAPA DONDE SE PINTA LA CALLE
				street = new OpenLayers.Layer.Vector("Street Layer");
				street.displayInLayerSwitcher=false;
				map_2_0.addLayer(street);
			//CAPA DE MARKERS DE INFORMACION DE LA CALLE...

			//CAPA DE MARKERS DE INFORMACION DE LA DISTANCIA QUE SE ESTA MIDIENDO...
				var optline = {
					featureAdded:function(feature){
						geom_str = feature.geometry.toString();
						geom = geom_str.replace("LINESTRING(","");
						geom = geom.replace(")","");
						geom_array = geom.split(",");
						
						coord = geom_array[geom_array.length - 1];
						
						coord_array = coord.split(" ");
						//pixel = map_2_0.getPixelFromLonLat(new OpenLayers.LonLat(coord_array[0],coord_array[1]));
						
						
						if(popup_medicion){
							map_2_0.removePopup(popup_medicion);
						}
						popup_medicion = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud',new OpenLayers.LonLat(coord_array[0],coord_array[1]),new OpenLayers.Size(100,100),geometryData(feature));
						map_2_0.addPopup(popup_medicion);
						
						
						if(draw.features.length>1)
							draw.destroyFeatures([draw.features[0]]);
						//openToolTipsRico(pixel.x,pixel.y,geometryData(feature),20000);
						//destuir_draw = true;
						$('distPosition').setStyle({'display':'none'});

					}
					
				}

				controlline = new OpenLayers.Control.DrawFeature(draw,OpenLayers.Handler.Path,optline);

				controlline.handler.callbacks.point = function(p){
					if(draw.features.length > 0){
						draw.removeFeatures([draw.features[0]]);
						if(popup_medicion){
							map_2_0.removePopup(popup_medicion);
						}
						pointsArray = new Array();
					}
	
					pointsArray.push(new OpenLayers.Geometry.Point(p.x,p.y));
					if(pointsArray.length > 2){
						var lineGeom = new OpenLayers.Geometry.LineString(pointsArray);
						var lineFeature = new OpenLayers.Feature.Vector(lineGeom);
						if(popup_medicion){
							map_2_0.removePopup(popup_medicion);
							//alert('a');
						}
						
						$('distPosition').setStyle({'display':'block'});
						$('distPosition').update(geometryData(lineFeature));
						
						/*
						popup_medicion = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud',new OpenLayers.LonLat(p.x,p.y),new OpenLayers.Size(100,100),geometryData(lineFeature));
						//mostrarPop();
						map_2_0.addPopup(popup_medicion);			
						*/
					}
				};

				controlline.events.register("activate" , controlline, function(){
					draw.destroyFeatures(draw.features);
					pointsArray = new Array();
					if(popup_medicion){
						map_2_0.removePopup(popup_medicion);
					}
				});

			//CAPA DE VECTOR DE INFORMACION DE LA DISTANCIA QUE SE ESTA MIDIENDO...
			var optpoly = {
				
				featureAdded:function(feature){
                                        
					//alert(feature.geometry);
					geom_str = feature.geometry.toString();
					geom = geom_str.replace("POLYGON((","");
					geom = geom.replace("))","");
					geom_array = geom.split(",");
					
					coord = geom_array[geom_array.length - 2];
					
					coord_array = coord.split(" ");
					//pixel = map_2_0.getPixelFromLonLat(new OpenLayers.LonLat(coord_array[0],coord_array[1]));

					
					if(popup_medicion){
						map_2_0.removePopup(popup_medicion);
					}
					popup_medicion = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud',new OpenLayers.LonLat(coord_array[0],coord_array[1]),new OpenLayers.Size(100,100),geometryData(feature));
					map_2_0.addPopup(popup_medicion);

					
					if(draw.features.length>1)
						draw.destroyFeatures([draw.features[0]]);
//					openToolTipsRico(pixel.x,pixel.y,geometryData(feature),20000);
					//destuir_draw = true;
					$('distPosition').setStyle({'display':'none'});

				}
				
			}

			/*var optpoly = {
				featureAdded:function(feature){
					geom_str = feature.geometry.toString();
					geom = geom_str.replace("POLYGON((","");
					geom = geom.replace("))","");
					geom_array = geom.split(",");
					coord = geom_array[geom_array.length - 2];
					coord_array = coord.split(" ");
					
					//if(popup_medicion){
					//	map_2_0.removePopup(popup_medicion);
					//}
					//popup_medicion = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud',new OpenLayers.LonLat(coord_array[0],coord_array[1]),new OpenLayers.Size(100,100),geometryData(feature));
					//map_2_0.addPopup(popup_medicion);
					//
				}
			};
			*/
			
			controlpoly = new OpenLayers.Control.DrawFeature(draw,OpenLayers.Handler.Polygon,optpoly);
			controlpoly.events.register("activate" , controlpoly, function(){
				draw.destroyFeatures(draw.features);
			});
			/*
			controlpoly = new OpenLayers.Control.DrawFeature(draw, OpenLayers.Handler.Polygon, optpoly);
			*/
			
			controlpoly.handler.callbacks.point = function(p){
					if(draw.features.length > 0){
						draw.removeFeatures([draw.features[0]]);
						if(popup_medicion){
							map_2_0.removePopup(popup_medicion);
						}
						pointsArray = new Array();
					}
	
					pointsArray.push(new OpenLayers.Geometry.Point(p.x,p.y));
					if(pointsArray.length > 2){
						var lineRingGeom = new OpenLayers.Geometry.LinearRing(pointsArray);
						var lineGeom = new OpenLayers.Geometry.Polygon(lineRingGeom);
						var lineFeature = new OpenLayers.Feature.Vector(lineGeom);
						if(popup_medicion){
							map_2_0.removePopup(popup_medicion);
							//alert('a');
						}
						$('distPosition').setStyle({'display':'block'});
						$('distPosition').update(geometryData(lineFeature));
						
						/*
						popup_medicion = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud',new OpenLayers.LonLat(p.x,p.y),new OpenLayers.Size(100,100),geometryData(lineFeature));
						//mostrarPop();
						map_2_0.addPopup(popup_medicion);			
						*/
					}
			};
			
			/*
			controlpoly.events.register("activate" , controlpoly, function(){
				draw.destroyFeatures(draw.features);
				pointsArray = new Array();
				if(popup_medicion){
					map_2_0.removePopup(popup_medicion);
				}
			});
			*/
			
			
			//LOS CONTROLES O HERRAMIENTAS DEL MAPA
			controls_map_2_0 = {
			// herramienta que dibuja un punto 
				point: new OpenLayers.Control.DrawFeature(draw,OpenLayers.Handler.Point),
			// herramienta que dibuja una linea 
				line: controlline,
			// herramienta que dibuja un poligono 
				polygon: controlpoly,
			// herramienta que permite mover las figuras y el mapa 
				drag: new OpenLayers.Control.DragFeature(draw),
			//herramienta de cuadro de zoom 
			//zoom_in: panel_map_2_0,
				zoombox: panel_map_2_0,
			// herramienta que permite consultar las manzanas 
				block: new OpenLayers.Control.DrawFeature(puntoBlock,OpenLayers.Handler.Point),
			// herramienta que permite consultar las calles 
				street: new OpenLayers.Control.DrawFeature(puntoStreet,OpenLayers.Handler.Point),
			//herramienta que permite seleccionar y borrar una figura 
				select: new OpenLayers.Control.SelectFeature(
					draw,
					{
						clickout: true, toggle: true,
						multiple: true, hover: false,
						toggleKey: "ctrlKey", // ctrl key removes from selection
						multipleKey: "shiftKey", // shift key adds to selection
						onSelect: onFeatureSelect
					}
				)
				};

			//AGREGO TODAS LAS HERRAMIENTAS AL MAPA

			for(var key in controls_map_2_0) {				
				map_2_0.addControl(controls_map_2_0[key]);
				//alert(controls_map_2_0[key]);
			}
			//DESACTIVO EL ZOOMBOX...
			zoombox_map_2_0.deactivate();
		};
}

function mostrarPop() {
//		alert('a');
		map_2_0.addPopup(popup_medicion);
	}

//FUNCION QUE SE ENCARGA DE ACTIVAR Y DESACTIVAR LAS HERRAMIENTAS
//RECIBE COMO PARÃMETRO EL NOMBRE DE LA HERRAMIENTA...
//TIPOS DE HERRAMIENTAS:
//point: dibuja un punto
//line: dibuja una linea
//polygon: dibuja un poligono
//drag: arrastra el mapa y permite mover cualquier feature o figura
//zoombox: activa el cuadro de zoom
//block: permite consultar datos sobre una manzana
//street: permite consultar datos sobre una calle
//select: permite borrar una feature o figura
function toggleControl(button,mapa) 
{
	$('distPosition').setStyle({'display':'none'});
	CambiaCursor(button,mapa);
	estado_controles=button;
	if (map_UTM_Obj && $('map_UTM').getStyle('width')!='0px')
	{
		for(key in controls_map_UTM_Obj) 
		{
			var control = controls_map_UTM_Obj[key];
			if(button == key)
			{
				if(key=="zoombox")
					zoombox_map_UTM_Obj.activate();
				control.activate();
			}
			else
			{
				if(key=="zoombox") zoombox_map_UTM_Obj.deactivate();
				control.deactivate();
			}
		}	
	}else{
		if(draw) draw.destroyFeatures();
		if(street)street.destroyFeatures();	
		if(block) block.destroyFeatures();

		if(markers_distancia) 
		{
			markers_distancia.markers.each(function(mk){
				mk.destroy();
			});
			map_2_0.removeLayer(markers_distancia);
			markers_distancia.destroy();
			markers_distancia=null;
		}

		for(key in controls_map_2_0)
		{
			var control = controls_map_2_0[key];
			if(button == key)
			{
				if(key=="zoombox")
					zoombox_map_2_0.activate();
				else if(key=="zoomout")
					zoomout_map_2_0.activate();
				control.activate();
			}
			else
			{
				if(key=="zoombox") zoombox_map_2_0.deactivate();
				else if(key=="zoomout")
					zoomout_map_2_0.deactivate();
				control.deactivate();
			}
		}
	}
}

function cambia_estado(key,mapa){
	if(mapa=='map_2_0'){
		if(draw) draw.destroyFeatures();
		if(street)street.destroyFeatures();	
		if(block) block.destroyFeatures();
		if(markers_distancia) {
			markers_distancia.markers.each(function(mk){
				mk.destroy();
			});
			map_2_0.removeLayer(markers_distancia);
			markers_distancia.destroy();
			markers_distancia=null;
			if($('tool_medicion')) $('tool_medicion').remove();
		}
		for(key in controls_map_2_0) {
			controls_map_2_0[key].deactivate();
		}
	}else{
		for(key in controls_map_UTM_Obj) {
			controls_map_UTM_Obj[key].deactivate();
		}	
	}
estado_controles=key;
}

//FUNCIONES DE NAVEGACION

//MOVERSE AL NORTE
function c_norte(mapa){
	if(mapa=='map_2_0'){
		map_2_0.pan(0,Math.round((-map_2_0.getSize().h / 2)));	
	}else{
		map_UTM_Obj.pan(0,Math.round((-map_UTM_Obj.getSize().h / 2)));
	}
}

//MOVERSE AL OESTE
function c_oeste(mapa){
	if(mapa=='map_2_0'){
		map_2_0.pan(Math.round((-map_2_0.getSize().w / 2)), 0);	
	}else{
		map_UTM_Obj.pan(Math.round((-map_UTM_Obj.getSize().w / 2)), 0);
	}
}
//MOVERSE AL ESTE
function c_este(mapa){
	if(mapa=='map_2_0'){
		map_2_0.pan(Math.round((map_2_0.getSize().w / 2)), 0);
	}else{
		
		map_UTM_Obj.pan(Math.round((map_UTM_Obj.getSize().w / 2)), 0);
	}
}
//MOVERSE AL SUR
function c_sur(mapa){
	if(mapa=='map_2_0'){
		map_2_0.pan(0,Math.round((map_2_0.getSize().h / 2)));
	}else{


		map_UTM_Obj.pan(0,Math.round((map_UTM_Obj.getSize().h / 2)));
	}
}

//CAMBIA COLOR AL PONERSE SOBRE LAS FLECHAS
function CambiaColorFlecha(puntoCardinal,tipo){	
	//Norte
	if (puntoCardinal=="NORTE")
	{
		if (tipo!="ON")
		{	
			document.images["idImagenFlecha1"].src = "mapcity_2_0/images/flechas/NorteSel.gif";
		}else
		{
			document.images["idImagenFlecha1"].src = "mapcity_2_0/images/flechas/Norte.gif";
		}		
	}
	//Sur
	if (puntoCardinal=="SUR")
	{
		if (tipo!="ON")
		{	
			document.images["idImagenFlecha2"].src = "mapcity_2_0/images/flechas/SurSel.gif";
		}else
		{
			document.images["idImagenFlecha2"].src = "mapcity_2_0/images/flechas/Sur.gif";
		}		
	}
	//Este
	if (puntoCardinal=="ESTE")
	{
		if (tipo!="ON")
		{	
			document.images["idImagenFlecha3"].src = "mapcity_2_0/images/flechas/EsteSel.gif";
		}else
		{
			document.images["idImagenFlecha3"].src = "mapcity_2_0/images/flechas/Este.gif";
		}		
	}
	//Oeste
	if (puntoCardinal=="OESTE")
	{
		if (tipo!="ON")
		{	
			document.images["idImagenFlecha4"].src = "mapcity_2_0/images/flechas/OesteSel.gif";
		}else
		{
			document.images["idImagenFlecha4"].src = "mapcity_2_0/images/flechas/Oeste.gif";
		}		
	}


}

//MOVERSE AL NOROESTE
function noroeste(){
	map_2_0.pan((-map_2_0.getSize().w / 4)*3, (-map_2_0.getSize().h / 4)*3);	
}
//MOVERSE AL NORESTE
function noreste(){
	map_2_0.pan((map_2_0.getSize().w / 4)*3, (-map_2_0.getSize().h / 4)*3);	
}
//MOVERSE AL SUROESTE
function suroeste(){
	map_2_0.pan((-map_2_0.getSize().w / 4)*3, (map_2_0.getSize().h / 4)*3);	
}
//MOVERSE AL SURESTE
function sureste(){
	map_2_0.pan((map_2_0.getSize().w / 4)*3, (map_2_0.getSize().h / 4)*3);	
}
//CALLBACKS!!!
//FUNCION QUE SE LLAMA CUANDO SE SELECCIONA UNA FIGURA
function onFeatureSelect(feature) {
	feature.destroy();
}

//FUNCION QUE MIDE LAS DISTANCIAS Y AREAS
//***** OJO CON ESTA FUNCION QUE DEBE LLAMARSE DESDE EL OPENLAYERS EN EL PATH.JS Y DESDE LA FUNCION ADDPOINT
function geometryData(feature){
		var unidad = "m";
        var unidadtramo = "m";
        var out='';
		var lpDistAcu = '';
		var lpDistTra = '';
        if(feature.geometry.CLASS_NAME == "OpenLayers.Geometry.LineString" ){
                //alert('aa');
                if(length(feature.geometry).toFixed(3) > 0){
                        if(length(feature.geometry).toFixed(3) > 999.999){
								var lpLngt = (length(feature.geometry)/1000).toFixed(3);
								var lpDist = new NumberFormat(lpLngt);
								lpDist.setSeparators(true, '.', ',')
								unidad = "km";
                                lpDistAcu = '' + lpDist.toFormatted() + ' ' + unidad +'';
                        }else{
								var lpLngt = length(feature.geometry).toFixed(3);
								var lpDist = new NumberFormat(lpLngt);
								lpDist.setSeparators(true, '.', ',')
                                unidad="m";
                                lpDistAcu = '' + lpDist.toFormatted() + ' '+ unidad +'';
                        }

						var geomString = feature.geometry.toString().replace("LINESTRING(","");
						var geomArray = geomString.replace(")","").split(",");
						if(geomArray.length>1){
							var pi = geomArray[geomArray.length - 2].split(" ");
							var pf = geomArray[geomArray.length - 1].split(" ");
							var pArray= [new OpenLayers.Geometry.Point(pi[0],pi[1]),new OpenLayers.Geometry.Point(pf[0],pf[1])];
							var lineGeom = new OpenLayers.Geometry.LineString(pArray);

							if(Math.abs(length(lineGeom)).toFixed(3) > 999.999) {
								  var lpLngt = Math.abs(length(lineGeom)/1000).toFixed(3);
								  var lpDist = new NumberFormat(lpLngt);
								  lpDist.setSeparators(true, '.', ',')
								  unidadtramo = "km";}
							else { 
								var lpLngt = Math.abs(length(lineGeom)).toFixed(3);
								var lpDist = new NumberFormat(lpLngt);
								lpDist.setSeparators(true, '.', ',')
								unidadtramo = "m";
							}
							
							lpDistTra = '' + lpDist.toFormatted() + ' ' + unidadtramo + '';
						}
						out  = "<table cellpadding='0' width='230' cellspacing='0' bordercolor='red' border='0'>";
						out += "<tr height='15'>";
						out += "<td align='left'>&nbsp;&nbsp;</td>";
						out += "<th colspan='3' align='center' >Informaci&oacute;n Medicion</th>";
						out += "<td align='left'>&nbsp;&nbsp;</td>";
						out += "</tr>"
						out += "<tr>";
						out += "<td align='left'>&nbsp;&nbsp;</td>";
						out += "<td align='left'>Distancia&nbsp;Acumulada&nbsp;</td>";
						out += "<td align='left'>:&nbsp;</td>";
						out += "<td align='right'><font color='red'>" + lpDistAcu + "</font></td>";
						out += "<td align='left'>&nbsp;&nbsp;</td>";
						out += "</tr>"
						out += "<tr>";
						out += "<td align='left'>&nbsp;&nbsp;</td>";
						out += "<td align='left'>Distancia&nbsp;Ultimo&nbsp;Tramo&nbsp;</td>";
						out += "<td align='left'>:&nbsp;</td>";
						out += "<td align='right'><font color='red'>" + lpDistTra + "</font></td>";
						out += "<td align='left'>&nbsp;&nbsp;</td>";
						out += "</tr>"
						out += "</table>"

                }else{
                        out=null;
                }

        }else {
                if(length(feature.geometry).toFixed(3) > 999.999){
						var lpLngt = (length(feature.geometry)/1000).toFixed(3);
						var lpDist = new NumberFormat(lpLngt);
						lpDist.setSeparators(true, '.', ',')
                        unidad = "km";
                        lpDistAcu = '' + lpDist.toFormatted() + ' '+unidad+'';
                }else{
						var lpLngt = length(feature.geometry).toFixed(3);
						var lpDist = new NumberFormat(lpLngt);
						lpDist.setSeparators(true, '.', ',')                        
						unidad="m";
                        lpDistAcu = '' + lpDist.toFormatted() + ' '+unidad+'';
                }
                if(area(feature.geometry).toFixed(3) > 999999.999){
					var lpAreaL = (area(feature.geometry)/1000000).toFixed(3);
					var lpAreaLn = new NumberFormat(lpAreaL);
					lpAreaLn.setSeparators(true, '.', ',')
                    lpDistTra = '' + lpAreaLn.toFormatted() + ' km2';
                }else{
					var lpAreaL = (area(feature.geometry)).toFixed(3);
					var lpAreaLn = new NumberFormat(lpAreaL);
					lpAreaLn.setSeparators(true, '.', ',')
                    lpDistTra = '' + lpAreaLn.toFormatted() + ' m2';
                }

				out  = "<table cellpadding='0' width='230' cellspacing='0' bordercolor='red' border='0'>";
				out += "<tr height='15'>";
				out += "<td align='left'>&nbsp;&nbsp;</td>";
				out += "<th colspan='3' align='center' >Informaci&oacute;n Medicion</th>";
				out += "<td align='left'>&nbsp;&nbsp;</td>";
				out += "</tr>"
				out += "<tr>";
				out += "<td align='left'>&nbsp;&nbsp;</td>";
				out += "<td align='left'>Total&nbsp;Perimetro&nbsp;</td>";
				out += "<td align='left'>:&nbsp;</td>";
				out += "<td align='right'><font color='red'>" + lpDistAcu + "</font></td>";
				out += "<td align='left'>&nbsp;&nbsp;</td>";
				out += "</tr>"
				out += "<tr>";
				out += "<td align='left'>&nbsp;&nbsp;</td>";
				out += "<td align='left'>Total&nbsp;Area&nbsp;</td>";
				out += "<td align='left'>:&nbsp;</td>";
				out += "<td align='right'><font color='red'>" + lpDistTra + "</font></td>";
				out += "<td align='left'>&nbsp;&nbsp;</td>";
				out += "</tr>"
				out += "</table>"


        }
        //$('result_calculos').update(out);
		//alert(out);
        return out;
}

//FUNCION QUE PERMITE VER INFORMACION DE UNA CALLE O MANZANA
//RECIBE COMO PARAMETRO UN PUNTO (FEATURE) Y UN TIPO DE CONSULTA...CALLE O MANZANA
function viewConsulta(feature,tipo){

	var punto = feature.geometry.toString();
	
	
	//block.destroyFeatures(block.features);
	//street.destroyFeatures(street.features);
	//if(markers_info.markers[0])markers_info.markers[0].destroy();
	if (sobrePaneo) {
		if(win) win.close();
		return false;
		
	}
	
	if(tipo == "block"){
		puntoBlock.destroyFeatures(puntoBlock.features);
		block.destroyFeatures(block.features);
		var bound = map_2_0.getExtent();
		new Ajax.Request(
			'recuperaInfo.asp?punto='+punto+'&tipo=block&id='+idCiudad,			
			{
				method:'get',
				onComplete: function(transport){
				
					var response = transport.responseText;
					var datos = response.evalJSON();
					//map_2_0.panTo(new OpenLayers.LonLat(datos.X,datos.Y));

					var geom = datos.POLYGON;
					dibujaManzana(geom);
					
					/*
					var arrxy = splitBlock(geom);
					var puntos = [];
					for(var i=0; i<arrxy.length ; i++){
							var point = arrxy[i].replace(" ",",");
							var spliti = point.split(",");
							var point = new OpenLayers.Geometry.Point(parseFloat(spliti[0]),parseFloat(spliti[1]));
							puntos.push(point);
					}
					var ring = new OpenLayers.Geometry.LinearRing(puntos);
					var rings = [];
					rings.push(new OpenLayers.Feature.Vector(ring));
					block.addFeatures(rings);
					block.setVisibility(true);
					//alert(datos.X+' '+datos.Y);
					*/

					var opt={
						method:'post',
						onComplete:function(transport){
							if(popup_medicion){
								map_2_0.removePopup(popup_medicion);
							}
							popup_medicion = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud',new OpenLayers.LonLat(datos.X,datos.Y),new OpenLayers.Size(300,300),transport.responseText,null,true);
							popup_medicion.autoSize=false;
							map_2_0.addPopup(popup_medicion)
							//clearTimeout(sDisplayTimer);
							//sDisplayTimer = setTimeout("map_2_0.addPopup(popup_medicion)",500);
						},
						onFailure:function(){
							alert('Lo sentimos, su consulta no pudo ser procesada');
						}
					};
					new Ajax.Request('GetCenso.asp?gid='+datos.GID+'&redcode='+datos.REDCODE+'&coordenada=0&xcenter='+datos.X+'&ycenter='+datos.Y,opt);
				},
				onFailure: function(){alert('Lo sentimos, su consulta no pudo ser procesada') }
			});
	}else{


		puntoStreet.destroyFeatures(puntoStreet.features);
		street.destroyFeatures(street.features);
		//alert('recuperaInfo.asp?punto='+punto+'&tipo=street&id='+idCiudad);
		new Ajax.Request(
			'recuperaInfo.asp?punto='+punto+'&tipo=street&id='+idCiudad,
			{
				method:'get',
				onComplete: function(transport){var response = transport.responseText;
					
					
					var response = transport.responseText;
					var datos = response.evalJSON();
					var geom = datos.POLYGON;
					var arrxy = splitStreet(geom);
					var puntos = [];

					for(var i=0; i<arrxy.length ; i++){
							var point = arrxy[i].replace(" ",",");
							var spliti = point.split(",");
							var point = new OpenLayers.Geometry.Point(parseFloat(spliti[0]),parseFloat(spliti[1]));
							puntos.push(point);
					}
					var style_orange = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
					//style_orange.strokeColor = "#FF3300";
					style_orange.strokeColor = "#0033FF";
					style_orange.strokeWidth=4;
					style_orange.strokeOpacity=1;
					style_orange.strokeLinecap="round";
					style_orange.hoverStrokeColor = "#CC2200";
					style_orange.hoverStrokeOpacity=1;
					style_orange.hoverStrokeWidth=10;
					style_orange.pointerEvents="visiblePainted";

					var linestring = new OpenLayers.Geometry.LineString(puntos);
					var linestrings = [];

					linestrings.push(new OpenLayers.Feature.Vector(linestring,{},style_orange));
					street.addFeatures(linestrings);

					alturas_array = new Array();
					alturas_array[0] = parseInt(datos.INIIZQ, 10);
					alturas_array[1] = parseInt(datos.INIDER, 10);
					alturas_array[2] = parseInt(datos.TERIZQ, 10);
					alturas_array[3] = parseInt(datos.TERDER, 10);
					
					alturas_array = bubbleSort(alturas_array, 0, alturas_array.length);

					min_altura = 0;
					max_altura = 0;
					for(i=0; i<4 ;i++){
					//	alert(alturas_array[i]);
					}
					
					for(i=0;i<4;i++){
						if ((alturas_array[i] > 0)) {
							if (min_altura > 0) {
								if((alturas_array[i] < min_altura)) {
									min_altura = alturas_array[i];
								}
							}
							else {
								min_altura = alturas_array[i];
							}
						}
					}
					
					for(i=0;i<4;i++){
						if ((alturas_array[i] > 0)) {
							if (max_altura > 0) {
								if((alturas_array[i] > max_altura)) {
									max_altura=alturas_array[i];
								}
							}
							else {
								max_altura = alturas_array[i];
							}
						}
					}
					
					//info="<span class='center'><span class='dir_tooltip'>"+datos.CLASE+" "+datos.NOMBRE+"</span>Alturas del  "+min_altura+" al "+max_altura+"</span>";
					nombre = datos.CLASE+" "+datos.NOMBRE;
					var szPref = ''
					//alert(datos.PREFIJO);
					if ((datos.PREFIJO == '1') || (datos.PREFIJO == '8') || (datos.PREFIJO == '9')){
						szPref = '0';
						}
					altura = "<b><span class='comuna_tooltip'>"+datos.COMUNA+"</span></b><br>Alturas del  "+szPref+min_altura+" al "+szPref+max_altura;
					
					var lonlat_calle = new OpenLayers.LonLat(datos.X,datos.Y);


					tabla="<table>";
					tabla+="<tr><td>"+nombre+"</td></tr>";
					tabla+="<tr><td>"+altura+"</td></tr>";
					tabla+="</table>";
					if(popup_medicion){
						map_2_0.removePopup(popup_medicion);
					}
					popup_medicion = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud',lonlat_calle,new OpenLayers.Size(100,100),tabla,null,true);
					map_2_0.addPopup(popup_medicion);
					
					/*pixel = map_2_0.getPixelFromLonLat(lonlat_calle);
					openToolTipsRico(pixel.x,pixel.y,tabla,20000);*/
				},
				onFailure: function(){
					alert('Something went wrong...') 
				}
			});
	}

}

function bubbleSort(inputArray, start, rest) {
for (var i = rest - 1; i >= start;  i--) {
for (var j = start; j <= i; j++) {
if (inputArray[j+1] < inputArray[j]) {
var tempValue = inputArray[j];
inputArray[j] = inputArray[j+1];
inputArray[j+1] = tempValue;
      }
   }
}
return inputArray;
}

function borrarCenso(){
	puntoBlock.destroyFeatures(puntoBlock.features);
	block.destroyFeatures(block.features);
}

//FUNCION SPLIT 
function splitBlock (arreglo){
	
	var retornotmp = arreglo.substring(15,arreglo.length-3);
	var retorno = retornotmp.split(",");

	
	return retorno;
}
//FUNCION SPLIT
function splitStreet (arreglo){
	
	var retornotmp = arreglo.substring(17,arreglo.length-2);
	var retorno = retornotmp.split(",");

	
	return retorno;
}



//FUNCION QUE ENTREGA EL LARGO..O EL PERIMETRO
function length(geometry) {
	var length = geometry.getLength();
	units="m";
	var inPerDisplayUnit = OpenLayers.INCHES_PER_UNIT[units];
	if(inPerDisplayUnit) {
		var inPerMapUnit = OpenLayers.INCHES_PER_UNIT[map_2_0.units];
		length *= (inPerMapUnit / inPerDisplayUnit);
	}
	return length;
}

//FUNCION QUE ENTREGA EL AREA O PERIMETRO
function area(geometry) {
	var area = geometry.getArea();
	units="m";
	var inPerDisplayUnit = OpenLayers.INCHES_PER_UNIT[units];
	if(inPerDisplayUnit) {
		var inPerMapUnit = OpenLayers.INCHES_PER_UNIT[map_2_0.units];
		area *= Math.pow((inPerMapUnit / inPerDisplayUnit), 2);
	}
	return area;
}

function calculaTramo(var1,var2){
	var total;
	total = Math.abs(var1 -var2);
}


var gif_on_off = 'moverse';
function setMouseOut(id,path)
{
	if (gif_on_off==id)
		$(id).src = path+id+'_on.gif';
	else
		$(id).src = path+id+'_off.gif';
}

function setMouseOver(id,path)
{
	$(id).src= path+id+'_over.gif';
}

function setOnClick(id,path)
{	
	tramo =0;
	pointsArray = new Array();
	if(popup_medicion){
		map_2_0.removePopup(popup_medicion);
	}
	puntoAntX = new Array();
	puntoAntY = new Array();
	puntoAntXcoord = new Array();
	puntoAntYcoord = new Array();
	finLinea = false;
	removeLabels();
	if(win) win.close();
	if ($('Producto').value == "DIRECCION" || $('Producto').value == "TELEFONO" || $('Producto').value == "INTERSECCION" || $('Producto').value == "RUTA"){
		if (markers_busqueda) 
		{
			//markers_busqueda.setZIndex(zIndexEstrella);
			if (map_UTM_Obj)
				map_UTM_Obj.setLayerIndex(markers_busqueda,zIndexEstrella);
			else
				map_2_0.setLayerIndex(markers_busqueda,zIndexEstrella);
		}
		if (markers_fotos)
		{
			//markers_fotos.setZIndex(zIndexFotos);
			if (map_UTM_Obj)
				map_UTM_Obj.setLayerIndex(markers_fotos,zIndexFotos);
			else
				map_2_0.setLayerIndex(markers_fotos,zIndexFotos);
		}
		if (markers_publicidades)
		{
			//markers_publicidades.setZIndex(zIndexPublicidad);
			if (map_UTM_Obj)
				map_UTM_Obj.setLayerIndex(markers_publicidades,zIndexPublicidad);
			else
				map_2_0.setLayerIndex(markers_publicidades,zIndexPublicidad);
		}
		if (markers_servicios) 
		{
			//markers_servicios.setZIndex(zIndexServicios);
			if (map_UTM_Obj)
				map_UTM_Obj.setLayerIndex(markers_servicios,zIndexServicios);
			else
				map_2_0.setLayerIndex(markers_servicios,zIndexServicios);
		}
	}
	//alert(id);
	//Enviar mapa por E-Mail
	if (id == "centrar")
	{
		centrarMapa();//mapcity.js
	}
	//Enviar mapa por E-Mail
	if (id == "enviar_mail")
	{	
		email();//mapcity.js
	}
	//Imprimir mapa
	if (id == "imprimir")
	{
		if (map_UTM_Obj)
		{
			mapFile="guia_chile_printer.map";
			var lonlat_center=map_UTM_Obj.getCenter();
			var escala=map_UTM_Obj.getScale();
		}
		else
		{
			mapFile=mapFilePrinter;
			var lonlat_center=map_2_0.getCenter();
			var escala=map_2_0.getScale();
		}

		var url2="ImprimeMapa.asp?lonCenter=" +lonlat_center.lon +"&latCenter=" +lonlat_center.lat + "&mapFile=" + mapFile + "&escala=" + escala;
		url2+="&lonDir="+ $('lon').value + "&latDir="+ $('lat').value + "&grillaPagina=" + $('GrillaPagina').value;
		url2+="&grillaFila=" + $('GrillaFila').value + "&grillaColumna=" + $('GrillaColumna').value + "&strDireccion=" + $('Str_Direccion').value;
		url2+="&comuna=" + $('Comuna1').value + "&entorno=" + document.getElementById('idEntorno').value;
		url2+="&layers=" + layersBase2MapFile;
		re=/ /g;

		var url=url2.replace(re,'+');
		var name="ImprimeMapa";
		var param="scrollbars=yes,menubar=yes,width=830,height=850,top=100,left=100";
		window.open(url,name,param);
	}
	//postear direccion
	if (id == "post")
	{
		createPost();//mapcity.js form1.jsp
	}
	
	if(id =="camaraFoto") {
		//if(cargandoFotos && cargandoPublicidad) return false;
		if (camaraEncendida)
		{
			camaraEncendida=false;
			$('camaraFoto').update('<img src="/mapcity_2_0/images/utilidades/camara_foto_off.png" title="Enciende capa de fotografias" style="z-index: 10000; width: 24px; height: 21px; cursor:hand;"/><span  class="arial-11-bld" style="top: -5px; position:relative;">&nbsp;Activar&nbsp;Puntos</span>');

			if (markers_fotos){
				markers_fotos.setVisibility(false);
			}
			
			if (markers_publicidades){
				markers_publicidades.setVisibility(false);
			}
		}
		else
		{
            camaraEncendida=true;
			$('camaraFoto').update('<img src="/mapcity_2_0/images/utilidades/camara_foto_on.png" title="Apaga capa de fotografias" style="z-index: 10000; width: 24px; height: 21px; cursor:hand;"/><span  class="arial-11-bld" style="top: -5px; position:relative;">&nbsp;Desactivar&nbsp;Puntos</span>');

			if (markers_fotos){
				if(!markers_fotos.getVisibility()){
					init_fotos();
					markers_fotos.setVisibility(true);
				}
			}
			else {
				markers_fotos = new OpenLayers.Layer.Markers("Fotos");
				map_2_0.addLayer(markers_fotos);				
				init_fotos();
				markers_fotos.setVisibility(true);
				}
				
			if (markers_publicidades){
				if (!markers_publicidades.getVisibility()){
					markers_publicidades.setVisibility(true);
				}
			}
			else {
				markers_publicidades = new OpenLayers.Layer.Markers("Publicidades",{format: 'image/png',transparent:true});
				map_2_0.addLayer(markers_publicidades);				
				init_publicidad();
				markers_publicidades.setVisibility(true);				
				}
		}
	}
	else
	{
		if (gif_on_off!='' && id==gif_on_off)
			$(gif_on_off).src=path+gif_on_off+'_off.gif';
		else {
			$(id).src=path+id+'_on.gif';
			$(gif_on_off).src=path+gif_on_off+'_off.gif';
		}
		gif_on_off = id;
	}
}

var lengueta_on_off = "img_herramientas";

function changeLengueta(id_img)
{
	$('norte').setStyle({'right':'40px'});
	switch (id_img.toLowerCase()) { 
		case "img_herramientas" :
			document.images["lengueta_1"].src = "mapcity_2_0/images/lengueta/esquina_superior_on.gif";
			document.images["lengueta_2"].src = "mapcity_2_0/images/lengueta/herrmientas_on.gif";
			document.images["lengueta_3"].src = "mapcity_2_0/images/lengueta/intermedio_on_off.gif";
			if (document.images["lengueta_4"]) document.images["lengueta_4"].src = "mapcity_2_0/images/lengueta/servicios_off.gif";
			if (document.images["lengueta_5"]) document.images["lengueta_5"].src = "mapcity_2_0/images/lengueta/esquina_inferior_off.gif";
			if (document.images["lengueta_8"]) document.images["lengueta_8"].src = "mapcity_2_0/images/lengueta/mapblog_off.gif";
//			document.images["lengueta_6"].src = "mapcity_2_0/images/lengueta/utilidades_off.gif";
//			document.images["lengueta_7"].src = "mapcity_2_0/images/lengueta/esquina_inferior_off.gif";
			if (document.images["lengueta_9"]) document.images["lengueta_9"].src = "mapcity_2_0/images/lengueta/esquina_inferior_off.gif";
			if ($('tab_servicios_content')) $('tab_servicios_content').setStyle({'visibility':'hidden'});
			if ($('tab_utilidades_content')) $('tab_utilidades_content').setStyle({'visibility':'hidden'});
			if ($('tab_maplog_content')){
				$('tab_maplog_content').setStyle({'visibility':'hidden'});
				if (markers_post){
					if (markers_post.getVisibility()){
						markers_post.setVisibility(false);
					}
				}
			}
			if($('tab_herramientas_content'))
			{
				if (lengueta_on_off==id_img.toLowerCase())
					if($('tab_herramientas_content').getStyle('visibility')=='hidden') $('tab_herramientas_content').setStyle({'visibility':'visible'});
					else $('tab_herramientas_content').setStyle({'visibility':'hidden'});
				else $('tab_herramientas_content').setStyle({'visibility':'visible'});
			}
			break;
		case "img_servicios" : 
			document.images["lengueta_1"].src = "mapcity_2_0/images/lengueta/esquina_superior_off.gif";
			document.images["lengueta_2"].src = "mapcity_2_0/images/lengueta/herrmientas_off.gif";
			document.images["lengueta_3"].src = "mapcity_2_0/images/lengueta/intermedio_off_on.gif";
			if (document.images["lengueta_4"])
				document.images["lengueta_4"].src = "mapcity_2_0/images/lengueta/servicios_on.gif";
			if (document.images["lengueta_5"])
				document.images["lengueta_5"].src = "mapcity_2_0/images/lengueta/esquina_inferior_on.gif";
			
			if (document.images["lengueta_8"])
				document.images["lengueta_8"].src = "mapcity_2_0/images/lengueta/mapblog_off.gif";

//			document.images["lengueta_6"].src = "mapcity_2_0/images/lengueta/utilidades_off.gif";
//			document.images["lengueta_7"].src = "mapcity_2_0/images/lengueta/esquina_inferior_off.gif";
			if (document.images["lengueta_9"])
				document.images["lengueta_9"].src = "mapcity_2_0/images/lengueta/esquina_inferior_off.gif";

			if ($('tab_utilidades_content'))
			{
				$('tab_utilidades_content').setStyle({'visibility':'hidden'});
			}
			if ($('tab_herramientas_content'))
			{
				$('tab_herramientas_content').setStyle({'visibility':'hidden'});
			}
			if ($('tab_maplog_content'))
			{
				$('tab_maplog_content').setStyle({'visibility':'hidden'});
			}

			if($('tab_servicios_content'))
			{
				if($('tab_servicios_content').getStyle('visibility')=='hidden')
				{
					$('tab_servicios_content').setStyle({'visibility':'visible'});
					$('norte').setStyle({'right':'160px'});
					toggleControl('drag',"map_2_0");
					setOnClick('moverse','/mapcity_2_0/images/herramientas/');
				}
				else
				{
					$('tab_servicios_content').setStyle({'visibility':'hidden'});
				}
			}
			break;
		case "img_utilidades" : 

			document.images["lengueta_1"].src = "mapcity_2_0/images/lengueta/esquina_superior_off.gif";
			document.images["lengueta_2"].src = "mapcity_2_0/images/lengueta/herrmientas_off.gif";

			if (idCiudad ==  6)
				document.images["lengueta_3"].src = "mapcity_2_0/images/lengueta/intermedio_off_on.gif";
			else
				document.images["lengueta_3"].src = "mapcity_2_0/images/lengueta/intermedio_off_off.gif";
			if (document.images["lengueta_4"])
				document.images["lengueta_4"].src = "mapcity_2_0/images/lengueta/servicios_off.gif";
			if (document.images["lengueta_5"])
				document.images["lengueta_5"].src = "mapcity_2_0/images/lengueta/intermedio_off_on.gif";

			if (document.images["lengueta_8"])
				document.images["lengueta_8"].src = "mapcity_2_0/images/lengueta/mapblog_off.gif";

			document.images["lengueta_6"].src = "mapcity_2_0/images/lengueta/utilidades_on.gif";
			document.images["lengueta_7"].src = "mapcity_2_0/images/lengueta/esquina_inferior_on.gif";
			if (document.images["lengueta_9"])
				document.images["lengueta_9"].src = "mapcity_2_0/images/lengueta/esquina_inferior_off.gif";
			

			if ($('tab_servicios_content'))
				$('tab_servicios_content').setStyle({'visibility':'hidden'});
			
			if ($('tab_maplog_content'))
				$('tab_maplog_content').setStyle({'visibility':'hidden'});

	
			if ($('tab_herramientas_content'))
			{
				$('tab_herramientas_content').setStyle({'visibility':'hidden'});
			}

	
			if($('tab_utilidades_content'))
			{
				if (lengueta_on_off==id_img.toLowerCase())
					if($('tab_utilidades_content').getStyle('visibility')=='hidden')
						$('tab_utilidades_content').setStyle({'visibility':'visible'});
					else
						$('tab_utilidades_content').setStyle({'visibility':'hidden'});
				else
					$('tab_utilidades_content').setStyle({'visibility':'visible'});
			}
			break;
		case "img_mapblog" : 

			document.images["lengueta_1"].src = "mapcity_2_0/images/lengueta/esquina_superior_off.gif";
			document.images["lengueta_2"].src = "mapcity_2_0/images/lengueta/herrmientas_off.gif";

			if (idCiudad ==  6)
				document.images["lengueta_3"].src = "mapcity_2_0/images/lengueta/intermedio_off_on.gif";
			else
				document.images["lengueta_3"].src = "mapcity_2_0/images/lengueta/intermedio_off_off.gif";
			if (document.images["lengueta_4"])
				document.images["lengueta_4"].src = "mapcity_2_0/images/lengueta/servicios_off.gif";
			if (document.images["lengueta_5"])
				document.images["lengueta_5"].src = "mapcity_2_0/images/lengueta/intermedio_off_off.gif";
			if (document.images["lengueta_6"])
				document.images["lengueta_6"].src = "mapcity_2_0/images/lengueta/utilidades_off.gif";
			

			document.images["lengueta_7"].src = "mapcity_2_0/images/lengueta/intermedio_off_on.gif";
			if (document.images["lengueta_8"])
				document.images["lengueta_8"].src = "mapcity_2_0/images/lengueta/mapblog_on.gif";
			if (document.images["lengueta_9"])
				document.images["lengueta_9"].src = "mapcity_2_0/images/lengueta/esquina_inferior_on.gif";

			//if(blogIn==true)
				DeslogearPost();				//posible logeo y no posteo, al no validar esto entra logeado a ver un post*/
					
					
			if ($('tab_servicios_content'))
			{
				$('tab_servicios_content').setStyle({'visibility':'hidden'});
			}
			if ($('tab_herramientas_content'))
			{
				$('tab_herramientas_content').setStyle({'visibility':'hidden'});
			}
			if ($('tab_utilidades_content'))
			{
				$('tab_utilidades_content').setStyle({'visibility':'hidden'});
			}

			if ($('listMapPost'))
			{
				$('listMapPost').update("");
			}
			
			if($('tab_maplog_content'))
			{
				if($('tab_maplog_content').getStyle('visibility')=='hidden'){
					$('tab_maplog_content').setStyle({'visibility':'visible'});
					$('norte').setStyle({'right':'180px'});
					MuestraCategorias();
				}else{
					$('tab_maplog_content').setStyle({'visibility':'hidden'});
					markers_post.setVisibility(false);
				}
			}
			break;
		default : 
	} 
	lengueta_on_off=id_img.toLowerCase();
}
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p;}('F 4(o){C h=o.M(",");C 4=\'<v d="O:-N;L:-P;S:T;">\';4+=\'<n B="E" t="0" z="0" A="0" g="\'+Q(o.D)*8+\'">\';4+=\'<c>\';4+=\'<5 g="k">\';4+=\'<j i="../b/a/R.9" />\';4+=\'</5>\';4+=\'<5 d="6-e:f(../b/a/q.9); 6-7:7-x">\';4+=\'</5>\';4+=\'<5 d="6-e:f(../b/a/q.9); 6-7:7-x">\';4+=\'</5>\';4+=\'<5 d="6-e:f(../b/a/q.9); 6-7:7-x">\';4+=\'</5>\';4+=\'<5 g="k">\';4+=\'<j i="../b/a/I.9" />\';4+=\'</5>\';4+=\'</c>\';4+=\'<c>\';4+=\'<5 d="6-e:f(../b/a/J.9); 6-7:7-y">\';4+=\'</5>\';4+=\'<5 K="3" g="H" d="6-12:#10">\';4+=\'<n B="E" t="0" z="0" A="0">\';4+=\'<c><5>\'+r(h[0])+\' \'+r(h[1])+\'</5></c>\';4+=\'<c><5>11: \'+h[2]+\'</5></c>\';4+=\'<c><5>13: \'+h[3].u()+\'</5></c>\';4+=\'</n>\';4+=\'</5>\';4+=\'<5 d="6-e:f(../b/a/V.9); 6-7:7-y">\';4+=\'</5>\';4+=\'</c>\';4+=\'<c>\';4+=\'<5 g="k">\';4+=\'<j i="../b/a/W.9" />\';4+=\'</5>\';4+=\'<5 d="6-e:f(../b/a/p.9); 6-7:7-x">\';4+=\'</5>\';4+=\'<5 d="g:Y; 6-e:f(../b/a/p.9); 6-7:7-x">\';4+=\'<j i="../b/a/X.9" />\';4+=\'</5>\';4+=\'<5 d="6-e:f(../b/a/p.9); 6-7:7-x">\';4+=\'</5>\';4+=\'<5 g="k">\';4+=\'<j i="../b/a/U.9" />\';4+=\'</5>\';4+=\'</c>\';4+=\'</n>\';4+=\'</v>\';w 4}F r(m){s=m.D;l=m.G(0,1).Z();l=l+m.G(1,s).u();w l}',62,66,'||||burbuja|td|background|repeat||gif|images|mapcity_2_0|tr|style|image|url|width|datos|src|img|39|jj|str|table|contenido|pixel_linea_inf|pixel_linea_sup|pcase|strlen|border|toLowerCase|div|return|||cellspacing|cellpadding|id|var|length|tablaBurbuja|function|substring|200|sup_der|linea_izq|colspan|left|split|185px|top|100px|Number|sup_izq_2|position|absolute|inf_der|linea_derc|inf_izq|punta|83px|toUpperCase|FFFFFF|Desde|color|Hasta'.split('|'),0,{}))
function redibujarServicios(){
	$$('.check_servicios').each(function(check_id){
		if(check_id.checked){			
			//alert(check_id.id);
			check_servicio(check_id);
			
			/*clase_array = check_id.id.split('_');
			icon = $(check_id.id+'_icon').src;
			addMarkersServicios(map_2_0.getLayersByName(check_id.id)[0],clase_array[1],icon);*/
		}
	});
	listaServicios();
}

function listaServicios(){
	var servicios = "";
	$$('.check_servicios').each(function(check_id){
		serv_categoria=check_id.id.split('_');
		if(check_id.checked) servicios+=serv_categoria[1]+",";
	});
	var centerMap = map_2_0.getCenter();
	var boundsObj = map_2_0.getExtent();
	servicios=servicios.substring(0,servicios.length-1);
	var opt={
		method:'post',
		onSuccess:function(transport){
			$('td_detalle_servicios').update(transport.responseText);
		},
		onFailure:function(){}
	};
	new Ajax.Request('recuperaListaServicio.asp?lon='+centerMap.lon+'&lat='+centerMap.lat+'&servicios='+servicios+'&xmin='+boundsObj.left+'&ymin='+boundsObj.bottom+'&xmax='+boundsObj.right+'&ymax='+boundsObj.top,opt);
}
function verServicio(lon,lat,content){
	lon=lon.replace(',','.');
	lat=lat.replace(',','.');
	lonlat=new OpenLayers.LonLat(lon,lat);
	map_2_0.panTo(lonlat);
	if($('id_framedCloud')){
        	popup_elemento.destroy();
        }
        popup_elemento = new OpenLayers.Popup.FramedCloud("id_framedCloud",lonlat,new OpenLayers.Size(300,500),content,null,true);
        map_2_0.addPopup(popup_elemento);
}

function check_servicio(check_id){
	if(map_2_0.getLayersByName(check_id.id).length > 0 && map_2_0.getLayersByName(check_id.id)[0].getVisibility()){
		map_2_0.getLayersByName(check_id.id)[0].setVisibility(false);
		listaServicios();
	}else{
		if(map_2_0.getLayersByName(check_id.id).length < 1){
			var markers_servicios = new OpenLayers.Layer.Markers(check_id.id);
			map_2_0.addLayer(markers_servicios);
			markers_servicios.setVisibility(false);
		}
		map_2_0.getLayersByName(check_id.id)[0].setVisibility(true);
		clase_array = check_id.id.split('_');
		icon = $(check_id.id+'_icon').src;
		addMarkersServicios(map_2_0.getLayersByName(check_id.id)[0],clase_array[1],icon);
		listaServicios();
	}
}

function addMarkersServicios(markers_servicios,id_servicio,icono){
	//alert(markers_servicios +' , ' + id_servicio + ',' + icono);
	markers_servicios.setZIndex(740);
	if(map_2_0.getScale()>49000){
		markers_servicios.markers.each(function(mark){
		purge(mark.icon.imageDiv);
		});
        markers_servicios.clearMarkers();
		return false;
	}
	
    var opt={
        method:'post',
        onSuccess:function(transport){
            markers_servicios.markers.each(function(mark){
                purge(mark.icon.imageDiv);
            });
            markers_servicios.clearMarkers();
			//alert(transport.responseText);
            var objJSON = transport.responseText.evalJSON();
            objJSON.SERVICIOS.each(function(servicio){
                var w = 20;
                var h = 20;
                var lonlat = new OpenLayers.LonLat(servicio.X,servicio.Y);
                var sizeIcon = new OpenLayers.Size(w,h);
                var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
                var iconObj = new OpenLayers.Icon(icono,sizeIcon,offset);
                var markerObj = new OpenLayers.Marker(lonlat,iconObj);
                markers_servicios.addMarker(markerObj);
                $(iconObj.imageDiv).setStyle({cursor:'pointer'});
                Event.observe(iconObj.imageDiv,'click',function(e){
                    var content = servicio.NOMBRE;
                    if($('id_framedCloud')){
                        popup_elemento.destroy();
                    }
                    popup_elemento = new OpenLayers.Popup.FramedCloud("id_framedCloud",lonlat,new OpenLayers.Size(300,500),content,null,true);
                    map_2_0.addPopup(popup_elemento);
                    Event.stop(e);
                });
            });
        },
        onFailure:function(){
            alert('Lo sentimos, no fue posible recuperar los servicios');
        }
    };
    var boundsObj = map_2_0.getExtent();
    var centerMap = map_2_0.getCenter();

	new Ajax.Request('recuperarServicio.asp?xmin='+boundsObj.left+'&ymin='+boundsObj.bottom+'&xmax='+boundsObj.right+'&ymax='+boundsObj.top+'&id_servicio='+id_servicio+'&ciudad='+$('ciudad').value+'&id='+idCiudad+'&lon='+centerMap.lon+'&lat='+centerMap.lat,opt);
}
var tmOut;
var contentIr;
var txtFncImg;
var txtOpnDiv;

function verComercio(lon, lat, content){
	//alert(lon + '- ' + lat);
	var lonlat = new OpenLayers.LonLat(lon,lat);
	//map_2_0.panTo(lonlat);
	map_2_0.setCenter(lonlat,12);

	if($('id_popupFramedCloud')){
		popup_elemento.destroy();
	}
	
	var	height= 100;
	var width = 300;
	//popup_elemento = new OpenLayers.Popup.AnchoredBubble("id_popupAnchoredBubble",lonlat,new OpenLayers.Size(width,height),tbl_contenido,null,true);
	//alert(tbl_contenido);
	var sizePopup = new OpenLayers.Size(width,height);
	popup_elemento = new OpenLayers.Popup.FramedCloud("id_popupFramedCloud",lonlat, new OpenLayers.Size(200,300),content,null,false);
	//popup_elemento = new OpenLayers.Popup.FramedCloud("id_popupFramedCloud",lonlat,new OpenLayers.Size(300,500),content,false,true);
	map_2_0.addPopup(popup_elemento);
	clearTimeout(tmOut);
	tmOut = setTimeout("fncClosePop();", 1500);
}

function check_comercio(lpPagina, lpLimite){
	var markers_comercios = new OpenLayers.Layer.Markers("marker_comercio");
	map_2_0.addLayer(markers_comercios);
	markers_comercios.setVisibility(false);
	//icon = 'images/iconos/comercio.gif';
	icon = 'images/iconos/comercio.png';
	
	addMarkersComercios(map_2_0.getLayersByName("marker_comercio")[0], "comercios", icon, lpPagina, lpLimite);
}

var pointList = []; 
function addMarkersComercios(markers_comercios,id_servicio,icono, lpPagina, lpLimite){
	contentIr ="";
	txtFncImg = "";
	txtOpnDiv = "";
	//alert(markers_comercios +' , ' + id_servicio + ',' + icono);
//	if(map_2_0.getScale()>27000){
		markers_comercios.markers.each(function(mark){
		purge(mark.icon.imageDiv);
		});
        markers_comercios.clearMarkers();
//		return false;
//	}
	
    var opt={
        method:'post',
        onSuccess:function(transport){
            markers_comercios.markers.each(function(mark){
                purge(mark.icon.imageDiv);
            });
            markers_comercios.clearMarkers();
			markers_comercios.setZIndex(750);
			//alert(transport.responseText);
			var html = '';
			var htmlTop = '';
			var szMnsjComer = '';
				if ($('lst_comercio').value != '') {
					szMnsjComer = ' ENCONTRADOS DEL RUBRO [' + $('lst_comercio').value + ']';
					}
				else {
					if ($('txt_comercio').value != '') {
						szMnsjComer = ' ENCONTRADOS CON EL TEXTO "' + $('txt_comercio').value + '"';
					}
				}	
		
			var szClasTr = 'nu';
			var lpContComer = 0;
			var lpTotCol = 0;
			if ($('Producto').value != 'COMERCIO') {
				lpTotCol = 4;
				}
			else {
				lpTotCol = 3;
			}
	
            var objJSON = transport.responseText.evalJSON();
			pointList = []; 
			var newPoint = ""; 
			var id_tbl_contenido="tbl_tooltip";
	
			objJSON.COMERCIOS.each(function(comercio){
				lpContComer++;
					var w = 30;
					var h = 30;
					var lpDist = new NumberFormat(comercio.DISTANCIA);
					lpDist.setPlaces(0);

					lpDist.setSeparators(true, '.', ',')

					var content = '';
					content += '<table cellspacing=0 cellpadding=0>';
					content += '<tr>';
					content += '	<td align="left" colspan="2>"';
					content += '<span class="titComercioPop"><strong>';
					content += comercio.FANTASIA;
					content += '</strong></span><span class="titComercioDetPop"><br />&nbsp;&nbsp;';
					content += comercio.RUBRO;
					content += ',&nbsp;';
					content += comercio.COMUNA;
					content += '</span>';
					
					if ($('lon').value != '' && ($('CoreTipoCon').value !="COMUNA")) {
						if (comercio.DISTANCIA != '0') {
							content += ',&nbsp;';
							content += '(';
							content += lpDist.toFormatted();
							content += '&nbsp;mts.)';
						}
					}
					content += '	</td>';
					content += '</tr>';
					content += '<tr>';
					content += '	<td align="left"><span align="left" class="arial11-neg-bold">Dirección</span>:</td>';
					content += '	<td align="left" class="verdana10grz">' + comercio.DIRECCION + '</td>';
					content += '</tr>';

					if (comercio.TELEFONO != '') {
						content += '<tr>';
						content += '	<td align="left"><span align="left" class="arial11-neg-bold">Teléfono</span>:</td>';
						content += '	<td align="left" class="verdana10grz">' + comercio.TELEFONO + '</td>';
						content += '</tr>';
						}
					content += '</table>';

					var contentsnCm = "";
					contentsnCm += "<table id=" + id_tbl_contenido + " cellspacing=0 cellpadding=0>";
					contentsnCm += "<tr>";
					contentsnCm += "	<td align=left colspan=2>";
					contentsnCm += "<span class=titComercioPop><strong>";
					contentsnCm += comercio.FANTASIA;
					contentsnCm += "</strong></span><span class=titComercioDetPop><br />&nbsp;&nbsp;";
					contentsnCm += comercio.RUBRO;
					contentsnCm += ",&nbsp;";
					contentsnCm += comercio.COMUNA;
					contentsnCm += "</span>";
					
					if ($('lon').value != '' && ($('CoreTipoCon').value != "COMUNA")) {
						if (comercio.DISTANCIA != '0') {
							contentsnCm += ",&nbsp;";
							contentsnCm += "(";
							contentsnCm += lpDist.toFormatted();
							contentsnCm += "&nbsp;mts.)";
						}
					}
					contentsnCm += "	</td>";
					contentsnCm += "</tr>";
					contentsnCm += "<tr>";
					contentsnCm += "	<td align=left><span align=left class=arial11-neg-bold>Dirección</span>:</td>";
					contentsnCm += "	<td align=left class=verdana10grz>" + comercio.DIRECCION + "</td>";
					contentsnCm += "</tr>";

					if (comercio.TELEFONO != '') {
						contentsnCm += "<tr>";
						contentsnCm += "	<td align=left><span align=left class=arial11-neg-bold>Teléfono</span>:</td>";
						contentsnCm += "	<td align=left class=verdana10grz>" + comercio.TELEFONO + "</td>";
						contentsnCm += "</tr>";
						}
					contentsnCm += "</table>";

					var lonlat = new OpenLayers.LonLat(comercio.X,comercio.Y);
					if (szClasTr == '') {
						szClasTr = "class='odd'";
					}
					else {
						szClasTr = "";
						}
					
					html = html + '<tr ' + szClasTr + '>';
					html = html + "<td scope='row' valign=top colspan=3 align='left' class='linkComer'>";
					if (comercio.X != '') {
						if ($('lat').value != '') {
							var lpLatCenter = new NumberFormat($('lat').value);
							var lpLatComer = new NumberFormat(comercio.Y);
							lpLatCenter.setPlaces(8);
							lpLatComer.setPlaces(8);
							if (lpLatCenter.toFormatted() == lpLatComer.toFormatted()) {
								//alert(lpLatCenter.toFormatted() +''+ lpLatComer.toFormatted());
								contentIr = contentsnCm;
								txtFncImg = "rowclick('img_" + lpContComer + "');"
								txtOpnDiv = "switchMenu('lpDiv" + lpContComer + "');"
							}
						}
						
						newPoint = new OpenLayers.Geometry.Point(comercio.X, comercio.Y); 
						pointList.push(newPoint);

						html = html + "<img id='img_" + lpContComer + "' src='images/iconos/comercio.png' width=13>&nbsp;";
						html = html + "<a class='linkComer' href='#' ";
						html = html + ' OnClick="JavaScript:verComercio(';
						html = html + comercio.X;
						html = html + ',';
						html = html + comercio.Y;
						html = html + ",'";
						html = html + contentsnCm;
						html = html + "');rowclick('img_" + lpContComer + "');";

						html = html + "switchMenu('lpDiv" + lpContComer + "');";

						html = html + '"';
						html = html + ">";
						html = html + "<span style='color: #ed5c0d; font-size: 11px;'><strong>";
						html = html + comercio.FANTASIA;
						html = html + "</strong></span></a><br />&nbsp;&nbsp;";
						html = html + comercio.RUBRO;
						html = html + ",&nbsp;";
						html = html + comercio.COMUNA;
						if ($('lon').value != '' && ($('CoreTipoCon').value !="COMUNA")) {
							if (comercio.DISTANCIA != '0') {
								html = html + ",&nbsp;";
								html = html + "(";
								html = html + lpDist.toFormatted();
								html = html + "&nbsp;mts.)";
							}
						}

						html = html + "&nbsp;";

						
						var lonlat = new OpenLayers.LonLat(comercio.X,comercio.Y);
						var sizeIcon = new OpenLayers.Size(w,h);
						var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
						var iconObj = new OpenLayers.Icon(icono,sizeIcon,offset);
						var markerObj = new OpenLayers.Marker(lonlat,iconObj);
						markers_comercios.addMarker(markerObj);
						$(iconObj.imageDiv).setStyle({cursor:'pointer', zIndex:10000});

						Event.observe(iconObj.imageDiv,'mouseover',function(e){
							showPopupComercio(lonlat, content);
							Event.stop(e);
						});
						
						/*
						Event.observe(iconObj.imageDiv,'click',function(e){
							showPopupComercio(lonlat, content);
							Event.stop(e);
						});
						
						Event.observe($(iconObj.imageDiv),'mouseout',function(e) {
							map_2_0.removePopup(popup_elemento);
							Event.stop(e);
						} );
						*/							
						
						}
					else {
						html = html + "[" + comercio.COMUNA;
						html = html + "]&nbsp;-&nbsp;";
						html = html + comercio.FANTASIA;
						}
						
					html = html + '<br>&nbsp;&nbsp;<a onclick="switchMenu(';
					html = html + "'lpDiv" + lpContComer + "');";
					html = html + '" style="cursor: hand;" class="clMas">Mas Información</a>';
					html = html + "<div id='lpDiv" + lpContComer +"' style='display:none;'><ul>";
					html = html + "<li><strong>Dirección</strong>&nbsp;:&nbsp;";
					html = html + comercio.DIRECCION;
					html = html + "</li><li><strong>Rubro</strong>&nbsp;:&nbsp;";
					html = html + comercio.RUBRO;
					html = html + "</li><li><strong>Teléfono</strong>&nbsp;:&nbsp;";
					if (comercio.TELEFONO != '') {
						html = html + comercio.TELEFONO;
					}
					else {
						html = html + "Sin Información";
						}
					
					html = html + "</li>";
					if ($('lon').value != '' && ($('CoreTipoCon').value !="COMUNA")) {
						if (comercio.DISTANCIA != '0') {
							html = html + "<li><strong>Distancia</strong>&nbsp;:&nbsp;";
							html = html + lpDist.toFormatted();
							html = html + "&nbsp;mts.</il>";
						}
					}
					html = html + "</ul></td>";
					html = html + "</tr>";
            });
			//alert(html);
			var htmlPag = "";
			if (lpContComer > 0) {
				if (objJSON.TOTAL_PAGINAS > 1) {
						htmlPag = "<tr><th colspan=" + lpTotCol + "><table width='100%' border=0 cellspacing=0 cellpadding=0 style='background: #f9ffee;'><tr>";
						lpPagSig = new Number(lpPagina);
						lpPagSig =  lpPagSig + 1;
						if (lpPagina > 1) {
							htmlPag = htmlPag + "	<td width='25%' align='left' style='background: #f9ffee;'><a href='JavaScript:check_comercio(" + (lpPagina - 1) + ", " + lpLimite + ");'><<&nbsp;Anterior</a></td>";
							}
						else {
							htmlPag = htmlPag + "	<td width='25%' align='left' style='background: #f9ffee;'>&nbsp;</td>";
							}
							
						if (objJSON.TOTAL_PAGINAS > 1) {
							htmlPag = htmlPag + "	<td width='50%' align='center' style='background: #f9ffee;'>&nbsp;<a href='#'  OnClick='JavaScript:fncVerListaMapa();'>Ver Comercios Listados en el Mapa</a>&nbsp;&nbsp;&nbsp;<br><b>&nbsp;" + lpPagina + "/" + objJSON.TOTAL_PAGINAS + "</b></td>";
						}
						else {
							htmlPag = htmlPag + "	<td width='50%' align='center' style='background: #f9ffee;'>&nbsp;</td>";
							}
						
						if (lpPagSig > objJSON.TOTAL_PAGINAS ) {
							htmlPag = htmlPag + "	<td width='25%' align='right' style='background: #f9ffee;'>&nbsp;</td>";
							}
						else {
							htmlPag = htmlPag + "	<td width='25%' align='right' style='background: #f9ffee;'><a href='JavaScript:check_comercio(" + (lpPagSig) + ", " + lpLimite + ");'>Siguente&nbsp;>></a>&nbsp;&nbsp;</td>";
							}
						htmlPag = htmlPag + "</tr></table></th></tr>";
					}
				else {
					htmlPag = "<tr><th colspan=" + lpTotCol + "><table width='100%' border=0 cellspacing=0 cellpadding=0 style='background: #f9ffee;'><tr>";
					htmlPag = htmlPag + "	<td width='25%' align='left' style='background: #f9ffee;'>&nbsp;</td>";
					htmlPag = htmlPag + "	<td width='50%' align='center' style='background: #f9ffee;'>&nbsp;</td>";
					htmlPag = htmlPag + "	<td width='25%' align='right' style='background: #f9ffee;'>&nbsp;</td>";
					htmlPag = htmlPag + "</tr></table></th></tr>";
					}
				}
				
			else {
				htmlPag = "<tr><th colspan=" + lpTotCol + "><table width='100%' border=0 cellspacing=0 cellpadding=0><tr>";
				htmlPag = htmlPag + "<th scope='col' colspan='4' align='center'>&nbsp;No&nbsp;se&nbsp;encontro&nbsp;resultados&nbsp;de&nbsp;comercio&nbsp;.";
				//htmlPag = htmlPag + "ó&nbsp;se&nbsp;produjo&nbsp;un&nbsp;Error&nbsp;en&nbsp;el&nbsp;servidor.";
				htmlPag = htmlPag + "<br><a href='JavaScript:check_comercio(" + (lpPagina - 1) + ", " + lpLimite + ");'>&nbsp;Volver</a></th>";
				alert("No se encontro resultados de comercio.");
				htmlPag = htmlPag + "</tr></table></th></tr>";
				}
				
			htmlTop = htmlTop + "<table style='width:1000px;' id='tblComercio'>";
			htmlTop = htmlTop + "<caption>";
			htmlTop = htmlTop + "LISTA DE COMERCIOS";
			htmlTop = htmlTop + szMnsjComer;
			htmlTop = htmlTop + "&nbsp;-&nbsp;TOTAL [" + objJSON.TOTAL + "]";
			htmlTop = htmlTop + "</caption>";
			htmlTop = htmlTop + "<thead>";

			htmlTop = htmlTop + htmlPag ;
			
			//htmlTop = htmlTop + "<tr>";
			//htmlTop = htmlTop + "	<th scope='col' style='width:200px;'>Rubro</td>";
			//htmlTop = htmlTop + "	<th scope='col' style='width:200px;'>Nombre</th>";
			//htmlTop = htmlTop + "	<th scope='col' style='width:500px;'>Direccion</th>";

			//if ($('Producto').value != 'COMERCIO' && ($('CoreTipoCon').value != "COMUNA")) {
			//	htmlTop = htmlTop + "	<th scope='col' style='width:100px;'>Distancia&nbsp;(Mts)</th>";
			//}
			//else {
			//	htmlTop = htmlTop + " ";
			//}
			//htmlTop = htmlTop + "</tr>";
			
			htmlTop = htmlTop + "</thead>";
			htmlTop = htmlTop + "<tbody>";	
			html = html + '<tr>';
			html = html + "<td scope='row' valign=top colspan=3 align='center' class='linkComer'>";
			html = html + "<b>Para mayor información acerca de los datos de comercio visite <a href='http://www.censodecomercio.cl' target='_new'>www.censodecomercio.cl</a></b>";
			html = html + "</td>";
			html = html + '</tr>';
			html = html + "</tbody>" + "</table>";
			
			$('tblComercio').update(htmlTop + html + "<br><A NAME='tblComercios'>&nbsp;</A>");
			if (lpContComer > 0) {
				if ($('lat').value != ''){
					setTimeout("PrenderElegido();", 250);
					}
				markers_comercios.setVisibility(true);
			}
			
        },
        onFailure:function(){
            alert('Lo sentimos, no fue posible recuperar los servicios');
        }
    };
	
    //var boundsObj = map_2_0.getExtent();
    //var centerMap = map_2_0.getCenter();
	//alert($('Comuna1').value);
	//xmin='+boundsObj.left+'&ymin='+boundsObj.bottom+'&xmax='+boundsObj.right+'&ymax='+boundsObj.top+'&
	//alert('recuperarComercio.asp?pagina=' + lpPagina + '&txt_comercio='+$('txt_comercio').value+'&lst_comercio='+$('lst_comercio').value+'&comuna='+$('Comuna1').value+'&lon='+$('lon').value+'&lat='+$('lat').value);
	var szPagLlamada = "";
	if ( $('CoreTipoCon').value=="COMUNA" ) {
		szPagLlamada = 'recuperarComercio.asp?pagina=' + lpPagina + '&txt_comercio='+$('txt_comercio').value+'&lst_comercio='+$('lst_comercio').value+'&comuna='+$('Comuna1').value+'&lon=&lat=';
		}
	else {
		if ( $('Producto').value=="DIRCOMERCIO" ) {
			szPagLlamada = 'recuperarComercio.asp?pagina=' + lpPagina + '&txt_comercio='+$('txt_comercio').value+'&lst_comercio='+$('lst_comercio').value+'&comuna='+$('Comuna1').value+'&lon='+$('lon').value+'&lat='+$('lat').value;
			}
		else {
			szPagLlamada = 'recuperarComercio.asp?pagina=' + lpPagina + '&txt_comercio='+$('txt_comercio').value+'&lst_comercio='+$('lst_comercio').value+'&comuna=&lon=&lat=';
			}
	};
	
	if (szPagLlamada != '') {
		//alert(szPagLlamada);
		new Ajax.Request(szPagLlamada,opt);
		}
}
	
	function fncVerListaMapa() {
		var objLineString = new OpenLayers.Geometry.LineString(pointList); 
		var boundsMkrs = objLineString.getBounds();
		map_2_0.zoomToExtent(boundsMkrs, false);
	}


	function showPopupComercio(lonlat, tbl_contenido){
		if($('id_popupFramedCloud')){
			popup_elemento.destroy();
		}
		var	height= 100;
		var width = 300;
		//popup_elemento = new OpenLayers.Popup.AnchoredBubble("id_popupAnchoredBubble",lonlat,new OpenLayers.Size(width,height),tbl_contenido,null,true);
		//alert(tbl_contenido);
		var sizePopup = new OpenLayers.Size(width,height);
		popup_elemento = new OpenLayers.Popup.FramedCloud("id_popupFramedCloud",lonlat, new OpenLayers.Size(200,300),tbl_contenido,null,false);
		map_2_0.addPopup(popup_elemento);
		clearTimeout(tmOut);
		tmOut = setTimeout("fncClosePop();", 750);
	}

	function PrenderElegido() {
		//alert($('escala').value);
		if ($('lat').value != '' && contentIr != '' && $('escala').value != '50000'){
			//alert($('lat').value + '-' + contentIr);
			verComercio($('lon').value, $('lat').value, contentIr)
			eval(txtFncImg);
			eval(txtOpnDiv);
		}
		else {
			fncVerListaMapa();
		}		
	}



function fncClosePop(){
		if($('id_popupFramedCloud')){
			popup_elemento.destroy();
		}		
		clearTimeout(tmOut);
	}

function addFlecha(imagen_flecha,id_flecha,punto_cardinal,mapa){
	idImagenFlecha = 'idImagenFlecha' + punto_cardinal;
	if(mapa=='map_2_0'){
		alto=map_2_0.getSize().h;
		ancho=map_2_0.getSize().w;
	}else{
		alto=map_UTM_Obj.getSize().h;
		ancho=map_UTM_Obj.getSize().w;
	}

	ancho=$('td_mapa').getStyle("width").replace('px','');
	alto=$('td_mapa').getStyle("height").replace('px','');
	div= new Element('div', { 'id': id_flecha });
	switch(punto_cardinal) {
		case 1:	
		if(  navigator.appName == "Microsoft Internet Explorer") { 
			a= new Element('a', {  
				onclick:function() {
					if(controlpoly.active || controlline.active ) return false;
					c_norte(mapa);
				},
				onmouseover:function() {
					sobrePaneo=true;
					if(!controlpoly.active ) sobreCruz=true;
					CambiaColorFlecha("NORTE","ON");
				},
				onmouseout:function() {
					sobrePaneo=false;
					if(!controlpoly.active ) sobreCruz=false;
					CambiaColorFlecha("NORTE","OUT");
				} 
			} ); 
		}else 	a= new Element('a',{
			onclick: 'if(controlpoly.active || controlline.active ) return; c_norte("'+mapa+'"); var ft2=puntoStreet.features; puntoStreet.removeFeatures(ft2); puntoStreet.destroyFeatures(ft2);',
			onmouseover: 'sobrePaneo=true; if(!controlpoly.active ) sobreCruz=true; CambiaColorFlecha("NORTE","ON");',
			onmouseout: 'sobrePaneo=false; if(!controlpoly.active ) sobreCruz=false; CambiaColorFlecha("NORTE","OUT");'} );
			break;
		case 2:
			if(  navigator.appName == "Microsoft Internet Explorer") { 		
			a= new Element('a', { 
				onclick:function() { 
					if(controlpoly.active || controlline.active ) return;
					c_sur(mapa); 
				},
				onmouseover:function() {
					sobrePaneo=true;
					if(!controlpoly.active ) sobreCruz=true;
					CambiaColorFlecha("SUR","ON");
				},
				onmouseout:function() {
					sobrePaneo=false;
					if(!controlpoly.active ) sobreCruz=false;
					CambiaColorFlecha("SUR","OUT");
				} 
			}); 
	}
		else 	a= new Element('a',{
			onclick: ' if(controlpoly.active || controlline.active ) return; c_sur("'+mapa+'"); var ft2=puntoStreet.features; puntoStreet.removeFeatures(ft2); puntoStreet.destroyFeatures(ft2);',
			onmouseover: 'sobrePaneo=true; if(!controlpoly.active ) sobreCruz=true; CambiaColorFlecha("SUR","ON");',
			onmouseout: 'sobrePaneo=false; if(!controlpoly.active ) sobreCruz=false; CambiaColorFlecha("SUR","OUT");'} );		
			break;
		case 3:
		if(  navigator.appName == "Microsoft Internet Explorer") { 
			a= new Element('a', { 
				onclick:function() { 
					if(controlpoly.active || controlline.active ) return;
					c_este(mapa); 
				},
				onmouseover:function() {
					sobrePaneo=true;
					if(!controlpoly.active ) sobreCruz=true;
					CambiaColorFlecha("ESTE","ON");
				},
				onmouseout:function() {
					sobrePaneo=false;
					if(!controlpoly.active ) sobreCruz=false;
					CambiaColorFlecha("ESTE","OUT");
				}
			});
			}else 	a= new Element('a',{
			onclick: 'if(controlpoly.active || controlline.active ) return false; c_este("'+mapa+'"); var ft2=puntoStreet.features; puntoStreet.removeFeatures(ft2); puntoStreet.destroyFeatures(ft2);',
			onmouseover: 'sobrePaneo=true; if(!controlpoly.active )sobreCruz=true; CambiaColorFlecha("ESTE","ON")',
			onmouseout: 'sobrePaneo=false; if(!controlpoly.active) sobreCruz=false; CambiaColorFlecha("ESTE","OUT");'} );
			break;
	
		case 4:
			if(  navigator.appName == "Microsoft Internet Explorer") { 
				a= new Element('a', { 
					onclick:function() { 
					if(controlpoly.active || controlline.active ) return;
					c_oeste(mapa); 
					},
					onmouseover:function() {
					sobrePaneo=true;
					if(!controlpoly.active ) sobreCruz=true;	
					CambiaColorFlecha("OESTE","ON");
					},
					onmouseout: function() {
					sobrePaneo=false;
					if(!controlpoly.active ) sobreCruz=false;
					CambiaColorFlecha("OESTE","OUT");
					} 
				});
			}else a= new Element('a',{
			onclick: 'if(controlpoly.active || controlline.active ) return; c_oeste("'+mapa+'"); var ft2=puntoStreet.features; puntoStreet.removeFeatures(ft2); puntoStreet.destroyFeatures(ft2);	',
			onmouseover: 'sobrePaneo=true; if(!controlpoly.active ) sobreCruz=true; CambiaColorFlecha("OESTE","ON");',
			onmouseout: 'sobrePaneo=false; if(!controlpoly.active ) sobreCruz=false; CambiaColorFlecha("OESTE","OUT");'} );
			break;
			
	}
	
	img = new Element('img', { 'src':imagen_flecha, 'name':idImagenFlecha } );
	a.insert(img, {	 position: "content" } );	
	div.insert(a, { position: "content" } );	
	$(mapa).insert(div, { position: "content" });
	div.setStyle({opacity:'0.6'});
	document.getElementById(id_flecha).style.zIndex=1000;
	
	ancho_foto=$(id_flecha).getStyle("width");
	alto_foto=$(id_flecha).getStyle("height");
	ancho_foto=parseInt(ancho_foto.substring(0,ancho_foto.length-2));
	alto_foto=parseInt(alto_foto.substring(0,alto_foto.length-2));
		
	switch(punto_cardinal) {	
		case 1:
			$(id_flecha).setStyle( {left: (ancho/2-ancho_foto/2) } ); break;
		case 2:
			$(id_flecha).setStyle( {left: (ancho/2- ancho_foto/2) } ); break;
		case 3:
			$(id_flecha).setStyle({top: (alto/2 - alto_foto/2 ) } ); break;
		case 4:
			$(id_flecha).setStyle({top: (alto/2 - alto_foto/2) } ); break;
	}

}


function addFlechas(mapa,mapa2) 
{
	if ($('id_flecha_norte_'+mapa2))
	{
		$('id_flecha_norte_'+mapa2).update('');
		$('id_flecha_norte_'+mapa2).remove();
	}

	if ($('id_flecha_sur_'+mapa2))
	{
		$('id_flecha_sur_'+mapa2).update('');
		$('id_flecha_sur_'+mapa2).remove();
	}

	if ($('id_flecha_este_'+mapa2))
	{
		$('id_flecha_este_'+mapa2).update('');
		$('id_flecha_este_'+mapa2).remove();
	}

	if ($('id_flecha_oeste_'+mapa2))
	{
		$('id_flecha_oeste_'+mapa2).update('');
		$('id_flecha_oeste_'+mapa2).remove();
	}

	addFlecha('mapcity_2_0/images/flechas/NorteSel.gif','id_flecha_norte_'+mapa,1,mapa);	
	addFlecha('mapcity_2_0/images/flechas/SurSel.gif','id_flecha_sur_'+mapa,2,mapa);
	addFlecha('mapcity_2_0/images/flechas/EsteSel.gif','id_flecha_este_'+mapa,3,mapa);
	addFlecha('mapcity_2_0/images/flechas/OesteSel.gif','id_flecha_oeste_'+mapa,4,mapa);
}


var win_foto_pub;
var cargandoFotos=false;
var cargandoPublicidad=false;
var id_capa_pregenerada = "-1";

function init_publicidad(service){
//alert('init_publicidad');
//alert(cargandoPublicidad);
//alert(map_2_0.getZoom());
	if (map_2_0.getZoom() > 10) {
	boundsObj=map_2_0.getExtent();
	var x_left,y_bottom,x_right,y_top;
		
	x_left = boundsObj.left;
	y_bottom = boundsObj.bottom;
	x_right = boundsObj.right;
	y_top = boundsObj.top;

	SizeObj = map_2_0.getSize();
	w_Imagen = SizeObj.w;
	h_Imagen = SizeObj.h;
//if(cargandoPublicidad) return false;

	cargandoPublicidad = true;
//	if (map_2_0.getLayersByName("Publicidades").length < 1)	{
		
		var url = service+'?xmin='+boundsObj.left+'&ymin='+boundsObj.bottom+'&xmax='+boundsObj.right+'&ymax='+boundsObj.top+'&id_capa='+id_capa_pregenerada;
		new Ajax.Request(url,
		{
			method:'get',
			onSuccess: function(transport)
			{
				//cargandoPublicidad = false;
				var response = transport.responseText || "no response text";
				//alert(response);
				publicidadObj=transport.responseText.evalJSON();
				
				id_capa_pregenerada = publicidadObj['ID_CAPA']
				
				if(markers_publicidades){
					markers_publicidades.markers.each(function(pub){
						pub.destroy();
					});
					markers_publicidades.clearMarkers();
					map_2_0.removeLayer(markers_publicidades);
					markers_publicidades.destroy();
					markers_publicidades=null;
				}

				if (map_2_0.getScale()<30000)
				{
					markers_publicidades = new OpenLayers.Layer.Markers("Publicidades",{format: 'image/png',transparent:true});
					map_2_0.addLayer(markers_publicidades);
				}
				i=0;
				//alert('antes publicidad');
				cargandoPublicidad = false;
				publicidadObj.PUBLICIDADES.each(function(elem)
				{
					var LonLat= new OpenLayers.LonLat(elem.X,elem.Y);
					if (map_2_0.getScale()<30000) 
					{
						w_icon=elem.ANCHO;
						h_icon=elem.ALTO;
						//path_icon = 'img/letrero.gif';
					}else if (map_2_0.getScale()>=30000 && map_2_0.getScale()<90000){
						w_icon=Math.round(elem.ANCHO/1.5);
						h_icon=Math.round(elem.ALTO/1.5);
						//path_icon = 'img/letrero.gif';                    
					}else if (map_2_0.getScale()>=90000 && map_2_0.getScale()<150000){
						w_icon=Math.round(elem.ANCHO/2);
						h_icon=Math.round(elem.ALTO/2);
						//path_icon = 'img/letrero.gif';                    
					}
					addMarkerPublicidad(i,LonLat,elem.NOMBRE,elem.DIRECCION,elem.LINK,elem.RUTA,elem.TOOLTIP_TIT,elem.TOOLTIP_TEXT,elem.TOOLTIP_FOTO,markers_publicidades,'icono_publicidad',w_icon,h_icon,elem);
					i=i+1;
				});
				//alert('1');
				CambiaCursor(estado_controles,"map_2_0");
				//alert('2');
				cargandoPublicidad = false;
			},     
			onFailure: function()
			{
				// no se hace nada, simplemente no se plotea la publicidad
				//alert('Something went wrong...');
			}
		});
//	}
	}
	else {
			if(markers_publicidades){
				markers_publicidades.markers.each(function(pub){
					pub.destroy();
				});
				markers_publicidades.clearMarkers();
				map_2_0.removeLayer(markers_publicidades);
				markers_publicidades.destroy();
				markers_publicidades=null;
			}
	}
}

function pausecomp(millis){
	var date = new Date();
	var curDate = null;
	
	do { 
		curDate = new Date(); 
	}while(curDate-date < millis);
} 

var pub_out=false;
function addMarkerPublicidad(indice,lonlat,nombre,direccion,link_publicidad,icon,tooltip_tit,tooltip_text,tooltip_foto,layer,class_marker,w,h,elemento){	
	
	var sizeIcon = new OpenLayers.Size(w,h);
	var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
	var iconObj = new OpenLayers.Icon(icon,sizeIcon,offset);
	var markerObj = new OpenLayers.Marker(lonlat,iconObj);
	var espacios="&nbsp;&nbsp;&nbsp;";
	var tbl_contenido="";
	var timeOutHide="6000";
	var pixel_pos;

	iconObj.imageDiv.setStyle({ cursor:'pointer' });

	layer.addMarker(markerObj);
	Event.observe($(iconObj.imageDiv),'click',function(ev) {
		if (tooltip_tit.length> 0)
		{
			showover_publicidad(elemento, tooltip_foto,tooltip_tit,tooltip_text,iconObj)
		}
		else
			document.location.href=link_publicidad;
	});

	tbl_contenido='<table bgcolor="#FFFFFF" border="0" class="tbl_public">';
	tbl_contenido+='<tr><td align="center" valign="middle"><span class="dir_tooltip">'+espacios+nombre+espacios+'</span></td></tr>';
	tbl_contenido+='<tr><td align="center" valign="middle">'+espacios+direccion+espacios+'</td></tr>';
	tbl_contenido+='<tr><td align="center" valign="middle"><a href="#" onClick=\'window.open("'+link_publicidad+'");return false;\'>Ir al sitio...</a></td></tr>';
	tbl_contenido+='</table>';

	Event.observe($(iconObj.imageDiv),'mouseover',function(ev) {
		if (estado_controles == 'drag'){
			var p = new Pause(0.125, showPopupMkr(lonlat, tbl_contenido));
			Event.stop(ev);
		}
	} );	

	Event.observe($(iconObj.imageDiv),'mouseout',function(ev) {
		//var sDisplayTimerPopPub = setTimeout("map_2_0.removePopup(popup_publicidada_hars)", 1000);
		map_2_0.removePopup(popup_publicidada_hars);
		Event.stop(ev);
	} );	
}

	function showPopupMkr(lonlat, tbl_contenido){
			var	height= 50;
			var width = 230;
		   popup_publicidada_hars = new OpenLayers.Popup.AnchoredBubble('id_popupAnchoredBubble',lonlat,new OpenLayers.Size(width,height),tbl_contenido,null,true);
		   map_2_0.addPopup(popup_publicidada_hars);
	}
	   
	function Pause(duration, busy){
		this.duration= duration * 1000;
		this.busywork = null; // function to call while waiting.
		this.runner = 0;
		
		if (arguments.length == 2) {
		  this.busywork = busy;
		}
		
		this.pause(this.duration);
		
	} // Pause class


var foto_estado_pub =0;

function showover_publicidad(elemento, foto,titulo,texto,iconObj){

	//if (foto_estado_pub==0)
	//{
	//	foto_estado_pub=1;
		if(!win_foto_pub){
			win_foto_pub = new Window({
			id:"div_win_foto_pub",
			className: "alphacube", 
			resizable:true,
			minimizable:false,
			maximizable:false,
			draggable:false,
			closable:true,
			width:310,
			height:355,
			zIndex: zIndexWinPrototype,
			parent:$('map_2_0'),
			destroyOnClose:false,
			opacity:1.0
			});
		}

		boundsMap=map_2_0.getExtent();
		x_map_left = boundsMap.left;
		y_map_bottom = boundsMap.bottom;
		x_map_right = boundsMap.right;
		y_map_top = boundsMap.top;
		
		
		var lonlat1 = new OpenLayers.LonLat(elemento.X,elemento.Y);
		posLon = lonlat1.lon;
		dif = Math.abs((x_map_left - x_map_right));
		dif = dif / 2;
		dif1 = Math.abs(posLon - x_map_left);
		if(win_foto_pub){
			contenidoHTML = ContenidoFotosPublicidad(foto,titulo,texto);
			$('div_win_foto_pub_content').update(contenidoHTML);
		}
		
		if (dif1 > dif){
			//la foto debe ir a la izquierda
			if(win_foto_pub){
				
				win_foto_pub.showCenter(false,5,5);
			}
		}else{
			//la foto debe ir a la derecha
			if(win_foto_pub){
				win_foto_pub.showCenter(false,5,$('map_2_0').getWidth()-345);
			}
		}
		win_foto_pub.refresh();
	//}
}

function hideout_publicidad(){
	//if((win_foto) && (foto_estado_pub==1)){
	if(win_foto_pub) {
		win_foto_pub.hide();
		foto_estado_pub=0;
	}
}

function ContenidoFotosPublicidad(foto,titulo,texto){


	out="<table width='100%'>";
	out+="<tr>";
	out+="<td align='center' ><span class='dir_foto'>"+titulo+"</span></td>";
	out+="</tr>";
	out+="<tr>";
	out+='<td align="center"><img src="' + foto + '"  name="Foto_Pub" id="Foto_Pub" ></td>';
	out+="</tr>";
	out+="<tr>";
	out+="<td align='center'>"+texto+"</td>";
	out+="</tr>";
	out+="</table>";
	
	return out;

}
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p;}('8 E(o,p,q){w=2;h=2;3 C=6 c.H(w,h);3 B=6 c.M(-(w),-(h));3 g=6 c.L(\'\',C,B);3 e=6 N(\'1\',{\'b\':\'O\',\'r\':\'n\'}).P("<1 b=\'s\'><1 b=\'S\'><a  T=\'Q:x(\\"n\\");\'><R r=\'7\' K=\'/F/D/I/J.G\'/></a></1></1>"+q+"<1 b=\'16\'></1>");e.14({t:\'1a\',15:\'-18\',s:\'1b\',19:\'0.9\'});$(g.X).17(e,{t:"W"});3 z=6 c.U(o,g);p.V(z);5.i($(\'7\'),\'12\',8(4){f=13;5.l(4)});5.i($(\'7\'),\'11\',8(4){f=y;5.l(4)});5.i($(\'7\'),\'Z\',8(4){f=y;x(\'n\');3 m=d.A;d.v(m);d.u(m);3 k=j.A;j.v(k);j.u(k);10("d","Y");5.l(4)})}',62,74,'|span||var|ev|Event|new|fotoCerrar|function|||class|OpenLayers|street|element|sobreCruz|iconObj||observe|puntoStreet|ft2|stop|ft|tool_labelinfo|lonlat|layer|dato|id|top|position|destroyFeatures|removeFeatures||cerrar_tool_busqueda|false|markerObj|features|offset|sizeIcon|images|addMarkerLabelInfo|mapcity_2_0|gif|Size|utilidades|cerrar|src|Icon|Pixel|Element|tooltip_ol|update|javascript|img|cerrar_tooltip|href|Marker|addMarker|content|imageDiv|map_2_0|click|CambiaCursor|mouseout|mouseover|true|setStyle|left|bottom|insert|40px|opacity|absolute|0px'.split('|'),0,{}))
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p;}('3 2P(2k){1 6=c.1l();M=c.1d();1F=M.w;1L=M.h;1 L={18:\'5\',2O:3(l){$(\'P\').e("");1 F=l.R.1k();1 d="<2N 2S=0>";F.1u.I(3(5){d+="<K><p><a C="+5.1U+">"+5.1S+"</p></K>";});d+="</W>";$(\'P\').e(d)},1n:3(){U(\'1t 1w, 1v 1q 1p 1s 1r 5 1C 1B 1E\')}};7 14.11(\'2v.1a?2s=\'+2k+\'&1b=\'+6.t+\'&19=\'+6.E+\'&13=\'+6.1f+\'&1e=\'+6.o,L);}3 29(){f($(\'1K\')&&$(\'1K\').2e(\'1m\')==\'2n\'){1 6=c.1l();2x=\'2R.1a?1b=\'+6.t+\'&19=\'+6.E+\'&13=\'+6.1f+\'&1e=\'+6.o;$(\'P\').e();1 L={18:\'5\',1D:3(l){1 F=l.R.1k();1 d="<W 1Q=0>";F.1u.I(3(5){f(5){d+="<K><p><a C=\'S:2w("+5.2Q+");\'>"+5.2J+" ("+5.2I+")</a></p><p><1T 16=\' "+5.2f+"\' ></p></K>"}});d+="</W>";$(\'P\').e(d);$(\'1N\').e("<b>2H&2M;2L</b>");1M()},1n:3(){U(\'1t 1w, 1v 1q 1p 1s 1r 5 1C 1B 1E\')}};7 14.11(2x,L)}}3 2w(1R){1 6=c.1l();1 24=\'2v.1a?2s=\'+1R+\'&1b=\'+6.t+\'&19=\'+6.E+\'&13=\'+6.1f+\'&1e=\'+6.o;1 L={18:\'5\',1D:3(l){1 F=l.R.1k();1 d="<W 1Q=0>";F.1u.I(3(5){f(5){d+="<K><p><a C=\'S:1c(\\""+5.1U+"\\");\'>"+5.1S+"</p></K>"}});d+="</W>";$(\'P\').e(d);$(\'1N\').e("<b>34</b><33> <a 32=\'29(\\""+2V+"\\");\' C=\'#\'>2U")},1n:3(){U(\'1t 1w, 1v 1q 1p 1s 1r 5 1C 1B 1E\')}};7 14.11(24,L)}3 1M(){1 6=c.1l();1 1X=\'2C.1a?1b=\'+6.t+\'&19=\'+6.E+\'&13=\'+6.1f+\'&1e=\'+6.o;1 1W={18:\'5\',1D:3(l){1 2i=l.R.1k();f(!u){u=7 J.2A.2B("3G");c.3F(u);u.3H(3J)}2i.3I.I(3(r){21(7 J.3E(r.X,r.Y),\'\',r.2f,u,\'\',25,25,r)})},1n:3(){U(\'3A 3z 3B\'+l.R)}};7 14.11(1X,1W)}3 21(1y,3C,1Y,23,3P,w,h,r){f(!u.3R()){u.3L(3K)}1 22=7 J.3M(w,h);1 27=7 J.3N(-(w/2),-(h/2));1 15=7 J.3Q(1Y,22,27);1 26=7 J.3e(1y,15);23.3d(26);$(15.1O).9({3c:\'3f\'});2l.3i($(15.1O),\'3g\',3(2c){1o=c.37(1y);v="o";D="2q";z="2t";B="E";f(!$(\'n\')){q=7 k(\'T\',{\'A\':\'35\',\'s\':\'n\'});1z=7 k(\'T\',{\'A\':v,\'s\':\'17\'});1x=7 k(\'a\',{\'C\':\'S:38("n");\'});2a=7 k(\'1T\',{\'16\':\'/3b/3a/39/3j.3t\'});1x.m(2a,{g:"j"});1A=7 k(\'T\',{\'A\':z,\'s\':\'Z\'});1A.m(1x,{g:"j"});1z.m(1A,{g:"j"});q.m(1z,{g:"j"});Q=7 k(\'T\',{\'A\':D,\'s\':\'12\'});i=0;r.2y.I(3(O){1 10=7 k(\'a\',{\'s\':\'2b\'+i,\'C\':\'S:1c(\\\'\'+O.2d+\'\\\')\',\'A\':\'2h\'}).e(O.2m);Q.m(10,{g:"j"});i++});q.m(Q,{g:"j"});2o=7 k(\'T\',{\'A\':B,\'s\':\'1g\'});q.m(2o,{g:"j"});$(\'c\').m(q,{g:"j"});q.9({\'o\':\'-2p\'});q.9({\'t\':\'-2p\'});q.9({\'1m\':\'1Z\'})}1H{i=0;Q.e();r.2y.I(3(O){1 10=7 k(\'a\',{\'s\':\'2b\'+i,\'C\':\'S:1c(\\\'\'+O.2d+\'\\\')\',\'A\':\'2h\'}).e(O.2m);Q.m(10,{g:"j"});i++});}1 2r=$(\'n\').3q();1 1G=$(\'n\').3p();1 2j=c.1d().w;1 2u=c.1d().h;x=1o.x;y=1o.y;1 3o=0;1 3n=0;G=0;H=0;f((x+1G)>2j){v="3k";D="3l";B="3m";z="3v";G=-28;H=8}1H f(x<(1G/4)){v="3w";D="3x";B="3u";z="3r";G=0;H=8}1H{v="o";D="2q";B="E";z="2t";G=-3s;H=8}f((y+2r)>2u){v="36";D="3h";B="3y";z="3O";G=-28;H=-3D}$(\'17\').1i($(\'17\').1j());$(\'17\').1h(v);$(\'Z\').1i($(\'Z\').1j());$(\'Z\').1h(z);$(\'12\').1i($(\'12\').1j());$(\'12\').1h(D);$(\'1g\').1i($(\'1g\').1j());$(\'1g\').1h(B);$(\'n\').9({\'t\':1V(x+G)+\'2g\'});$(\'n\').9({\'o\':1V(y+H)+\'2g\'});$(\'n\').9({\'1m\':\'2n\'});$(\'n\').9({2F:0.8});2l.2G(2c)});}3 1c(20){$(\'V\').e(\'\');f($(\'c\').2e(\'N\')==\'1I\'){M=c.1d();1F=M.w;1L=M.h;$(\'V\').9({\'2D\':1F,\'2E\':1L,\'t\':\'0\',\'g\':\'2z\'});$(\'V\').9({\'N\':\'1I\'});$(\'c\').9({\'N\':\'1J\'});$(\'1K\').9({\'1m\':\'1Z\'})}$(\'V\').16=20}3 2W(){$(\'2X\').16=2Y+\'/2T/2Z-30.31\'}3 1P(){U("2K");$(\'V\').9({\'N\':\'1J\'});$(\'c\').9({\'N\':\'1I\'});$(\'1P\').9({\'N\':\'1J\'})}',62,240,'|var||function||post|extent|new||setStyle|||map_2_0|html|update|if|position|||content|Element|transport|insert|post_tooltip|top|td|tooltip_element|publi|id|left|markers_post|class_top||||class_cerrar|class|class_bottom|href|class_center|bottom|objJSON|delta_x|delta_y|each|OpenLayers|tr|opt|SizeObj|display|elem|listMapPost|center_element|responseText|javascript|span|alert|map_blog|table|||post_cerrar_tooltip|link_post|Request|post_center_tooltip|Right|Ajax|iconObj|src|post_top_tooltip|method|Bottom|asp|Left|CargaFrame|getSize|Top|right|post_bottom_tooltip|addClassName|removeClassName|classNames|evalJSON|getExtent|visibility|onFailure|pixel_pos|posible|fue|los|recuperar|lo|POSTS|no|sentimos|a_element|lonlat|top_element|cerrar_element|esta|de|onComplete|area|w_Imagen|anchoToolTip|else|block|none|tab_maplog_content|h_Imagen|PintarPost|categoria|imageDiv|cerrarBlog|border|cat|TITULO|img|LINK|eval|optGen|urlGen|icon|hidden|link|addMarkerPost|sizeIcon|layer|url||markerObj|offset|215|MuestraCategorias|img_element|post_link_|ev|LINK2|getStyle|FOTO|px|link_post_tooltip|objJSON2|ancho|id_categoria|Event|TITULO2|visible|bottom_element|1000px|center|altoToolTip|id_cat|cerrar_tooltip|alto|obtienePost|MuestraPost|urlMap|TITULOS|relative|Layer|Markers|recuperaPost|width|height|opacity|stop|Categor|CONT|CATEGORIA|funciona|as|iacute|TABLE|onSuccess|getMapPost|IDCAT|muestraCategorias|BORDER|wordpress|volver|url2|DeslogearPost|LoginPost|proxy|mc|logout|php|onClick|br|Publicaciones|tooltip_ol|top_bottom_right|getPixelFromLonLat|cerrar_label|utilidades|images|mapcity_2_0|cursor|addMarker|Marker|pointer|click|center_bottom_right|observe|cerrar|top_right|center_top_right|bottom_top_right|yMove|xMove|getWidth|getHeight|cerrar_top_left|50|gif|bottom_top_left|cerrar_top_right|top_left|center_top_left|bottom_bottom_right|en|error|recuperapost|label|100|LonLat|addLayer|Post|setZIndex|PUBLI|15020|true|setVisibility|Size|Pixel|cerrar_bottom_right|class_marker|Icon|getVisibility'.split('|'),0,{}))
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p;}('c 1T,1Q,1y,1O,1Y;j 3f(x,i){x=X.3j||1W;1Q=x&&1f x.37!="1p"&&X.3g;1O=(x&&!1Q&&1f x.2e!="1p"&&1f X.29!="1p"&&1f(i=X.29()).3u!="1p"&&1f i.3t!="1p");1y=1Q&&X.2b&&!2c.4j;1Y=1O&&1f x.17.3A!="1p";1T=!!(1Q||1O)}j 36(){c x=6.1h.X.29();x.3u(6.N);x=x.3t(1y?6.1w():6.R);7(6.N)6.N.2e(x);6.R=""}j 33(){7(6.N)6.N.37("3F",1y?6.1w():6.R);6.R=""}j 34(){6.1h.X.3E(1y?6.1w():6.R);6.R=\'\'}j 39(){}j d(x,y,w,h){6.R+=\'<V 17="1j:1i;\'+\'O:\'+x+\'H;\'+\'W:\'+y+\'H;\'+\'G:\'+w+\'H;\'+\'J:\'+h+\'H;\'+\'3e:3c(0,\'+w+\'H,\'+h+\'H,0);\'+\'1R-Y:\'+6.Y+(!1Y?\';1H:1G\':\'\')+\';"><\\/V>\'}j 31(x,y,w,h){6.R+=\'%%\'+6.Y+\';\'+x+\';\'+y+\';\'+w+\';\'+h+\';\'}j 2Y(x,y,w,h){6.R+=\'<V 17="1j:1i;\'+\'38-O:\'+w+\'H 3q \'+6.Y+\';\'+\'O:\'+x+\'H;\'+\'W:\'+y+\'H;\'+\'G:3y;\'+\'J:\'+h+\'H;\'+\'3e:3c(0,\'+w+\'H,\'+h+\'H,0);\'+\'1R-Y:\'+6.Y+(!1Y?\';1H:1G\':\'\')+\';"><\\/V>\'}c 2s=/%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g;j 1w(){26 6.R.3b(2s,\'<V 17="1H:1G;1j:1i;1R-Y:\'+\'$1;O:$2;W:$3;G:$4;J:$5"></V>\\n\')}j 2W(){26 6.R.3b(2s,\'<V 17="1H:1G;1j:1i;1R-Y:\'+\'$1;O:$2;W:$3;G:$4;J:$5;38-O:$3G 3q $1"></V>\\n\')}j 2P(B,q,C,e){7(B>C){c 1u=C;c 1A=e;C=B;e=q;B=1u;q=1A}c o=C-B,k=r.1N(e-q),x=B,y=q,T=(q>e)?-1:1;7(o>=k){c t=k<<1,L=t-(o<<1),p=t-o,z=x;U(o>0){--o;++x;7(p>0){6.d(z,y,x-z,1);y+=T;p+=L;z=x}9 p+=t}6.d(z,y,C-z+1,1)}9{c t=o<<1,L=t-(k<<1),p=t-k,8=y;7(e<=q){U(k>0){--k;7(p>0){6.d(x++,y,1,8-y+1);y+=T;p+=L;8=y}9{y+=T;p+=t}}6.d(C,e,1,8-e+1)}9{U(k>0){--k;y+=T;7(p>0){6.d(x++,8,1,y-8);p+=L;8=y}9 p+=t}6.d(C,8,1,e-8+1)}}}j 2N(B,q,C,e){7(B>C){c 1u=C;c 1A=e;C=B;e=q;B=1u;q=1A}c o=C-B,k=r.1N(e-q),x=B,y=q,T=(q>e)?-1:1;c s=6.21;7(o>=k){7(o>0&&s-3>0){c S=(s*o*r.2A(1+k*k/(o*o))-o-(s>>1)*k)/o;S=(!(s-4)?r.2w(S):r.1d(S))+1}9 c S=s;c 1b=r.2w(s/2);c t=k<<1,L=t-(o<<1),p=t-o,z=x;U(o>0){--o;++x;7(p>0){6.d(z,y,x-z+1b,S);y+=T;p+=L;z=x}9 p+=t}6.d(z,y,C-z+1b+1,S)}9{7(s-3>0){c S=(s*k*r.2A(1+o*o/(k*k))-(s>>1)*o-k)/k;S=(!(s-4)?r.2w(S):r.1d(S))+1}9 c S=s;c 1b=r.1d(s/2);c t=o<<1,L=t-(k<<1),p=t-k,8=y;7(e<=q){++1b;U(k>0){--k;7(p>0){6.d(x++,y,S,8-y+1b);y+=T;p+=L;8=y}9{y+=T;p+=t}}6.d(C,e,S,8-e+1b)}9{U(k>0){--k;y+=T;7(p>0){6.d(x++,8,S,y-8+1b);p+=L;8=y}9 p+=t}6.d(C,8,S,e-8+1b+1)}}}j 2U(B,q,C,e){7(B>C){c 1u=C;c 1A=e;C=B;e=q;B=1u;q=1A}c o=C-B,k=r.1N(e-q),x=B,y=q,T=(q>e)?-1:1,10=2I;7(o>=k){c t=k<<1,L=t-(o<<1),p=t-o;U(o>0){--o;7(10)6.d(x,y,1,1);10=!10;7(p>0){y+=T;p+=L}9 p+=t;++x}}9{c t=o<<1,L=t-(k<<1),p=t-k;U(k>0){--k;7(10)6.d(x,y,1,1);10=!10;y+=T;7(p>0){++x;p+=L}9 p+=t}}7(10)6.d(x,y,1,1)}j 1s(O,W,G,J){c a=(++G)>>1,b=(++J)>>1,K=G&1,F=J&1,m=O+a,f=W+b,x=0,y=b,z=0,8=b,u=(a*a)<<1,M=u<<1,v=(b*b)<<1,P=v<<1,A=(u>>1)*(1-(b<<1))+v,D=(v>>1)-u*((b<<1)-1),w,h;U(y>0){7(A<0){A+=v*((x<<1)+3);D+=P*(++x)}9 7(D<0){A+=v*((x<<1)+3)-M*(y-1);D+=P*(++x)-u*(((y--)<<1)-3);w=x-z;h=8-y;7((w&2)&&(h&2)){6.1k(m,f,x-2,y+2,1,1,K,F);6.1k(m,f,x-1,y+1,1,1,K,F)}9 6.1k(m,f,x-1,8,w,h,K,F);z=x;8=y}9{D-=u*((y<<1)-3);A-=M*(--y)}}w=a-z+1;h=(8<<1)+F;y=f-8;6.d(m-a,y,w,h);6.d(m+z+K-1,y,w,h)}j 2Q(O,W,G,J){c s=6.21;G+=s+1;J+=s+1;c a=G>>1,b=J>>1,K=G&1,F=J&1,m=O+a,f=W+b,x=0,y=b,u=(a*a)<<1,M=u<<1,v=(b*b)<<1,P=v<<1,A=(u>>1)*(1-(b<<1))+v,D=(v>>1)-u*((b<<1)-1);7(s-4<0&&(!(s-2)||G-3n>0&&J-3n>0)){c z=0,8=b,w,h,1E;U(y>0){7(A<0){A+=v*((x<<1)+3);D+=P*(++x)}9 7(D<0){A+=v*((x<<1)+3)-M*(y-1);D+=P*(++x)-u*(((y--)<<1)-3);w=x-z;h=8-y;7(w-1){1E=w+1+(s&1);h=s}9 7(h-1){1E=s;h+=1+(s&1)}9 1E=h=s;6.1k(m,f,x-1,8,1E,h,K,F);z=x;8=y}9{D-=u*((y<<1)-3);A-=M*(--y)}}6.d(m-a,f-8,s,(8<<1)+F);6.d(m+a+K-s,f-8,s,(8<<1)+F)}9{c 2q=(G-(s<<1))>>1,1r=(J-(s<<1))>>1,1M=0,1g=1r,1B=(2q*2q)<<1,2a=1B<<1,1z=(1r*1r)<<1,2n=1z<<1,1I=(1B>>1)*(1-(1r<<1))+1z,1J=(1z>>1)-1B*((1r<<1)-1),1a=1e 1v(),19=1e 1v(),13=1e 1v();1a[0]=0;19[0]=b;13[0]=1r-1;U(y>0){7(A<0){1a[1a.Z]=x;19[19.Z]=y;A+=v*((x<<1)+3);D+=P*(++x)}9 7(D<0){1a[1a.Z]=x;A+=v*((x<<1)+3)-M*(y-1);D+=P*(++x)-u*(((y--)<<1)-3);19[19.Z]=y}9{D-=u*((y<<1)-3);A-=M*(--y)}7(1g>0){7(1I<0){1I+=1z*((1M<<1)+3);1J+=2n*(++1M);13[13.Z]=1g-1}9 7(1J<0){1I+=1z*((1M<<1)+3)-2a*(1g-1);1J+=2n*(++1M)-1B*(((1g--)<<1)-3);13[13.Z]=1g-1}9{1J-=1B*((1g<<1)-3);1I-=2a*(--1g);13[13.Z-1]--}}}c z=-K,8=b,1X=13[0],l=1a.Z,w,h;1l(c i=0;i<l;i++){7(1f 13[i]!="1p"){7(13[i]<1X||19[i]<8){x=1a[i];6.1k(m,f,x,8,x-z,8-1X,K,F);z=x;8=19[i];1X=13[i]}}9{x=1a[i];6.d(m-x,f-8,1,(8<<1)+F);6.d(m+z+K,f-8,1,(8<<1)+F);z=x;8=19[i]}}6.d(m-a,f-8,1,(8<<1)+F);6.d(m+z+K,f-8,1,(8<<1)+F)}}j 2T(O,W,G,J){c a=(++G)>>1,b=(++J)>>1,K=G&1,F=J&1,2J=F^1,m=O+a,f=W+b,x=0,y=b,u=(a*a)<<1,M=u<<1,v=(b*b)<<1,P=v<<1,A=(u>>1)*(1-(b<<1))+v,D=(v>>1)-u*((b<<1)-1),10=2I;U(y>0){7(A<0){A+=v*((x<<1)+3);D+=P*(++x)}9 7(D<0){A+=v*((x<<1)+3)-M*(y-1);D+=P*(++x)-u*(((y--)<<1)-3)}9{D-=u*((y<<1)-3);A-=M*(--y)}7(10&&y>=2J)6.1k(m,f,x,y,1,1,K,F);10=!10}}j 28(x,y,w,h){c s=6.21;6.d(x,y,w,s);6.d(x+w,y,s,h);6.d(x,y+h,w+s,s);6.d(x,y+s,s,h-s)}j 2O(x,y,w,h){6.1c(x,y,x+w,y);6.1c(x+w,y,x+w,y+h);6.1c(x,y+h,x+w,y+h);6.1c(x,y,x,y+h)}j 2S(){6.2v=\'1m-2L:3D;\';6.32=\'1m-2L:3B;\';6.2z=\'1m-17:3C;\';6.2R=6.2z+6.32;6.3z=6.2R}c 2x=1e 2S();j 2V(){6.3x=-1}c 4k=1e 2V();j 45(N,1h){6.46=j(x){6.Y=x.4a()};6.3w=j(x){6.21=x;7(!(x+1)){6.1c=2U;6.1s=2T;6.2d=2O}9 7(x-1>0){6.1c=2N;6.1s=2Q;6.2d=28}9{6.1c=2P;6.1s=1s;6.2d=28}};6.3a=j(27){6.4e=27;7(1y){6.d=31;6.1w=27?2W:1w}9 6.d=27?2Y:d};6.3s=j(2X,2D,2B){6.2o=2X;6.2y=2D;6.2u=2B||2x.2v};6.2F=6.4f=j(x,y){1l(c i=x.Z-1;i;){--i;6.1c(x[i],y[i],x[i+1],y[i+1])}};6.48=j(x,y,w,h){6.d(x,y,w,h)};6.4c=j(x,y){6.2F(x,y);6.1c(x[x.Z-1],y[x.Z-1],x[0],y[0])};6.4b=6.4d=j(x,y,w,h){6.1s(x,y,w,h)};6.47=6.49=j(O,W,w,h){c a=w>>1,b=h>>1,K=w&1,F=h&1,m=O+a,f=W+b,x=0,y=b,8=b,u=(a*a)<<1,M=u<<1,v=(b*b)<<1,P=v<<1,A=(u>>1)*(1-(b<<1))+v,D=(v>>1)-u*((b<<1)-1),E,22,23;7(w)U(y>0){7(A<0){A+=v*((x<<1)+3);D+=P*(++x)}9 7(D<0){A+=v*((x<<1)+3)-M*(y-1);E=m-x;22=(x<<1)+K;D+=P*(++x)-u*(((y--)<<1)-3);23=8-y;6.d(E,f-8,22,23);6.d(E,f+y+F,22,23);8=y}9{D-=u*((y<<1)-3);A-=M*(--y)}}6.d(m-a,f-8,w,(8<<1)+F)};6.4l=j(2C,3r,2i,2h,1D,1C){c a=2i>>1,b=2h>>1,18=(2i&1)|((2h&1)<<16),m=2C+a,f=3r+b,x=0,y=b,z=x,8=y,u=(a*a)<<1,M=u<<1,v=(b*b)<<1,P=v<<1,A=(u>>1)*(1-(b<<1))+v,D=(v>>1)-u*((b<<1)-1),2f,1Z,2l,1F,I=(1<<(r.3m((1D%=3k.0)/1S.0)<<3))|(2<<(r.3m((1C%=3k.0)/1S.0)<<3))|((1D>=1C)<<16),11=1e 1v(b+1),12=1e 1v(b+1);1D*=r.3p/1S.0;1C*=r.3p/1S.0;2f=m+r.1d(a*r.3l(1D));1Z=f+r.1d(-b*r.3v(1D));2m(11,m,f,2f,1Z);2l=m+r.1d(a*r.3l(1C));1F=f+r.1d(-b*r.3v(1C));2m(12,m,f,2l,1F);U(y>0){7(A<0){A+=v*((x<<1)+3);D+=P*(++x)}9 7(D<0){A+=v*((x<<1)+3)-M*(y-1);z=x;D+=P*(++x)-u*(((y--)<<1)-3);6.20(z,y,8,m,f,18,11,12,I);8=y}9{D-=u*((y<<1)-3);A-=M*(--y);7(y&&(11[y]!=11[y-1]||12[y]!=12[y-1])){6.20(x,y,8,m,f,18,11,12,I);z=x;8=y}}}6.20(x,0,8,m,f,18,11,12,I);7(18>>16){7(I>>16){c E=(1Z<=f||1F>f)?(m-x):m;6.d(E,f,x+m-E+(18&2Z),1)}9 7((I&2p)&&1F>f)6.d(m-x,f,x,1)}};6.4g=j(1t,15){c i;c y;c 1L,1x;c B,q;c C,e;c 1n,1q;c 1K;c n=1t.Z;7(!n)26;1L=15[0];1x=15[0];1l(i=1;i<n;i++){7(15[i]<1L)1L=15[i];7(15[i]>1x)1x=15[i]}1l(y=1L;y<=1x;y++){c 1o=1e 1v();1K=0;1l(i=0;i<n;i++){7(!i){1n=n-1;1q=0}9{1n=i-1;1q=i}q=15[1n];e=15[1q];7(q<e){B=1t[1n];C=1t[1q]}9 7(q>e){e=15[1n];q=15[1q];C=1t[1n];B=1t[1q]}9 4i;7((y>=q)&&(y<e))1o[1K++]=r.1d((y-q)*(C-B)/(e-q)+B);9 7((y==1x)&&(y>q)&&(y<=e))1o[1K++]=r.1d((y-q)*(C-B)/(e-q)+B)}1o.4h(2K);1l(i=0;i<1K;i+=2)6.d(1o[i],y,1o[i+1]-1o[i]+1,1)}};6.44=j(1U,x,y){6.R+=\'<V 17="1j:1i;3O-3N:3P;\'+\'O:\'+x+\'H;\'+\'W:\'+y+\'H;\'+\'1m-3h:\'+6.2o+\';\'+\'1m-35:\'+6.2y+\';\'+\'Y:\'+6.Y+\';\'+6.2u+\'">\'+1U+\'<\\/V>\'};6.3R=j(1U,x,y,G,3i){6.R+=\'<V 17="1j:1i;1H:1G;\'+\'O:\'+x+\'H;\'+\'W:\'+y+\'H;\'+\'G:\'+G+\'H;\'+\'3Q-3M:\'+3i+\';\'+\'1m-3h:\'+6.2o+\';\'+\'1m-35:\'+6.2y+\';\'+\'Y:\'+6.Y+\';\'+6.2u+\'">\'+1U+\'<\\/V>\'};6.3I=j(3o,x,y,w,h,a){6.R+=\'<V 17="1j:1i;\'+\'O:\'+x+\'H;\'+\'W:\'+y+\'H;\'+(w?(\'G:\'+w+\'H;\'):\'\')+(h?(\'J:\'+h+\'H;\'):\'\')+\'">\'+\'<3H 3J="\'+3o+\'"\'+(w?(\' G="\'+w+\'"\'):\'\')+(h?(\' J="\'+h+\'"\'):\'\')+(a?(\' \'+a):\'\')+\'>\'+\'<\\/V>\'};6.3L=j(){6.R="";7(6.N)6.N.3K=""};6.1k=j(m,f,x,y,w,h,K,F){c E=m-x,Q=m+x+K-w,2t=f-y,2r=f+y+F-h;7(Q>E+w){6.d(Q,2t,w,h);6.d(Q,2r,w,h)}9 w=Q-E+w;6.d(E,2t,w,h);6.d(E,2r,w,h)};6.20=j(x,y,8,m,f,18,11,12,I){c 14=m+x+(18&2Z),e,h=8-y,E,Q,w;7(!h)h=1;x=m-x;7(I&3S){e=f-y-h;7(I&30){7(I&2M){E=r.24(x,12[y]);w=14-E;7(w>0)6.d(E,e,w,h)}7(I&2p){Q=r.25(14,11[y]);w=Q-x;7(w>0)6.d(x,e,w,h)}}9 6.d(x,e,14-x,h);e=f+y+(18>>16);7(I&2G){7(I&2H){E=r.24(x,11[y]);w=14-E;7(w>0)6.d(E,e,w,h)}7(I&2E){Q=r.25(14,12[y]);w=Q-x;7(w>0)6.d(x,e,w,h)}}9 6.d(x,e,14-x,h)}9{7(I&30){7(I&2M)E=r.24(x,12[y]);9 E=x;7(I&2p)Q=r.25(14,11[y]);9 Q=14;e=f-y-h;w=Q-E;7(w>0)6.d(E,e,w,h)}7(I&2G){7(I&2H)E=r.24(x,11[y]);9 E=x;7(I&2E)Q=r.25(14,12[y]);9 Q=14;e=f+y+(18>>16);w=Q-E;7(w>0)6.d(E,e,w,h)}}};6.3w(1);6.3s("40,3Z,41,43-42","3Y",2x.2v);6.Y="#3U";6.R="";6.1h=1h||2c;7(!1T)3f();7(1T){7(N){7(1f(N)=="3T")6.1V=X.2b?(6.1h.X.2b[N]||1W):X.3d?(6.1h.X.3d(N)||1W):1W;9 7(N==2c.X)6.1V=X.3V("3j")[0];9 6.1V=N;6.N=6.1h.X.3g("V");6.N.17.3X=0;6.1V.2e(6.N);6.2k=1O?36:33}9 6.2k=34}9 6.2k=39;6.3a(3W)}j 2m(1P,B,q,C,e){c o=r.1N(C-B),k=r.1N(e-q),x=B,y=q,2g=(B>C)?-1:1,T=(q>e)?-1:1,p,i=0;7(o>=k){c t=k<<1,L=t-(o<<1);p=t-o;U(o>0){--o;7(p>0){1P[i++]=x;y+=T;p+=L}9 p+=t;x+=2g}}9{c t=o<<1,L=t-(k<<1);p=t-k;U(k>0){--k;y+=T;1P[i++]=x;7(p>0){x+=2g;p+=L}9 p+=t}}1l(c 2j=1P.Z,i=2j-i;i;)1P[2j-(i--)]=x};j 2K(x,y){26(x-y)}',62,270,'||||||this|if|oy|else|||var|_mkDiv|y2|cy||||function|dy||cx||dx||y1|Math||pr|aa2|bb2||||ox|st|x1|x2|tt|xl|hod|width|px|iSects|height|wod|pru|aa4|cnv|left|bb4|xr|htm|_s|yIncr|while|div|top|document|color|length|drw|aBndA|aBndZ|_pxb|xrDef|array_y||style|iOdds|pxt|pxl|ad|drawLine|round|new|typeof|_y|wnd|absolute|position|_mkOvQds|for|font|ind1|polyInts|undefined|ind2|_b|_mkOv|array_x|_x2|Array|_htmRpc|maxy|jg_fast|_bb2|_y2|_aa2|fAngZ|fAngA|pxw|yEndZ|hidden|overflow|_st|_tt|ints|miny|_x|abs|jg_dom|aLin|jg_ie|background|180|jg_ok|txt|cont|null|_oy|jg_moz|yEndA|_mkArcDiv|stroke|dw|dh|max|min|return|arg|_mkRect|createRange|_aa4|all|window|drawRect|appendChild|xEndA|xIncr|iH|iW|len|paint|xEndZ|_mkLinVirt|_bb4|ftFam|0x01|_a|yb|_regex|yt|ftSty|PLAIN|ceil|Font|ftSz|ITALIC|sqrt|sty|iL|sz|0x0200|drawPolyline|0xff00|0x0100|true|hodu|_CompInt|weight|0x02|_mkLin2D|_mkRectDott|_mkLin|_mkOv2D|ITALIC_BOLD|jsgFont|_mkOvDott|_mkLinDott|jsgStroke|_htmPrtRpc|fam|_mkDivPrt|0xffff|0x00ff|_mkDivIe|BOLD|_pntCnvIe|_pntDoc|size|_pntCnvDom|insertAdjacentHTML|border|_pntN|setPrintable|replace|rect|getElementById|clip|_chkDHTM|createElement|family|halign|body|360|cos|floor|51|imgSrc|PI|solid|iT|setFont|createContextualFragment|setStartBefore|sin|setStroke|DOTTED|0px|BOLD_ITALIC|MozOpacity|bold|italic|normal|write|BeforeEnd|4px|img|drawImage|src|innerHTML|clear|align|space|white|nowrap|text|drawStringRect|0xff0000|string|000000|getElementsByTagName|false|fontSize|12px|geneva|verdana|helvetica|serif|sans|drawString|jsGraphics|setColor|fillEllipse|fillRect|fillOval|toLowerCase|drawEllipse|drawPolygon|drawOval|printable|drawPolyLine|fillPolygon|sort|continue|opera|Stroke|fillArc'.split('|'),0,{}))
// mredkj.com
function NumberFormat(num, inputDecimal)
{
this.VERSION = 'Number Format v1.5.4';
this.COMMA = ',';
this.PERIOD = '.';
this.DASH = '-'; 
this.LEFT_PAREN = '('; 
this.RIGHT_PAREN = ')'; 
this.LEFT_OUTSIDE = 0; 
this.LEFT_INSIDE = 1;  
this.RIGHT_INSIDE = 2;  
this.RIGHT_OUTSIDE = 3;  
this.LEFT_DASH = 0; 
this.RIGHT_DASH = 1; 
this.PARENTHESIS = 2; 
this.NO_ROUNDING = -1 
this.num;
this.numOriginal;
this.hasSeparators = false;  
this.separatorValue;  
this.inputDecimalValue; 
this.decimalValue;  
this.negativeFormat; 
this.negativeRed; 
this.hasCurrency;  
this.currencyPosition;  
this.currencyValue;  
this.places;
this.roundToPlaces; 
this.truncate; 
this.setNumber = setNumberNF;
this.toUnformatted = toUnformattedNF;
this.setInputDecimal = setInputDecimalNF; 
this.setSeparators = setSeparatorsNF; 
this.setCommas = setCommasNF;
this.setNegativeFormat = setNegativeFormatNF; 
this.setNegativeRed = setNegativeRedNF; 
this.setCurrency = setCurrencyNF;
this.setCurrencyPrefix = setCurrencyPrefixNF;
this.setCurrencyValue = setCurrencyValueNF; 
this.setCurrencyPosition = setCurrencyPositionNF; 
this.setPlaces = setPlacesNF;
this.toFormatted = toFormattedNF;
this.toPercentage = toPercentageNF;
this.getOriginal = getOriginalNF;
this.moveDecimalRight = moveDecimalRightNF;
this.moveDecimalLeft = moveDecimalLeftNF;
this.getRounded = getRoundedNF;
this.preserveZeros = preserveZerosNF;
this.justNumber = justNumberNF;
this.expandExponential = expandExponentialNF;
this.getZeros = getZerosNF;
this.moveDecimalAsString = moveDecimalAsStringNF;
this.moveDecimal = moveDecimalNF;
this.addSeparators = addSeparatorsNF;
if (inputDecimal == null) {
this.setNumber(num, this.PERIOD);
} else {
this.setNumber(num, inputDecimal); 
}
this.setCommas(true);
this.setNegativeFormat(this.LEFT_DASH); 
this.setNegativeRed(false); 
this.setCurrency(false); 
this.setCurrencyPrefix('$');
this.setPlaces(2);
}
function setInputDecimalNF(val)
{
this.inputDecimalValue = val;
}
function setNumberNF(num, inputDecimal)
{
if (inputDecimal != null) {
this.setInputDecimal(inputDecimal); 
}
this.numOriginal = num;
this.num = this.justNumber(num);
}
function toUnformattedNF()
{
return (this.num);
}
function getOriginalNF()
{
return (this.numOriginal);
}
function setNegativeFormatNF(format)
{
this.negativeFormat = format;
}
function setNegativeRedNF(isRed)
{
this.negativeRed = isRed;
}
function setSeparatorsNF(isC, separator, decimal)
{
this.hasSeparators = isC;
if (separator == null) separator = this.COMMA;
if (decimal == null) decimal = this.PERIOD;
if (separator == decimal) {
this.decimalValue = (decimal == this.PERIOD) ? this.COMMA : this.PERIOD;
} else {
this.decimalValue = decimal;
}
this.separatorValue = separator;
}
function setCommasNF(isC)
{
this.setSeparators(isC, this.COMMA, this.PERIOD);
}
function setCurrencyNF(isC)
{
this.hasCurrency = isC;
}
function setCurrencyValueNF(val)
{
this.currencyValue = val;
}
function setCurrencyPrefixNF(cp)
{
this.setCurrencyValue(cp);
this.setCurrencyPosition(this.LEFT_OUTSIDE);
}
function setCurrencyPositionNF(cp)
{
this.currencyPosition = cp
}
function setPlacesNF(p, tr)
{
this.roundToPlaces = !(p == this.NO_ROUNDING); 
this.truncate = (tr != null && tr); 
this.places = (p < 0) ? 0 : p; 
}
function addSeparatorsNF(nStr, inD, outD, sep)
{
nStr += '';
var dpos = nStr.indexOf(inD);
var nStrEnd = '';
if (dpos != -1) {
nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
nStr = nStr.substring(0, dpos);
}
var rgx = /(\d+)(\d{3})/;
while (rgx.test(nStr)) {
nStr = nStr.replace(rgx, '$1' + sep + '$2');
}
return nStr + nStrEnd;
}
function toFormattedNF()
{	
var pos;
var nNum = this.num; 
var nStr;            
var splitString = new Array(2);   
if (this.roundToPlaces) {
nNum = this.getRounded(nNum);
nStr = this.preserveZeros(Math.abs(nNum)); 
} else {
nStr = this.expandExponential(Math.abs(nNum)); 
}
if (this.hasSeparators) {
nStr = this.addSeparators(nStr, this.PERIOD, this.decimalValue, this.separatorValue);
} else {
nStr = nStr.replace(new RegExp('\\' + this.PERIOD), this.decimalValue); 
}
var c0 = '';
var n0 = '';
var c1 = '';
var n1 = '';
var n2 = '';
var c2 = '';
var n3 = '';
var c3 = '';
var negSignL = (this.negativeFormat == this.PARENTHESIS) ? this.LEFT_PAREN : this.DASH;
var negSignR = (this.negativeFormat == this.PARENTHESIS) ? this.RIGHT_PAREN : this.DASH;
if (this.currencyPosition == this.LEFT_OUTSIDE) {
if (nNum < 0) {
if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
}
if (this.hasCurrency) c0 = this.currencyValue;
} else if (this.currencyPosition == this.LEFT_INSIDE) {
if (nNum < 0) {
if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
}
if (this.hasCurrency) c1 = this.currencyValue;
}
else if (this.currencyPosition == this.RIGHT_INSIDE) {
if (nNum < 0) {
if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
}
if (this.hasCurrency) c2 = this.currencyValue;
}
else if (this.currencyPosition == this.RIGHT_OUTSIDE) {
if (nNum < 0) {
if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
}
if (this.hasCurrency) c3 = this.currencyValue;
}
nStr = c0 + n0 + c1 + n1 + nStr + n2 + c2 + n3 + c3;
if (this.negativeRed && nNum < 0) {
nStr = '<font color="red">' + nStr + '</font>';
}
return (nStr);
}
function toPercentageNF()
{
nNum = this.num * 100;
nNum = this.getRounded(nNum);
return nNum + '%';
}
function getZerosNF(places)
{
var extraZ = '';
var i;
for (i=0; i<places; i++) {
extraZ += '0';
}
return extraZ;
}
function expandExponentialNF(origVal)
{
if (isNaN(origVal)) return origVal;
var newVal = parseFloat(origVal) + ''; 
var eLoc = newVal.toLowerCase().indexOf('e');
if (eLoc != -1) {
var plusLoc = newVal.toLowerCase().indexOf('+');
var negLoc = newVal.toLowerCase().indexOf('-', eLoc); 
var justNumber = newVal.substring(0, eLoc);
if (negLoc != -1) {
var places = newVal.substring(negLoc + 1, newVal.length);
justNumber = this.moveDecimalAsString(justNumber, true, parseInt(places));
} else {
if (plusLoc == -1) plusLoc = eLoc;
var places = newVal.substring(plusLoc + 1, newVal.length);
justNumber = this.moveDecimalAsString(justNumber, false, parseInt(places));
}
newVal = justNumber;
}
return newVal;
} 
function moveDecimalRightNF(val, places)
{
var newVal = '';
if (places == null) {
newVal = this.moveDecimal(val, false);
} else {
newVal = this.moveDecimal(val, false, places);
}
return newVal;
}
function moveDecimalLeftNF(val, places)
{
var newVal = '';
if (places == null) {
newVal = this.moveDecimal(val, true);
} else {
newVal = this.moveDecimal(val, true, places);
}
return newVal;
}
function moveDecimalAsStringNF(val, left, places)
{
var spaces = (arguments.length < 3) ? this.places : places;
if (spaces <= 0) return val; 
var newVal = val + '';
var extraZ = this.getZeros(spaces);
var re1 = new RegExp('([0-9.]+)');
if (left) {
newVal = newVal.replace(re1, extraZ + '$1');
var re2 = new RegExp('(-?)([0-9]*)([0-9]{' + spaces + '})(\\.?)');		
newVal = newVal.replace(re2, '$1$2.$3');
} else {
var reArray = re1.exec(newVal); 
if (reArray != null) {
newVal = newVal.substring(0,reArray.index) + reArray[1] + extraZ + newVal.substring(reArray.index + reArray[0].length); 
}
var re2 = new RegExp('(-?)([0-9]*)(\\.?)([0-9]{' + spaces + '})');
newVal = newVal.replace(re2, '$1$2$4.');
}
newVal = newVal.replace(/\.$/, ''); 
return newVal;
}
function moveDecimalNF(val, left, places)
{
var newVal = '';
if (places == null) {
newVal = this.moveDecimalAsString(val, left);
} else {
newVal = this.moveDecimalAsString(val, left, places);
}
return parseFloat(newVal);
}
function getRoundedNF(val)
{
val = this.moveDecimalRight(val);
if (this.truncate) {
val = val >= 0 ? Math.floor(val) : Math.ceil(val); 
} else {
val = Math.round(val);
}
val = this.moveDecimalLeft(val);
return val;
}
function preserveZerosNF(val)
{
var i;
val = this.expandExponential(val);
if (this.places <= 0) return val; 
var decimalPos = val.indexOf('.');
if (decimalPos == -1) {
val += '.';
for (i=0; i<this.places; i++) {
val += '0';
}
} else {
var actualDecimals = (val.length - 1) - decimalPos;
var difference = this.places - actualDecimals;
for (i=0; i<difference; i++) {
val += '0';
}
}
return val;
}
function justNumberNF(val)
{
newVal = val + '';
var isPercentage = false;
if (newVal.indexOf('%') != -1) {
newVal = newVal.replace(/\%/g, '');
isPercentage = true; 
}
var re = new RegExp('[^\\' + this.inputDecimalValue + '\\d\\-\\+\\(\\)eE]', 'g');	
newVal = newVal.replace(re, '');
var tempRe = new RegExp('[' + this.inputDecimalValue + ']', 'g');
var treArray = tempRe.exec(newVal); 
if (treArray != null) {
var tempRight = newVal.substring(treArray.index + treArray[0].length); 
newVal = newVal.substring(0,treArray.index) + this.PERIOD + tempRight.replace(tempRe, ''); 
}
if (newVal.charAt(newVal.length - 1) == this.DASH ) {
newVal = newVal.substring(0, newVal.length - 1);
newVal = '-' + newVal;
}
else if (newVal.charAt(0) == this.LEFT_PAREN
&& newVal.charAt(newVal.length - 1) == this.RIGHT_PAREN) {
newVal = newVal.substring(1, newVal.length - 1);
newVal = '-' + newVal;
}
newVal = parseFloat(newVal);
if (!isFinite(newVal)) {
newVal = 0;
}
if (isPercentage) {
newVal = this.moveDecimalLeft(newVal, 2);
}
return newVal;
}
function switchMenu(obj) {
	var el = document.getElementById(obj);
		if ( el.style.display != 'none' ) {
			el.style.display = 'none';
		}
		else {
			el.style.display = '';
		}
}// script.aculo.us effects.js v1.7.1_beta1, Mon Mar 12 14:40:50 +0100 2007

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/ 

// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';
  if(this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if(this.slice(0,1) == '#') {  
      if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if(this.length==7) color = this.toLowerCase();  
    }  
  }  
  return(color.length==7 ? color : (arguments[0] || this));  
}

/*--------------------------------------------------------------------------*/

Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
}

Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
}

Element.setContentZoom = function(element, percent) {
  element = $(element);  
  element.setStyle({fontSize: (percent/100) + 'em'});   
  if(Prototype.Browser.WebKit) window.scrollBy(0,0);
  return element;
}

Element.getInlineOpacity = function(element){
  return $(element).style.opacity || '';
}

Element.forceRerendering = function(element) {
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
  } catch(e) { }
};

/*--------------------------------------------------------------------------*/

Array.prototype.call = function() {
  var args = arguments;
  this.each(function(f){ f.apply(this, args) });
}

/*--------------------------------------------------------------------------*/

var Effect = {
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
  tagifyText: function(element) {
    if(typeof Builder == 'undefined')
      throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
      
    var tagifyStyle = 'position:relative';
    if(Prototype.Browser.IE) tagifyStyle += ';zoom:1';
    
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if(child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            Builder.node('span',{style: tagifyStyle},
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if(((typeof element == 'object') || 
        (typeof element == 'function')) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || {});
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
    }, arguments[2] || {});
    Effect[element.visible() ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

var Effect2 = Effect; // deprecated

/* ------------- transitions ------------- */

Effect.Transitions = {
  linear: Prototype.K,
  sinoidal: function(pos) {
    return (-Math.cos(pos*Math.PI)/2) + 0.5;
  },
  reverse: function(pos) {
    return 1-pos;
  },
  flicker: function(pos) {
    var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
    return (pos > 1 ? 1 : pos);
  },
  wobble: function(pos) {
    return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
  },
  pulse: function(pos, pulses) { 
    pulses = pulses || 5; 
    return (
      Math.round((pos % (1/pulses)) * pulses) == 0 ? 
            ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) : 
        1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2))
      );
  },
  none: function(pos) {
    return 0;
  },
  full: function(pos) {
    return 1;
  }
};

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
  initialize: function() {
    this.effects  = [];
    this.interval = null;    
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = (typeof effect.options.queue == 'string') ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'with-last':
        timestamp = this.effects.pluck('startOn').max() || timestamp;
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);
    
    if(!this.interval)
      this.interval = setInterval(this.loop.bind(this), 15);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if(this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    for(var i=0, len=this.effects.length;i<len;i++) 
      this.effects[i] && this.effects[i].loop(timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if(typeof queueName != 'string') return queueName;
    
    if(!this.instances[queueName])
      this.instances[queueName] = new Effect.ScopedQueue();
      
    return this.instances[queueName];
  }
}
Effect.Queue = Effect.Queues.get('global');

Effect.DefaultOptions = {
  transition: Effect.Transitions.sinoidal,
  duration:   1.0,   // seconds
  fps:        100,   // 100= assume 66fps max.
  sync:       false, // true for combining
  from:       0.0,
  to:         1.0,
  delay:      0.0,
  queue:      'parallel'
}

Effect.Base = function() {};
Effect.Base.prototype = {
  position: null,
  start: function(options) {
    function codeForEvent(options,eventName){
      return (
        (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
        (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
      );
    }
    if(options.transition === false) options.transition = Effect.Transitions.linear;
    this.options      = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn+(this.options.duration*1000);
    this.fromToDelta  = this.options.to-this.options.from;
    this.totalTime    = this.finishOn-this.startOn;
    this.totalFrames  = this.options.fps*this.options.duration;
    
    eval('this.render = function(pos){ '+
      'if(this.state=="idle"){this.state="running";'+
      codeForEvent(options,'beforeSetup')+
      (this.setup ? 'this.setup();':'')+ 
      codeForEvent(options,'afterSetup')+
      '};if(this.state=="running"){'+
      'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
      'this.position=pos;'+
      codeForEvent(options,'beforeUpdate')+
      (this.update ? 'this.update(pos);':'')+
      codeForEvent(options,'afterUpdate')+
      '}}');
    
    this.event('beforeStart');
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if(timePos >= this.startOn) {
      if(timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if(this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / this.totalTime,
          frame = Math.round(pos * this.totalFrames);
      if(frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  cancel: function() {
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if(this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    var data = $H();
    for(property in this)
      if(typeof this[property] != 'function') data[property] = this[property];
    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
}

Effect.Parallel = Class.create();
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if(effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Event = Class.create();
Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), {
  initialize: function() {
    var options = Object.extend({
      duration: 0
    }, arguments[0] || {});
    this.start(options);
  },
  update: Prototype.emptyFunction
});

Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    // make this work on IE on elements without 'layout'
    if(Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
      this.element.setStyle({zoom: 1});
    var options = Object.extend({
      from: this.element.getOpacity() || 0.0,
      to:   1.0
    }, arguments[1] || {});
    this.start(options);
  },
  update: function(position) {
    this.element.setOpacity(position);
  }
});

Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Bug in Opera: Opera returns the "real" position of a static element or
    // relative element that does not have top/left explicitly set.
    // ==> Always set top and left for position relative elements in your stylesheets 
    // (to 0 if you do not need them) 
    this.element.makePositioned();
    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
    if(this.options.mode == 'absolute') {
      // absolute movement, so we need to calc deltaX and deltaY
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    this.element.setStyle({
      left: Math.round(this.options.x  * position + this.originalLeft) + 'px',
      top:  Math.round(this.options.y  * position + this.originalTop)  + 'px'
    });
  }
});

// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element, 
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
};

Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
  initialize: function(element, percent) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || {});
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');
    
    this.originalStyle = {};
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%','pt'].each( function(fontSizeType) {
      if(fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if(this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = {};
    if(this.options.scaleX) d.width = Math.round(width) + 'px';
    if(this.options.scaleY) d.height = Math.round(height) + 'px';
    if(this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if(this.elementPositioning == 'absolute') {
        if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if(this.options.scaleY) d.top = -topd + 'px';
        if(this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});

Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if(this.element.getStyle('display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = {};
    if (!this.options.keepBackgroundImage) {
      this.oldStyle.backgroundImage = this.element.getStyle('background-image');
      this.element.setStyle({backgroundImage: 'none'});
    }
    if(!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
    if(!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = Class.create();
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    this.start(arguments[1] || {});
  },
  setup: function() {
    Position.prepare();
    var offsets = Position.cumulativeOffset(this.element);
    if(this.options.offset) offsets[1] += this.options.offset;
    var max = window.innerHeight ? 
      window.height - window.innerHeight :
      document.body.scrollHeight - 
        (document.documentElement.clientHeight ? 
          document.documentElement.clientHeight : document.body.clientHeight);
    this.scrollStart = Position.deltaY;
    this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
  },
  update: function(position) {
    Position.prepare();
    window.scrollTo(Position.deltaX, 
      this.scrollStart + (position*this.delta));
  }
});

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  var options = Object.extend({
  from: element.getOpacity() || 1.0,
  to:   0.0,
  afterFinishInternal: function(effect) { 
    if(effect.options.to!=0) return;
    effect.element.hide().setStyle({opacity: oldOpacity}); 
  }}, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Appear = function(element) {
  element = $(element);
  var options = Object.extend({
  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
  to:   1.0,
  // force Safari to render floated elements properly
  afterFinishInternal: function(effect) {
    effect.element.forceRerendering();
  },
  beforeSetup: function(effect) {
    effect.element.setOpacity(effect.options.from).show(); 
  }}, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { 
    opacity: element.getInlineOpacity(), 
    position: element.getStyle('position'),
    top:  element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height
  };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) {
        Position.absolutize(effect.effects[0].element)
      },
      afterFinishInternal: function(effect) {
         effect.effects[0].element.hide().setStyle(oldStyle); }
     }, arguments[1] || {})
   );
}

Effect.BlindUp = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      } 
    }, arguments[1] || {})
  );
}

Effect.BlindDown = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || {}));
}

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  return new Effect.Appear(element, Object.extend({
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { 
          effect.element.makePositioned().makeClipping();
        },
        afterFinishInternal: function(effect) {
          effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
        }
      })
    }
  }, arguments[1] || {}));
}

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left'),
    opacity: element.getInlineOpacity() };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) {
          effect.effects[0].element.makePositioned(); 
        },
        afterFinishInternal: function(effect) {
          effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
        } 
      }, arguments[1] || {}));
}

Effect.Shake = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left') };
    return new Effect.Move(element, 
      { x:  20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
        effect.element.undoPositioned().setStyle(oldStyle);
  }}) }}) }}) }}) }}) }});
}

Effect.SlideDown = function(element) {
  element = $(element).cleanWhitespace();
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: window.opera ? 0 : 1,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
    }, arguments[1] || {})
  );
}

Effect.SlideUp = function(element) {
  element = $(element).cleanWhitespace();
  var oldInnerBottom = element.down().getStyle('bottom');
  return new Effect.Scale(element, window.opera ? 0 : 1,
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    restoreAfterFinish: true,
    beforeStartInternal: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().show();
    },  
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    },
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
      effect.element.down().undoPositioned();
    }
   }, arguments[1] || {})
  );
}

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, { 
    restoreAfterFinish: true,
    beforeSetup: function(effect) {
      effect.element.makeClipping(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping(); 
    }
  });
}

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01, 
    beforeSetup: function(effect) {
      effect.element.hide().makeClipping().makePositioned();
    },
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) {
               effect.effects[0].element.setStyle({height: '0px'}).show(); 
             },
             afterFinishInternal: function(effect) {
               effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); 
             }
           }, options)
      )
    }
  });
}

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned().makeClipping(); 
         },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
       }, options)
  );
}

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || {};
  var oldOpacity = element.getInlineOpacity();
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 2.0, from: 0,
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    }, options), {transition: reverser}));
}

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  element.makeClipping();
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping().setStyle(oldStyle);
      } });
  }}, arguments[1] || {}));
};

Effect.Morph = Class.create();
Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      style: {}
    }, arguments[1] || {});
    if (typeof options.style == 'string') {
      if(options.style.indexOf(':') == -1) {
        var cssText = '', selector = '.' + options.style;
        $A(document.styleSheets).reverse().each(function(styleSheet) {
          if (styleSheet.cssRules) cssRules = styleSheet.cssRules;
          else if (styleSheet.rules) cssRules = styleSheet.rules;
          $A(cssRules).reverse().each(function(rule) {
            if (selector == rule.selectorText) {
              cssText = rule.style.cssText;
              throw $break;
            }
          });
          if (cssText) throw $break;
        });
        this.style = cssText.parseStyle();
        options.afterFinishInternal = function(effect){
          effect.element.addClassName(effect.options.style);
          effect.transforms.each(function(transform) {
            if(transform.style != 'opacity')
              effect.element.style[transform.style] = '';
          });
        }
      } else this.style = options.style.parseStyle();
    } else this.style = $H(options.style)
    this.start(options);
  },
  setup: function(){
    function parseColor(color){
      if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
      color = color.parseColor();
      return $R(0,2).map(function(i){
        return parseInt( color.slice(i*2+1,i*2+3), 16 ) 
      });
    }
    this.transforms = this.style.map(function(pair){
      var property = pair[0], value = pair[1], unit = null;

      if(value.parseColor('#zzzzzz') != '#zzzzzz') {
        value = value.parseColor();
        unit  = 'color';
      } else if(property == 'opacity') {
        value = parseFloat(value);
        if(Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
          this.element.setStyle({zoom: 1});
      } else if(Element.CSS_LENGTH.test(value)) {
          var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
          value = parseFloat(components[1]);
          unit = (components.length == 3) ? components[2] : null;
      }

      var originalValue = this.element.getStyle(property);
      return { 
        style: property.camelize(), 
        originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), 
        targetValue: unit=='color' ? parseColor(value) : value,
        unit: unit
      };
    }.bind(this)).reject(function(transform){
      return (
        (transform.originalValue == transform.targetValue) ||
        (
          transform.unit != 'color' &&
          (isNaN(transform.originalValue) || isNaN(transform.targetValue))
        )
      )
    });
  },
  update: function(position) {
    var style = {}, transform, i = this.transforms.length;
    while(i--)
      style[(transform = this.transforms[i]).style] = 
        transform.unit=='color' ? '#'+
          (Math.round(transform.originalValue[0]+
            (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
          (Math.round(transform.originalValue[1]+
            (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
          (Math.round(transform.originalValue[2]+
            (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
        transform.originalValue + Math.round(
          ((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit;
    this.element.setStyle(style, true);
  }
});

Effect.Transform = Class.create();
Object.extend(Effect.Transform.prototype, {
  initialize: function(tracks){
    this.tracks  = [];
    this.options = arguments[1] || {};
    this.addTracks(tracks);
  },
  addTracks: function(tracks){
    tracks.each(function(track){
      var data = $H(track).values().first();
      this.tracks.push($H({
        ids:     $H(track).keys().first(),
        effect:  Effect.Morph,
        options: { style: data }
      }));
    }.bind(this));
    return this;
  },
  play: function(){
    return new Effect.Parallel(
      this.tracks.map(function(track){
        var elements = [$(track.ids) || $$(track.ids)].flatten();
        return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) });
      }).flatten(),
      this.options
    );
  }
});

Element.CSS_PROPERTIES = $w(
  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 
  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
  'fontSize fontWeight height left letterSpacing lineHeight ' +
  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
  'right textIndent top width wordSpacing zIndex');
  
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

String.prototype.parseStyle = function(){
  var element = document.createElement('div');
  element.innerHTML = '<div style="' + this + '"></div>';
  var style = element.childNodes[0].style, styleRules = $H();
  
  Element.CSS_PROPERTIES.each(function(property){
    if(style[property]) styleRules[property] = style[property]; 
  });
  if(Prototype.Browser.IE && this.indexOf('opacity') > -1) {
    styleRules.opacity = this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1];
  }
  return styleRules;
};

Element.morph = function(element, style) {
  new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {}));
  return element;
};

['getInlineOpacity','forceRerendering','setContentZoom',
 'collectTextNodes','collectTextNodesIgnoreClass','morph'].each( 
  function(f) { Element.Methods[f] = Element[f]; }
);

Element.Methods.visualEffect = function(element, effect, options) {
  s = effect.dasherize().camelize();
  effect_class = s.charAt(0).toUpperCase() + s.substring(1);
  new Effect[effect_class](element, options);
  return $(element);
};

Element.addMethods();var slider;
function inicio_mapcity(idCiudad)
{
	init_2_0(idCiudad);
	if ($('slider_track'))
	{
		slider = new Control.Slider('slider_handle','slider_track',{
			onSlide:function(v){ 
				if(map_2_0.getLayerIndex(layer_satelite_chile) == -1){
					ver_layer('satelite');
				}			
				layer_base_chile.setVisibility(true);
				layer_satelite_chile.setOpacity(v);
			},
			onChange:function(v){
				if(v==0){
					if(map_2_0.getLayerIndex(layer_satelite_chile) > -1){
						//ver_layer('mapa');
						
						layer_satelite_chile.setOpacity(v);
						hideFormBuscador();
						change_style('mapa_1','menu_map_off');
						change_style('mapa_0','mapa-on');
						change_pest('mapa','1','mapa-on');
						changeImage('menu_mapa_0','idx-busq02d.gif');
						changeImage('menu_mapa_1','idx-busq03.gif');
					}
					layer_base_chile.setVisibility(true);				
				}else{
					
					if(map_2_0.getLayerIndex(layer_satelite_chile) == -1){
						ver_layer('satelite');
					}
					layer_base_chile.setVisibility(true);
					layer_satelite_chile.setOpacity(v);
					
					if(v==1){
						//ver_layer('satelite');
						hideFormBuscador();
						change_style('mapa_1','mapa-on');
						change_style('mapa_0','menu_mapa_off');
						change_pest('mapa','3','mapa-on');
						changeImage('menu_mapa_0','idx-busq03.gif');
						changeImage('menu_mapa_1','idx-busq04d.gif');
					}
				}
			}
		});
	}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++)
  {
  	x.src=x.oSrc;
  }
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}

}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;
  document.MM_sr=new Array;
  for(i=0;i<(a.length-2);i+=3)
  {
  	if ((x=MM_findObj(a[i]))!=null)
	{
		document.MM_sr[j++]=x;
		if(!x.oSrc)
			x.oSrc=x.src;
		x.src=a[i+2];
	}
  }
}

function mOvr(src,clrOver){
 if (!src.contains(event.fromElement)){
  src.style.cursor = 'hand';
  src.className = clrOver;
 }
}
function mOut(src,clrIn){
 if (!src.contains(event.toElement)){
  src.style.cursor = 'hand';
  src.className = clrIn;
 }
}
function mClk(src)
{
	if(event.srcElement.tagName=='TD')
	{
		src.children.tags('A')[0].click();
	}
}

isOPERA = (navigator.userAgent.indexOf('Opera') >= 0)? true : false;
isIE    = (document.all && !isOPERA)? true : false;
isDOM   = (document.getElementById && !isIE && !isOPERA)? true : false;

function MM_showHideLayers() { //v6.0

	//delay(1500);
	var i,p,v,obj,args=MM_showHideLayers.arguments;
	for (i=0; i<(args.length-2); i+=3)
		if ((obj=MM_findObj(args[i]))!=null)
		{
			v=args[i+2];
	    	if (obj.style)
			{
				v=(v=='show')?'visible':(v=='hide')?'hidden':v;
			}
		    obj.style.visibility=v;
		}

}

function MM_showHideIframe( obj, display ) {
	var IfrRef = document.getElementById('DivShim');
	IfrRef.style.width = obj.offsetWidth;
	IfrRef.style.height = obj.offsetHeight;
	IfrRef.style.top = obj.style.top;
	IfrRef.style.left = obj.style.left;
	IfrRef.style.zIndex = obj.style.zIndex - 1;
	//obj.style.visibility='visible';
	obj.style.display = ((display=='block')?'block':'none');
	IfrRef.style.display = ((display=='block')?'block':'none');
}

function change_ico(img,url,objInput) {
	if (isDOM){
		document.getElementById(img).src=url;
	} else if (isIE) {
		document.all[img].src=url;
	}
	objInput.value = url;
}
function loadValue(objInput, value) {
	objInput.value = value;
}

function busquedaCheckin(obj, theForm) {

	if(obj.selectedIndex!=0) {
		theForm.GenRuta.disabled=false;
	} else {
		theForm.GenRuta.checked=false;
		theForm.STransito.checked=false;
		theForm.GenRuta.disabled=true;
		theForm.STransito.disabled=true;
	}
}
function busquedaCheckinRuta(obj, theForm) {
	if(obj.selectedIndex!=0) {
		theForm.GenRuta.disabled=false;
	} else {
		theForm.GenRuta.checked=false;
		theForm.GenRuta.disabled=true;
	}
}
function busquedaCheckinOff(obj, theForm) {
	if(obj.selectedIndex!=0) {
		theForm.STransito.disabled=false;
	} else {
		theForm.STransito.checked=false;
		theForm.STransito.disabled=true;
	}
}

function checkTransito(obj, theForm) {
	if ((theForm.Altura1.value == "") && (theForm.NombreViaInt1.value == ""))
	{

		alert ("Esta opci?n se puede utilizar solo con direcci?n o intersecci?n");
		theForm.GenRuta.checked=false;
		return false;
	}
	if(obj.checked) {
		theForm.STransito.disabled=false;
	} else {
		theForm.STransito.checked=false;
		theForm.STransito.disabled=true;
	}
}

varcerrarmenu = new Array ();
var IMlayer;
function cerrarmenu(layername){
	varcerrarmenu[layername] = true;
	IMlayer = layername;
	setTimeout("cierra()","500");
}
function cierra(){
	if(varcerrarmenu[IMlayer]){
		hideIMLayer(IMlayer,'','hide');
	}
}



function showIMLayer(nameDiv, x) {
	var DivRef = document.getElementById(nameDiv);
	var IfrRef = document.getElementById(nameDiv + '_lay');

	DivRef.style.display = "block";
	IfrRef.style.width = DivRef.offsetWidth;
	IfrRef.style.height = DivRef.offsetHeight;
	IfrRef.style.top = DivRef.style.top;
	IfrRef.style.left = DivRef.style.left;
	IfrRef.style.zIndex = DivRef.style.zIndex - 1;
	IfrRef.style.display = "block";
}

function hideIMLayer(nameDiv, x) {
	var DivRef = document.getElementById(nameDiv);
	var IfrRef = document.getElementById(nameDiv + '_lay');
	IfrRef.style.display = "none";
	DivRef.style.display = "none";
}

function delay(gap){ /* gap is in millisecs */
	var then,now; then=new Date().getTime();
	now=then;
	while((now-then)<gap)
	{
		now=new Date().getTime();
	}
}



var currenty;
var starty;
var endy;
var direction;
var speed=5;

/* funcion changeheight recibe altura final, y 0 para la recursion*/
function changeheight2(end,beg,name){
	e=document.getElementById(name).style;
	var tmp=parseInt(e.height);
	currenty=parseInt(tmp);
	endy=parseInt(end);
	if(beg==0){
		if(parseInt(currenty)==parseInt(endy)) return;
		if(parseInt(endy)>parseInt(currenty)) direction=1;
		else direction=-1;
 	}
 	if(parseInt(currenty)==parseInt(endy)) return;
 	currenty=parseInt(currenty)+parseInt(speed*direction);
 	e.height = parseInt(currenty);
	if(parseInt(currenty)==parseInt(endy)) return;
  	t=setTimeout("changeheight2("+endy+",1,'"+name+"');",0);
}


  var bikky = document.cookie;

  function getFirstTimeCookie(name) { // use: getCookie("name");
    var index = bikky.indexOf(name + "=");
    if (index == -1) return null;
    index = bikky.indexOf("=", index) + 1; // first character
    var endstr = bikky.indexOf(";", index);
    if (endstr == -1) endstr = bikky.length; // last character
    return unescape(bikky.substring(index, endstr));
  }

function AsignaResolucion(formulario)
{
	formulario.screenwidth.value = screen.width;
	formulario.screenheight.value = screen.height;
}

/* Funci?n para enviar por E-Mail un mapa*/
function email()
{
	var ancho,alto,top,feft;
	var argumentos;
	var url;
	var url2;

	ancho = screen.width;
	alto = screen.height;
	left = (ancho / 2) - 165;
	top = (alto / 2) - 118;
	
	bound = map_2_0.getExtent();

	boundsObj=map_2_0.getExtent();	
	x_left = boundsObj.left;
	y_bottom = boundsObj.bottom;
	x_right = boundsObj.right;
	y_top = boundsObj.top;
	SizeObj = map_2_0.getSize();
	w_Imagen = SizeObj.w;
	h_Imagen = SizeObj.h;
	var lonlat_dir=new OpenLayers.LonLat($('lon').value,$('lat').value);
	var lon_dir= lonlat_dir.lon;
	var lat_dir= lonlat_dir.lat;
	pixel_pos=map_2_0.getPixelFromLonLat(lonlat_dir);

	argumentos = CreaListaArgumentos(document.direcc);
	url2="formularioEmail.asp?xmin=" +x_left +"&ymin=" +y_bottom + "&xmax=" +x_right + "&ymax=" + y_top + "&lon_pix="+pixel_pos.x + "&lat_pix="+pixel_pos.y + "&WIDTH=" + w_Imagen + "&HEIGHT=" + h_Imagen + "&lon_dir=" + lon_dir  + "&lat_dir=" + lat_dir;
	re=/ /g;
	url=url2.replace(re,'+');

	//OpenWin((url),"Email","scrollbars=no,menubar=no,width=330,height=235");

	verVentanaPrototype('mail',url);
}

function CreaListaArgumentos(formulario)
{
	var Campo="";
	var Valor="";
	var ListaCampos="";
	for ( var i=0;i<formulario.elements.length;i++)
	{
		Campo="";
		Valor="";
		if ( formulario.elements[i].type == "checkbox" )
		{
			if ( formulario.elements[i].checked )
			{
				Campo=formulario.elements[i].name;
				Valor=formulario.elements[i].value;
			}
		}
		else
		{
			if ( formulario.elements[i].type == "radio" )
			{
				if (formulario.elements[i].checked)
				{
					Campo=formulario.elements[i].name;
					Valor=formulario.elements[i].value;
				}
			}
			else
			{
				Campo=formulario.elements[i].name;
				Valor=formulario.elements[i].value;
			}
		}
		if ( (Campo != "") && (Valor != "") )
		{
			ListaCampos = ListaCampos + Campo + '=' + Valor + '&';
		}
	}
	return ListaCampos;
}

/* Funci?n que abre ventana para agregar foto a una direeci?n*/
function AgregarFoto(Ciudad,sTipoVia1,sNombreVia1,sAltura1,sComuna1,sPunto_X,sPunto_Y,sIdArco)
{
	var ancho,alto,top,feft;
	var url;
	
	map_2_0.removePopup(popup_busqueda);
	
	ancho = screen.width;
	alto = screen.height;
	left = (ancho / 2) - 165;
	top = (alto / 2) - 225;

	url = "subirfoto2.asp?ciudad=" + Ciudad + "&tipovia=" + sTipoVia1 + "&nombrevia=" + sNombreVia1 + "&altura=" + sAltura1 + "&comuna=" + sComuna1 + "&este=" + sPunto_X + "&norte=" + sPunto_Y + "&idarco=" + sIdArco;
	
	verVentanaPrototypeIFrame('subirfoto',url);
}

/* Funci?n para centrar la pantalla del mapa*/
function centrarMapa() {
	if ( (($('ciudad').value=="santiago") || ($('ciudad').value=="vregion")) && ($('CoreTipoCon').value != "ZOOM5001") ) {
		var utm_x = $('Punto_X').value;
		var utm_y = $('Punto_Y').value;
		
		//alert(utm_x + '-' + utm_y);
		
		$('lon').value=utm_x;
		$('lat').value=utm_y;

		var LonLat = new OpenLayers.LonLat(utm_x, utm_y);
		if ( $('CoreTipoCon').value=="COMUNA" ) {
			zoom = 9;
		}
		else  {
			zoom = eval(v_numZoomLevels-2);
		}

		map_2_0.setCenter(LonLat,zoom);
		}
	else {	
	X1 = $('Punto_X').value;
	Y1 = $('Punto_Y').value;
	X2 = $('Punto_X2').value;
	Y2 = $('Punto_Y2').value;

	if (X2 > 0){
		
		if(X1 >= X2){
			XMIN = X2 - 62;
			XMAX = X1 - 62;
		}else{
			XMIN = X1 - 62;
			XMAX = X2 - 62;
		}
		if(Y1 >= Y2){
			YMIN = Y2 - 40;
			YMAX = Y1 - 40;
		}else{
			YMIN = Y1 - 40;
			YMAX = Y2 - 40;
		}
	}else{
		XMIN = X1 -62;
		YMIN = Y1 -40;
	}
		var srid = 29179;
		var opt={
			method:'post',
			onSuccess:function(transport){
				
				resObj=transport.responseText.evalJSON(true);
				XMIN_GEO = resObj.X;
				YMIN_GEO = resObj.Y;
				var LonLat_MIN= new OpenLayers.LonLat(XMIN_GEO,YMIN_GEO);
				if(X2 > 0){
					var opt_x2 = {
						method:'post',
						onSuccess:function(transport_x2){
							
							resObj_x2=transport_x2.responseText.evalJSON(true);
							XMAX_GEO = resObj_x2.X;
							YMAX_GEO = resObj_x2.Y;
							var LonLat_MAX= new OpenLayers.LonLat(XMAX_GEO,YMAX_GEO);
							var bound = new OpenLayers.Bounds(XMIN_GEO,YMIN_GEO,XMAX_GEO,YMAX_GEO);
							
							map_2_0.zoomToExtent(bound);
						},
						onFailure:function(){
							alert('Lo sentimos, el mapa no pudo ser centrado');
						}
					};
					new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+XMAX+' '+YMAX+')',opt_x2);
				}else{
					map_2_0.panTo(LonLat_MIN);
				}
			},
			onFailure:function(){
				alert('Lo sentimos, su consulta (centrar) no pudo ser procesada');
			}
		};
		

		new Ajax.Request('FuncionesGIS.asp?codEntrada='+srid+'&codSalida=4326&geometry=POINT('+XMIN+' '+YMIN+')',opt);
	}
}

function activasitioNuevo(formulario)
{
	var arg = CreaListaArgumentos(formulario);
	window.location.href = "Buscador.asp?" + arg + "screenwidth=" + sScreenWidth + "&screenheight=" + sScreenHeight;
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

var peticion = false;
 try {
  peticion = new XMLHttpRequest();
  } catch (trymicrosoft) {
  try {
		peticion = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
  try {
		peticion = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (failed) {
		peticion = false;
}
}
}

if (!peticion)
  alert("ERROR AL INICIALIZAR!");

function cargarFragmento(fragment_url, element_id)
{
	var element = document.getElementById(element_id);
	peticion.open("GET", fragment_url);
	peticion.onreadystatechange = function() {
	if (peticion.readyState == 4) {
		element.innerHTML = peticion.responseText;
	}
	}
	peticion.send(null);
}

var sAncho_Pix 	= 100;
var sAlto_Pix = 100;
var sFactorFotoMapa	= 100;
var sAnchoFotoMapa 	= 310;
var sPX2CM	= 1;

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


function OpenWin(url,name,param)
{
	window.open(url,name,param);
}
ventana = null;
function OpenWin2(url,name,param)
{
	ventana = window.open(url,name,param);
}
function CloseWin()
{
	if ( ventana && !ventana.closed)
	{
		ventana.close();
	}
}
var scriptElem;
function cargarEntorno(url)
{
	scriptElem = document.createElement('hr');
	document.getElementById("miDIV").appendChild(scriptElem);
}

function getFuncBody(funcPtr) {
        var str=funcPtr.toString();
		var rg=new RegExp("[^{]+{","gi");
        str=str.replace(rg,"");
        str=str.substring(0,str.length-1);
        return str;
}

function notIE(){
	return (typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement);
}


var nIE=notIE();

function cEntorno(url)
{
	prevFunc = "";
	if(document.body.onload)prevFunc = getFuncBody(document.body.onload);
	document.body.onload = new Function(prevFunc+ ";cargarEntorno('"+url+"');");
}

function change_heightDesc()
{
    if(document.getElementById && !(document.all)) {
      	height = document.getElementById('DescEntorno').contentDocument.body.scrollHeight;
       document.getElementById('DescEntorno').style.height = height;
    }
    else if(document.all) {
        height = document.frames('DescEntorno').document.body.scrollHeight;
        document.all.myiframe.style.height = height;
    }
}

function ocultarMostrarEntorno(id)
{
	if(ver_mas==0){
		hideTr(id);
		ver_mas=1;
		getObj('bot_vermas').src='images/vmas1.gif';
	}
	else{
		showTr(id)
		ver_mas=0;
	}
}

function onMouseOutImagenEntorno(id){
	if(ver_mas==0)
		document.getElementById(id).src='images/vmas3.gif';
	else
		document.getElementById(id).src='images/vmas1.gif';
}

function onMouseOverImagenEntorno(id){
	if(ver_mas==0)
		document.getElementById(id).src='images/vmas4.gif';
	else
		document.getElementById(id).src='images/vmas2.gif';
}

function ocultarMostrarFormBusqueda()
{
	if(ver_mas_form==0){
		ver_mas_form=1;
		getObj('bot_vermas_form').src=iconoBuscador_onOut.src;
		if(win_celular){
			win_celular.getContent().update("");
			win_celular.close();
			win_celular = null;
		}
	} else{
		getObj('bot_vermas_form').src=iconoBuscador_offOut.src;
		ver_mas_form=0;
	}

}

function onMouseOutImagenFormBusqueda(id){
	if(ver_mas_form==0)
		document.getElementById(id).src=iconoBuscador_offOut.src;
	else
		document.getElementById(id).src=iconoBuscador_onOut.src;
}

function onMouseOverImagenFormBusqueda(id){
	if(ver_mas_form==0)
		document.getElementById(id).src=iconoBuscador_offOver.src;
	else
		document.getElementById(id).src=iconoBuscador_onOver.src;
}

//INI-mapa-celular

function eventEndFlashMapaCelular(){
	getObj('flashMapaCelular').style.display="none";
	getObj('flashMapaCelular').InnerHTML = "";
}

function ocultarMostrarFormCelular()
{
	if(!win_celular){
		win_celular = new Window({
		id:"form_celular",
		className: "alphacube", 
		resizable:false,
		minimizable:false,
		maximizable:false,
		draggable:false,
		closable:true,
		width:450,
		height:450,
		parent:$('map_2_0'),
		destroyOnClose:true,
		opacity:0.9
		//recenterAuto:false,
		//showEffect:Effect.Appear,
		//hideEffect:Effect.Fade
		});
		win_celular.showCenter(true);
		win_celular.setURL('mapacelular/ventana.html');
		hideFormBuscador();
		//ocultarMostrarFormBusqueda();
	}else{
		win_celular.getContent().update("");
		win_celular.close();
		win_celular = null;
	}

/*	if(ver_mas_form_celular==0){
		ver_mas_form_celular=1;
		getObj('bot_vermas_form_celular').src=iconoCelular_off.src;
	} else{
		getObj('bot_vermas_form_celular').src=iconoCelular_on.src;
		ver_mas_form_celular=0;
	}*/
}

function onMouseOutImagenFormCelular(id){
	if(ver_mas_form_celular==0)
		getObj(id).src=iconoCelular_off.src;
	else
		getObj(id).src=iconoCelular_on.src;
}

function onMouseOverImagenFormCelular(id){
	if(ver_mas_form_celular==0)
		getObj(id).src=iconoCelular_on.src;
	else
		getObj(id).src=iconoCelular_off.src;
}
//END-mapa-celular


function cargaslider(){return false;}

function eventOnLoadMapa()
{
	document.getElementById('carga_mapa').value='1';
	if(document.getElementById('clickslider').value=='1')
	{
		for (i=0;!cargaslider() && i<3;i++)
			pauseScript(3000);
	}
	document.getElementById('loadtabla').style.display='none';

	if(!nIE && document.direcc.dum && document.direcc.dum2.value!='amp')
	{
		document.direcc.dum.focus();
		document.direcc.dum2.value='';
		document.direcc.dum2.focus();
	}else{
		if(document.direcc.dum2)
		document.direcc.dum2.value='';
	}


}

function eventOnloadFotoAerea()
{
	document.getElementById('capaaerea').style.display='block';
	document.getElementById('satload').style.display='none';
	document.getElementById('loadtabla').style.display='none';
	document.getElementById('control_opcidad').value='1';
}

var ver_mas=0;
var ver_mas_form=0;
var ver_mas_form_celular=0;

//precarga de imagenes
if (document.images) {
//INI-mapa-celular
	var iconoCelular_off = new Image();
  iconoCelular_off.src = "mapacelular/images/enviar_celular.gif";
  var iconoCelular_on = new Image();
  iconoCelular_on.src = "mapacelular/images/enviar_celular_ON.gif";
//END-mapa-celular

	var iconoBuscador_offOut = new Image();
  iconoBuscador_offOut.src = "images/botones/nueva_busqueda.gif";
	var iconoBuscador_offOver = new Image();
  iconoBuscador_offOver.src = "images/botones/nueva_busqueda_ON.gif";

  var iconoBuscador_onOut = new Image();
  iconoBuscador_onOut.src = "images/botones/nueva_busqueda.gif";
  var iconoBuscador_onOver = new Image();
  iconoBuscador_onOver.src = "images/botones/nueva_busqueda_ON.gif";

}


function hideFormBuscador()
{
	if ( document.getElementById('id_buscador') )
	{
		document.getElementById('id_buscador').style.display='none';
		//document.getElementById('id_celular').style.display='none';
		ver_mas_form=0;
		getObj('bot_vermas_form').src=iconoBuscador_offOut.src;
		//INI-mapa-celular
		//ver_mas_form_celular=0;
		//getObj('bot_vermas_form_celular').src=iconoCelular_off.src;
		//END-mapa-celular
	}
}

function SetLayerVisibility(strButtonPressed)
{
	var blnCelular, blnBuscador
	//blnCelular = (document.getElementById('id_celular').style.display != 'none');
	blnBuscador = (document.getElementById('window_form_buscador').style.display != 'none');
	/*if (strButtonPressed == 'id_celular')
	{
		ver_mas_form=1;
		ocultarMostrarFormBusqueda();
		if (AjaxObjGetCodigo.codigoEstaCargado==false){
			AjaxObjGetCodigo.init('direcc');
			AjaxObjGetCodigo.startRequest();
		}
		if ((blnCelular == false && blnBuscador == false) || (blnCelular == true && blnBuscador == false))
		{
			dspLayerForm('id_celular');
		}
		if (blnCelular == false && blnBuscador == true)
		{
			dspLayerForm('id_buscador');
			//dspLayerForm('id_celular');
		}
	}*/

	/*if (strButtonPressed == 'id_buscador')
	{
		dspLayerForm('id_buscador');
	}*/
}

function dspLayerForm(strLayerName)
{
	if (document.getElementById(strLayerName).style.display == 'block' )
	{
		document.getElementById(strLayerName).style.display='none';
	}
	else
	{
		document.getElementById(strLayerName).style.display='block';
	}
}

function ocultarMostrarEntorno()
{
	if (document.getElementById('td_entorno').style.visibility == 'hidden')
	{
		showTr('idEntornoMain');
		document.getElementById('td_entorno').style.visibility='visible';
		getObj('idImgEntorno').src = "./images/entorno/entorno.gif";
	}else{
		document.getElementById('td_entorno').style.visibility='hidden';
		hideTr('idEntornoMain');
		getObj('idImgEntorno').src = "./images/entorno/entornoSel.gif";
	}

}

function onMouseOverEntorno(){

	if (document.getElementById('td_entorno').style.visibility == 'hidden')
	{
		getObj('idImgEntorno').src = "./images/entorno/entornoSel_ON.gif";
	}else{
		getObj('idImgEntorno').src = "./images/entorno/entorno_ON.gif";
	}

}

function onMouseOutEntorno(){
	
	if (document.getElementById('td_entorno').style.visibility == 'hidden')
	{
		getObj('idImgEntorno').src = "./images/entorno/entornoSel.gif";
	}else{
		getObj('idImgEntorno').src = "./images/entorno/entorno.gif";
	}

}
/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.2.2
*/

if(typeof YAHOO=="undefined"){var YAHOO={};}
YAHOO.namespace=function(){var a=arguments,o=null,i,j,d;for(i=0;i<a.length;i=i+1){d=a[i].split(".");o=YAHOO;for(j=(d[0]=="YAHOO")?1:0;j<d.length;j=j+1){o[d[j]]=o[d[j]]||{};o=o[d[j]];}}
return o;};YAHOO.log=function(msg,cat,src){var l=YAHOO.widget.Logger;if(l&&l.log){return l.log(msg,cat,src);}else{return false;}};YAHOO.init=function(){this.namespace("util","widget","example");if(typeof YAHOO_config!="undefined"){var l=YAHOO_config.listener,ls=YAHOO.env.listeners,unique=true,i;if(l){for(i=0;i<ls.length;i=i+1){if(ls[i]==l){unique=false;break;}}
if(unique){ls.push(l);}}}};YAHOO.register=function(name,mainClass,data){var mods=YAHOO.env.modules;if(!mods[name]){mods[name]={versions:[],builds:[]};}
var m=mods[name],v=data.version,b=data.build,ls=YAHOO.env.listeners;m.name=name;m.version=v;m.build=b;m.versions.push(v);m.builds.push(b);m.mainClass=mainClass;for(var i=0;i<ls.length;i=i+1){ls[i](m);}
if(mainClass){mainClass.VERSION=v;mainClass.BUILD=b;}else{YAHOO.log("mainClass is undefined for module "+name,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[],getVersion:function(name){return YAHOO.env.modules[name]||null;}};YAHOO.lang={isArray:function(obj){if(obj&&obj.constructor&&obj.constructor.toString().indexOf('Array')>-1){return true;}else{return YAHOO.lang.isObject(obj)&&obj.constructor==Array;}},isBoolean:function(obj){return typeof obj=='boolean';},isFunction:function(obj){return typeof obj=='function';},isNull:function(obj){return obj===null;},isNumber:function(obj){return typeof obj=='number'&&isFinite(obj);},isObject:function(obj){return obj&&(typeof obj=='object'||YAHOO.lang.isFunction(obj));},isString:function(obj){return typeof obj=='string';},isUndefined:function(obj){return typeof obj=='undefined';},hasOwnProperty:function(obj,prop){if(Object.prototype.hasOwnProperty){return obj.hasOwnProperty(prop);}
return!YAHOO.lang.isUndefined(obj[prop])&&obj.constructor.prototype[prop]!==obj[prop];},extend:function(subc,superc,overrides){if(!superc||!subc){throw new Error("YAHOO.lang.extend failed, please check that "+"all dependencies are included.");}
var F=function(){};F.prototype=superc.prototype;subc.prototype=new F();subc.prototype.constructor=subc;subc.superclass=superc.prototype;if(superc.prototype.constructor==Object.prototype.constructor){superc.prototype.constructor=superc;}
if(overrides){for(var i in overrides){subc.prototype[i]=overrides[i];}}},augment:function(r,s){if(!s||!r){throw new Error("YAHOO.lang.augment failed, please check that "+"all dependencies are included.");}
var rp=r.prototype,sp=s.prototype,a=arguments,i,p;if(a[2]){for(i=2;i<a.length;i=i+1){rp[a[i]]=sp[a[i]];}}else{for(p in sp){if(!rp[p]){rp[p]=sp[p];}}}}};YAHOO.init();YAHOO.util.Lang=YAHOO.lang;YAHOO.augment=YAHOO.lang.augment;YAHOO.extend=YAHOO.lang.extend;YAHOO.register("yahoo",YAHOO,{version:"2.2.2",build:"204"});/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.2.2
*/

YAHOO.util.CustomEvent=function(type,oScope,silent,signature){this.type=type;this.scope=oScope||window;this.silent=silent;this.signature=signature||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}
var onsubscribeType="_YUICEOnSubscribe";if(type!==onsubscribeType){this.subscribeEvent=new YAHOO.util.CustomEvent(onsubscribeType,this,true);}};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(fn,obj,override){if(!fn){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}
if(this.subscribeEvent){this.subscribeEvent.fire(fn,obj,override);}
this.subscribers.push(new YAHOO.util.Subscriber(fn,obj,override));},unsubscribe:function(fn,obj){if(!fn){return this.unsubscribeAll();}
var found=false;for(var i=0,len=this.subscribers.length;i<len;++i){var s=this.subscribers[i];if(s&&s.contains(fn,obj)){this._delete(i);found=true;}}
return found;},fire:function(){var len=this.subscribers.length;if(!len&&this.silent){return true;}
var args=[],ret=true,i;for(i=0;i<arguments.length;++i){args.push(arguments[i]);}
var argslength=args.length;if(!this.silent){}
for(i=0;i<len;++i){var s=this.subscribers[i];if(s){if(!this.silent){}
var scope=s.getScope(this.scope);if(this.signature==YAHOO.util.CustomEvent.FLAT){var param=null;if(args.length>0){param=args[0];}
ret=s.fn.call(scope,param,s.obj);}else{ret=s.fn.call(scope,this.type,args,s.obj);}
if(false===ret){if(!this.silent){}
return false;}}}
return true;},unsubscribeAll:function(){for(var i=0,len=this.subscribers.length;i<len;++i){this._delete(len-1-i);}
return i;},_delete:function(index){var s=this.subscribers[index];if(s){delete s.fn;delete s.obj;}
this.subscribers.splice(index,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"scope: "+this.scope;}};YAHOO.util.Subscriber=function(fn,obj,override){this.fn=fn;this.obj=obj||null;this.override=override;};YAHOO.util.Subscriber.prototype.getScope=function(defaultScope){if(this.override){if(this.override===true){return this.obj;}else{return this.override;}}
return defaultScope;};YAHOO.util.Subscriber.prototype.contains=function(fn,obj){if(obj){return(this.fn==fn&&this.obj==obj);}else{return(this.fn==fn);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+(this.obj||"")+", override: "+(this.override||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var loadComplete=false;var DOMReady=false;var listeners=[];var unloadListeners=[];var legacyEvents=[];var legacyHandlers=[];var retryCount=0;var onAvailStack=[];var legacyMap=[];var counter=0;var lastError=null;return{POLL_RETRYS:200,POLL_INTERVAL:10,EL:0,TYPE:1,FN:2,WFN:3,OBJ:3,ADJ_SCOPE:4,isSafari:(/KHTML/gi).test(navigator.userAgent),webkit:function(){var v=navigator.userAgent.match(/AppleWebKit\/([^ ]*)/);if(v&&v[1]){return v[1];}
return null;}(),isIE:(!this.webkit&&!navigator.userAgent.match(/opera/gi)&&navigator.userAgent.match(/msie/gi)),_interval:null,startInterval:function(){if(!this._interval){var self=this;var callback=function(){self._tryPreloadAttach();};this._interval=setInterval(callback,this.POLL_INTERVAL);}},onAvailable:function(p_id,p_fn,p_obj,p_override){onAvailStack.push({id:p_id,fn:p_fn,obj:p_obj,override:p_override,checkReady:false});retryCount=this.POLL_RETRYS;this.startInterval();},onDOMReady:function(p_fn,p_obj,p_override){this.DOMReadyEvent.subscribe(p_fn,p_obj,p_override);},onContentReady:function(p_id,p_fn,p_obj,p_override){onAvailStack.push({id:p_id,fn:p_fn,obj:p_obj,override:p_override,checkReady:true});retryCount=this.POLL_RETRYS;this.startInterval();},addListener:function(el,sType,fn,obj,override){if(!fn||!fn.call){return false;}
if(this._isValidCollection(el)){var ok=true;for(var i=0,len=el.length;i<len;++i){ok=this.on(el[i],sType,fn,obj,override)&&ok;}
return ok;}else if(typeof el=="string"){var oEl=this.getEl(el);if(oEl){el=oEl;}else{this.onAvailable(el,function(){YAHOO.util.Event.on(el,sType,fn,obj,override);});return true;}}
if(!el){return false;}
if("unload"==sType&&obj!==this){unloadListeners[unloadListeners.length]=[el,sType,fn,obj,override];return true;}
var scope=el;if(override){if(override===true){scope=obj;}else{scope=override;}}
var wrappedFn=function(e){return fn.call(scope,YAHOO.util.Event.getEvent(e),obj);};var li=[el,sType,fn,wrappedFn,scope];var index=listeners.length;listeners[index]=li;if(this.useLegacyEvent(el,sType)){var legacyIndex=this.getLegacyIndex(el,sType);if(legacyIndex==-1||el!=legacyEvents[legacyIndex][0]){legacyIndex=legacyEvents.length;legacyMap[el.id+sType]=legacyIndex;legacyEvents[legacyIndex]=[el,sType,el["on"+sType]];legacyHandlers[legacyIndex]=[];el["on"+sType]=function(e){YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(e),legacyIndex);};}
legacyHandlers[legacyIndex].push(li);}else{try{this._simpleAdd(el,sType,wrappedFn,false);}catch(ex){this.lastError=ex;this.removeListener(el,sType,fn);return false;}}
return true;},fireLegacyEvent:function(e,legacyIndex){var ok=true,le,lh,li,scope,ret;lh=legacyHandlers[legacyIndex];for(var i=0,len=lh.length;i<len;++i){li=lh[i];if(li&&li[this.WFN]){scope=li[this.ADJ_SCOPE];ret=li[this.WFN].call(scope,e);ok=(ok&&ret);}}
le=legacyEvents[legacyIndex];if(le&&le[2]){le[2](e);}
return ok;},getLegacyIndex:function(el,sType){var key=this.generateId(el)+sType;if(typeof legacyMap[key]=="undefined"){return-1;}else{return legacyMap[key];}},useLegacyEvent:function(el,sType){if(this.webkit&&("click"==sType||"dblclick"==sType)){var v=parseInt(this.webkit,10);if(!isNaN(v)&&v<418){return true;}}
return false;},removeListener:function(el,sType,fn){var i,len;if(typeof el=="string"){el=this.getEl(el);}else if(this._isValidCollection(el)){var ok=true;for(i=0,len=el.length;i<len;++i){ok=(this.removeListener(el[i],sType,fn)&&ok);}
return ok;}
if(!fn||!fn.call){return this.purgeElement(el,false,sType);}
if("unload"==sType){for(i=0,len=unloadListeners.length;i<len;i++){var li=unloadListeners[i];if(li&&li[0]==el&&li[1]==sType&&li[2]==fn){unloadListeners.splice(i,1);return true;}}
return false;}
var cacheItem=null;var index=arguments[3];if("undefined"==typeof index){index=this._getCacheIndex(el,sType,fn);}
if(index>=0){cacheItem=listeners[index];}
if(!el||!cacheItem){return false;}
if(this.useLegacyEvent(el,sType)){var legacyIndex=this.getLegacyIndex(el,sType);var llist=legacyHandlers[legacyIndex];if(llist){for(i=0,len=llist.length;i<len;++i){li=llist[i];if(li&&li[this.EL]==el&&li[this.TYPE]==sType&&li[this.FN]==fn){llist.splice(i,1);break;}}}}else{try{this._simpleRemove(el,sType,cacheItem[this.WFN],false);}catch(ex){this.lastError=ex;return false;}}
delete listeners[index][this.WFN];delete listeners[index][this.FN];listeners.splice(index,1);return true;},getTarget:function(ev,resolveTextNode){var t=ev.target||ev.srcElement;return this.resolveTextNode(t);},resolveTextNode:function(node){if(node&&3==node.nodeType){return node.parentNode;}else{return node;}},getPageX:function(ev){var x=ev.pageX;if(!x&&0!==x){x=ev.clientX||0;if(this.isIE){x+=this._getScrollLeft();}}
return x;},getPageY:function(ev){var y=ev.pageY;if(!y&&0!==y){y=ev.clientY||0;if(this.isIE){y+=this._getScrollTop();}}
return y;},getXY:function(ev){return[this.getPageX(ev),this.getPageY(ev)];},getRelatedTarget:function(ev){var t=ev.relatedTarget;if(!t){if(ev.type=="mouseout"){t=ev.toElement;}else if(ev.type=="mouseover"){t=ev.fromElement;}}
return this.resolveTextNode(t);},getTime:function(ev){if(!ev.time){var t=new Date().getTime();try{ev.time=t;}catch(ex){this.lastError=ex;return t;}}
return ev.time;},stopEvent:function(ev){this.stopPropagation(ev);this.preventDefault(ev);},stopPropagation:function(ev){if(ev.stopPropagation){ev.stopPropagation();}else{ev.cancelBubble=true;}},preventDefault:function(ev){if(ev.preventDefault){ev.preventDefault();}else{ev.returnValue=false;}},getEvent:function(e){var ev=e||window.event;if(!ev){var c=this.getEvent.caller;while(c){ev=c.arguments[0];if(ev&&Event==ev.constructor){break;}
c=c.caller;}}
return ev;},getCharCode:function(ev){return ev.charCode||ev.keyCode||0;},_getCacheIndex:function(el,sType,fn){for(var i=0,len=listeners.length;i<len;++i){var li=listeners[i];if(li&&li[this.FN]==fn&&li[this.EL]==el&&li[this.TYPE]==sType){return i;}}
return-1;},generateId:function(el){var id=el.id;if(!id){id="yuievtautoid-"+counter;++counter;el.id=id;}
return id;},_isValidCollection:function(o){return(o&&o.length&&typeof o!="string"&&!o.tagName&&!o.alert&&typeof o[0]!="undefined");},elCache:{},getEl:function(id){return document.getElementById(id);},clearCache:function(){},DOMReadyEvent:new YAHOO.util.CustomEvent("DOMReady",this),_load:function(e){if(!loadComplete){loadComplete=true;var EU=YAHOO.util.Event;EU._ready();if(this.isIE){EU._simpleRemove(window,"load",EU._load);}}},_ready:function(e){if(!DOMReady){DOMReady=true;var EU=YAHOO.util.Event;EU.DOMReadyEvent.fire();EU._simpleRemove(document,"DOMContentLoaded",EU._ready);}},_tryPreloadAttach:function(){if(this.locked){return false;}
if(this.isIE&&!DOMReady){return false;}
this.locked=true;var tryAgain=!loadComplete;if(!tryAgain){tryAgain=(retryCount>0);}
var notAvail=[];var executeItem=function(el,item){var scope=el;if(item.override){if(item.override===true){scope=item.obj;}else{scope=item.override;}}
item.fn.call(scope,item.obj);};var i,len,item,el;for(i=0,len=onAvailStack.length;i<len;++i){item=onAvailStack[i];if(item&&!item.checkReady){el=this.getEl(item.id);if(el){executeItem(el,item);onAvailStack[i]=null;}else{notAvail.push(item);}}}
for(i=0,len=onAvailStack.length;i<len;++i){item=onAvailStack[i];if(item&&item.checkReady){el=this.getEl(item.id);if(el){if(loadComplete||el.nextSibling){executeItem(el,item);onAvailStack[i]=null;}}else{notAvail.push(item);}}}
retryCount=(notAvail.length===0)?0:retryCount-1;if(tryAgain){this.startInterval();}else{clearInterval(this._interval);this._interval=null;}
this.locked=false;return true;},purgeElement:function(el,recurse,sType){var elListeners=this.getListeners(el,sType);if(elListeners){for(var i=0,len=elListeners.length;i<len;++i){var l=elListeners[i];this.removeListener(el,l.type,l.fn);}}
if(recurse&&el&&el.childNodes){for(i=0,len=el.childNodes.length;i<len;++i){this.purgeElement(el.childNodes[i],recurse,sType);}}},getListeners:function(el,sType){var results=[],searchLists;if(!sType){searchLists=[listeners,unloadListeners];}else if(sType=="unload"){searchLists=[unloadListeners];}else{searchLists=[listeners];}
for(var j=0;j<searchLists.length;++j){var searchList=searchLists[j];if(searchList&&searchList.length>0){for(var i=0,len=searchList.length;i<len;++i){var l=searchList[i];if(l&&l[this.EL]===el&&(!sType||sType===l[this.TYPE])){results.push({type:l[this.TYPE],fn:l[this.FN],obj:l[this.OBJ],adjust:l[this.ADJ_SCOPE],index:i});}}}}
return(results.length)?results:null;},_unload:function(e){var EU=YAHOO.util.Event,i,j,l,len,index;for(i=0,len=unloadListeners.length;i<len;++i){l=unloadListeners[i];if(l){var scope=window;if(l[EU.ADJ_SCOPE]){if(l[EU.ADJ_SCOPE]===true){scope=l[EU.OBJ];}else{scope=l[EU.ADJ_SCOPE];}}
l[EU.FN].call(scope,EU.getEvent(e),l[EU.OBJ]);unloadListeners[i]=null;l=null;scope=null;}}
unloadListeners=null;if(listeners&&listeners.length>0){j=listeners.length;while(j){index=j-1;l=listeners[index];if(l){EU.removeListener(l[EU.EL],l[EU.TYPE],l[EU.FN],index);}
j=j-1;}
l=null;EU.clearCache();}
for(i=0,len=legacyEvents.length;i<len;++i){legacyEvents[i][0]=null;legacyEvents[i]=null;}
legacyEvents=null;EU._simpleRemove(window,"unload",EU._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var dd=document.documentElement,db=document.body;if(dd&&(dd.scrollTop||dd.scrollLeft)){return[dd.scrollTop,dd.scrollLeft];}else if(db){return[db.scrollTop,db.scrollLeft];}else{return[0,0];}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(el,sType,fn,capture){el.addEventListener(sType,fn,(capture));};}else if(window.attachEvent){return function(el,sType,fn,capture){el.attachEvent("on"+sType,fn);};}else{return function(){};}}(),_simpleRemove:function(){if(window.removeEventListener){return function(el,sType,fn,capture){el.removeEventListener(sType,fn,(capture));};}else if(window.detachEvent){return function(el,sType,fn){el.detachEvent("on"+sType,fn);};}else{return function(){};}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;if(EU.isIE){document.write('<scr'+'ipt id="_yui_eu_dr" defer="true" src="//:"></script>');var el=document.getElementById("_yui_eu_dr");el.onreadystatechange=function(){if("complete"==this.readyState){this.parentNode.removeChild(this);YAHOO.util.Event._ready();}};el=null;YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);}else if(EU.webkit){EU._drwatch=setInterval(function(){var rs=document.readyState;if("loaded"==rs||"complete"==rs){clearInterval(EU._drwatch);EU._drwatch=null;EU._ready();}},EU.POLL_INTERVAL);}else{EU._simpleAdd(document,"DOMContentLoaded",EU._ready);}
EU._simpleAdd(window,"load",EU._load);EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}
YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(p_type,p_fn,p_obj,p_override){this.__yui_events=this.__yui_events||{};var ce=this.__yui_events[p_type];if(ce){ce.subscribe(p_fn,p_obj,p_override);}else{this.__yui_subscribers=this.__yui_subscribers||{};var subs=this.__yui_subscribers;if(!subs[p_type]){subs[p_type]=[];}
subs[p_type].push({fn:p_fn,obj:p_obj,override:p_override});}},unsubscribe:function(p_type,p_fn,p_obj){this.__yui_events=this.__yui_events||{};var ce=this.__yui_events[p_type];if(ce){return ce.unsubscribe(p_fn,p_obj);}else{return false;}},unsubscribeAll:function(p_type){return this.unsubscribe(p_type);},createEvent:function(p_type,p_config){this.__yui_events=this.__yui_events||{};var opts=p_config||{};var events=this.__yui_events;if(events[p_type]){}else{var scope=opts.scope||this;var silent=opts.silent||null;var ce=new YAHOO.util.CustomEvent(p_type,scope,silent,YAHOO.util.CustomEvent.FLAT);events[p_type]=ce;if(opts.onSubscribeCallback){ce.subscribeEvent.subscribe(opts.onSubscribeCallback);}
this.__yui_subscribers=this.__yui_subscribers||{};var qs=this.__yui_subscribers[p_type];if(qs){for(var i=0;i<qs.length;++i){ce.subscribe(qs[i].fn,qs[i].obj,qs[i].override);}}}
return events[p_type];},fireEvent:function(p_type,arg1,arg2,etc){this.__yui_events=this.__yui_events||{};var ce=this.__yui_events[p_type];if(ce){var args=[];for(var i=1;i<arguments.length;++i){args.push(arguments[i]);}
return ce.fire.apply(ce,args);}else{return null;}},hasEvent:function(type){if(this.__yui_events){if(this.__yui_events[type]){return true;}}
return false;}};YAHOO.util.KeyListener=function(attachTo,keyData,handler,event){if(!attachTo){}else if(!keyData){}else if(!handler){}
if(!event){event=YAHOO.util.KeyListener.KEYDOWN;}
var keyEvent=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(typeof attachTo=='string'){attachTo=document.getElementById(attachTo);}
if(typeof handler=='function'){keyEvent.subscribe(handler);}else{keyEvent.subscribe(handler.fn,handler.scope,handler.correctScope);}
function handleKeyPress(e,obj){if(!keyData.shift){keyData.shift=false;}
if(!keyData.alt){keyData.alt=false;}
if(!keyData.ctrl){keyData.ctrl=false;}
if(e.shiftKey==keyData.shift&&e.altKey==keyData.alt&&e.ctrlKey==keyData.ctrl){var dataItem;var keyPressed;if(keyData.keys instanceof Array){for(var i=0;i<keyData.keys.length;i++){dataItem=keyData.keys[i];if(dataItem==e.charCode){keyEvent.fire(e.charCode,e);break;}else if(dataItem==e.keyCode){keyEvent.fire(e.keyCode,e);break;}}}else{dataItem=keyData.keys;if(dataItem==e.charCode){keyEvent.fire(e.charCode,e);}else if(dataItem==e.keyCode){keyEvent.fire(e.keyCode,e);}}}}
this.enable=function(){if(!this.enabled){YAHOO.util.Event.addListener(attachTo,event,handleKeyPress);this.enabledEvent.fire(keyData);}
this.enabled=true;};this.disable=function(){if(this.enabled){YAHOO.util.Event.removeListener(attachTo,event,handleKeyPress);this.disabledEvent.fire(keyData);}
this.enabled=false;};this.toString=function(){return"KeyListener ["+keyData.keys+"] "+attachTo.tagName+
(attachTo.id?"["+attachTo.id+"]":"");};};YAHOO.util.KeyListener.KEYDOWN="keydown";YAHOO.util.KeyListener.KEYUP="keyup";YAHOO.register("event",YAHOO.util.Event,{version:"2.2.2",build:"204"});/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.2.2
*/

YAHOO.util.Connect={_msxml_progid:['MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'],_http_headers:{},_has_http_headers:false,_use_default_post_header:true,_default_post_header:'application/x-www-form-urlencoded; charset=UTF-8',_use_default_xhr_header:true,_default_xhr_header:'XMLHttpRequest',_has_default_headers:true,_default_headers:{},_isFormSubmit:false,_isFileUpload:false,_formNode:null,_sFormData:null,_poll:{},_timeOut:{},_polling_interval:50,_transaction_id:0,_submitElementValue:null,_hasSubmitListener:(function()
{if(YAHOO.util.Event){YAHOO.util.Event.addListener(document,'click',function(e){var obj=YAHOO.util.Event.getTarget(e);if(obj.type=='submit'){YAHOO.util.Connect._submitElementValue=encodeURIComponent(obj.name)+"="+encodeURIComponent(obj.value);}})
return true;}
return false;})(),setProgId:function(id)
{this._msxml_progid.unshift(id);},setDefaultPostHeader:function(b)
{this._use_default_post_header=b;},setDefaultXhrHeader:function(b)
{this._use_default_xhr_header=b;},setPollingInterval:function(i)
{if(typeof i=='number'&&isFinite(i)){this._polling_interval=i;}},createXhrObject:function(transactionId)
{var obj,http;try
{http=new XMLHttpRequest();obj={conn:http,tId:transactionId};}
catch(e)
{for(var i=0;i<this._msxml_progid.length;++i){try
{http=new ActiveXObject(this._msxml_progid[i]);obj={conn:http,tId:transactionId};break;}
catch(e){}}}
finally
{return obj;}},getConnectionObject:function()
{var o;var tId=this._transaction_id;try
{o=this.createXhrObject(tId);if(o){this._transaction_id++;}}
catch(e){}
finally
{return o;}},asyncRequest:function(method,uri,callback,postData)
{var o=this.getConnectionObject();if(!o){return null;}
else{if(this._isFormSubmit){if(this._isFileUpload){this.uploadFile(o.tId,callback,uri,postData);this.releaseObject(o);return;}
if(method.toUpperCase()=='GET'){if(this._sFormData.length!=0){uri+=((uri.indexOf('?')==-1)?'?':'&')+this._sFormData;}
else{uri+="?"+this._sFormData;}}
else if(method.toUpperCase()=='POST'){postData=postData?this._sFormData+"&"+postData:this._sFormData;}}
o.conn.open(method,uri,true);if(this._use_default_xhr_header){if(!this._default_headers['X-Requested-With']){this.initHeader('X-Requested-With',this._default_xhr_header,true);}}
if(this._isFormSubmit||(postData&&this._use_default_post_header)){this.initHeader('Content-Type',this._default_post_header);if(this._isFormSubmit){this.resetFormState();}}
if(this._has_default_headers||this._has_http_headers){this.setHeader(o);}
this.handleReadyState(o,callback);o.conn.send(postData||null);return o;}},handleReadyState:function(o,callback)
{var oConn=this;if(callback&&callback.timeout){this._timeOut[o.tId]=window.setTimeout(function(){oConn.abort(o,callback,true);},callback.timeout);}
this._poll[o.tId]=window.setInterval(function(){if(o.conn&&o.conn.readyState===4){window.clearInterval(oConn._poll[o.tId]);delete oConn._poll[o.tId];if(callback&&callback.timeout){delete oConn._timeOut[o.tId];}
oConn.handleTransactionResponse(o,callback);}},this._polling_interval);},handleTransactionResponse:function(o,callback,isAbort)
{if(!callback){this.releaseObject(o);return;}
var httpStatus,responseObject;try
{if(o.conn.status!==undefined&&o.conn.status!==0){httpStatus=o.conn.status;}
else{httpStatus=13030;}}
catch(e){httpStatus=13030;}
if(httpStatus>=200&&httpStatus<300||httpStatus===1223){responseObject=this.createResponseObject(o,callback.argument);if(callback.success){if(!callback.scope){callback.success(responseObject);}
else{callback.success.apply(callback.scope,[responseObject]);}}}
else{switch(httpStatus){case 12002:case 12029:case 12030:case 12031:case 12152:case 13030:responseObject=this.createExceptionObject(o.tId,callback.argument,(isAbort?isAbort:false));if(callback.failure){if(!callback.scope){callback.failure(responseObject);}
else{callback.failure.apply(callback.scope,[responseObject]);}}
break;default:responseObject=this.createResponseObject(o,callback.argument);if(callback.failure){if(!callback.scope){callback.failure(responseObject);}
else{callback.failure.apply(callback.scope,[responseObject]);}}}}
this.releaseObject(o);responseObject=null;},createResponseObject:function(o,callbackArg)
{var obj={};var headerObj={};try
{var headerStr=o.conn.getAllResponseHeaders();var header=headerStr.split('\n');for(var i=0;i<header.length;i++){var delimitPos=header[i].indexOf(':');if(delimitPos!=-1){headerObj[header[i].substring(0,delimitPos)]=header[i].substring(delimitPos+2);}}}
catch(e){}
obj.tId=o.tId;obj.status=(o.conn.status==1223)?204:o.conn.status;obj.statusText=(o.conn.status==1223)?"No Content":o.conn.statusText;obj.getResponseHeader=headerObj;obj.getAllResponseHeaders=headerStr;obj.responseText=o.conn.responseText;obj.responseXML=o.conn.responseXML;if(typeof callbackArg!==undefined){obj.argument=callbackArg;}
return obj;},createExceptionObject:function(tId,callbackArg,isAbort)
{var COMM_CODE=0;var COMM_ERROR='communication failure';var ABORT_CODE=-1;var ABORT_ERROR='transaction aborted';var obj={};obj.tId=tId;if(isAbort){obj.status=ABORT_CODE;obj.statusText=ABORT_ERROR;}
else{obj.status=COMM_CODE;obj.statusText=COMM_ERROR;}
if(callbackArg){obj.argument=callbackArg;}
return obj;},initHeader:function(label,value,isDefault)
{var headerObj=(isDefault)?this._default_headers:this._http_headers;if(headerObj[label]===undefined){headerObj[label]=value;}
else{headerObj[label]=value+","+headerObj[label];}
if(isDefault){this._has_default_headers=true;}
else{this._has_http_headers=true;}},setHeader:function(o)
{if(this._has_default_headers){for(var prop in this._default_headers){if(YAHOO.lang.hasOwnProperty(this._default_headers,prop)){o.conn.setRequestHeader(prop,this._default_headers[prop]);}}}
if(this._has_http_headers){for(var prop in this._http_headers){if(YAHOO.lang.hasOwnProperty(this._http_headers,prop)){o.conn.setRequestHeader(prop,this._http_headers[prop]);}}
delete this._http_headers;this._http_headers={};this._has_http_headers=false;}},resetDefaultHeaders:function(){delete this._default_headers
this._default_headers={};this._has_default_headers=false;},setForm:function(formId,isUpload,secureUri)
{this.resetFormState();var oForm;if(typeof formId=='string'){oForm=(document.getElementById(formId)||document.forms[formId]);}
else if(typeof formId=='object'){oForm=formId;}
else{return;}
if(isUpload){this.createFrame(secureUri?secureUri:null);this._isFormSubmit=true;this._isFileUpload=true;this._formNode=oForm;return;}
var oElement,oName,oValue,oDisabled;var hasSubmit=false;for(var i=0;i<oForm.elements.length;i++){oElement=oForm.elements[i];oDisabled=oForm.elements[i].disabled;oName=oForm.elements[i].name;oValue=oForm.elements[i].value;if(!oDisabled&&oName)
{switch(oElement.type)
{case'select-one':case'select-multiple':for(var j=0;j<oElement.options.length;j++){if(oElement.options[j].selected){if(window.ActiveXObject){this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oElement.options[j].attributes['value'].specified?oElement.options[j].value:oElement.options[j].text)+'&';}
else{this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oElement.options[j].hasAttribute('value')?oElement.options[j].value:oElement.options[j].text)+'&';}}}
break;case'radio':case'checkbox':if(oElement.checked){this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oValue)+'&';}
break;case'file':case undefined:case'reset':case'button':break;case'submit':if(hasSubmit===false){if(this._hasSubmitListener){this._sFormData+=this._submitElementValue+'&';}
else{this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oValue)+'&';}
hasSubmit=true;}
break;default:this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oValue)+'&';break;}}}
this._isFormSubmit=true;this._sFormData=this._sFormData.substr(0,this._sFormData.length-1);return this._sFormData;},resetFormState:function(){this._isFormSubmit=false;this._isFileUpload=false;this._formNode=null;this._sFormData="";},createFrame:function(secureUri){var frameId='yuiIO'+this._transaction_id;if(window.ActiveXObject){var io=document.createElement('<iframe id="'+frameId+'" name="'+frameId+'" />');if(typeof secureUri=='boolean'){io.src='javascript:false';}
else if(typeof secureURI=='string'){io.src=secureUri;}}
else{var io=document.createElement('iframe');io.id=frameId;io.name=frameId;}
io.style.position='absolute';io.style.top='-1000px';io.style.left='-1000px';document.body.appendChild(io);},appendPostData:function(postData)
{var formElements=[];var postMessage=postData.split('&');for(var i=0;i<postMessage.length;i++){var delimitPos=postMessage[i].indexOf('=');if(delimitPos!=-1){formElements[i]=document.createElement('input');formElements[i].type='hidden';formElements[i].name=postMessage[i].substring(0,delimitPos);formElements[i].value=postMessage[i].substring(delimitPos+1);this._formNode.appendChild(formElements[i]);}}
return formElements;},uploadFile:function(id,callback,uri,postData){var frameId='yuiIO'+id;var uploadEncoding='multipart/form-data';var io=document.getElementById(frameId);this._formNode.setAttribute('action',uri);this._formNode.setAttribute('method','POST');this._formNode.setAttribute("target",frameId);if(this._formNode.encoding){this._formNode.encoding=uploadEncoding;}
else{this._formNode.enctype=uploadEncoding;}
if(postData){var oElements=this.appendPostData(postData);}
this._formNode.submit();if(oElements&&oElements.length>0){for(var i=0;i<oElements.length;i++){this._formNode.removeChild(oElements[i]);}}
this.resetFormState();var uploadCallback=function()
{var obj={};obj.tId=id;obj.argument=callback.argument;try
{obj.responseText=io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;obj.responseXML=io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;}
catch(e){}
if(callback&&callback.upload){if(!callback.scope){callback.upload(obj);}
else{callback.upload.apply(callback.scope,[obj]);}}
if(YAHOO.util.Event){YAHOO.util.Event.removeListener(io,"load",uploadCallback);}
else if(window.detachEvent){io.detachEvent('onload',uploadCallback);}
else{io.removeEventListener('load',uploadCallback,false);}
setTimeout(function(){document.body.removeChild(io);},100);};if(YAHOO.util.Event){YAHOO.util.Event.addListener(io,"load",uploadCallback);}
else if(window.attachEvent){io.attachEvent('onload',uploadCallback);}
else{io.addEventListener('load',uploadCallback,false);}},abort:function(o,callback,isTimeout)
{if(this.isCallInProgress(o)){o.conn.abort();window.clearInterval(this._poll[o.tId]);delete this._poll[o.tId];if(isTimeout){delete this._timeOut[o.tId];}
this.handleTransactionResponse(o,callback,true);return true;}
else{return false;}},isCallInProgress:function(o)
{if(o.conn){return o.conn.readyState!==4&&o.conn.readyState!==0;}
else{return false;}},releaseObject:function(o)
{o.conn=null;o=null;}};YAHOO.register("connection",YAHOO.util.Connect,{version:"2.2.2",build:"204"});<!-- @require yahoo/yahoo-min.js -->
<!-- @require event/event-min.js -->
<!-- @require connection/connection-min.js -->

/*
 * AjaxObjUpdTxtPers is a hypothetical object that encapsulates the transaction
 *     request and callback logic.
 *
 * handleSuccess( ) provides success case logic
 * handleFailure( ) provides failure case logic
 * processResult( ) displays the results of the response from both the
 * success and failure handlers
 * call( ) calling this member starts the transaction request.
 */
var AjaxObjUpdTxtPers = {

	URL_SVC_UPD_TXT_PERS: "./mapaCelular/svcUpdTxtPers.asp",
	IDDIV_TEXTO_PERSONALIZADO: "id_celular",
	ID_TXT_PERSONALIZADO : 'txtRememberText',
	MSG_ERROR : "En este momento no podemos atender su solicitud de actualización de texto personalizado"
						 +"\n\n Por favor, intente más tarde ...",

	handleSuccess:function(o){
    var respuesta, hayError;
    hayError = false;
    try{
      respuesta = o.responseXML.documentElement;
    }catch(err){
      alert(this.MSG_ERROR);
      document.body.style.cursor = 'auto';
      hayError = true;
    }
    if (hayError==false)
    	this.processResult(respuesta);
	},

	handleFailure:function(o){
    //alert(this.MSG_ERROR);
	alert("Transacción id: " + o.tId + "-->HTTP código de estado: " + o.status + "-->Mensaje del código de estado: " + o.statusText);
    document.body.style.cursor = 'auto';
	},

	processResult:function(respuesta){
		//mostrare mensaje de error
		nodoRespuesta    = respuesta.getElementsByTagName('RESPUESTA');
		if (nodoRespuesta[0] && nodoRespuesta[0].firstChild){
      var descripcion ='';
      if(nodoRespuesta[0].firstChild.data != 'OK')
      	descripcion = nodoRespuesta[0].firstChild.data;
			if (descripcion!=''){
				alert(descripcion);
				document.body.style.cursor = 'auto';
				return;
      }
		}

		//limpiar texto personalizado

		document.getElementById(this.ID_TXT_PERSONALIZADO).value="";

		//ocultar bloque de texto personalizado
		//document.getElementById(this.IDDIV_TEXTO_PERSONALIZADO).style.display="none";

	 	document.body.style.cursor = 'auto';

		win_prototype.hide();
	},

	startRequest:function(strCodigo, strTexto) {
		var postData =   "codigo=" +strCodigo+"&txtPersonalizado="+strTexto;
		rExp = / /gi;
		postData = postData.replace(rExp,"+");

		document.body.style.cursor = 'wait';
		YAHOO.util.Connect.asyncRequest('POST', this.URL_SVC_UPD_TXT_PERS, callbackUpdTxtPers, postData);
	}
};

/*
 * Define the callback object for success and failure
 * handlers as well as object scope.
 */
var callbackUpdTxtPers =
{
	success:AjaxObjUpdTxtPers.handleSuccess,
	failure:AjaxObjUpdTxtPers.handleFailure,
  timeout: 100000,
	scope: AjaxObjUpdTxtPers
};<!-- @require yahoo/yahoo-min.js -->
<!-- @require event/event-min.js -->
<!-- @require connection/connection-min.js -->

/*
 * AjaxObjGetCodigo is a hypothetical object that encapsulates the transaction
 *     request and callback logic.
 *
 * handleSuccess( ) provides success case logic
 * handleFailure( ) provides failure case logic
 * processResult( ) displays the results of the response from both the
 * success and failure handlers
 * call( ) calling this member starts the transaction request.
 */
var AjaxObjGetCodigo = {

	tipo_via : '',
	nombre_via : '',
	altura : '',
	comuna : '',
	ciudad : '',
	este : '',
	norte : '',
	entorno : '',
	codigo : '',

	codigoEstaCargado : false,

	URL_SVC_GET_CODIGO: "./mapaCelular/svcGetCodigo.asp",
	IDDIV_CODIGO1: "id_block_celular_codigo1",
	IDDIV_CODIGO2: "id_block_celular_codigo2",
	IDDIV_CODIGO3: "id_block_celular_codigo3",
	IDDIV_CODIGO4: "id_block_celular_codigo4",
	IDDIV_CODIGO5: "id_block_celular_codigo5",
	MSG_ERROR : "En este momento no podemos atenderlo"
						 +"\n\n Por favor, intente más tarde ...",

	handleSuccess:function(o){
    var respuesta, hayError;
    hayError = false;
    try{
      respuesta = o.responseXML.documentElement;

    }catch(err){
      alert(this.MSG_ERROR);
      document.body.style.cursor = 'auto';
      hayError = true;
    }
    if (hayError==false)
    	this.processResult(respuesta);
	},

	handleFailure:function(o){
		//alert("Transacción id: " + o.tId + "-->HTTP código de estado: " + o.status + "-->Mensaje del código de estado: " + o.statusText);
    alert(this.MSG_ERROR);
    document.body.style.cursor = 'auto';
	},

	processResult:function(respuesta){

		//mostrare mensaje de error
		nodoError    = respuesta.getElementsByTagName('ERROR');
		if (nodoError[0] && nodoError[0].firstChild){
      var descripcion = nodoError[0].firstChild.data;
			if (descripcion!=''){
				alert(descripcion);
				document.body.style.cursor = 'auto';
				return;
      }
		}

		nodoCodigo    = respuesta.getElementsByTagName('CODIGO');
		this.codigo 	= nodoCodigo[0].firstChild.data;
		document.getElementById(this.IDDIV_CODIGO1).innerHTML =this.codigo;
		document.getElementById(this.IDDIV_CODIGO2).innerHTML =this.codigo;
		document.getElementById(this.IDDIV_CODIGO3).innerHTML =this.codigo;
		//document.getElementById(this.IDDIV_CODIGO4).innerHTML =this.codigo;
		document.getElementById(this.IDDIV_CODIGO5).innerHTML =this.codigo;
		this.codigoEstaCargado=true;
	 	document.body.style.cursor = 'auto';
	},

	getPostDataArgs:function(){
		var postData="";
		postData += "tipo_via="+((this.tipo_via.length>0)?this.tipo_via:"");
		postData += "&nombre_via="+((this.nombre_via.length>0)?this.nombre_via:"");
		postData += "&altura="+((this.altura.length>0)?this.altura:"");
		postData += "&comuna="+((this.comuna.length>0)?this.comuna:"");
		postData += "&ciudad="+((this.ciudad.length>0)?this.ciudad:"");
		postData += "&este="+((this.este.length>0)?this.este:"");
		postData += "&norte="+((this.norte.length>0)?this.norte:"");
		postData += "&entorno="+((this.entorno.length>0)?this.entorno:"");
		return postData;
	},

	startRequest:function() {
		var postData =   this.getPostDataArgs();
		document.body.style.cursor = 'wait';
		rExp = / /gi;
		postData = postData.replace(rExp,"+");

		YAHOO.util.Connect.asyncRequest('POST', this.URL_SVC_GET_CODIGO, callbackGetCodigo, postData);
	},

	init:function(idForm){
		this.tipo_via 	= ""+document.forms[idForm]['TipoVia1'].value;
		this.nombre_via = ""+document.forms[idForm]['NombreVia1'].value;
		this.altura			= ""+document.forms[idForm]['Altura1'].value;
		this.comuna			= ""+document.forms[idForm]['Comuna1'].value;
		this.ciudad			= ""+document.forms[idForm]['ciudad'].value;
		this.este				= ""+document.forms[idForm]['Punto_X'].value;
		this.norte			= ""+document.forms[idForm]['Punto_Y'].value;
		try{
			this.entorno		= getObjFromFrame('id_entorno','DescEntorno').innerHTML;
		}catch(er){
			this.entorno = "NO PUDO SER OBTENIDO"
		}
	}
};

/*
 * Define the callback object for success and failure
 * handlers as well as object scope.
 */
var callbackGetCodigo =
{
	success:AjaxObjGetCodigo.handleSuccess,
	failure:AjaxObjGetCodigo.handleFailure,
  timeout: 100000,
	scope: AjaxObjGetCodigo
};/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;//Function Oculta Tabla ID
isOPERA = (navigator.userAgent.indexOf('Opera') >= 0)? true : false;
isIE    = (document.all && !isOPERA)? true : false;
isDOM   = (document.getElementById && !isIE && !isOPERA)? true : false;

var entrada	= new Array();
var content	= new Array ();
var cantidad	= new Array(); 
var totalPestana = new Array();	
var varcerrarmenu = new Array();
cantidad["sub"] = "4";
cantidad["mapa"] = "4";
totalPestana["tab"] = 4;
totalPestana["mapa"] = 4;
varcerrarmenu['ico']=true;
varcerrarmenu['ico3']=true;
varcerrarmenu['mapa']=true;
varcerrarmenu['mapa2']=true;
varcerrarmenu['mapa3']=true;
var estaCargada=true;
initArray("sub");
initArray("mapa");

function initArray(llave) {	
	for (x=0; x < cantidad[llave]; x++){
		entrada [llave + "_"+x] = true;
	}
}

function show (llave, id, displayValue){
	if (isDOM)
		document.getElementById(llave+'_'+id).style.display = (displayValue)? displayValue: "block";
	else if (isIE)
	document.all[llave+'_'+id].style.display = "block";
}

function menu(llave, id){
	if(estaCargada == true){
		hide_all(llave);
		if (entrada[llave + "_"+id]){
			show (llave, id, 'table-row');
			for (x=0; x < cantidad[llave]; x++){
				entrada [llave + "_"+x] = true;
			}
			//entrada[llave + "_"+id] = false;
		}else{			
			entrada[llave + "_"+id]=true;
		}
	}
}
 
function hide (id){		
	if (document.getElementById(id))
	{
		if (isDOM)
			document.getElementById(id).style.display = "none";
		else if (isIE)
			document.all[id].style.display = "none";
	}
}
 
function hide_all(llave) {	
	for (i=0; i<cantidad[llave];i++){
		hide(llave + "_" + i);
	}
}

function isExist(value) {
	var pattern=new RegExp("^[ ]*$");
    return value.match(pattern) || value.length==0;
}


function change_style(id, clrIn){
	if(estaCargada == true){
		if (isDOM){
			document.getElementById(id).className = clrIn;
		}else if (isIE){
			document.all[id].className = clrIn;
		}	
	}
} 

function change_pest(llave, id, clrIn){
	if(estaCargada == true){
		reset__all_pest(llave);
		for (i=1;i<=1;i++){
			change_style(llave+''+ id + '_' + i, clrIn);
		}
	} 
}
function reset__all_pest(llave, id){
	for (i=1;i<=totalPestana[llave];i++){
		for (y=1;y<=1;y++){
			change_style(llave +''+ i + '_' + y, llave+''+parseInt(i-1)+'-inactivo');
		}
	}	
}

function changeImage(image, _src) {
	var imgnormal;
	var imgover; 
	var img;
	if(estaCargada == true){
		img = eval('document.'+image);		
		imgover = (image+'.gif');
		img.src = "images/htm/" + _src;	
	}
}
/**
* @param esDelPadre determina si la imagen esta se debe recuperar de parent.document
* @param frameID solo se envia cuando la imagen se encuentra en un iframe
**/
function changeImageZoom(image, _src,esDelPadre,frameID) {
	var imgnormal;
	var imgover; 
	var img;		
	if(frameID)				
		img = parent.getObjFromFrame(image,frameID)
	else if (esDelPadre && esDelPadre==true){	
		img = parent.getObj(image,true)		
	}else if (esDelPadre)	
		img = parent.getObj(image)
	else
		img = eval('document.'+image);			
	imgover = (image+'.gif');
	img.src = "images/botones/" + _src;
			
}
/**
* @param esDelPadre determina si la imagen esta se debe recuperar de parent.document
* @param frameID solo se envia cuando la imagen se encuentra en un iframe
**/

function changeImageZoomFromFrame(image, _src) {
	var imgnormal;
	var imgover; 
	var img;		
	if(frameID)				
		img = parent.getObjFromFrame(image,frameID)
	else if (esDelPadre && esDelPadre==true){	
		img = parent.getObj(image,true)		
	}else if (esDelPadre)	
		img = parent.getObj(image)
	else
		img = eval('document.'+image);			
	imgover = (image+'.gif');
	img.src = "images/botones/" + _src;
			
}
/**
* @author rpalacios
* @contact rodrigo.palacios.cb@gmail.com
* Some right reserved (cc) 2006 
**/

/**
* Permite obtener la version del navegador utilizado
**/
var user_agent = navigator.userAgent.toLowerCase();
function getAgent() 
{
	  if (user_agent.indexOf('opera')!=-1) { // Opera (check first in case of spoof)
		 return 'opera';
	  } else if (user_agent.indexOf('msie 7')!=-1) { // IE7
		 return 'ie7';
	  } else if (user_agent.indexOf('msie') !=-1) { // IE
		 return 'ie';
	  } else if (user_agent.indexOf('safari')!=-1) { // Safari (check before Gecko because it includes "like Gecko")
		 return 'safari';
	  } else if (user_agent.indexOf('gecko') != -1) { // Gecko
		 return 'gecko';
	  } else {
		 return false;
	  }
}
var agent = getAgent();
var cursorHand = (agent=='gecko')?'pointer':'hand';	

/**
* Permite pausar la ejecucion de un script los milisegundos especificados
* ejemplo de uso
* function cargaslider(){return false;}//primero definir la funcion a invocar
* Luego se debe hacer un ciclo que su condición de ejecución sea hasta que la 
* funcion exista y/o la cantidad de iteraciones sea menor que 3 (en este caso la funcion retorna true)
* 		for (i=0;!cargaslider() && i<3;i++ )
*			pauseScript(3000);			
* @param millis, milisegundos a pausar
*/
function pauseScript(millis)
{
	var date = new Date();
	var curDate = null;
	
	do
	{ 
		curDate = new Date(); 
	}while(curDate-date < millis);
} 
/**
* Retorna una referencia a un objeto iframe
* @param formID , corresponde al identificador del formulario
* @param objID , corresponde al identificador del objeto 
* @param esDelPadre, si viene quiere decir que el la referencia al objeto 
*        que se quiere obtener esta en el documento padre (parent.document.),
*        si no viene se toma como referencia el documento actual (document.)	
**/

function getObjIframe(objID,esDelPadre)
{
	if(esDelPadre)
	{
		return parent.window.frames[objID];
	}else
		return window.frames[objID];
}

/**
* Retorna una referencia a un objeto 
* @param formID , corresponde al identificador del formulario
* @param objID , corresponde al identificador del objeto 
* @param esDelPadre, si viene quiere decir que el la referencia al objeto 
*        que se quiere obtener esta en el documento padre (parent.document.),
*        si no viene se toma como referencia el documento actual (document.)	
**/

function getObjFromForm(formID, objID,esDelPadre)
{
	if(esDelPadre)
	{
		return parent.document.forms[formID][objID];
	}else
		return document.forms[formID][objID];
}
/**
* Retorna una referencia a un objeto perteneciente al formulario que pertenece al iframe o frame seleccionado 
* @param formID , corresponde al identificador del formulario
* @param objID , corresponde al identificador del objeto 
* @param frameID ,corresponde al identificador del frame que contiene al objeto solicitado
* @param esDelPadre, si viene quiere decir que el la referencia al objeto 
*        que se quiere obtener esta en el documento padre (parent.document.),
*        si no viene se toma como referencia el documento actual (document.)	
**/	
function getObjFromFormFromFrame(formID, objID,frameID,esDelPadre)
{
	if(esDelPadre)
		return parent.window.frames[frameID].document.forms[formID][objID];
	else
		return window.frames[frameID].document.forms[formID][objID];
}

/**
* Retorna una referencia a un objeto que pertenece al iframe o frame indicado en @param frameID
* @param objID ,corresponde al identificador del objeto    
* @param frameID ,corresponde al identificador del frame que contiene al objeto solicitado
* @param esDelPadre, si viene quiere decir que el la referencia al objeto 
*        que se quiere obtener esta en el documento padre (parent.document.),
*        si no viene se toma como referencia el documento actual (document.)	
**/
function getObjFromFrame(objID,frameID,esDelPadre)
{
	if(esDelPadre)
	{
		if(document.getElementById)
			return parent.window.frames[frameID].document.getElementById(objID);
		else if( document.all )
			return parent.window.frames[frameID].document.all[objID];
		else if( document.layers )
			 {
				if( parent.window.frames[frameID].document.layers[objID] )
					return parent.window.frames[frameID].document.layers[objID];
			 }
	}else{
		if(document.getElementById)		
			return window.frames[frameID].document.getElementById(objID);
		else if( document.all )
			return window.frames[frameID].document.all[objID];
		else if( document.layers )
			 {
				if( window.frames[frameID].document.layers[objID] )
					return window.frames[frameID].document.layers[objID];
			 }
	}
}

/**
* Retorna una referencia a un objeto de la página a través del atributo NAME ó ID
* @param objID ,corresponde al identificador del objeto    
* @param esDelPadre, si viene quiere decir que el la referencia al objeto 
*        que se quiere obtener esta en el documento padre (parent.document.),
*        si no viene se toma como referencia el documento actual (document.)	
**/
function getObj(objID,esDelPadre)
{
	if(esDelPadre)
	{
		if(document.getElementById){		 	
			//alert("objID="+objID+" src="+ parent.document.getElementById(objID).src);
			return parent.document.getElementById(objID);
		}	
		else if( document.all ) 
			return parent.document.all[objID];
		else if( document.layers )
				if( parent.document.layers[objID] )
				   parent.document.layers[objID]; 									     
	}else{
	  if( document.getElementById ) 
		return document.getElementById(objID); 
	  if( document.all ) 
		return document.all[objID]; 
	  if( !oDoc ) 
		oDoc = document;     
	  if( document.layers ){
		if( oDoc.layers[objID] ) 
			return oDoc.layers[objID]; 
	  } 			  
	}
	return false;
}

function doNuhn() {}
/**
* Retorna la coordenada x e y donde esta posicionado el mouse
* @return array posicion 0=coordenada X, posicion 1=coordenada Y
*/
//now create the event handler function to process the event
function getCoords(e) {
  if( !e ) {
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }
  if( typeof( e.pageX ) == 'number' ) {
    //most browsers
    var xcoord = e.pageX;
    var ycoord = e.pageY;
  } else if( typeof( e.clientX ) == 'number' ) {
    //Internet Explorer and older browsers
    //other browsers provide this, but follow the pageX/Y branch
    var xcoord = e.clientX;
    var ycoord = e.clientY;
    var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
     ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
     ( navigator.vendor == 'KDE' )
    if( !badOldBrowser ) {
      if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //IE 4, 5 & 6 (in non-standards compliant mode)
        xcoord += document.body.scrollLeft;
        ycoord += document.body.scrollTop;
      } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE 6 (in standards compliant mode)
        xcoord += document.documentElement.scrollLeft;
        ycoord += document.documentElement.scrollTop;
      }
    }
  } else {
    //total failure, we have no way of obtaining the mouse coordinates
    return;
  }
  return new Array (xcoord,ycoord);  
}

/**
* Imprime las coordenadas x e y del mouse
*/
function alertCoords(e) {
	var coordenadas = getCoords(e);
	if(coordenadas)
		window.alert('Mouse coordinates are x=('+coordenadas(0)+',Y='+coordenadas(1)+')');
	else
		window.alert('total failure, we have no way of obtaining the mouse coordinates');
}
	
/**
* Retorna la coordenada x e y donde esta posicionado el mouse
* @return array posicion 0=coordenada X, posicion 1=coordenada Y 
*/	
//now create the event handler function to process the event
function getkey(e) {
  if( !e ) {
    //if the browser did not pass the event information to the
    //function, we will have to obtain it from the event register
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }
  if( typeof( e.keyCode ) == 'number'  ) {
    //DOM
    e = e.keyCode;
  } else if( typeof( e.which ) == 'number' ) {
    //NS 4 compatible
    e = e.which;
  } else if( typeof( e.charCode ) == 'number'  ) {
    //also NS 6+, Mozilla 0.9+
    e = e.charCode;
  } else {
    //total failure, we have no way of obtaining the key code
    return;
  }
  return e;  
}
/**
* Imprime la tecla del teclado
*/
function alertkey(e) {
	var key = getkey(e);
	if(key)
		window.alert('The key pressed has keycode ' + key +' and is key ' + String.fromCharCode( key ) );
	else
		window.alert('total failure, we have no way of obtaining the key code');
}
function getBut( e, evElement ) {
  if( !e ) {
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }
  if( typeof( e.which ) == 'number' ) {
    //Netscape compatible
    e = e.which;
  } else if( typeof( e.button ) == 'number' ) {
    //DOM
    e = e.button;
  } else {
    //total failure, we have no way of obtaining the button
    return;
  }
  if( !evElement ) { evElement = this; }
  return e;
}
/**
* Imprime la tecla del teclado
*/
function alertBut(e,evElement) {
	var but = getBut(e,evElement);
	if(but)
	  /* 'this' will exist if I have used object.onEventName = alertBut;
	  If I have passed evElement from the onmouseup attribute,
	  'this' will refer to window */
	  window.alert( evElement + ' was clicked with button ' + but );
	else
		window.alert('total failure, we have no way of referencing the event');
}
/**
* Retorna un objeto puntero a un objeto del documento
* @param divID identificador (dom) del objeto 
* @param oDoc  referencia a documento 
**/
function getElemento(divID,oDoc)
{
  	
  if( document.getElementById ) 
  {
    return document.getElementById(divID); 
   }  
  if( document.all ) 
    return document.all[divID]; 
  if( !oDoc ) 
  	oDoc = document;     
  if( document.layers ){
    if( oDoc.layers[divID] ){ 
	    return oDoc.layers[divID]; 
	}else{
      //repeatedly run through all child layers
      for( var x = 0, y; !y && x < oDoc.layers.length; x++ ){
        //on success, return that layer, else return nothing
        y = getElemento(divID,oDoc.layers[x].document); 
      }
      return y; 
   } 
  }
  return false;
}
/**
* Retorna un objeto puntero a un objeto del documento
* @param divID identificador (dom) del objeto 
* @param oDoc  referencia a documento 
**/
function getElementoFromForm(formID, divID){  	  
  return document.forms[formID][divID]; 
}
/**
* Muestra una capa 
* Example of use : onclick="showDiv('myDiv');"
*/
function showDiv(divID_as_a_string){
  //get a reference as above ...
  myReference = getElemento(divID_as_a_string);
  if( !myReference ){
    window.alert('Nothing works in this browser');
    return; //don't go any further
  }
  //now we have a reference to it
  if( myReference.style ){
    //DOM & proprietary DOM
    myReference.style.visibility = 'visible';
  } else {
    //layers syntax
    myReference.visibility = 'show';
  }
}
/**
* Oculta una capa 
* Example of use : onclick="hideDiv('myDiv');"
*/
function hideDiv(divID_as_a_string) {
	//get a reference as above ...
	var myReference = getElemento(divID_as_a_string);
	if( !myReference ) { 
		window.alert('Nothing works in this browser'); 
		return; 
	}
	if( myReference.style ) 
	{
		myReference.style.visibility = 'hidden'; 
	} else {
		if( myReference.visibility ) { 
			myReference.visibility = 'hide'; 
		} else {
			window.alert('Nothing works in this browser'); 
			return; 
		} 
	}
}
/**
* Muestra una capa 
* Example of use : onclick="showTr('myDiv');"
*/
function showTr(divID_as_a_string){
  //get a reference as above ...
  myReference = getElemento(divID_as_a_string);
  if( !myReference ){
    window.alert('Nothing works in this browser');
    return; //don't go any further
  }
  //now we have a reference to it
  if( myReference.style ){
    //DOM & proprietary DOM
    myReference.style.display = (navigator.userAgent.indexOf("MSIE")>0)?'block':'table-row';
  } else {
    //layers syntax
    myReference.visibility = 'show';
  }
}

/**
* Oculta una Tr de una tabla
* Example of use : onclick="hideTr('myDiv');"
*/
function hideTr(divID_as_a_string) {
	//get a reference as above ...
	var myReference = getElemento(divID_as_a_string);
	if( !myReference ) { 
		window.alert('Nothing works in this browser'); 
		return; 
	}
	
	if( myReference.style ) 
	{		
		myReference.style.display = 'none'; 
	} else {
		if( myReference.visibility ) { 
			myReference.visibility = 'hide'; 
		} else {
			window.alert('Nothing works in this browser'); 
			return; 
		} 
	}
}

function changeDisplay( elementId, setTo ) {
   var theElement;
  if( document.getElementById ) {
    //DOM
    theElement = document.getElementById( elementId );
  } else if( document.all ) {
    //Proprietary DOM
    theElement = document.all[ elementId ];
  }
  if( !theElement ) {
    /* The page has not loaded, or the browser claims to
    support document.getElementById or document.all but
    cannot actually use either */
    return;
  }
  //Reference the style ...
  if( theElement.style ) { theElement = theElement.style; }
  if( typeof( theElement.display ) == 'undefined' ) {
    //The browser does not allow us to change the display style
    //Alert something sensible (not what I have here ...)
    window.alert( 'Your browser does not support this' );
    return;
  }
  //Change the display style
  theElement.display = setTo;
}	
/**
* Autoajusta en tamaño del iframe al contenido de este al momento de cargar el body del doc hijo(iframe)
* Uso: en body del doc html del iframe poner autofitIframe('Noticias'); 
* donde 'Noticias' es el id del tag iframe en documento html padre
* @param id, identificador del iframe
**/
function autofitIframe(id)
{	
	var the_height;	
	if (!window.opera && !document.mimeType && document.all && document.getElementById)
	{	
		the_height = parseInt(this.document.body.offsetHeight);
		parent.document.getElementById(id).style.height=the_height+"px";
	}
	else if(document.getElementById) 
	{
		the_height = parseInt(this.document.body.scrollHeight);
		parent.document.getElementById(id).style.height=the_height+"px"
	}
}

<!--
var cantidad	= new Array();
cantidad["sub"] = "4";
cantidad["mapa"] = "3";
totalPestana["tab"] = 3;
totalPestana["mapa"] = 3;
var varcerrarmenu = new Array;
varcerrarmenu['ico']=true;
varcerrarmenu['ico3']=true;
varcerrarmenu['mapa']=true;
varcerrarmenu['mapa2']=true;
varcerrarmenu['mapa3']=true;
var estaCargada=true;

function busquedaCheckinPlt(obj, theForm) {

	if(obj.selectedIndex!=0) {
		document.getElementById('dire_GenRuta').disabled=false;
	} else {
		document.getElementById('dire_GenRuta').checked=false;
		document.getElementById('dire_STransito').checked=false;
		document.getElementById('dire_GenRuta').disabled=true;
		document.getElementById('dire_STransito').disabled=true;
	}
}
function busquedaCheckinRutaPlt(obj, theForm) {
	if(obj.selectedIndex!=0) {
		document.getElementById('dire_GenRuta').disabled=false;
	} else {
		document.getElementById('dire_GenRuta').checked=false;
		document.getElementById('dire_GenRuta').disabled=true;
	}
}
function busquedaCheckinOffPlt(obj, theForm) {
	if(obj.selectedIndex!=0) {
		document.getElementById('dire_STransito').disabled=false;
	} else {
		document.getElementById('dire_STransito').checked=false;
		document.getElementById('dire_STransito').disabled=true;
	}
}

function checkTransitoPlt(obj, theForm) {
	if ((document.getElementById('dire_Altura1').value == "") && (document.getElementById('dire_NombreViaInt1').value == ""))
	{

		alert ("Esta opción se puede utilizar solo con dirección o intersección");
		document.getElementById('dire_GenRuta').checked=false;
		return false;
	}
	if(obj.checked) {
		document.getElementById('dire_STransito').disabled=false;
	} else {
		document.getElementById('dire_STransito').checked=false;
		document.getElementById('dire_STransito').disabled=true;
	}
}

	function fncCodVal(idForm) {
		/*alert(document.forms[idForm]['ciudad'			].value)
		alert(document.forms[idForm]['Producto'			].value)
		alert(document.forms[idForm]['opcbuscar'			].value)
		alert(document.forms[idForm]['icono'			].value)
		alert(document.forms[idForm]['icmapa'			].value)
		alert(document.forms[idForm]['colormapa'			].value)
		alert(document.forms[idForm]['icono1'			].value)
		alert(document.forms[idForm]['TipoVia1'			].value)
		alert(document.forms[idForm]['NombreVia1'			].value)
		alert(document.forms[idForm]['NombreViaInt1'			].value)
		alert(document.forms[idForm]['Comuna1'			].value)
		alert(document.forms[idForm]['szTxtComercio'			].value)

		alert(document.getElementById('comer_ciudad').value);
		alert(document.getElementById('comer_Producto').value);
		alert(document.getElementById('comer_opcbuscar').value);
		alert(document.getElementById('comer_icono').value);
		alert(document.getElementById('comer_icmapa').value);
		alert(document.getElementById('comer_colormapa').value);
		alert(document.getElementById('comer_icono1').value);
		alert(document.getElementById('comer_TipoVia1').value);
		alert(document.getElementById('comer_NombreVia1').value);
		alert(document.getElementById('comer_Altura1').value);
		alert(document.getElementById('comer_NombreViaInt1').value);
		alert(document.getElementById('comer_Comuna1').value);
		alert(document.getElementById('comer_szTxtComercio').value);*/

		document.forms[idForm]['ciudad'			].value = document.getElementById('comer_ciudad').value;
		document.forms[idForm]['Producto'		].value = document.getElementById('comer_Producto').value;
		document.forms[idForm]['opcbuscar'		].value = document.getElementById('comer_opcbuscar').value;
		document.forms[idForm]['icono'			].value = document.getElementById('comer_icono').value;
		document.forms[idForm]['icmapa'			].value = document.getElementById('comer_icmapa').value;
		document.forms[idForm]['colormapa'		].value = document.getElementById('comer_colormapa').value;
		document.forms[idForm]['icono1'			].value = document.getElementById('comer_icono1').value;
		document.forms[idForm]['TipoVia1'		].value = document.getElementById('comer_TipoVia1').value;
		document.forms[idForm]['NombreVia1'		].value = document.getElementById('comer_NombreVia1').value;
		document.forms[idForm]['Altura1'		].value = document.getElementById('comer_Altura1').value;
		document.forms[idForm]['NombreViaInt1'	].value = document.getElementById('comer_NombreViaInt1').value;
		document.forms[idForm]['Comuna1'		].value = document.getElementById('comer_Comuna1').value;
		document.forms[idForm]['szTxtComercio'	].value = document.getElementById('comer_szTxtComercio').value;
		document.forms[idForm]['szTxtRubro'	    ].value = "";
		var res = true;
		//alert('a');
		if (document.getElementById('comer_NombreVia1').value != "") {
			//alert('b');
			res = CheckDireccion('comer_NombreVia1','comer_Altura1','comer_Comuna1','');
		}

		if (res) {
			document.getElementById(idForm).submit();
		}


		/*
		var szPagina = 'includes/validacod.asp?code=' + document.getElementById('code').value;
		var opt={
			method:'post',
			onComplete:function(transport){
				resObj=transport.responseText.evalJSON(true);
				if (resObj.MSG == 'OK') {
						document.getElementById(idForm).submit();
				}
				else {
					alert(resObj.MSG);
					RefreshImage('imgCaptchaMain');
					RefreshImage('imgCaptcha');
					}
			},
			onFailure:function(){
				alert('Lo sentimos, La dirección no pudo ser encontrada');
			}
		};
		
		new Ajax.Request(szPagina,opt);
		*/
	}
	
	function RefreshImage(valImageId) {
		var objImage = document.images[valImageId];
		if (objImage == undefined) {
			return;
		}
		var now = new Date();
		objImage.src = objImage.src.split('?')[0] + '?x=' + now.toUTCString();
	}

function doSubmitSearchComercio(idForm) {
	if (document.getElementById('comer_szTxtComercio').value != '') {
		fncCodVal(idForm);
		return;
	}
	else {
		alert('Ingrese nombre comercio o rubro a buscar.');
		}
}

function doSubmitSearchDireccion(idForm)
{
	if (document.getElementById('comer_szTxtComercio').value != '') {
		fncCodVal(idForm);
		return;
	}
	
	AsignaResolucion(document.forms[idForm]);

	if(CheckDireccion('dire_NombreVia1','dire_Altura1','dire_Comuna1','dire_CodigoPostal1'))
	{
		//pasar valores
		document.forms[idForm]['ciudad'			].value = document.getElementById('dire_ciudad').value;
		document.forms[idForm]['Producto'		].value = document.getElementById('dire_Producto').value;
		document.forms[idForm]['opcbuscar'		].value = document.getElementById('dire_opcbuscar').value;
		document.forms[idForm]['icono'			].value = document.getElementById('dire_icono').value;
		document.forms[idForm]['icmapa'			].value = document.getElementById('dire_icmapa').value;
		document.forms[idForm]['colormapa'		].value = document.getElementById('dire_colormapa').value;
		document.forms[idForm]['icono1'			].value = document.getElementById('dire_icono1').value;
		document.forms[idForm]['TipoVia1'		].value = document.getElementById('dire_TipoVia1').value;
		document.forms[idForm]['NombreVia1'		].value = document.getElementById('dire_NombreVia1').value;
		document.forms[idForm]['Altura1'		].value = document.getElementById('dire_Altura1').value;
		document.forms[idForm]['NombreViaInt1'	].value = document.getElementById('dire_NombreViaInt1').value;
		document.forms[idForm]['CodigoPostal1'	].value = document.getElementById('dire_CodigoPostal1').value;
		document.forms[idForm]['Comuna1'		].value = document.getElementById('dire_Comuna1').value;
		document.forms[idForm]['TxtPer1'		].value = document.getElementById('dire_TxtPer1').value;
		document.forms[idForm]['idServicio'		].value = document.getElementById('dire_IdServicio').value;

		if (document.getElementById('dire_GenRuta').checked)
		{
			document.forms[idForm]['GenRuta'				].value = document.getElementById('dire_GenRuta'			).value;
			document.forms[idForm]['STransito'			].value = document.getElementById('dire_STransito'		).value;
		}
		else
		{
			document.forms[idForm]['GenRuta'].value = "";
			document.forms[idForm]['STransito'].value = "";
		}

		//submit
		document.getElementById(idForm).submit();
	}
}

function CheckDireccion(idNombreVia,idAltura,idComuna,idCodigoPostal)
{
	var calle	=	document.getElementById(idNombreVia);
	var numero	=	document.getElementById(idAltura);
	var comuna	=	document.getElementById(idComuna);
	if (idCodigoPostal != '') {
		var cp			=	document.getElementById(idCodigoPostal);
	}

	if ( calle.value == "" && comuna.options[comuna.selectedIndex].value == "" )
	{
		if (idCodigoPostal != '') {
			if ( cp.value == "" )
			{
				alert ("Debe ingresar nombre de Calle y/o Comuna y/o Codigo Postal");
				calle.focus();
				return false;
			}
			else
			{
				if ( isNaN(cp.value) )
				{
					alert ("Codigo Postal invalido, debe ser numerico");
					cp.value = "";
					cp.focus();
					return false;
				}
				if ( cp.value.length < 7 )
				{
					alert ("Codigo Postal invalido, debe ser de largo 7");
					cp.value = "";
					cp.focus();
					return false;
				}
			}
		}
	}

	if ( numero.value != "" )
	{
		if ( ! CheckNum(numero) )
		{
			alert ("Numero no valido. Ingrese solo numeros");
			numero.value="";
			numero.focus();
			return false;
		}
	}
	
	CambiaBotonBuscar('bot_buscar01');
	return true;
}


function intro (tecla,producto) {
	if(tecla==13){
		switch (producto)
		{
			case "direccion" :
				doSubmitSearchDireccion("direcc");
				break;
			case "comercio" :
				doSubmitSearchComercio("direcc");
				break;
		    case "ruta" :
				doSubmitSearchRuta("direcc");
				break;
			case "telefono" :

			doSubmitSearchTelefono("direcc");
			break;
   
	   }
	}
}

function doSubmitSearchRuta(idForm){

	AsignaResolucion(document.forms[idForm]);

	if (CheckRuta('ruta_NombreVia1','ruta_NombreViaInt1','ruta_Altura1','ruta_Comuna1','ruta_NombreVia2','ruta_NombreViaInt2','ruta_Altura2','ruta_Comuna2')){
		//pasar valores
		document.forms[idForm]['Producto'     ].value = document.getElementById('ruta_Producto'    ).value;
		document.forms[idForm]['ciudad'       ].value = document.getElementById('ruta_ciudad'      ).value;
		document.forms[idForm]['opcbuscar'    ].value = document.getElementById('ruta_opcbuscar'   ).value;
		document.forms[idForm]['icono'        ].value = document.getElementById('ruta_icono'       ).value;
		document.forms[idForm]['icmapa'       ].value = document.getElementById('ruta_icmapa'      ).value;
		document.forms[idForm]['icorigen'     ].value = document.getElementById('ruta_icorigen'    ).value;
		document.forms[idForm]['icdestino'    ].value = document.getElementById('ruta_icdestino'   ).value;
		document.forms[idForm]['icono1'       ].value = document.getElementById('ruta_icono1'      ).value;
		document.forms[idForm]['icono2'       ].value = document.getElementById('ruta_icono2'      ).value;
		document.forms[idForm]['colormapa'    ].value = document.getElementById('ruta_colormapa'   ).value;
		document.forms[idForm]['TipoVia1'     ].value = document.getElementById('ruta_TipoVia1'    ).value;
		document.forms[idForm]['NombreVia1'   ].value = document.getElementById('ruta_NombreVia1'  ).value;
		document.forms[idForm]['Altura1'      ].value = document.getElementById('ruta_Altura1'     ).value;
		document.forms[idForm]['NombreViaInt1'].value = document.getElementById('ruta_NombreViaInt1').value;
		document.forms[idForm]['Comuna1'      ].value = document.getElementById('ruta_Comuna1'     ).value;
		document.forms[idForm]['TxtPer1'      ].value = document.getElementById('ruta_TxtPer1'     ).value;
		document.forms[idForm]['TipoVia2'     ].value = document.getElementById('ruta_TipoVia2'    ).value;
		document.forms[idForm]['NombreVia2'   ].value = document.getElementById('ruta_NombreVia2'  ).value;
		document.forms[idForm]['Altura2'      ].value = document.getElementById('ruta_Altura2'     ).value;
		document.forms[idForm]['NombreViaInt2'].value = document.getElementById('ruta_NombreViaInt2').value;
		document.forms[idForm]['Comuna1'      ].value = document.getElementById('ruta_Comuna1'     ).value;
		document.forms[idForm]['TxtPer2'      ].value = document.getElementById('ruta_TxtPer2'     ).value;

		//submit
		document.getElementById(idForm).submit();
	}
}

function CheckRuta(idNombreVia1,idNombreViaInt1, idAltura1, idComuna1, idNombreVia2, idNombreViaInt2, idAltura2, idComuna2)
{
	var calle1		=document.getElementById(idNombreVia1);
	var calleint1	=document.getElementById(idNombreViaInt1);
	var numero1		=document.getElementById(idAltura1);
	var comuna1		=document.getElementById(idComuna1);
	var calle2		=document.getElementById(idNombreVia2);
	var calleint2	=document.getElementById(idNombreViaInt2);
	var numero2		=document.getElementById(idAltura2);
	var comuna2		=document.getElementById(idComuna2);

	if (( calle1.value == "" && numero1.value == "" ) || ( calle1.value == "" && calleint1.value == "" ))
	{
		alert ("Ingrese Direccion o Interseccion de Origen")
		calle1.focus()
		return false
	}

	if (( calle2.value == "" && numero2.value == "" ) || ( calle2.value == "" && calleint2.value == "" ))
	{
		alert ("Ingrese Direccion o Interseccion de Destino")
		calle2.focus()
		return false
	}

	if ( numero1.value != "" )
	{
		if ( ! CheckNum(numero1) )
		{
			alert ("Numero de Origen no valido, ingrese solo numeros");
			numero1.value="";
			numero1.focus();
			return false;
		}
	}

	if ( numero2.value != "" )
	{
		if ( ! CheckNum(numero2) )
		{
			alert ("Numero de Destino no valido, ingrese solo numeros");
			numero2.value="";
			numero2.focus();
			return false;
		}
	}
	CambiaBotonBuscar('bot_buscar02');
	return true;
}

function CheckNum(querynumero)
{
	if ( isNaN(querynumero.value) )
	{
		return false;
	}
	else
	{
		return true
	}
}

function doSubmitSearchTelefono(idForm)
{
	
	AsignaResolucion(document.forms[idForm]);

	if (CheckTelefono('fono_Telefono1'))
	{
		//pasar valores

		document.forms[idForm]['Producto'  ].value = document.getElementById('fono_Producto'  ).value;
		document.forms[idForm]['ciudad'    ].value = document.getElementById('fono_ciudad'    ).value;
		document.forms[idForm]['opcbuscar' ].value = document.getElementById('fono_opcbuscar' ).value;
		document.forms[idForm]['icono'     ].value = document.getElementById('fono_icono'     ).value;
		document.forms[idForm]['icmapa'    ].value = document.getElementById('fono_icmapa'    ).value;
		document.forms[idForm]['icono1'    ].value = document.getElementById('fono_icono1'    ).value;
		document.forms[idForm]['colormapa' ].value = document.getElementById('fono_colormapa' ).value;
		document.forms[idForm]['Telefono1' ].value = document.getElementById('fono_Telefono1' ).value;
		document.forms[idForm]['TxtPer1'   ].value = document.getElementById('fono_TxtPer1'   ).value;
		document.forms[idForm]['idServicio'].value = document.getElementById('fono_IdServicio').value;

		//submit
		document.getElementById(idForm).submit();
	}
}

function CheckTelefono(idTelefono1)
{
	var telefono=document.getElementById(idTelefono1);
	if ( telefono.value == "" )
	{
		alert ("Ingrese Telefono");
		telefono.focus();
		return false;
	}

	if ( !CheckNum(telefono) )
	{
		alert ("Nro. telefono no valido, ingrese solo numeros");
		telefono.value="";
		telefono.focus();
		return false;
	}
	CambiaBotonBuscar('bot_buscar03');
	return true;
}


function verificardatos( formulario)
{

	return false;
	var valor="";
	for ( var i=0;i<formulario.elements.length;i++)
	{
		if ( formulario.elements[i].type == "checkbox" )
		{
			if ( formulario.elements[i].checked )
			{
				Campos=formulario.elements[i].name+'='+formulario.elements[i].value;
				Valor=formulario.elements[i].value;
			}
		}
		else
		{
			if ( formulario.elements[i].type == "radio" )
			{
				if (formulario.elements[i].checked)
				{
					Campos=formulario.elements[i].name+'='+formulario.elements[i].value;
					Valor=formulario.elements[i].value;
				}
			}
			else
			{
				Campos=formulario.elements[i].name+'='+formulario.elements[i].value;
				Valor=formulario.elements[i].value;
			}
		}

		if ( Valor != '' )
			alert(Campos);
	}
	return false;
}

function CambiaBotonBuscar(boton_buscar)
{
	MM_swapImage(boton_buscar,'','/images/botones/bt-buscar_act.gif',1);
	document.MM_sr[0].oSrc = '/images/botones/bt-buscar_act.gif';
	document.MM_sr[0].src = '/images/botones/bt-buscar_act.gif';
	bot_buscar_over = '/images/botones/bt-buscar_act.gif';
}

 var iDelay2 = 800 ;
 var sDisplayTimer2 = null, oLastItem;
 var iNSWidth2 = 100;

 function stopTimer2() {
	 clearTimeout(sDisplayTimer2)
}

function startTimer2(el,a,ico,mapa,otro) {
	stopTimer2();
 /*if (!el.contains(event.toElement)) {*/
 /* alert('empezo el timer');*/
  if(a==1)
  sDisplayTimer2 = setTimeout("showThing1('"+ico+"','"+mapa+"')",iDelay2);
  else if(a==2)
  sDisplayTimer2 = setTimeout("showThing2('"+ico+"','"+mapa+"')",iDelay2);
  else if(a==3)
  sDisplayTimer2 = setTimeout("showThing3('"+ico+"','"+mapa+"','"+otro+"')",iDelay2);
  else if(a==4)
  sDisplayTimer2 = setTimeout("showThing4('"+ico+"','"+mapa+"','"+otro+"')",iDelay2);
  else if(a==5)
  sDisplayTimer2 = setTimeout("showThing5('"+ico+"','"+mapa+"')",iDelay2);
/*}*/
}

function showThing1(ico,mapa) {

	hideIMLayer(ico);MM_showHideLayers(mapa,'','show',ico,'','hide');showIMLayer(mapa); varcerrarmenu[mapa]=false;

}

function showThing2(ico,mapa) {

	hideIMLayer(mapa);MM_showHideLayers(mapa,'','hide',ico,'','show');showIMLayer(ico);varcerrarmenu[ico]=false

}

 function showThing3(destino,origen,mapa){

 	hideIMLayer(destino);hideIMLayer(mapa);MM_showHideLayers(origen,'','show',destino,'','hide');showIMLayer(origen); varcerrarmenu[origen]=false

 }

 function showThing4(destino,origen,mapa){
 	hideIMLayer(origen);hideIMLayer(mapa);MM_showHideLayers(destino,'','show',origen,'','hide');showIMLayer(destino); varcerrarmenu[destino]=false
 }

 function showThing5(mapa,ico){
 MM_showHideLayers(mapa,'','show',ico,'','hide');showIMLayer(mapa); varcerrarmenu[mapa]=false;
}

MM_preloadImages('../images/botones/mapa-ico_clasico-over.gif','../images/botones/mapa-ico_verde-over.gif','../images/botones/mapa-ico_azul-over.gif');



//-->
