var youtube = $.inherit(Module, {
    __constructor: function(div) {
        this.__base(div);
        this.type = "youtube";
        var tmp = this; // necessary
        var minWidth = 175; // used when there is no embed line
        this.isResizing = true;
        this.keepAspectRatio = false;
        this.container = $('.module-container', this.element);
    },

    lyOnResize: function (newWidth, newHeight, resizeIframe) {
        this.checkResize(newWidth, newHeight, resizeIframe);
    },

    lyOnResizing: function (newWidth, newHeight, resizeIframe) {
        this.checkResize(newWidth, newHeight, resizeIframe);
    },

    checkResize: function (newWidth, newHeight, resizeIframe) {
        // state 1 = first drop;
        // state 0 = resizing;
        // state 2 = after embed code is added;
        var state = Lycos.ui.regionCtrl.callingResize;
        var iframe = document.getElementById(resizeIframe);
        var div = iframe.contentWindow.document.getElementById("youtube"+this.instId);
        var objct = div.getElementsByTagName('object')[0];
        var embed = div.getElementsByTagName('embed')[0];

        if(state && state == 1){
            newHeight = 285;
            newWidth = 340;
        }
        // width
        if(div.style.width.replace("px", "") != newWidth || state == 2){
            div.style.width = (embed || newWidth > minWidth) ? newWidth+"px" : minWidth+"px";
            if(embed){ // video
                embed.style.width = newWidth+"px";
                objct.style.width = newWidth+"px";
            }
            else{ // no video
                iframe.style.width = (newWidth > minWidth) ? newWidth+"px" : minWidth+"px";
            }
        }
        // height
        if (div.style.height.replace("px", "") != newHeight || state == 2) {
            var minHeight = (newWidth < 203) ? 45 : 25;
            div.style.height = (embed || newHeight > minHeight) ? newHeight+"px" : minHeight+"px";
            if(embed){ // video
                embed.style.height = newHeight+"px";
                objct.style.height = newHeight+"px";
            }
            else{ // no video
                iframe.style.height = (newHeight > minHeight) ? newHeight+"px" : minHeight+"px";
            }
        }
    },

    loadModule: function(postSaveData, doSizing, floatVal, callback) {
        // Clear out the contents of the div (needed for proper loading of images)
        this.addLoadingDiv();

        if (postSaveData) {
            this.postSaveData = postSaveData;
        }

        var _this = this;

        // Get the JSON string (including HTML) representing this module's data
        $.ajax({url: '/frame.php?' + this.getAJAXParams(), 
            async: false,
            dataType: "json",
            success: function(data, textStatus) {
                _this.loadModuleCallback(data, textStatus);
                (callback || $.noop)();
            }
        });
    },


    // This is called as a callback from loadModule.
    // It should also be called directly by modules that overload loadModule and avoid calls to frame2 on init (like customHtml).
    loadModuleCallback: function(data, textStatus) {
        // Store the returned data so we can access it later on
        this.moduleData = data;

        // We need to use innerHTML here because of the (highly probable)
        // chance that the html we get back has <script> in it.  jQuery 1.4
        // tries to be smart and not insert non-standard code.
        this.container[0].innerHTML = data.html;

        // Handle actions to be taken after the saving of this module's settings
        if (this.postSaveData) {
            this.handleModuleSaveResult(this.postSaveData);
            this.postSaveData = '';
        }

        // Since the HTML we just inserted could contain <script>,
        // move them to a place where they'll get executed.
        $("script", this.container).each(function() {
            if ($(this).text() == "") {
                $.getScript($(this).attr("src"));
            }
            else {
                $("body").append(this);
            }
        });

        this.addDragHandle(data);

        // If a module has declared itself resizing, make it so...
        if ( this.isResizing ) {
          this.addResizing();
        }

        // Make sure embed tag is properly resized
        this.resizeEmbedTag();
    },

    // When this module contains a valid YouTube video, the video's embed tag has to be height and 
    // width 100% of the module container
    resizeEmbedTag: function() {
        $('embed', this.container).css({ 'width': '100%', 'height': '100%' });

        // Remove any height and width attributes for the embed and object tags in the module container,
        // because the size of these should be determined by the size of the module container div
        $('embed', this.container).attr({ 
            width: '100%',
            height: '100%'
        });

        $('object', this.container).removeAttr('width').removeAttr('height');
    },


    /* Adds resize handles and functionality to the module div */
    addResizing: function() {
        var _this = this;
        var aspectRatio = 0;

        // Destroy the current handle (needed for returning from preview mode) and create a new one
        this.container.resizable('destroy');

        this.container.resizable({
                handles: "se", 
                containment: this.element.parent(), 
                aspectRatio: this.keepAspectRatio, 
                minHeight: 40,
                minWidth: 84,
                autoHide: false,
                start: function(e, ui) {
                        _this.element.unbind('mouseleave');
                        aspectRatio = ui.originalSize.height / ui.originalSize.width;
                        $("<div />", { "class": "resizeDimensions" }).appendTo(_this.container).fadeIn("fast");

                        _this.element.find('embed').css('height', '100%');
                    },

                resize: function(e, ui) {
                        var w = _this.container.width();
                        var h = _this.container.height();

                        _this.onResize(e, ui);

                        _this.element.css({
                            width: w + "px",
                            height: h + "px"
                        });

                        _this.setDragHandlePosition();
                        $('.resizeDimensions', _this.container).html(w + "x" + h);
                    },

                stop: function(e, ui) {
                        _this.element.bind('mouseleave', function() {
                            if (_this.doOnMouseOut) {
                                _this.doOnMouseOut();
                            }
                            else {
                                _this.draghandle.fadeOut(_this.mouseFadeOutTime);
                            }
                        });

                        if (_this.keepAspectRatio) {
                          var resizeTo = Math.round(_this.container.width() * aspectRatio);
                          // Retain the aspect ratio based on width.
                          _this.element.css({'height': resizeTo + "px"});
                          _this.container.css({'height': resizeTo +  "px"});
                        }

                        $(".resizeDimensions", _this.container).fadeOut("fast").remove();
                    } 
        });
    }
});

