HD.Content = function(config) {
	this.model = new HD.Content.Model(config);
	this.view = new HD.Content.View(this.model);
	this.controller = new HD.Content.Controller(this.model, this.view);
	this.model.addObserver(this.view);
};

HD.Content.prototype = {
	addObserver : function(observer) {
		this.model.addObserver(observer);
	}
};

HD.Content.Model = function(config) {
	this.config = config;
	this.observers = [];
};

HD.Content.Model.prototype = {
	getContent : function(source) {
		this.notifyObservers("getContent_Start");
		
		var source = HD.util.Common.hasValue(source) ? source : this.config.source;
		
		var cb = this;
		HD.util.Common.requestContent(source, function(response) {
			var eventName = HD.util.Common.hasValue(response) ? "getContent_Finish" : "getContent_Error";
			cb.notifyObservers.call(cb, eventName, response);
		});
	}
};

HD.extend(HD.Content.Model, [HD.util.Observable]);

HD.Content.View = function(model){
	this.model = model;
	this.config = this.model.config;
	
	var triggerEl = HD.get(this.config.trigger);
	var callback = function() {
		model.getContent.call(model);
	};
	
	if(this.config.onclick != null) {
		callback = this.config.onclick;
	}
	
	triggerEl.onclick = callback;
	
	this.observers = [];
};

HD.Content.View.prototype = {	
    update : function(eventName, eventData) {
    	if(eventName == "getContent_Start") {
    		this.loading(true);
    	} else if(eventName == "getContent_Finish") {
    		var id = HD.util.Common.generateElementId();
    		var html = [
    			'<div id="', id, '">', 
    				eventData,
    			'</div>'
    		].join('');
    		
    		var parentEl = this.getParent();
    		var modelCb = this.model;
    		var cb = this;
    		HD.util.DOM.onContentReady(id, function(){
    			modelCb.notifyObservers.call(modelCb, "getContent_Rendered");
    			cb.loading.call(cb, false);
    		});
    		this.render(html);
    	}
    },
    
    getHtml : function(response) {
    	return response;
    }
};

HD.extend(HD.Content.View, [HD.Widget]);

HD.Content.Controller = function(model, view){
	this.model = model;
	this.view = view;
};

HD.Content.Controller.prototype = {
	
};

HD.register("hd_content", "HD.Content", {version: "1.0", build: "1"});