var Popup = Class.create();
Popup.prototype =
{
  initialize: function(options)
  {
    this.options = {
      url: '#',
      width: 300,
      height: 300
    }
    Object.extend(this.options, options || {});
    window.open(this.options.url, '', 'width='+this.options.width+',height='+this.options.height + ',scrollbars=yes,resizable=yes');
  }
}

var _cache = {
    ajax: {
        links: [],
        link:{ 
            action: function(e){
                e.preventDefault();
                console.log('default ajax link action');
            }
        },
        forms: [],
        form:{
            action: function(e)
            {
                e.preventDefault();
                console.log('default ajax form action');
            }
        }
    }
};

var dgui_modal = Class.create({

    window:null,
    draggable: null,
    isUpload:false,
    _open:false,

    initialize: function()
    {
        //console.log('modal loaded');
        this.create();
    },

    open: function(){
        this.window.setStyle({
            'display':'block'
        });
        this.center();
        this.draggable = new Draggable(this.window, {handle: this.window.down('.hd'), scroll: window, starteffect: function(){}, endeffect: function(){}});
        this._open = true;
    },

    close: function(e)
    {
        if(e)
            e.preventDefault();
        
        this.window.setStyle({
            'display':'none'
        });
        this.draggable.destroy();

        $('page-wrap').select('.loading').each(function(button){
            button.removeClassName('loading');
        });

        if(this.isUpload)
            this.isUpload = false;

        this._open = false;
    },

    title: function(title, isUpload, skip)
    {
      if(this.isUpload !== true || skip === true){
        this.open();
        this.window.down('.title').update(title);
        if(isUpload)
                this.isUpload = true;
      }
    },

    content: function(content, isUpload, skip)
    {
        if(this.isUpload !== true || skip === true){
            this.open();
            this.window.down('.bd').update(content);
            if(isUpload)
                this.isUpload = true;
        }
    },

    isOpen: function()
    {
      return this._open;
    },

    center: function()
    {
        var w = document.viewport.getDimensions();
        var m = this.window.getDimensions();
        var offset = document.viewport.getScrollOffsets();

        this.window.setStyle({
            'left': w.width/2 - m.width/2 + 'px',
            'top': offset.top + (w.height/2 - m.height/2) + 'px'
        });
    },

    create: function()
    {
       if(!Object.isElement(this.window)){

           this.window = new Element('div', {'class':'dgui-modal-window'});
           this.window.insert('<div class="dgui-block style-3"><div class="hd"><h1 class="title">Window</h1></div><div class="bd"></div></div><div class="dgui-modal-window-close"><div class="dgui-button-group modal"><a href="#" class="dgui-button"><span class="text">X</span></a></div></div>');
           $(document.body).insert({'bottom': this.window});

           this.window.down('.dgui-modal-window-close').observe('click', this.close.bind(this));

       }
    }

});


var ajaxify = Class.create({

    initialize: function()
    {
        _cache.ajax.link.action = this.link_action.bind(this);
        _cache.ajax.form.action = this.form_action.bind(this);
        var self = this;
        var tmp = $$('a.ajax, form.ajax');
        tmp.each(function(el){
            self.convert(el);
        });
    },

    convert: function(el)
    {
        var el = $(el);

        if(el.tagName == 'A'){
            if(_cache.ajax.links.indexOf(el) == -1){
                _cache.ajax.links.push(el);
            }

            _cache.ajax.links[_cache.ajax.links.indexOf(el)].observe('click', _cache.ajax.link.action);
        }
        if(el.tagName == 'FORM'){
            if(_cache.ajax.forms.indexOf(el) == -1){
                _cache.ajax.forms.push(el);
                el.select('input[type=submit]').each(function(input){
                    input.observe('click', function(e){
                        var el = Event.element(e);
                        el.isClicked = true;
                    });
                });
            }
            _cache.ajax.forms[_cache.ajax.forms.indexOf(el)].observe('submit', _cache.ajax.form.action);
        }
    },

    link_action: function(e)
    {
        var self = this;
        e.preventDefault();

        var el = Event.findElement(e, 'a');

        if(el.hasClassName('modal-image')){
           modal.content('<img src="' + el.readAttribute('href') + '" alt=""/>');
           modal.title(el.readAttribute('title'));
        }
        else{

            new Ajax.Request(el.readAttribute('href'), {
                method:'get',
                onSuccess: function(t)
                {
                    if(el.hasClassName('modal')){
                        modal.content(t.responseText);
                        modal.title(el.readAttribute('title'));
                        self.update(modal.window);
                    }

                    if(el.hasClassName('modal-block-new-open')){
                        modal.blockNewOpen = true;
                        modal.content(t.responseText);
                        modal.title(el.readAttribute('title'));
                        self.update(modal.window);
                    }

                    if(el.hasClassName('modal-menu')){
                        menu.setTrigger(el);
                        menu.content(t.responseText);
                        self.update(menu.window);
                    }
                }
            });

        }
    },

    form_action:function(e)
    {
        var self = this;

        var form = Event.element(e);
        var submit = false;

        var inputs = form.select('input[type=submit]');
        inputs.each(function(input){
            if(input.isClicked){
                submit = input;
                submit.addClassName('loading');
            }

        });

        form.getElements().each(function(el){
            if(el.hasClassName('tinyMCE')){
                el.value = tinyMCE.get(el.id).getContent();
            }

            if(el.hasClassName('sample')){
                el.value = '';
                el.removeClassName('sample');
            }
        });

        form.request({
          onSuccess: function(t)
          {
            if(submit){
                submit.removeClassName('loading');
                submit.isClicked = false;
            }

            if(form.hasClassName('modal')){
                modal.content(t.responseText);
                self.update(modal.window);
            }

            if(form.hasClassName('self')){
                var update = form.up();
                if(t.responseText.indexOf(':no-replace:') == -1 || t.responseText.indexOf(':no-replace:') > 0){
                    form.replace(t.responseText);
                }
                else{
                    t.responseText.evalScripts();
                }

                self.update(update);
            }
//
//                if(el.hasClassName('modal-menu')){
//                    menu.setTrigger(el);
//                    menu.content(t.responseText);
//                    self.update(menu.window);
//                }
          },
          parameters: { "button":submit.name }
        });
        Event.stop(e);
    },

    update: function(el)
    {
        var self = this;
        var tmp = el.select('a.ajax, form.ajax');

        tmp.each(function(el){
            self.convert(el);
        });

        if(el.down('form')){
            var form = $(el.down('form'));
            var element = form.findFirstElement();
            if(!element.hasClassName('sample')){
                element.focus();
            }
        }

        this.check();
    },

    check: function()
    {
        var self = this;
        _cache.ajax.links.each(function(el){
            if(!$(el).up())
            {
                _cache.ajax.links[_cache.ajax.links.indexOf(el)].stopObserving();
                _cache.ajax.links = _cache.ajax.links.without(el);
            }
        });

        _cache.ajax.forms.each(function(el){
            if(!$(el).up())
            {
                _cache.ajax.forms[_cache.ajax.forms.indexOf(el)].stopObserving();
                _cache.ajax.forms = _cache.ajax.forms.without(el);
            }
        });
    },

    add: function(el)
    {
        this.convert(el);
    },

    remove: function(el)
    {
        if(el.tagName == 'A'){
            if(_cache.ajax.links.indexOf(el) > -1){
                _cache.ajax.links.push(el);
                _cache.ajax.links[_cache.ajax.links.indexOf(el)].stopObserving('click', _cache.ajax.link.action);
            }
        }
        if(el.tagName == 'FORM'){
            if(_cache.ajax.forms.indexOf(el) > -1){
                _cache.ajax.forms.push(el);
                _cache.ajax.forms[_cache.ajax.forms.indexOf(el)].stopObserving('submit', _cache.ajax.form.action);
            }
        }
    }

});

var dgui_ellipsis = Class.create({
    initialize: function()
    {
       var self = this;
       //document.write('<style type="text/css">' + '.ellipsis { margin-right:-10000px; }</style>');

      document.observe("dom:loaded", function() {
        $$('.ellipsis_text').each(self.ellipsis.bind(self));
      });

    },

    ellipsis: function(e)
    {
        e = $(e);
        var lineheight = this.lineheight(e);

        var text = e.innerHTML;
        var dim = e.getDimensions();
        var rows = Math.floor(dim.height / lineheight);
        var length = Math.floor(text.length / rows) - 5;

        if(length < text.length){
            e.update(text.truncate(length));
        }

    },

    lineheight: function(e)
    {
        var lineheight = e.getStyle('line-height');
        lineheight = lineheight.truncate(2,'');
        return new Number(lineheight);
    }
});

var dgui_modal_menu = Class.create({
    window: null,
    trigger: null,

    initialize: function()
    {
        this.create();

    },

    create: function()
    {
        if(!Object.isElement(this.window)){
            this.window = new Element('div', {'class':'dgui-modal-menu'});
            $(document.body).insert({'bottom':this.window});
            this.window.hide();
        }
    },

    setTrigger: function(trigger)
    {
        this.trigger = trigger;
    },

    content: function(content)
    {
        this.window.update(content);
        this.show();
    },

    show: function(e)
    {
        if(Object.isElement(this.trigger)){
            var hide = this.hide.bind(this);
            this.trigger.observe('click', hide);
            this.trigger.addClassName('selected');
            ajax.remove(this.trigger);
        }

        this.window.setStyle({
            'display':'block'
        });

        this.draggable = new Draggable(this.window, {scroll: window, starteffect: function(){}, endeffect: function(){}});

        this.position();
    },

    hide: function(e)
    {
        if(Object.isElement(this.trigger)){
            e.preventDefault();
            var hide = this.hide.bind(this);
            this.trigger.stopObserving('click', hide);
            this.trigger.removeClassName('selected');
            ajax.add(this.trigger);
        }

        this.window.setStyle({
            'display':'none'
        });

        this.draggable.destroy();
    },

    position: function()
    {
        if(Object.isElement(this.trigger)){
            var pos = this.trigger.cumulativeOffset();
            var wdim = this.window.getDimensions();
            var tdim = this.trigger.getDimensions();

            this.window.setStyle({
                'left': pos.left - wdim.width + tdim.width + 'px',
                'top': pos.top + 30 + 'px'
            });
        }
    }

});

var dgui_form = Class.create({

    initialize: function()
    {
        
    },

    addSampleText: function(options)
    {
        var el = $(options.element);

        var text = options.text;
        var old_length = el.readAttribute('maxlength');

        if(el.value.blank()){
            el.addClassName('sample');
            el.value = text;
        }

        el.writeAttribute('maxlength', text.length);
        el.blur();

        el.observe('focus', function(e){
            var element = Event.element(e);
            if(element.value == text)
            {
                el.writeAttribute('maxlength', old_length);
                element.value = '';
                el.removeClassName('sample');
            }
        });

        el.observe('blur', function(e){
            var element = Event.element(e);
            if(element.value.blank())
            {
                el.writeAttribute('maxlength', text.length);
                element.value = text;
                el.addClassName('sample');
            }
        });
    },

    addSampleForm: function(form)
    {
        form = $(form);
        form.observe('submit', function(e){
            e.preventDefault();
            var _form = Event.element(e);
            _form.getElements().each(function(element){
                if(element.hasClassName('sample')){
                    element.removeClassName('sample');
                    element.value = '';
                }
            });
            _form.submit();
        });
    }

});

var modal = {};
var _form = new dgui_form();
var ajax = {};
var ellipsis = new dgui_ellipsis();
var menu = {};

document.observe("dom:loaded", function() {
    modal = new dgui_modal();
    ajax = new ajaxify();
    menu = new dgui_modal_menu();
});