

// Register namespaces
if (typeof iJ == 'undefined') {
    iJ = {
        Service: {},
        Block: {}
    };
}

//
// iJ Autoload blocks
//
$(function() {
    iJ.get('Loader').run();
});

//
// iJ ServiceFactory
//
iJ.Service.ServiceFactory = function() {
    var self = this;
    
    this.services = {};
    this.get = function(name) {
        if (self.services[name] === undefined)
            self.services[name] = self.inst(name);
        return self.services[name];
    }
    this.inst = function(name) {
        return new iJ.Service[name]();
    }
}

//
// Init Service Factory
//
;(function() {
    var sf = new iJ.Service.ServiceFactory();
    // Create aliases
    iJ.get = sf.get;
    iJ.inst = sf.inst;
})();


//
// iJ Data Store
//
iJ.Service.DataStore = function() {
    this.data = {};
    this.set = function(id, data) {
        this.data[id] = data;
    }
    this.use = function(id) {
        return this.data[id];
    }
}



//
// iJ Event Dispatcher
//
iJ.Service.EventDispatcher = function() {
    this.listeners = {};
    this.connect = function (name, listener) {
        if (this.listeners[name] === undefined) {
            this.listeners[name] = [];
        }
        this.listeners[name].push(listener);
    }
    this.notify = function (name, params) {
        if (this.listeners[name] === undefined) {
            return;
        }
        for (var i = 0; i < this.listeners[name].length; i++) {
            this.listeners[name][i](params);
        }
    }
}


//
// iJ Loader
//
iJ.Service.Loader = function() {
    var self = this;
    this.blocks = function() {
        $('[class^="b-"]').each(function() {
            self.block($(this));
        });
    };
    this.block = function(block) {
        var c = block.attr('class').split(' ');
        for (var i = 0; i < c.length; i++) {
            if (/^b-/.test(c[i])) {
                if (iJ.Block[c[i]] !== undefined) {
                    new iJ.Block[c[i]](block);
                }
            }
        }
    }
    this.run = function() {
        this.blocks();
    }
}


//
// iJ Cookie
//
iJ.Service.Cookie = function() {
    var self = this;
    
    this.get = function(name) {
        var parts = (document.cookie || '').split(';');
        for (var i = 0; i < parts.length; i++) {
            var h = parts[i].split('=');
            if ($.trim(h[0]) == name) return decodeURIComponent(h[1]);
        }    
    }
    
    this.set = function (name, value, expires, path, domain, secure) {
        var cookie = [];
        cookie.push(name + "=" + encodeURIComponent(value));
        if (expires) {
            cookie.push("expires=" + expires.toGMTString());
        }
        if (path) {
            cookie.push("path=" + path);
        }
        if (domain) {
            cookie.push("domain=" + domain);
        }
        if (secure === true) {
            cookie.push("secure");
        }
        document.cookie = cookie.join(';');
    }

    this.getHash = function(name) {
        try {
            return $.evalJSON(self.get(name));
        }
        catch (e) {
            return [];
        }
    }
    
    this.setHash = function(name, value, expires, path, domain, secure) {
        self.set(name, $.toJSON(value), expires, path, domain, secure);
    }
}



//
// Cart Service
//
iJ.Service.ProductCart = function() {
    var self = this;
    
    this.readStore = function() {
        return iJ.get('Cookie').getHash('productcart') || [];
    }
    
    this.saveStore = function(value) {
        var date = new Date();
        date.setTime(date.getTime() + (30*24*60*60*1000));
        iJ.get('Cookie').setHash('productcart', value, date, '/')
    }
    
    this.find = function(id, cart) {
        if (!cart) cart = self.readStore();
        for (var i = 0; i < cart.length; i++) {
            if (cart[i].id == id) {
                return i;
            }
        }
        return false;
    }
    
    this.add = function(id, price) {
        var cart = self.readStore();
        if (!cart) cart = [];
        var i = self.find(id, cart);
        if (i === false) {
            var p = {
                'id': id,
                'price': price,
                'count': 1
            };
            cart.push(p);            
        }
        else {
            cart[i].count = parseInt(cart[i].count)+1;
        }
        self.saveStore(cart);
        iJ.get('EventDispatcher').notify('productcart.onupdate');
    }
    
    this.setCount = function(id, count) {
        var cart = self.readStore();
        if (!cart) cart = [];
        var i = self.find(id, cart);
        if (i !== false) {
            cart[i].count = parseInt(count);          
        }
        self.saveStore(cart);
        iJ.get('EventDispatcher').notify('productcart.onupdate');        
    }
    
    this.remove = function(id) {
        var cart = self.readStore();
        var nc = [];
        for(var i = 0; i < cart.length; i++) {
            if (cart[i].id != id) {
                nc.push(cart[i]);
            }
        }
        self.saveStore(nc);
        iJ.get('EventDispatcher').notify('productcart.onupdate');
    }
    
    this.clear = function() {
        self.saveStore([]);
        iJ.get('EventDispatcher').notify('productcart.onupdate');
    }
    
    this.sum = function() {
        var cart = self.readStore();
        var s = 0.0;
        for (var i = 0; i < cart.length; i++) {
            s += parseFloat(cart[i].price)*parseInt(cart[i].count);
        }
        return s;
    }
    
    this.count = function() {
        var cart = self.readStore();
        var c = 0;
        for (var i = 0; i < cart.length; i++) {
            c += parseInt(cart[i].count);
        }
        return c;
    }

}



iJ.Block['b-gallery-short'] = function(block) {
    block.find('a').fancybox();
}

iJ.Block['b-gallery-main'] = function(block) {
    block.find('a').fancybox();
}

iJ.Block['b-images'] = function(block) {
    block.find('a').fancybox();
}

iJ.Block['b-contacts-list'] = function(block) {
    block.find('.image a').fancybox();
}

//
//  Content block
//
iJ.Block['b-content'] = function(block) {
    
    //Add fancybox gallery to images
    $('a.image-inline-content', block).fancybox();
}
iJ.Block['b-news'] = function(block) {
    
    //Add fancybox gallery to images
    $('a.image-inline-content', block).fancybox();
}
iJ.Block['b-product'] = function(block) {
    
    //Add fancybox gallery to images
    $('a.image-inline-content', block).fancybox();
    $('.back a', block).click(function(e) {
        e.preventDefault();
        history.go(-1);
    });
}

//
//  Top cart block
//
iJ.Block['b-top-cart'] = function(block) {
    var fade = block.find('.fade').css('opacity', 0.7);

    var update = function() {
        var cart = iJ.get('ProductCart');
        var count = cart.count();
        var sum = cart.sum();
        if (count) {
            fade.hide();
        }
        else {
            fade.show();
        }
        block.find('.count').text(parseInt(count));
        block.find('.sum').text(parseFloat(sum));
    }
    iJ.get('EventDispatcher').connect('productcart.onupdate', update);
    update();
}


//
// Top image block
//
iJ.Block['b-top-image'] = function(block) {
    var im = block.find('.canvas .image');
    block.find('.thumbs .image img').each(function(i,v) {
        var index = im.length-1 - i;
        $(v).click(function() {
            if ($(im[index]).is(':visible')) return;
            im.filter(':visible').fadeOut();
            $(im[index]).fadeIn();
        });
    });
}


//
// Products categories block
//
iJ.Block['b-prod-category'] = function(block) {    
/*
    block.find('.haschild > a').click(function(e) {
        e.preventDefault();
        var t = $(this).next();
        if (!t.parent().hasClass('selected')) {
            //Up over slider here
            t.parents('.haschild').children('a').next().addClass('_notcollapse');
            block.find('.selected.haschild > a').next().each(function() {
                var s = $(this);
                if (!s.hasClass('_notcollapse'))
                    s.hide(0, function() { 
                        $(this).parent().removeClass('selected');
                        $(this).prev().removeClass('expanded'); 
                    });
            });
            t.parents('.haschild').children('a').next().removeClass('_notcollapse');
        }
        
        
        t.toggle(0,function() { 
            $(this).parent().toggleClass('selected');
            if ($(this).paren().is('td')) {
                $(this).prev().toggleClass('expanded');
            } 
        });
    });
    
    /*
    var first = true;
    block.find('.expand a').click(function(e) {
        e.preventDefault();
        if (first) {
            block.find('.haschild > a').next().slideDown(function() { $(this).parent().addClass('selected'); });
            first = false;
        }
        else {
            block.find('.haschild > a').next().slideToggle(function() { $(this).parent().toggleClass('selected'); });
        };
        var t = $(this);
        var m = t.text();
        t.text(t.attr('toggletext'));
        t.attr('toggletext',m);
    });
    */
    
    block.find('.selected').children('ul').show();
}

//
// Production companies list
//
iJ.Block['b-proizv-list'] = function (block) {
    block.find('.item .image').hover(function() {
        var t = $(this);
        if (t.find('img').length < 2) return;
        t.find('img:last').fadeOut();
        t.find('img:first').fadeIn();
    }, function() {
        var t = $(this);
        if (t.find('img').length < 2) return;
        t.find('img:first').fadeOut();
        t.find('img:last').fadeIn();
    });
}


//
//
//
iJ.Block['b-product-images'] = function (block) {
    var i = block.children('.image').find('img');
    var l = block.find('.thumbs img').click(function(e) {
        e.preventDefault();
        var t = $(this);
        i.load(function() { 
            i.fadeIn();
            i.unbind('click').click(function() {
                $.fancybox([{
                    'href': t.attr('srcimage'),
                    'title': t.attr('title')
                }], {'type': 'image'});
            }); 
        }).fadeOut(function() { i.attr('src', t.attr('bigimage')) });
    });
    i.unbind('click').click(function() {
        var t = l.eq(0); 
        $.fancybox([{
            'href': t.attr('srcimage'),
            'title': t.attr('title')
        }], {'type': 'image'});
    });    
    
}


//
//
//
iJ.Block['b-menu'] = function (block) {
    return;
    var l = block.find('td > a');
    var showed = null;
    l.mouseover(function() {
        var t = $(this);
        var p = t.parent();
        if (p.find('.submenu').is(':visible')) return;
        if (showed) {
            showed.fadeOut();
            showed.parent().children('a').removeClass('unone');
        }
        showed = null;
        if (p.hasClass('haschild')) {
            showed = p.find('.submenu').fadeIn();
            t.addClass('unone');
        }
    });
    
}


//
//
//
iJ.Block['b-search'] = function (block) {
    var form = block.find('form');
    block.find('.button a').click(function(e) {
        e.preventDefault();
        form.get(0).submit();
    });
}


//
//
//
iJ.Block['b-action-tocart'] = function (block) {
    block.click(function(e) {
        e.preventDefault();
        
        var id = parseInt(block.attr('productid'));
        var store = iJ.get('DataStore').use('product-'+id);
        if (store) {
            var cart = iJ.get('ProductCart');
            cart.add(store.id, store.price);
        }
        
        setTimeout(function() {
            var prev = block.text();
            block.text('добавлено');
            setTimeout(function() {
                block.text(prev);
            }, 3000);
        },100);
    });
}


//
//
//
/*
iJ.Block['b-cart-page'] = function (block) {
    var f = block.find('.list .quant input[type=text]');
    f.keydown(function(e) {
        var s = '0'.charCodeAt(0);
        var t = '9'.charCodeAt(0);
        if ( (e.which < s || e.which > t) && e.which != 8 && e.which != 46 && e.which != 37 && e.which != 39) {
            e.preventDefault();
        }
    });
    f.keyup(function(e) {
        var t = $(this);
        var v = parseInt($(e.target).val() || 0);
        if (v < 1) {
            v = 1; t.val(v);
        }
        var id = parseInt(t.parent().find('[type=hidden]').val());
        var cart = iJ.get('ProductCart');
        cart.setCount(id, v);
    });
    
    block.find('.list .fromcart a').click(function(e) {
        e.preventDefault();
        var t = $(this);
        var id = t.attr('productid');
        
        var cart = iJ.get('ProductCart');
        cart.remove(id);
        t.parents('tr:eq(0)').remove();
    });

    block.find('.list tr.total .fromcart a').unbind('click').click(function(e) {
        e.preventDefault();
        var t = $(this);
        var cart = iJ.get('ProductCart');
        cart.clear();
        block.children('.list, .button').remove();
    });
    
    block.children('.clearcart').find('a').click(function(e) {
        e.preventDefault();
        var t = $(this);
        var cart = iJ.get('ProductCart');
        cart.clear();
        block.children('.list, .button').remove();
    });
    
    var update = function() {
        var cart = iJ.get('ProductCart');
        var count = cart.count();
        var sum = cart.sum();
        var total = block.find('.list tr.total');
        total.find('.price .value').text(parseFloat(sum));
        total.find('.count .value').text(parseInt(count));
        
        if (!count) {
            block.children('.list, .button').remove();
        }
    }
    
    iJ.get('EventDispatcher').connect('productcart.onupdate', update);
    update();
}
*/
iJ.Block['b-cart-list'] = function (block) {
    var f = block.find('.list-list .quant input[type=text]');
    f.keydown(function(e) {
        var s = '0'.charCodeAt(0);
        var t = '9'.charCodeAt(0);
        if ( (e.which < s || e.which > t) && e.which != 8 && e.which != 46 && e.which != 37 && e.which != 39) {
            e.preventDefault();
        }
    });
    f.keyup(function(e) {
        var t = $(this);
        var v = parseInt($(e.target).val() || 0);
        if (v < 1) {
            v = 1; t.val(v);
        }
        var id = parseInt(t.parent().find('[type=hidden]').val());
        var cart = iJ.get('ProductCart');
        cart.setCount(id, v);
    });
    
    block.find('.list-list .fromcart a').click(function(e) {
        e.preventDefault();
        var t = $(this);
        var id = t.attr('productid');
        
        var cart = iJ.get('ProductCart');
        cart.remove(id);
        t.parents('.b-cart-list-item:eq(0)').remove();
    });
    
    var update = function() {
        var cart = iJ.get('ProductCart');
        var count = cart.count();
        var sum = cart.sum();
        var total = block.find('.list-total');
        total.find('.price .value').text(parseFloat(sum));
        
        if (!count) {
            block.children('.list-list, .list-total, .control').remove();
        }
    }
    
    iJ.get('EventDispatcher').connect('productcart.onupdate', update);
    update();
    
    
    block.find('.list-list .quant:eq(0)').each(function() {
        var t = $(this);
        t.tipsy({
            gravity: 's',
            fallback: 'Вы можете изменить количество',
            trigger: 'manual',
            fade: true,            
        });
        var m = t.tipsy(true);
        m.show();
        setTimeout(function() {
            m.hide();
        },9000);
    });
}


iJ.Block['b-order'] = function (block) {

    block.find('.top .sum').text(iJ.get('ProductCart').sum());
    

    var self = this;
    var form = block.find('.form');
    
    this.checker = {
        "name": function (v) { return /.+/.test(v); }
        , "phone": function (v) { return !v || /^([0-9-+ )(*#])+$/.test(v); }
        , "email": function (v) { return !v || /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(v); }
    }
      
    this.serialize = function () {
        var data = {};
        form.find('input,textarea').each(function() {
            var t = $(this);
            var name = t.attr('name');
            if (data[name]) {
                if (t.attr('checked')) data[name] = t.val();
            }
            else {
                data[name] = t.val();
            }
        });
        return data;
    }
    
    this.errors = function (data) {
        var errors = {};
        for (var i in data) {
            if (self.checker[i] && !self.checker[i](data[i],data)) {
                errors[i] = true;
            }
        }
        return errors;
    }
    

    this.submit = function () {
        var data = self.serialize();
        var errors = self.errors(data);
        var fail = false;
        for (var i in errors) {
            form.find('input[name='+i+']').tipsy(true).show();
            fail = true;
        }
        if (fail) return;
        
        $.ajax({
            'type': 'post',
            'data': data,
            'url': '/.order.post',
            'dataType': 'json',
            'success': function(data) {
                if (data.success) {
                    self.sendsuccess();
                }
                else {
                    self.senderror();
                }
            },
            'error': function() {
                self.senderror();
            }
        });
        block.find('.submit a').unbind('click').click(function(e) {
            e.preventDefault();
        }).text('Обработка');
    }

    this.sendsuccess = function() {
        form.hide();
        block.find('.f-caption').text('Заявка принята.').show();
        iJ.get('ProductCart').clear();
    }

    this.senderror = function() {
        form.hide();
        block.find('.f-caption').text('Отправка завки завершилась неудачей, пожалуйста повторите позже.').show();
    }

    block.find('.submit a').click(function(e) {
        e.preventDefault();
        self.submit();
    });


    form.find('input').tipsy({
        gravity: 's',
        fallback: 'Поле заполнено некорректно',
        trigger: 'manual',
        fade: true
    }).bind('focus', function() {
        $(this).tipsy(true).hide();
    });

    
}








//
//
//
iJ.Block['b-faq-form'] = function (block) {

    var self = this;
    var form = block.find('.form');
    
    this.checker = {
        "question": function(v) { return /.+/.test(v); }
        , "name": function (v) { return /.+/.test(v); }
        , "email": function (v) { return !v || /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(v); }
    }
      
    this.serialize = function () {
        var data = {};
        form.find('input,textarea').each(function() {
            var t = $(this);
            var name = t.attr('name');
            if (data[name]) {
                if (t.attr('checked')) data[name] = t.val();
            }
            else {
                data[name] = t.val();
            }
        });
        return data;
    }
    
    this.errors = function (data) {
        var errors = {};
        for (var i in data) {
            if (self.checker[i] && !self.checker[i](data[i],data)) {
                errors[i] = true;
            }
        }
        return errors;
    }
    

    this.submit = function () {
        var data = self.serialize();
        var errors = self.errors(data);
        var fail = false;
        for (var i in errors) {
            form.find('[name='+i+']').tipsy(true).show();
            fail = true;
        }
        if (fail) return;
        
        $.ajax({
            'type': 'post',
            'data': data,
            'url': '/faq.post',
            'dataType': 'json',
            'success': function(data) {
                if (data.success) {
                    self.sendsuccess();
                }
                else {
                    self.senderror();
                }
            },
            'error': function() {
                self.senderror();
            }
        });
        block.find('.submit input').unbind('click').click(function(e) {
            e.preventDefault();
        }).text('Обработка');
    }

    this.sendsuccess = function() {
        form.hide();
        block.find('h2').text('Вопрос принята.').show();
    }

    this.senderror = function() {
        form.hide();
        block.find('h2').text('Отправка вопроса завершилась неудачей, пожалуйста повторите позже.').show();
    }

    block.find('.submit input').click(function(e) {
        e.preventDefault();
        self.submit();
    });


    form.find('input, textarea').tipsy({
        gravity: 's',
        fallback: 'Заполнено некорректно',
        trigger: 'manual',
        fade: true
    }).bind('focus', function() {
        $(this).tipsy(true).hide();
    });

}







//
//
//
/*
iJ.Block['b-order-form'] = function (block) {

    var self = this;
    var form = block.find('.form');
    
    this.checker = {
        "company": function(v,data) { return (data.face == 'company') ? /.+/.test(v) : true; }
        , "name": function (v) { return /.+/.test(v); }
        , "city": function (v) { return /.+/.test(v); }
        , "address": function (v) { return /.+/.test(v); }
        , "phone": function (v) { return /^([0-9-+ )(*#])+$/.test(v); }
        , "email": function (v) { return !v || /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(v); }
    }
      
    this.serialize = function () {
        var data = {};
        form.find('input').each(function() {
            var t = $(this);
            var name = t.attr('name');
            if (data[name]) {
                if (t.attr('checked')) data[name] = t.val();
            }
            else {
                data[name] = t.val();
            }
        });
        return data;
    }
    
    this.errors = function (data) {
        var errors = {};
        for (var i in data) {
            if (self.checker[i] && !self.checker[i](data[i],data)) {
                errors[i] = true;
            }
        }
        return errors;
    }
    

    this.submit = function () {
        var data = self.serialize();
        var errors = self.errors(data);
        var fail = false;
        for (var i in errors) {
            form.find('input[name='+i+']').tipsy(true).show();
            fail = true;
        }
        if (fail) return;
        
        $.ajax({
            'type': 'post',
            'data': data,
            'url': '/.order.post',
            'dataType': 'json',
            'success': function(data) {
                if (data.success) {
                    self.sendsuccess();
                }
                else {
                    self.senderror();
                }
            },
            'error': function() {
                self.senderror();
            }
        });
        block.find('.button a').unbind('click').click(function(e) {
            e.preventDefault();
        }).text('Обработка');
    }

    this.sendsuccess = function() {
        form.hide();
        block.children('.message').text('Заявка принята.').show();
        iJ.get('ProductCart').clear();
    }

    this.senderror = function() {
        form.hide();
        block.children('.message').text('Отправка завки завершилась неудачей, пожалуйста повторите позже.').show();
    }

    block.find('.button a').click(function(e) {
        e.preventDefault();
        self.submit();
    });


    form.find('input').tipsy({
        gravity: 'w',
        fallback: 'Поле заполнено некорректно',
        trigger: 'manual',
        fade: true
    }).bind('focus', function() {
        $(this).tipsy(true).hide();
    });

}
*/

















