var pw = pw || {}; // Namespace

pw.ProductBuilder = function(config) { // Init
    this.config = config;
    this.uploader = {};
    this.blueprintData = {};

    if (!$('#upload-container').length) {
        return;
    }

    this.setupUploader();
    this.setupEvents();
    this.selectBlueprintTab($('#blueprint').val());
    this.changeImageCount($('#blueprintMaxImages').val());
/*
    var jsonresponse = jQuery.parseJSON(response.response);

    if (jsonresponse !== null)
    {
        if('errorMessage' in jsonresponse)
        {
            alert(jsonresponse.errorMessage);
            $('#uploade-container').show();
        }
        else
        {

        }
    }
    */
};
pw.ProductBuilder.prototype = { // Functions
    setupEvents: function() {
        var self = this;

        window.onbeforeunload = function() {
            if ($('.pictures .loading').lenght) {
                return 'You are uploading files. Sure you want to leave this page?';
            }
        };

        $('.removeImage').click(function(event) {
            event.preventDefault();

            var img = $(this).siblings('div').find('img');
            if (img.length)
            {
                var div = $(this).siblings('div');
                var li  = div.parent('li');

                div.addClass('deleting');
                img.clearQueue().fadeTo(1000, 0.4);

                $.post('/external/PW_ProductBuilder/remove', {'index': li.index()}, function(data) {
                    div.removeClass('deleting');
                    if (data == 1)
                    {
                        img.clearQueue().fadeOut(400, function() {
                            img.remove();
                            div.addClass('empty');
                            div.html('<span class="info">'
                                + ext.JavaScriptTools.translate('productBuilderRemoveImageInfo')
                                + '</span>');
                            //li.parent().append(li);

                            self.refreshFreeSlots();
                            //$('#upload-container').find('*').trigger('click');
                        });
                    }
                    else
                    {
                        img.clearQueue().fadeTo(500, 1.0);
                    }
                });
            }
            else
            {
                var div = $(this).siblings('div');
                div.html('<span class="info">'
                    + ext.JavaScriptTools.translate('productBuilderRemoveImageInfo')
                    + '</span>');
            }
        });

        $('.productType li a').click(function(event) {
            event.preventDefault();

            var blueprintId = String($(this).attr('id')).replace('pid-', '');
            $('#blueprint').val(blueprintId);

            self.selectBlueprintTab(blueprintId);

            var imageCountUpdated = false;
            if (blueprintId in self.blueprintData)
            {
                self.changeImageCount(self.blueprintData[blueprintId]['imageCount']);
                self.changeBlueprintVariantData(blueprintId);
                imageCountUpdated = true;
            }

            // Tell backend what blueprint we should use
            $.post('/external/PW_ProductBuilder/updateBlueprint', {'id': blueprintId, 'cid': $('#categoryId').val()}, function(data) {
                if (!imageCountUpdated && data)
                {
                    self.blueprintData[blueprintId] = data;
                    self.changeImageCount(self.blueprintData[blueprintId]['imageCount']);
                    self.changeBlueprintVariantData(blueprintId);
                }
            }, 'json');
        });

        $('#addToCart').click(function(event) {
            var emptySlots = $('.pictures .empty:visible').length;
            if (emptySlots > 0) {
                event.preventDefault();
                alert(ext.JavaScriptTools.translate('productBuilderMoreFreeSlots'));
            }
        });
    },

    setupUploader: function() {
        var self = this;
        self.uploader = new plupload.Uploader({
            runtimes : 'html5,flash',
            browse_button : 'upload-button',
            container : 'upload-container',
            max_file_size : '20mb',
            multipart : false,
            url : '/external/PW_ProductBuilder/upload/',
            flash_swf_url : '/js/plupload/plupload.flash.swf',
            filters : [
                {title : "Images", extensions : "jpeg,jpg,gif,png"}
            ]
        });

        self.uploader.init();

        self.uploader.bind('FilesAdded', function(up, files) {
            up.start();
        });

        self.uploader.bind('UploadFile', function(up, file) {
            var emptySlots = $('.pictures .empty:visible');
            if (emptySlots.length)
            {
                $(emptySlots[0]).addClass('loading').removeClass('empty');
            }
        });

        self.uploader.bind('FileUploaded', function(up, file, response) {
            var freeSlots = $('.pictures .loading');
            if (freeSlots.length)
            {
                var jsonResponse = jQuery.parseJSON(response.response);
                $(freeSlots[0]).removeClass('loading');

                if (jsonResponse !== null)
                {
                    if('errorMessage' in jsonResponse)
                    {
                        $(freeSlots[0]).empty();
                        $(freeSlots[0]).append($('<span class="info">' + jsonResponse.errorMessage + '</span>'));
                        $(freeSlots[0]).addClass('empty');
                        /*
                        var div = $(this).siblings('div');
                        div.addClass('empty');
                        div.html('<span class="info">'
                            + jsonResponse.errorMessage
                            + '</span>');
                        */
                    }
                    else
                    {
                        var newImage = $('<img src="' + jsonResponse.url + '" />');
                        $(newImage).hide();
                        $(freeSlots[0]).empty();
                        $(freeSlots[0]).append(newImage);
                        $(newImage).fadeIn(800);
                    }
                    self.refreshFreeSlots();
                }
            }
        });

    },

    selectBlueprintTab: function(blueprintId) {
        var tab = $('#pid-' + blueprintId);
        tab.parent().siblings().find('a').removeClass('selected');
        tab.addClass('selected');
    },

    changeImageCount: function(count) {
        var li = $('.pictures li');
        li.show();
        li.eq(count - 1).nextAll().hide();

        $('#addToCart').attr('class', '').addClass('count-' + count);

        this.refreshFreeSlots();
    },

    changeBlueprintVariantData: function(blueprintId) {
        var variants = this.blueprintData[blueprintId]['variants'];
        var variantIndex = 0;
        var variantId = 0;
        for (variantId in variants)
        {
            if (variants.hasOwnProperty(variantId))
            {
                variantIndex++;

                var label = $('.variant-' + variantIndex);
                if (label.length)
                {
                    $(label).find('input').val(variantId);
                    $(label).find('.variant-name').text(variants[variantId]['name']);
                    $(label).find('.variant-price').html(variants[variantId]['price']);
                }
            }
        }
    },

    refreshFreeSlots: function() {
        var self = this;

        var freeSlots = $('.pictures li div.empty:visible').length;
        if (freeSlots > 0) {
            $('#upload-maxed-notice').hide();
            $('#upload-info').show();
            $('#upload-container').show();

            self.uploader.refresh();
        } else {
            $('#upload-container').hide();
            $('#upload-info').hide();
            $('#upload-maxed-notice').show();
        }
    }
};


$(function() { // Instances
    var ProductBuilder = new pw.ProductBuilder({
//        'blueprintValue': '#blueprint',
//        'blueprints': '.productType li'
    });
});

