/**
 * This script is responsible for comparing credit card products. Functionality includes
 * handling the checkboxes, compare buttons, remove buttons, etc.
 *
 * @requires /scripts/https-common/jquery/jquery.js
 * @version 2.0
 *
 */

// make sure the correct credit level message is displayed    
$.elReady("#creditLevelInfoBar", function() {
    switch (get_userCreditLevel_cookie())
    {
        case CONSTANT_CREDIT_TYPE_EXCELLENT:
            var creditLevelText = CONSTANT_CREDIT_TYPE_EXCELLENT_TEXT;
            break;
        case CONSTANT_CREDIT_TYPE_GOOD:
            var creditLevelText = CONSTANT_CREDIT_TYPE_GOOD_TEXT;
            break;
        case CONSTANT_CREDIT_TYPE_AVERAGE:
            var creditLevelText = CONSTANT_CREDIT_TYPE_AVERAGE_TEXT;
            break;
        case CONSTANT_CREDIT_TYPE_LIMITED:
            var creditLevelText = CONSTANT_CREDIT_TYPE_LIMITED_TEXT;
            break;
        default:
            return;
    }

    // Change the credit level information bar
    $('#creditLevelInfoBarReset').css({display:"none"});
    $('#creditLevelInfoBar').css({display:"block"});
    $('#creditLevelAssignment').html(creditLevelText);
    $('#creditLevelAssignment').removeClass().addClass('creditLevel_' + get_userCreditLevel_cookie());
});
// Compare Cards Init
var timerCount = 0;

//inital flag set to see if we're using xplusone
var runXP1Flag = true;
if (typeof xp_exp == 'undefined' || !window.xpEnable)
{ 
	runXP1Flag = false;
}
else if(xp_exp.match(/bau/i))
{
	runXP1Flag = false;
}
runXP1Flag = true;
//For setting the exp variable from quesry string. If set then overwrite the current experience
var xp_set = "";

runXP1Flag = true;
// Modify the xplusone experience(tg.segment.exp) format to Testgroup_experience
if (xp_set != "" && typeof xp_set != 'undefined' && typeof window.xp1ExpSet != 'undefined')
{	
	runXP1Flag = true;	
}
//alert(runXP1Flag);
var Compare_Cards_Init = function()
{
    // Enable the compare functionality since Javascript is enabled

    var Remove_Card = function(card)
    {
        var removeIndex = $(card).attr('class').substring($(card).attr('class').length - 1);
        var pValue = $('.ui-content-' + removeIndex + ' input').attr('id');
        
        _removeProductFromCardCookie(pValue);
        $('.ui-content-' + removeIndex).remove();

        if ($('.hide:first').size())
        {
            var nextShowElement = $('.hide:first').removeClass('hide');
            var showIndex       = nextShowElement.attr('class').substring(nextShowElement.attr('class').length - 1);
            $('.ui-content-' + showIndex).removeClass('hide').addClass('show');
        }
        if ($('table#productTable tbody tr td').size() == 0)
        {
            $('#productTable').css('display', 'none');
            $('#noSelectionBox').css({display:'block'});
        }

        Update_Remove_Button_Status();
    }
    
    //updates remove button status on detailed comparison page
    var Update_Remove_Button_Status = function()
    {
        if ($('tr#removeCardRow input:checkbox:checked').size() > 0)
        {
            //if one or more checkboxes checked then show button as active
            $('tr#removeCardRow button[type=submit], tr#removeCardRow button[type=submit] img').each(function()
            {
                Toggle_Button_Action_State(this, 'enable');
            });
        }
        else
        {
            //else make button inactive 
            $('tr#removeCardRow button[type=submit], tr#removeCardRow button[type=submit] img').each(function()
            {
                Toggle_Button_Action_State(this, 'disable');
            });
        }
    }
    
    //updates remove button status on detailed comparison page
    $('tr#removeCardRow input:checkbox').click(function()
    {
        Update_Remove_Button_Status();
    });


    $('form#compareForm button[type=submit]').click(function()
    {
        if ($('form#compareForm input:checkbox:checked').size() >= 2)
        {
            if ($.browser.msie)
            {
                /**
                 * Hack for IE browsers! For <button> elements, IE submit the contents
                 * inside of the <button> as its value ignoring the value="" attribute
                 * This corrects the problem, by forcing the value to be the attribute value=""
                 * and then hiding the contents inside the <button> element
                 *
                 * @see http://narayanraman.blogspot.com/2006/12/button-tag-problems-and-ie-6.html
                 */

                this.value = this.attributes.getNamedItem('value').value;
                this.style.display = 'none';
            }

            document.compareForm.submit();
        }
    });

    $('form#compareForm input:checkbox').click(function()
    {
        Compare_Cards_Validation_Check();
    });

    $('#removeCardRow a').click(function()
    {
        Remove_Card(this);
    });

    $('#removeCardRow button').click(function()
    {
        for (var x = 0; x < DETAILED_COMPARISON_MAX_DISPLAY_ITEMS; x++)
        {
            if( $('.ui-content-'+x+' input:checkbox').attr('checked') )
            {
                Remove_Card('.ui-content-'+x);
            }
        }

        return false;
    });

    Compare_Cards_Validation_Check();
    Update_Remove_Button_Status();
    Update_Checked_Boxes();
    $('#productTable tr.compareRow th, #productTable tr.compareRow td.cardListCompare p').css({visibility:'visible'});

};

var Toggle_Button_Action_State = function(target, state)
{
    if (state == 'enable')
    {
        if (target.tagName.toLowerCase() == 'img')
        {
            var buttonName = $(target).attr('id').substring(0, $(target).attr('id').indexOf('Button')).toLowerCase();

            $(target).attr('src', '/images/https-creditcards/web_shopper/interface_elements/buttons/btn_b_' + buttonName + '.png');
        }
        else if (target.tagName.toLowerCase() == 'button')
        {
            $(target).removeAttr('disabled');
        }
    }
    else if (state == 'disable')
    {
        if (target.tagName.toLowerCase() == 'img')
        {
            var buttonName = $(target).attr('id').substring(0, $(target).attr('id').indexOf('Button')).toLowerCase();

            $(target).attr('src', '/images/https-creditcards/web_shopper/interface_elements/buttons/btn_disabled_' + buttonName + '.gif');
        }
        else if (target.tagName.toLowerCase() == 'button')
        {
            $(target).attr('disabled', 'disabled');
        }
    }
};

var Update_Checked_Boxes = function ()
{
    var _cardCookie       = new Card.Cookie();
    var _previousProducts = _cardCookie.getSub('userSelectedProduct');

    _tmpString        = new String(_previousProducts);
    productArray      = _tmpString.split(',');
    
    // uncheck all boxes for compare
    $('tr.compareRow input, td.compareAllApply input').each(function(i) {
            $(this).removeAttr('checked');
    });
    
    // check only the boxes in cookie array
    for (var i=0; i<productArray.length; i++)
    {
        $('tr.compareRow input#'+productArray[i]+', td.compareAllApply input#'+productArray[i]).attr('checked', 'checked');
    }
    
/*
    // uncheck all boxes for compare
    $('tr.compareRow input').each(function(i) {
            $(this).removeAttr('checked');
    });
    
    // uncheck all boxes for compare
    $('td.compareAllApply input').each(function(i) {
            $(this).removeAttr('checked');
    });
    
    // check only the boxes in cookie array
    for (var i=0; i<productArray.length; i++)
    {
        $('tr.compareRow input#'+productArray[i]).attr('checked', 'checked');
    }
    
    // check only the boxes in cookie array
    for (var i=0; i<productArray.length; i++)
    {
        $('td.compareAllApply input#'+productArray[i]).attr('checked', 'checked');
    }
*/
};

var Compare_Cards_Validation_Check = function()
{
    var _cardCookie       = new Card.Cookie();
    var _previousProducts = _cardCookie.getSub('userSelectedProduct');

    _tmpString        = new String(_previousProducts);
    productArray      = _tmpString.split(',');
    
    var Update_Compare_Link_Active = function()
    {
        // makes compare link at the bottom of overview pages an active link to product detail comparison page
        $('td.cardListCompare').each(function (index, domEle) {
            if ($(this).find('label').attr('for')!=undefined)
            {
                $(this).find('label').remove();
                $(this).find('input').after('<a href="javascript:void(0);" onclick="document.compareForm.submit();return false;">Compare</a>');
            }
        });
        
        // makes compare link at the right of compare all page an active link to product detail comparison page
        $('p.compareCheckbox').each(function (index, domEle) {
            if ($(this).find('label').attr('for')!=undefined)
            {
                $(this).find('label').remove();
                $(this).find('input').after('<a href="javascript:void(0);" onclick="document.compareForm.submit();return false;">Compare</a>');
            }
        });
        
        // make cursor a pointer (hand)
        $('form#compareForm button[type=submit]').css('cursor','pointer');
    }

    var Update_Compare_Link_InActive = function()
    {
        // changes compare link at the bottom of overview pages to an inactive text that (un)checks boxes
        $('td.cardListCompare').each(function (index, domEle) {
            pValue = $(this).find('input').attr('id');
            if ($(this).find('a').attr('href')!=undefined)
            {
                $(this).find('a').remove();
                $(this).find('input').after('<label for="'+pValue+'">Compare</label>');
            }
        });
        
        // changes compare link at the right of compare all page to an inactive text that (un)checks boxes
        $('p.compareCheckbox').each(function (index, domEle) {
            pValue = $(this).find('input').attr('id');
            if ($(this).find('a').attr('href')!=undefined)
            {
                $(this).find('a').remove();
                $(this).find('input').after('<label for="'+pValue+'">Compare</label>');
            }
        });
        
        //make cursor an arrow (remove hand)
		$('form#compareForm button[type=submit]').css('cursor','default');
    }

    // Disable the Compare Button if there are not at least 2 cards to compare
    if (productArray.length >= 2)
    {
        $('form#compareForm button[type=submit], form#compareForm button[type=submit] img').each(function()
        {
            Toggle_Button_Action_State(this, 'enable');
        });
        Update_Compare_Link_Active();
    }
    else
    {
        $('form#compareForm button[type=submit], form#compareForm button[type=submit] img').each(function()
        {
            Toggle_Button_Action_State(this, 'disable');
        });
        Update_Compare_Link_InActive();
    }

    // Disable the compare checkboxes once max number checkboxes are checked
    if (productArray.length == DETAILED_COMPARISON_MAX_DISPLAY_ITEMS)
    {
        $('form#compareForm input:checkbox:not(:checked)').attr('disabled', 'disabled');
    }
    else
    {
        $('form#compareForm input:checkbox:not(:checked)').removeAttr('disabled');
    }
};

var Toggle_Detailed_Compare_Sections = function()
{
    $('#productTable tr.controlRow').click(function()
    {
        var stop = false;

        $(this).children('th').toggleClass('close');
        $(this).nextAll('tr').each(function()
        {
            if ($(this).hasClass('controlRow') || $(this).attr('id') == 'removeCardRow')
            {
                stop = true;
            }
            else if (stop != true)
            {
                $(this).toggleClass('contentRowHide');
            }
        })
    });
};

var settimer = function() 
{
	compare_Cards();
}

var compare_Cards = function() 
{
	if (runXP1Flag && timerCount < 50 && document.getElementById("productOverviewTable") != null )
	{
		if (document.getElementById("productOverviewTable").style.visibility == "hidden")
		{
			timerCount++;
			window.setTimeout("settimer()",150);
			return;
		}
		else
		{
			Compare_Cards_Init();
		    // Detail Compare Toggle Titles
		    Toggle_Detailed_Compare_Sections();
		}
	}
	else
	{
		Compare_Cards_Init();
	    // Detail Compare Toggle Titles
	    Toggle_Detailed_Compare_Sections();
	}
}

$(document).ready(function()
{
	compare_Cards();
});