if(!window.console) window.console = {
    log: function(){},
    warn: function(){},
    debug: function(){},
    clean: function(){}
}

var Class = function Class() {
	
    var the_class, ex;
	
    if(arguments[0].constructor == Function) {
        ex = arguments[0];
    }
	
    var definition = arguments[arguments.length - 1] || {};
	
    if(definition.constructor != Object) {
        throw (new TypeError('a config object is expected'));
    }
	
    if(definition.__construct ) {
        the_class = definition.__construct;
    }
    else  {
        the_class = function () {
            this.test = "test";
        };
    }
	
    if(ex) {
        var tmp_constructor = function(){};
        tmp_constructor.prototype = ex.prototype;
        // the_class.prototype = {__proto__: ex.prototype};
        the_class.prototype = new tmp_constructor();
        the_class.prototype.superClass = ex;
    }
    else {
        the_class.prototype.superClass = Object;
    }
	
	
    for(var x in definition) {
        if(x !== '__construct') {
            the_class.prototype[x] = definition[x];
        }
    }
	
    the_class.prototype.constructor = the_class;
	
    return the_class;
};

/**
 * a class from which objects that have to trigger events should derive
 */
var EventEmitter = new Class({
    __construct: function EventEmitter() {
        this.events = {};
    },
    addEvent: function (e) {
        if (e.constructor !== String) throw (new TypeError("addEvent : an event ID must be a string"));
        this.events[e] = new Array();
    },
    fireEvent: function (e) {
        var l = this.events[e];
        if (!l) throw (new TypeError('event ' + e + ' does not exist'));
        var args = new Array();
        for (var i = 1; i < arguments.length; ++i) {
            args.push(arguments[i]);
        }
        var res = true;
        for (var i = 0; i < l.length; ++i) {
            if (l[i].f) {
                var b = l[i].f.apply(l[i].o, args);
                b = b === undefined ? true : b;
                res = res && b;
            }
        }
        return res;
    },
    /**
	 * param e : event param f : handler function param o : subject object, o
	 * will be available as 'this' in the function
	 */
    addEventListener: function (e, f, o) {
        var l = this.events[e];
        if (!l) throw (new TypeError('event ' + e + ' does not exist'));
        var res = {
            f: f,
            o: o
        };
        l.push(res);
        return res;
    },
    on: function () {
        return this.addEventListener.apply(this, arguments);
    },
    resetEvents: function (e) {
        this.events[e] = new Array();
    },
    removeEventListener: function (e, f, o) {
        var l = this.events[e];
        for (var i = 0; i < l.length; ++i) {
            if (l[i].f === f) {
                if (o) {
                    if (l[i].o === o) {
                        delete l[i--];
                    }
                } else {
                    delete l[i--];
                }
            }
        }
    }
});

var Vetstoria = new (new Class(EventEmitter, {
	
    __construct: function () {
        if (typeof jQuery == "undefined") {
            console.error('Jquery is not loaded');
            return false;
        }
        EventEmitter.apply(this);
    },
	
	
    /**
	 * Include an external JS file
	 * 
	 * @param[in] : (str) relative js file located in $FRONTEND_PATH.'js/'
	 * @param[in] : (function) pointer to a function launched when the file is
	 *            loaded
	 */
    include_js: function(file_name, onload) {
		
        if(!window.$FRONTEND_PATH) return false;
		
        var script = document.createElement('script');
		
        script.onload = function () {
            if (typeof onload == 'function') {
                (onload)();
            }
        };
		
        script.onreadystatechange = function () {
            if (script.readyState == 'complete') {

                if (typeof onload == 'function') {
                    (onload)();
                }
            }
        };
		
        script.src = $FRONTEND_PATH + 'js/' + file_name;
		
        document.getElementsByTagName('head')[0].appendChild(script);
		
        return true;
    },
	
    browser: function() {
    },
	
    get_url_vars: function() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }

        return vars;
    },
	
    /**
	 * Perform a synchronus ajax request and return the result
	 * @author Charaf
	 */
    json_command: function(json_url, post_object) {
		
        var result;
		
        $.ajax({
            type: "POST",
            dataType:"json",
            cache: false,
            data: {
                'data': post_object
            },
            url: json_url,
            async: false,
            beforeSend: function(){
                $('.ui.ajax').hide();
                $('.ui.ajax.processing').show();
            },
            success: function(r){
                $('.ui.ajax.processing').fadeOut();
                result = r;
            // console.log(r);
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){
                $('.ui.ajax.processing').fadeOut();
                console.log(textStatus);
            }
        });
		
        return result;
    },
    escapeHTML: function(html) {
        return(html.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/"/g,'&quot;'));
    },
    unescapeHTML: function(html) {
        return html.replace('&lt;', '<').replace('&gt;', '>').replace('&quot;', '"').replace('&amp;', '&');
    },
    countNL: function(str) {
        var m = (/\r\n/g).exec(str);
        if (!m || !m.length)return 0;
        return m.length - 1;
    },
    /**
	 * Perform an asynchronus ajax request
	 * @author Charaf
	 */
    json_async_command: function(json_url, post_object, onsuccess_function, onerror_function) {
		
        return $.ajax({
            type: "POST",
            dataType: "json",
            cache: false,
            data: {
                'data': post_object
            },
            url: json_url,
            async: true,
            success: onsuccess_function,
            error: onerror_function
        });
		
    },

    /**
	 * Perform a non-synchronus ajax request and calls handler
	 */
    json_command_async: function(json_url, post_object, handler) {
        var result;
		
        $.ajax({
            type: "POST",
            dataType:"json",
            cache: false,
            data: {
                'data': post_object
            },
            url: json_url,
            async: true,
            beforeSend: function(){
            //$('.ui.ajax').hide();
            //$('.ajax.processing').show();
            },
            success: function(r){
                //$('.ajax.processing').fadeOut();
                if(r.state==0) handler(r.data);
                else {
                    $.msgbox(r.data[0].Error);
                    handler(new Array());
                }
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){
                //$('.ajax.processing').fadeOut();
                console.log('json_command_async used');
                console.log(textStatus);
            }
        });
		
        return;
    },
	
    /**
	 * Redirect to a given location
	 */
    redirect: function(uri, external) {
        console.log('Vetstoria.redirect : to ' + uri + ', external = ' + external);
		
        if(external)
            window.location = uri;
        else
            window.location = $BASE_PATH + uri;
		
        return;
    },
	
    setDate:function(){
    
        var t = function() {
            var date;
            $("em.timestamp").each(function(){
                date = $(this).attr('rel');
                $(this).text(prettyDate(date));
            });
        };
        setInterval(t, 1000);
        
    },
    
    init: function() {
		
        console.log('Vetstoria:', 'Vetstoria initialisation');
		
        try {
            Vetstoria.debug.init();
        } catch(e) {
            console.error('Vetstoria.init() : error with Vetstoria.debug.init(). ' + e);
        }
		
        try {
            Vetstoria.session.init();
        } catch(e) {
            console.error('Vetstoria.init() : error with Vetstoria.session.init(). ' + e);
        }
		
        try {
            Vetstoria.layout.init();
        } catch(e) {
            console.error('Vetstoria.init() : error with Vetstoria.layout.init(). ' + e);
        }
		
        try {
            Vetstoria.usermenu.init();
        } catch(e) {
            console.error('Vetstoria.init() : error with Vetstoria.usermenu.init(). ' + e);
        }

        try {
            Vetstoria.contextualmenu.init();
        } catch(e) {
            console.error('Vetstoria.init() : error with Vetstoria.contextualmenu.init(). ' + e);
        }
		
        try {
        //Vetstoria.twitter.init();
        } catch(e) {
            console.error('Vetstoria.init() : error with Vetstoria.twitter.init(). ' + e);
        }
		
		
    },
	
    logout: function () {
        return Vetstoria.session.logout();
    },
	
    getURLHash: function() {
        return $.address.value();
    },
	
    setNewURLHash: function(hash) {
        $.address.value('/'+hash);
    },
	
    removeURLHash: function() {
        $.address.value('');
    },
	
    addToURLHash: function(hash) {
        $.address.value($.address.value()+'/'+hash);
    },
	
    findKeywordInURLHash: function(keyword) {
        var val = $.address.value();
        if(val.indexOf(keyword)>=0) return true;
        return false;
    },

	assert_urlreload: function(key){
		//Temporary fix until /edit becomes part of the AJAX navigation system
		if(window.location.href.indexOf('/edit')>0){
			var newloc = window.location.href;
			newloc = newloc.replace('/edit','') + '#/' + key;
			window.location.href = newloc;
			return;
		}
	}
	
}));


