/* fixes internet explorer hover for all elements
startList = function() {
	if (document.all&&document.getElementById) {
		navRoot = document.getElementById("nav");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}
window.onload=startList;
*/

setStyles = function(element, stylesString) {
  if ($.browser.msie) {
    element.styleSheet.cssText = stylesString;
  } else {
    var propToSet = $.browser.safari ? 'innerText' : 'innerHTML';
    element[propToSet] = stylesString;
  }
};
var gethits_timeout;
var estimated_count = 0;
var cache = Array();

function _(s) {
    if (window.lang_strings && lang_strings[s]) {
        return lang_strings[s];
    }
    return s;
}

function toggle(e) {
    if (e.style.display == 'none') {
        e.style.display = '';
    }
    else {
        e.style.display = 'none';
    }
}
function rih(e, s) {e.parentNode.innerHTML = s;return false;}

function clear_select(e) {
    for (var i = e.options.length; i >= 0; i--) {
        e.options[i] = null;
    }
}
function gethits_from_url(url) {
    var query_string = 'h';
    serial_form = $('#search').formSerialize();
    if (serial_form != '') {
        query_string = 'h&' + serial_form;
    }
    function update_hits(num) {
        /*
        var estimate = false;
        if (num && num[0] == '_') {
            estimate = true;
            num = num.substring(1, num.length);
        }
        */
        var parts = num.split('|');
        var hits = parseInt('0x'+parts[0]);
        if (parts[1] != undefined) {
            var avg = parseInt('0x'+parts[1]);
            $(".avg").html(_('Average price') + ': ' + avg + ' EUR');
        }
        //$("#submitbutton").attr('value', 'Found: ' + hits);
        $(".hits").html(_('Found') + ': ' + hits + ' ' + _('classifieds'));
        //$(".search_submit").val(_('Show results')+' (' + hits + ')');
        $('#search').attr('hits', parts[0]);
        if ($("fieldset.extras input:checked").length < 1) {
            estimated_count = num;
        }
    }
    var cache_key = url+'?'+query_string;
    query_string += '&ec='+estimated_count;
    if (cache[cache_key]) {
        update_hits(cache[cache_key]);
    } else {
        $.ajax({
            type: "get",
            data: query_string,
            url: url,
            dataType: "text",
            success: function(num) {
                cache[cache_key] = num;
                update_hits(num);
            }
        });
    }
}

function gethitstime() {
    if (gethits_timeout) {
        window.clearTimeout(gethits_timeout)
    }
    gethits_timeout = window.setTimeout("gethits()", 500);
}

function models(options) {
	var default_args = {
		make_id : 'make_id',
		model_id : 'model_id',
        categories : false,
        gethits : false,
        unselected : '-',
        parse_url : false
	}
	for (var index in default_args) {
		if (typeof options[index] == 'undefined') {
            options[index] = default_args[index];
        }
	}
    var make_select = $("#"+options['make_id']);
    var model_select = $("#"+options['model_id']);
    if (make_select.val() == '') {
        model_select.removeOption(/./);
        // [TODO] Replace this with a message beside it instead
        //model_select[0].disabled = true;
        model_select.addOption('', _('Select Make'), false)
        return;
    }
    var url = '/classifieds/cars/models/' + make_select.val() + '/';
    if (options['categories']) {
        url += '?e'
    }
    function populate_models(data) {
       model_select.removeOption(/./);
       model_select.addOption('', options['unselected'], false);
       for (var cat in data) {
           if (cat == 'null') {
               for (var i in data[cat]) {
                   model_select.addOption(data[cat][i][1], data[cat][i][0], false);
               }
           } else {
               var parts = cat.split('|');
               model_select.addOption(parts[1], parts[0], false);
               for (var i in data[cat]) {
                   model_select.addOption(data[cat][i][1], '\xa0\xa0\xa0'+data[cat][i][0], false);
               }
           }
       }
       // [TODO] Replace this with a message beside it instead
       //model_select[0].disabled = false;
       if (options['parse_url']) {
           var url_model = window.location.hash.substring(1, window.location.hash.length);
           if (url_model == '') {
               url_model = $(document).getUrlParam(options['model_id']);
           }
           if (url_model != null) {
               model_select.selectOptions(url_model);
           }
       }
       model_select.change(function() {
           window.location.hash = model_select.val();
       });
       if (options['gethits']) {
           gethits();
       }
    }
    if (cache[url]) {
        populate_models(cache[url]);
        return;
    } else {
        $.ajax({
               type: 'get',
               url: url,
               dataType: 'json',
               success: function(data) {
                   cache[url] = data;
                   populate_models(data);
               }
        });
    }
}


$(function(){
    $(".delete").click(function() {
        var t = $(this);
        if (confirm(_('Are you sure you want to delete this classified?'))) {
            $.ajax({
                type: "post",
                data: {},
                url: t.attr('href'),
                dataType: "text",
                success: function(data) {
                    var tbody = t.parent().parent().parent();
                    tbody.html('<tr><td style="text-align: center" colspan="4">'+data+'</td></tr>').css({'background': '#ffd'});
                }
            });
        }
        return false;
    });
});
function checkrange(val, min, max, msg) {
    if (val < min || val > max) {
        alert(msg + ' ' + _('must be between') + " [" + min + ".." + max + "]");
        return false;
    }
return true;
}
function currency_format(x) {
    var d = ''+Math.round(parseFloat(x)*100);
    for (i = d.length-5; i > 0; i -= 3) {
        d = d.substring(0, i) + '.' + d.substring(i, d.length);
        }
    return d.substring(0, d.length-2) + ',' + d.substring(d.length-2, d.length);
}
function finance() {
    payments = parseInt($("#payments").val()) || 1;
    downpay = parseInt($("#downpay").val()) || 0;
    $("#payments").val(payments);
    $("#downpay").val(downpay);
    if (!checkrange(payments, 1, i_m, _('Installments')) || !checkrange(downpay, parseInt(d_m * p_c / 100), p_c, _('Downpayment'))) {
        return;
    }
    $("#downpayment").html(downpay+'');
    $("#installments").html(payments+'');
    var principal = p_c - downpay;
    if (i_r != 0) {
        var i = i_r/0xb71b00;
        var pow = Math.pow((1+i), payments);
        $("#installment").html(currency_format((principal * pow * i) / (pow - 1)));
    }
    else {
        $("#installment").html(currency_format(principal / payments));
    }

}

