/*global jQuery, $ */

if (typeof DFS === 'undefined') {
    var DFS = {};
}
/**
 *	For IE ONLY it has not implemented the indexOf function for the array object
 */
if (typeof Array.prototype.indexOf == 'undefined') {
	 Array.prototype.indexOf = function (obj) {
	     for (var i = 0; i < this.length; ++i) {
	         if (this[i] === obj) {
	             return i;
	         }
	     }
	  return -1;
	 }
}

/**
 * Insert an item or list of items, ensuring exclusivity 
 */
Array.prototype.insert = function(item) {
	if (item.constructor === Array)	{
		for (var i=0, l=item.length; i<l; i++) {
			this.insert(item[i]);
		}
		return;
	}

	if (this.indexOf(item) === -1) {	
		this.push(item);
	}
};

/**
 * Singleton encapsulating "Help Me Choose" logic
 */
DFS.Chooser = function() {
	return {
		init: function() {
			var chooser = this; 
			
			this.rewardsInputs  = $('input[name~=rewards]');
			this.businessInputs = $('input[name=business]');
			this.studentInputs  = $('input[name=student]');
			
			$('#reset-link').click(function(){
			 chooser.reset();
			});
		},
		
		/**
		 * Return true if any of inputs is checked; false otherwise
		 */
		rewardsChecked: function(){
            return this.rewardsInputs.is(":checked");
		},

		businessChecked: function(){
			return this.businessInputs.is(":checked");
		},
		
		studentChecked: function(){
            return this.studentInputs.is(":checked");
        },
        
        /**
         * Return selected value of form field, or null
         */
        businessValue: function(){
            return parseInt(this.businessInputs.filter(":checked").attr("value"));
        },
        
        studentValue: function(){
            return parseInt(this.studentInputs.filter(":checked").attr("value"));
        },
		
		/**
         * Return an index into the FIRST level of the cardLogic data structure
         * (either a particular checkbox name, or 'rewards-none' if none are selected)
         */
		checkboxLogicIndex: function( el ){
			if ( !this.rewardsChecked() ) { return 'rewards-none'; }
		    
			return el.attr('name');
		},
		
		/**
		 * Return an index into the SECOND level of the cardLogic data structure
		 * (which radio button is checked - both/business/student)
		 */
		radioLogicIndex: function()	{
			var business = this.businessChecked(),
			    student  = this.studentChecked();
				
                if ( business && student ) { 
                    return 2; 
                }
				
				// Since "No answer" entries are the same for both radio buttons,
				//  this could return 0 OR 1
				if ( !business && !student ){
					return 0;					
				}
				
				if (business) { return 0; }
				
				return 1;
		},
		
		/**
         * Return an index into the THIRD level of the cardLogic data structure
         * (the value of the radio button - unchecked/yes/no)  
         */		
		radioResponseIndex: function(){
            var business    = this.businessChecked(),
                student     = this.studentChecked(),
                businessVal = this.businessValue(),
                studentVal  = this.studentValue();
				
                if ( (business && student) ) { 
		            switch (businessVal + "|" + studentVal){
                        case "1|1": return 0;
                        case "0|1": return 1;
                        case "1|0": return 2;
                        case "0|0": return 3;
                        default: throw new Error("Invalid value for radioResponseIndex()");
                    };
                };
				
				if ( !business && !student ){
					return 0;
				}
                
                var radioVal;
                
                if (business){ 
                    radioVal = businessVal;  
                }
                else {
                    radioVal = studentVal;
                }
                
                switch(radioVal){
                    case 0:  return 2;
                    case 1:  return 1;
                    default: return 0;
                }
             

		},
		
		/**
		 * Fade in current list of cards, and fade out others
		 */
		showCards: function(){
            
			for (var abbrev in this.cardIds){    
				if ( this.cardsToShow.indexOf( abbrev ) === -1 ){
					$( '#' + this.cardIds[ abbrev ] ).fadeTo("normal", 0.1);
				}
				else {
					$( '#' + this.cardIds[ abbrev ] ).fadeTo("normal", 1);
				}
                
			};
		},
		
		/**
		 * Remove 'checked' state on all questions
		 */
		reset: function(){
			this.rewardsInputs.attr("checked", false);
			this.businessInputs.attr("checked", false);
			this.studentInputs.attr("checked", false);
		}
		
	};
}();

/**
 * Maps 2-character card names to DOM element ids
 */
DFS.Chooser.cardIds = {
    'MR': 'more-card',
    'MO': 'motiva-card', 
    'OR': 'openroad-card', 
    'MI': 'miles-card',
    'ST': 'student-card',
    'BU': 'business-card',
    'BM': 'business-miles-card',
    'ES': 'escape-card',
    'SO': 'student-open-road-card'
};

DFS.Chooser.cardLogic = {
    
    /**
    
    // Replacement #1
    ([A-Z]{2})
    '$1'
    
    // Replacement #2
      
    ], [
    
    // Replacement #3
    
    
    */
    
        // If first checkbox is checked: I use my card for everything....
        'rewards1': [
        
            // If EITHER or NEITHER of Business/Student questions are answered:
            [
                ['BU', 'MR', 'ST'], // if "Business" question has no answer 
                ['BU'],             // if "Business" question was answered "Yes"
                ['MR', 'ST']        // if "Business" question was answered "No"
            ],
            [
                ['ST'],             // if "Student" question has no answer 
                ['ST'],             // if "Student" question was answered "Yes"
                ['MR', 'BU']        // if "Student" question was answered "No"
            ],
            
            // If BOTH Business AND Student questions are answered:
            [
                ['ST', 'SO'],					// business yes, student yes 
                ['ST'],             			// business no,  student yes
                ['MR', 'BU'],             		// business yes, student no
                ['MR']                         // business no,  student no
            ]
        ],
        
        // If 2nd checkbox is checked: I spend a lot on gas 
        'rewards2': [
        
            [
                ['OR', 'SO'], 					// Business NOT CHECKED
                ['BU'], 						// Business YES
                ['OR', 'SO']					// Business NO
            ],
            [
                ['OR', 'SO'], 					// Student NOT CHECKED
                ['SO'], 						// student YES
                ['OR']          				// Student NOT
            ],
            
            // If BOTH Business AND Student questions are answered:
            [
                ['SO'], 							// Business YES, Student YES
                ['SO'],								// Business NO, Student YES
                ['OR', 'BU'], 						// Business YES, Student NO
                ['OR']								// Business NO, Student NO
            ]
         ],
                  
        // If 3rd checkbox is checked: I'd like to earn Miles
        'rewards3': [
            [
                ['BM', 'MI', 'ES'], 		// Business NOT CHECKED
                ['BM'], 					// Business YES
                ['MI', 'ES']				// Business NO
            ], 
            [
                ['BM', 'MI', 'ES'], 				// Student NOT CHECKED
                ['ST', 'SO'],						// Student YES
                ['BM', 'MI', 'ES']					// Student NO
            ],
            
            // If BOTH Business AND Student questions are answered: 
            [
                ['ST', 'SO'], 						// Business YES & Student YES
                ['ST', 'SO'], 						// Business NO & Student YES
                ['BM'], 							// Businesss YES & Student NO
                ['MI', 'ES']						// Business NO & Studetn NO
            ]        
        ],
        
        // If 4th checkbox is checked: I usually carry and...
        'rewards4': [
            [
                ['MO'],					// Business NOT CHECKED
                ['BU', 'BM', 'MO'],		// Business YES
                ['MO']            		// Business NO
            ],
            [
                ['MO'],					// Student NOT CHECKED
                ['ST', 'SO'],		// Student YES
                ['MO']  				// Student NO          
            ],
            
            // If BOTH Business AND Student questions are answered:             
            [
                ['ST', 'SO'],						// Business YES & Student YES
                ['ST', 'SO'],						// Business NO & Student YES
                ['MO', 'BU', 'BM'],					// Business YES & Student NO
                ['MO']            					// Business NO & Student NO
            ]        
        ],

         // If NO checkboxes are checked
        'rewards-none': [
            [
			    // All
                ['MR', 'MO', 'OR', 'MI', 'ST', 'BU', 'BM', 'ES', 'SO'],
				
				// Business only 
				['BU', 'BM'], 

				// Everything else
				['MR', 'MO', 'OR', 'MI', 'ST', 'ES', 'SO']
            ],
			[
                // All
                ['MR', 'MO', 'OR', 'MI', 'ST', 'BU', 'BM', 'ES', 'SO'],

                // Student only 
                ['ST', 'SO'], 
                
                // Everything else
                ['MR', 'MO', 'OR', 'MI', 'BU', 'BM', 'ES']
            ],
			[
                // yes/yes (all)
                ['ST', 'SO'],
				
				// no/yes (student only) 
                ['ST', 'SO'],
				
				// yes/no (business only)
				['BU', 'BM'], 
				
				// no/no
                ['MR', 'MO', 'OR', 'MI', 'ES']
            ]
        ]

};

DFS.Chooser.getCardsToShow = function(){
    var chooser = this, cardList = [];
    
    // If NO Rewards are checked: 
    if ( !this.rewardsChecked() ){
        var $this = $(this);
        
        var rewardId = chooser.checkboxLogicIndex($this), 
            radioId = chooser.radioLogicIndex(), 
            radioResponseIndex = chooser.radioResponseIndex();

       // Merge the cards into the list
       cardList.insert(chooser.cardLogic[rewardId][radioId][radioResponseIndex]);            
    }
    
    // Add cards to show based on any checked checkboxes
    if ( this.rewardsChecked() ){
        this.rewardsInputs
            
            .filter(":checked")
            
            .each(function(){
                var $this = $(this);
                
                var rewardId = chooser.checkboxLogicIndex($this), 
                    radioId = chooser.radioLogicIndex(), 
                    radioResponseIndex = chooser.radioResponseIndex();

                // Merge the cards into the list
                cardList.insert(chooser.cardLogic[rewardId][radioId][radioResponseIndex]);
            });             
    }
	
	// Based cards shown only on radio buttons
    else {
        var rewardId = chooser.checkboxLogicIndex();

        if ( this.businessChecked() && this.studentChecked()){
			var radioId = chooser.radioLogicIndex(),
			    radioResponseIndex = chooser.radioResponseIndex();
	
			cardList.insert(chooser.cardLogic[rewardId][this.radioLogicIndex()][radioResponseIndex]);
		}
		else {
	        if ( this.businessChecked() ) {
	            var radioResponseIndex = chooser.radioResponseIndex();

	            cardList.insert(chooser.cardLogic[rewardId][0][radioResponseIndex]);
	        } 
	        if ( this.studentChecked() ){
	         
	            var radioResponseIndex = chooser.radioResponseIndex();

	            cardList.insert(chooser.cardLogic[rewardId][1][radioResponseIndex]);
	        }
		}

    }    

    return cardList;
};

DFS.Chooser.choose = function() {
	var chooser = this;

	this.cardsToShow = this.getCardsToShow();

	this.showCards();
};
    
$(document).ready(function() {

	$("#clicks").hide();
	$("#clicks").attr("value", 0);
	
	
	DFS.Chooser.init();
	
	$('input').click(function()
	{
	   DFS.Chooser.choose();
	});
});