Calc.prototype = {
    
	/**
	 * Инициализация калькулятора
	 */
    initialize: function()
    {
        this.fillData(door_type, 'door_type', 'imagelist');
        
        // отделка
        this.fillData(furnish_o, 'furnish_o', 'imagelist');
        this.fillData(furnish_i, 'furnish_i', 'imagelist');
        //this.fillListData(furnish_o_brand, 'furnish_o_brand', 'furnish_o_model');
        //this.fillListData(furnish_i_brand, 'furnish_i_brand', 'furnish_i_model');
        
        this.fillData(handle, 'handle', 'imagelist');
        
        this.fillListData(lockb_brand, 'lockb_brand', 'lockb_model');
        this.fillListData(lockt_brand, 'lockt_brand', 'lockt_model');
        
        this.fillData(bolt, 'bolt', 'imagelist');
        this.fillData(closer, 'closer', 'imagelist');
        this.fillData(box, 'box', 'imagelist');
        
        
        
        $('#furnish_o_popup ul a').click(function() { $('#furnish_o_popup2').addClass('pushow'); });
        $('#furnish_i_popup ul a').click(function() { $('#furnish_i_popup2').addClass('pushow'); });
        
        // Дополнительные параметры
        var i = 0, str = '';
        for(var key in this.add_options)
        {
        	i++;
        	if((i%2) == 0)
                str += '<div class="chbox chr">';
            else
                str += '<div class="chbox">';
        	
            str += '<input type="checkbox" id="'+ key +'" /><label for="'+ key +'">'+ this.add_options[key].name +'</label>;';

            if((i%2) == 0)
                str += '</div><div class="spacer">&nbsp;</div>';
            else
                str += '</div>';
        }
        
        str += '<div class="spacer">&nbsp;</div>';
        $('#add_options').append(str);
    },
    
    
    /**
     * Устанавливает значение переменное для дальшейшего расчёта по формуле
     * @param {String} option имя опции
     * @param {String} value значение опции
     * @param {String} name именованное значение опции, которое будет установлено в инпут привязанный к этой опции
     */
    setOption: function(option, value, name)
    {
        this[option] = value;
        $('#' + option).val(name);
    },
    
    
    /**
     * Устанавливает дефолтные параметры для параметров калькулятора
     */
    setDefaults: function()
    {
        // тип двери
        this.setOption('door_type', door_type[0].price, door_type[0].name);
        
        // внешняя отделка 
        this.setOption('furnish_o', 0, furnish_o[0].name);
        //this.setOption('furnish_o_model', 0, furnish_o_brand[0].models[0].name);
        //this.fillData(furnish_o_brand[0].models, 'furnish_o_model', 'imagelist');
        
        // внутренняя отделка
        this.setOption('furnish_i', 0, furnish_i[0].name);
        //this.setOption('furnish_i_brand', furnish_i_brand[0].price, furnish_i_brand[0].name);
        //this.setOption('furnish_i_model', 0, furnish_i_brand[0].models[0].name);
        //this.fillData(furnish_i_brand[0].models, 'furnish_i_model', 'imagelist');
        
        // ручка
        this.setOption('handle', handle[0].price, handle[0].name);
        
        // нижний замок
        this.setOption('lockb_brand', lockb_brand[0].price, lockb_brand[0].name);
        this.setOption('lockb_model', lockb_brand[0].models[0].price, lockb_brand[0].models[0].name);
        this.fillData(lockb_brand[0].models, 'lockb_model', 'imagelist');
        
        // верхний замок
        this.setOption('lockt_brand', lockt_brand[0].price, lockt_brand[0].name);
        this.setOption('lockt_model', lockt_brand[0].models[0].price, lockt_brand[0].models[0].name);
        this.fillData(lockt_brand[0].models, 'lockt_model', 'imagelist');
        
        // задвижка
        //this.setOption('bolt', bolt[0].price, bolt[0].name);

        // доводчик
        //this.setOption('closer', closer[0].price, closer[0].name);

        // коробка
        //this.setOption('box', box[0].price, box[0].name);
    },
    
    
    /**
     * Наполняет попап данными
     * @param {Array} data массив с данными
     * @param {String} id ID элемента
     * @param {String} type тип 
     */
    fillData: function(data, id, type)
    {
        if('imagelist' == type)
        {
            /**
            * Список с картинками
            */
            var src = $('#' + id + '_popup .carousel ul');
            $('#' + id + '_popup').toggleClass('pushow');
            src.html('');
            for(var i = 0, len = data.length; i < len; i++)
            {
                var price = data[i].price;
                if ('furnish_o' == id || 'furnish_i' == id)
                {
                    price = i;
                }
                src.append('<li><a href="javascript:void(0);" onclick="calc.setOption(\''+ id +'\', \''+ price +'\', \''+ data[i].name +'\'); $(\'#' + id + '_popup\').removeClass(\'pushow\'); "><img src="'+ data[i].pic +'" alt="" /><span>'+ data[i].name +'</span></a><span>'+ data[i].price +' руб.</span></li>');
            }

            if(len % 4 != 0)
            {
                for(var i=0; i < 4 - len%4 ; i++)
                {
                    src.append('<li></li>');
                }
            }
	       
            $('#' + id + '_popup .carousel').jCarouselLite({
                 btnNext: "#" + id + "_popup .next",
                 btnPrev: "#" + id + "_popup .prev",
                 visible: 4,
                 scroll: 4,
                 circular: false
            });
		
            $('#' + id + '_popup').toggleClass('pushow');
            
            $("#" + id + "_popup .prev").addClass('disabled');

            if(len <= 4)
                $("#" + id + "_popup .next").addClass('disabled');
        }
        else if('list' == type)
        {
            /**
            * Список        
            */

            var src = $('#' + id + '_popup ul');
            src.html('');
            
            for(var i = 0, len = data.length; i < len; i++)
            {
                src.append('<li><a href="javascript:void(0);" onclick="calc.setOption(\''+ id +'\', \''+ data[i].price +'\', \''+ data[i].name +'\'); $(\'#' + id + '_popup\').removeClass(\'pushow\'); ">'+ data[i].name +'</a></li>');
            }
            src.append('<div style="float:left;z-index:1000;width:100%;cursor:hand;background:url(\'/i/collapse_bt.gif\') 45px 0px no-repeat;height:16px;" onclick="$(\'#' + id + '_popup\').removeClass(\'pushow\'); "></div>');		
        }
        
    	if( type != 'list')
    	   src.append('<div style="float:left;z-index:1000;cursor:hand;width:100%;background:url(\'/i/collapse_bt_wide.gif\') 5px 0px repeat-x;height:16px;" onclick="$(\'#' + id + '_popup\').removeClass(\'pushow\'); "></div>');	
    },
    
    
    
    
    fillListData: function(data, brandId, modelId)
    {
        this.fillData(data, brandId, 'list');
        $('#'+ brandId + '_popup .ulselect a').click(function()
        {
            calc.fillData(data[calc[brandId]].models, modelId, 'imagelist');
        })
    },

    
    calculate: function()
    {
        // Расчёт основных параметров
        var width = parseInt($('#width').attr('value'));
        var height = parseInt($('#height').attr('value'));
        
        // Площадь
        var area = parseFloat((width / 1000) * (height / 1000));
        
        // Базовая конфигурация
        var base = Math.round((area - 1.6) * this.param1 + this.param2);
        // Тип двери
        var door_type = this.door_type;

        // Наличник
        var lock_plate = $('#lock_plate').attr('checked') == true ? this.lock_plate_c : 0;
        
        var lock_plate_decor_o = (this.lock_plate_decor_sign_o == 1) ? this.lock_plate_decor_o_c : 0;
        var lock_plate_decor_i = (this.lock_plate_decor_sign_i == 1) ? this.lock_plate_decor_i_c : 0;
        
        // Отделка внешняя
        var id = this.furnish_o; // id
        var furnish_o_ = (furnish_o[id].sign == 1) ? furnish_o[id].price : Math.round(area) * furnish_o[id].price;
        
        // Отделка внутренняя
        id = this.furnish_i; // id
        var furnish_i_ = (furnish_i[id].sign == 1) ? furnish_i[id].price : Math.round(area) * furnish_i[id].price;
        
        // Ручки
        var handle = this.handle;
        
        // Замок нижний
        var lock_bottom = this.lockb_model;
        
        // Замок верхний
        var lock_top = this.lockt_model;
        
        // Задвижка
        var bolt = this.bolt;
        
        // Доводчик
        var closer = this.closer;
        
        // Утепление
        var heat = $('#heat').attr('checked') == true ? this.heat_c * Math.round(area) : 0;
        
        // Коробка
        var box = this.box;
        
        // 2 лист металла
        var list_2nd = $('#list_2nd').attr('checked') == true ? this.list_2nd * Math.round(area) : 0;
        
        // Расчёт дополнительных параметров
        var add_options = 0;
        for(var key in this.add_options)
        {
            if($('#' + key).attr('checked') == true)
                add_options += this.add_options[key].price;
        }
        
        // Проверка
        if(isNaN(area) || !area)    { alert('Укажите габариты двери'); return; }
        //if(!door_type)     { alert('Укажите тип двери'); return; }
        //if(isNaN(furnish_o) || !furnish_o) { alert('Укажите тип внешней отделки'); return; }
        //if(isNaN(furnish_i) || !furnish_i) { alert('Укажите тип внутренней отделки'); return; }
        //if(!handle)        { alert('Укажите используемую ручку'); return; }
        
        //if(!lock_bottom)   { alert('Укажите нижний замок'); return; }
        //if(!lock_top)      { alert('Укажите верхний замок'); return; }
        //if(!bolt)          { alert('Укажите задвижку'); return; }
        //if(!closer)        { alert('Укажите доводчик'); return; }
        //if(!box)           { alert('Укажите коробку'); return; }
            
        // Рассчёт суммы
        var sum;
        sum  = parseInt(base) + parseInt(lock_plate) + parseInt(door_type) + parseInt(lock_plate_decor_o);
        sum += parseInt(lock_plate_decor_i) + parseInt(furnish_o_) + parseInt(furnish_i_) + parseInt(handle);
        sum += parseInt(lock_bottom) + parseInt(lock_top) + parseInt(bolt) + parseInt(closer) + parseInt(heat);
        sum += parseInt(box) + parseInt(list_2nd) + parseInt(add_options);
        
        // Блок вывода результатов
        $('.cell.komplekt').css('display', 'block');
        $('#result_block').html('Габариты: ' + parseInt(height/10) + 'cм х '+ parseInt(width/10) +' cм.<br />');
        $('#result_block').append('Тип двери: '+ $('#door_type').attr('value') +'<br />');
        $('#result_block').append('Наличник: '+ ((lock_plate) ? 'есть' : 'нет') +'<br />');
        
        $('#result_block').append('Отделка внешняя: '+ $('#furnish_o').attr('value') +'<br />');
        $('#result_block').append('Отделка внутреняя: '+ $('#furnish_i').attr('value') +'<br />');
        
        $('#result_block').append('Ручка: '+ $('#handle').attr('value') +'<br />');
        $('#result_block').append('Замок верхний: '+ $('#lockt_brand').attr('value') +', '+ $('#lockt_model').attr('value') +'<br />');
        //$('#result_block').append('Замок верхний: <a href="'+ lockt_brand[calc.lockt_brand].url +'">'+ $('#lockt_brand').attr('value') +'</a>, '+ $('#lockt_model').attr('value') +'<br />');
        $('#result_block').append('Замок нижний: '+ $('#lockb_brand').attr('value') +', '+ $('#lockb_model').attr('value') +'<br />');
        //$('#result_block').append('Замок нижний: <a href="'+ lockb_brand[calc.lockb_brand].url +'">'+ $('#lockb_brand').attr('value') +'</a>, '+ $('#lockb_model').attr('value') +'<br />');
        if(bolt) $('#result_block').append('Задвижка: '+ $('#bolt').attr('value') +'<br />');
        if(closer) $('#result_block').append('Доводчик: '+ $('#closer').attr('value') +'<br />');
        $('#result_block').append('Утепление: '+ ((heat) ? 'есть' : 'нет') +'<br />');
        if(box) $('#result_block').append('Коробка: '+ $('#box').attr('value') +'<br />');
        $('#result_block').append('2-й лист металла: '+ (list_2nd ? 'есть' : 'нет') +'<br />');
        
        if(add_options)
        {
            $('#result_block').append('Дополнительные параметры:<ul></ul>');
            for(var key in this.add_options)
            {
                if($('#' + key).attr('checked') == true)
                {
                    $('#result_block ul').append('<li>'+ this.add_options[key].name +'</li>')
                }
            }
        }
        
        $('#result_sum').html('<span class="price">'+ parseInt(sum) +'</span> руб.');
    }
}




$(document).ready(function()
{
    calc = new Calc();
    calc.initialize();
    calc.setDefaults();

    $('#calculate').click(function() { calc.calculate(); return false; })
    
    calc.calculate();

    /*
    // ширина
    $('#width').focus(function() {
        if($(this).val() == '800')
            $(this).val('');
    });

    // высота
    $('#height').focus(function() {
        if($(this).val() == '2000')
            $(this).val('');
    });
    */
});
