﻿//AttachmentBox
(function ($) {

    var methods = {
        init: function (options) {

            var settings = {
                PostBackControlID: 'fakeID',
                RefreshInterval: 0,
                AddNew: true,
                InitArray: [],
                FileError: false
            };

            //options
            if (options) {
                jQuery.extend(settings, options);
            }
            //fileupload styling

            jQuery.fn.choose = function (f) {
                jQuery(this).bind('choose', f);
            };


            jQuery.fn.file = function () {
                return this.each(function () {
                    var btn = jQuery(this);
                    var pos = btn.offset();

                    function update() {
                        pos = btn.offset();
                        file.css({
                            'top': pos.top,
                            'left': pos.left,
                            'width': btn.width(),
                            'height': btn.height()
                        });
                    }

                    btn.mouseover(update);

                    var file = jQuery('.NewFileUpload').css({
                        'position': 'absolute',
                        'overflow': 'hidden',
                        '-moz-opacity': '0',
                        'filter': 'alpha(opacity: 0)',
                        'opacity': '0',
                        'z-index': '2'
                    });

                    function reset() {
                        file.change(function (e) {
                            jQuery(this).unbind();
                            btn.trigger('choose', jQuery(this));
                            reset();
                        });
                    };

                    reset();

                    function btnInPos(e) {
                        var res = false;

                        if ((pos.left <= e.pageX) && (e.pageX <= pos.left + btn.width())) {
                            if ((pos.top <= e.pageY) && (e.pageY <= pos.top + btn.height())) {
                                res = true;
                            }
                        }
                        return res;
                    }

                    function placer(e) {
                        if (btnInPos(e)) {
                            file.css('left', e.pageX - file.width() + 25);
                            file.css('top', e.pageY - file.height() / 2 + 3);
                        }
                        else {
                            file.css('left', pos.left);
                            file.css('top', pos.top);
                        }
                    }

                    function redirect(name) {
                        file[name](function (e) {
                            btn.trigger(name);
                        });
                    }

                    file.mousemove(placer);
                    btn.mousemove(placer);

                    redirect('mouseover');
                    redirect('mouseout');
                    redirect('mousedown');
                    redirect('mouseup');

                    update();
                });
            };

            //functionality
            window.parent.ResponseAttachmentIframeCallback(window, settings.AddNew, false, settings.InitArray);
            jQuery(this).each(function () {
                var $this = jQuery(this);
                //trigger file select dialog here
                $this.find('.AddAttachmentTrigger').file().choose(function () {
                    window.parent.ResponseAttachmentIframeCallback(window, false, false, null, true);
                    __doPostBack(settings.PostBackControlID, '');
                });
                $this.find('a.Delete').click(function () {
                    window.parent.ResponseAttachmentIframeCallback(window, false, true);
                    __doPostBack(jQuery(this).attr('rel'), '');
                });
                $this.find('a.RotateCCW').click(function () {
                    window.parent.ResponseAttachmentIframeCallback(window, false, false);
                    __doPostBack(jQuery(this).attr('rel'), '');
                });
                $this.find('a.RotateCW').click(function () {
                    window.parent.ResponseAttachmentIframeCallback(window, false, false);
                    __doPostBack(jQuery(this).attr('rel'), '');
                });
                $this.find('a.ErrorAction').click(function () {
                    window.parent.ResponseAttachmentIframeCallback(window, settings.FileError, true);
                    __doPostBack(jQuery(this).attr('rel'), '');
                });
                $this.mouseover(function () {
                    $this.find('.ResponseAttachmentToolbox').show();
                });
                $this.mouseout(function () {
                    $this.find('.ResponseAttachmentToolbox').hide();
                });
                if (settings.RefreshInterval > 0) {
                    setInterval(
                        function () {
                            window.parent.ResponseAttachmentIframeCallback(window, false, false);
                            __doPostBack($this.find('.UpdateTrigger').attr('name'), '');
                        }, 
                        settings.RefreshInterval);
                }
            });
        }
    };

    $.fn.AttachmentBox = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.AttachmentBox');
        }

    };

})(jQuery);

//ResponseAttachmentClientEntry
(function ($) {

    var methods = {
        //Returns MediaEntry object assotiated with current DOM element
        init: function (options) {
            //functionality
            return { AttachmentID: jQuery(this).find('iframe').contents().find('.AttachmentState input').val() };
        }
    };

    $.fn.ResponseAttachmentClientEntry = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.ResponseAttachmentClientEntry');
        }

    };

})(jQuery);

//ResponseAttachmentClientArray
(function ($) {

    var methods = {
        init: function (options) {

            //ResponseAttachmentClientArray class
            function ResponseAttachmentClientArray(attachmentsArray) {
                var that = this;

                var data = attachmentsArray;
                this.Attachments = function () { return data ? data : []; }

            };
            //functionality

            var $this = jQuery(this);
            var data = $this.data("ResponseAttachmentClientArray");
            if (!data) {
                var data = jQuery.parseJSON($this.val());
                if (!data) {
                    data = [];
                }
                $this.data("ResponseAttachmentClientArray", new ResponseAttachmentClientArray(data.Attachments));
                return $this.data("ResponseAttachmentClientArray");
            }
            else {
                return data;
            }

        }
    };

    $.fn.ResponseAttachmentClientArray = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.ResponseAttachmentClientArray');
        }

    };

})(jQuery);

function ResponseAttachmentIframeCallback(wnd, addNew, hideSender, initArray, fileUploaded) {
    jQuery('iframe', '.ResponseAttachments').each(function () {
        var match = false;
        if (this.contentWindow) {
            match = this.contentWindow === wnd;
        }
        else {
            match = this.contendDocument === wnd;
        }
        if (match) {
            var $this = jQuery(this);
            $this.parents('.ResponseAttachments').ResponseAttachments().ToggleSpinner($this, addNew, hideSender, initArray, fileUploaded);
        }
    });
}

//ResponseAttachments
(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
                ClientAttachmentsArraySelector: 'fakeSelector',
                AttachmentsIframeUrl: '/Templates/Responses/Attachment.aspx',
                ResponseID: -1,
                AddNew: true
            };

            //options
            if (options) {
                jQuery.extend(settings, options);
            }

            //ResponseAttachments class

            function ResponseAttachments(settings) {
                var that = this;
                //private fields
                var attachmentsArray = jQuery(settings.ClientAttachmentsArraySelector).ResponseAttachmentClientArray();
                //public methods
                var GetIframeSrc = function (attachmentEntry) {
                    if (attachmentEntry == undefined) {
                        attachmentEntry = {};
                    }
                    var templates = [];
                    templates['New'] =
                        settings.AttachmentsIframeUrl + '?responseid={0}';
                    templates['Edit'] =
                        settings.AttachmentsIframeUrl + '?attachmentid={0}';
                    return !attachmentEntry.AttachmentID
                        ? templates['New'].replace('{0}', settings.ResponseID)
                        : templates['Edit'].replace('{0}', attachmentEntry.AttachmentID);
                }

                var RenderAttachment = function (attachmentEntry, prepend) {
                    if (attachmentEntry == undefined) {
                        attachmentEntry = {};
                    }
                    var $container = settings.$Container;
                    //<iframe style="display: none;" src="'
                    //    + GetIframeSrc(attachmentEntry)
                    //    + '" />
                    var newElement = jQuery(
                        '<div class="ResponseAttachmentClientEntry Loading'
                        + '"></div>');
                    var $entry;
                    if (!prepend) {
                        $container.append(newElement);
                        $entry = $container.find('.ResponseAttachmentClientEntry:last');
                    }
                    else {
                        var $entries = $container.find('.ResponseAttachmentClientEntry');
                        if ($entries.length >= 2) {
                            $container.find('.ResponseAttachmentClientEntry:last').before(newElement);
                        }
                        else {
                            $container.append(newElement);
                        }
                        $entries = $container.find('.ResponseAttachmentClientEntry');
                        if ($entries.length >= 2) {
                            $entry = jQuery($entries[$entries.length - 2]);
                        }
                        else {
                            $entry = $container.find('.ResponseAttachmentClientEntry:last');
                        }
                    }

                    $entry.append('<iframe style="display: none;" src="'
                        + GetIframeSrc(attachmentEntry)
                        + '" />');

                    //events
                    var $iframe = $entry.find('iframe');
                    $iframe.load(function () {
                        $entry.removeClass('Loading');
                        jQuery(this).show();
                    });
                }
                var haveNewAttachmentRendered = false;
                this.RenderNewAttachmentBox = function () {
                    if (!settings.$Container) {
                        return;
                    }
                    if (!haveNewAttachmentRendered) {
                        RenderAttachment();
                        haveNewAttachmentRendered = true;
                    }
                };
                this.Render = function () {
                    if (!settings.$Container) {
                        return;
                    }
                    //rendering iframes

                    var entries = attachmentsArray.Attachments();

                    for (var i = 0; i < entries.length; i++) {
                        RenderAttachment(entries[i]);
                    }

                    if (settings.AddNew) {
                        that.RenderNewAttachmentBox();
                    }
                };
                this.ToggleSpinner = function ($iframe, addNew, hideSender, initArray, fileUploaded) {
                    $entity = $iframe.parent();
                    if (fileUploaded) {
                        haveNewAttachmentRendered = false;
                    }
                    if (hideSender) {
                        $entity.hide();
                    }

                    if ($iframe.css('display') == 'none') {
                        $iframe.show();
                    }
                    else {
                        $iframe.hide();
                    }
                    $entity.toggleClass('Loading');

                    if (initArray) {
                        if (initArray.length > 0) {
                            for (var i = 0; i < initArray.length; i++) {
                                RenderAttachment({AttachmentID: initArray[i]}, true);
                            }
                        }
                    }

                    var $container = settings.$Container;
                    var clientEntries = $container.find(".ResponseAttachmentClientEntry").ResponseAttachmentClientEntry();

                    if (addNew) {
                        that.RenderNewAttachmentBox();
                    }
                    
                    var entry = $entity.ResponseAttachmentClientEntry();
                    if (entry.AttachmentID == -1) {
                        $entity.hide();
                    }
                };

                //setup on load
            }

            //functionality

            var $this = jQuery(this);
            var localSettings = {
                ClientAttachmentsArraySelector: settings.ClientAttachmentsArraySelector,
                AttachmentsIframeUrl: settings.AttachmentsIframeUrl,
                ResponseID: settings.ResponseID,
                $Container: $this,
                AddNew: settings.AddNew
            }
            var data = $this.data("ResponseAttachments");
            if (!data) {
                $this.data("ResponseAttachments", new ResponseAttachments(localSettings));
                return $this.data("ResponseAttachments");
            }
            else {
                return data;
            };
//            return new ResponseAttachments(localSettings);
        }
    };

    $.fn.ResponseAttachments = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.ResponseAttachments');
        }

    };

})(jQuery);
