var themes;
var categories;
var recipes;
var todays = "";
var totalcount = 0;
var readingSettings = false;

var selectedTheme = '';
var selectedCategory = '';
var selectedSearch = '';
var selectedDiff = '';
var selectedTime = 150;
var selectedPage = 1;

var pageSize = 25;

// Page ids in vertical site for the different xml sources
var VS_settingsPage = '2959';
var VS_searchPage = '2957';
var VS_recipePage = '2958';

String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

String.prototype.ucfirst = function(str)
{return (this.substring(0, 1).toUpperCase() + this.substring(1))}

$(document).ready(function() {
	
	$.get("page", { 'id': VS_settingsPage }, function(xml) {

		// Themes
		themes = $("theme", xml);
		l = "";
		for(i = 0; i < themes.length; i++) {
			theme = themes.eq(i);
			l += "<li class='theme' id='theme_" + theme.attr("id") + "'>" + theme.attr("name") + "</li>";
		}
		$("#lstTheme").empty().append(l);

		// Categories
		categories = $("recipedata > category", xml);
		l = "";
		for(i = 0; i < categories.length; i++) {
			cat = categories.eq(i);
			l += "<li class='category' id='category_" + cat.attr("id") + "'>" + cat.attr("name") + "</li>";
		}
		$("#lstCategory").empty().append(l);

		// Click action for themes
		$(".theme").click(function() {
			selectedTheme = $(this).attr("id").substring(6);
			$(".theme").removeClass("selected");
			$(this).addClass("selected");
			selectedPage = 1;
			updateRecipeList();
		});

		// Click action or categories
		$(".category").click(function() {
			selectedCategory = $(this).attr("id").substring(9);
			$(".category").removeClass("selected");
			$(this).addClass("selected");
			selectedPage = 1;
			updateRecipeList();
		});

/*		todays = $("today > recipe", xml).attr("href").match("key=([^&]*)")[1]; */
		todays = $("today > recipe", xml).attr("id");
		showRecipe(todays);
		readSettings();
	});

	selectedSearch = $("#txtSearch").val();

	$("#sliderTime").slider({
			'range': "min",
			'value': selectedTime,
			'min': 1,
			'max': 180,
			'slide': function(event, ui) {
				updateTimeLabel(ui.value);
			},
			'change': function(event, ui) {
				selectedTime = ui.value;
				if(!readingSettings) {
					selectedPage = 1;
					updateRecipeList();
				}
			}
	});

	$(".diffselector").click(function() {
		if(selectedDiff == $(this).attr("id").substring(4).toLowerCase()) {
			selectedDiff = "";
			$(".diffselector > div").removeClass("selected");
		} else {
			selectedDiff = $(this).attr("id").substring(4).toLowerCase();
			$(".diffselector > div").removeClass("selected");
			$("div", this).addClass("selected");
		}
		selectedPage = 1;
		updateRecipeList();
	});

	$("#txtSearch").keyup(function(e) {
		selectedSearch = $("#txtSearch").val();

		if(e.keyCode == 13) {
			$("#btnSok").click();
		}
	});

	$("#btnSok").click(function() {
		selectedSearch = $("#txtSearch").val();
		selectedPage = 1;
		updateRecipeList();
	});

	$("#btnResetSok").click(function() {
		$("#txtSearch").val("");
		selectedSearch = "";
		selectedPage = 1;
		updateRecipeList();
	});

	$("#btnDagens").click(function() {
		showRecipe(todays);
	});
	
	$("#btnResetValg").click(function() {
		selectedTheme = "";
		$(".theme").removeClass("selected");

		selectedDiff = "";
		$(".diffselector > div").removeClass("selected");

		selectedCategory = "";
		$(".category").removeClass("selected");

		selectedPage = 1;

		updateRecipeList();
	});

	$("#btnPrevious").click(function() {
		if(selectedPage > 1) {
			selectedPage--;
			updateRecipeList();
		}
	});

	$("#btnNext").click(function() {
		if((selectedPage * pageSize) < totalcount) {
			selectedPage++;
			updateRecipeList();
		}
	});

	updateTimeLabel(selectedTime);
	readSettings();
	updateRecipeList();
});

function updateTimeLabel(minutes) {
	h = Math.floor(minutes / 60);
	m = minutes - (h * 60);
	t = "";

	if(h > 0) {
		t = h + " time";
		if(h > 1) {
			t += "r";
		}
	}

	if(m > 0) {
		t += " " + m + " minutt";
		if(m > 1) {
			t += "er";
		}
	}

	$("#spnTime").text(t);
}

function updateRecipeList() {
	url = "page";
	query = "";

	$("#loader").show();
	$("#lstOppskrifter").empty();
	$("#headerOppskrifter").text("Laster...");

	if(selectedSearch != "") {
		query += 'data/* LIKE "%' + selectedSearch + '%" AND ';
	}

	if(selectedDiff != "") {
		query += 'data/difficulty= "' + selectedDiff + '" AND ';
	}

	if(selectedTheme != "") {
		query += "data/themes/content/@key=" + selectedTheme + ' AND ';
	}

	if(selectedTime != "") {
		query += "data/worktime < " + selectedTime + " AND ";
	}

	if(query.endsWith(" AND ")) {
		query = query.substring(0, query.length - 5);
	}

	params = {
		'id': VS_searchPage,
		'query': query,
		'count': pageSize,
		'index': ((selectedPage - 1) * pageSize)
	};

	if(selectedCategory != "") {
		params.cat = selectedCategory;
	}

	storeSettings();

	$.get(url, params, function(xml) {
		recipes = $("recipe", xml);
		totalcount = $("recipes", xml).attr("totalcount");

		l = "";
		for(i=0; i < recipes.length; i++) {
			recipe = recipes.eq(i);
			l += "<li class='recipe' id='recipe_" + recipe.attr("id") + "'>" + recipe.attr("name") + "</li>";
		}

		$("#headerOppskrifter").text(totalcount + " oppskrifter");
		$("#loader").hide();
		$("#lstOppskrifter").append(l);

		$(".recipe").click(function() {
			goToRecipe($(this).attr("id").substring(7));
		});

		start = ((selectedPage - 1) * pageSize) + 1;
		end = Math.min(start + pageSize - 1, totalcount);
		pageCount = Math.ceil(totalcount / pageSize);

		$("#lblPage").text("Side " + selectedPage + " av " + pageCount);

		if((selectedPage * pageSize) > totalcount) {
			$("#btnNext").css("visibility", "hidden");
		} else {
			$("#btnNext").css("visibility", "visible");
		}

		if(selectedPage <= 1) {
			$("#btnPrevious").css("visibility", "hidden");
		} else {
			$("#btnPrevious").css("visibility", "visible");
		}
	});
}

function readSettings() {
	if(location.hash.length > 1) {
		readingSettings = true;

		selectedPage = 1;
		selectedDiff = "";
		selectedCategory = "";
		selectedTime = 60;
		selectedSearch = "";
		selectedTheme = "";

		settings = location.hash.substring(1).split("&");
		for(i = 0; i < settings.length; i++) {
			setting = settings[i].split("=");
	
			if(setting[0] == "page") {
				selectedPage = setting[1];
			}

			if(setting[0] == "diff") {
				selectedDiff = setting[1];
				$(".diffselector > div").removeClass("selected");
				$("#diff" + selectedDiff.ucfirst() + " > div").addClass("selected");
			}

			if(setting[0] == "category") {
				selectedCategory = setting[1];
				$(".category").removeClass("selected");
				$("#category_" + selectedCategory).addClass("selected");
			}

			if(setting[0] == "search") {
				selectedSearch = setting[1];
			}

			if(setting[0] == "worktime") {
				selectedTime = setting[1];
				updateTimeLabel(selectedTime);
				$("#sliderTime").slider('value', selectedTime);
			}

			if(setting[0] == "theme") {
				selectedTheme = setting[1];
				$(".theme").removeClass("selected");
				$("#theme_" + selectedTheme).addClass("selected");
				$("#lstTheme").scrollTo("#theme_" + selectedTheme);
			}
		}

		if(selectedTheme == "") {
			$(".theme").removeClass("selected");
		}

		if(selectedCategory == "") {
			$(".category").removeClass("selected");
		}

		if(selectedDiff == "") {
			$(".diffselector > div").removeClass("selected");
		}

		$("#txtSearch").val(selectedSearch);
		readingSettings = false;
	}
}

function storeSettings() {
	h = "#";

	if(selectedSearch != "") {
		h += 'search=' + selectedSearch + '&';
	}

	if(selectedDiff != "") {
		h += 'diff=' + selectedDiff + '&';
	}

	if(selectedTheme != "") {
		h += 'theme=' + selectedTheme + '&';
	}

	if(selectedCategory != "") {
		h += 'category=' + selectedCategory + '&';
	}

	if(selectedPage > 1) {
		h += "page=" + selectedPage + "&";
	}

	if(selectedTime != "") {
		h += "worktime=" + selectedTime + "&";
	}

	if(h.endsWith("&")) {
		h = h.substring(0, h.length - 1);
	}

	window.location.hash = h;
	lastHash = h;
}

function showRecipe(key) {
	$.get("page", { 
		'id': VS_recipePage, 
		'key': key
	}, function(xml) {
		imgsrc = $("recipe", xml).attr("imgsrc");
		if(imgsrc != "") {
			$("#imgOppskrift").attr("src", imgsrc).show();
			$("#imgOppskrift").show();
		} else {
			$("#imgOppskrift").hide();	
		}
		$("#recipeTitle").text( $("recipe", xml).attr("name") ).show();
		$("#txtDescription").text( $("description", xml).text() ).show();
		$("#btnToRecipe").attr("href", $("recipe", xml).attr("href") );

	});
}

function goToRecipe(key) {

	for(var i = 0; i < recipes.length; i++) {
		var r = $(recipes[i]);
		if(r.attr("id") == key) {
			location.href = r.attr("href");
		}
	}
/*
	$.get("page", { 
		'id': VS_recipePage, 
		'key': key
	}, function(xml) {
		location.href = $("recipe", xml).attr("href");
	});
*/
}

var lastHash = '';

function pollHash() {
    if(lastHash !== location.hash) {
        lastHash = location.hash;

        readSettings();
		updateRecipeList();
    }
}

setInterval(pollHash, 100);

