/* This file was compressed using MbCompression library. http://blog.mironabramson.com */ /*global primitives - Do NOT MODIFY*/
$.console.log('begin loading global.js');

jQuery.isEmpty = function(v)
{
	return  (typeof(v) === 'undefined' || v === null || v.length === 0);
};
jQuery.isArray = function(v)
{
	return  (typeof(v) !== 'undefined' && v !== null && v.constructor === Array);
};

//url encoder
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

function configUrlTemplate(url)
{
	var keys = url.match(configUrlTemplate.re);
	if (keys && keys.length > 0)
	{
		for (var idx = 0, len = keys.length, key, re; idx < len; idx++)
		{
			key = keys[idx].substr(1, keys[idx].length-2);
			eval('configUrlTemplate.currentVal = ' + key);
			//configUrlTemplate.currentVal = $.URLEncode(configUrlTemplate.currentVal);
			url = url.replace(keys[idx], configUrlTemplate.currentVal);
			configUrlTemplate.currentVal = null;
		}
	}	
	return url;
}
configUrlTemplate.currentVal = null;
configUrlTemplate.re = new RegExp();
configUrlTemplate.re.compile('({[^}]*})', 'g');

/*global search*/
var options =
{
    containerQuery: '#global-search',
    triggerQuery: '.global-search-btn',     
    successHandler: function(result)
    {   
        var data = {            
            mode: 'ui_mode',
            query: $('#global-search input').val()
        };    
        
        window.location = '/search/SearchResults.aspx?ui_mode='+data.mode+'&question_box='+data.query;             
    }
};
new $.validation.Group(options);

/*global nav hover*/
$('#nav > li')
    .mouseover(function(){ $(this).addClass('hover') })
    .mouseout(function(){ $(this).removeClass('hover') }); 
          
/*dropdown bgiframes*/
$('#nav li ul').bgiframe();

/*landing page register dynamic modal*/
$('.register-link').click(function(evt)
{   
    evt.preventDefault();
    createRegisterModal();
});


var createRegisterModal = function(err)
{
    var html = [];
    html[html.length] = "<div id=\"registration-modal\" class=\"modal modal-content-wrap\" style=\"display:block;\">";
    html[html.length] = "<h3>Submit Finance Account Number</h3>";
    html[html.length] = "<p>Register your Financial Services account to access our convenient online account tools. Once registered, you can:</p>";
    html[html.length] = "<ul>";
    html[html.length] = "<li>Make payments online</li>";
    html[html.length] = "<li>View statements</li>";
    html[html.length] = "<li>View transaction history</li>";
    html[html.length] = "<li>Update account profile information</li>";
    html[html.length] = "<li>Receive email notification when your statements are available</li>";
    html[html.length] = "</ul>";
    html[html.length] = "<form id=\"registration-form\" method=\"post\" action=\""+regLink+"\">";
    html[html.length] = (err === 1) ? "<p class=\"err-message\">We could not find that account number in our records. Please check the number and re-enter it.</p>" : '';
    html[html.length] = (err === 2) ? "<p class=\"err-message\">That account number is already in use. To manage your account online, please log in.</p>" : '';
    html[html.length] = "<div class=\"field form-login\">";
    html[html.length] = "<label for=\"account-num\">Please Enter Your Financial Services Account Number:</label>";
    html[html.length] = "<input id=\"account-num\" name=\"account-num\" type=\"text\" class=\"default-text required\" />";
    html[html.length] = "</div>";
    html[html.length] = "<a href=\"/\" rel=\"{id:'popup-test-1',url:'https://seal.verisign.com/splash?form_file=fdf/splash.fdf&amp;dn=WWW.ACURAFINANCIALSERVICES.COM&amp;lang=en',width:540,height:460,scrollbars:'yes'}\" class=\"popup-opener\"><img src=\"/images/banner-verisige.gif\")\" alt=\"\" class=\"verisign\"/></a>";
    html[html.length] = "<a class=\"btn-orange submit\"><span>Submit</span></a>";
    html[html.length] = "</form>";
    html[html.length] = "</div>";
    
    X.ModalFactory.create([], html.join(''), true, true, null, null, function(modal) {    
        
        //set the close button to destroy the modal
        $('a.modal-close', modal.elements.wrapper).click(function(evt) {
            var id = '#'+X.ModalFactory.currentModal.id;
            $(id).parent().parent().remove();
        });
        
        $('.popup-opener', modal.elements.content).click(X.PopupFactory._onClick);
        
        // registration form
        var options =
        {
            containerQuery: '#registration-form',
            triggerQuery: '#registration-form .btn-orange',     
            successHandler: function(result)
            { 
             X.Omniture.trigger({data: {pageName:window.omniData['pageName'],prop16:'REGISTRATION'}});       
             $('#registration-form').submit();
             $('#registration-form .btn-orange').unbind();
             $('#registration-form .btn-orange').click(function(evt) {
                evt.preventDefault();
             });
            }
        };
        new $.validation.Group(options);     
    }); 
};

var createAdvisoryModal = function()
{
    var html = [];
    html[html.length] = "<div id=\"registration-modal\" class=\"modal modal-content-wrap\" style=\"display:block;\">";
    html[html.length] = "<h3 style=\"color:red;\">Important Advisory</h3>";
    html[html.length] = "<p style=\"line-height:1.5em;\">AcuraFinancialServices.com will be temporarily unavailable on January 24, 2010 beginning at 12:00 am PST for approximately 4 hours due to routine maintenance.</p>";    
    html[html.length] = "</div>";
    
    X.ModalFactory.create([], html.join(''), true, true, null, null, function(modal) {    
        
        //set the close button to destroy the modal
        $('a.modal-close', modal.elements.wrapper).click(function(evt) {
            var id = '#'+X.ModalFactory.currentModal.id;
            $(id).parent().parent().remove();
        });            
    }); 
};

/*forgot password dynamic modal*/
$('.forgot-password-link').click(function(evt)
{   
    evt.preventDefault();
    var data = {id:'forgot-password-popup',url:forgotPasswordLink,width:'590',height:'360',scrollbars:'no'};
    X.PopupFactory.create(data);
   
});

/*landing page dealer locator search*/
var options =
{
    containerQuery: '.sidebar3 .form1',
    triggerQuery: '.sidebar3 .form1 .submit',     
    successHandler: function(result)
    {  
        var zip = $('#dl-zipcode').val();
        window.location = 'tools/dealerlocator/DealerLocator.aspx?zip='+zip+'&radius=0';  
    }
};
new $.validation.Group(options);

/*print area functionality*/

$('li.print a').click(function () {
    if($(".main").hasClass("current-offers")){ heightPadding = 500; }
    else if($(".main").hasClass("dealer-locator") && $(".results").hasClass("unordered")){ heightPadding = 210; }
    else if($(".main").hasClass("dealer-locator") && $(".results").hasClass("list-view") ){ heightPadding = -400; }
    else if($(".main").hasClass("dealer-locator") && ($("table.search-results").length > 0) ){ heightPadding = 100; }
    else if($(".main").hasClass("calc")){ heightPadding = 125; }
    else if ($(".sitemap-content").length > 0) { heightPadding = 150; }
    
    else    { heightPadding = 50; }
    
    
    $(".content").printArea(
    {
        htmlPrefix: '<div class="print-view-div"><img src="/images/logo1.gif" class="print-logo"><div class="' + $(".main").attr('class') + '"><div class="content-holder">',
        htmlSuffix: '</div></div></div>',
        show: true,
        height: ($(".content").outerHeight() + heightPadding) + "px",
        width: '706px'/*,
        js: '$(".content-body").prepend(\'<img src="/images/print-logo.gif"/><h2>Dealer Locator: Dealer Search Results</h2>\');'*/
    });
});

function printIframe(iframeId) {
	document.getElementById(iframeId).contentWindow.focus();
	document.getElementById(iframeId).contentWindow.print();	
}
function showLayer(x,id)
{
    if(x==0)
    {
        document.getElementById(id).style.visibility = "hidden";            
    }
    if(x==1)
    {
        document.getElementById(id).style.visibility = "visible";
    }
}
             


// Loop through all text inputs that have the class default-text and extend their functionality
$(':text.default-text').each(function(idx)
{
	var defaultValue = this.value;
	$(this)
		.focus(function() { if (this.value === defaultValue) { this.value = ''; } })
		.blur(function() { if (this.value === '') { this.value = defaultValue; }
	});
});

//reset error fields upon focus
$('input, textarea').focus(function()
{   
    if ($(this).parent().hasClass('err-field')) { $(this).parent().removeClass('err-field'); }	    
});

//set currency auto-formatting for currency text fields
$('.val-currency').change(function(idx)
{
    if ($(this).val()) {                 
        if(parseFloat($(this).val().replace(/(\$|\,)/g,''))||$(this).val() == 0) {
            var val = parseFloat($(this).val().replace(/(\$|\,)/g,''));        
            $(this).val(val.toUSD('forceDecimal'));
        }
    }
});

/*send email dynamic modal*/
$('.send-email-link').click(function(evt)
{   
    evt.preventDefault();
    createEmailModal();
});

var createEmailModal = function()
{
    var html = [];
    html[html.length] = '<div id="email-form" class="emailform modal modal-content-wrap" style="display:block;">';
    html[html.length] = '<div class="emailform-headwrap">';
    html[html.length] = '<span class="header">Email a link to this page</span>';
    html[html.length] = '<p>We do not store or share these email addresses.</p>';
    html[html.length] = '<p class="right">* = Required</p>';
    html[html.length] = '</div>';
    html[html.length] = '<fieldset>';
    html[html.length] = '<div class="field name">';
    html[html.length] = '<label for="email-form-Name">From (Name):*</label>';
    html[html.length] = '<input type="text" id="email-form-Name" name="Name" class="default-text required" />';
    html[html.length] = '</div>';
    html[html.length] = '<div class="field from-address">';
    html[html.length] = '<label for="email-form-FromEmail">From (Email Address):*</label>';
    html[html.length] = '<input type="text" id="email-form-FromEmail" name="FromEmail" class="txt required val-email" />';
    html[html.length] = '</div>';
    html[html.length] = '<div class="field to-address">';
    html[html.length] = '<label for="email-form-ToEmail">To (Email Address):*</label>';
    html[html.length] = '<input type="text" id="email-form-ToEmail" name="ToEmail" class="txt required val-email" />';
    html[html.length] = '</div>';
    html[html.length] = '<div class="field comments">';
    html[html.length] = '<label for="email-form-Comments">Comments:</label>';
    html[html.length] = '<textarea id="email-form-Comments" name="Comments" rows="10" cols="53" class="val-textarea"></textarea>';
    html[html.length] = '</div>';
    html[html.length] = '</fieldset>';
    html[html.length] = '<a class="btn-orange cancel" href="/" title="Cancel"><span>Cancel</span></a>';
    html[html.length] = '<a class="btn-orange submit" href="/" title="Submit"><span>Send</span></a>';
    html[html.length] = '<input type="hidden" id="reqURL" name="reqURL" value="'+window.location+'" />';   
    html[html.length] = '</div>';
    
    X.ModalFactory.create([], html.join(''), true, true, null, null, function(modal) {    
        
        //set the close button to destroy the modal
        $('a.modal-close', modal.elements.wrapper).click(function(evt) {           
            var id = '#'+X.ModalFactory.currentModal.id;
            $(id).parent().parent().remove();
        });
        
        //set the cancel button to click the close button
        $('#email-form a.cancel').click(function(evt) {
            evt.preventDefault();
            $(this).parent().parent().parent().find('.modal-close').click();
        });
        
        var options =
        {
            containerQuery: '#email-form',
            triggerQuery: '#email-form .submit',
            failureHandler: function(result)
            {
                var namesHash = {};		        
		        result.container.containerElm.addClass('err-container');
		       
		        for (var idx = 0, len = result.errors.length, err, srcElm, name; idx < len; idx++)
		        {
			        err = result.errors[idx];
			        srcElm = err.srcElement.get(0);
			        name = srcElm.name;
			        
			        if (err.id === 'val-textarea') {
        			   err.srcElement.parent().append('<p class="err-message">Disallowed character(s) were entered</p>'); 
        			}
        			
			        if (namesHash[name]) { continue; }
			        namesHash[name] = true;
        			
			        err.srcElement.parent().addClass('err-field');
		        }
            },     
            successHandler: function(result)
            {   
                X.Omniture.trigger({data: {pageName:window.omniData['pageName'],prop16:'EMAIL SEND'}})
                
                //extract form data
                var data = {
                    name: $('#email-form-Name').val(),
                    fromEmail: $('#email-form-FromEmail').val(),
                    toEmail: $('#email-form-ToEmail').val(),
                    comments: $.URLEncode($('#email-form-Comments').val()),
                    reqURL: $('#reqURL').val() 
                };
                
                //replace unix \n with encoded br tag
                data.comments = data.comments.replace(/%0A/g, '%3Cbr%20/%3E');
                
                //callback
                var callback = function(response)
                {
                    if (response.Error) {
                        $('#email-form fieldset').prepend('<p class="err-message">'+response.Error+'</p>');
                    } else if (response.Success) {
                        $('#email-form').empty();
                        $('#email-form').prepend('<p class="success">'+response.Success+'</p>');
                    }
                };
                
                //make the call
                X.JsonRequestManager.call('send-email',
                {
	                url: configUrlTemplate(serviceUrls.emailHandler, data.name, data.fromEmail, data.toEmail, data.comments, data.reqURL),
	                cache: false,
	                success: callback.delegate(this),
	                error: function(textStatus, msg) { alert(msg); }
                });		    
            }
        };

        new $.validation.Group(options);
          
    }); 
};

//Search results page validation
var options =
{
    containerQuery: '.search-results',
    triggerQuery: '.search-results .submit',
    successHandler: function(result)
    {   
        var data = {            
            mode: 'ui_mode',
            query: $('#search-results-search').val()
        };    
        
        window.location = '/search/SearchResults.aspx?ui_mode='+data.mode+'&question_box='+data.query;             
    }
};
new $.validation.Group(options);

/*unload and garbage collection*/
$(window).unload(function(evt)
{
    $(document.body).empty();
    if (window.CollectGarbage) { window.CollectGarbage(); }
});

/*factory inits*/
$(document).ready(function()
{
	// Initialize our 
	X.PopupFactory.init();
	X.ModalFactory.init();
	X.TooltipFactory.init();
});

$.console.log('end loading global.js');




(function($) {
    var printAreaCount = 0;
    $.fn.printArea = function(settings)
        {
            settings = $.extend(
            {
                htmlPrefix: null,
                htmlSuffix: null,
                /*height: ($(this).outerHeight()) + "px",
                width: ($(this).outerWidth()) + "px",*/
                height: ($(this).outerHeight()) + "px",
                width: "506px",
                show: true,
                modal: true,
                printCss: '/css/print.css'
            }, settings);
            
            var ele = $(this);
            var idPrefix = "printArea_";
            
            removePrintArea(idPrefix);
            
            var iframeId = idPrefix;
            var iframeStyle = (!settings.show)?
                'position:absolute;width:0px;height:0px;left:-10000px;top:-10000px;z-index:0;' :
                'position:absolute;width:' + settings.width + ';height:' + settings.height + ';left:100px;top:50px;z-index:1000000;border:0 none;';
            if (settings.modal)
            {
                //iframe = $('<div class="modal-wrap modal-fixed modal-closeable" style="display:block;"><div class="modal-inner"><div class="modal modal-content-wrap" style="display:block;"><iframe name="' + iframeId + '" id="' + iframeId + '" style="width:' + ($(this).outerWidth()+90) + 'px;height:' + ($(this).outerHeight()+50) + 'px;border:0 none;" frameborder="no" scrolling="no"></iframe></div></div></div>').appendTo(document.body).find('iframe').get(0); //document.createElement('IFRAME');
                
                var onShowHandler = function(modal) {
                
                    //change the close button class
                    $('a.modal-close', modal.elements.wrapper).removeClass('modal-close').addClass('close-page');
                    
                    //change the close button class
                    $('a.modal-print', modal.elements.wrapper).removeClass('modal-print').addClass('printarea-print').click(function(evt)
                    {
                        X.Omniture.trigger({data: {pageName:window.omniData['pageName'],prop16:'PRINT'}});
                        //window.print();
                        printIframe('printArea_');
                    });
                    
                    //set the close button to destroy the modal
                    $('a.close-page', modal.elements.wrapper).click(function(evt) {
                        var id = '#'+X.ModalFactory.currentModal.id;
                        $(id).parent().parent().remove();
                    });                    
                };
                
                X.ModalFactory.create([], '<iframe name="' + iframeId + '" id="' + iframeId + '" style="width:596px;height:' + settings.height + ';border:0 none;" frameborder="no" scrolling="no"></iframe>', true, true, null, null, onShowHandler, false);
                  
                iframe = $('#'+iframeId).get(0);
            }
            else
            {
                iframe = $('<iframe name="' + iframeId + '" id="' + iframeId + '" style="' + iframeStyle + '" frameborder="no" scrolling="no"></iframe>').appendTo($("body")).get(0); //document.createElement('IFRAME');
            }
            
            var html = [];
            html[html.length] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
            html[html.length] = '<html xmlns="http://www.w3.org/1999/xhtml">';
            html[html.length] = '<head>';
            html[html.length] = '<title>' + document.title + '</title>';
            html[html.length] = '<meta http-equiv="content-type" content="text/html,utf-8" />';
            html[html.length] = '<style type="text/css">';
            html[html.length] = 'body.hide { display:none; }';
            
            html[html.length] = '</style>';                       
//            html[html.length] = '<link type="text/css" rel="stylesheet" href="/css.axd?d=landing" media="all" />';
            $(document).find("link")
                .filter(function(){ return ($(this).attr("rel").toLowerCase() === "stylesheet"); })
                .each(function()
                {
                    var href = $(this).attr("href");
                    //if (href.charAt(0) !== '/') { href = '/' + href; }
                    html[html.length] = '<link type="text/css" rel="stylesheet" href="' + href + '" />';
                }
            );
            html[html.length] = '<link type="text/css" rel="stylesheet" href="' + settings.printCss + '" media="print" />';
            html[html.length] = '</head>';
            html[html.length] = '<body id="' + document.body.id + '" class="hide">';
            //html[html.length] = '<div class="' + $('#doc-wrap').get(0).className + '">';
            if (settings.htmlPrefix) { html[html.length] = settings.htmlPrefix; }
            html[html.length] = '<div class="' + $(ele).attr("class") + '">' + $(ele).html() + '</div>';
            
            if (settings.htmlSuffix) { html[html.length] = settings.htmlSuffix; }
            html[html.length] = '</div>';            
            html[html.length] = '<script src="/js/ext/jquery-1.2.6.min.js" type="text/javascript"></script>';
            html[html.length] = '<script src="/js/print-functions.js" type="text/javascript"></script>';
            html[html.length] = '<script type="text/javascript">/*<![CDATA[*/';

            if (settings.js)
            {
                html[html.length] = settings.js;
            }
            //html[html.length] = 'window.onload = function(){ parent.printIframe(\'' + iframeId + '\'); }';
            html[html.length] = '/*]]>*/</script>';
            html[html.length] = '</body>';
            html[html.length] = '</html>';
            
            //alert(html);
            var doc = iframe.contentWindow.document;
            doc.open('text/html', true);
            doc.write(html.join('\n'));
            doc.close();
            doc = null;
			var frameWindow = iframe.contentWindow;
            //debugger;
            frameWindow.close();
            frameWindow = null;
            

        }
        
        var removePrintArea = function(id)
        {
            var printElm = $("iframe#" + id);
            if (printElm.length > 0)
            {
                printElm = printElm.get(0);
	            try { printElm.parentNode.removeChild(printElm); }
	            catch (ex) {}
	            printElm = null;
	        }
        };

})(jQuery);


$.console.log('begin loading login.js');

$('.login-link').click(function(evt)
{
    evt.preventDefault();
    $('.right-area .global-login-form').toggle().css("left","75px").css("top","0px");
});
$('.login-link-inline').click(function(evt)
{
    evt.preventDefault();
	var win = jQuery(window);
	var scrollY = win.scrollTop();
	var scrollX = win.scrollLeft();

	var xPos = ($(this).offset().left - $('.content-holder').offset().left + $(this).width() + 20);
    var yPos = ($(this).offset().top - 80);
    if (yPos < 0) {yPos = 0;}
    $('.right-area .global-login-form').toggle().css("top", yPos).css("left", xPos);
    
    var output = 'scrollY: ' + scrollY;
    output += '\nscrollX: ' + scrollX;
    output += '\nxPos: ' + xPos;
    output += '\nyPos: ' + yPos;

    //alert(output);
});
$('.right-area .global-login-form').bgiframe();

$('.right-area .global-login-form .close-btn').click(function(evt)
{
    $('.right-area .global-login-form').hide();
});


var options =
{
    containerQuery: '.login-form',
    triggerQuery: '.login-form .btn-orange',     
    successHandler: function(result)
    {       
        X.Omniture.trigger({data: {pageName:window.omniData['pageName'],prop16:'LOG IN'}});
        $('.login-form').submit();
        $('.login-form .btn-orange').unbind();
        $('.login-form .btn-orange').click(function(evt) {
            evt.preventDefault();
        });
    }
};

new $.validation.Group(options);

options.containerQuery = '.global-login-form';
options.triggerQuery = '.global-login-form .btn-orange';
options.successHandler = function(result)
{
    X.Omniture.trigger({data: {pageName:window.omniData['pageName'],prop16:'LOG IN'}});
    $('.global-login-form').submit();
    $('.global-login-form .btn-orange').unbind();
    $('.global-login-form .btn-orange').click(function(evt) {
        evt.preventDefault();
    });
};

new $.validation.Group(options);

if (window.loginErr)
{  
   switch(parseInt(loginErr))
   {
        case 1:
        if (window.ref)
        {
            switch (ref)
            {
                case 'login-form-layer':
                $('.global-login-form').prepend('<p class="err-message">Invalid Login</p>');
                $('.login-link').click();
                break;
                
                case 'login-form':
                $('.login-form fieldset').prepend('<p class="err-message">Invalid Login</p>');
                break;                
            }
        } else {
            alert('Invalid Login');
        }          
   }
}
if (window.regErr)
{
   switch(parseInt(regErr))
   {
        case 1:
        $('#registration-form').prepend('<p class="err-message">We could not find that account number in our records. Please check the number and re-enter it.</p>');        
        createRegisterModal(1);
        break;
        
        case 2:
        $('#registration-form').prepend('<p class="err-message">That account number is already in use. To manage your account online, please log in.</p>');        
        createRegisterModal(2);   
        break;      
   }
}

if (parseInt($.cookie('LoginCount')) > 2)
{
    var data = {id:'forgot-password-popup',url:forgotPasswordLink,width:'590',height:'360',scrollbars:'no'};
    X.PopupFactory.create(data);
	$.cookie('LoginCount', null, { expires: -1, path: '/' });
	$.cookie('LoginCount', 0, { expires: 30, path: '/' });
}

$.console.log('end loading login.js');


