// Extend the site object to have this functionality
lib.obj.dynamicDropdown = function(settings) {
	if(arguments.length > 0)
	{ this.init(settings); }
};

lib.obj.dynamicDropdown.prototype.init = function(settings) {
	var settings = jQuery.extend({
		dropdownSelector : "._dds",
		inputSelector : "#_ddinput",
		noDefaults : false,
		customDefaults : false,
		customDefaultLabels : [],
		customDefaultValues : []
	},settings);
	
	this.dropdownSelector = settings.dropdownSelector;
	this.inputSelector = settings.inputSelector;
	this.noDefaults = settings.noDefaults;
	this.hasCustomDefaults = settings.customDefaults;
	this.defaultLabels = settings.customDefaultLabels;
	this.defaultValues = settings.customDefaultValues;
	this.values = [];
	this.labels = [];
	this.ids = [];
	this.isActive = [];
	this.order = [];
	this.selected = [];
	
	// working set arrays
	this.uniqueValues = [];
	this.uniqueValuesIndex = [];
};

lib.obj.dynamicDropdown.prototype.addEntry = function(entry) {
	 var entryCorrect = ( (entry.id != null) && (entry.values != null) && (entry.labels != null) && (entry.values.length == entry.labels.length) ) ? true : false;
	 if(entryCorrect)
	 {
	 	//if first entry, add the default blank entry
	 	if( this.values.length == 0 )
	 	{  
	 		var blankVals = [];
	 		var blankLabels = [];
	 		for( var i = 0; i < entry.values.length; i++)
			{
				blankLabels[i] = this.hasCustomDefaults ? this.defaultLabels[i] : "Select";
				blankVals[i] = this.hasCustomDefaults ? this.defaultValues[i] : "";
			}
	 		
	 		this.values[this.values.length] = blankVals;
	 		this.labels[this.labels.length] = blankLabels;
	 		this.ids[this.ids.length] = null;
	 		this.isActive[this.isActive.length] = true;
	 	}
	 	
	 	this.values[this.values.length] = entry.values;
	 	this.labels[this.labels.length] = entry.labels;
	 	this.ids[this.ids.length] = entry.id;
	 	this.isActive[this.isActive.length] = true;
	 }
	 else
	 { alert("There is a problem with this entry, you may be missing values, labels, and id, or the values / labels aren't the same size."); }	
};

lib.obj.dynamicDropdown.prototype.start = function() {
	
	// setup the default for order and selected
	if( this.values.length > 0)
	{
		// initialize these arrays correctly (reset arrays)
		for( var i = 0; i < this.values[0].length; i++)
		{
			this.order[i] = null;
			this.selected[i] = null;
			this.uniqueValues[i] = [];
			this.uniqueValuesIndex[i] = [];
		}	
		
		this.updateDropdowns();
		this.addEvents();
	}
	else
	{ alert("No entries in dropdown group"); }
};

lib.obj.dynamicDropdown.prototype.addEvents = function() {
	// Add events to dropdowns 	
	var ddObj = this;	
	$(this.dropdownSelector).unbind("change.dynamicDropdown");
	$(this.dropdownSelector).each(function(i) {
		$(this).bind("change.dynamicDropdown",function() {
			// set this dropdown in the order
			var setOrder = false;
			for( var j = 0; j < ddObj.order.length; j++)
			{
				if(setOrder && (ddObj.order[j] != null))
				{
					ddObj.selected[ddObj.order[j]] = null;
					ddObj.order[j] = null;
				}
			
				if( !setOrder && ((ddObj.order[j] == null) || (ddObj.order[j] == i)) )
				{
					ddObj.order[j] = ($(this).val() != ddObj.defaultValues[j]) ? i : null;
					setOrder = true;
				}
			}
			// set this value as the selected
			ddObj.selected[i] = ( $(this).val() != ddObj.defaultValues[i] ) ? $(this).val() : null;
			// now update the dropdown display
			ddObj.updateDropdowns();
		});
	});
};

lib.obj.dynamicDropdown.prototype.updateState = function() {
	//reset the unique value arrays
	for(var i = 0; i < this.values[0].length; i++)
	{
		this.uniqueValues[i] = [];
		this.uniqueValuesIndex[i] = [];
		if(!this.noDefaults) // add the default option
		{ this.uniqueValuesIndex[i][this.uniqueValuesIndex[i].length] = 0; } 
	}
	
	// loop through all entries and do work
	for(var i = 1; i < this.ids.length; i++)
	{
		var stillActive = true;
		for(var j = 0; j < this.values[0].length; j++)
		{
			if( (this.selected[j] != null) && (this.values[i][j] != this.selected[j]) )
			{ 
				stillActive = false;
				x = this.values[0].length;
			}
		}
		this.isActive[i] = stillActive;
		
		// if this is going to be active see if it contains a unique value to add to dropdown
		if( this.isActive[i] )
 		{
 			for( var j = 0; j < this.values[0].length; j++ )
	 		{
	 			var isUnique = true;
	 			for( var x = 0; x < this.uniqueValues[j].length; x++)
	 			{
	 				if( this.uniqueValues[j][x] == this.values[i][j] )
	 				{
	 					isUnique = false;
	 					x = this.uniqueValues[j].length;
	 				}
	 			}
	 			if(isUnique)
	 			{  
	 				this.uniqueValues[j][this.uniqueValues[j].length] = this.values[i][j];
	 				this.uniqueValuesIndex[j][this.uniqueValuesIndex[j].length] = i;
	 			}
	 		}
 		}
 		// ------------------------
	}
	
	// remove the unique values, as just need unique indexes
	for( i = 0; i < this.values[0].length; i++) // don't need the values just need indexs
 	{ this.uniqueValues[i] = []; }
};

lib.obj.dynamicDropdown.prototype.updateDropdowns = function() {
	// first update the new state of the drop-downs
	this.updateState();
	
	//remove old dropdown values and populate dropdowns with all new values
	var ddObj = this;
	$(ddObj.dropdownSelector).each(function(i) {
		
		if( ddObj.selected[i] == null )
		{
			//remove old options
			$("option", this).remove();
			
			// add the correct options/ update options if not the box you just selected
			var optionHTML = "";
			var hasEmpty = false;
			var hasOther = false;
			
			for( var j = 0; j < ddObj.uniqueValuesIndex[i].length; j++)
	        {
				if ( "NA" == ddObj.values[ddObj.uniqueValuesIndex[i][j]][i] ){
					
					hasEmpty = true;
				}else if ("null" != ddObj.values[ddObj.uniqueValuesIndex[i][j]][i] && "not-sure" != ddObj.values[ddObj.uniqueValuesIndex[i][j]][i]){
					hasOther = true;
				}
	        }
			
			// hide the dropdown if it only has empty value
			if ( hasEmpty && !hasOther ){
				
				$(this).hide();
				$(this).append('<option value="NA">-</option>');
				
				
				if ( $("#TireConsultationContent").size() > 0 ){
					$(this).parent().hide();
				}
				
				return 0;
				
			}else{
				$(this).show();
				
				if ( $("#TireConsultationContent").size() > 0 ){
					$(this).parent().show();
				}
				
			}
         // first put select XXX option          
         for( var j = 0; j < ddObj.uniqueValuesIndex[i].length; j++)
          {
             if("null" == ddObj.values[ddObj.uniqueValuesIndex[i][j]][i]) {
               optionHTML += '<option value="' + ddObj.values[ddObj.uniqueValuesIndex[i][j]][i] + '">' + ddObj.labels[ddObj.uniqueValuesIndex[i][j]][i] + '</option>';
             }
          }
          // second put  not sure option             
         for( var j = 0; j < ddObj.uniqueValuesIndex[i].length; j++)
          {
             if("not-sure" == ddObj.values[ddObj.uniqueValuesIndex[i][j]][i] && ddObj.uniqueValuesIndex[i].length > 3
            		 															// updated, if the dropdown has only defaul value and one additional value, don't show the not-sure
            		 ){
               optionHTML += '<option value="' + ddObj.values[ddObj.uniqueValuesIndex[i][j]][i] + '">' + ddObj.labels[ddObj.uniqueValuesIndex[i][j]][i] + '</option>';
             }
          }

         ddObj.uniqueValuesIndex[i].sort(
            function compare(a, b) {
                if (ddObj.labels[a][i] <ddObj.labels[b][i]) {
                  return -1;
               }
                if (ddObj.labels[a][i] >ddObj.labels[b][i]) {
                   return 1;
               }
               if (ddObj.labels[a][i] ==ddObj.labels[b][i]) {
                  return 0;
               }
            }
         );
         
         for( var j = 0; j < ddObj.uniqueValuesIndex[i].length; j++)
			{
            if(("null" != ddObj.values[ddObj.uniqueValuesIndex[i][j]][i]) && ("not-sure" != ddObj.values[ddObj.uniqueValuesIndex[i][j]][i])) {
               optionHTML += '<option value="' + ddObj.values[ddObj.uniqueValuesIndex[i][j]][i] + '">' + ddObj.labels[ddObj.uniqueValuesIndex[i][j]][i] + '</option>';
            }
         }
			$(this).append(optionHTML);
		
		}
		
			// set to the correct value
			if(ddObj.selected[i] != null )
			{ $(this).val( ddObj.selected[i] ); }
		
	});
	
	// set the "variant id" if all dropdowns are selected
	this.setInput();
};

lib.obj.dynamicDropdown.prototype.setInput = function() {
	var variantSelected = true;
	for( var j = 0; j < this.selected.length; j++)
	{
		if( this.selected[j] == null )
		{ variantSelected = false; }
	}
	
	//if all values selected, find first active entry and set that as the value.
	if(variantSelected)
	{
		for( var j = 1; j < this.ids.length; j++)
		{
			if( this.isActive[j] )
			{
				$(this.inputSelector).val( this.ids[j] );
				j = this.ids.length;
			}
		}
	}
	else
	{ $(this.inputSelector).val(""); }
};
