function Phire() {
}

//MVC
Phire.model = [];
Phire.view = [];
Phire.command = [];
Phire.notificationsList = {};

Phire.registerCommand = function(notification, command) {
	Phire.command.push({
		notification : notification,
		command : command
	});
};

Phire.registerView = function(view) {
	if(view.name == null)
		throw ("View needs name property.");
	Phire.view[view.name] = view;
	var list = view.notificationsList;
	if(list == null)
		throw ("View needs notificationsList property.");
	for(var i = 0; i < list.length; ++i) {
		var list2 = Phire.notificationsList[list[i]];
		if(list2 == null){
			Phire.notificationsList[list[i]] = [];
			list2 = Phire.notificationsList[list[i]];
		}
			
		if(list2.indexOf(view) == -1)
			list2.push(view);

	}

};
Phire.unregisterView = function(viewName) {
	var view = Phire.view[viewName];
	if(view == null)
		return;
	Phire.view[viewName] = null;
	delete Phire.view[viewName];

}
Phire.getView = function(viewName) {
	if(Phire.view[viewName] == null)
		throw ("Model " + viewName + " not found.");
	return Phire.view[viewName];
};

Phire.registerModel = function(model) {
	if(model.name == null)
		throw ("Model needs name property.");
	Phire.model[model.name] = model;
}
Phire.unregisterModel = function(modelName) {
	var model = Phire.model[modelName];
	if(model == null)
		return;
	Phire.model[model.name] = model;
};

Phire.getModel = function(modelName) {
	if(Phire.model[modelName] == null)
		throw ("Model " + modelName + " not found.");
	return Phire.model[modelName];
};

Phire.sendNotification = function(notification, data) {
	var i, n, list;
	//Commands
	for( i = 0; i < Phire.command.length; ++i) {
		if(Phire.command[i].notification == notification) {
			new Phire.command[i].command(data);
		}
	}
	//Views
	for(i in Phire.notificationsList) {

		if(i == notification) {
			list = Phire.notificationsList[i];
			log(list);
			for( n = 0; n < list.length; ++n) {
				if(list[n].handleNotification == null)
					throw ("View needs handleNotification method.");
				list[n].handleNotification(notification, data);
			}

		}
	}
};

Phire.templatePath = "templates"
Phire.placeTemplate = function(id, url, callback) {
	$(id).html("");
	$(id).load(Phire.templatePath + "/" + url, callback);
};

Phire.removeTemplate = function(id) {
	$(id).remove();
};

if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
};

