if(typeof(CanadaConfig)=='undefined'){
    var CanadaConfig = {
        selectors:{
            applyLink           : "a.apply-link",
            applyLinkNoDialogue : "a.apply-link[href*='application.capitalone.com']"
        }
    }
}


var tooltipDefaults = {
	local: true,
	sticky: true,
	arrows: true,
	activation: 'click',
	dropShadow: false,
	escapeTitle: true,
	showTitle: false,
	closeText: '',
	width: 339,
	onActivate: function(){
		var cluetip = $('#cluetip');
		$('.cluetip-top-center').width('auto');
		$('.cluetip-middle-center').width('auto');
		$('.cluetip-bottom-center').width('auto');
		
		$('.cluetip-middle-center').height('auto');
		
		// L/R
		$('.cluetip-middle-left').height('auto');
		$('.cluetip-middle-center').height('auto');
		$('.cluetip-middle-right').height('auto');
	},
	onShow: function(ct, c){
		var cluetip = $('#cluetip');
		WebTracker.send($('.tooltipReservedContent',c).attr('track'),'click','display');
				// Center //
		$('.cluetip-top-center').width(cluetip.width() - 18);
		$('.cluetip-middle-center').width(cluetip.width() - 18);
		$('.cluetip-bottom-center').width(cluetip.width() - 18);
		
		$('.cluetip-middle-center').height('auto');
		
		// L/R
		$('.cluetip-middle-left').height($('.cluetip-middle-center').height());
		$('.cluetip-middle-center').height($('.cluetip-middle-center').height());
		$('.cluetip-middle-right').height($('.cluetip-middle-center').height());
	}
};

$(document).ready(
	function(){
		// Setup application links
		setupApplicationLinks();
		// Dialog attachment
		// If the current page is a dialog, and any links open a new window,
		// make sure the dialog closes.
		if($('body').hasClass('dialog')){
			$('a[target*="blank"], a[target*="BLANK"]').click(function(){
				parent.$.fn.colorbox.close();
				return true;
			});
		}
		// Any link with target of dialog will open up in a colorbox.
		$('a[target*="dialog"], a[target*="DIALOG"]').each(
			function(){
				var href = $(this).attr('href');
				$(this).click(function(){
					parent.constructDialog(href);
					return false;
				});
				$(this).attr('href','javascript:void(0);');
			}
		);
		// Catch-all to make sure all external links (using redirect.php) open in a new window
		$("a[href*='redirect.php']").not('[href^="javascript:"]').attr("target","_blank");
    
		// track the online opinion lab clicks
		$('#O_c').click(function(){
			WebTracker.send('OnlineOpinionLab','click','display');
		});
    
		// tracking for list item questions
		$('a.menuitem.question').click(function(){
			if(this.rel && !this.tracked){
				WebTracker.send(this.rel,'click','display');
			}
			this.tracked=true;
		});
		
		applyTooltips();
	}
);

function applyTooltip(element){
	if($(element).data('tooltipApplied'))return;
	// We pull the contents of the tooltip.
	var relElement = $($(element).attr('rel'));
	// We remove the original from the DOM.
	relElement.appendTo($('body'));
	eval('var options = ' + $(element).attr('options'));
	if(typeof options.local == false && typeof options.ajaxProcess != 'undefined'){
		options.ajaxProcess = function(data){
			var tooltip = $('<root>' + data + '</root>');
			var box = $('.tt_box',tooltip);
			if(box.length == 1){
				return box.html();
			}
			else {
				return data;
			}
		}
	}
	var defaults = $.extend({},tooltipDefaults,options);
	$(element).cluetip(defaults);
	$(element).data('tooltipApplied',true);
	$(element).trigger('showCluetip');
}

function applyTooltips(){
	$('.hasTooltip').each(function(){
		var anchor = this;
		// We do an onclick event for the anchor
		// to apply the tooltip. We do this instead of
		// directly applying the tooltip because the x,y of
		// the tooltip is determined when the tip is created.
		// It's possible for the element to not have a layout
		// when the tooltip is being created, so the tooltip
		// shows up in a position that is not in correlation
		// with the anchor.
		$(anchor).bind('click.applyTooltips',function(){
			$(anchor).unbind('click.applyTooltips');
			applyTooltip(anchor);
		});
	});
}

function setupApplicationLinks(){
	if(linkIdParams.testcell.indexOf('MIN') != -1)
		return;
    $(CanadaConfig.selectors.applyLinkNoDialogue).each(function(){
		this.linkid = LinkId.getSectionsFrom($(this).attr('href'));
		$(this).attr('href','javascript:void(0);');

		$(this).click(function(){
			var rel = $(this).attr('rel');
			var jsonData;
			$.ajax({
				type: 'GET',
				url: '/credit-card/dialog/' + rel + '/?random=' + Math.random(),
				dataType: 'json',
				async: false,
				success: function(data){
					jsonData = data;
				}
			});
			if(jsonData.pagecode != ''){
				sections = this.linkid;
				LinkId.set('area',sections.area);
				LinkId.set('subarea',sections.subarea);
				jsonData.url = jsonData.url + '?linkid=' + LinkId.outputId(sections.type,jsonData.pagecode)
			}
			
			if(jsonData.target == '_dialog'){
				parent.constructDialog(jsonData.url);
				return false;
			}
			else {
				$(this).attr('href',jsonData.url);
				$(this).attr('target',jsonData.target); 
				return true;
			}
		});
    });
}

function constructDialog (url){
	$.fn.colorbox({
		href: url,
		opacity: "0.8",
		width: "200px",
		height: "200px",
		iframe: true, 
		overlayClose: true, 
		scrolling: false,
		onOpen: $.fn.colorbox.hide,
		onResize: function () {
			scrollToColorbox();
			$.fn.colorbox.show();
		},
		transition: 'none',
		onLoad: function (){
			if(window.top)window.top.setClickAction('LightboxOpen'); 
		},
		onCleanup: function () {
			if(window.top)window.top.setClickAction('LightboxClose');
		},
		onClosed: $.fn.colorbox.hide
	});
}

function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


/**
 * This prototype will allow a string to be converted from a query (one=1&two=2)
 * into a map.
 * Example: new String('one=1&two=2&boolean=false').fromQuery() == {one: '1', two: '2',boolean: 'false'} == true
 */
String.prototype.fromQuery = function(){
	var outputMap = {};
	var keyValuePairs = this.split('&');
	for(index in keyValuePairs){
		key_value = keyValuePairs[index].split('=');
		outputMap[key_value[0]] = key_value[1];
	}
	return outputMap;
}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.substring(1);
}

String.prototype.camelCase = function() {
    var s = this.replace(/^\s*|\s*$/g, "");
    return (/\S[A-Z]/.test(s))
    ? s.replace(/(.)([A-Z])/g, function(t,a,b) {
        return a + ' ' + b.toLowerCase();
    })
    : s.replace(/( )([a-z])/g, function(t,a,b) {
        return b.toUpperCase();
    });
}

/**
 * This URL Class takes a URL and returns an object containing
 * information about it.
 */
var URL = function(url){
    this.url = '';
    this.domain = '';
    this.params = {};
	this.sections = new Array();
    this.protocol = '';
    this.path = '';

    /**
     * constructor logic
     * @param string url the url to handle
     */
    this.__construct = function(url){
        if(!(url && url.length))
            return;

        this.url = url;

        var arSplit = this.url.split('?');
        var baseUrl = arSplit[0];

        if(baseUrl.match(/:\/\//)){
            // pull out the protocol
            var proto = baseUrl.split('://');
            this.protocol = proto[0];

            // pull out the domain
            var dom = proto[1].split('/');
            var dom1 = dom[0].split(':');
            this.domain = dom1[0];

            // extract the path and paste it back together
            this.path = dom.slice(1).join('/');
        }
		else{
            // pull the protocol from the location
            var prot=location.protocol.split(':');
            this.protocol = prot[0];

            // pull out the domain
            var dom = document.domain;
            var dom1 = dom.split(':');
            this.domain = dom1[0];

            this.path = baseUrl;
        }

		var sections = this.path.split('/');
		for(index in sections){
			if(sections[index] != '')
				this.sections.push(sections[index]);
		}

        if(arSplit[1]){
            var parms = arSplit[1].split('&');
            for(var i = 0; i < parms.length; i++){
                var thisParam = parms[i].split('=');
				if(typeof thisParam[1] == 'undefined')
					thisParam[1] = null;
                this.params[ thisParam[0] ] = thisParam[1];
            }
        }
    };
    this.__construct(url);
	
	/**
	 * Rebuilds the url.
	 */
	this.get = function(){
		var queryString = jQuery.param(this.params);
		if(queryString != '')
			queryString = '?' + queryString;
		var path = this.sections.join('/');
		if(path != '')
			path = '/' + path + '/';
		else path = '/';
		return this.protocol + '://' + this.domain + path + queryString;
	}

    /**
     * test if this domain is a subdomain of the domain passed in
     *
     * @param string domain the domain to test against
     */
    this.isSubOf = function(domain){
        var parts = this.domain.split('.').reverse();
        var inParts = domain.split('.').reverse();
        for(var i = 0; i<inParts.length; i++)
            if(inParts[i]!=parts[i])
                return false;
        return true;
    }
    
    /**
     * Checks if the domain is secure or not.
     */
    this.isSecure = function(){
        return this.protocol.indexOf('https') != -1
    }
	
	this.noQuery = function(){
		var splitted = this.url.split('?');
		return splitted[0];
	}
	
	this.addQueryParam = function(key,value){
		this.params[key] = value;
	}
}

if(typeof(linkIdParams)!='undefined'){
    var LinkId = {
        params:linkIdParams,
        set:function(name,value) {
            this.params[name]=value;
        },
        get:function(name) {
            return this.params[name];
        },
        outputId:function(type,pageCode)
        {
            if( typeof(LinkId.params.area) == 'undefined' )
                LinkId.params.area='Z';
            if( typeof(LinkId.params.subarea) == 'undefined' )
                LinkId.params.subarea='Z';
        
            return this.params.channel+'_'
                +this.params.strategy+'_'
                +this.params.wildcard+'_'
                +this.params.testcell+'_'
                +this.params.source+'_'
                +this.params.area+'_'
                +this.params.subarea+'_'
                +type+'_'
                +pageCode;
        },
        /**
         * @return integer The index of a named position within the linkid
         */
        indexOf:function(position) {
            switch(position) {
				case 'channel'     : return 0;
                case 'strategy'    : return 1;
                case 'wildcard'    : return 2;
                case 'testcell'    : return 3;
                case 'source'      : return 4;
                case 'area'        : return 5;
                case 'subarea'     : return 6;
                case 'type'        : return 7;
                case 'destination' : return 8;
				default            : return -1;
            }
        },
        extractFrom:function(url) {
            var match = /linkid=(([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^&#]*))/;
            var matches = match.exec(url);
            if( matches!=null )
                return matches[1];
            else return null;
        },
        replace:function(url,position,code) {
            var match = /linkid=(([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^&#]*))/;
            var matches = match.exec(url);
            if( matches == null )
                return url;
            var idx = LinkId.indexOf(position);
			if(position == 'subarea' && new Number(code) < 10)code = "0" + code;
            matches.shift();
            original = matches.shift(matches);
            matches[idx] = code;
            newid = matches.join('_');
            return url.replace(original,newid);
        },
        getFrom:function(url,position) {
            var match = /linkid=(([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^&#]*))/;
            var matches = match.exec(url);
            if( matches == null )
                return null;
            var idx = LinkId.indexOf(position);
            matches.shift();
            original = matches.shift(matches);
            return matches[idx]
        },
        /**
         * Replaces a position in the link id with a new value
         * on all anchors on the page.
         */
        replaceAll:function(position,code) {
			if(typeof linkIdParams[position] != 'undefined'){
				linkIdParams[position] = code;
				$("a",document.body).each(function(){
					if( typeof(this.href) != 'undefined' && this.href.length > 0 )
						this.href = LinkId.replace(this.href,position,code);
				});
			}
        },
		reverseIndexOf:function(position) {
			switch(position){
				case 0 : return 'channel';
				case 1 : return 'strategy';
				case 2 : return 'wildcard';
				case 3 : return 'testcell';
				case 4 : return 'source';
				case 5 : return 'area';
				case 6 : return 'subarea';
				case 7 : return 'type';
				case 8 : return 'destination';
				default: return null;
			}
		},
		getSectionsFrom:function(url){
			var match = /linkid=([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^&#]*)/;
			var matches = match.exec(url);
			if(matches == null)return null;
			matches.shift();
			var returnObject = {};
			for(var x = 0; x <= 8; x++)
				returnObject[LinkId.reverseIndexOf(x)] = matches[x];
			return returnObject;
		},
		getLinks:function(object,selectorParam){
			if(typeof object == "object"){
				var selector = typeof selectorParam != "undefined" ? selectorParam : document;
				var links = $('a',selector);
				var filteredLinks = new Array();
				links.each(
					function(){
						var shouldAdd = true;
						linkIds = LinkId.getSectionsFrom($(this).attr('href'));
						//this.linkIdParams = linkIdParams;
						if(linkIdParams != null){
							for(section in object){
								if(linkIdParams[section] != object[section]){
									shouldAdd = false;
									break;
								}
							}
							if(shouldAdd == true){
								filteredLinks.push(this);
							}
						}
					}
				);
				return filteredLinks;
			}
			return null;
		},
		getUniqueSubareaForArea:function(area,selector){
			var links = LinkId.getLinks({area:area},selector);
			var subArea = 0;
			$(links).each(
				function(){
					var currentSubArea = new Number(this.linkIdParams['subarea']);
					if(subArea < currentSubArea)subArea = currentSubArea;
					else if(subArea == currentSubArea){
						// uh-oh, linkId conflict.
					}
				}
			);
			subArea++;
			return subArea;
		},
		getLinkIdFromDom:function(selector,attribute){
			if(typeof attribue == 'undefined')
				attribute = 'href';
			var linkIds = [];
			var here = this;
			$('a',selector).each(
				function(){
					var theId = here.extractFrom($(this).attr(attribute));
					if(theId != null)linkIds.push(theId);
				}
			);
			if(linkIds.length > 0)return linkIds[0];
			else return false;
		}
	}
}

