/**
 * Вывод страницы продукта
 * @param {Object} params параметры
 */
Umnitsa.Interface.Products.Page = function(params) {

    var params = mergeHash(params, {
        selector : '#prod-page',
        videoFadeDuration : 250
    });

    var $wrap = $(params.selector);
    var productId, variantId;
    var $variants;

    var cache;

    /**
     * Инициализация
     */
    function _init_() {
        // Определим id продукта
        productId = $wrap.children('input[name="product_id"]').val();

        // Кнопка купить
        $wrap.find('#product-buy-btn').click(function() {
            buy(this);
        });

        // Кнопка кредита
        $wrap.find('#product-credit-btn').click(function() {
            buy(this, { credit : 1 });
        });


        // Варианты товара
        $variants = $wrap.find('.variants li');
        $variants.find('input').change(function() {
            variantId = this.value;
        });

        // Настройка «умных» ссылок
        $wrap.find('a.smart').click(smartLinkHandler);

        cache = new Object();
    }

    function buy(link, params) {
        if ($variants.length) {
            if (variantId) {
                eStore.addToBasket(productId + ':' +variantId, link, params);
            }
        } else {
            eStore.addToBasket(productId, link, params);
        }
    }

    /**
     * Обработчик умных ссылок
     */
    function smartLinkHandler() {
        var anchor = this.href.split('#', 2)[1];
        if (anchor !== '') {
            anchor = anchor.split(':');
            var method = anchor[0];
            var id = anchor[1];
            doSmart(method, id, this);
            return false;
        }

    }
    function doSmart(method, id, el) {
        switch (method) {
            case 'picture' :
                showPicture(id, el);
                break;

            case 'multiview' :
                showMultiview(id, el);
                break;

            case 'video' :
                showVideo(id, el);
                break;

            case 'award' :
                showAward(id, el);
                break;

            case 'good' :
            case 'bad' :
            case 'question' :
            case 'friend' :
            case 'callback' :
                showPopupForm(method, el);
                break;

            case 'wishlist' :
                addToWishList(el);
                break;
        }
    }

    /**
     * Показать картинку с камментов
     * @param {Number} id ID объекта
     * @param {Object} [el] Элемент, вызвавший
     */
    function showPicture(id, el) {
        var cacheKey = 'pitcure' + id;
        if (!cache[cacheKey]) {
            Umnitsa.Loader.show(el);
            Umnitsa.getJSON({
                '_do' : 'get_picture',
                'id' : id
            }, function(data) {
                Umnitsa.Loader.hide();
                cache[cacheKey] = data.c;
                Umnitsa.Popup.showHTML({
                    html : data.c,
                    css : 'picture',
                    width: 450
                });
            });
        } else {
            Umnitsa.Popup.showHTML({
                html : cache[cacheKey],
                css : 'picture',
                width: 450
            });
        }
    }

    /**
     * Показать награду
     */
    function showAward(id) {
        var cacheKey = 'award' + id;
        if (!cache[cacheKey]) {
            Umnitsa.getJSON({
                '_do' : 'get_award',
                'id' : id
            }, function(data) {
                cache[cacheKey] = data.c;
                Umnitsa.Popup.showHTML(data.c);
            });
        } else {
            Umnitsa.Popup.showHTML(cache[cacheKey]);
        }
    }

    /**
     * Показать форму
     */
    function showPopupForm(name) {
        var cacheKey = 'form_' + name;
        if (!cache[cacheKey]) {
            Umnitsa.getJSON({
                '_do' : 'get_popup_form',
                'name' : name,
                'product_id' : productId
            }, function(data) {
                cache[cacheKey] = data.c;
                popupForm(data.c);
            });
        } else {
            popupForm(cache[cacheKey]);
        }
    }
    function popupForm(html) {
        Umnitsa.Popup.showHTML({
            html : html,
            css : 'ball'
        });
        var $form = Umnitsa.Popup._$.find('form').submit(formSubmitHandler);
        $form.find('.submit>span').click(function() {
            $form.triggerHandler('submit');
        });
    }
    function formSubmitHandler() {
        var $form = $(this)
        $form.find('.field').removeClass('error');
        var params = $form.serializeArray();
        params.push({ name : '_do', value : 'submit_form' });
        Umnitsa.getJSON(params, formResponseHandler);
        Umnitsa.Loader.show($form.find('.submit>span'));
        return false;
    }
    function formResponseHandler(data) {
        Umnitsa.Loader.hide();
        var $form = Umnitsa.Popup._$.find('form');
        if (data.errors) {

            for (var i = 0; i < data.errors.length; i++) {
                $form.find('.attr-' + data.errors[i]).addClass('error');
            }
        } else if (data.c) {
            $form.parent().html('<div class="text">' + data.c + '</div>');
        }
    }


    /**
     * Показать мультивью картинок
     * @param {Number} id ID объекта
     * @param {Object} el вызвавший объект
     */
    function showMultiview(id, el) {
        var cacheKey = 'multiview' + id;
        if (!cache[cacheKey]) {
            Umnitsa.Loader.show(el);
            Umnitsa.getJSON({
                '_do' : 'get_multiview',
                'id' : id
            }, function(data) {
                Umnitsa.Loader.hide();
                cache[cacheKey] = data;
                Umnitsa.Popup.showMultiview(data);
            });
        } else {
            Umnitsa.Popup.showMultiview(cache[cacheKey]);
        }
    }

    function addToWishList() {
        Umnitsa.getJSON({
            '_do' : 'wish_list',
            'method' : 'add',
            'id' : productId
        }, wishListHandler);
    }
    function wishListHandler(data) {
        if (data.register) {
            Umnitsa.showAuthForm(data.message);
        } else {
            Umnitsa.Popup.showHTML({
                html : data.message,
                css : 'ball'
            });
        }
    }

    function showVideo(id, el) {
        var cacheKey = 'video' + id;
        if (!cache[cacheKey]) {
            Umnitsa.getJSON({
                '_do' : 'get_video',
                'id' : id
            }, function(data) {
                cache[cacheKey] = data;
                playVideo(data);
            });
        } else {
            playVideo(cache[cacheKey]);
        }
    }

    function playVideo(data) {
        var $photo = $wrap.find('.photo');
        if (jQuery.isFunction(window.hideVideo))
            window.hideVideo();

        var $video = $(document.createElement('div')).addClass('video').hide().appendTo($photo);
        var spanObject = document.createElement('span');
        spanObject.id = 'flashvideo' + data.id;
        $video.append(spanObject);

        swfobject.embedSWF("/i/f/mplayer.swf", spanObject.id, "240", "180", "8.0.0", "", {'clip' : data.src}, {'wmode' : 'opaque'}, {});
        var $img = $photo.find('img').animate({ 'opacity' : 0 }, params.videoFadeDuration);
        $video.fadeIn(params.videoFadeDuration);
        window.hideVideo = function() {
            $img.animate({ 'opacity' : 1 }, params.videoFadeDuration);
            $video.fadeOut(params.videoFadeDuration, function() { $video.remove() });
            window.hideVideo = null;
        }
    }

    _init_();
}

