/**
 * productMatcher overrides specific for operating the product match form on the "Find a Card" page
 */
 
productMatcher.config.firstClick			= '#cust-started';
productMatcher.config.nextClick			= '#cust-next';
productMatcher.config.previousClick	= '#cust-previous';
productMatcher.config.previousClickFinished 	= '#cust-previous-finished';
productMatcher.config.skipClick			= '#cust-skip';
productMatcher.config.progressIncrement = 9.10;
 
 
productMatcher.oldFormSetup = productMatcher.formSetup;
productMatcher.formSetup = function(form){
	this.config.startingLinkIdSubArea = LinkId.getUniqueSubareaForArea('C1');
	this.setupiFixPNG();
	this.oldFormSetup(form);
}
 
productMatcher.completeForm = function(){
	$('.check').show();
	$('.wizard .main').css('height','70px');
	$('#question-spot').hide();
	$('#complete').show();
	$('#form-control-buttons').hide();
	
	this.progress = 100;
	this.updateProgress(this.progress);

	// if the form has a suggested cards section,
	// replace the "recommended cards" text with the completion text.
	if(this.hasSuggestedCards){
		var e = $(this.config.recommendedMessageSel).get(0);
		e.oldHtml = $(e).html();
		$(e).html($(this.config.completeRecommendedSel).html());
	}
	
	if(this.config.terminalPageCodes.end) this.pageCode = this.config.terminalPageCodes.end;
	if(this.config.terminalCg4Values.end) this.cg4 = this.config.terminalCg4Values.end;
	if(this.config.terminalLpChatPageNames.end) this.lpChatPageName = this.config.terminalLpChatPageNames.end;
}

productMatcher.setupiFixPNG = function(){
	if (navigator.appVersion.indexOf('MSIE 6.0') != -1) {
		$('.form-control-buttons').css('overflow','hidden').show();
		$(this.config.nextClick + ' img').ifixpng();
		$(this.config.skipClick).show()
		$(this.config.skipClick + ' img').ifixpng();
		$(this.config.skipClick).hide();
		$('.form-control-buttons').hide();
	}
}

productMatcher.setupClicks = function() {
        // if the restore state put us on an input other than the first,
        // then attache the next click function instead of the first click
        if( this.form.processor.currentInput != this.form.inputsArray[0].name ) {
            this.showRecommendations();
        } else {
            this.pageCode = this.config.terminalPageCodes.start;
            this.cg4 = this.config.terminalCg4Values.start;
            this.lpChatPageName = this.config.terminalLpChatPageNames.start;
        }
		// So, basically, a tracker is assigned to this function (see product-match.js, decorateForTracking). There is also
		// a tracker assigned to cardsCallback. When the user returns from the unknown to this page
		// we don't want to track twice. So, we'll just not attachFirstClick, since the user won't ever see that page anyways.
		if(this.progress == productMatcher.config.progressIncrement)
			this.attachFirstClick();
		this.attachNextClick();
		this.attachPreviousClick();
		this.attachSkipClick();
}

/**
 * Attatch click functions.
 */
productMatcher.attachFirstClick = function(){
    var here = this;
    this.firstClickFunc = function(){here.firstClick()};
    $(this.config.firstClick + ' a').bind('click',this.firstClickFunc);
}

productMatcher.attachNextClick = function() {
        var here = this;
        this.form.processor.processCallback = ['productMatcher','processCallback'];
        this.nextClickFunc = function(){ here.nextClick(); }
        $(this.config.nextClick + ' a').click(here.nextClickFunc);
}

productMatcher.attachPreviousClick = function() {
	var here = this;
	this.previousClickFunc = function(){ here.previousClick(); }
	$(this.config.previousClick + ' a').click(here.previousClickFunc);
	$(this.config.previousClickFinished + ' a').click(here.previousClickFunc);
}

productMatcher.attachSkipClick = function() {
	var here = this;
	this.skipClickFunc = function(){ here.skipClick(); }
	$(this.config.skipClick + ' a').click(here.skipClickFunc);
}


/**
 * Actual click functions.
 */
productMatcher.firstClick = function() {

    this.showRecommendations();
	var inp = this.form.inputsArray[0];
	if(typeof inp.config.canSkipTo != 'undefined')$(this.config.skipClick).show();
	else $(this.config.skipClick).hide();
	$('#form-control-buttons').show();
    this.swapOut( inp.domElement );
}

productMatcher.nextClick = function() {
	if(!this.trackingLock){
		var proc = this.form.processor;
		var inp = this.form.inputs[proc.currentInput];
		this.clearFitOverrides();
		this.passback = null;
		if(inp.domElement.getActualValue() == '' && typeof inp.config.canSkipTo != 'undefined'){
			WebTracker.send({eventName:inp.name + ':Next'},'click','button');
			this.skipAction();
		}
		else {
			if(!proc.process()){
				if(typeof inp.notValidValue != 'undefined')inp.notValidValue();
			}
			else {
				WebTracker.send({eventName:inp.name + ':' + inp.domElement.getValue(),userInput:inp.domElement.getActualValue()},'click','button');
			}
		}
	}
}

productMatcher.previousClick = function() {
	if(!this.trackingLock){
		var oldInput = this.form.processor.currentInput == 'result' ? 'result' : this.form.inputs[this.form.processor.currentInput];
		if (this.form.processor.goBack()){
			if(oldInput != 'result'){
				var defaultValue = oldInput.config['javascript']['defaultValue'];
				var value = (typeof(defaultValue) != "undefined" ? defaultValue : '' );
				oldInput.domElement.setActualValue(value);
				WebTracker.send({eventName:"previousClick - From:" + oldInput.name + ", To: " + this.form.processor.currentInput},'click','button');
			}
			else WebTracker.send({eventName:"previousClick - From:" + oldInput + ", To: " + this.form.processor.currentInput},'click','button');
		}
	}
}

productMatcher.skipClick = function(){
	if(!this.trackingLock){
		WebTracker.send({eventName:this.form.processor.currentInput + ':No Thanks'},'click','button');
		this.skipAction();
	}
}

/* Standard Functions */


productMatcher.skipAction = function(){
	var proc = this.form.processor;
	var canSkipTo = this.form.inputs[proc.currentInput].config.canSkipTo;
	if(typeof canSkipTo != 'undefined'){
		this.form.inputs[proc.currentInput].domElement.setActualValue('');
		proc.deadProcess(canSkipTo);
	}
}

var RecommendedCardCollection = [];

var RecommendedCard = function (sections, cardName) {
    this.card_box = $(sections.get(0));
    this.apr_box = $(sections.get(1));
    this.annual_fee_box = $(sections.get(2));
    this.rewards = $(sections.get(3));
    this.apr_links = $(sections.get(4));
    this.card_box.attr('card-name', cardName);
    this.card_image = $('.card-image img', this.card_box);
    this.anch = $('.more-details-link', this.card_box);
    this.description = $('.description .more-details-link', this.card_box);
    this.description_extended = $('.description-ext', this.card_box);
    this.authorize_user = $('.authUser', this.apr_box);
}
RecommendedCard.prototype = {
    setCardImage: function (url, altText, link) {
        this.card_image.attr('src', url);
        this.card_image.attr('alt', altText);
        this.card_image.get(0).style.cursor = 'pointer';
        
        $(this.card_image.parent()).attr('href', LinkId.replace(link,'type','G'));
    },
    setMoreDetailsLink: function (text, link) {
        this.anch.attr('title', text);
        $(this.anch[0]).attr('href', LinkId.replace(link,'type','G'))
        $(this.anch[1]).attr('href', LinkId.replace(link,'type','T'))
        this.anch.css('cursor', 'pointer');
    },
    setCardTitle: function (title, additional_title) {
        this.description.html(title);
        this.description_extended.html(additional_title);
    },
    showAPR: function () {
        this.apr_box.show();
        this.apr_links.show();
        if ($('.apr-rewards', this.rewards).html()) this.rewards.show();
        this.annual_fee_box.show();
        if ($('#disclaimers').html()) {
            $('#disclaimers').show();
        }
    }
}

/* Card Callback Functions */

productMatcher.suggestedCardsCallback = function(response){
    
	if( response.match(/SUCCESS/) )
	{
		// var 'result' is defined in the response
		eval(response);
		
		// clear out the old suggested cards
		this.clearCardSpots();
		
		var startingLinkIdSubArea = this.config.startingLinkIdSubArea;
		
		// if card char codes are returned,
		// then put them in cg5 for the next track() call
		if( !this.cg5 && result.cardCharCodes )
            this.cg5 = 'LKP1-'+result.cardCharCodes;
		
        var cardCol = new Array();
		var cardNumber = 1;
        var cardSpot;
        
        var fn = $('#disclaimers');
        if (result.disclaimers) {
            fn.html(result.disclaimers);
        } else {
            fn.html('');
        }
        
        
		for( var i in result.cards )
		{
			var current = result.cards[i];
			var detailsText = 'Click for details on the '+current.altAndTitle;
			
			cardSpot = new RecommendedCard($('.card'+cardNumber), i);
            cardSpot.setCardImage(current.thumbnail, detailsText, current.details);
            cardSpot.setMoreDetailsLink(detailsText, current.details);
            cardSpot.setCardTitle(current.name, current.nameExt);
            cardCol.push(cardSpot);

			$('.more-details-link', cardSpot.apr_links).each(
				function(){
					$(this).attr('href',current.details);
				}
			);		
			
			$('.apply-link', cardSpot.apr_links).attr('title','Apply Now').attr('href',current.application).attr('rel',current.applicationRel);
			
			var linksCardSpot = [];
			$('a',cardSpot).each(function(){
				linksCardSpot.push(this);
			});
			
			linksCardSpot.reverse();
			$(linksCardSpot).each(function(){
				$(this).attr('href',LinkId.replace($(this).attr('href'),'subarea',startingLinkIdSubArea++));
			});
			
			if(current.authUser != null){
				cardSpot.authorize_user.show();
				$('.apr-authfee', cardSpot.authorize_user).html(current.authUser);
			}
			else {
				cardSpot.authorize_user.hide();
				$('.apr-authfee', cardSpot.authorize_user).html('');
			}
			
			if(current.rewards){
				$('.apr-rewards', cardSpot.rewards).html(current.rewards);
			}
			else {
				cardSpot.rewards.hide();
				$('.apr-rewards', cardSpot.rewards).html('');
			}
			cardSpot.annual_fee_box.hide();
			$('.apr-purchases',cardSpot.apr_box).html(current.purchaseAPR);
			$('.apr-balancetransfer',cardSpot.apr_box).html(current.transferAPR);
			$('.apr-cashadvance',cardSpot.apr_box).html(current.cashAdvanceAPR);
			$('.apr-annualfee',cardSpot.annual_fee_box).html(current.annualFee);
			
			
			cardNumber ++;
		}
		
		// if there were no cards returned, 
		// then disable the compare cards link
		if( cardNumber == 1 ) {
			this.setSuggestedTitle( this.config.suggestedTitleInitialSel );                
			this.compareCardsEnabled(false);
		} else {
			this.setSuggestedTitle( this.config.suggestedTitleInterimSel );
			this.compareCardsEnabled(true);
		}
		
		if(this.progress == 100){
			for (var col_item in cardCol) cardCol[col_item].showAPR();
		}
		
		centerCardMessageHeight();
		setupApplicationLinks();
		applyTooltips();
		return result;
	}
}


productMatcher.clearCardSpots = function(){
	if( $(this.config.suggestedCardsSel).length == 0 )
		return;
	// now clear out spots we didn't update this call
	for( var i=1; i<=4; i++ )
		this.clearCardSpot(i);
		
	centerCardMessageHeight();
}

productMatcher.clearCardSpot = function(i){
        var cardSpot = new RecommendedCard($('.card'+i));
        
        var img = cardSpot.card_image;
        img.attr('src','/img/ca/cardfinder/module-card-shell.png');
        img.attr('alt','Blank spot');
        img.get(0).style.cursor='default';
        var anch = cardSpot.anch;
        anch.attr('title', '');
        $(anch[0]).attr('href', 'javascript:void(0);');
        $(anch[1]).attr('href', 'javascript:void(0);');
        cardSpot.description.html('');
		cardSpot.description_extended.html('').hide();
        anch.css('cursor','default');
		cardSpot.apr_box.hide();
        cardSpot.apr_links.hide();
        cardSpot.annual_fee_box.hide();
        cardSpot.rewards.hide();
        
        $('#disclaimers').hide();
}

productMatcher.clearCardSpots();

function centerCardMessageHeight(){
	var cardMessageHeight = $('#recommendedMessage').height();
	var cardsHeight = $('.cards').height();
	var newCardsHeight = (cardsHeight / 2) - (cardMessageHeight / 2) + 'px';
	$('#recommendedMessage').css('margin-top',newCardsHeight);
}

/**
 * Other functions.
 */
productMatcher.showRecommendations = function() {
    $('.recommendations').show();
} 

productMatcher.reset = function(){
	this.form.reset();
	this.form.resetState();
	
	this.passback = null;
	this.cg5 = '';
	this.lpChatPageName = null;
	
	var inp = this.form.inputsArray[0];
	if(this.progress == 100){
		$('.wizard .main').css('height','300px');
		$('#form-control-buttons').show();
		$('#question-spot').show();
		$('#complete').hide();
		$('.aprBox').hide();
		$('.description-ext').hide();
		$('.check').hide();
	}
	this.swapOut( inp.domElement );
	
	$(this.config.nextClick).show();
	if(typeof inp.config.canSkipTo != 'undefined')$(this.config.skipClick).show();
	else $(this.config.skipClick).hide();
	
	this.updateProgress(productMatcher.config.progressIncrement);
	
	if( this.hasSuggestedCards ) {
		var e = $(this.config.recommendedMessageSel).get(0);
		if( e.oldHtml )
			$(e).html(e.oldHtml);
		this.setSuggestedTitle( this.config.suggestedTitleInitialSel );
	}
	
	this.clearFitOverrides();
	
	this.clearCardSpots();
	
	this.compareCardsEnabled(false);
	this.resetShow(false);
}

productMatcher.resetShow = function(on) {
	if(on == true){
		$(this.config.resetSel).show();
		$(this.config.previousClick).show();
	}
	else {
		$(this.config.resetSel).hide();
		$(this.config.previousClick).hide();
		
	}
}

productMatcher.restoreState = function() {

	this.passback = this.form.restoreState();
	if( this.passback && this.passback.type && this.passback.type.length>0 )
	{
		if( this.passback.type == 'result' ) {
			this.progress = 100;
			this.resetShow(true);
			this.completeForm();
			
			//compare cards click - blue button on final screen
			var here = this;
			$(this.config.compareLink).click(function(){here.compareSuggestedCards();});
		}
		else{
			this.swapOut( this.form.inputs[this.form.processor.currentInput].domElement );
			this.resetShow(true);
			$('#form-control-buttons').show();
			this.progress = this.form.processor.previousLogic.length * this.config.progressIncrement;
			if(typeof this.form.inputs[this.form.processor.currentInput].config.canSkipTo != 'undefined')$(this.config.skipClick).show();
		}
		this.getSuggestedCards();
	} else {
		this.setSuggestedTitle( this.config.suggestedTitleInitialSel );
		this.resetShow(false);
		this.passback = null;
		this.progress = productMatcher.config.progressIncrement;
	}
	this.updateProgress(this.progress);
}

productMatcher.setLiveChatClickAction = function() {
    setClickAction('Finder_StartOver');
}

/* Regular Process Callbacks */

productMatcher.processCallback = function(processor, input, value, passback) {
	if(!passback)return;
	if(!this.skipTracking)this.trackingLock = true;
	this.passback = passback;
	var formInput = this.form.inputs[this.passback.value];
	// store the form state each question answered
	this.storeState();
	
	// if the passback goes to another question
	// then advance the progress bar
	// and swap out the current question with the question indicated
	// by the passback object
	if( this.passback.type != 'result' ) {
	this.lpChatPageName = null;
		this.swapOut( formInput.domElement );
		this.progress = this.progress + this.config.progressIncrement;
		if(typeof formInput.config.canSkipTo != 'undefined')$(this.config.skipClick).show();
		else $(this.config.skipClick).hide();
	} else {
		this.completeForm();
		//compare cards click - blue button on final screen
		var here = this;
		$(this.config.compareLink).click(function(){here.compareSuggestedCards();});
	}

	// get the suggested cards
	this.getSuggestedCards();  
	
	this.updateProgress(this.progress);
	this.resetShow(true);
}

productMatcher.previousCallback = function(processor, input, value, passback) {
	if(!this.skipTracking)this.trackingLock = true;
	this.passback = passback;
	this.storeState();
	this.clearFitOverrides();
	
	var formInput = this.form.inputs[input];
	
	if(this.progress == 100){
		$('.wizard .main').css('height','300px');
		$('#form-control-buttons').show();
		$('#question-spot').show();
		$('#complete').hide();
		$('.aprBox').hide();
		$('.check').hide();
		
		centerCardMessageHeight();
		if( this.hasSuggestedCards ) {
			var e = $(this.config.recommendedMessageSel).get(0);
			if( e.oldHtml )
				$(e).html(e.oldHtml);
			this.setSuggestedTitle( this.config.suggestedTitleInitialSel );
		}
		this.compareCardsEnabled(false);
	}

	this.progress = this.config.progressIncrement * processor.previousLogic.length;
	this.updateProgress(this.progress);
	
	if(typeof formInput.config.canSkipTo != 'undefined')$(this.config.skipClick).show();
	else $(this.config.skipClick).hide();
	$(this.config.nextClick).show();
	if(processor.previousLogic.length == 1){
		this.resetShow(false);
		this.trackingLock = false;
	}
	
	this.swapOut(formInput.domElement);
	
	this.getSuggestedCards(); 
}
