var Jvna = {};

Jvna.Status = {
	enable: "enable",
	disable: "disable",
	undef: "undefined"
};

Jvna.StatusKey = "status";

Jvna.Badges = {
	enable: "NoAD",
	disable: ""
};

Jvna.Titles = {
	enable: "点击允许插片广告",
	disable: "点击屏蔽插片广告"
};

Jvna.getStatus = function () {
	var status = localStorage[Jvna.StatusKey];
	if (status!==Jvna.Status.enable && status!==Jvna.Status.disable) {
		return Jvna.Status.undef;
	}
	
	return status;
}

Jvna.setStatus = function (status) {
	localStorage[Jvna.StatusKey] = status;
}

Jvna.enable = function () {
	var result;
	
	result = Switchy.enableAutoPac();
	if (!result)
		return false;

	Jvna.setStatus(Jvna.Status.enable);
	
	chrome.browserAction.setBadgeText({text: Jvna.Badges.enable});
	chrome.browserAction.setTitle({title: Jvna.Titles.enable});

	return true;
}

Jvna.disable = function () {
	var result;
	
	result = Switchy.disableAutoPac();
	if (!result)
		return false;

	Jvna.setStatus(Jvna.Status.disable);
	
	chrome.browserAction.setBadgeText({text: Jvna.Badges.disable});
	chrome.browserAction.setTitle({title: Jvna.Titles.disable});
		
	return true;
}

Jvna.init = function () {
	var status;
	
	chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
		if (request.action == "get_status")
      		sendResponse({status: Jvna.getStatus()});
		else
			sendResponse({});
	});
	
	chrome.browserAction.onClicked.addListener(function(tab) {
		var status = Jvna.getStatus();
		if (status == Jvna.Status.enable) {
			Jvna.disable();
		} else {	//disable
			Jvna.enable();
		}
	});
	
	status = Jvna.getStatus();
	if (status == Jvna.Status.disable) {
		return Jvna.disable();
	} else {	//enable & undefined
		return Jvna.enable();
	}
}
