function logslider(value, minval, maxval) {
    // value will be between 0 and 100
    var min = 0;
    var max = 100;

    var minv = Math.log(minval);
    var maxv = Math.log(maxval);

    // calculate adjustment factor
    var scale = (maxv-minv) / (max-min);

  
    return  Math.exp(minv + scale*(value-min)).round();
}


function intComma(number) {
    number = '' + number;
    if (number.length > 3) {
        var mod = number.length % 3;
        var output = (mod > 0 ? (number.substring(0,mod)) : '');
        for (i=0 ; i < Math.floor(number.length / 3); i++) {
            if ((mod == 0) && (i == 0))
                output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
            else
                output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
        }
        return (output);
    }
    else return number;
}
Dotted = intComma;

function nl2br(str) {
    return str.replace(/\n/g, "<br />");
}



function displayMore(pk){
    var product_description = $$("#product-"+pk+" p.description").pop();
    var product_action = $$("#product-"+pk+" .action").pop();
    var gallery = $$("#product-"+pk+" .gallery").pop();
    product_description.update(nl2br($('product-'+pk).desc));
    product_description.setStyle({
        display: 'block'
    });
    if (gallery.childNodes.length > 0) gallery.setStyle({
        display: 'block'
    });
	
    product_action.show_text = product_action.innerHTML;
    product_action.update("ocultar");
    product_action.onclick = function(){
        hideExtraInfo(pk)
    };
    facebox = new Facebox();
}

function hideExtraInfo(pk) {
    var product_action = $$("#product-"+pk+" .action").pop();
    $$("#product-"+pk+" p.description").pop().update($("product-"+pk).short_desc);
    $$("#product-"+pk+" .gallery").pop().hide();
    product_action.update(product_action.show_text);
    product_action.onclick = function(){
        displayMore(pk)
    };
}


function loadHousing(pk, no_reload) {
    var url = "/load_product/housing/"+pk;
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(t) {
            data = t.responseText.evalJSON();
            $("product-"+pk).short_desc = $$("#product-"+pk+" p.description").pop().innerHTML;
            $("product-"+pk).desc = data.description;
            data.photos.each(function(photo) {
                var link = new Element('a', {
                    href: photo.url,
                    rel: 'facebox'
                });
				
                var img = new Element('img', {
                    src: photo.thumb,
                    alt: "foto vivienda"
                });
				
                link.insert(img);
                $$("#product-"+pk+" .gallery").pop().insert(link);
            })
            displayMore(pk);
        },
        onFailure: function(t) {
            AjaxFailure(t)
        }
    });
}

var hierarchicalFields = Class.create();
hierarchicalFields.prototype = {
    initialize: function(url, fields, index) {
				
		
        this.url = url;
        this.fields = fields;
        if (index == undefined) {
            index = 0;
            this.fields.each(function(field){
                if (field.getValue() != ''){
                    index++;
				
                }
            })
        }
		
        this.fields.each(function(element) {
            element.observe('change', function() {
                this.updateChildrens(element);
            }.bind(this));
        }.bind(this));
        if (index < this.fields.size()) {
            this.disableChildrens(this.fields[index]);
        }
    },
	
    resetChildrens: function(field){
        var cut = this.fields.indexOf(field)  + 1;
        childrens = this.fields.slice(cut);
        childrens.each(function(child){
            child.setValue('');
        })
    },

    disableChildrens: function(field, force) {
        if (force == undefined) force = false;
        var cut = this.fields.indexOf(field) + 1;
        childrens = this.fields.slice(cut);
        childrens.each(function(element){
            if (element.getValue() == '' || force) {
                element.disable();
            }
        })
    },
	
    getNextField: function(field) {
        var index = this.fields.indexOf(field)  + 1;
        return this.fields[index];
    },
	
    updateChildrens: function(field) {
        this.resetChildrens(field);
        this.disableChildrens(field, true);
		
        var value = field.getValue();
        next = this.getNextField(field);
        var fields = this.fields.clone().reverse();
		
        values = fields.slice(fields.indexOf(field)).map(function(e){
            return e.getValue()
        });
		
        var hash = new Hash();
        hash.set('query',values);
		
		
        try {
			
            $$('#'+next.id+' option').each(function(option){
                option.remove()
            }); //delete all options
            next.insert(new Element('option', {
                'value':''
            }).update('---------'));
        //next.insert(new Element('option', {'value':''}).update('cualquiera'));
        } catch (e) {}
		
        if (value != '' && next != undefined) {
            new Ajax.Request(this.url + '?' + hash.toQueryString(), {
                method: 'get',
                onSuccess: function(t) {
                    data = t.responseText.evalJSON();
                    data.each(function(element){
                        next.insert(new Element('option', {
                            'value':element.pk
                        }).update(element.fields.name));
                    })
                }
            })
        }
        try {
            this.getNextField(field).enable();
        } catch (e) {}
    }
}

function updateSupply(id, response){
    str = response.substring(1, response.length);
    alert(str.evalJSON());
}

function deleteSupplyDialog(id) {
    var div="<div id=\"delete_dialog\" >";
    div +=	"<p>Estas seguro de que deseas suprimir esta oferta, una vez suprimida no podrás recuperarla.</p>";
    div +=	"<p><button onclick=\"deleteSupply("+id+")\">Borrar</button>&nbsp;&nbsp;&nbsp;&nbsp;<button onclick=\"facebox.close()\">Cancelar</button></p>";
    div +=	"</div>";
    facebox.reveal(div, null);
}

function deleteDemandDialog(id) {
    var div="<div id=\"delete_dialog\" >";
    div +=	"<p>Estas seguro de que deseas suprimir esta demanda, una vez suprimida no podrás recuperarla.</p>";
    div +=	"<p><button onclick=\"deleteDemand("+id+")\">Borrar</button>&nbsp;&nbsp;&nbsp;&nbsp;<button onclick=\"facebox.close()\">Cancelar</button></p>";
    div +=	"</div>";
    facebox.reveal(div, null);
}

function deleteSupply(id) {
    g = new k.Growler();
    url = "/mi-cuenta/borrar/oferta/" + id;
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(t) {
            if (t.responseText == 'ok') {
                $("supply-"+id).hide();
                g.growl("Oferta borrada");
            } else {
                g.growl("Hubo un error y la oferta no fue borrada");
            }
        },
        onFailure: function(t) {
            AjaxFailure(t)
        }
    });
    facebox.close();
}


function deleteDemand(id) {
    g = new k.Growler();
    url = "/mi-cuenta/borrar/demanda/" + id;
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(t) {
            if (t.responseText == 'ok') {
                $("demand-"+id).hide();
                g.growl("Demanda borrada");
            } else {
                g.growl("Hubo un error y la demanda no fue borrada");
            }
        },
        onFailure: function(t) {
            AjaxFailure(t)
        }
    });
    facebox.close();
}


function AjaxFailure(t) {
    var g = new k.Growler();
    g.growl("Hubo al contactar con el servidor, recarga la página y vuelve a intentarlo.");
}


function filereset(id) {
    $(id).setValue('');
}

function saveDemand(form_id) {
    var params = $("home_search_form").serialize();
    window.location = "/mi-cuenta/actividad/mis-demandas/?" + params + "&save.x=1";
}

var CreditsCalculator = Class.create();
CreditsCalculator.prototype = {
    initialize: function(id) {
        this.id = id;
        $$("#"+this.id+" tr td input").each(
            function(element){
                element.observe('change', function(event){
                    this.updateRow(event)
                }.bind(this))
            }.bind(this)
            );
    },
	
    updateRow: function(event) {
        var input = event.target;
        var tr = input.up(1);
        var price = tr.down('.price').innerHTML;
        var result = tr.down('.result');
		
        if (this.isInteger(input.getValue())) {
            result.update(input.getValue()*price);
        } else {
            input.setValue('');
            result.update(0);
        }
        this.updateFinalResult();
    },
	
    updateFinalResult: function() {
        var results = $$("#credits_calculator td.result").map(function(e){
            return e.innerHTML
        });
        var total = 0;
        results.each(function(e){
            total = total + parseInt(e);
        })
        $$("#"+this.id+" .finalresult").pop().update(total);
    },
	
    isInteger: function(str) {
        return parseInt(str).toString() != "NaN";
    }
}

function updateDemand(data) {
    demand = $('demand-' + data.id);
    if (data.modality) demand.down(".modality").update(data.modality);
    if (data.type) demand.down(".type").update(data.type);
    if (data.status) demand.down(".status").update(data.status);
    demand.down(".rooms").update(data.rooms);
    demand.down(".bathrooms").update(data.bathrooms);
    if (data.price_from) demand.down(".price_from").update("desde: " + data.price_from + "<br />hasta: " + data.price_to);
    if (data.m2_from) demand.down(".m2_from").update("desde: " + data.m2_from + "<br />hasta: " + data.m2_to);
}


function confirmActionPrice(price) {
    try {
        return confirm(CONFIRM_START + price + CONFIRM_END);
    } catch (err){
        return confirm("Esta acción tiene un coste de "+price+" créditos, ¿desea continuar?");
    }
}

function seleccionar_menu(name){

    var ofertas = document.getElementById(name);
    if (ofertas.className != 'cuadro-submenu_selected_fixed'){
        ofertas.className= 'cuadro-submenu_selected';
    }

}

function deseleccionar_menu(name){
    
    var ofertas = document.getElementById(name);
    if (ofertas.className != 'cuadro-submenu_selected_fixed'){
        ofertas.className= 'cuadro-submenu';
    }
}
