SITE_HOST = '/calc';

function isSet(obj) {
    return (obj != null && typeof(obj) != undefined);
}

function isEmpty(obj) {
    if(!isSet(obj)) {
        return true;
    }
    if(obj == '' || obj == 0) {
        return true;
    }
    return false;
}

window.steps = [];

function CalcStep(_container, _valid, init, extended) {
    var self = this;
    
    this.id = window.steps.length;
    window.steps.push(this);
    this.container = _container;
    this.valid = _valid;
    
    this.unblock = function() {
        this.container.css({'opacity': 1});
        this.container.find('input,select').each(function(){
            $(this).attr('disabled', false);
        });
    }
    this.block = function() {
        this.container.css({'opacity': '0.3'});
        this.container.find('input,select').each(function(){
            $(this).attr('disabled', true);
        });
    }
    this.blockAll = function() {
        for(var i=self.id+1; i<window.steps.length; i++) {
            window.steps[i].block();
        }
    }
    this.unblockAll = function() {
        this.blockAll();
        for(var i=self.id+1; i<window.steps.length; i++) {
            window.steps[i].unblock();
            if(!window.steps[i].valid()) {
                break;
            }
        }
    }
    this.unblockNext = function() {
        window.steps[self.id+1].unblock();
    }
    this.getInfo = function() {
        return this.container.data('info');
    }
    
    if(isSet(extended)) {
        for(var fName in extended) {
            self[fName] = extended[fName];
        }
    }
    
    init.apply(self, []);
}

function imageResize(img, src, callback) {
    img.setAttribute('width', '200');
    img.setAttribute('height', '200');
    img.src = src;
    img.onload = function(){
        if($.browser.msie) {
            var html = img.outerHTML;
            if(html != undefined && html.length > 0) {
                var t1 = html.split(' ');
                for(var i=0; i<t1.length; i++) {
                    var t2 = t1[i].split('=');
                    if(isEmpty(t2[0])) {
                        continue;
                    }
                    if(t2[0] == 'width') {
                        var width = parseInt(t2[1], 10);
                    }
                    if(t2[0] == 'height') {
                        var height = parseInt(t2[1], 10);
                    }
                }
            }
        } else {
            var width = parseInt(img.getAttribute('width'), 10);
            var height = parseInt(img.getAttribute('height'), 10);
        }
        if( isNaN(width) || isNaN(height) || width == 0 || height == 0 ) {
            return;
        }
        var ratio = width/height;
        var tmpImg = new Image();
        tmpImg.src = src;
        var ratioNativ = tmpImg.width/tmpImg.height;
        if( ratioNativ < ratio ) {
            img.setAttribute('height', height );
            img.removeAttribute('width');
        } else {
            img.setAttribute('width', width );
            img.removeAttribute('height');
        }
        if(typeof(callback) == 'function') {
            callback(tmpImg.width, tmpImg.height);
        }
    }
}




function calcModule() {
    var ks = parseInt(window.curImage.pixels, 10)/parseFloat(window.curImage.area);
    var width = parseInt($('#weighth').val(), 10);
    var height = parseInt($('#height').val(), 10);
    var sall = (height*width)/1000000;
    window.curRes = {};
    var s = sall*ks;
    var n = Math.ceil(s*getCoef());
    window.curRes.n = n;
    window.curRes.power = Math.ceil(1000*window.curModule.power*n*1.2)/1000;
    var price = parseFloat($('#coast').val());
    if(isNaN(price) || price == 0) {
        price = window.curModule.price;
    }
    window.curRes.price = Math.ceil(1000*price*n)/1000;
    window.curRes.area = Math.ceil(s*1000)/1000;
    $('#result').html('<p>Площадь освещения: <b>'+window.curRes.area+' м<sup>2</sup></b><br/>'+
    'Выбран модуль: <b>'+$('#modulname').val()+'</b><br/>'+
    'Количество модулей: <b>'+window.curRes.n+' (шт)</b><br/>'+
    'Суммарная мощность: <b>'+window.curRes.power+' (Вт)</b><br/>'+
    'Стоимость модулей: <b>'+window.curRes.price+' (у.е.)</b></p>');
    
    /*Foe email*/
    $('#area_email').val(window.curRes.area);
    $('#modul_email').val($('#modulname').val());
    $('#count_email').val(window.curRes.n);
    $('#power_email').val(window.curRes.power);
    $('#price_email').val(window.curRes.price);
}
function calc() {
    calcModule();
    if(window.curBlocks.length == 0) {
        return;
    }
    var blcoast = 0;
    var blpower = 0;
    var bdescs = '';
    $('#email_blocks').html('');
    for(var i=0; i<window.curBlocks.length; i++) {
        blcoast += window.curBlocks[i].count * parseFloat(window.curBlocks[i].block.price);
        blpower += window.curBlocks[i].count * parseFloat(window.curBlocks[i].block.power);
        bdescs += '<p><b>'+window.curBlocks[i].block.name+' ('+window.curBlocks[i].block.power+' Вт) - '+window.curBlocks[i].count+' (шт)</b></p>';
        $('#email_blocks').append(
            '<input name="blocks[]" type="hidden"  value="'+window.curBlocks[i].block.name+'"/>'+
            '<input name="'+window.curBlocks[i].block.name+'_email" type="hidden"  value="'+window.curBlocks[i].count+'"/>'
        );
    }
    var fulcoast = window.curRes.price + blcoast;
    $('#result').append('<p>Выбрано блоки питания:</p>'+
    bdescs+
    '<p>Сумарная мощность: <b>'+blpower+' (Вт) </b><br/>'+
    '<p>Стоимость блоков: <b>'+blcoast+' (y.e) </b><br/>'+
    '<font color="red" size="3"><b>Общая стоимость:<br/> '+fulcoast+' (у.е.)</b></font></p>');
    
    /*For email*/
    $('#blockpower_email').val(blpower);
    $('#blockprice_email').val(blcoast);
    $('#sumprice_email').val(fulcoast);
    $('#callback').show();
}
function getCoef() {
    var str = $('#ratio').val().replace(",",".");
    if (str == '--Свой вариант--') {
        return parseFloat($('#customRatioField').val());
    } else {
        return parseFloat(str);
    }
}



window.curImage = null;
window.curModule = null;
window.curBlocks = [];
window.curRes = null;


$(document).ready(function() {
    $('.steps').find('input,select').each(function(){
        $(this).attr('disabled', true);
    });
    
    
    var s1 = new CalcStep($('#imageSelect'), function() {
        return true;
    }, function(){
        var self = this;
        self.unblock();
        $('.close').click(function(){
            $('#uploadedFile').val('');
            $('#image').hide();
            $('#imageeditor').show();
            self.blockAll();
        });
        var uploader = new qq.FileUploader({
            // element: $('#profile .browse').get(0),
            button: $('#browse').get(0),
            element: $('#upload').get(0),
            action: SITE_HOST+'/default/upload/',
            // debug: true,
            params: {},
            multiple: false,
            allowedExtensions: ['jpg', 'jpeg', 'gif', 'png', 'bmp'],
            sizeLimit: 2000000,
            template: '<div class="qq-uploader">' + 
                '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
                '<div class="qq-upload-button"></div>' +
                '<ul class="qq-upload-list"></ul>' + 
             '</div>',
            onSubmit: function(id, fileName, params) {
                params.isCrop = $('#isCrop').attr('checked');
                $('#upload').val(fileName);
                $('#imageeditor').hide();
                $('#preload').show();
                return true;
            },
            onComplete: function(id, fileName, responseJSON) {
                $('#upload').val('');
                $('#preload').hide();
                self.container.find('.message').hide();
                if(responseJSON.status == 200) {
                    window.curImage = responseJSON.result;
                    if(window.curImage.pixels == 0) {
                        self.container.find('.message').text('Invalid image').show();
                    }
                    var uploadedFile = responseJSON.result.url + responseJSON.result.fileName;
                    $('#uploadedFile').val(responseJSON.result.fileName);
                    $('#imageeditor').hide();
                    $('#image').fadeIn();
                    imageResize($('#imageCont').get(0), uploadedFile, function(width, height){
                        $('#image .info').text(width+'px X '+height+'px');
                    });
                    self.unblockAll();
                } else {
                    // alert(responseJSON.result);
                    $('#imageeditor').show();
                    self.container.find('.message').text(responseJSON.result).show();
                }
            }
        });
    });
    
    var s2 = new CalcStep($('#depht'), function() {
        var weighth = parseInt($('#weighth').val(), 10);
        var height = parseInt($('#height').val(), 10);
        return (!isNaN(weighth) && !isNaN(height));
    }, function(){
        var self = this;
        $('#weighth,#height').change(function(){
            self.container.find('.message').hide();
            if(self.valid()) {
                var weighth = parseInt($('#weighth').val(), 10);
                var height = parseInt($('#height').val(), 10);
                var realRatio = Math.round(weighth/height);
                var imgRatio = Math.round($('#imageCont').width()/$('#imageCont').height());
                if(realRatio == imgRatio) {
                    self.unblockAll();
                } else {
                    self.container.find('.message').show();
                    self.blockAll();
                }
            } else {
                self.blockAll();
            }
        });
        $('#inputdepth').change( function(){
            self.initSelect();
        });
        self.initSelect();
    }, {
        initSelect: function() {
            $("#selecteble li").each(function (){
                $(this).removeClass('ui-depth');
                var depth = $("#inputdepth").val().split('-');
                var a = $(this).children(".hidden_depth");
                if ( parseFloat(a.val()) <= parseFloat(depth[1]) &&  parseFloat(a.val()) >= parseFloat(depth[0]) ) {
                    a.parent().addClass('ui-depth');
                }
            });  
        }
    });
    
    var s3 = new CalcStep($('#modulesSelect'), function() {
        return isSet(window.curModule);
    }, function(){
        var self = this;
        $('#selmodul').bind('selected', function(){
            var mname = $('.ui-selected:first .hidden_depth').attr('id');
            var smallInfo ='<div class="ui-selectmenu-smallinfo">';
            smallInfo += ' <img src="'+SITE_HOST+'/media/photos/'+mname+'.bmp" height="16" width="18"/>';
            smallInfo += ' <div class="username">'+mname+ '</div>';
            smallInfo += '</div>';
            smallInfo += '<input id="modulname" name="modul" type="hidden" value="'+mname+'">';
            $('#selectedmodul').html(smallInfo);
            self.container.find('.message').html('');
            $.ajax({
                dataType: 'json',
                data:  {'module': mname},
                url: SITE_HOST+'/default/coefs/',
                success: function( res ) {
                    var retdata = res.result;
                    window.curModule = retdata;
                    var oldVal = $('#ratio').val();
                    $('#ratio').html('<option></option>');
                    if ( retdata.coef_min != 0 && retdata.coef_norm != 0 && retdata.coef_max !=0) {
                        $('#ratio').append('<option>'+retdata.coef_min+'</option>');
                        $('#ratio').append('<option>'+retdata.coef_norm+'</option>');
                        $('#ratio').append('<option>'+retdata.coef_max+'</option>');
                    }
                    $('#ratio').append('<option>--Свой вариант--</option>');
                    if(!isEmpty(oldVal)) {
                        if($('#ratio option:contains("'+oldVal+'")')) {
                            $('#ratio').val(oldVal);
                        }
                    }
                    // unblockStep($('#coefficient'));
                    self.unblockAll();
                }
            });
        });
    });
    
    var s4 = new CalcStep($('#coefficient'), function() {
        var str = $('#ratio').val().replace(",",".");
        if (str == '--Свой вариант--') {
            var a = parseFloat($('#customRatioField').val());
        } else {
            var a = parseFloat(str);
        }
        return !isNaN(a);
    }, function(){
        var self = this;
        $('#ratio').change(function(){ 
            var str = $(this).val().replace(",",".");
            $('#customRatio').hide();
            self.container.find('.message').hide(); 
            if (str == '--Свой вариант--') {
                $('#customRatio').show();
            } else {
                if(self.valid()) {
                    self.unblockAll();
                } else {
                    // self.container.find('.message').show();
                    self.blockAll();
                }
            }
        });
        $('#customRatioField').change(function(){ 
            $("#message_coef").hide(); 
            if(self.valid()) {
                self.unblockAll();
            } else {
                self.container.find('.message').show();
                self.blockAll();
            }
        });
    });
    
    var s5 = new CalcStep($('#calc'), function() {
        return true;
    }, function(){
        var self = this;
        $('#getresult').click(function() {
            calc();
            self.unblockAll();
            $('#bp').show();
        });
    });
    
    var s6 = new CalcStep($('#bp'), function() {
        return window.curBlocks.length > 0;
    }, function(){
        var self = this;
        $('#selblock').bind('selected', function(mname){
            window.curBlocks = [];
            var smallInfo ='';
            $('.bl-selected').each(function(){
                var blockInfo = {};
                blockInfo.block = eval('('+$(this).find('.blockData').val()+')');
                blockInfo.count = $(this).find('.countered').val();
                window.curBlocks.push(blockInfo);
                
                smallInfo += 
                '<div class="ui-selectmenu-smallinfo">'+
                ' <img src="'+SITE_HOST+'/media/photos/'+blockInfo.block.name+'.bmp" height="16" width="18"/>'+
                ' <div class="username">'+blockInfo.block.name+' ('+blockInfo.count+' шт)</div>'+
                '</div>';
            });
            $('#selectedBlock').html(smallInfo);
        });
    });

    
    $('#mailForm').submit(function() {
        $('#mess').hide();
        $(this).ajaxSubmit({
            beforeSubmit:  function(formData, jqForm, options) {
                $('#mailForm').validate({
                    rules: {
                        email: {
                            required: true,
                            email: true
                        },
                        email_fname: {
                         required: true
                        },
                        email_phone: {
                         required: true
                        }
                    },
                    messages: {
                        email: {
                            required: "Введите данные",
                            email: "Неверный формат"
                        },
                        email_fname: {
                         required: "Введите данные"
                        },
                        email_phone: {
                         required: "Введите данные"
                        }
                    }
                });
                return $('#mailForm').validate().form();
            },
            success:    function(data, statusText) {
                if(data.status == 200) {
                    $('#mess').html('<p>Письмо отправлено</p>');
                } else {
                    $('#mess').html('<p>Возникла ошибка при отправке</p>');
                }
                $('#mess').show();
                // $('#send_email').hide();
            },
            url:       SITE_HOST+'/default/mail/',
            dataType:  'json'
        });
        return false;
    });
});
