// Description: Card selector javascript support file
// Author: RxM
// Date: 24/09/2008

$(document).ready(function() {

    // Depending on the browser, let's decide whether to show the JS selection panel or not
    // Anything below firefox 2 and IE6 will be shown the standard HTML selection panel.
    
    var enableJS = true;
    
    if ( jQuery.browser.mozilla && (jQuery.browser.version.substring(0, 5) == "1.8.0" || jQuery.browser.version.substring(0, 3) < 1.8) )
        enableJS = false;
        
    if ( jQuery.browser.msie && jQuery.browser.version < 6 )
        enableJS = false;

    if ( $.query.get("accessible") )
        enableJS = false;
        
    // Execute all the JS enhanced features only if the browser is a fairly modern one. Older browsers
    // will fall back to the standard HTML version.
    if ( enableJS )
    {

        function onSlide(e, ui)
    	{
    		clearTimeout(timerId);
    		timerId = setTimeout(updateDisplay, 100);
    	}

        $(".javascriptControls").css("display", "block");
        $(".nonJavascriptControls").css("display", "none");

    	///////////////////////////////////////////////////////////////////////////////////////////////
    	// Initialisation
    	///////////////////////////////////////////////////////////////////////////////////////////////
    	
    	$("#creditRatingSlider").slider({
    		min : 0,
    		max : 2,
    		startValue: $("#inpCreditRating").val(),
    		stepping: 1,
    		slide: onSlide
    	});


    	///////////////////////////////////////////////////////////////////////////////////////////////
    	// Form Event Handlers
    	///////////////////////////////////////////////////////////////////////////////////////////////
    	
    	
    	
    	function usePurchaseButtonHandler(event){
            event.preventDefault();
    		$("#inpUsePurchase").attr("checked", "checked");
    		$("#usePurchaseButton").attr("class", "radioButtonOn");
    		$("#useBalanceTransferButton").attr("class", "radioButtonOff");
			$("#useRewardedButton").attr("class", "radioButtonOff")
    		$("#useBothButton").attr("class", "radioButtonOff");
    		updateDisplay();		
    	}

    	
    	
    	function useBalanceTransferButton(event){
            event.preventDefault();
    		$("#inpUseBalanceTransfer").attr("checked", "checked");
    		$("#usePurchaseButton").attr("class", "radioButtonOff");
			$("#useRewardedButton").attr("class", "radioButtonOff")
    		$("#useBalanceTransferButton").attr("class", "radioButtonOn");
    		$("#useBothButton").attr("class", "radioButtonOff");
    		updateDisplay();		
    	}
    	
    	function useBothButtonHandler(event){
            event.preventDefault();
    		$("#inpUseBoth").attr("checked", "checked");
    		$("#usePurchaseButton").attr("class", "radioButtonOff");
    		$("#useBalanceTransferButton").attr("class", "radioButtonOff");
			$("#useRewardedButton").attr("class", "radioButtonOff")
    		$("#useBothButton").attr("class", "radioButtonOn");
    		updateDisplay();		
    	}
    	
		function useRewardedButtonHandler(event){
			event.preventDefault();
    		$("#inpUseRewarded").attr("checked", "checked");
    		$("#usePurchaseButton").attr("class", "radioButtonOff");
    		$("#useBalanceTransferButton").attr("class", "radioButtonOff");
    		$("#useBothButton").attr("class", " radioButtonOff ");
			$("#useRewardedButton").attr("class", "radioButtonOn");
    		updateDisplay();		
    	}

    	// This one is a special case - we need to disable all the benefits below
    	// when this is enabled...

    	
    	function studentButtonHandler(event){
            event.preventDefault();
    		if ($("input[@name=inpStudent]:checked").val() == 1)
    		{
    			$("#inpStudentNo").attr("checked", "checked");
    			$("#studentButton").attr("class", "toggleButtonOff");
    			$('#filterBoxTitle').css('opacity', 1);
    			$("#footballButton").attr("class", ($("input[@name=inpFootball]:checked").val() == 1) ? "toggleButtonOn" : "toggleButtonOff");
    			$("#rewardsButton").attr("class", ($("input[@name=inpRewards]:checked").val() == 1) ? "toggleButtonOn" : "toggleButtonOff");
    			$("#travelButton").attr("class", ($("input[@name=inpTravel]:checked").val() == 1) ? "toggleButtonOn" : "toggleButtonOff");
    			$("#charityButton").attr("class", ($("input[@name=inpCharity]:checked").val() == 1) ? "toggleButtonOn" : "toggleButtonOff");
    			$("#contactlessButton").attr("class", ($("input[@name=inpContactless]:checked").val() == 1) ? "toggleButtonOn" : "toggleButtonOff");
    			$("#environmentButton").attr("class", ($("input[@name=inpEnvironment]:checked").val() == 1) ? "toggleButtonOn" : "toggleButtonOff");
    		}
    		else
    		{
    			$("#inpStudentYes").attr("checked", "checked");
    			$("#studentButton").attr("class", "toggleButtonOn");
    			$('#filterBoxTitle').css('opacity', 0.5);
    			$("#footballButton").attr("class", ($("input[@name=inpFootball]:checked").val() == 1) ? "toggleButtonDisabledOn" : "toggleButtonDisabledOff");
    			$("#rewardsButton").attr("class", ($("input[@name=inpRewards]:checked").val() == 1) ? "toggleButtonDisabledOn" : "toggleButtonDisabledOff");
    			$("#travelButton").attr("class", ($("input[@name=inpTravel]:checked").val() == 1) ? "toggleButtonDisabledOn" : "toggleButtonDisabledOff");
    			$("#charityButton").attr("class", ($("input[@name=inpCharity]:checked").val() == 1) ? "toggleButtonDisabledOn" : "toggleButtonDisabledOff");
    			$("#contactlessButton").attr("class", ($("input[@name=inpContactless]:checked").val() == 1) ? "toggleButtonDisabledOn" : "toggleButtonDisabledOff");
    			$("#environmentButton").attr("class", ($("input[@name=inpEnvironment]:checked").val() == 1) ? "toggleButtonDisabledOn" : "toggleButtonDisabledOff");
    		}
    		updateDisplay();		
    	}
    	
    	// Switch the football button - but only if student/graduate option is not selected
    	
    	function footballButtonHandler(event){
            event.preventDefault();
    	    if ($("input[@name=inpStudent]:checked").val() == 0)
    	    {
    		    if ($("input[@name=inpFootball]:checked").val() == 1)
    		    {
    			    $("#inpFootballNo").attr("checked", "checked");
    			    $("#footballButton").attr("class", "toggleButtonOff");
    		    }
    		    else
    		    {
    			    $("#inpFootballYes").attr("checked", "checked");
    			    $("#footballButton").attr("class", "toggleButtonOn");
    		    }
    		    updateDisplay();
    		}		
    	}

    	// Switch the rewards button - but only if student/graduate option is not selected

    	function rewardsButtonHandler(event){
            event.preventDefault();
    	    if ($("input[@name=inpStudent]:checked").val() == 0)
    	    {
    		    if ($("input[@name=inpRewards]:checked").val() == 1)
    		    {
    			    $("#inpRewardsNo").attr("checked", "checked");
    			    $("#rewardsButton").attr("class", "toggleButtonOff");
    		    }
    		    else
    		    {
    			    $("#inpRewardsYes").attr("checked", "checked");
    			    $("#rewardsButton").attr("class", "toggleButtonOn");
    		    }
    		    updateDisplay();
    		}		
    	}

    	// Switch the travel button - but only if student/graduate option is not selected

    	
    	function travelButtonHandler(event){
            event.preventDefault();
    	    if ($("input[@name=inpStudent]:checked").val() == 0)
    	    {
    		    if ($("input[@name=inpTravel]:checked").val() == 1)
    		    {
    			    $("#inpTravelNo").attr("checked", "checked");
    			    $("#travelButton").attr("class", "toggleButtonOff");
    		    }
    		    else
    		    {
    			    $("#inpTravelYes").attr("checked", "checked");
    			    $("#travelButton").attr("class", "toggleButtonOn");
    		    }
    		    updateDisplay();
            }		
    	}

    	// Switch the charity button - but only if student/graduate option is not selected

    	
    	function charityButtonHandler(event){
            event.preventDefault();
    	    if ($("input[@name=inpStudent]:checked").val() == 0)
    	    {
    		    if ($("input[@name=inpCharity]:checked").val() == 1)
    		    {
    			    $("#inpCharityNo").attr("checked", "checked");
    			    $("#charityButton").attr("class", "toggleButtonOff");
    		    }
    		    else
    		    {
    			    $("#inpCharityYes").attr("checked", "checked");
    			    $("#charityButton").attr("class", "toggleButtonOn");
    		    }
    		    updateDisplay();
            }		
    	}

    	// Switch the contactless button - but only if student/graduate option is not selected

    	
    	function contactlessButtonHandler(event){
            event.preventDefault();
    	    if ($("input[@name=inpStudent]:checked").val() == 0)
    	    {
    		    if ($("input[@name=inpContactless]:checked").val() == 1)
    		    {
    			    $("#inpContactlessNo").attr("checked", "checked");
    			    $("#contactlessButton").attr("class", "toggleButtonOff");
    		    }
    		    else
    		    {
    			    $("#inpContactlessYes").attr("checked", "checked");
    			    $("#contactlessButton").attr("class", "toggleButtonOn");
    		    }
    		    updateDisplay();
            }		
    	}

    	// Switch the environment button - but only if student/graduate option is not selected
    	
    	function environmentButtonHandler(event){
            event.preventDefault();
    	    if ($("input[@name=inpStudent]:checked").val() == 0)
    	    {
    		    if ($("input[@name=inpEnvironment]:checked").val() == 1)
    		    {
    			    $("#inpEnvironmentNo").attr("checked", "checked");
    			    $("#environmentButton").attr("class", "toggleButtonOff");
    		    }
    		    else
    		    {
    			    $("#inpEnvironmentYes").attr("checked", "checked");
    			    $("#environmentButton").attr("class", "toggleButtonOn");
    		    }
    		    updateDisplay();
            }		
    	}

        // Handler to flip the card view div to the info view
        $(".cardInfoButton").click(function(event) {
            event.preventDefault();
            var id = event.target.id.replace('cardInfoButton', '');
            
            if ($(this).attr("class") == "cardInfoButton")
            {
                $(this).attr("class", "cardSummaryButton");
                $('#cardIntro'+id).css("display", "none");
                $('#cardContent'+id).css("display", "block");
            }
            else
            {
                $(this).attr("class", "cardInfoButton");
                $('#cardIntro'+id).css("display", "block");
                $('#cardContent'+id).css("display", "none");
            }
        });

    	$('.cardContent').css('display', 'none');

        // Handler to flip the card view div to the summary view
        $(".cardSummaryButton").click(function() {
            var id = $(this).attr("id").replace("cardSummaryButton", "");
            $("#cardSummaryView"+id).css("display", "block");
            $("#cardInfoView"+id).css("display", "none");
        });

    	$('.showAllCards').click(function(event){
    		event.preventDefault();

    		$('.showAllCards').toggleClass('lnkClicked');
            
            if ($(this).hasClass('lnkClicked'))
            {
                $('.showAllCards').children('img').attr('src', '/images/btn_amend_card_choice.gif');
                $('.showAllCards').children('img').attr('title', 'Amend card choice');
                $('.showAllCards').children('img').attr('alt', 'Amend card choice');
                $("div[@class~=filtersBoxBlock]").css('opacity', 0.55);
            }
            else
            {
                $('.showAllCards').children('img').attr('src', '/images/btnViewAllCards.jpg');
                $('.showAllCards').children('img').attr('title', 'View all cards');
				$('.showAllCards').children('img').attr('alt', 'View all cards');
            }
            
            if ($(this).hasClass('lnkClicked'))
            {
                $("div[@class~=filtersBoxBlock]").css('opacity', 0.55);
            }
            else
            {
                $("div[@class~=filtersBoxBlock]").css('opacity', 1);
            }
            
    		//$("div[@class~=filtersBoxBlock]").css('opacity',($(this).hasClass('lnkClicked')) ? 0.55 : 1);

    		if ($(this).hasClass('lnkClicked')) {
    			
    			$('#init').css('display','none');
    			$('#noCards').css('display','none');
    			
    			var queryString = {showAll:true};
    			
    			$.getJSON("services/validcards.php", queryString, function(data){
    				for (var i = 0; i < $("#totalCards").val(); i++) {
    					$("#card" + i).fadeIn(400, fadeComplete);
    				}
    				// Update the cards selected text					
    				$(".cardsSelectedNumber").text(data.length);
    				$(".cardsSelectedText").text((data.length == 1 ? "card matches your selection" : "cards match your selection"));
    			});
    			deInitForm();
    			
    			$('.cardIntro').css('display', 'block');
    			$('.cardContent').css('display', 'none');
    		} else {
    			updateDisplay();
    			initForm();
    			
    			$('.cardIntro').css('display', 'block');
    			$('.cardContent').css('display', 'none');
    			$(".cardInfoButton").css('background-image', 'url(/images/btnInfo.jpg)');
    		}
    	});

    	/* Tooltip handler */
    	function tooltipHandler(event){
    		var intId = event.target.id.replace('interest_', '');
    		jQuery.each($('.toolTipBox'), function(value, element) {
    			$(element).css('display', (event.type == 'mouseover' && value == intId) ? 'block' : 'none');
				if (event && window.event) {
					window.n_mouseY=event.clientY+document.body.scrollLeft+document.documentElement.scrollTop;
					window.n_mouseX=event.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;
				} else {
					window.n_mouseY=event.pageY;
					window.n_mouseX=event.pageX;
				} 
				$('#tooltips').css('top',(window.n_mouseY-($(element).height())-25)+"px"); 
				$('#tooltips').css('left',(window.n_mouseX-70)+"px"); 
    		});	
    	}
    	
    	// form (de)initialization function
    	function initForm(){
    		if($("#creditRatingSlider").slider) $("#creditRatingSlider").slider("enable");
            $(".ui-slider").css('opacity', 1);
    		$("#usePurchaseButton").click(usePurchaseButtonHandler);
    		$("#useBalanceTransferButton").click(useBalanceTransferButton);
    		$("#useBothButton").click(useBothButtonHandler);	
    		$("#useRewardedButton").click(useRewardedButtonHandler); // added				
    		$('.tooltip').mouseover(tooltipHandler);
    		$('.tooltip').mouseout(tooltipHandler);	
			$('.cardSummaryButton').attr("class","cardInfoButton");
    	}
    	function deInitForm(){
    		if($("#creditRatingSlider").slider) $("#creditRatingSlider").slider("disable");
            $(".ui-slider").css('opacity', 0.55);
    		$("#usePurchaseButton").unbind('click');
    		$("#useBalanceTransferButton").unbind('click');
    		$("#useBothButton").unbind('click');
			$("#useRewardedButton").unbind('click'); // added
    		/*$('.tooltip').unbind('mouseover');
    		$('.tooltip').unbind('mouseout');*/
			$('.cardSummaryButton').attr("class","cardInfoButton");
    	}
    	/* initialize form */
    	initForm();

    	///////////////////////////////////////////////////////////////////////////////////////////////
    	// Functions
    	///////////////////////////////////////////////////////////////////////////////////////////////
    	
    	// A simple function that returns true if an array contains a particular value
    	function arrayContains(ar, val)
    	{
    		for (var i=0; i<ar.length; i++)
    		{
    			if (ar[i] == val)
    				return true;
    		}
    		return false;
    	}

    	var timerId = 0;

    	// A function that buffers the slider by 100milliseconds to prevent hammering the server with
    	// multiple AJAX requests when sliding


    	var fading = new Array();
    	
    	// Fades cards in/out depending on whether they match the selection criteria
    	function updateDisplay()
    	{
    		// Grab the slider value
    		var sliderValue = $("#creditRatingSlider").slider("value");
    		
    		// Set the drop down box (which is hidden by CSS) to the value of the slider
    		$("#inpCreditRating").attr("value", sliderValue);
    		
    		var queryString = {creditRating: sliderValue,
    							use: $("input[@name=inpUse]:checked").val()};
    							
            // Query the web service to find the cards that match the criteria and then fade in cards that 
            // match the criteria, and fade out cards that don't. Also update the card selection text
    		$.getJSON("services/validcards.php", queryString, function(data) {
    			for (var i = 0; i < $("#totalCards").val(); i++)
    			{
    				if (arrayContains(data, i))
    					$("#card"+i).fadeIn(400, fadeComplete);
    					
    				else
    					$("#card"+i).fadeOut(400, fadeComplete);
    			}
                
                // Update the cards selected text
                $(".cardsSelectedNumber").text(data.length);
    			
                $(".cardsSelectedText").text( (data.length == 1 ? "card matches your selection" : "cards match your selection") );
    			$('#noCards').css('display', (data.length == 0) ? 'block' : 'none');
    		});
    		$('#init').css('display','none');		
        }
    	

    	// This is required to fix the cleartype glitch in IE7 (where faded/animated text elements lose their cleartype)
    	function fadeComplete()
    	{
    	    if(jQuery.browser.msie)
        	    this.style.removeAttribute('filter');
    	}

    }
});