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

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

	$("#enabled").bind("change", function() {
		self.model.enabled = $(this).is(":checked");
	});

	$("#server").bind("change", function() {
		self.model.server = $(this).val();
	});

	$("#username").bind("change", function() {
		self.model.username = $(this).val();
	});

	$("#password").bind("change", function() {
		self.model.password = $(this).val();
	});

	$("#mtu").bind("change", function() {
		self.model.mtu = $(this).val();
	});

	$("#routeAllTrafficThroughVpn").bind("change", function() {
		self.model.routeAllTrafficThroughVpn = $(this).is(":checked");
	});
	
	$("#usepeerdns").bind("change", function() {
		self.model.usepeerdns = $(this).is(":checked");
	});

	$("#refuse-pap").bind("change", function() {
		self.model.refuse_pap = $(this).is(":checked");
	});

	$("#refuse-eap").bind("change", function() {
		self.model.refuse_eap = $(this).is(":checked");
	});

	$("#require-mppe-128").bind("change", function() {
		self.model.require_mppe_128 = $(this).is(":checked");
	});

	$("#__ML_save").bind("click", function() {
		self.save();
	});
	$("#__ML_cancel").bind("click", function() {
		self.cancel();
	});

	$("#showHidePassword").bind("click", function() {
		self.view.showHidePassword();
	});
};

Controller.prototype.init = function() {
	this.setValues();
	this.view.init();
};

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

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

Controller.prototype.setValues = function() {

	if(this.model.enabled) {
		$("#enabled").attr("checked", "checked");
	} else {
		$("#enabled").removeAttr("checked");
	}

	$("#server").val(this.model.server);
	$("#username").val(this.model.username);
	$("#password").val(this.model.password);
	$("#mtu").val(this.model.mtu);
	
	if(this.model.routeAllTrafficThroughVpn) {
		$("#routeAllTrafficThroughVpn").attr("checked", "checked");
	} else {
		$("#routeAllTrafficThroughVpn").removeAttr("checked");
	}
	
	if(this.model.usepeerdns) {
		$("#usepeerdns").attr("checked", "checked");
	} else {
		$("#usepeerdns").removeAttr("checked");
	}
	
	if(this.model.refuse_pap) {
		$("#refuse-pap").attr("checked", "checked");
	} else {
		$("#refuse-pap").removeAttr("checked");
	}
	
	if(this.model.refuse_eap) {
		$("#refuse-eap").attr("checked", "checked");
	} else {
		$("#refuse-eap").removeAttr("checked");
	}
	
	if(this.model.require_mppe_128) {
		$("#require-mppe-128").attr("checked", "checked");
	} else {
		$("#require-mppe-128").removeAttr("checked");
	}
};

var controller;

$(document).ready(function() {
	parseURI();
	controller = new Controller(GETDATA["inst"]);
});
