var defaultHiddenItems=",";

$(function () {
    $("#nav ul li a").corner();
    $('[autofocus]').autofocus();
});

function setDefaultHiddenItems(list) {
	defaultHiddenItems=list;
}

function currentPerspective() {
	p = $.jStorage.get('SELECTED_PERSPECTIVE', '_NOT_FOUND_');
	if (p=='_NOT_FOUND_') {
		$.jStorage.set('SELECTED_PERSPECTIVE', 'P1');
		return 'P1';
	}
	return p;
}

function removeFromPerspective(item) {
	curr = currentPerspective();
	list = retrieveHiddenList(curr);
	if(list.indexOf(","+item+",") == -1) {
		list += item + ",";
		$.jStorage.set(curr, list);
	}
}

function retrieveHiddenList(p) {
	list = $.jStorage.get(p, '_NOT_FOUND_');
	if (list=='_NOT_FOUND_') {
		$.jStorage.set(p, defaultHiddenItems);
		return defaultHiddenItems;
	}
	return list;
}

function addToPerspective(item) {
	curr = currentPerspective();
	list = retrieveHiddenList(curr);
	if(list.indexOf(","+item+",") > -1) {
		list = list.replace(","+item+",", ",");
		$.jStorage.set(curr, list);
	}
}

$(document).ready(function () {
    updateMenu(currentPerspective());
});

function perspectiveItemName(el) {
	return el.name.replace("perspective_check_", "");
}

function configPerspectives() {	
	if ($('#menuConfig').is(':visible')) {
		$('#menuConfig').hide();
	} else {
		updatePerspectiveCheckboxes();
		$('#menuConfig').show();
	}
}

function updatePerspectiveCheckboxes() {
	var blacklist = retrieveHiddenList(currentPerspective());
	
	$('#menuConfig input').each(function (ix, el) {
		var name = perspectiveItemName(el);
		if(blacklist.indexOf(","+name+",") > -1)
			el.checked=false;
		else
			el.checked=true;
	});
}

function changePerspectiveItem(el) {
	var name = perspectiveItemName(el);

	//Uncomment for debug
	//console.log("changing " + name);
	
	if(!el.checked) {
		removeFromPerspective(name);
	} else {
		addToPerspective(name);
	}
	updateMenu(currentPerspective());
}

function resetJStorage(p) {
	if (confirm("Reset Local Storage?")) {
        $.jStorage.flush();
        window.location.reload();
    }
}

function updateMenu(p) {
    list = retrieveHiddenList(p);     
    $(".menuItem").each(function () {
        if ((new RegExp("," + $(this).text() + ",")).test(list)) {
            $(this).hide();
        } else {
            $(this).show();
        }
    });
    $(".menuPerspective").removeClass("selected");
    $("#menu_" + p).addClass("selected");
}

function changePerspective(p) {
    $.jStorage.set("SELECTED_PERSPECTIVE", p);
    updatePerspectiveCheckboxes();
    updateMenu(p);
}
