var BBCode = function() {
    window.undefined = window.undefined;
    this.initDone = false;
}
BBCode.prototype.init = function(t) {
    if (this.initDone)
        return false;
    if (t == undefined)
        return false;
    this._target = t ? document.getElementById(t): t;
    this.initDone = true;
    return true;
}
BBCode.prototype.noForm = function() {
    return this._target == undefined;
}
// insertcode is used for bold, italic, underline and quote and just
// wraps the tags around a selection or prompts the user for some
// text to apply the tag to
BBCode.prototype.insertCode = function(tag, desc, endtag) {
    if (this.noForm())
        return false;
    var isDesc = (desc == undefined || desc == '') ? false: true;
    // our textfield
    var textarea = this._target;
    // our open tag
    var open = '[' + tag + ']';
    var close = '[/' + ((endtag == undefined) ? tag: endtag) + ']';
    if ( ! textarea.setSelectionRange) {
        var selected = document.selection.createRange().text;
        if (selected.length <= 0) {
            // no text was selected so prompt the user for some text
            textarea.value += open + ((isDesc) ? prompt("Please enter the text you'd like to " + desc, "") + close: '');
        } else {
            // put the code around the selected text
            document.selection.createRange().text = open + selected + ((isDesc) ? close: '');
        }
    } else {
        // the text before the selection
        var pretext = textarea.value.substring(0, textarea.selectionStart);
        // the selected text with tags before and after
        var codetext = open + textarea.value.substring(textarea.selectionStart, textarea.selectionEnd) + ((isDesc) ? close: '');
        // the text after the selection
        var posttext = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
        // check if there was a selection
        if (codetext == open + close) {
            //prompt the user
            codetext = open + ((isDesc) ? prompt("Please enter the text you'd like to " + desc, "") + close: '');
        }
        // update the text field
        textarea.value = pretext + codetext + posttext;
    }
    // set the focus on the text field
    textarea.focus();
}

BBCode.prototype.insertEmo = function(emo) {
    var textarea = this._target;
    var pretext = textarea.value.substring(0, textarea.selectionStart);
    var posttext = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
    textarea.value = pretext + emo + posttext;
    textarea.focus();
}

BBCode.prototype.insertAttachment = function(image) {
    var textarea = this._target;
    var pretext = textarea.value.substring(0, textarea.selectionStart);
    var posttext = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
    textarea.value = pretext + "[attached]" + image + "[/attached]" + posttext;
    textarea.focus();
}

// inserts an image by prompting the user for the url
BBCode.prototype.insertImage = function(html) {
    if (this.noForm())
        return false;
    var src = prompt('Please enter the url', 'http://');
    this.insertCode('img=' + src);
}

// inserts a link by prompting the user for a url
BBCode.prototype.insertLink = function(html) {
    if (this.noForm())
        return false;
    this.insertCode('url=' + prompt("Please enter the url", "http://"), 'as text of the link', 'url')
    }

// inserts a quote by prompting the user for a url
BBCode.prototype.insertQuote = function(html) {
    if (this.noForm())
        return false;
    this.insertCode('quote=' + prompt("Please enter the quote user", ""), 'for the quote', 'quote')
    }

function aptools(thisurl) {
    new Ajax.Updater('dropnotice', thisurl, {
        asynchronous: true,
        onLoading: function() {
            Effect.SlideUp('dropnotice', {
                duration: 0.1
            });
        },
        onComplete: function() {
            Effect.SlideDown('dropnotice', {
                queue: 'end'
            });
        }
    });
}

function aptabs(thisurl) {
    new Ajax.Updater('main', thisurl, {
        asynchronous: true,
        onLoading: function() {},
        onComplete: function() {}
    });
}

function aprank(from) {
    new Ajax.Updater('myrank', 'http://www.animepaper.net/?getrank&rnum=' + from, {
        asynchronous: true
    });
}

/*
 * $id ouput.js 0005 7/8/2007 00:07 $ck
 * @author      chaoskaizer <ck@animepaper.net>
 * @link        <http://chaoskaizer.animepaper.net>
 * @require:    prototype 1.5.1+
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

// Append file(s) index
var registerObj = "";
// firebug
var isFirebug = (typeof console != "undefined") ? true: false;

// vanilla for dom & various methods 
var ApMambot = {};
var ApModules = {};

ApMambot.createDOM = function(s, o) {
    if (typeof s != "undefined" && s != "") {
        var e = { dom: document.createElement(s) };
        var f = function(k) { var a = k.split(";"); e.dom.setAttribute(a[0], a[1]) };
        if (typeof o != 'undefined') o.each(f);
        return Element.extend(e.dom);
    }
}

ApMambot.decode = function(t, o) {
    var d = new Template(t);  return d.evaluate(o);
}

ApMambot.getSelector = function(o) {
    return $(o.parent).getElementsBySelector(o.selector);
}

ApMambot.staticRoute = function(d) {
    var s = {
        x: 6,y: 'static',m: '.animepaper.net/', u: 'http://#{domain}.animepaper.net/#{dir}'
    };
    s.r = Math.round(s.x * Math.random());
    s.l = this.decode(s.u, {domain: s.y + s.r, dir: d });
    return(parseInt(s.r) < 1) ? 'http://' + s.y + s.m + d: s.l;
}

/* Modules
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
ApModules.isRotator = function(s) {
    var c = {
        x: ApMambot.getSelector( {parent: 'layout', selector: 'div.header'})[0],
        k: ['rotate.data.js', 'rotate.mod.js']};
    var o = Apc.append.bind(Apc);
    c.r = c.x.getStyle('backgroundImage').toLowerCase();
    if ( ! c.r.match(s))return false;
    c.k.each(o);
    return true;
}

ApModules.observePopup = function(c) {
    var e = {
        l: $$('a.' + c),
        f: function(v) {
            var w = {};
            var h = $(Event.element(v)).readAttribute('href');
            w.str = $(Event.element(v)).readAttribute('rel');
            w.rel = w.str.split(':');
            w.width = w.rel[0] || 250;
            w.height = w.rel[1] || 400;
            w.scroll = w.rel[2] || 'yes';
            w.resize = w.rel[3] || 'yes';
            var win = window.open(h, c, 'width=' + w.width + ',height=' + w.height + ',scrollbars=' + w.scroll + ',resizable=' + w.resize + '');
            win.window.focus();
        }
    };
    e.l.each(function(k) { $(k).observe('click', e.f); k.onclick = function() { return false;  }; });
}

ApModules.parameters = {
    thistype: ['wallpapers', 'scans'],
    oby: ['totalrating', 'downloads', 'title', 'updated'],
    oasc: ['asc', 'desc']    
}

ApModules.sfHover = function(id) {
    var n = $(id).getElementsByTagName("LI");
    for (var i = 0; i < n.length; i ++ ) {
        var li = $(n[i]);
        var link = li.down('a');
        li.onmouseover = function() {
            this.className += " sfhover";
        };
        li.onmouseout = function() {
            this.className = this.className.replace(/\b(sfhover)\b/, "");
        };
        
        if (link.innerHTML.match('Home') && !link.innerHTML.match('Classic Home'))
            link.addClassName('nav-home');
        if (link.href.match('http://www.animepaper.net/submit/'))
            link.addClassName('nav-submit');
        
    }
}

/* Component
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
var ApCore = Class.create();

ApCore.prototype = {
    initialize: function() {
        this.dev = ['bantam', 'chaoskaizer'];
        this.baselib = {
            img: this.domain('images/v5/'),  js: this.domain('scripts/'),
            css: this.domain('upload/css/'), cssx: this.domain('css/'),
            upload: this.domain('upload/'), json: this.domain('scripts/jsonrpc/'),
            local: 'http://localhost/ap/public/scripts/'
        };
        this.ancestor = 'container';
        this.section = { userpage: 'thisup', forums: 'thisforums', groups: 'thisgroups'
        };
        this.ext = { php: '.php', ap: '.ap', css: '.css',  js: '.js', json: '.json', xml: '.xml' };
    },
    domain: function(str) { return ApMambot.staticRoute(str);
    },
    append: function(file) {
        if (null != file && "" != file) {
            var fileObj = file.split(/s*,s*/);
            var path = this.baselib;
            var newdom = ApMambot.createDOM.bind(ApMambot);
            fileObj.each(function(elm, index) {
            	var str, src;
                var fileref = fileObj[index];
                var el = "";
                if (registerObj.indexOf(fileref) ==- 1) {
                    if (fileref.indexOf(".json") !=- 1) {
                        el = newdom('script', ['type;text/javascript', 'src;' + path.json + fileref, 'id;jsonrpc']);
                        if (isFirebug)
                            console.log('[%s] | %s ', fileref, path.json);
                    } else if (fileref.indexOf(".js") !=- 1) {
                        var src = (fileref != 'rotate.data.js') ? path.js: path.upload;                        
                        el = newdom('script', ['type;text/javascript', 'src;' + src + fileref]);
                        if (isFirebug)
                            console.log('[%s] | %s ', fileref, src);
                    } else if (fileref.indexOf('.css') !=- 1) {
                        el = newdom('link', ['rel;stylesheet', 'type;text/css', 'href;' + path.css + fileref]);
                        if (isFirebug)
                            console.log('[%s] | %s ', fileref, path.css);
                    } else if (fileref.indexOf('.csx') !=- 1) {
                    	str = fileref.split('.');
						src =  path.cssx + str[0] + '.css';                   	
                        el = newdom('link', ['rel;stylesheet', 'type;text/css', 'href;' + src]);
                        if (isFirebug)
                            console.log('[%s]', fileref);
                    }
                }
                
                if (el != "" && el != "undefined") {
                    document.getElementsByTagName('head').item(0).appendChild(el);
                    registerObj += fileref + " ";
                }
            });
        }
        return this;
    },
    activate: function(){
    // rules set within common-outer.tpl	
    if ($('layout'))
	    ApModules.isRotator('http://static.animepaper.net/upload/rotate.jpg');
	    ApModules.observePopup('popup'); 
		['nav', 'side'].each(Element.cleanWhitespace);
	    ApModules.sfHover('nav');		
	}    
}
var Apc = new ApCore();
Event.observe(window, 'load',Apc.activate.bind(Apc), false);