﻿var NULL_ID = "{00000000-0000-0000-0000-000000000000}";
var CATEGORY_1_LIST;
var CATEGORY_2_LIST;
var CATEGORY_3_LIST;
var REGIONS_LIST;
var COUNTRIES_LIST;
var PARTNER_LIST;
var STATUS_ELEM;
var MESSAGE_ELEM;
var LINK_ELEM;
var PRINT_ELEM;
var ACTION_PANE;

$(document).ready(function()
{
	CATEGORY_1_LIST = $('#Category1');
	CATEGORY_2_LIST = $('#Category2');
	CATEGORY_3_LIST = $('#Category3');
	REGIONS_LIST = $('#RegionsOfOperation');
	COUNTRIES_LIST = $('#CountriesOfOperation');
	PARTNER_LIST = $('#PartnerList');
	STATUS_ELEM = $('#Status');
	MESSAGE_ELEM = $('#Message');
	LINK_ELEM = $('#LinkToThisPage');
	PRINT_ELEM = $('#PrinterFriendly');
	ACTION_PANE = $('#Actions .actionPane');

	InitializeLists();

	LINK_ELEM.click(ToggleLink);
	if (window.location.search.indexOf("p=1") != -1)
	{
		LINK_ELEM.hide();
		PRINT_ELEM.hide();
	}
});

function InitializeLists()
{
	ShowStatus();

	//add default option to Category 2 select list, disable it and assign event handler	
	CATEGORY_2_LIST.addOption("", "-- All --", true);
	CATEGORY_2_LIST.attr("disabled", "disabled");
	CATEGORY_2_LIST.change(Category2_Change);

	//add default option to Category 3 select list, disable it and assign event handler
	CATEGORY_3_LIST.addOption("", "-- All --", true);
	CATEGORY_3_LIST.attr("disabled", "disabled");
	CATEGORY_3_LIST.change(UpdatePartnerList);
	
	//add options to Category 1 select list
	$.ajax({
		type: "POST",
		url: "/Webservices/LLC/PartnerLookup.asmx/GetCategories",
		data: "{'parentCategoryID':''}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg)
		{
			//evaluate the webservice response, if it's a string value, then parse the JSON into array/object
			var categories = (typeof msg.d) == 'string' && msg.d != '' ? eval('(' + msg.d + ')') : msg.d;
			//add default option
			CATEGORY_1_LIST.addOption("", "-- All --", false);
			//add options
			for (var i = 0; i < categories.length; i++)
			{
				CATEGORY_1_LIST.addOption(categories[i].Value, categories[i].Text, false);
			}
			//assign event handler
			CATEGORY_1_LIST.change(Category1_Change);
		},
		complete: function(msg)
		{
			if (typeof (CATEGORY_1_ID) != "undefined")
			{
				CATEGORY_1_LIST.val(CATEGORY_1_ID);
				UpdateCategory2(false);
			}
			if (typeof (CATEGORY_2_ID) != "undefined")
			{
				CATEGORY_2_LIST.val(CATEGORY_2_ID);
				UpdateCategory3(false);
			}
			if (typeof (CATEGORY_3_ID) != "undefined")
			{
				CATEGORY_3_LIST.val(CATEGORY_3_ID);
			}
		}
	});	

	//add options to Region select list
	$.ajax({
		type: "POST",
		url: "/Webservices/LLC/PartnerLookup.asmx/GetRegions",
		data: "{}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg)
		{
			//evaluate the webservice response, if it's a string value, then parse the JSON into array/object
			var regions = (typeof msg.d) == 'string' && msg.d != '' ? eval('(' + msg.d + ')') : msg.d;
			//add default option
			REGIONS_LIST.addOption("", "-- All --", false);
			//add options
			for (var i = 0; i < regions.length; i++)
			{
				REGIONS_LIST.addOption(regions[i].Value, regions[i].Text, false);
			}
			//assign event handler
			REGIONS_LIST.change(UpdatePartnerList);
		},
		complete: function()
		{
			if (typeof (REGION_ID) != "undefined")
			{
				REGIONS_LIST.val(REGION_ID);
			}
		}
	});

	//add options to Country select list
	$.ajax({
		type: "POST",
		url: "/Webservices/LLC/PartnerLookup.asmx/GetCountries",
		data: "{}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg)
		{
			//evaluate the webservice response, if it's a string value, then parse the JSON into array/object
			var countries = (typeof msg.d) == 'string' && msg.d != '' ? eval('(' + msg.d + ')') : msg.d;
			//add default option
			COUNTRIES_LIST.addOption("", "-- All --", false);
			//add options
			for (var i = 0; i < countries.length; i++)
			{
				COUNTRIES_LIST.addOption(countries[i].Value, countries[i].Text, false);
			}
			//assign event handler
			COUNTRIES_LIST.change(UpdatePartnerList);
		},
		complete: function()
		{
			if (typeof (COUNTRY_ID) != "undefined")
			{
				COUNTRIES_LIST.val(COUNTRY_ID);
			}
		}
	});

	PARTNER_LIST.one('ajaxStop', function()
	{		
		UpdatePartnerList();
	});
}

function Category1_Change()
{
	UpdateCategory2(true);
}

function UpdateCategory2(doPartnerUpdate)
{
	CATEGORY_2_LIST.html('');
	CATEGORY_2_LIST.addOption("", "-- All --", true);
	CATEGORY_2_LIST.attr("disabled", "disabled");

	CATEGORY_3_LIST.html('');
	CATEGORY_3_LIST.addOption("", "-- All --", true);
	CATEGORY_3_LIST.attr("disabled", "disabled");	

	var parentCategoryID = CATEGORY_1_LIST.val() != null ? CATEGORY_1_LIST.val() : '';
	if (parentCategoryID != '')
	{
		$.ajax({
			async: false,
			type: "POST",
			url: "/Webservices/LLC/PartnerLookup.asmx/GetCategories",
			data: "{'parentCategoryID':'" + parentCategoryID + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg)
			{
				var categories = (typeof msg.d) == 'string' && msg.d != '' ? eval('(' + msg.d + ')') : msg.d;

				//handle pass-through categories
				if (categories.length == 1 && categories[0].PassThrough)
				{
					CATEGORY_2_LIST.html('');
					CATEGORY_2_LIST.addOption(categories[0].Value, "-- All --", true);
					CATEGORY_2_LIST.attr("disabled", "disabled");

					doPartnerUpdate = false;
					//need to disable partner list update before this call
					Category2_Change();
				}
				else if (categories.length > 0)
				{
					for (var i = 0; i < categories.length; i++)
					{
						CATEGORY_2_LIST.addOption(categories[i].Value, categories[i].Text, false);
					}
					CATEGORY_2_LIST.removeAttr("disabled");
				}
			}
		});
	}
	
	if (doPartnerUpdate)
	{		
		UpdatePartnerList();
	}
}

function Category2_Change()
{
	UpdateCategory3(true);
}

function UpdateCategory3(doPartnerUpdate)
{
	CATEGORY_3_LIST.html('');
	CATEGORY_3_LIST.addOption("", "-- All --", true);
	CATEGORY_3_LIST.attr("disabled", "disabled");

	var parentCategoryID = CATEGORY_2_LIST.val() != null ? CATEGORY_2_LIST.val() : '';
	if (parentCategoryID != '')
	{
		$.ajax({
			async: false,
			type: "POST",
			url: "/Webservices/LLC/PartnerLookup.asmx/GetCategories",
			data: "{'parentCategoryID':'" + parentCategoryID + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg)
			{
				var categories = (typeof msg.d) == 'string' && msg.d != '' ? eval('(' + msg.d + ')') : msg.d;

				if (categories.length > 0)
				{
					for (var i = 0; i < categories.length; i++)
					{
						CATEGORY_3_LIST.addOption(categories[i].Value, categories[i].Text, false);
					}
					CATEGORY_3_LIST.removeAttr("disabled");
				}
			}
		});
	}
	if (doPartnerUpdate)
	{
		UpdatePartnerList();
	}
}

function UpdatePartnerList()
{
	HideLink();
	ShowStatus();
	
	var category1 = CATEGORY_1_LIST.val() != null ? CATEGORY_1_LIST.val() : '';
	var category2 = CATEGORY_2_LIST.val() != null ? CATEGORY_2_LIST.val() : '';	
	var category3 = CATEGORY_3_LIST.val() != null ? CATEGORY_3_LIST.val() : '';
	var region = REGIONS_LIST.val() != null ? REGIONS_LIST.val() : '';
	var country = COUNTRIES_LIST.val() != null ? COUNTRIES_LIST.val() : '';

	$.ajax({
		type: "POST",
		url: "/Webservices/LLC/PartnerLookup.asmx/GetPartnerList",
		data: "{'category1':'" + category1 + "','category2':'" + category2 + "','category3':'" + category3 + "','region':'" + region + "','country':'" + country + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg)
		{
			var partners = (typeof msg.d) == 'string' && msg.d != '' ? eval('(' + msg.d + ')') : msg.d;
			if (partners.length > 0)
			{
				var html = '<table cellspacing="1">';
				html += '<th>Company Name</th>';
				html += '<th>Country</th>';
				html += '<th class="address">Address</th>';
				html += '<th>Contact</th>';
				html += '<th>Email</th>';
				html += '<th>Phone</th>';
				for (var i = 0; i < partners.length; i++)
				{
					html += '<tr>';
					html += '<td>';
					if (partners[i].Website != '')
					{
						html += '<a href="' + partners[i].Website + '" target="_blank">';
						html += partners[i].PartnerName;
						html += '</a>';
					}
					else
					{
						html += partners[i].PartnerName;
					}
					html += '</td>';
					html += '<td>' + partners[i].Country + '&#160;</td>';
					html += '<td>' + partners[i].Address.replace(/\n/g, "<br />") + '&#160;</td>';
					html += '<td>' + partners[i].Contact + '&#160;</td>';
					html += '<td>';
					if (partners[i].Email != '')
					{
						html += '<a href="mailto:' + partners[i].Email + '">';
						html += partners[i].Email;
						html += '</a>';
					}
					else
					{
						html += '&#160';
					}
					html += '</td>';
					html += '<td>' + partners[i].Phone + '&#160;</td>';
					html += '</tr>';
				}
				html += '</table>';
				PARTNER_LIST.html(html);
			}
			else
			{
				ShowMessage("<h3>Sorry, but we don't seem to have any partners matching the criteria you specified.</h3>");
			}
			HideStatus();
		},
		complete: function(msg)
		{
			PRINT_ELEM.attr('href', GenerateLink(true));
		}
	});	
}

function ShowStatus()
{
	if (!STATUS_ELEM.is(":visible"))
	{
		STATUS_ELEM.fadeIn(400);
		MESSAGE_ELEM.hide();
		PARTNER_LIST.html('');
	}
}

function HideStatus()
{
	STATUS_ELEM.slideUp(800);
	//STATUS_ELEM.hide();
}

function ShowMessage(message)
{
	MESSAGE_ELEM.html("<h3>" + message + "</h3>");
	MESSAGE_ELEM.fadeIn(2000);
}

function HideLink()
{
	ACTION_PANE.slideUp(400);
}

function ToggleLink()
{	
	var html = "<h3>Below is a URL you can use to return to these results:</h3><h4>" + GenerateLink(false) + "</h4>";
	if (ACTION_PANE.is(":visible"))
	{
		ACTION_PANE.slideUp(400);		
	}
	else
	{
		ACTION_PANE.html(html)
		ACTION_PANE.slideDown(400);
	}
}

function GenerateLink(includePrint)
{	
	var link = "http://" + window.location.host + window.location.pathname;
	var query = '';
	if (CATEGORY_1_LIST.val() != '')
	{
		query += "c1=" + CATEGORY_1_LIST.val();
	}
	if (CATEGORY_2_LIST.val() != '')
	{
		if (query != '') query += '&';
		query += "c2=" + CATEGORY_2_LIST.val();
	}
	if (CATEGORY_3_LIST.val() != '')
	{
		if (query != '') query += '&';
		query += "c3=" + CATEGORY_3_LIST.val();
	}
	if (REGIONS_LIST.val() != '')
	{
		if (query != '') query += '&';
		query += "re=" + REGIONS_LIST.val();
	}
	if (COUNTRIES_LIST.val() != '')
	{
		if (query != '') query += '&';
		query += "co=" + COUNTRIES_LIST.val();
	}
	if (includePrint)
	{
		if (query != '') query += '&';
		query += "p=1";
	}
	if (query != '')
	{
		query = "?" + query;
	}
	return link + query;
}

///////////////////////
// MAPPING FUNCTIONS //
///////////////////////
/*
function UpdatePartnerMap()
{
	mgr.clearMarkers();
	var partnerType = GetValueFromList(partnerTypesElemId);
	var productType = GetValueFromList(productTypesElemId);
	var applicationType = GetValueFromList(applicationTypesElemId);	
	var regionOfOperation = GetValueFromList(regionsElemId);
	var countryOfOperation = GetValueFromList(countriesElemId);
	NatureWorks.Web.Webservices.LLC.PartnerLookupService.GetMapMarkers(partnerType, productType, applicationType, regionOfOperation, countryOfOperation, function(result) {	
	if (result != null && result.length > 0)
		{
			var markers = [];
			for (var i=0; i<result.length; i++)
			{					
				markers.push(CreateMarker(result[i]));				
			}
			mgr.addMarkers(markers, 0, 17);
			mgr.refresh();
		}
	});
}
*/
/*
	the CreateMarker function MUST be a separate function to give the 'marker' variable proper scope for adding
	event listeners.
	for some reason it doesn't work if you attempt to roll the marker creation into the for loop when iterating through the
	items to add.
*/
/*
function CreateMarker(currentItem)
{
	var icon = currentItem.IconURL;
	if (icon == null)
	{
		icon = new GIcon(G_DEFAULT_ICON);
	}
	var title = currentItem.Title;
	var posn = new GLatLng(currentItem.Latitude, currentItem.Longitude);
	var marker = new GMarker(posn, {title: title, icon: icon, draggable:false });
	
	//have to grab partnerID here, result[i] isn't in scope within the anonymous functions below.
	var partnerID = currentItem.ID;
	
	GEvent.addListener(marker, "click", function() {
											NatureWorks.Web.Webservices.LLC.PartnerLookupService.GetPartnerDetails(partnerID, function(result) {
																								marker.openInfoWindowHtml(result);
																							});																	
										});	
	return marker;
}
*/
//function AddListeners(marker, currentItem)
//{	
	/*
	if (result[i].EventListeners != null && result[i].EventListeners.length > 0)
	{							
		for (var j=0; j<result[i].EventListeners.length; j++)
		{
			GEvent.addListener(marker, result[i].EventListeners[j].EventName, new Function(result[i].EventListeners[j].Function));
			//alert(marker.EventListeners[j].Function);	
		}
	}
	*/
//}