/**
 * @author samuelme
 */

(function($) {
  //
  // Creates the functionality for the Allergen Info page
  //
  $.fn.Allergens = function(options) {
	//debug(this);
	// build main options before element iteration
	var opts = $.extend({}, $.fn.Allergens.defaults, options);
	// iterate and reformat each matched element
//	return this.each(function() {
	  var scope = $(this);
//	  // build element specific options
//	  var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
//	});

	//setupBtns($(this));
	handlexml($.fn.Allergens.defaults.xml,scope);
	//debug("this is it: "+$(this).html());
	$('#foodType').change(function(){
		handlexml($.fn.Allergens.defaults.xml,$('html'),$(this).val());
	})
  };
  
  
  
  //
  // private function for debugging
  //
  var firstcat_ingred;
  var $selectedObj;
  var forceSelection;
  
  function handlexml(ajaxURL,scope,type){
	  
	var $this = scope;
		
  	$.ajax({
		url: ajaxURL,
		type: "GET",
		dataType: "xml",
		success: function(xml) {
		
			
			//find main cats
			var food_cat_array = [];
			$(xml).find('menuSet').each(function(i){
				var foodType = $(this).attr('type');
				
//				if (type == undefined) {
//					debug("type: "+type);
//					food_cat_array.push(foodType);
//					if(i == 0){
//						 $selectedObj = $('<option  value="' + foodType + '">' + foodType + '</option>');
//						 $selectedObj.appendTo('#foodType');
//					}else{
//						$('#foodType').append('<option value="' + foodType + '">' + foodType + '</option>');
//					}
//				}
			});
			
			//remove error message:
			$('.allergyChart .noMsg').remove();
			
			
			if(type == undefined){
				firstcat_ingred = food_cat_array[0];
				forceSelection = true;
			}else{
				firstcat_ingred = type;
				$("#AllergyChart").remove();
				var mytype = type.toLowerCase();
			}
			var $length = $(xml).find("menuSet").find("item[ "+mytype+" = 'full' ]").size() + $(xml).find("menuSet").find("item[ "+mytype+" = 'part' ]").size();
			var $tableObj = createTable();
			var $tableBodyObj = createTbody($tableObj);
			var tableRowColor = ["even","odd"];
			var i = 1;
			
			function makeTable(obj,tableObj,tableBodyObj,tableRowColor) {
				var ingred_title = $(obj).attr('title') ? $(obj).attr('title') : "empty";
				var milk = $(obj).attr('milk') ? $(obj).attr('milk') : "empty";
				var egg = $(obj).attr('egg') ? $(obj).attr('egg') : "empty";
				var fish = $(obj).attr('fish') ? $(obj).attr('fish') : "empty";
				var shellfish = $(obj).attr('shellfish') ? $(obj).attr('shellfish') : "empty";
				var wheat = $(obj).attr('wheat') ? $(obj).attr('wheat') : "empty";
				var soy = $(obj).attr('soy') ? $(obj).attr('soy') : "empty";
				var peanuts = $(obj).attr('peanuts') ? $(obj).attr('peanuts') : "empty";
				var nuts = $(obj).attr('nuts') ? $(obj).attr('nuts') : "empty";
				var tableDataArray = [ingred_title, milk, egg, fish, shellfish, wheat, soy, peanuts, nuts];
				
				//table row shading
				if (i == 1) {i = 0;}
				else if (i == 0) {i = 1;}
				
				var $tableRow = createTableRow($tableBodyObj, tableRowColor[i]);
				var $tableData = createTableData($tableRow, tableDataArray);
			}
			
			///function for the return of all allergens
			if (type == undefined || mytype == "all") {
				$(xml).find("menuSet").find('item').each(function(){
					makeTable($(this),$tableObj,$tableBodyObj,tableRowColor);
				});
			}else{
				///function for the return of specified allergens
				$(xml).find("menuSet").find("item[ "+mytype+" = 'full' ]").each(function(){
					makeTable($(this),$tableObj,$tableBodyObj,tableRowColor);
				});

				///function for the return of specified allergens
				$(xml).find("menuSet").find("item[ "+mytype+" = 'part' ]").each(function(){
					makeTable($(this),$tableObj,$tableBodyObj,tableRowColor);
				});
				
				//handel if nothing is returned.
				if($length <= 0){
					createNoReturnMsg($tableBodyObj,type);
					//clears out the allergy chart since nothing is there to display.
					$('#AllergyChart').remove();
				}
			}
			
		},
		error: function() {
		},
		complete: function(){
		
		}
	});
	
	
  }
  function createTable(){
  	var $obj = $('<table id="AllergyChart" cellpadding="0" cellspacing="0"><thead><tr>'
	+'<th scope="col" class="allergyCat">&nbsp;</th><th scope="col">Milk</th><th scope="col">Egg</th><th scope="col">Fish</th><th scope="col">Shellfish</th><th scope="col">Wheat</th><th scope="col">Soy</th><th scope="col">Peanuts</th><th scope="col">Nuts</th>'
	+'</tr></thead>'
	+'<tfoot><tr><td scope="col" class="allergyCat">&nbsp;</td><td scope="col">Milk</td><td scope="col">Egg</td><td scope="col">Fish</td><td scope="col">Shellfish</td><td scope="col">Wheat</td><td scope="col">Soy</td><td scope="col">Peanuts</td><td scope="col">Nuts</td></tr></tfoot>'
	+'</table>');
	$obj.appendTo(".allergyChart");
  	return $obj;
  }
  function createTbody($scope){
  	var $obj = $('<tbody> </tbody>');
  	$obj.appendTo($scope);
  	return $obj;
  }
  function createTableRow($scope,trHighLight){
  	var $obj = $('<tr class="'+trHighLight+'"> </tr>');
  	$obj.appendTo($scope);
  	return $obj;
  }
  
  function createTableData($scope,tableDataArray){
  	for(i=0; i<tableDataArray.length; i++){
		if (i == 0) {
			$scope.append('<td class="foodTitle">' + tableDataArray[0] + '</td>');
		}
		else {
			$scope.append('<td><span class="'+tableDataArray[i]+'">'+tableDataArray[i]+'</span></td>');
		}
	}
  }
  
  function createNoReturnMsg($scope,type){
  	$('.allergyChart').append('<p class="noMsg">No ingredients found that contain "'+type+'" at this time.</p>');
  }


  function setSelection($obj){
  	if (forceSelection == true ) {
		setTimeout(function(){$obj.attr('selected', 'selected')},1);
		forceSelection = false;
	}	
  }
  function debug($obj) {
	if (window.console && window.console.log)
	  window.console.log($obj);
  };

 
  $.fn.Allergens.defaults = {xml:'xml/allergens_v2.23.00.xml'};
})(jQuery);