var dialog_open = false;
var save_search_dialog = false;
var count_tabs = 1;
var tap1 = false;
var tap2 = false;
var tap3 = true;
var tap4 = false;
var tap5 = false;
var agent_property = 0; //var global for agent
var load_agent; //var for abort
var load_prop_prev; //var for abort
var msg_agent; //var for abort
$(function() {
	// Fix for Main Menu in IE
	$("#navmenu-h li,#navmenu-v li").hover( function() {
		$(this).addClass("iehover");
	}, function() {
		$(this).removeClass("iehover");
	});	
});

$(function() {

	if (typeof CookiesEnabled == 'function') {
		CookiesEnabled();
	}

	if($('#LeadTelephone1') && isVisible($('#LeadTelephone1'))){
		$('#LeadTelephone1').focus();
	}
	
	if (typeof loadMaps == 'function') {
		loadMaps();
	}
});

function JsCounty(county_id, params) {
	
	var main_container = $('#MainContainer'+county_id);
	var div_container = $('#ResultsContainer'+county_id);
	var hidden = $('#OpenedCounty' + county_id);
	var cross = $('#Cross' + county_id);
	
	main_container.attr("className", "");		

	if (hidden.val() != 1) {

		div_container.html('<div style="margin-left: 100px;color:#000;"><img src="/property_search/img/icons/ajax-loader.gif" style="margin-right:10px;margin-top:-7px;">Loading...</div>');
		main_container.show();

		var url = '/properties/search_county/?county=' + county_id + '&' + params;
		
		if ($('#CountyCheckbox'+county_id).attr("checked")){
			url += '&cas2=1';
		}	

		cross.html('<img src="/property_search/img/layout/top_line.jpg" />');		
		div_container.load(url, {}, function() {});
		hidden.val(1);

	} else {
		
		main_container.hide();
		cross.html('<img src="/property_search/img/icons/cross.jpg" />');
		hidden.val(0);
	}
}

function getOpenedCounties(element_id){

	var counties = '';
	
	if ($("#" + element_id).length > 0) {

		$("#" + element_id + " input:checkbox").each(
			function() {
				
				if (this.name == 'county'){					
					
					if($('#OpenedCounty'+this.value).val()==1){
						counties += this.value + ',';
					}	
				}	
			});

		counties = counties.substr(0, counties.length - 1);
	}
	
	return counties;	
}

function JsSearchState() {

	if(!$("#StateId")){ 
		return false;
	}	
	
	if(!$("input[@name=ltype]:checked")){
		return false;
	}	
	
	var state_id = $("#StateId").val();
	var ltype = $("input[@name=ltype]:checked").val();

	if (state_id == '') {		

		$("#StateId").focus();

	} else {

		var url = '/properties/advanced_search?ltype=' + ltype + '&state=' + state_id;
		$(document.location).attr("href", url);
	}
}

function JsSearchStateList(id) {
	
	// var ltype = $("input[@name=ltype_checkbox]:checked").val();
	var ltype = $("#ltype").val();	
	var reo = $("#reo").val();
	var ss = $("#ss").val();

	var url = '/properties/advanced_search?ltype=' + ltype + '&state=' + id + '&reo=' + reo + '&ss=' + ss;
	$(document.location).attr("href", url);
}

function JsvalorP(pestana) {
	// var pestana = pestana;
}

/*
 * Returns the number of tab selected in the form
 * 
 */

function getSelectedTab() {

	var selected = 1;
	var count = 1;

	$('#tab-container-1-nav').find('li').each( function() {

		if ($(this).attr("class") == 'activeli') {

			selected = count;
		}

		count++;
	});

	return selected;
}

/*
 * Perform the needed actions to redirect to the url search
 * 
 */
 
function showRegister(is_second){
	
	$("#register").dialog('open');
	if(is_second==1){
		$('#CloseRegisterDialog').hide();
		
	}
} 
function changeSignIn(){
	//change to register
	$("#register_left_login").hide();
	$("#register_right_signin").show();
	$("#acc_chang_text").html("Alredy have an account?");
	$(".social_network_text").html("Join");
	$("#chage_register_title").html("<a href='#' class='green_text'>Sign In</a> <span class='big_text'>/ Join</span>")
	registerFlag = 1;
}

/*  openRegisterStep2
 ** This function opens the steap 2 at will
 ** firs open the register and then inmediatly changes to step 2
 **/
function openRegisterStep2(){
	$("#register").mask("Loading...");
	$("#register").load("/leads/register_step2/", function(){
		$("#register").unmask();
	});
	showRegister(1);	
	
}
/* function openGoogle
 * This function opens the window to allow a lead login by google
 **/
function openGoogle(){
	var vals = window.location.href;
	vals = vals.replace('http://', '');
	vals = vals.replace(/#/g, '');
	//this is a little trick to replace slashes ( / with _diagonal_ ) because its getting conflict with google (later we will convert them back to / )
	vals = vals.replace(/\//g, '_diagonal_');
	vals = vals.replace(/&/g, '_amp_');
	window.open('/users/login_openid/?c_url='+vals+'&prop_id='+$('#prop_id').val()+'&ltype='+$('#LeadLtype').val(), 'GmailLogin', 'width=300,height=400');
	return false;
}
/*
$(document).ready(function() {
	$(".sell_your_home_img").click(function() {
		openRegisterStep2();
	});
});
*/
function JsSearchAll() {

	var selected_tab = getSelectedTab();
	var parameters = parseParameters();
	var url = buildSearchUrl(parameters, selected_tab);
	
	switch (selected_tab) {

		case 1: {
	
			// Search by Location
			if (url.length > 0) {
				$("#searching-modal").modal();
				$(document.location).attr("href", url);
			}
			break;
		}
	
		case 2: {
	
			// Search by Zip Code
			var tipo=$('#tipo').val();
			// alert(tipo);
			if(tipo==1){
				
				if (url.length > 0) {
					$("#searching-modal").modal();
					$(document.location).attr("href", url);
				}
				break;
				
				
				
				
		}else{
			
			if (url.length > 0) {
					$("#searching-modal").modal();
					var zip = parameters.property_zip;
					var ltype=$('#ltype').val();
					var reo=$('#reo').val();				
					var ss=$('#ss').val();					
					var url = '/properties/search/?ltype=' + ltype + '&reo='+ reo+ '&ss='+ ss+ '&zip='+ zip;			
					// alert(url);
					$(document.location).attr("href", url);
				}
				break;
			
			}
			
			
			
		}

		case 3: {
	
			// Search by ID or MLS
			if ($('#PropertyId').val() != '' || $('#PropertyMlsId').val() != '') {
				$("#searching-modal").modal();
				$("#SearchByIdForm").submit();
			} else {
				alert('You must enter either the ID or MLS');
			}
			break;
		}
	}
}

/*
 * Parse form parameters to an object
 * 
 */
 
function parseParameters() {

	var parameters = {};

	if ($('#state').length != 0)
		parameters.state = $("#state").val();
	else
		parameters.state = '';

	if ($("input[@name=ltype]:checked").length != 0)
		parameters.ltype = $("input[@name=ltype]:checked").val();		
		
	else
		parameters.ltype = '';	
	
	if ($("#PropertyHtype").length != 0)
		parameters.property_htype = $("#PropertyHtype").val();
	else
		parameters.property_htype = '';

	if ($("#PropertyPmin").length != 0)
		parameters.property_pmin = $("#PropertyPmin").val();
	else
		parameters.property_pmin = '';

	if ($("#PropertyPmax").length != 0)
		parameters.property_pmax = $("#PropertyPmax").val();
	else
		parameters.property_pmax = '';

	if ($("#PropertyBeds").length != 0)
		parameters.property_beds = $("#PropertyBeds").val();
	else
		parameters.property_beds = '';

	if ($("#PropertyBaths").length != 0)
		parameters.property_baths = $("#PropertyBaths").val();
	else
		parameters.property_baths = '';

	if ($("#PropertySqft").length != 0)
		parameters.property_sqft = $("#PropertySqft").val();
	else
		parameters.property_sqft = '';

	if ($("#PropertyZip").length != 0)
		parameters.property_zip = $("#PropertyZip").val();
	else
		parameters.property_zip = '';

	if ($("#PropertyPhoto").length != 0)
		parameters.property_photo = document.getElementById('PropertyPhoto').checked;
	else
		parameters.property_photo = '';
	
	if ($("#PropertyReduced").length != 0)
		parameters.property_reduced = document.getElementById('PropertyReduced').checked;
	else
		parameters.property_reduced = '';		
	
	if ($("#PropertyNew").length != 0)
		parameters.property_new = document.getElementById('PropertyNew').checked;
	else
		parameters.property_new = '';		
		
	parameters.property_ss = false;
	parameters.property_bo = false;

	switch (parameters.ltype) {

		case '3': {
			parameters.reo = true;
			break;
		}
		case '4': {
			parameters.ss = true;
			break;
		}
		default:{			
			parameters.reo = false;
			parameters.ss = false;
			
			if ($("#PropertySs").length != 0)
				parameters.property_ss = document.getElementById('PropertySs').checked;
			else
				parameters.property_ss = false;

			if ($("#PropertyBo").length != 0)
				parameters.property_bo = document.getElementById('PropertyBo').checked;
			else
				parameters.property_bo = false;
			
			break;	
		}
	}

	return parameters;
}

/*
 * Gets a list of selected counties in the form
 * 
 */

function getSelectedCounties(element_id) {

	var counties = '';

	if ($("#" + element_id).length > 0) {

		$("#" + element_id + " input[@type=checkbox]:checked").each(
				function() {
					if (this.name == 'county')
						counties += this.value + ','
				});

		counties = counties.substr(0, counties.length - 1);
	}

	return counties;
}

/*
 * Gets a list of selected cities in the form
 * 
 */

function getSelectedCities(element_id) {

	var cities = '';

	if ($("#" + element_id).length > 0) {

		$("#" + element_id + " input[@type=checkbox]:checked").each(
				function() {
					if (this.name == 'city')
						cities += this.value + ','
				})

		cities = cities.substr(0, cities.length - 1);
	}

	return cities;
}

/*
 * Builds the URL to do the search
 * 
 */

function buildSearchUrl(parameters, selected_tab) {

	var url = '';

	switch (selected_tab) {

		case 1: {
	
			// Search by City/Area
			var counties = getSelectedCounties("county");
			var cities = getSelectedCities("city");
	
			if (counties.length > 0 || cities.length > 0) {
	
				url = '/properties/search?';
				
				if (counties.length > 0)
					url += 'county=' + counties + '&';
				
				if (cities.length > 0)
					url += 'city=' + cities + '&';
								
				if (parameters.ltype.length > 0){
				
					switch (parameters.ltype) {
						case '3': {
							url += 'ltype=1&reo=1&';
							break;
						}
						case '4': {
							url += 'ltype=1&ss=1&';
							break;
						}
						default:{
							url += 'ltype=' + parameters.ltype + '&';
							break;
						}
					}	
				}	
								
				if (parameters.state.length > 0)
					url += 'state=' + parameters.state + '&';
				if (parameters.property_htype.length > 0)
					url += 'htype=' + parameters.property_htype + '&';
				if (parameters.property_pmin.length > 0)
					url += 'pmin=' + parameters.property_pmin + '&';
				if (parameters.property_pmax.length > 0)
					url += 'pmax=' + parameters.property_pmax + '&';
				if (parameters.property_beds.length > 0)
					url += 'beds=' + parameters.property_beds + '&';
				if (parameters.property_baths.length > 0)
					url += 'baths=' + parameters.property_baths + '&';
				if (parameters.property_sqft.length > 0)
					url += 'sqft=' + parameters.property_sqft + '&';
				if (parameters.property_photo)
					url += 'photo=1&';
				if (parameters.property_reduced)
					url += 'reduced=1&';
				if (parameters.property_new)
					url += 'new=1&';				
				if (parameters.property_ss)
					url += 'no_ss=1&';
				if (parameters.property_bo)
					url += 'no_reo=1&';
				
			} else {
	
				alert('You must select a location');
			}
	
			break;
		}
	
		case 2: {
	
			// Search By ZipCode
			if (isValidZipString(parameters.property_zip)) {
	
				if (parameters.property_zip.length > 0) {
	
					url = '/properties/search?';

					if (parameters.ltype.length > 0){
						
						switch (parameters.ltype) {
							case '3': {
								url += 'ltype=1&reo=1&';
								break;
							}
							case '4': {
								url += 'ltype=1&ss=1&';
								break;
							}
							default:{
								url += 'ltype=' + parameters.ltype + '&';
								break;
							}
						}	
					}
					
					if (parameters.state.length > 0)
						url += 'state=' + parameters.state + '&';
					if (parameters.property_htype.length > 0)
						url += 'htype=' + parameters.property_htype + '&';
					if (parameters.property_pmin.length > 0)
						url += 'pmin=' + parameters.property_pmin + '&';
					if (parameters.property_pmax.length > 0)
						url += 'pmax=' + parameters.property_pmax + '&';
					if (parameters.property_beds.length > 0)
						url += 'beds=' + parameters.property_beds + '&';
					if (parameters.property_baths.length > 0)
						url += 'baths=' + parameters.property_baths + '&';
					if (parameters.property_sqft.length > 0)
						url += 'sqft=' + parameters.property_sqft + '&';
					if (parameters.property_zip.length > 0)
						url += 'zip=' + parameters.property_zip + '&';
					if (parameters.property_photo)
						url += 'photo=1&';
					if (parameters.property_reduced)
						url += 'reduced=1&';
					if (parameters.property_new)
						url += 'new=1&';					
					if (parameters.reo)
						url += 'reo=1&';
					if (parameters.ss)
						url += 'ss=1&';
					if (parameters.property_ss)
						url += 'no_ss=1&';
					if (parameters.property_bo)
						url += 'no_reo=1&';
					
				} else {
	
					alert('Enter a Zip Code');
				}
			} else {
	
				alert("You must enter zipcode numbers separated by commas");
			}
	
			break;
		}
	}
	
	return url;
}

/*
 * Determines if a string is a valid formated zip code
 * 
 */

function isValidZipString(zip_code) {

	var strings = new Array();
	strings = zip_code.split(',');
	no = strings.length;

	for (x in strings) {

		var string = strings[x];
		string = string.replace(" ", "");

		if (!isNumeric(string)) {

			return false;
		}
	}

	return true;
}

/*
 * Determines if a string has only numeric values
 * 
 */

function isNumeric(string) {

	var valid_chars = "0123456789.";
	var is_number = true;
	var char;

	for (i = 0; i < string.length && is_number == true; i++) {

		char = string.charAt(i);

		if (valid_chars.indexOf(char) == -1)
			is_number = false;
	}

	return is_number;
}

/*
 * 
 * Updates search list based on selected form params
 * 
 */

function updatePrices(ltype){
	
	if(ltype==2){
		
		$("#PropertyPmin").html($("#PropertyRentPriceMinValues").html());
		$("#PropertyPmax").html($("#PropertyRentPriceMaxValues").html());			
	}
	else{
		
		$("#PropertyPmin").html($("#PropertySalePriceMinValues").html());
		$("#PropertyPmax").html($("#PropertySalePriceMaxValues").html());			
	}	
}


function updateList(update_prices) {	

	var opened_counties = getOpenedCounties('county');

	// Show modal window while new search list is loaded
	// $("#updating-modal").modal();

	// Get selected params
	var parameters = parseParameters();
	var url = '/properties/search_state?';

	// Get selected localities
	var counties = getSelectedCounties("county");
	var cities = getSelectedCities("city");
	
	// Build URL
	if (opened_counties.length > 0)
		url += 'show_counties=' + opened_counties + '&';	
	if (counties.length > 0)
		url += 'selected_counties=' + counties + '&';
	if (cities.length > 0)
		url += 'selected_cities=' + cities + '&';
	
	if (parameters.ltype.length > 0){
		
		if(update_prices){
							
			if(parameters.ltype==2){
				
				parameters.property_pmin = 1000;
				parameters.property_pmax = 0;
			}
			else{
				
				parameters.property_pmin = 75000;
				parameters.property_pmax = 0;
			}	
		}

		switch(parameters.ltype){
			
			case '1':{				
				url += 'ltype=' + parameters.ltype + '&';
				$("#ForSaleOptions").show();
				break;
			}
			case '2':{
				url += 'ltype=' + parameters.ltype + '&';
				$("#ForSaleOptions").hide();				
				break;
			}
			case '3':{
				url += 'ltype=1&reo=1&';
				$("#ForSaleOptions").hide();				
				break;
			}
			case '4':{
				url += 'ltype=&ss=1&';
				$("#ForSaleOptions").hide();				
				break;
			}			
			default: {				
				url += 'ltype=' + parameters.ltype + '&';
				$("#ForSaleOptions").hide();
				break;
			}
		}
	}	
	if (parameters.property_htype)
		url += 'htype=' + parameters.property_htype + '&';
	if (parameters.property_pmin)
		url += 'pmin=' + parameters.property_pmin + '&';
	if (parameters.property_pmax)
		url += 'pmax=' + parameters.property_pmax + '&';
	if (parameters.property_beds)
		url += 'beds=' + parameters.property_beds + '&';
	if (parameters.property_baths)
		url += 'baths=' + parameters.property_baths + '&';
	if (parameters.property_sqft)
		url += 'sqft=' + parameters.property_sqft + '&';
	if (parameters.property_photo)
		url += 'photo=1&';
	if (parameters.property_reduced)
		url += 'reduced=1&';			
	if (parameters.property_new)
		url += 'new=1&';			
	
	
	$('#tab1').html('<div class="loader" style="margin-top:10px;"></div> <div style="font-weight:bold;margin-left:180px;">Loading ...</div>');

	// Refresh search list
	$('#tab1').load(url, function() {
		// close modal window
		// $.modal.close();
	});
}


function JsSaveSearch() {
	
	if (!save_search_dialog) {

		$("#dialog").dialog( {modal :true,title :'Save this Search',width :500,resizable: false,draggable: false});
		save_search_dialog = true;
	} else {
		
		$("#dialog").dialog('open', {modal :true,title :'Save this Search',width :500,resizable: false,draggable: false});
	}
}

/*
 * function JsSaveSearch(){ alert('entra') if(!dialog_open) {
 * 
 * $("#search-dialog").dialog({modal:true,title:'Save this Search',width:500});
 * dialog_open = true; } else{
 * $("#search-dialog").dialog('open',{modal:true,title:'Save this
 * Search',width:500}); } }
 */

/*
 * function JsSearchFavorite(url){
 * 
 * var notify=$('#notify').attr('checked'); var name=$("#name").val(); var
 * keyid=$("#key_search").val();
 * 
 * if(notify==true){notify=1;} if(notify==false){notify=0;}
 * 
 * url=url+'&notify='+notify+'&name='+name+'&keyid='+keyid;
 * 
 * var urla='/properties/save_search?'+url; divId='urlactual';
 * 
 * $('#Res').load(urla, function() { setTimeout("$('#Res').html('')",2000);
 * setTimeout("$('#dialog').dialog('close')",2500); JsMessage() }); }
 */

function JsSaveSearchData(lead_id) {

	if(lead_id!=undefined && lead_id!=""){
		
		var p_name = $("#name").val();
		var p_parameters = $("#key_search").val();
		var p_notify = $('#notify').attr('checked');
		var url = '/properties/save_search/lead_id:'+lead_id;
		
		if(!p_name && !p_parameters){
		
			var p_name = $("#search_name").val();
			var p_parameters = $("#parsed_params").val();		
		
		}
			
		
		$('#dialog').dialog('close');
		$("#saving-search-dialog").dialog({
			title: "Save Search", 
			modal:true, 
			width: 500,
			height: 150,
			resizable:false, 
			draggable: false,
			buttons : {
				"Ok" : function() {
					$(this).dialog("close");
					$('#saving-search-dialog').html('<p>Your search is being saved, wait a few seconds.</p> <img src="/property_search/img/icons/ajax-loader-localities.gif">');
				}
			}
		});
		
		$.ajax({url: url, type:'POST' ,data : {name: p_name, parameters: p_parameters, notify: p_notify}, 				
			success: function(){
				
				setTimeout("$('#saving-search-dialog').html('<p>Your search has been saved.</p>');", 1000);
			}
		});			
		
/*		$.post(url, {name: p_name, parameters: p_parameters, notify: p_notify}, function(data) {

			setTimeout("$('#saving-search-dialog').html('<p>Your search has been saved.</p>');", 1000);
		});*/
	}
}

function JsMessage(){
						
	setTimeout("$('#Message').html('Your Search has been saved'); $('#Message').show();",1500);					
}

function validateLeadInfo(url, form_id, notice_id) {
	if ($('#LeadFirstname').val() != "" && $('#LeadLastname').val() != "" && $('#LeadEmail').val() != "" && ( $('#LeadTelephone1').val() != "" || $('#cellular_phone1').val() != "") ) {
		
		//if (!$('#CaptchaValue') || $('#CaptchaValue').val() != "") {falta ver si lleva captcha aqui o no...
						
		
			$("#saving-modal").modal();
			
			$.post(url, $('#'+form_id).serialize(), function(data){				
															 
					if(data==''){
						
						$("#"+notice_id).attr("class", "error-message");
						$("#saving-modal").html("<h3>Error ...</h3><p>Error saving your information. Please contact us.</p>");
						setTimeout('$.modal.close();', 3000);									
						$("#"+notice_id).html('Error. Please contact us.');
					}
					if(data=='-2'){

						if($("#captcha_image")){
						
							$("#captcha_image").html('<div class="loader"></div>');
							$("#"+notice_id).attr("class", "error-message");
							$("#"+notice_id).html('Error, image characters are incorrect.');
							$("#captcha_image").load('/captcha/image_html');
							$.modal.close();
						}	
					}
					if(data=='-1'){
					
						$("#"+notice_id).attr("class", "message");
						$("#saving-modal").html("<h3>Information Saved ...</h3><p>Your information has been saved.</p>");
						setTimeout('$.modal.close(); parent.$.fancybox.close();', 2000);
						$("#"+notice_id).html('You have scheduled a showing.');
					}
					else {
									
						$.modal.close();
						parent.$.fancybox.close();
						parent.location.reload(true);
						/*
						$.fancybox({
							type: 'iframe',
							href: '/leads/register_step2/?id='+data+'&message=true',
							padding: 10,
					        height: 570,
					        width: 600
						});		*/
					}	
			 });
		//}
		/*else{
		
			$("#"+notice_id).attr("class", "error-message");
			$("#"+notice_id).html('Write the characters of the image.');
		}*/		
	} else {
		
		$("#"+notice_id).attr("class", "error-message");
		$("#"+notice_id).html('Please enter mandatory fields.');
	}
}

// ///////////sort///////////////////////
function sortByProperties(formId, sortFieldId, directionFieldId, sortSelectId, loggedIn){
	
	sort = '';
	direction = '';
	sortBy = Number($('#'+sortSelectId).val());
	var can_send_form = true;
	
	switch(sortBy){
	
		case 1:{
			sort = 'listing_price';
			direction = 'desc';
			break;
		}
		case 2:{
			sort = 'listing_price';
			direction = 'asc';
			break;
		}
		case 3:{
			sort = 'creation_date';
			direction = 'desc';
			break;
		}		
		case 4:{
			sort = 'num_beds';
			direction = 'desc';
			break;
		}
		case 5:{
			//if(loggedIn==true){
				sort = 'listing_price_sqft';
				direction = 'asc';
			/*}
			else{
				registerMember();
				can_send_form = false;
			}*/
			break;
		}
	}
	
	if(sort!='' && direction!='' && can_send_form==true){
		
		$('#'+sortFieldId).val(sort);
		$('#'+directionFieldId).val(direction);
		$('#'+formId).submit();
	}	
}


function getPageContent(url, divId, loaderClass) {

	url += '?time=' + new Date().getTime();	
	$("#"+divId).hide().load('<div class="'+loaderClass+'"></div>',{},function () {$(this).show(500);});	
}

function addToFavorites(lead_id, property_id , index, ajax_way){
	
	if(confirm('Are you sure you want to add as favorite this Property?')){
		if(ajax_way){
			$("#saving-modal").modal();
			$.ajax({url: '/properties/favorite', type:'POST' ,data : {lead_id: lead_id, property_id: property_id, ajax_way: ajax_way}, 				
				success: function(){
				location.reload();
				}
			});	
		}
		else{
                    $(document.location).attr("href", '/properties/favorite/lead_id:'+ lead_id + '/property_id:' + property_id+ '/index:' + index);
		}
		
	}	
	
}

function isVisible(obj){
	
    if (obj == document) return true
    
    if (!obj) return false
    if (!obj.parentNode) return false
    if (obj.style) {
        if (obj.style.display == 'none') return false
        if (obj.style.visibility == 'hidden') return false
    }
    
    // Try the computed style in a standard way
    if (window.getComputedStyle) {
        var style = window.getComputedStyle(obj, "")
        if (style.display == 'none') return false
        if (style.visibility == 'hidden') return false
    }
    
    // Or get the computed style using IE's silly proprietary way
    var style = obj.currentStyle
    if (style) {
        if (style['display'] == 'none') return false
        if (style['visibility'] == 'hidden') return false
    }
    
    return isVisible(obj.parentNode)
}

function scheduleShowing(property_id, req_type, showing){

	url = '/leads/request_info/property_id:'+property_id+'/type:'+req_type;
	if(showing) url += '/showing:true/';

	$.fancybox({
		type: 'iframe',
		href: url,
		padding: 10,
        height: 650,
        width: 500
	});	
}

function showMessage(divId, content) {

	$(divId).className = 'message';

	if ($(divId) != null) {
		$(divId).innerHTML = content;
		$(divId).show();
		messageHide(divId);
	}
}

function messageHide (divId) {
	
	if ($(divId) != null) {
		new Effect.Highlight(divId, {
			startcolor :'#F39249'
		});
	}
}

function CookiesEnabled() {
	
	if (!navigator.cookieEnabled
			&& location.href != 'http://www.homeconnector.com/pages/enable_cookies'
			&& location.href != 'http://homec/pages/enable_cookies') {

		window.location = '/pages/enable_cookies';
	}
}

function removeFromFavorites(property_id, notice_id){
	
	var successMess = "The Property has been removed from your favorites.";
	var errorMess = "Error removing the property from favorites.";
	var url = '/properties/remove/id:'+property_id+'/type:3';
	
	$('#loading').load(url, function() {
		// close modal window
		// $.modal.close();
	});
	
	
}

function savePropertyNotes(property_id, form_id, notice_id){
	
	if ($(form_id) != null){
		formParameters = $(form_id).serialize(true);}
	else{
		formParameters = null;}
			
	var url = '/properties/save_notes/id:'+property_id;	
	var str = $.post(url, $('#'+form_id).serialize());
			
	$('#'+notice_id).show();
	$("#"+form_id).text(str);
	setTimeout("parent.$.fancybox.close();", 2000);
}

function saveLeadInformation(url, form_id, notice_id) {

	var successMess = "The info has been sent";
	var errorMess = "Error sending info, please contact us to info@homeconnector.com";

	if ($(form_id) != null)
		formParameters = $(form_id).serialize(true);
	else
		formParameters = null;
		
		$('#'+form_id).load(url, function() {
	});
}

function closeShadowBox(){
	
	parent.$.fancybox.close();
}

function numbersonly(myfield, e, dec) {
	var key;
	var keychar;

	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;
	keychar = String.fromCharCode(key);

	// control keys
	if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13)
			|| (key == 27))
		return true;

	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
		return true;

	// decimal point jump
	else if (dec && (keychar == ".")) {
		myfield.form.elements[dec].focus();
		return false;
	} else
		return false;
}

/*
 * This script and many more are available free online at The JavaScript
 * Source!! http://javascript.internet.com Created by: Cyanide_7 |
 */
var isNN = (navigator.appName.indexOf("Netscape") != -1);

function autoTab(input, len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode;
	var filter = (isNN) ? [ 0, 8, 9 ] : [ 0, 8, 9, 16, 17, 18, 37, 38, 39, 40,
			46 ];
	if (input.value.length >= len && !containsElement(filter, keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input) + 1) % input.form.length].focus();
	}

	function containsElement(arr, ele) {
		var found = false, index = 0;
		while (!found && index < arr.length)
			if (arr[index] == ele)
				found = true;
			else
				index++;
		return found;
	}

	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
			if (input.form[i] == input)
				index = i;
			else
				i++;
		return index;
	}
	return true;
}

function getSavedProperties(url, divId, loaderClass, typeId){

	if($('#'+divId).html()==''){
	
		$('#'+divId).html('<div class="'+loaderClass+'"></div>');
		$('#'+divId).load(url);
                
	}
}
function JsSearchPropertyNotes(lead_id){
	
	var lead_id=lead_id
	var type=1;
	var notes=1;
	
	var ulr='/properties/view_saved/type:'+ type + '/lead_id:' + lead_id+ '/notes:' + notes;
	// alert(ulr);
	$('#my-notes').load(ulr);
	
	
	}

function JsChangeStatusRejected(lead_id,property_id,index,ajax_way){
	
	if(confirm('Are you sure you want to reject this Property?')){
		
		if(ajax_way){
			$.ajax({url: '/properties/reject', type:'POST' ,data : {lead_id: lead_id, property_id: property_id, ajax_way: ajax_way}, 				
				success: function(){
					
					location.reload();
				}
			});	
		}
		else{
			$(document.location).attr("href", '/properties/reject/lead_id:'+ lead_id + '/property_id:' + property_id);
		}
	}
}

function JsChangeStatusUnRejected(lead_id,property_id,ajax_way){
	
	if(confirm('Are you sure you want to un-reject this Property?')){
		
		if(ajax_way){
			$.ajax({url: '/properties/unreject', type:'POST' ,data : {lead_id: lead_id, property_id: property_id, ajax_way: ajax_way}, 				
				success: function(){
					
					location.reload();
				}
			});	
		}
		else{		
		
			$(document.location).attr("href", '/properties/unreject/lead_id:'+ lead_id + '/property_id:' + property_id);
		}
	}
}

function viewPropertyPhotos(id){

	url = '/properties/view_photos_url/id:'+id;	

	$.fancybox({
		type: 'iframe',
		href: url,
		padding: 10,
        height: 450,
        width: 550
	});		
}

function JsSavedSearchesIdlead(divId, loaderClass){	
	
	var url='/properties/search_save_result';
	
	if($('#'+divId).html()==''){
	
		$('#'+divId).html('<div class="'+loaderClass+'"></div>');
		$('#'+divId).load(url);
	}	
}
function JsDeletesearch(id){ 

var answer = confirm("Do you really want to delete this sarch?")

	if (answer){
		
		var url='/properties/delete_search/id:'+id;
		var divId='resultsearchsave';
	
		$('#'+divId).html('<div class="loader"></div>');			
		$('#'+divId).load(url);		
		setTimeout("JsSavedSearchesIdlead('resultsearchsave','loader')",1500);
	}
}

function clearForm(formId) {
	
	
	$(':input','#'+formId)
	 .not(':button, :submit, :reset, :hidden')
	 .val('')
	 .removeAttr('checked')
	 .removeAttr('selected');
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g, '');
	if (isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100 + 0.50000000001);

	cents = num % 100;
	num = Math.floor(num / 100).toString();
	if (cents < 10)
		cents = "0" + cents;
	
	for ( var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		num = num.substring(0, num.length - (4 * i + 3)) + ','
				+ num.substring(num.length - (4 * i + 3));
	// return (((sign) ? '' : '-') + '$' + num + '.' + cents);
	return (((sign) ? '' : '-') + '$' + num);
}

function addCurrencyListeners(inputId) {

    if ($('#' + inputId) != null) {

        $('#' + inputId).val(formatCurrency($('#' + inputId).val()));

        $('#' + inputId).blur( function() {
            $('#' + inputId).val(formatCurrency($('#' + inputId).val()));
        });

        $('#' + inputId).focus( function() {
            $('#' + inputId).val(removeFormatCurrency($('#' + inputId).val()));
        });
    }
}

function removeFormatCurrency(num) {
	num = num.toString().replace(/\$|\,/g, '', '.');	
	return num;
}

function showMessage (divId, content){

	/*
	 * $(divId).className = 'message';
	 * 
	 * if ($(divId) != null) { $(divId).innerHTML = content; $(divId).show();
	 * messageHide(divId); }
	 */
}

function messageHide (divId) {
	
	/*
	 * if ($(divId) != null) { new Effect.Highlight(divId, { startcolor
	 * :'#F39249' }); new Effect.Fade(divId, { duration :4.5 }); }
	 */
}

function saveLeadAction(url, form_id, notice_id, successMess, errorMess, show_message) {

	if($(form_id)!=null){
		formParameters = $(form_id).serialize(true);
	}	
	else{
		formParameters = null;
	}	
				
	$('#'+form_id).load(url);
}

function JsContador(inicia){	
	
	var inicia=inicia; 
	var valor=$('#contadorPhoto').val();
	var total=$('#phototal').val();	
	var mem=$('#contadorPhoto').val();
	
	valor = parseInt(valor) ;
	total = parseInt(total);
		
	if(inicia=='1'){
		
		if( valor < total){
			
			valor=parseInt(valor) +1;
			// alert(valor);
			$('#contadorPhoto').val(valor);
			var message='Photo '+valor+' to '+ total;
			$('#NumberPhoto').html(message)		
		}else {

			$('#contadorPhoto').val(1);
			var message='Photo '+1+' to '+ total;
			$('#NumberPhoto').html(message)		
		}
	}

	if(inicia=='2'){		
		
		if(valor ==1){
			
			var message='Photo '+total+' to '+ total;
			$('#contadorPhoto').val(total);				
			$('#NumberPhoto').html(message);				

		}else{	
	
			if( valor  !=1 &&  valor <= total){
				valor=parseInt(valor) -1;					
				$('#contadorPhoto').val(valor);
				var message='Photo '+valor+' to '+ total;
				$('#NumberPhoto').html(message);
			}			
		}	
	}	
}

function JsViewBestBuysMessage(header_title){
	
	$("#best-buys-dialog").dialog( {modal :true,title :header_title,width :600,height:200,resizable: false,draggable: false});

}

function JsInfo(header_title){
	
	$("#my_hc_group").dialog( {modal :true,title :header_title,width :650,height:300,resizable: false,draggable: false});

}
function JsViewMessageAgent(user_id,property_id){	
		
	if(user_id !='' && property_id !=''){
		var url='/properties/view_notes/user_id:'+user_id+'/property_id:'+property_id;

		$('#dialog').load(url);	
		
		
		if (!save_search_dialog) {
	
			$("#dialog").dialog( {modal :true,title :'View Messages Agent',width :600,height:500,resizable: false,draggable: false});
			save_search_dialog = true;
		
		} else {
			
			$("#dialog").dialog('open', {modal :true,title :'View Messages Agent',width :600,height:500,resizable: false,draggable: false});
		}
	}	
	
	}
	function JsSaveMessageLead(lead_id_param, property_id_param){

		var message_param = $('#body').val();
		// message_param = message_param.replace(/ /g,'|');
		
		if(message_param ==''){

			alert('The message can not be null');
			$('#body').focus();
			alert(message_param);
			return false;
		
		}else{				
			$('#property_notes').html('<div class="loader"></div>');
			$.ajax({url: '/properties/save_note', type:'POST' ,data : {lead_id: lead_id_param, property_id: property_id_param, message: message_param}, 
				success: function(){					
					
					$('#property_notes').load('/properties/view_notes/user_id:'+lead_id_param+'/property_id:'+property_id_param);
					$('#body').val('');
				}
			});
			
		}		
	}
		
		
	function JsSearchModal(){
		
		$("#SearchModal").dialog( {
		resizable : false,
		width : 680,
		height : 690,
		modal : true,
		title :'Search Connector'
		
		
	});
		var url='/leads/search_connector';
		$('#SearchModal').load(url);
		}
		
		
	function changeHomeTab(homeTabs){

	var homeTabs = homeTabs;
	
	if(homeTabs!=undefined){
	
		if(count_tabs>=homeTabs.length){
			count_tabs = 0;
		}

		var city_id = homeTabs[count_tabs++];
				
		$('#neighborhoods_tabs .neighborhood').hide();
		$('#neighborhood_' + city_id).show();
		$('.menu_arrow a').attr('class', '');
		$('.menu_arrow #link_neighborhood_' + city_id).attr('class', 'selected');
	}		
}
	function JsOnchangue(city_id) {
	
// alert(city_id)
	$('#neighborhoods_tabs .neighborhood').hide();
	$('#' + city_id).show();
	$('.menu_arrow a').attr('class', '');
	$('.menu_arrow #link_' + city_id).attr('class', 'selected');
	// clearTimeout (changeHomeTab(1));
	
	
}
	
function isValidEmail(email) {

   return (email.indexOf(".") > 2) && (email.indexOf("@") > 0);
}

function JsValidateSearchConnector(){
		if($('#location').val() ==''){
			alert('Location is Mandatory');
			$('#location').focus();
			return 1;
			}
		if($('#minprice').val()==''){
			alert('Range Price is Mandatory');
			$('#minprice').focus();
			return 1;
			}else{
				if (isNaN($('#minprice').val())==true){
					alert("The price is not an amount");
					$('#minprice').focus();
					return 1;
				}	
			}	
			
		if($('#maxprice').val() ==''){
			alert('Range Price is Mandatory');
			$('#maxprice').focus();
			return 1;
			}else{
				if (isNaN($('#maxprice').val())==true){
					alert("The price is not an amount");
					$('#maxprice').focus();
					return 1;
				}	
			}
		
		
		if($('#firstname').val() ==''){
			alert('First name is Mandatory');
			$('#firstname').focus();
			return 1;
			}
			
		if($('#lastname').val()==''){
			alert('Last name is Mandatory');
			$('#lastname').focus();
			return 1;
			}
	
			if($('#telephone').val() ==''){
			alert('Telephone  is Mandatory');
			$('#telephone').focus();
			return 1;
			}else{
				if (isNaN($('#telephone').val())==true){
					alert("The telephone is not number");
					$('#telephone').focus();
					return 1;
				}	
			}

		if($('#email').val() ==''){
			alert('E-mail  is Mandatory');
			$('#email').focus();
			return 1;
			}else{
				if(!isValidEmail($('#email').val())){
				alert("E-mail is not valid");
				$('#email').focus();
				return 1;			
			}
		}

		var url='/leads/search_connector/location:'+$('#location').val()+'/price1:'+$('#minprice').val()+'/price2:'+$('#maxprice').val()+'/bed:'+$('#minbeds').val()+'/bath:'+$('#minbahtrooms').val()+'/request:'+$('#request').val()+'/firstname:'+$('#firstname').val()+'/lastname:'+$('#lastname').val()+'/telephone:'+$('#telephone').val()+'/alt_telephone:'+$('#alt_telephone').val()+'/email:'+$('#email').val();		
		$(document.location).attr("href", url);			
}

function registerMember(property_id, action_blocked){
	changeSignIn();
	$('#prop_id').val(property_id);//fiel necessary in all site
	$('#prop_register_id').val(property_id);//field necesary in register form
	$("#register").dialog('open');
}

function JsPaginateProp(position, photos){

	var position=position; 
	var valor=$('#contadorPhoto').val();
	var total=$('#phototal').val();	
	var mem=$('#contadorPhoto').val();
	valor = parseInt(valor) ;
	total = parseInt(total);
	var exploded = photos.split(',');	
	if(position == 0){
            valor=parseInt(valor) -1;
	}
	if(position == 1){	
		valor=parseInt(valor) +1;				
	}	

	if(valor>=1 && valor <=total){
		
		$('#inc').html(valor+' to '+total);
		$('#contadorPhoto').val(valor);						
			$('#photos').html('<div style="margin-left: 20px; margin-top: 80px; color:#000;"><img src="/property_search/img/icons/ajax-loader-localities.gif" style="margin-right:10px;margin-top:-7px;">Loading...</div>');
			$.ajax({url: '/properties/load_photos/?prop_id='+$('#prop_id').val()+'', type:'POST' ,data : {pic: exploded[valor-1]}, 				
				success: function(data){
					$('#photos').html(data);
				}
			});			
	}
}

/**
 * @name:JsPaginateProp2
 * @param:position <int> pocision actual de la foto
 * @param:photos <string> un string conn las fotos separadas por comas
 * @param:idProperty <int> id de la propiedad seleccionado
 *
 *  este metodo pagina las fotos
 **/
function JsPaginateProp2(position, photos,idProperty, view_type){

        
	var position=position;
	var valor=$('#contadorPhoto').val();
	var total=$('#phototal').val();
	var mem=$('#contadorPhoto').val();
	valor = parseInt(valor) ;
	total = parseInt(total);
	var exploded = photos.split(',');
	if(position == 0){
            valor=parseInt(valor) -1;
	}
	if(position == 1){
		valor=parseInt(valor) +1;
	}
	if ( (valor>=1 && valor <=total)  ){

		$('#contadorPhoto').val(valor);
		if(view_type=='large'){
			$('#inc2').html(valor+' to '+total);
			$('#photos2').html('<div style="margin-left: 20px; margin-top: 80px; color:#000;"><img src="/property_search/img/icons/ajax-loader-localities.gif" style="margin-right:10px;margin-top:-7px;">Loading...</div>');
			$.ajax({url: '/properties/load_photos2/?prop_id='+idProperty+'&view_type='+view_type, type:'POST' ,data : {pic: exploded[valor-1]},
				success: function(data){
					$('#photos2').html(data);
				}
			});
		}
		else{
			$('#inc').html(valor+' to '+total);
			$('#photos').html('<div style="margin-left: 20px; margin-top: 80px; color:#000;"><img src="/property_search/img/icons/ajax-loader-localities.gif" style="margin-right:10px;margin-top:-7px;">Loading...</div>');
			$.ajax({url: '/properties/load_photos2/?prop_id='+idProperty+'&view_type=', type:'POST' ,data : {pic: exploded[valor-1]},
				success: function(data){
					$('#photos').html(data);
				}
			});			
		
		}
	}
}

/**
 * @name: getFirstPropertyByType
 * @author: isai rivas
 * @param:type <int> el tipo del que se va a obtener la propiedad
 *
 *  este metodo obtiene la primer propiedad de el lead logueado y de el tipo que se le envia
 *  y la carga en el preview en myhomeconnector segun el tipo de propiedad que se requiera
 **/
function getFirstPropertyByType(type)
{
    var propertySelected = null;
    
    $.ajax({
            url:'/properties/getFirtsPropertyByType',
            type:'GET',
            data:'type='+type,
            success:function (data){
                if ( data != '' ) {
                    JsLoadPropPrev(data,'','myhomeconnector','');
                }
            }
     });
}
/**
 * @name:getFirstPropertyWithNotes
 * @author: isai rivas
 *
 *   este metodo mediante ajax obtiene la primera propiedad que tiene alguna nota
 *   y la carga en el preview de la pestaña de notes and question de myhomeconnector
 */
function getFirstPropertyWithNotes()
{
    var propertySelected = null;
    $.ajax({
            url:'/properties/getFirstPropertyWithNotes',
            type:'GET',
            success:function (data){
                if ( data != '' ) {
                    JsLoadPropPrev(data,'','','');
                }
            }
     });
}
function JsLoadPropPrev(id, lead_id, params, index){
	
	$(document).ready(function () {
	
		//Abort ajax request in var load agent
		if(load_agent != undefined){
			load_agent.abort();
		}
		//Abort ajax request in var load_prop_prev
		if(load_prop_prev != undefined){
			load_prop_prev.abort();
		}
		//Abort ajax request in var load_agent
		if(msg_agent != undefined){
			msg_agent.abort();
		}
		var url='/properties/load_prop_prev/id:'+id+'/';//+'/params:'+params+'/';
		$('#prop_id').val(id);
		$('#prop_register_id').val(id);
		
		if(lead_id!=undefined && lead_id!=0){		
		    url += 'lead_id:'+lead_id+'/';
		}
		if(index!=undefined){		
		    //url += 'index:'+index+'/';
		    url += 'index:0/';
		}
		if ( (aEliminar= document.getElementById('container_share_by_email') ) ){
			var padre = aEliminar.parentNode;
			padre.removeChild(aEliminar);
		}
		$('#cont_pp').html('<div style="margin-left: 90px; margin-top: 80px; color:#000;"><img src="/property_search/img/icons/ajax-loader-localities.gif" style="margin-right:10px;margin-top:-7px;">Loading...</div>');
		load_prop_prev = $.ajax({
				    type: 'POST',
				    url: url,
				    success: function(data) {
					$('#cont_pp').html(data);
					}
				});
		$('#preperty_preview').css('display','block');
		$('#cont_pp').css('display','block');
		//if var agent_property diferent to hiden field value with ID from propertys
		
		if(agent_property != $('#'+id).val() && $('#'+id).val() != undefined){//Take the agent_id in id param
			agent_property = $('#'+id).val();
			//Load agent box
			load_agent = $.ajax({
				    type: 'POST',
				    url: '/properties/get_agent/id:'+id,
				    success: function(data) {
					$('#real_state_sidebar .green_header .content').html(data);
					//Load agent box message
					msg_agent = $.ajax({
							type: 'POST',
							url: '/properties/agent_contact/agent_id:'+agent_property,
							success: function(data) {
								$('#agentmsg_img').html(data); //Load Agent Img
								$('#agentid_mail').val($('#'+id).val()); //Change id from hidden field
							}
					});
					
					}
				});
		}
		if(agent_property != $('#geo_'+id).val() && $('#geo_'+id).val() != undefined){
			agent_property = $('#geo_'+id).val();
			//Load agent box
			load_agent = $.ajax({
				    type: 'POST',
				    url: '/properties/get_agent/id:'+id,
				    success: function(data) {
					$('#agent_box').html(data);
					//Load agent box message
					msg_agent = $.ajax({
							type: 'POST',
							url: '/properties/agent_contact/agent_id:'+agent_property,
							success: function(data) {
								$('#agentmsg_img').html(data); //Load Agent Img
								$('#agentid_mail').val($('#'+id).val()); //Change id from hidden field
							}
					});
					}
				});
		}
     });
}

$('#prop_box').live('click',function(){
	});
function LoadPhotos(photos){	
    $.ajax({url: '/properties/load_photos', type:'POST' ,data : {photos: photos},
            success: function(data){
                    alert(data);
                    $('#photo_set').html(data);
            }
    });
}
function requestShowing(property_id){

	var url = '/leads/request_info/property_id:'+property_id+'/showing:true';
				
	$.fancybox({
		type: 'iframe',
		href: url,
		padding: 10,	
        height: 520,
        width: 600,
        autoScale: true
	});
}

function JsVieMapProperty(){
	$("#ViewMap").dialog( {
		resizable : false,
		width : 300,
		height : 400,
		modal : true		
	});	
}

function delete_search(search_id, lead_id){	
	if(confirm('Are you sure that you want delete this search?')){
		$('#tabs1-2').html('<div class="ajax_loader"></div>'); 
		$.ajax({url: '/properties/delete_search/id:'+search_id+'/lead_id:'+lead_id, type:'GET', 
			success: function(){
				$('#tabs1-2').load('/properties/saved_searches/lead_id:'+lead_id);
			}
		});	
	}
}

function viewDetalis(){
	
	alert($('#url').val());	
	alert($('#key_search').val());	
	
	$.ajax({url: '/properties/load_photos', type:'POST' ,data : {photos: photos}, 
		success: function(data){
			alert(data);
			$('#photo_set').html(data);
		}
	});		
	
}

function recalculate(){
	var home_price = $('#hprice').val().replace(/,/g, '');
	home_price = parseFloat(home_price)*0.2;
	$('#downpay').val('');
	var num = new oNumero(home_price);
	$('#downpay').val(num.formato(2, true));
}

function calcMonthlyPayment(){
	
	var m;
	var hprice;
	
	if($('#hprice').val()){
		
		var home_price = $('#hprice').val().replace(/,/g, '');
		var downpay = $('#downpay').val().replace(/,/g, '');
		
		home_price = home_price - downpay;
		hprice=0;
	}
	else{
		
		home_price = 200000;
		hprice=1;
	}
	
	var rate1 = $('#rate1').val();
	var rate2 = $('#rate2').val();
	var rate3 = $('#rate3').val();	
	
	var term1 = $('#term1').val();
	var term2 = $('#term2').val();
	var term3 = $('#term3').val();		
	
	var rate1 =  parseFloat(rate1)/1200;
	var rate2 =  parseFloat(rate2)/1200;
	var rate3 =  parseFloat(rate3)/1200;	
	
	step1_formula1 = Math.pow( ( 1 + rate1)  , ( parseInt(term1) * 12 ) );
	step2_formula1 = step1_formula1 -1;
	step3_formula1 = rate1 / step2_formula1;
	step4_formula1 = rate1 + step3_formula1
	step5_formula1 = step4_formula1 * parseFloat(home_price);
	
	step1_formula2 = Math.pow( ( 1 + rate2)  , ( parseInt(term2)  * 12 ) );
	step2_formula2= step1_formula2 -1;
	step3_formula2 = rate2 / step2_formula2;
	step4_formula2 = rate2 + step3_formula2
	step5_formula2 = step4_formula2 * parseFloat(home_price);
	
	step1_formula3 = Math.pow( ( 1 + rate3)  , ( parseInt(term3)  * 12 ) );
	step2_formula3 = step1_formula3 -1;
	step3_formula3 = rate3 / step2_formula3;
	step4_formula3 = rate3 + step3_formula3
	step5_formula3 = step4_formula3 * parseFloat(home_price);		
	
	m=step5_formula1;
	m1=step5_formula2;
	m2=step5_formula3;	

	
	var num = new oNumero(m);
	var num1 = new oNumero(m1);	
	var num2 = new oNumero(m2);
	
	
	if(hprice){
		
		$('#field1').html(''+num.formato(2, true)+'');
		$('#field2').html(''+num1.formato(2, true)+'');
		$('#field3').html(''+num2.formato(2, true)+'');		
		
	}
	else{
		
		$('#field1').val(num.formato(2, true));
		$('#field2').val(num1.formato(2, true));
		$('#field3').val(num2.formato(2, true));
	
	}
	
}

//Objeto oNumero
	function oNumero(numero){
		//Propiedades
		this.valor = numero || 0
		this.dec = -1;
		//M�todos
		this.formato = numFormat;
		this.ponValor = ponValor;
		//Definici�n de los m�todos
		function ponValor(cad){
			
			if (cad =='-' || cad=='+') return
			if (cad.length ==0) return
			if (cad.indexOf('.') >=0)
			this.valor = parseFloat(cad);
			else
			this.valor = parseInt(cad);
		}
		function numFormat(dec, miles){
				
			var num = this.valor, signo=3, expr;
			var cad = ""+this.valor;
			var ceros = "", pos, pdec, i;
			for (i=0; i < dec; i++)
				ceros += '0';
			pos = cad.indexOf('.')
			if (pos < 0)
				cad = cad+"."+ceros;
			else{
				pdec = cad.length - pos -1;
				if (pdec <= dec)
				{
					for (i=0; i< (dec-pdec); i++)
						cad += '0';
				}
				else{
					
					num = num*Math.pow(10, dec);
					num = Math.round(num);
					num = num/Math.pow(10, dec);
					cad = new String(num);
				}
			}
			pos = cad.indexOf('.')
			if (pos < 0) pos = cad.lentgh
			if (cad.substr(0,1)=='-' || cad.substr(0,1) == '+')
			signo = 4;
			if (miles && pos > signo)
			do{
			expr = '/([+-]?\d)(\d{3}[\.\,]\d*)/'
			cad.match(expr)
			cad=cad.replace(expr, RegExp.$1+','+RegExp.$2)
			}

                    
			while (cad.indexOf(',') > signo)
			if (dec<0) cad = cad.replace(/\./,'')
			return cad;
			}
	}//Fin del objeto oNumero:

        function remove_from_myhc(idPropiedad,tipo)
        {
            if ( confirm('Are you sure you want to remove this property from the myhomeconnector') ){
                $('#'+idPropiedad).css('display','none');
                $('#cont_pp').css('display','none');
                 $.ajax({
                     url: '/properties/delete_saved_homes2/',
                     type:'GET',
                     data:"property="+idPropiedad,
                    success: function(data) {
                       getFirstPropertyByType(tipo);
                    }

                });
                
            }
        }

        /**
         * @name:change_property_type
         * @author: isai rivas
         * @param: idPropiedad <int> el id de la propiedad a cambiar de tipo
         * @param: valor <int> el id del tipo de la propiedad a cambiar
         * @param:tipo <int> el id del tipo de propiedad actual
         * @param: changePreview <boolean> si se va a necesitar cambiar de propiedad
         * @param: idlead <int> el id del lead seleccionado
         *
         *  este metodo cambia de tipo de propiedad ,mediante ajax
         */
        function change_property_type(idPropiedad,valor,tipo,changePreview,idLead){
            switch(valor){
                case '-1':
                    var select =  document.getElementById('select_'+idPropiedad);
                    var item = null;
                   switch(tipo){
                       case '1':item = 3;break;
                       case '2':item = 2;break;
                       case '3':item = 1;break;
                   }
                   select[item].selected= true;
                    break;
                case '2':
                    requestShowing(idPropiedad);
                    break;
                case '3':
                    addToFavorites(idLead, idPropiedad, 0, true);
                    var select =  document.getElementById('select_'+idPropiedad);
                   var item = null;
                   switch(tipo){
                       case '1':item = 3;break;
                       case '2':item = 2;break;
                       case '3':item = 1;break;
                   }
                   select[item].selected= true;
                    break;
                default:
                    if ( confirm('Are you sure you want to change this property group') ){
                        $('#'+idPropiedad).css('display','none');
                        $('#cont_pp').css('display','none');
                        $('#preperty_preview').css('display','none');
                         $.ajax({
                             url: '/properties/change_type_saved_home/',
                             type:'GET',
                             data:"property="+idPropiedad+"&type="+valor,
                            success: function(data) {
                               if (changePreview){
                                   location.reload();
//                                   getFirstPropertyByType(tipo);
                               } else {
                                   location.reload();
                               }
                            }
                          });
                       } else {
                       var select =  document.getElementById('select_'+idPropiedad);
                       var item = null;
                       switch(tipo){
                           case '1':item = 3;break;
                           case '2':item = 2;break;
                           case '3':item = 1;break;
                       }
                       select[item].selected= true;

                    }
                    break;
            }
            
        }



        /**
         
         * @author:isai rivas
         * @name:backDeselectedItemAndOpenRegisterDialog
         * @param: id <int> id del elemento a verificar
         * @param: propertyId <int> id de la propiedad que se encuentra seleccionada
         *
         *  este metodo se usa en el select para cambiar de tipo de propiedad ya sea
         *  my favorite, visited and like etc. y se ejecuta cuando no se esta registrado
         *  y el usuario cambia de opcion en el select y lo que hace es abrir el
         *  dialog de registrar y no te permite seleccionar otra opcion mientras no
         *  estes logueado
         */
        function backDeselectedItemAndOpenRegisterDialog(id,propertyId)
        {
            var select = document.getElementById(id);
            select[0].selected = true;
            registerMember(propertyId);
        }

function showMap(latitude, longitude, user_id, property_id) {
	$('#mapContainer').show();
	if(map != false) {
		map.dispose();
	}
	var options={ 
		elt:document.getElementById('mapPreview'),
		zoom:13,
		latLng:{lat:latitude, lng:longitude},
		mtype:'map',
		zoomOnDoubleClick:false
	};
	map = new MQA.TileMap(options);
	MQA.withModule('smallzoom', function() {
		map.addControl(
			new MQA.SmallZoom(),
			new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5,5))
		);
	});
	var basic=new MQA.Poi( {lat:latitude, lng:longitude} );
	map.addShape(basic);
	$.ajax({
		url: '/properties/save_map_view/'+property_id,
		success: function(data) {
		}
	});
	return false;
}
$(document).ready(function() {
	parameters = '';
	//getFirstPropertyByType(3); por que se llama aqui esto si solo afecta a MYHC????
	$('div.home div.bottom div.left ul li a').click(function() {
		var i = $('div.home div.bottom div.left ul li a').index(this);
		$('div.home div.bottom div.left ul li a').removeClass('selected');
		$(this).addClass('selected');
		$('div.home div.bottom div.right div.city').hide();
		$($('div.home div.bottom div.right div.city').get(i)).show();
		return false;
	});
	$($('div.home div.bottom div.left ul li a').get(0)).addClass('selected');
	$($('div.home div.bottom div.right div.city').get(0)).show();
	$('div.home div.bottom div.left ul li a').hover(function() {
		var i = $('div.home div.bottom div.left ul li a').index(this);
		$('div.home div.bottom div.right div.city').hide();
		$($('div.home div.bottom div.right div.city').get(i)).show();
	}, function() {
		var selected = $('div.home div.bottom div.left ul li a.selected');
		var i = $('div.home div.bottom div.left ul li a').index(selected);
		$('div.home div.bottom div.right div.city').hide();
		$($('div.home div.bottom div.right div.city').get(i)).show();
	});
	$('#mapContainer').hide();
	$('#mapContainer a.closeMap').click(function() {
		$('#mapContainer').hide();
		return false;
	});
	
	$('#Div_Menu ul.top li').hover(function() {
		$($(this).find('ul')).show();
	},function(){
		$($(this).find('ul')).hide();
	});
	
	//this function allows the form in the index to go /sell-your-home-in-somewhere
	if($('#sell_form') != null){
		$('#sell_form').submit(function(){
			var zip=$('#zip_input').val();
			$.ajax({
				url: "/leads/get_territory_byzip/"+zip,
				context: document.body,
				success: function(territory){
					//redirect
					if(territory != "false"){
						territory=territory.replace(/ /g, "-");
						var url="/sell-your-home-in-"+territory;
						$(location).attr('href',url);
					}
					else{
						alert('The zip you are looking for is not correct or does not exist');
					}
					//$(location).attr('href',url);
				}
			});
			return false;
		});	
	}
	//this function allows the form in /free_home_valuation to go /free_home_valuation_in_somewhere
	if($('#valuation_form') != null){
		$('#valuation_form').submit(function(){
			var zip=$('#zip_code').val();
			$.ajax({
				url: "/leads/get_territory_byzip/"+zip,
				context: document.body,
				success: function(territory){
					//redirect
					if(territory != "false"){
						var url="/free_home_valuation_in_"+territory;
						$(location).attr('href',url);
					}
					else{
						alert('The zip you are looking for is not correct or does not exist');
					}
					//$(location).attr('href',url);
				}
			});
			return false;
		});	
	}	
});

//scrips que estaban en views/elements/layout/scripts.ctp
function start_slideshow(start_frame, end_frame, delay) {	
    setTimeout(switch_slides(start_frame,start_frame,end_frame, delay), delay);
}

function switch_slides(frame, start_frame, end_frame, delay) {
    return (function() {
	Effect.Fade('banner' + frame);
	if (frame == end_frame) { frame = start_frame; } else { frame = frame + 1; }
	setTimeout("Effect.Appear('banner" + frame + "');", 850);
	setTimeout(switch_slides(frame, start_frame, end_frame, delay), delay + 850);
    })
}

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];}}
}

$("#fhv_2").submit(
	function(){
	if($(".firstName").val() == "" || $(".email").val() == "" || $(".phone").val() == ""){
	    alert("Please fill out all the fields");
	    return false;
	}  
} );
$('#syhome').submit(
	function(){
	if($(".requiredName").val() == "" || $(".requiredMail").val() == "" || $(".requiredText").val() == "" || $(".requiredCaptcha").val() == ""){
	    alert("Please fill out all the requiered fields");
	    return false;
	}  
} );

$('#syhome_ei').submit(
	function(){
	if($(".requiredName").val() == "" || $(".requiredMail").val() == ""){
	    alert("Please fill out all the requiered fields");
	    return false;
	}  
} );
$('div.green_header .send_message').live('click', function() {
	$("#agent_contact").dialog('open');
	return false;
});

/*DROP DOWN MENU*/
$(document).ready(function () {
    $('#nav li').hover(
        function () {
            //show its submenu
            $('ul', this).slideDown(100);
	    $(this).css("background-image", "url('/img/fondo_btn_activo.jpg')");
        }, 
        function () {
            //hide its submenu
            $('ul', this).slideUp(100);
	    $(this).css("background-image", "none");
        }
    );
     
});
//// END OF DROP DOWN MENU
/*validate numeric fields in foreclouse and mortgage*/
$('.numeric_field').live('keydown',function(event) {
	//only backspace, left and right 
	if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39){
	}
	//only numbers
	else if(event.keyCode < 48 || event.keyCode > 57 ) {
		event.preventDefault();
	}
});
