function initialize() {
	
}

function IsNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++) 
	  { 
	  Char = sText.charAt(i); 
	  if (ValidChars.indexOf(Char) == -1) 
		 {
		 IsNumber = false;
		 }
	  }
	return IsNumber;
   
}

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/
 
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function getRadioButtonSelectedValue(ctrl) {
	for (i=0; i<ctrl.length; i++) {
        if (ctrl[i].checked){
            return(ctrl[i].value);
         }
    }
}

function getSelectSelectedValue(ctrl){ 
   	var indice = ctrl.selectedIndex ;
	var valor = ctrl.options[indice].value ;
	return(valor);
} 


function jsSearch(pageNumber) {
 	//var precio = trim(document.getElementById('precio-maximo').value);
	var precio = "";
	var operacion = getRadioButtonSelectedValue(document.getElementById('buscador').condicion);
	var propiedad = getSelectSelectedValue(document.getElementById('tipoI')); 
	//var vendedor = getSelectSelectedValue(document.getElementById('tipoV')); 
	var vendedor = 'T';
	if(propiedad != 'CS'){
		var dorm = getSelectSelectedValue(document.getElementById('dormN'));
	}
	if(propiedad == 'CS'){
		var dorm = getSelectSelectedValue(document.getElementById('dormN-casas'));
	}  
	
	if(precio != "" && !(IsNumeric(precio)) ){
		alert("El precio máximo debe ser numérico");
		document.getElementById('precio-maximo').focus();
		document.getElementById('precio-maximo').select();
		return;
	}  
	//return xajax_ajxDoSearch(operacion,propiedad,vendedor,null,precio,dormitorios,pageNumber);
	$("#divDestacados").hide('slow');
	$("#divResultados").hide('slow');
	return xajax_ajxDoSearch(operacion,propiedad,vendedor,precio,dorm,pageNumber);
	
}		

function jsSearchSaloon(pageNumber) {
	var operacion = getRadioButtonSelectedValue(document.getElementById('buscadorSaloon').condicion);
	var propiedad = getSelectSelectedValue(document.getElementById('tipoIS')); 
	return xajax_ajxDoSearch(operacion,propiedad,pageNumber);
}

function loadPano(vtourdir) {
	if (typeof(deconcept) !== 'undefined' && deconcept.SWFObjectUtil.getPlayerVersion().major >= 6)
		{
			var so = new SWFObject("/krpano/krpano.swf", "krpanoSWFObject", "100%", "500", "9.0.28","#000000");
			so.addParam("allowFullScreen","true");
			so.addVariable("pano", "/vtours/" + vtourdir + "/01.xml");
			so.addVariable("onstart","set(autorotate.enabled,true);");
			so.useExpressInstall("krpano/swfobject/expressinstall.swf");
			so.setAttribute("xiRedirectUrl", window.location);
			if ( so.write("pano-salon") ) { var mousewheelfixes = new SWFkrpanoMouseWheel(so); }
		}
		else{
			document.getElementById("pano-salon").innerHTML = '<table width="100%" height="100%"><tr valign="middle"><td><center>ERROR:<br><br>Adobe Flash Player 9 needed<br><br><br><a href="http://www.adobe.com/go/getflashplayer/"  target="_blank"><IMG SRC="http://www.macromedia.com/images/shared/download_buttons/get_flash_player.gif" BORDER="1"></a><br>...click here to download...<br><br><br><br></center></td></tr></table>';
		}
}

function loadSlider() {

    var $panels = $('#slider .scrollContainer > div');
    var $container = $('#slider .scrollContainer');

    // if false, we'll float all the panels left and fix the width 
    // of the container
    var horizontal = true;

    // float the panels left if we're going horizontal
    if (horizontal) {
        $panels.css({
            'float' : 'left',
            'position' : 'relative' // IE fix to ensure overflow is hidden
        });

        // calculate a new width for the container (so it holds all panels)
        $container.css('width', $panels[0].offsetWidth * $panels.length);
    }

    // collect the scroll object, at the same time apply the hidden overflow
    // to remove the default scrollbars that will appear
    var $scroll = $('#slider .scroll').css('overflow', 'hidden');

    // apply our left + right buttons
    $scroll
        .before('<img class="scrollButtons left" src="../../img/prevOff.png" onmouseover="this.src=\'../../img/prevOff.png\'" onmouseOut="this.src=\'../../img/prevOff.png\'" />')
        .after('<img class="scrollButtons right" src="../../img/nextOff.png" onmouseover="this.src=\'../../img/nextOff.png\'" onmouseOut="this.src=\'../../img/nextOff.png\'" />');

    // handle nav selection
    function selectNav() {
        $(this)
            .parents('ul:first')
                .find('a')
                    .removeClass('selected')
                .end()
            .end()
            .addClass('selected');
    }

    $('#slider .navigation').find('a').click(selectNav);

    // go find the navigation link that has this target and select the nav
    function trigger(data) {
        var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
        selectNav.call(el);
    }

    if (window.location.hash) {
        trigger({ id : window.location.hash.substr(1) });
    } else {
        $('ul.navigation a:first').click();
    }

    // offset is used to move to *exactly* the right place, since I'm using
    // padding on my example, I need to subtract the amount of padding to
    // the offset.  Try removing this to get a good idea of the effect
    var offset = parseInt((horizontal ? 
        $container.css('paddingTop') : 
        $container.css('paddingLeft')) 
        || 0) * -1;


    var scrollOptions = {
        target: $scroll, // the element that has the overflow

        // can be a selector which will be relative to the target
        items: $panels,

        navigation: '.navigation a',

        // selectors are NOT relative to document, i.e. make sure they're unique
        prev: 'img.left', 
        next: 'img.right',

        // allow the scroll effect to run both directions
        axis: 'xy',

        onAfter: trigger, // our final callback

        offset: offset,

        // duration of the sliding effect
        duration: 500,

        // easing - can be used with the easing plugin: 
        // http://gsgd.co.uk/sandbox/jquery/easing/
        easing: 'swing'
    };

    // apply serialScroll to the slider - we chose this plugin because it 
    // supports// the indexed next and previous scroll along with hooking 
    // in to our navigation.
    $('#slider').serialScroll(scrollOptions);

    // now apply localScroll to hook any other arbitrary links to trigger 
    // the effect
    $.localScroll(scrollOptions);

    // finally, if the URL has a hash, move the slider in to position, 
    // setting the duration to 1 because I don't want it to scroll in the
    // very first page load.  We don't always need this, but it ensures
    // the positioning is absolutely spot on when the pages loads.
    scrollOptions.duration = 1;
    $.localScroll.hash(scrollOptions);
}

/*
function muestra_cargando(){
	document.getElementById('divResultados').innerHTML = " ";
  	xajax.$('load').innerHTML='<img src="img/ajax-loader2.gif" alt="cargando..." width="64" height="64" border="0">';
}

function oculta_cargando(){
	xajax.$('load').innerHTML='';
}
   
xajax.callback.global.onResponseDelay = muestra_cargando;
xajax.callback.global.onComplete = oculta_cargando; */

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
	if(!radioObj) {
		return;
	} 
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function habilitarDormitoriosymas(type) {
	switch (type) {
		case 'CS':
			document.getElementById('dormitorios-casas').style.visibility = "visible";
			//document.getElementById('distritos').style.visibility = "visible";
			document.getElementById('dormitorios').style.visibility = "hidden";
			break;
		case 'DP':
			document.getElementById('dormitorios').style.visibility = "visible";
			document.getElementById('dormitorios-casas').style.visibility = "hidden";
			break;
		default:
			document.getElementById('dormitorios').style.visibility = "hidden";
			//document.getElementById('distritos').style.visibility = "hidden";
			document.getElementById('dormitorios-casas').style.visibility = "hidden";

	}
	
	switch (type) {
		case 'IV':
			setCheckedValue(document.forms['formbuscqueda'].elements['condicion'], 'V');
			break;
		default:
			break;
	}
}

function initializeSearchMap(points) {

      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("search-map"));
		
        // Create a base icon for all of our markers that specifies the
        // shadow, icon dimensions, etc.
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        //baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
       // baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
		
		// Creates a marker at the given point
		// Clicking the marker will hide it
		function createMarker(latlng, desc,id) {
          var vvfIcon = new GIcon(baseIcon);
          vvfIcon.image = "http://www.viviendafe.com.ar/img/gmap-icon.png";
          // Set up our GMarkerOptions object
          markerOptions = { icon:vvfIcon };
		  
		  var marker = new GMarker(latlng, markerOptions);
		  marker.value = desc;
		  GEvent.addListener(marker,"click", function() {
			var myHtml = desc + "</br> <a href=publicacion.php?id_publicacion=" + id +" target=blank>+ info </a>";
			map.openInfoWindowHtml(latlng, myHtml);
		  });
		  return marker;
		}

	var point;
	var centro_lat = 0;
	var centro_long = 0;
	for (i =0;i<points.length;i++){ 
	  point = new GLatLng(points[i][0],points[i][1]);
	  map.addOverlay(new createMarker(point,points[i][2],points[i][3]));
	  
	  centro_lat = centro_lat + points[i][0];
	  centro_long = centro_long + points[i][1];
	  }
	  
	  //(points.length-1) : the -1 is because there is a fake point at the end (0,0)
	//map.setCenter(new GLatLng(centro_lat/(points.length-1), centro_long/(points.length-1)), 13);
    map.setCenter(new GLatLng(-31.632337053668714, -60.699462890625), 13);
	map.addControl(new GSmallMapControl());
	//TODO: make a best center selection. distant points make a nonsense center point

      }
        
}

function jsSearchMap() {
 	//var precio = trim(document.getElementById('precio-maximo').value);
	var precio = '';
	var operacion = getRadioButtonSelectedValue(document.getElementById('buscador').condicion);
	var propiedad = getSelectSelectedValue(document.getElementById('tipoI')); 
	//var vendedor = getSelectSelectedValue(document.getElementById('tipoV')); 
	var vendedor = 'T';
	if(propiedad == 'DP'){
		var dorm = getSelectSelectedValue(document.getElementById('dormN'));
	}
	if(propiedad == 'CS'){
		var dorm = getSelectSelectedValue(document.getElementById('dormN-casas'));
	}   
	

	return xajax_ajxDoSearchMap(operacion,propiedad,vendedor,precio,dorm);
}
