var f = document.anunt_imobiliare;
function verifica_anunt_imobiliare(){
//var form = document.anunt_imobiliare;
//alert('ok');

return true;
}

//select
function update_gen(tip,x,y){
// 1 Apartamente
// 2 Case/Vile
// 3 Spatii Birouri
// 4 Spatii Comerciale
// 5 Spatii Industriale
// 6 Terenuri
if(tip == 0){ hide_all();}else{hide_all();show_all();}

if(tip == 1){
$$('div.apartamente').each(function(item){
	item.setStyle('display','block');					   
});	
} //end if Apartamente

if(tip == 2){
$$('div.case').each(function(item){
	item.setStyle('display','block');					   
});	
} //end if Case/Vile

if(tip == 3){
$$('div.birouri').each(function(item){
	item.setStyle('display','block');					   
});	
} //end if birouri

if(tip == 4){
$$('div.comerciale').each(function(item){
	item.setStyle('display','block');					   
});	
} //end if comerciale

if(tip == 5){
$$('div.industriale').each(function(item){
	item.setStyle('display','block');					   
});	
} //end if comerciale

if(tip == 6){
$$('div.terenuri').each(function(item){
	item.setStyle('display','block');					   
});	
} //end if Terenuri

//initialize map
//initializeMap(x,y);
}

function hide_all(){
$$('div.all_imobiliare').each(function(item){
	item.setStyle('display','none');					   
});	
$$('div.all_show').each(function(item){
	item.setStyle('display','block');					   
});	
}

function show_all(){
$$('div.all_show').each(function(item){
	item.setStyle('display','block');					   
});	
$$('div.all_show2').each(function(item){
	item.setStyle('display','block');					   
});	
}

function revealMap(x,y){ initializeMap(x,y);}

//add map
var marker= null;
var map = null;
var geocoder = null;
var pointDone = false;
function initializeMap(x,y,getAdress) {
	
 if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("imo-map"));
    var center = new GLatLng(x,y);
    geocoder = new GClientGeocoder();	
    map.setCenter(center, 7);
	map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());	


  }	

	/*if(getAdress){
		mapAddress();	
	}else{*/
if(!pointDone){
			  marker = new GMarker(new GLatLng(x,y), {draggable: true});
		      GEvent.addListener(marker, "dragstart", function() {
      			map.closeInfoWindow();
   			  });

    		  GEvent.addListener(marker, "dragend", function() {
      		  marker.openInfoWindowHtml("Duma la locatie...");
	  		  //add coordinates
	  		  //processMarkerPosition(marker.getLatLng());
    		 });
			 map.addOverlay(marker);	

pointDone = true;
}
poninttt= x+','+y;
	processMarkerPosition(poninttt);
	//mapAddress();
}

var markerADD = false;

function mapAddress() {
    var a = new Array();

if(document.anunt_imobiliare.strada){
	if(document.anunt_imobiliare.strada.value !='' && document.anunt_imobiliare.strada.value != null) 	a[a.length] =  document.anunt_imobiliare.strada.value;		
	//if(document.anunt_imobiliare.numar.value !='' && document.anunt_imobiliare.numar.value != null) 	a[a.length] =  document.anunt_imobiliare.numar.value;		
	if(document.anunt_imobiliare.judet.value !=0) 	a[a.length] =  document.anunt_imobiliare.judet.value;
}
	
	a[a.length] = 'Romania';
	address = a.join(' , '); 
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
       /* if (!point) {
          document.getElementById('map-status').innerHTML = "Nu a fost gasit locatia [ "+address+" ]";
			  markerADD = true;
			  marker = new GMarker(new GLatLng(45.813486,24.741211), {draggable: true});
		      GEvent.addListener(marker, "dragstart", function() {
      			map.closeInfoWindow();
   			  });

    		  GEvent.addListener(marker, "dragend", function() {
      		  marker.openInfoWindowHtml("Duma la locatie...");
	  		  //add coordinates
	  		  processMarkerPosition(marker.getLatLng());
    		 });
			 map.addOverlay(marker);		  
		  
		  
        } else {*/
          map.setCenter(point, 7);
		  
		  if(!markerADD){
			  markerADD = true;
			  marker = new GMarker(point, {draggable: true});
		      GEvent.addListener(marker, "dragstart", function() {
      			map.closeInfoWindow();
   			  });

    		  GEvent.addListener(marker, "dragend", function() {
      		  marker.openInfoWindowHtml("Duma la locatie...");
	  		  //add coordinates
	  		  processMarkerPosition(marker.getLatLng());
    		 });
			 map.addOverlay(marker);
		  }
	  //add coordinates
	  processMarkerPosition(point);
        //}
      }
    );
  }
}

function processMarkerPosition(coordinates){
	x = explode(',',coordinates);
	document.anunt_imobiliare.latitude.value = str_replace('(','',x[0]); 
	document.anunt_imobiliare.longitude.value = str_replace(')','',x[1]); 	
}


function zoomMap(value){
	z = str_replace('px','',document.getElementById("imo-map").style.height);
if (value=='plus')
height = parseInt(z)+50;
else
height = parseInt(z)-50;

	document.getElementById("imo-map").style.height = height+'px';
    map.setCenter(marker.getLatLng(), 7);	
}

function explode(delimiter,item) {
  tempArray = new Array(1);
  var Count=0;
  var tempString=new String(item);
  
  while (tempString.indexOf(delimiter)>0) {
	tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
	tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1);
	Count=Count+1
  }
  
  tempArray[Count]=tempString;
  return tempArray;
} 

function str_replace(search, replace, subject) {
    var s = subject;
    var ra = r instanceof Array, sa = s instanceof Array;
    var f = [].concat(search);
    var r = [].concat(replace);
    var i = (s = [].concat(s)).length;
    var j = 0;
    
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    }
 
    return sa ? s : s[0];
}

//later

var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function setMarkers(map, locations) {
  // Add markers to the map

  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.

  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.
  var image = new google.maps.MarkerImage('images/beachflag.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(20, 32),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML &lt;area&gt; element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
       // icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }
}

function loadDynamicMap(){
  var script = document.createElement("script");
  script.src = "http://www.google.com/jsapi?key="+mapSettings.api+"&callback=loadAnuntMap";
  script.type = "text/javascript";
  document.getElementsByTagName("head")[0].appendChild(script);
}

function loadAnuntMap() {
  google.load("maps", "2", {"callback" : loadAnuntMapFinal});
}

function loadAnuntMapFinal(){
	
    if(GBrowserIsCompatible()){
                    map = new GMap2(document.getElementById('ad-map'));
					center = new GLatLng(mapSettings.lat,mapSettings.long)
                    map.setCenter(center, mapSettings.zoom);
					map.setMapType(G_SATELLITE_MAP);
                    // add 10 markers to the map at random locations
                    map.addOverlay(new GMarker(center));
 					//createMarker(center,'sdfsdfsdfsd')
					marker = new GMarker(center);
					GEvent.addListener(marker, "click", function() {
					  marker.openInfoWindowHtml('asdasdas');
					});
					// save the info we need to use later for the side_bar

                    // add some simple controls
                    map.addControl(new GLargeMapControl());
                    map.addControl(new GMapTypeControl());
            }	

}

function submit_editeaza(){
	document.anunt_imobiliare.submit();
	return false;	
}

function submit_editeaza_and_close(){
	//alert();
	document.getElementById('redirect').value = 'true';
	document.anunt_imobiliare.submit();
	return false;	
}

function save_and_close(){
	//alert();
	document.getElementById('redirect').value = 'true';
	document.anunt_imobiliare.submit();
	return false;	
}

function update_inbunatatiri(nr){
	var atr = new Array();;
	for(i=1;i<=nr;i++){
		
		if($('inbunatatiri_'+i).checked)
			atr[atr.length]=$('inbunatatiri_'+i).value+'-1';
			else
			atr[atr.length]=$('inbunatatiri_'+i).value+'-0';			
			
	}
	$('inbunatatiri').value = atr; 
}

function update_utilitati(nr){
	var atr = new Array();;
	for(i=1;i<=nr;i++){
		
		if($('utilitati_'+i).checked)
			atr[atr.length]=$('utilitati_'+i).value+'-1';
			else
			atr[atr.length]=$('utilitati_'+i).value+'-0';			
			
	}
	$('utilitati').value = atr; 
}

function getAnuntPersoana(obj){
  if(obj.value == 'fizica' && obj.checked){ 
	  $('societate_div').setStyle('display','none'); 
	  $('societate').value='';
	  }else{
		  $('societate_div').setStyle('display','block'); 
  }
}

function addSuprafata(name1,name2,value1,value2){
	var div = new Element('div');
	var nrSup = document.getElementById('nr_sup_camere').value;
	div.id = 'sup-'+nrSup;
	div.innerHTML = '<label>'+name1+' </label><input onBlur="javascript:updateSuprafata()" class="input_anunturi" type="text" name="sup_camere_titlu_'+nrSup+'" id="sup_camere_titlu_'+nrSup+'" value="'+value1+'"/><label> '+name2+' </label><input class="input_anunturi" style="width:50px" type="text" name="sup_camere_valoare_'+nrSup+'" id="sup_camere_valoare_'+nrSup+'" value="'+value2+'" onBlur="javascript:updateSuprafata()" onkeypress="javascript:return isNumeric(event)"/><a href="javascript:void(0)" onclick="javascript:deleteSuprafata('+nrSup+')" rel="nofollow"><img src="/images/delete-suprafata.png" alt="sterge"/></a>';
	
	document.getElementById('sup_posibile').value +=','+nrSup;	
	document.getElementById('nr_sup_camere').value = parseFloat(nrSup) + 1;
	document.getElementById('sup_camere_container').appendChild(div);
	updateSuprafata();
}

function deleteSuprafata(nr){
	var obj = document.getElementById("sup-"+nr);
	document.getElementById('sup_camere_container').removeChild(obj);
	document.getElementById('sup_posibile').value = str_replace(','+nr,'',document.getElementById('sup_posibile').value);
	updateSuprafata();
}

function updateSuprafata(){
	var suprafete = document.getElementById('sup_posibile').value;
	var nrCamere = explode(',',suprafete);
	var camere = '';
	for(i=0;i<nrCamere.length;i++){
		camere+= document.getElementById('sup_camere_titlu_'+nrCamere[i]).value+'-'+document.getElementById('sup_camere_valoare_'+nrCamere[i]).value+'/';
	}
	document.getElementById('sup_camere').value = camere;
}


function isNumeric(value){
	return true;
	//de terminat;
	//alert(value);
	var numericExpression = /^[0-9]+$/;
	if(value.match(numericExpression)){
		return true;
	}else{
		return false;
	}
}

function addPretAndMP(value){
	sup_teren = parseInt(document.getElementById('sup_teren').value);
	sup_totala = parseInt(document.getElementById('sup_totala').value);	
	tip_anunt = parseInt(document.getElementById('tip_anunt').value);	
	if( sup_teren > 0 || sup_totala > 0){
	
	  if(value == 1){
		  pret = parseInt(document.getElementById('pret').value);
		  if(tip_anunt == 6) pretMP = pret/sup_teren;
		  if(tip_anunt == 3 || tip_anunt == 4 || tip_anunt == 5 ) pretMP = pret/sup_totala;		  
		  document.getElementById('pret_mp').value = roundNumber(pretMP,2);
	  }else{
		  pretMP = parseInt(document.getElementById('pret_mp').value);	
		  if(tip_anunt == 6) pret = pretMP*sup_teren;
		  if(tip_anunt == 3 || tip_anunt == 4 || tip_anunt == 5 ) pret = pretMP*sup_totala;			  
		  document.getElementById('pret').value = roundNumber(pret,2);		
	  }
	}

}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

var vitrinaON = false;
function changeVitrina(){
	if(vitrinaON){ 
		document.getElementById('vitrina').style.visibility = 'hidden';
		document.getElementById('vitrina').value= '';
		vitrinaON = false; 
		}else{ 
		document.getElementById('vitrina').value= 'Deschidere (m)';
		document.getElementById('vitrina').style.visibility = 'visible';		
		vitrinaON = true;}
	
	//alert(vitrinaON);
	
}

var sliderOpenStatus =  false;
function update_model_result(http){ $('model1').innerHTML = http.responseText;}
// check search
function check_imo_search(){
	
return true;	
}
//update search fields
function update_imo_tip(val){

}

var advancedSlide = null;

window.addEvent('domready', function(){
	advancedSlide = new Fx.Slide('hiddenSlider');
	advancedSlide.addEvent('onStart', function() {showMyLoading();});
	advancedSlide.addEvent('onComplete', function() {showMyLoading();});	
	advancedSlide.hide();
	$('hiddenSlider').setStyle('display','block');
	
	$('sliderButton').addEvent('click', function(e){
		e = new Event(e);
		if(openStatus){ openStatus = false; }else{ openStatus = true; }
		advancedSlide.toggle();
		e.stop();
	});
});

var openStatus = false;      
function drop_advanced_search(id){
	
	if(!openStatus){
		//modifica
		advancedSlide.toggle();
		search_do(id);			
		openStatus = true;
	}else{
			advancedSlide.toggle();
			//modifica
			search_do(id);	
					
			setTimeout('advancedSlide.toggle()',1000);
		    //openStatus = false;
	}
}

function drop_default_search(){
	if(!openStatus){
		//modifica
		advancedSlide.toggle();
		search_do(0);			
		openStatus = true;
	}
}

var closeSearch = true;
var loadingSearch = false;
function showMyLoading(){
    if(closeSearch){
		$('imo-search-loading').setStyle('display','block');
		closeSearch = false;
	}else { closeSearch = true;$('imo-search-loading').setStyle('display','none'); }
}

/*
<option value="1">Apartamente</option>
<option value="2">Case/Vile</option>
<option value="3" selected="selected">Spatii Birouri</option>
<option value="4">Spatii Comerciale</option>
<option value="5">Spatii Industriale</option>
<option value="6">Terenuri</option>   
<option value="0">Toate</option>           
*/
function search_do(id){

$('s-asezare-urbanistica').setStyle('display','none');
$('s-suprafata-teren').setStyle('display','none');
$('s-stadiu-constructie').setStyle('display','none');
$('s-etaj').setStyle('display','none');
$('s-etajare').setStyle('display','none');
$('s-asezare').setStyle('display','none');
$('s-amplasare').setStyle('display','none');
$('s-confort').setStyle('display','none');
$('s-suprafata-utila').setStyle('display','none');
$('s-nr-camere').setStyle('display','none');
$('s-an').setStyle('display','none');

//apartamente
if(id==1){
	$('s-nr-camere').setStyle('display','block');
	$('s-suprafata-utila').setStyle('display','block');	
	$('s-confort').setStyle('display','block');
	$('s-amplasare').setStyle('display','block');
	$('s-etajare').setStyle('display','block');
	$('s-etaj').setStyle('display','block');
	$('s-an').setStyle('display','block');
	$('s-asezare').setStyle('display','block');	
}
//case/vile
if(id==2){
	$('s-stadiu-constructie').setStyle('display','block');
	$('s-an').setStyle('display','block');
}
//terenuri
if(id==6){
	$('s-asezare-urbanistica').setStyle('display','block');
	$('s-suprafata-teren').setStyle('display','block');	
}
	
}

function anuntOver(obj){
	obj.className = 'anunt_container_over';
}

function anuntOut(obj){
	obj.className = 'anunt_container';
}
var imoForm = document.searchForm;
function resetAllFields(){alert('OK')}


function generalSelectCheck(obj,val1,val2,errorMSG){
	if(parseFloat(val1) > parseFloat(val2)){
		alert(errorMSG);
		obj.selectedIndex = 0;			
	}
}

function generalInputCheck(obj,val1,val2,errorMSG,maxValue){
	if(parseFloat(val1) > parseFloat(val2)){
		alert(errorMSG);
		obj.value = maxValue;			
	}
}
