var fullCountryList = new Array();
var allowedCountries = new Array();
var productsList = new Array();
var isInbound;

function productCallback(data) {
	productsList = new Array();
	var txt = '';
	$("#product").get(0).options.length = 0;
	$.each(data, function(index, item) {
		productsList.push(item);
        $("#product").get(0).options[$("#product").get(0).options.length] = new Option(item.NAME, item.ID);
    });	
	isInbound = 0;
}

function fullCountriesCallback(data) {
	fullCountryList = new Array();
	$("#ddlFullCountries").get(0).options.length = 0;
	$.each(data, function(index, item) {
		fullCountryList.push(item);
        $("#ddlFullCountries").get(0).options[$("#ddlFullCountries").get(0).options.length] = new Option(item.COUNTRY, item.ID);
    });
}

function ipCallback(data) {
	$("#txtIP").val(data['ip']);
}

function getAllowedCountriesCallback(data) {
	allowedCountries = new Array();
	$("#ddlAllowedCountries").get(0).options.length = 0;
	$.each(data, function(index, item) {
		allowedCountries.push(item);
        $("#ddlAllowedCountries").get(0).options[$("#ddlAllowedCountries").get(0).options.length] = new Option(item.COUNTRY, item.ID);
    });
}
function getItem(haystack,needle,field){
	for (var i in haystack){
		var item = haystack[i];
		if(item[field] == needle){
			return item;
		}
	}
	return null;
}
$("#product").change( function(e){
	  var i = $("#product").val();
	  var item = getItem(productsList,i,'ID');
	  if(isInbound != item.IS_INBOUND){
		  isInbound = item.IS_INBOUND;
		  $("#ddlAllowedCountries").get(0).options.length = 0;
		  $("#ddlFullCountries").get(0).options.length = 0;
		  switch(isInbound){
			  case "0":
				  $.each(fullCountryList, function(index, item) {
						$("#ddlFullCountries").get(0).options[$("#ddlFullCountries").get(0).options.length] = new Option(item.COUNTRY, item.ID);
				  });
				  $.each(allowedCountries, function(index, item) {
				        $("#ddlAllowedCountries").get(0).options[$("#ddlAllowedCountries").get(0).options.length] = new Option(item.COUNTRY, item.ID);
				  });
				  break;
			  case "1":
				  $.each(allowedCountries, function(index, item) {
						$("#ddlFullCountries").get(0).options[$("#ddlFullCountries").get(0).options.length] = new Option(item.COUNTRY, item.ID);
				  });
				  $.each(fullCountryList, function(index, item) {
				        $("#ddlAllowedCountries").get(0).options[$("#ddlAllowedCountries").get(0).options.length] = new Option(item.COUNTRY, item.ID);
				  });
				  break;
		  }
	  }
});
