﻿$(document).ready(function(){
	$.ajax({
		type:'POST',
		url:'/WebServices/WineCheesePair.aspx?function=GetWines',
		data: {},
		dataType:'json',
		success: function(j){
			var options = '';
			for (var i = 0; i < j.length; i++) {
				options = '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
				$(options).appendTo($('#selWine'));
			}
		},
		error: function(xhr, ajaxOptions, thrownError) {
			alert(xhr.status + '\n' + thrownError);
		}
	});
	$.ajax({
		type:'POST',
		url:'/WebServices/WineCheesePair.aspx?function=GetCheese',
		data: {},
		dataType:'json',
		success: function(j){
			var options = '';
			for (var i = 0; i < j.length; i++) {
				options = '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
				$(options).appendTo($('#selCheese'));
			}
		},
		error: function(xhr, ajaxOptions, thrownError) {
			alert(xhr.status + '\n' + thrownError);
		}
	});
	
});

function findMatchesFor(type) {
	if(type == 'cheese') {
		//clear out the wine select box
		$('#selWine').val(0);
		
		//if cheese selected, populate results
		if($('#selCheese').val() > 0) {
			$.ajax({
				type:'GET',
				url:'/WebServices/WineCheesePair.aspx?function=GetMatches&for=cheese&id=' + $('#selCheese').val(),
				data:{},
				dataType: 'json',
				success: function(j) {
					var t = $('#selCheese option:selected').text();
					$('#divCheeseName').html(t.split("&reg;").join("<sup>&reg;</sup>").split("®").join("<sup>&reg;</sup>"));
					var red = '';
					var white = '';
					var comma = '';
					for (var i = 0; i < j.length; i++) {
						if(j[i].wineType == 'Red') {
							comma = (red=='') ? ' ' : ', ';
							red += comma + j[i].wineDescription;
						} else {
							comma = (white=='') ? ' ' : ', '; 
							white += comma + j[i].wineDescription;
						}
					}
					$('#divRedWines').html(red);
					$('#divWhiteWines').html(white);
					$('#wcp-box-wine').show();
					$('#wcp-box-cheese').hide();
				},
				error: function(xhr, ajaxOptions, thrownError) {
					alert(xhr.status + '\n' + thrownError);
				}
			});
		} else {
			$('#wcp-box-wine').hide();
		}
	} else {
		//clear out the cheese select box
		$('#selCheese').val(0);
		
		//if wine selected, populate results
		if($('#selWine').val() > 0) {
			$.ajax({
				type:'GET',
				url:'/WebServices/WineCheesePair.aspx?function=GetMatches&for=wine&id=' + $('#selWine').val(),
				data:{},
				dataType: 'json',
				success: function(j) {
					$('#divWineName').html($('#selWine option:selected').text());
					var cheeses = '';
					for (var i = 0; i < j.length; i++) {
						cheeses += '<div class="wcp-cheese"><a href="' + j[i].cheeseUrl + '">' + j[i].cheeseDescription + '</a></div>';
					}
					$('#divCheeses').html(cheeses);
					$('#wcp-box-cheese').show();
					$('#wcp-box-wine').hide();
				}
			});
		} else {
			$('#wcp-box-cheese').hide();
		}
	}
}