﻿var _currentPageURL = -1;

$(document).ready(function() {
	Sys.Application.add_init(pageInit);
});

function pageInit() {
	// Enable history
	Sys.Application.set_enableHistory(true);

	// Add Handler for history
	Sys.Application.add_navigate(navigate);
}

function recordAjaxNav(args) {
    //_currentPageURL = this.getAttribute("pageURL");
    var locationArray = args.toString().split("/");
    var locationString = ""
    var first = "true";
    for (var i = 3; i < locationArray.length; i++) {
        if (locationArray[i] != "Search" && locationArray[i] != "CategorySearch" && locationArray[i] != "CategoryList") {
            if (first == "true") {
                first = "false";
            } else {
                locationString += "-";
            }
            locationString += locationArray[i];
        }
    }
    //locationString = locationArray[locationArray.length - 1];
    _currentPageURL = locationString;

    // Add history point
    Sys.Application.addHistoryPoint({ "pageURL": _currentPageURL });
}

function navigate(sender, e) {
	var pageURL = e.get_state().pageURL;

	// If pageURL != _currentPageURL then navigate
	if (pageURL != null){
	    if (pageURL != _currentPageURL) {
		    _currentPageURL = pageURL;
		    pageURL = pageURL.replace("-", "/")
		    loadAjaxPage(pageURL);
	    }
	} else { // pageURL == null
	    var locationArray = window.location.href.toString().split("/");
	    var locationString = locationArray[locationArray.length - 1];
	    pageURL = locationString;
	    _currentPageURL = pageURL;
	    loadAjaxPage(pageURL);
	}
}



function loadAjaxPage(pageURL) {
    // side bar: category results (eg: Dentist, Dance, Design)
	$.get("/Search/CategoryList/" + pageURL, function(response) {
		$("#resultscontainer").html(response);
	});

	// main content results
	$("#results").html("<div class='mainContentLoading'>");
	$.get(searchActionMethod + pageURL, function(response) {
		$("#results").html(response);
	});

    // make sure correct letter is highlighted
	$(".categoryListLink").each(function() {
		$(this).removeClass($(this).attr("title") + "active");
		if ($(this).attr("title").toLowerCase() == pageURL.charAt(0).toLowerCase()) {
			$(this).addClass($(this).attr("title") + "active");
		}
    });
    
    // make sure correct side bar - category result is bold
    $.get("/Search/CategoryName?CategoryQuery=" + "" + pageURL, function(response) {
        $(".categoryListSearchLink").each(function() {
            $(this).removeClass("active");
            if ($(this).text().toLowerCase() == response.toLowerCase()) {
                $(this).addClass("active");
            }
        })
    });
    
    //update breadcrumb
    $.get("/Search/CategoryName?CategoryQuery=" + pageURL, function(response) {
        $("#CategoryName").html(response);
        document.title = 'Yellow Pages - ' + Encoder.htmlDecode(response) + ' - Search the Guernsey Directory - Sure'; 
    });

	return false;
}

