///////////////////////////////////////////////////////////////////////////////////////////////////
// GENERIEKE CODE
///////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * String.namespace()
 * http://www.prototypejs.org/api/enumerable/inject
 * http://ajaxian.com/archives/namespaced-made-easy-with-prototype
 *
 * Creates an object namespace chain delimited by the separator.
 * 
 * @param string $separator
 * @return void
 */
String.prototype.namespace = function(separator) {
  this.split(separator || '.').inject(window, function(parent, child) {
    return parent[child] = parent[child] || { };
  });
};

/**
 * FCKReplace
 */

var FCKReplace = Class.create();
FCKReplace.prototype = {
    
    initialize: function(options) {
        
        this.options = {
            onCurrentLoadedChange: function() {},
            onEditorcountChange: function() {}
        };
        Object.extend(this.options, options || {});
        
        this.editors    = [];
        this.loadBuffer = [];
        this.currentLoaded = 0;
        
        window.FCKeditor_OnComplete = this.onFCKLoaded.bind(this);
    },
    
    add: function(element, params) {
        
        if (!params) params = {};
        
        var width = params.width || '350';
        var height = params.height || '200';
        
        var editor = new FCKeditor(element.name);
        editor.Width = width;
        editor.Height = height;
        editor.ToolbarSet = params.toolbarset || 'Basic';
        
        var editorArr = [element, editor];
        
        this.editors.push(editorArr);
        
        this.options.onEditorcountChange(this.editors.length);
        
        // direct vervangen
        if (params.simultaneously) {
            this.doReplace(editorArr);
        } else {
            
            if (params.replaceOnSelect) {
                Event.observe(element, 'focus', function() {
                    this.doReplace(editorArr);
                }.bind(this));
            } else if (params.assignDoReplace) {
                element.doReplace = this.doReplace(editorArr);
            } else {
                
                // grootte van de textarea wel alvast gelijk zetten
                element.style.textIndent = '-'+(width+'px');
                element.style.width = width+'px';
                element.style.height = height+'px';
                
                $(element.parentNode).startWaiting();
                
                // indien er niets wordt geladen, meteen vervangen
                if (this.loadBuffer.length == 0) {
                    this.doReplace(editorArr);
                }
                // toevoegen aan de laadbuffer
                this.loadBuffer.push(editorArr);
            }
        }
        
    },
    
    doReplace: function(editorArr) {
        
        editorArr[1].ReplaceTextarea();
    },
    
    onFCKLoaded: function(fck) {
        
        this.currentLoaded++;
        
        this.options.onCurrentLoadedChange(this.currentLoaded);

        $(fck.LinkedField.parentNode).stopWaiting();
        
        // buffer afhandelen
        var inBuffer = false;
        this.loadBuffer.each(function(editorArr) {
            if (editorArr[0] == fck.LinkedField) {
                inBuffer = editorArr;
            }
        });
        
        if (inBuffer) {
            this.loadBuffer = this.loadBuffer.without(inBuffer);
            if (this.loadBuffer.length > 0) {
                this.doReplace(this.loadBuffer.first());
            }
        }
    }
};

/**
 * Cookie manager
 */
var Cookie = {

    set: function(name, value, days) {
		
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60  * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		} else {
		    var expires = "";		
		}
        
        document.cookie = name + "=" + value + expires +"; path=/";
        
    },

    get: function(name) {
        
        var start = document.cookie.indexOf(name+"=");
        var len = start + name.length + 1;
        
        if ((!start) && (name != document.cookie.substring(0, name.length))) {
            return null;
        }
        
        if (start == -1) return null;
        
        var end = document.cookie.indexOf(";", len);
        
        if (end == -1) end = document.cookie.length;
        
        return unescape(document.cookie.substring(len, end));
    },
	
	remove: function(name) {
		Cookie.set(name, ' ', -1);
	}
};

/**
 * Prototype onDOMReady Implementatie
 */
Object.extend(Event, {
    
    _domReady : function() {  

     if (arguments.callee.done) return;  
     arguments.callee.done = true;  
   
     if (this._timer)  clearInterval(this._timer);  
       
     this._readyCallbacks.each(function(f) { f() });  
     this._readyCallbacks = null;  
 },  
   onDOMReady : function(f) {  
     if (!this._readyCallbacks) {  
       var domReady = this._domReady.bind(this);  
         
       if (document.addEventListener)  
         document.addEventListener("DOMContentLoaded", domReady, false);  
           
        // for Internet Explorer (using conditional comments)
        /*@cc_on @*/
        /*@if (@_win32)
        document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
        var script = document.getElementById("__ie_onload");
        script.onreadystatechange = function() {
            if (this.readyState == "complete") {
                domReady(); // call the onload handler
            }
        };
        /*@end @*/

         if (/WebKit/i.test(navigator.userAgent)) {   
           this._timer = setInterval(function() {  
             if (/loaded|complete/.test(document.readyState)) domReady();   
           }, 10);  
         }  
           
         Event.observe(window, 'load', domReady);  
         Event._readyCallbacks =  [];  
     }  
     Event._readyCallbacks.push(f);  
   }  
});  

function body() { return $(document.getElementsByTagName("body").item(0)); }

/**
 * loader class
 * maakt het makkelijk om een spinner aan een element toe te voegen :)
*/
var Loader = Class.create();
Loader.prototype = {

    node: false,
	indicator: false,

	initialize: function() {
		if ($('jsLoader')) return false;
		
		this.options = Object.extend({ 
            image:          'loader'
		}, arguments[0] || {} );
		
		this.node = document.createElement('div');
		this.node.className = this.options.image;
	},
	before: function(element) {
		element.parentNode.insertBefore(this.node, element);
	},
	after: function(element) {
		element.parentNode.appendChild(this.node);
	},
	insert: function(element) {
		element.insertBefore(this.node, element.firstChild);
	},
	append: function(element) {
		element.appendChild(this.node);
	},
	remove: function() {
		this.node.parentNode.removeChild(this.node);
	}
};

///////////////////////////////////////////////////////////////////////////////////////////////////
// ONLOAD HANDLERS
///////////////////////////////////////////////////////////////////////////////////////////////////

document.observe('dom:loaded', function() { 
    Behaviour.apply();
});