var Controller = function() {
	this.model = new Model();
	var self = this;
	this.model.ready.attach(function() {
		self.init();
	});
	this.view = new View();
	this.addSaveCancelEvents();
};

Controller.prototype.init = function() {
	this.view.init(this.model);
	this.setModulationValues();
	this.setPortValue();
	this.addModulationEvents();
	showPage();
};

Controller.prototype.addModulationEvents = function() {
	var self = this;

	$.each(self.model.modulationList, function(key, modulation) {
		$("#" + self.model.modulationIdList[key].id).bind("click", function() {
			modulation.enabled = $(this).is(":checked");
			if(modulation.enabled) {
				$("." + self.model.modulationIdList[key].id).show();
			} else {
				$("." + self.model.modulationIdList[key].id).hide();
			}
			self.setMultimodeValue();
		});

		if(modulation.enabled) {
			$("." + self.model.modulationIdList[key].id).show();
		} else {
			$("." + self.model.modulationIdList[key].id).hide();
		}

		if(modulation.profiles) {
			$.each(modulation.profiles, function(profileKey, profile) {
				$("#" + profileKey).bind("click", {}, function() {
					profile.enabled = $(this).is(":checked");
				});
			});
		}
	});

	$("#multimode").bind("click", {
		self : this
	}, function() {
		if($(this).is(":checked")) {
			for(var i in self.model.modulationList) {
				self.model.modulationList[i].enabled = true;
				$("." + self.model.modulationIdList[i].id).show();
			}
			self.setModulationValues();
		} else {
			self.setMultimodeValue();
		}
	});
	self.setMultimodeValue();

};

Controller.prototype.addSaveCancelEvents = function() {
	var self = this;
	$("#__ML_save").bind("click", function() {
		self.save();
	});
	$("#__ML_cancel").bind("click", function() {
		self.cancel();
	});
};

Controller.prototype.cancel = function() {
	disablePage();
	this.model.refreshData();
};

Controller.prototype.save = function() {
	disablePage();
	this.model.save();
};

Controller.prototype.setModulationValues = function() {

	for(var i in this.model.modulationList) {
		if(this.model.modulationList[i].enabled) {
			$("#" + this.model.modulationIdList[i].id).attr("checked", "checked");
		} else {
			$("#" + this.model.modulationIdList[i].id).removeAttr("checked");
		}

		for(var j in this.model.modulationList[i].profiles) {
			if(this.model.modulationList[i].profiles[j].enabled) {
				$("#" + j).attr("checked", "checked");
			} else {
				$("#" + j).removeAttr("checked");
			}
		}
	}
	this.setMultimodeValue();
};

Controller.prototype.setPortValue = function() {
	$("#port").html(this.model.port);
};

Controller.prototype.setMultimodeValue = function() {
	var multimode = true;
	for(var i in this.model.modulationList) {
		if(!this.model.modulationList[i].enabled) {
			multimode = false;
			break;
		}
	}
	if(multimode) {
		$("#multimode").attr("checked", "checked");
	} else {
		$("#multimode").removeAttr("checked");
	}

};

var controller;

$(document).ready(function() {
	controller = new Controller();
});
