jQuery(document).ready(function($){
	var subjects = [];
	$.extend({
		getClassSubjects: function(options) {
			$.ajax({
				type: "post",
				url: "contents/plugins/eedu_portal/ajax.php",
				data: {"action": "get_class_subjects", "selection": options.selection, fulloption: options.fulloption}
			}).done(function(data){
				try {
					data = JSON.parse(data);
					subjects[options.selection] = data.courses;
					$.listSubjects(options.selection, options.id);
				}
				catch(err) {
					console.log(err);
					console.log(data);
				}
				finally{
					console.log(data);
				}
			}).fail(function(err){
				console.log(err);
				$.getClassSubjects(options);
			})
		},
		listSubjects: function(selection, id) {
			$("#"+id).empty();
			$("#"+id).append('<option value="">Select...</option>');
			var html = "";
			var selected = "";
			if (typeof(Storage) !== "undefined") {
			  	selected = localStorage.getItem("selection-"+id);
			}
			for(var subject_id in subjects[selection]) {
				html += '<option value="'+subject_id+'"';
				if (subject_id == selected) {
					html += " selected ";
				}
				html += '>'+subjects[selection][subject_id]+'</option>';
			}
			$("#"+id).append(html).trigger("chosen:updated");
			$(document).on("change", "#"+id, function(){
				if (typeof(Storage) !== "undefined") {
				  	localStorage.setItem("selection-"+id, $(this).val());
				}
			})
		}
	})
	$(document).on("change", ".class-category", function(e) {
		var element = $(this);
		var val = $(element).val();
		if (typeof(Storage) !== "undefined") {
		  	localStorage.setItem("lastname", "Smith");
		}
		if(subjects[val] === undefined) {
			$.getClassSubjects({
				"selection": val,
				"fulloption": $(element).data('fulloption'),
				"id": $(element).data('id')
			});
		} else {
			$.listSubjects(val, $(element).data('id'));
		}
	})
})
