var institutionFacet = "no";
var progressionLevelFacet = "no";
var ucasCodeFacet = "no";
var page = 1;
var nPages = 0;
var counts = [];

$(document).ready(function() {
	
	$("#q").keypress(function(e){ if (e.which==13) {doSearch(1,true);} })
	
	$("#personalise_demo").bind("click",null,personaliseDemo);
	initPersonalisation();
	$("#showPersonalisedResult").bind("click",null,togglePersonalisationEvent);
	switchStyle("shop");
});

function initPersonalisation()
{
	if ($.url.param("myInstitution")==""){
		$("#showPersonalisedResultDiv").css("display","none");
	}
}

function togglePersonalisationEvent(e)
{
	highlightPersonalizedFacets();
}

function startsWith(s1, s2) {
	return s1.substring(0, s2.length)==s2;
}

function highlightPersonalizedFacets() {
	var personalised = $("#showPersonalisedResult")[0].checked;
	if ($.url.param("myInstitution")) {
		$("#institutionsChoices li a").each(function(){
			if (personalised && startsWith($(this).html(), addSpaces($.url.param("myInstitution")))) {
				$(this).parent().addClass("my");
			} else {
				$(this).parent().removeClass("my");
			}
		});
	}
	if ($.url.param("myProgressionLevel")) {
		$("#progressionLevelsChoices li a").each(function(){
			if (personalised && startsWith($(this).html(), addSpaces($.url.param("myProgressionLevel")))) {
				$(this).parent().addClass("my");
			} else {
				$(this).parent().removeClass("my");
			}
		});
	}
	if ($.url.param("myCourseTitle")) {
		$("#ucasCodesChoices li a").each(function(){
			if (personalised && startsWith($(this).html(), addSpaces($.url.param("myCourseTitle")))) {
				$(this).parent().addClass("my");
			} else {
				$(this).parent().removeClass("my");
			}
		});
	}
	if ($.url.param("myAcademicYear")) {
		$("#academicYearsChoices li a").each(function(){
			if (personalised && startsWith($(this).html(), addSpaces($.url.param("myAcademicYear")))) {
				$(this).parent().addClass("my");
			} else {
				$(this).parent().removeClass("my");
			}
		});
	}
}

//Keep this indirection. Extend the argument to handle different types of widget if/when we need them
function personaliseDemo(e){
	showWidget();
}

function showWidget(){
	var blankout = $("#blankout");
	var widget = $("#widget");
	$("#widgetContent").load("/personaliseDemo/personalise.html?r="+Math.random());
	blankout.show("fast");
	widget.show("fast");
}

function hideWidget(){
	var blankout = $("#blankout");
	var widget = $("#widget");
	blankout.hide("fast");
	widget.hide("fast");
}

function rememberSelection(facetName, value) {
	$("#selections").append("<div class='selection "
		+ facetName + "' value='"
		+ value + "'>"
		+ addSpaces(value) + "</div>"
		+ "<div class=\"selection-tail-closebox\" "
		+ "onmouseover=\"this.className='selection-tail-closebox-over'\" "
		+ "onmouseout=\"this.className='selection-tail-closebox'\" "
		+ "onclick='removeSelection(this);'>&nbsp;</div>");
	doSearch(1);
}

function updatePaging(nResults, page, pageSize) {
	page = page;
	if (page==1) $("#prev").hide();
	else  $("#prev").show();
	
	nPages = Math.floor(nResults/pageSize);
	nPages += ((nResults%pageSize)>0) ? 1 : 0;
	
	var nextPage = (page+1)*pageSize;
	
	if (nextPage > nResults+pageSize)
		$("#next").hide();
	else $("#next").show();
	
	if (page>=3) $("#first").show();
	else $("#first").hide();
	
	if (page<nPages) $("#last").show();
	else $("#last").hide();
	
	$("#paging").empty();
	$("#paging").append("page " + page + " of " + nPages + " (of " + nResults + " total results)");
}

function firstPage() {
	page = 1;
	doSearch(page);
}

function lastPage() {
	page = nPages;
	doSearch(page);
}

function prevPage() {
	page--;
	doSearch(page);
}

function nextPage() {
	page++;
	doSearch(page);
}

function removeSelection(divElement) {
	$(divElement).prev().remove();
	$(divElement).remove();
	doSearch(1);
}

function handleError(result) {
	alert("there was an error: " + result);
}

function doSearch(somePage, reset) {
	if (reset) resetAll();
	page = somePage;
	var q = $("#q")[0].value;
	if (q=="") {
		alert("You must specify some search term(s)!")
		return;
	}
	var facetingWidgets = $("#facetingWidgets select");
	var data = selectionsToMap($(".selection"));
	data["page"] = page;
	$.ajax({
		type: "GET",
		dataType: "text",
		url: "/solr/search?q="+q,
		data: data?data:null,
		error: function(message) {
			handleError(message);
		},
		success: function(result) {
			$("#results").empty();
			$("#results").append(result);
		}
	});
}

function updateFacetingWidgets(facetCounts) {
	updateFacetSelectionWidget(facetCounts.facet_fields["institutions"], "institutions");
	updateFacetSelectionWidget(facetCounts.facet_fields["progressionLevels"], "progressionLevels");
	updateFacetSelectionWidget(facetCounts.facet_fields["ucasCodes"], "ucasCodes");
	updateFacetSelectionWidget(facetCounts.facet_fields["academicYears"], "academicYears");
	$(".readingListsIcon").click(
		function() {
			var rlId = eval($(this).attr("readingList"));
			var rlDiv = $(this).parent().find("." + rlId);
			if (!$(this).attr("expanded") || $(this).attr("expanded")=="false") {
				$(this).attr("expanded", "true");
				
				if (rlDiv[0].innerHTML!="")
				{
					rlDiv.show("slow");
				} else {
					//rlDiv.load("/readingLists/" + rlId + ".html",null,function(){rlDiv.show()} );
					$.ajax({
						   type: "GET",
						   url: "/readingLists/" + rlId + ".html?reload=true",
						   success: function(msg){
						     rlDiv.hide();
						     rlDiv.html(msg);
						     rlDiv.show("slow");
						   }
						 });

				}
				
			} else {
				$(this).attr("expanded", "false");
				rlDiv.hide("slow");
				//rlDiv.empty();
			}
		}
	);
	highlightPersonalizedFacets();
}

function isPersonalized() {
	return $("#showPersonalisedResult")[0].checked;
}

function updateFacetSelectionWidget(nvPairs, facetName) {
	var choicesWrapper = $("#" + facetName + "ChoicesWrapper");
	var choices = $("#" + facetName + "Choices");
	choices.empty();
	if (nvPairs.length > 3) {
		counts[facetName] = nvPairs.length/2;
		choices.append("<li class=\"selectedChoice\">All</li>");
		for (var i=0; i<nvPairs.length; i++) {
			var text = nvPairs[i++];
			var count = nvPairs[i];
			if (facetName=="academicYears") {
				var year = Number(text);
				var value = year + "/" + (year+1);
				if ($("#showFacetCount")[0].checked)
					choices.append("<li><a href='javascript:rememberSelection(\"" + facetName + "\", \"" + text + "\")'>" + value +" ("+count+")" + "</a></li>");
				else
					choices.append("<li><a href='javascript:rememberSelection(\"" + facetName + "\", \"" + text + "\")'>" + value + "</a></li>");
			} else {
				if ($("#showFacetCount")[0].checked)
					choices.append("<li><a href='javascript:rememberSelection(\"" + facetName + "\", \"" + text + "\")'>" + addSpaces(text) +" ("+count+")" + "</a></li>");
				else
					choices.append("<li><a href='javascript:rememberSelection(\"" + facetName + "\", \"" + text + "\")'>" + addSpaces(text) + "</a></li>");
			}
		}
		choicesWrapper.show();
	} else if (nvPairs.length==2) {
		if (getSelectionDiv(facetName)) {
//			if ($("#showFacetCount")[0].checked)
//				choices.append("<li><a href='javascript:removeSelection(getSelectionDiv(\"" + facetName + "\"))'>All"  + " (" + counts[facetName] + ")</a></li>");
//			else
				choices.append("<li><a href='javascript:removeSelection(getSelectionDiv(\"" + facetName + "\"))'>All</a></li>");
		}
		var text = nvPairs[0];
		var count = nvPairs[1];
		if (facetName=="academicYears") {
			var year = Number(text);
			var value = year + "/" + (year+1);
			if ($("#showFacetCount")[0].checked)
				choices.append("<li>" + value + " ("+count+")" + "</li>");
			else
				choices.append("<li class=\"selectedChoice\">" + value + "</li>");
		} else {
			if
				($("#showFacetCount")[0].checked) choices.append("<li>" + addSpaces(text) + " ("+count+")" + "</li>");
			else
				choices.append("<li class=\"selectedChoice\">" + addSpaces(text) + "</li>");
		}
	} else {
		choicesWrapper.empty();
		choicesWrapper.append("<ul id=\"" + facetName + "Choices" + "\" class=\"itchoice\"/>");
	}
}

function moreLikeThis(terms) {
	terms = removeAll(terms, ".:;");
	$("#q")[0].value = terms;
	doSearch(1, true);
}

function removeAll(terms, chars) {
	for (var i=0; i<chars.length; i++)
		terms = terms.replace(chars.charAt(i), "");
	terms = terms.replace("  ", " ");
	return terms;
}

function resetAll() {
	$(".selection").remove();
	$(".selection-tail-closebox").remove();
	$(".selection-tail-closebox-over").remove();
}

function getPrettyFacetName(facetName) {
	switch(facetName) {
	case "institutions":
		return "Institutions";
	case "progressionLevels":
		return "Progression Levels";
	case "ucasCodes":
		return "Courses";
	case "academicYears":
		return "Academic Years";
	}
}

function getSelectionDiv(facetName) {
	var selectionDiv = $(".selection." + facetName).next()[0];
	return selectionDiv;
}

function addSpaces(s) {
	return s.replace(/#/g, " ");
}

function selectionsToMap(selectionDivs) {
	var map = {};
	for (var i=0; i<selectionDivs.length; i++) {
		var value = selectionDivs[i].getAttribute("value");
		var facetName = getFacetName(selectionDivs[i].className);
		if (facetName!=null) {
			map[facetName] = value;
		}
	}
	return map;
}

function getFacetName(className) {
	var names = className.split(" ");
	for (var i=0; i<names.length; i++) {
		if (names[i]=="selection") continue;
		return names[i];
	}
	return null;
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function switchStyle(styleType) {
	switch_style(styleType);
	switch(styleType) {
	case "shop":
		$("#facetingWidgets").hide();
		$("#shopFacetingWidgets").show();
		$("#itunesStyleCheck").removeAttr("checked");
		$("#shopStyleCheck").attr("checked", "checked");
		$("#shopInstitutionsChoicesWrapper").append($("#institutionsChoices"));
		$("#shopProgressionLevelsChoicesWrapper").append($("#progressionLevelsChoices"));
		$("#shopUcasCodesChoicesWrapper").append($("#ucasCodesChoices"));
		$("#shopAcademicYearsChoicesWrapper").append($("#academicYearsChoices"));
		return
	case "itunes":
		$("#shopFacetingWidgets").hide();
		$("#facetingWidgets").show();
		$("#itunesStyleCheck").attr("checked", "checked");
		$("#shopStyleCheck").removeAttr("checked");
		$("#itchoices").show();
		$("#institutionsChoicesWrapper").append($("#institutionsChoices"));
		$("#progressionLevelsChoicesWrapper").append($("#progressionLevelsChoices"));
		$("#ucasCodesChoicesWrapper").append($("#ucasCodesChoices"));
		$("#academicYearsChoicesWrapper").append($("#academicYearsChoices"));
		return
	}
}

function switch_style ( css_title ) {
  var i, link_tag ;
  for (i = 0, link_tag = document.getElementsByTagName("link") ;
    i < link_tag.length ; i++ ) {
    if ((link_tag[i].rel.indexOf( "stylesheet" ) != -1) &&
      link_tag[i].title) {
      link_tag[i].disabled = true ;
      if (link_tag[i].title == css_title) {
        link_tag[i].disabled = false ;
      }
    }
  }
}

