/*
 * RJS : Rukie JavaScript Lib.
 * -- based on Prototype(1.6.0+) and script.aculo.us(1.8.0+)
 * @author Kenny2
 */
var RJS = {
    VERSION: '0.1',
    SCRIPT_PATH: null,
    FILES_PATH : null,

    loadScript: function(scriptName) {
        document.write('<script src="'+RJS.SCRIPT_PATH+scriptName+'.js" type="text/javascript"><\/script>');
    },

    init: function() {
        // get rjs.js's path and files path
        var srcRgxp = /rjs\.js(\?.*)?$/;
        var rjsScript = $A(document.getElementsByTagName('script')).find(function(script) {
            return script.src.match(srcRgxp);
        });
        RJS.SCRIPT_PATH = rjsScript.src.replace(srcRgxp, '');
        RJS.FILES_PATH = RJS.SCRIPT_PATH+'files';
        // load required scripts
        RJS.loadScript('effects');
        RJS.loadScript('dragdrop');
        if( (scriptNames = rjsScript.src.match(/rjs\.js\?load=([a-z,]*)$/)) )
            $A(scriptNames[1].split(',')).each(function(scriptName){ RJS.loadScript(scriptName); });
    }
};
RJS.init();

/*
 * RJS.Browser
 */
RJS.Browser = {
    isIE: function() { return Prototype.Browser.IE },
    isOpera: function() { return Prototype.Browser.Opera },
    isWebKit: function() { return Prototype.Browser.WebKit },
    isGecko: function() { return Prototype.Browser.Gecko },
    isMobileSafari: function() { return Prototype.Browser.MobileSafari },

    getVersion: function() {
        if(RJS.Browser.isIE()) return /MSIE\s(.+);/.exec(navigator.appVersion)[1];
        else return null;
    }
};


/*
 * RJS.CSS
 */
RJS.CSS = {
    // for IE6-
    fixPNG: function(cssRules, imgPath) {
        var filterTpl = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="#{src}",sizingMethod="#{method}")';
        cssRules.each( function(rule) {
            var bgImg = rule.style.backgroundImage;
            if (bgImg && bgImg != 'none' && bgImg.match(/^url[("']+(.*\.png)[)"']+$/i)) {
                var src = RegExp.$1;
                var bgRepeat = rule.style.backgroundRepeat;
                rule.style.filter = filterTpl.interpolate({
                    src: imgPath + '/' + src,
                    method: (bgRepeat == "no-repeat") ? "crop" : "scale"
                });
                rule.style.backgroundImage = "none";
            }
        });
    },

    // for IE6-
    findRulesBySelector: function(selector, styles) {
        var rules = [];
        $A(styles).each(function(style){
            rules = rules.concat(
                $A(style.rules).findAll(function(rule){
                    return rule.selectorText.include(selector);
                })
            );
            if(style.imports) rules = rules.concat(RJS.CSS.findRulesBySelector(selector, style.imports));
        });
        return rules;
    }
};


/*
 * RJS.UI
 */
RJS.UI = {
    /* about RJS.UI.Window */
    WINDOWS: [],
    WINDOW_CLASS_NAME: 'rjs-win',
    WINDOW_FILES_PATH: '/ui/window',
    WINDOW_TPL: new Template(
                    '<div id="rjs-window_id-#{id}" class="#{className}">'+
                    '<div><div class="rjs-tl"></div><div class="rjs-tc">'+
                    '<div class="rjs-title"></div>'+
                    '<div class="rjs-buttons"><a class="rjs-closeWindowBtn" href="\##{id}" title="닫기">닫기</a></div>'+
                    '<div class="rjs-cb"></div>'+
                    '</div><div class="rjs-tr"></div><div class="rjs-cl"></div></div>'+
                    '<div><div class="rjs-ml"></div>'+
                    '<div class="rjs-content"></div>'+
                    '<div class="rjs-mr"></div><div class="rjs-cl"></div></div>'+
                    '<div><div class="rjs-bl"></div><div class="rjs-bc"></div><div class="rjs-br"></div><div class="rjs-cl"></div></div>'+
                    '</div>'
                ),
    WINDOW_IFRAME_TPL: new Template(
                        '<iframe src="#{url}" width="100%" height="100%" frameborder="0"></iframe>'
                       )
};


/*
 * RJS.UI.Window
 */
RJS.UI.Window = Class.create({
    id: null,
    element: null,
    titleContainer: null,
    contentContainer: null,
    contentDocument: null,
    dndHandler: null,
    closeButton: null,
    options: {},

    /* [options]
     *	title : String
     * 	content : String
     *  contentWidth : Integer
     *  contentHeight : Integer
     *  x : Integer
     *  y : Integer
     *  draggable : Boolean
     *  onOpen : Function
     *  onClose : Function
     */
    initialize: function(options) {
        this.options = options;

        this.id = RJS.UI.WINDOWS.size();
        RJS.UI.WINDOWS.push(this);

        // create&insert Window HTML element
        this.element = this.createElement();
        this.titleContainer = this.element.select('.rjs-title').first();
        this.contentContainer = this.element.select('.rjs-content').first();

        // set title
        if(this.options.title == undefined) this.titleContainer.insert('');
        else this.titleContainer.insert(this.options.title);

        // set content
        if(this.options.content == undefined) this.contentContainer.insert('');
        else if(this.options.content.match(/^https?:\/\/.+/i)) {
            this.contentContainer.insert(RJS.UI.WINDOW_IFRAME_TPL.evaluate({ url: this.options.content }));
            this.contentDocument = this.contentContainer.select('iframe')[0];
        } else this.contentContainer.insert(this.options.content);

        // set Size
        if(this.options.contentWidth == undefined) this.options.contentWidth = 320;
        if(this.options.contentHeight == undefined) this.options.contentHeight = 240;
        this.setSize(this.options.contentWidth, this.options.contentHeight);

        // set Position
        if(this.options.x == undefined) this.setX((document.viewport.getWidth()-this.element.getWidth())/2);
        if(this.options.y == undefined) this.setY((document.viewport.getHeight()-this.element.getHeight())/2);

        // set Draggable
        if(this.options.draggable == undefined) this.setDraggable();
    }
    ,
    open: function() {
        if(this.options.onOpen != undefined) this.options.onOpen();

        this.element.show();

        var win = this;
        this.closeButton = this.element.select('.rjs-closeWindowBtn').first();
        this.closeButton.observe('click', function(e){
            e.stop();
            win.close();
        });
    }
    ,
    close: function() {
        if(this.options.onClose != undefined) this.options.onClose();

        this.closeButton.stopObserving();
        if( this.dndHandler ) this.dndHandler.destroy();
        this.element.remove();
        RJS.UI.WINDOWS[this.id] = null;
    }
    ,
    createElement: function() {
        $(document.body).insert(
            RJS.UI.WINDOW_TPL.evaluate({
                id: this.id,
                className: RJS.UI.WINDOW_CLASS_NAME
            })
        );
        var element = $('rjs-window_id-'+this.id);
        element.hide();
        $(document.body).setStyle({ position: 'relative' });
        element.absolutize();
        return element;
    }
    ,
    setSize: function(contentWidth, contentHeight) {
        this.element.setStyle({
            width: contentWidth + 24 + 'px', height: contentHeight + 46 + 'px'
        });

        this.contentContainer.setStyle({
            width: contentWidth+'px', height: contentHeight+'px'
        });

        this.element.select('.rjs-tc').first().setStyle({ width: contentWidth+'px' });
        this.element.select('.rjs-bc').first().setStyle({ width: contentWidth+'px' });
        this.element.select('.rjs-ml').first().setStyle({ height: contentHeight+'px' });
        this.element.select('.rjs-mr').first().setStyle({ height: contentHeight+'px' });
    }
    ,
    setX: function(x) { this.element.setStyle({ left: x+'px' }); }
    ,
    setY: function(y) { this.element.setStyle({ top: y+'px' }); }
    ,
    setDraggable: function() {
        this.dndHandler = new Draggable(this.element, {
            handle: this.element.select('.rjs-tc').first(),
            snap: function(x, y, draggable) {
              function constrain(n, lower, upper) {
                if (n > upper) return upper;
                else if (n < lower) return lower;
                else return n;
              }

              element_dimensions = Element.getDimensions(draggable.element);
              return[
                constrain(x, 0, document.viewport.getWidth() - element_dimensions.width),
                constrain(y, 0, document.viewport.getHeight() - element_dimensions.height)];
            }
            ,starteffect: function(element){}, endeffect: function(element){}
        });
        this.dndHandler.handle.setStyle({ cursor: 'move' });
    }
});

/*
 * RJS.UI.Loading
 * 임의의 엘리멘트영역에 AJAX용 로딩이미지 표시
 * RJS.UI.Loading.start('foo');
 * RJS.UI.Loading.stop('foo');
 */
RJS.UI.Loading = {};


/*
 * RJS.Util
 */
RJS.Util = {
    getRandomInt: function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
};


/*
 * RJS.App
 */
RJS.App = {  };
RJS.App.Memail = {
    open: function(btn) {
        new RJS.UI.Window({
            title: 'me:mail', content: btn.href,
            contentWidth: 640, contentHeight: 480
        }).open();
    }
};
