var second;
var first;
var slider;
Ext.onReady(function(){
    second = document.getElementById('second_select_sale');
    first = document.getElementById('first_select_sale');
    second.onchange = init;
    first.onchange = getSecond;

    var sl1 = Ext.getDom('sl1');
    sl1.innerHTML = "";
    slider = new Ext.Slider({
        useTips: false,
        minValue: 1,
        maxValue: 12,
        increment: 1,
        value: 1,
        width: 192,
//        cls: 'slider',
        renderTo: 'sl1',
        listeners : {
            change: function (t, x, y) {
                move(x);
            }
        }
    });
    move(1);
});


function init() {
//    rez = getValue(1);
//    $("div#rezult").html(rez);
    move(slider.getValue());
}

function getSecond(a) {
    second.disabled = true;
    var attrs = $('select#first_select_sale option:selected');
    attr = attrs[0];
    if(attr.hasAttribute('href')) {
        $.post("index.php", {
                action: "get_second_sale",
                sale_id: attr.getAttribute('href')
            },
            function(data){
//                alert(data);
                var options = eval(data);
                for(i=second.options.length-1;i>=0;i--)
                {
                    second.remove(i);
                }
                for(var i = 0; i < options.length; i++){
                    var opt = new Option(options[i].TITLE);
                    opt.setAttribute('dir',options[i].COST_1 + '#' + options[i].COST_2 + '#' + options[i].COST_3);
                    opt.setAttribute('style','width: 160px;');
                    second.options[second.options.length] = opt;
                }
                init();
                second.disabled = false;
                move(slider.getValue());
            }
        );
    }
}

 function getValue(x) {
    var res = '';
    var attrs = $('select#second_select_sale option:selected');
    attr = attrs[0];
    price = new String(attr.getAttribute('dir'));

    var prices = price.split('#');
    var colmonth = x;
    if(colmonth < 3) {
        res = prices[0];
    }else if(colmonth < 8) {
        res = prices[1];
    }else if(colmonth <= 12) {
        res = prices[2];
    }
//    var full = prices[0]*colmonth;
    var full = prices[0];
    var proc = (full - res)*100/full;
    if(res < 1000) {
        if(proc > 9) {
            proc = Math.round(proc*10)/10;
        }else {
            proc = Math.round(proc*10)/10;
        }
    }else {
        proc = Math.round(proc);
    }
    res = res*colmonth;
    res = Math.round(res*100)/100;
    res += "$ ";
    if(proc > 0) {
        res += '(-' + proc + '%)'
    }
//    return x + ' ' + colmonth;
    return res;
 }

function move(x){
     var rez = getValue(x);
     $("div#rezult").html(rez);
};

