xhr = {
    script: function(html) {
    	var scriptIndex = 0;
    	var IWScripts = new Array();
    	document.onIWRun = null;
    	document.IWLoaded = true;

    	html = html.replace(/<(\/?)script/gi, "<$1script");
    	var scriptStart = html.indexOf("<script");
    	var scriptEnd = -1;
    	var scriptBody = "";

    	while(scriptStart > -1) {
    		scriptEnd = html.indexOf("</script>")+9;
    		scriptBody = html.substring(html.indexOf(">", scriptStart)+1, scriptEnd - 9);

    		document.onIWComplete = null;
    		try {
    			eval(scriptBody);
    		} catch (e) {
    			window.console.log(e);
    		}
    		if (document.onIWComplete) {
    			IWScripts[scriptIndex] = document.onIWComplete;
    			scriptIndex++;
    		}

    		html = html.substring(0,scriptStart) + html.substring(scriptEnd, html.length);
    		scriptStart = html.indexOf("<script");
    	}

    	if (typeof document.onIWRun == 'function') {
    		document.onIWRun(html);
    	}

    	if (IWScripts.length) {
    		for (var i = 0; i < IWScripts.length; i++) {
    			try {
    				IWScripts[i]( );
    			} catch (e) {
    				window.console.log(e);
    			}
    		}
    	}
    },

    action: function(obj, $container) {
        var action,
            title,
            $this       = $(obj),
            $preloader  = $('div.preloader'),
            $status     = $('<div>');

        action  = obj.action || obj.href,
        title   = obj.title || action;

        if (!$preloader.length) {
            $preloader  = $('<div>')
                            .addClass('preloader')
                            .prependTo('body');
        }

        if ($this.attr('title') !== false && typeof title == 'string') {
            $preloader.show();
            $status.text(title).appendTo($preloader);
        }

        function success(html) {
            var bodyStart   = html.toLowerCase().indexOf("<body>"),
                bodyEnd     = html.toLowerCase().indexOf("</body>");

            if (bodyStart > -1 && bodyEnd > -1)  {
                html = html.substring( bodyStart + 6, bodyEnd );
            }

            $container.html(html);

            $status.fadeOut('fast', function(){
                if ($preloader.find('div').length) $preloader.remove();
                if ($overlay) $overlay.remove();
            });
            
            if ($.fn.tipsy) $('input[title], textarea[title], select[title]').tipsy({ trigger:'focus', gravity:'sw'});
            $container.find('input.required').first().focus();
        }

        function error() {
            if ($overlay) $overlay.remove();
            $status
                .addClass('e')
                .append('<em>(404)</em>')
                .delay(2000)
                .fadeOut(function(){
                    $(this).remove();
                    if ($preloader.find('div').length) $preloader.remove();
                });
        }

        if ($container) {
            var $overlay = $('<div>')
                            .addClass('xhr-overlay')
                            .prependTo($container);

            function offset() {
                var h   = $container.height(),
                    w   = $container.width();

        		$overlay.css({ width:w, height:h });
            }

            offset();

            $(window).resize(function() {
        		offset();
        	});
        }

        if ($this.is('form')) {
    		  var options = {
    			  type: 'post',
    			  url: action,
    			  success: function(html) {
    				  success(html);
    			  },
    			  error: function() {
    			    error();
    			  }
    		  };
    		  $this.ajaxSubmit(options);
    	  } else {
    		  $.ajax({
    			  type: 'get',
    			  url: action,
    			  success: function(html) {
    				  success(html);
    			  },
    			  error: function() {
    			      error();
    			    }
    		  });
    	  }
    },

    refresh: function(url) {
        if (typeof url == 'undefined' || !url) {
            window.location.reload(true);
        } else {
            window.location.href = url;
        }
    }

};


(function($) {
    var Modal = function(options, $this) {
        var self = this;
        var settings = $.extend(this, $.fn.modal.constructor, options);

        if ($this) {
            $this.bind('click', function(e) {
                self.init(this);
                e.preventDefault();
            });
        } else {
            self.init();
        }
    };

    $.modal = function(options) {
         new Modal(options);
    };

    $.fn.modal = function(options) {
        return this.each(function(){
            var $this = $(this);
            if (!$this.data('modal')) {
                var modal = new Modal(options, $this);
                $this.data('modal', modal);
            }
        });
    };

    $.fn.modal.constructor = {
        url: false,
        content: '',
        data: {},
        scroll: 1,
        modal: 1,
        overlay: 1,
        opacity: 0.8,
        view: 1,
        move: 0,
        close: 0,
        container: 'body',
        cache: 0,

        init: function(opener) {
            this.opener = opener || false;
            if (this.url === false && this.content === '') this.url = this.opener.href;

            $(this.opener).addClass('active');

            if (this.$modal) {
                if (!this.$modal.is(':visible')) {
                    if (this.cache) {
                        this.show();
                    } else {
                        this.remove();
                        this.create();
                    }
                } else {
                    this.remove();
                }
            } else {
                this.create();
            }
        },

        create: function(){
            
            var self = this;

            if (this.url) {
                var $preloader  = $('div.preloader'),
                    title       = this.opener && $(this.opener).attr('title') ? $(this.opener).attr('title') : this.url;

                !$preloader.length ? $preloader = $('<div>').addClass('preloader').prependTo('body') : $preloader.show();

                this.$preloader ? this.$preloader.text(title) : this.$preloader = $('<div>').text(title);

                if (!self.$preloader.hasClass('a')) this.$preloader.appendTo($preloader).addClass('a').show(); // feautures
            }

            if (this.container == 'body') {
                if (!this.scroll) window.scroll(0, 0);

                this.$modal = $(
                    '<table class="modal' + ( this.scroll ? ' modal-scrollable' : '') + ' modal-view' + this.view + '">' +
                        '<tr>' +
                            '<td class="modal">' +
                                '<table class="modal-wrapper">' +
                                    '<tr>' +
                                        '<td class="modal-wrapper">' +
                                            '<div class="modal-window">' +
                                                '<div class="modal-menu">' +
                                                    '<a class="modal-remove" href="./">x</a>' +
                                                '</div>' +
                                                '<div class="modal-content xhr-container"></div>' +
                                            '</div>' +
                                        '</td>' +
                                    '</tr>' +
                                '</table>' +
                            '</td>' +
                        '</tr>' +
                    '</table>'
                ).hide();
            } else {
                this.$modal = $(
                    '<div class="modal-bind modal-view' + this.view + '">' +
                        '<div class="modal">' +
                            '<div class="modal-spacer"></div>' +
                            '<div class="modal-window">' +
                                '<div class="modal-menu">' +
                                    '<a class="modal-remove" href="./">x</a>' +
                                '</div>' +
                                '<div class="modal-content xhr-container"></div>' +
                            '</div>' +
                        '</div>' +
                    '</div>'
                ).hide();
            }

            if (this.overlay) {
                this.$overlay = $('<div class="modal-overlay"><iframe></iframe></div>');
                this.$overlay
                    .css({ display:'none', opacity:self.opacity })
                    .appendTo('body')
                    .fadeTo('fast', self.opacity);
            }

            this.$modal.appendTo(this.container);

            this.$window = this.$modal.find('table.modal-window');
            this.$content = this.$modal.find('div.modal-content');

            this.$modal.delegate('.modal-remove', 'click', function(e){
                self.remove();
                e.preventDefault();
            });
            this.$modal.delegate('a.modal-reload', 'click', function(e){
                xhr.action(this, self.$content);
                e.preventDefault();
            });

            
            if (!this.modal) {
                self.docevnt = function(e){
                    if (!(self.opener && self.opener == e.target || $(self.opener).has(e.target).length) && (self.$window.get(0) != e.target && !self.$window.has(e.target).length)) {
                        self.remove();
                    }
                };
                $(document).bind('click', self.docevnt);
            }

            if (this.url) {
                $.ajax({
                    type: 'get',
                    url: self.url,
                    data: self.data,
                    success: function(html) {
                        var bodyStart   = html.toLowerCase().indexOf("<body>"),
                            bodyEnd     = html.toLowerCase().indexOf("</body>");

                        if (bodyStart > -1 && bodyEnd > -1)  {
                            html = html.substring( bodyStart + 6, bodyEnd );
                        }

                        self.$content.html(html);
                        self.$modal.show();
                        self.$preloader.fadeOut('slow', function(){
                            $(this).remove();
                            if (!$preloader.find('div').length) $preloader.hide();
                        });
                        
                        if ($.fn.tipsy) $('input[title], textarea[title], select[title]').tipsy({ trigger:'focus', gravity:'sw'});
                        self.$content.find('input').not(':hidden').first().focus();
                    },
                    error: function() {
                        self.$modal.remove();
                        if (self.overlay) self.$overlay.hide();
                        self.$preloader
                            .addClass('e')
                            .append('<em>(404)</em>')
                            .delay(2000)
                            .fadeOut(function(){
                                $(this).remove();
                                delete self.$preloader;
                                if (!$preloader.find('div').length) $preloader.hide();
                            });
                    }
                });
            } else {
                self.$content.html(self.content);
                self.$modal.show();
                self.$preloader.fadeOut('slow', function(){ $(this).remove(); });
            }
        },

        show: function() {
            var self= this;

            this.$modal.show();
            this.overlay && this.$overlay.fadeTo('fast', self.opacity);
            !this.modal && $(document).bind('click', self.docevnt);

            if (this.container == 'body' && !this.scroll) window.scroll(0, 0);
        },

        remove: function() {
            var self= this;

            $(document).unbind('click', self.docevnt);

            if (this.cache) {
                this.$modal.hide();
                this.$overlay.fadeOut('fast', function(){
                  $(this).css({ opacity:self.opacity });
                });
            } else {
                this.$modal.remove();
                this.$overlay.fadeOut('fast', function(){
                  $(this).remove();
                });
            }

            $(this.opener).removeClass('active');
        }
    };
})(jQuery);

$(function(){  
    $('a.modal').modal();
    
    // $(document).delegate('form.xhr', 'submit', function(event){      
    //     xhr.action(this, $(this).closest('.xhr-container'));
    // 
    //     event.preventDefault();
    // });
    // 
    // $('a.xhr').live('click', function(event){
    //     var container = $(this).attr('data-container');
    //     xhr.action(this, $(container));
    // 
    //     event.preventDefault();
    //     return false;
    // });
});



