/* Path for this file: /content/dam/nissan/codepack/nissan/components/pages/layout/mainlayout.js/jcr:content/renditions/original */
// these were pulled from main JS file into mainlayout.js
/*
jQuery(document).ready(function() {
    if(jQuery("#frameBg").size()>0){
        //jQuery("#frameBg").height(jQuery("#frameContent").height()+20);
    }
    jQuery("#frameContent").click(function(){
        //jQuery("#frameContent").html(jQuery("#frameContent").html()+"<br /><br />");
        //resizeMe(jQuery("#frameContent").height());
    });    
});
function resizeMe(hgt){
    if(jQuery("#frameBg").size()>0){
        jQuery("#frameBg").height(hgt+20);
        if(jQuery("#frameContent").height() + 50 > jQuery("#pageBg").height()){
            //jQuery("#pageBg").height(jQuery("#pageBg").height()+20);
        }
    }
}
*/

jQuery(document).ready(function() {
    if(jQuery.browser.msie && parseInt(jQuery.browser.version) === 6) jQuery('#frameBg + #frameContent').addClass('frameContentHasBg');
 
    if(jQuery("#frameContent").height() + 50 > jQuery("#pageBg").height()){         
            jQuery("#pageBg").css("margin-bottom","50px");
        }
    
});


// written almost entirely by sean schricker

trace=(typeof console!='undefined' && typeof console['log']=='function')?console.log:function(){};
// zap this css. ideally, we'll change the template later. it's too much to do now, though.
jQuery('link[href*=codepack.incGlobPaths.true]').remove();

var bt={};
bt.form={};
bt.current={};
bt.isInfiniti=(/infiniti/.test(location.href));
bt.isNissan=!bt.isInfiniti;

bt.constants={PHONES_PER_PAGE:16,DEFAULT_DISCLAIMER:"Availability of specific features is dependent upon the phone's Bluetooth® support. Despite the fact that Bluetooth® is a global standard, many different versions are implemented in today's mobile devices. Every version offered may not support the profiles necessary to successfully communicate with the Nissan Bluetooth® Hands-free Phone System in your Nissan vehicle; therefore, only certain devices have been approved by Nissan. These devices have exceeded the minimum standards for compatibility as of the date of testing. This compatibility list is not a warranty for phone performance or functionality. System performance and feature availability can vary based on phone software version, wireless carrier, coverage, and many other factors outside of Nissan's control. Nissan does not guarantee the availability of any specific feature and makes no guarantees or warranties relating to the performance of these features. Device and feature compatibility status are subject to change without notice. Please refer to your phone owner's manual for details. Cell phone not included. The Bluetooth word mark and logos are owned by Bluetooth SIG, Inc., and any use of such marks by Nissan is under license.<br />"};
setupQS();

function setupQS(){
    bt.querystring={};
    bt.getQS=function(key,def){
        return unescape((key in bt.querystring)? bt.querystring[key] : (def||"")).replace(/\+/g,' ') ;
    }
    var _querystring=location.search.substr(1).split('&');
    for(var i=0;i<_querystring.length;i++){
        var pair=_querystring[i].split('=');
        bt.querystring[pair[0]]=pair[1];
    }
    bt.querystring.status=bt.getQS('status')||"FCP";
    bt.current.sort=bt.getQS('sort')||"name";
}

bt.common_qs="mfg={1}&vehicle={2}&year={3}&equip={4}&status={5}".format( //&page={6}&sort={7}  system={0}&
    bt.getQS('system'),
    bt.getQS('mfg'),
    bt.getQS('vehicle'),
    bt.getQS('year'),
    bt.getQS('equip'),
    bt.getQS('status') //,  bt.current.page,    bt.current.sort
);
jQuery(function(){
    // add the id to the body tag based on the filename.
    jQuery('body').attr('id',function(){
        //      (/.*\/([^\/]+?)(.html)?.*?/).test(location.pathname);
        (/.*\/([^\/]+)(.html)?.*?/).test(location.pathname);
        var pagename=RegExp.$1||'index';
        pagename=pagename.replace(/\.html/,''); // should incorporate into RE, but this was quick.
        var exceptions={'index':'home','bluetooth':'home'};
        bt.pageid=(pagename in exceptions)?exceptions[pagename]:pagename;
        return bt.pageid;
    });
    jQuery('#sort').change(function(){
        var newHref=location.href.replace(/#.+/,'').replace(/&page=\w*\b/,'')+'&page=1';
        newHref=newHref.replace(/&sort=\w*\b/,'')+'&sort='+this.value;
        location.href=newHref;
    });
    if(bt.getQS('sort')){
        jQuery('#sort').val(bt.getQS('sort'));
    }
    bt.isTaggingSinglePhone=(/^(phone|setup)$/.test(jQuery('body').attr('id')));
    if(!bt.isTaggingSinglePhone){
  //      crmEvent1();
    }

    jQuery('.discTog').each(function(){
        this.onclick="";
    }).click(function(){
        bt.toggleDisclaimer();
    });

    // tabs. FCP means it's recommended.
    var isFCP=(bt.getQS('status'))=='FCP';
    jQuery('#FCP').attr('src','/content/dam/nissan/bluetooth/bt_tab_recommended_{0}.gif'.format((isFCP)?'on':'off'));
    jQuery('#LCP').attr('src','/content/dam/nissan/bluetooth/bt_tab_notRecommended_{0}.gif'.format((!isFCP)?'on':'off'));

    jQuery('#phoneFeatures').attr('href','phone.html'+location.search);

    if(jQuery('#findForm').length==0){
        return;
    }

    //# load vehicle data 
    jQuery.getJSON("/content/nissan/us/en/bluetoothdata.vehicle.html",function(data){
        bt.vehicles={};
        bt.vehicles.raw=data.vehicles;
        bt.vehicles.byName={};
        for(var i=0;i<bt.vehicles.raw.length;i++){
            bt.vehicles.byName[bt.vehicles.raw[i].name]=bt.vehicles.raw[i];
        }
        bt.populate_select_vehicle();
        document.getElementById('year').disabled=true;
        document.getElementById('equip').disabled=true;
        document.getElementById('mfg').disabled=true;
        document.getElementById('submit').disabled=true;
        jQuery('#findForm').show(); 
    });
    //# load phone data 
    jQuery.getJSON("/content/nissan/us/en/bluetoothdata.db.html",function(data){
        // add some data objects. descriptions on the assignment a few lines down.
        bt.db={};
        bt.db.raw=data.db;
        bt.db.byPhones={};
        bt.db.byMfr={};
        bt.db.byPhoneArray=[];
        /// denormalize data for easier use.
        for(var i=0;i<bt.db.raw.mfrs.length;i++){
            var mfr=bt.db.raw.mfrs[i];
            bt.db.raw.mfrs[i].d=bt.db.raw.mfrs[i].d.replace(/\ufffd/g,'&copy;'); // not sure how this char got in there, but let's swap it out.
            bt.db.byMfr[bt.db.raw.mfrs[i].id]=bt.db.raw.mfrs[i]
            for(var j=0;j<mfr.phones.length;j++){
                /// these are the ones we want right here.
                mfr.phones[j].mfr=mfr; // let each phone know its daddy
                mfr[mfr.phones[j].id]=mfr.phones[j];
                bt.db.byPhoneArray.push(mfr.phones[j]); // make an array of alllll phones.
                bt.db.byPhones[mfr.phones[j].n]=mfr.phones[j]; //- make an object so we can ref phones by name. THIS may be useless. consider scrapping.
            }
        }
        if(bt.getQS('mfg') in bt.db.byMfr){
            bt.current.mfg=bt.db.byMfr[bt.getQS('mfg')];// make an object so we can ref mfrs by name.
        }

        //bt.populate_select_vehicle();
        //-bt.populate_select_mfg();
        bt.set_form_selection();

        if(bt.pageid=='home'){
            return;
        }
        
        /// get list of ALL phones or all phones from one mfr
        bt.current.phones=(bt.current.mfg&&bt.current.mfg.phones)? bt.current.mfg.phones : bt.db.byPhoneArray ;
        bt.sortPhones(bt.current.phones,(bt.getQS('sort')||'alpha')); // alpha|date

        if(bt.pageid=='testing'){
            bt.initTestingPage();
            return;
        }
        /// filter the list for pass/fail
        bt.current.phones=jQuery.grep(bt.current.phones,function(value,index){
            // if value.f even exists and has a value
            if((bt.getQS('equip') in value.f) && value.f[bt.getQS('equip')]){
                if((bt.getQS('status'))=="LCP"){
                    // FAIL. ouch.
                    return value.f[bt.getQS('equip')].toLowerCase()=='f'; // up to 13 now.
                }else{
                    // recommended phones, so see if it has data.
                    return value.f[bt.getQS('equip')].length>10; // up to 13 now.
                }
            }else{
                return false;
            }
        });


        /// BEGIN RESULTS PAGE. consider wrapping up and only calling on results. JS is so fast, this may gain zero noticeable improvement.
        jQuery('#phoneHeader').html('{0} {1} Recommended Bluetooth®-enabled phone model{2} found'.format(
            bt.current.phones.length,
            (((bt.getQS('status')||'FCP')=='FCP')?'':'Not'),
            (bt.current.phones.length==1?'':'s') // plural s 
        ));
        jQuery('#phoneNote').html((bt.getQS('status')=='FCP')?"The following devices have been tested by Nissan and are recommended for use with your vehicle.":'The following devices did not meet Nissan’s minimum compatibility standards and are not recommended for use with your vehicle.');

        bt.constants.PAGE_COUNT=Math.ceil(bt.current.phones.length/bt.constants.PHONES_PER_PAGE);
        bt.current.page=Math.min((+bt.getQS('page')||1),bt.constants.PAGE_COUNT);

        bt.initPaging();
        bt.handlePrevNextArrows();
        bt.fillPhoneMatrix();
        
        // fill print matrix/elements
        jQuery("#phoneMatrixPrint").html("");
        for(var i=0;i<bt.current.phones.length;i++){
            jQuery("#phoneMatrixPrint").append(bt.current.phones[i].mfr.n + " " + bt.current.phones[i].n + "<br />");
        }
        jQuery("#phoneVehicle").html(bt.form.vehicle.name);
        jQuery("#phoneYear").html(bt.form.year.name);
        //jQuery("#phoneEquip").html("");
        jQuery("#phoneMatrixPrint").css("border","10px red solid")
                
        /// END RESULTS PAGE
        /// BEGIN PHONE PAGE
        if(
               typeof bt.querystring.mid == 'string'
            && typeof bt.querystring.pid == 'string'
            && (bt.querystring.mid in bt.db.byMfr)
            && (bt.querystring.pid in bt.db.byMfr[bt.querystring.mid])
            && typeof bt.querystring.equip == 'string'
            && (bt.querystring.equip in bt.db.byMfr[bt.querystring.mid][bt.querystring.pid].f)
            && bt.db.byMfr[bt.querystring.mid][bt.querystring.pid].f[bt.querystring.equip].length>10
        ){
            bt.current.phone=bt.db.byMfr[bt.querystring.mid][bt.querystring.pid];
            if(1||bt.pageid=='phone')bt.initFeaturesPage();
            if(1||bt.pageid=='setup')bt.initSetupPage();
        }else{
            /// consider displaying an error message.
        }
        /// END PHONE PAGE
        /// Oh, and let's get some nice tagging in there.
        if(bt.isTaggingSinglePhone){
            var naviTag=jQuery("select#equip option:selected").text();
            crmEvent1(
                jQuery("select#vehicle").val().replace(/ /g,'_'),
                bt.current.phone.n.replace().replace(/ /g,'-'),
                ((naviTag=="Navigation System")?'(Navi)':((naviTag=="No Navigation System")?'(Non-Navi)':'')),
                jQuery("select#equip").val(),
                jQuery("select#year").val(),
                bt.current.phone.mfr.n.replace(/ /g,'-')
            );
        }
    });
});

bt.initPaging=function(){
    if(bt.current.phones.length<=bt.constants.PHONES_PER_PAGE){return;}
    jQuery('.bluePages').html(bt.constants.PAGE_COUNT);
    jQuery("#results .bluePaging").show();
    var pagers=jQuery(".blueSelect.viewCriteria")

    pagers.each(function(){
        for(var i=0;i<bt.constants.PAGE_COUNT;i++){
            this.options[i]=new Option(i+1,i+1);
        }
        this.value=bt.current.page;
    });
    jQuery(".bluePrev a").click(function(){
        //trace(bt.current.page>1)
        if(bt.current.page>1){
            pagers.val(bt.current.page-1);
            pagers.eq(0).change();
        }
    });
    jQuery(".blueNext a").click(function(){
        //trace(bt.current.page<bt.constants.PAGE_COUNT)
        if(bt.current.page<bt.constants.PAGE_COUNT){
            pagers.val(bt.current.page+1);
            pagers.eq(0).change();
        }
    });
//-bt.constants.PAGE_COUNT
    pagers.change(function(){
        bt.current.page=+this.value;
        // matching prod, but it should be visiblity, not display.
        bt.handlePrevNextArrows();
        bt.fillPhoneMatrix();
        pagers.val(this.value);
    });
}
bt.handlePrevNextArrows=function(){
    jQuery(".bluePrev a")[(bt.current.page<=1)?"hide":"show"]();
    jQuery(".blueNext a")[(bt.current.page>=bt.constants.PAGE_COUNT)?"hide":"show"]();
}
bt.initFeaturesPage=function(){
    jQuery('#phoneImage').attr('src',bt.current.phone.is);
    jQuery('#phoneMfg').html(bt.current.phone.mfr.n);
    jQuery('#phoneModel').html(bt.current.phone.n);
    jQuery('#backToSearch').attr('href','results.html'+location.search);
    jQuery('#setupGuide').attr('href','setup.html'+location.search);

    var equips = bt.db.byMfr[bt.querystring.mid][bt.querystring.pid].f[bt.querystring.equip].split("");
    jQuery('.phoneCompat').each(function(i){
        this.innerHTML=(equips[i]=='X')?'NA':equips[i];
    });
}
bt.initSetupPage=function(){
    jQuery('#phoneFeatures').attr('href','phone.html'+location.search);
    setupURL='/content/nissan/us/en/bluetoothdata.mfr.{0}.phone.{1}.system.{2}.setupguide.html'.format(
        bt.current.phone.mfr.id,
        bt.current.phone.id,
        bt.querystring.equip
    )
    //trace(setupURL);
    //jQuery('#phoneSetup').load('18_0_3.htm');
    if(jQuery('#setup #phoneSetup').length){
        jQuery('#setup #phoneSetup').load(setupURL);
    }
}
bt.sortPhones=function(myPhoneArray,date_or_alpha){
    if(date_or_alpha=='date'){
        myPhoneArray.sort(function(a,b){
            return (a.da>b.da)?-1:1;
        });
    }else{
        myPhoneArray.sort(function(a,b){
            var isGreater= (a.mfr.n.toLowerCase()==b.mfr.n.toLowerCase())?(a.n.toLowerCase()>b.n.toLowerCase()):(a.mfr.n.toLowerCase()>b.mfr.n.toLowerCase());
            return isGreater?1:-1;
        });
    }
}

bt.fillPhoneMatrix=function(){
    jQuery('#phoneMatrix').html("");
    
    var startingIndex=(+bt.current.page-1)*bt.constants.PHONES_PER_PAGE;
    var endingIndex=Math.min(((+bt.current.page)*bt.constants.PHONES_PER_PAGE),bt.current.phones.length);
    //trace([startingIndex,endingIndex])
    if(bt.current.phones.length)for(var i=startingIndex;i<endingIndex;i++){
        var _panel=('<{8} href="phone.html?mid={0}&pid={1}&page={2}&sort={3}&{4}" class="blueCell"><img alt="{5} {6}" src="{7}"/><div><span class="noprint">{5}</span> {6}</div></{8}>'.format(
            bt.current.phones[i].mfr.id,
            bt.current.phones[i].id,
            bt.current.page,
            bt.current.sort,
            bt.common_qs,
            bt.current.phones[i].mfr.n,
            bt.current.phones[i].n,
            bt.current.phones[i].is,
            ((bt.getQS('status')=='FCP')?'a':'div')
        ));
        jQuery('#phoneMatrix').append(_panel);
        //trace(bt.current.phones[i].n,bt.common_params)
    }
        jQuery('#results #phoneResults').show();
    jQuery('#FCP').parent().attr('href',location.href.replace(/#.+/,'').replace(/&status=\w*\b/,'')+'&status=FCP');
    jQuery('#LCP').parent().attr('href',location.href.replace(/#.+/,'').replace(/&status=\w*\b/,'')+'&status=LCP');
    if(bt.querystring.status=='FCP'){
        jQuery('#phoneTablink').html('tested but not recommended');
        jQuery('#phoneTablink').attr('href',jQuery('#LCP').parent().attr('href'));
    }else{
        jQuery('#phoneTablink').html('recommended');
        jQuery('#phoneTablink').attr('href',jQuery('#FCP').parent().attr('href'));
    }

}


bt.populate_select_mfg=function(){
    var select_mfg=jQuery("select#mfg");
    var select_equip_val=jQuery("select#equip").val();
    var allMfrs=bt.db.raw.mfrs;//a bit easier to look at.
    select_mfg[0].options.length=1;
    for(var i=0;i<allMfrs.length;i++){
        for(var j=0;j<allMfrs[i].phones.length;j++){
            if((typeof allMfrs[i].phones[j].f[select_equip_val])=='string' && allMfrs[i].phones[j].f[select_equip_val].length>10){
                select_mfg[0].options[select_mfg[0].options.length]=new Option(allMfrs[i].n,allMfrs[i].id);
                break;
            }
        }
    }
}
bt.populate_select_vehicle=function(){
    var select_vehicle=jQuery("select#vehicle");
    select_vehicle[0].options[0].value="";
    for(var i=0;i<bt.vehicles.raw.length;i++){
        select_vehicle[0].options[select_vehicle[0].options.length]=new Option(bt.vehicles.raw[i].name,bt.vehicles.raw[i].name);
    }
    
    select_vehicle.unbind('change').change(function(){
        bt.form.vehicle=(this.value)?bt.vehicles.byName[this.value]:null;
        bt.populate_select_year();
    });
}


bt.populate_select_year=function(){
    var select_year=jQuery("select#year");
    select_year[0].options.length=1;
    
    if(bt.form.vehicle){
        var _years=bt.form.vehicle.years;
        for(var i=0;i<_years.length;i++){
            select_year[0].options[select_year[0].options.length]=new Option(_years[i].name,_years[i].name);
        }
    }
    select_year[0].disabled=(select_year[0].options.length==1);
    if(select_year[0].disabled){
        bt.populate_select_equip();
    }
    select_year.unbind('change').change(function(){
        if(this.selectedIndex==0){
            bt.form.year="";
        }else for(var i=0;i<bt.form.vehicle.years.length;i++){
            if(bt.form.vehicle.years[i].name==this.value){
                bt.form.year=bt.form.vehicle.years[i];
            }
        }
        //trace(bt.form.vehicle.year);
        bt.populate_select_equip();
    });
    if(select_year[0].options.length==2){
        select_year[0].selectedIndex=1;
    }
    select_year.change();
}
bt.populate_select_equip=function(){
    var select_equip=jQuery("select#equip");
    select_equip[0].options.length=0;

    select_equip.unbind('change').change(function(){
        document.getElementById('mfg').disabled=!this.value;
        document.getElementById('submit').disabled=!this.value;
        bt.populate_select_mfg();
        //trace(bt.form.vehicle.year);
    });
    if(bt.form.year){
        var _equips=bt.form.year.equip;
        if(typeof _equips["Equipped With"]=='undefined'){
            select_equip[0].options[0]=new Option("Equipped With","");
        }
        for(var i in _equips){
            select_equip[0].options[select_equip[0].options.length]=new Option(i,_equips[i]);
        }
    }else{
        select_equip[0].options.length=1;
        select_equip[0].options[0]=new Option("Equipped With","");
    }
    select_equip[0].disabled=!bt.form.year;
//  select_equip[0].disabled=select_equip[0].options.length<=1;
    select_equip.change();
}

bt.initTestingPage=function(){
    jQuery('#phoneTestingList').each(function(){
        var me=jQuery(this);
        var _S=bt.db.raw.systems;

        // the more efficient way would be to filter out first, then alphabetize them. Computers 
        // are fast these days, though, so change the order if there's a need. Currently alphabetizing
        // before the bt.initTestingPage call is even made.
        bt.current.phones=jQuery.grep(bt.current.phones,function(_phone,index){
            var _tested=false;
            for(var i=0;i<_S.length;i++){
                if((_S[i] in _phone.f) && _phone.f[_S[i]]){
                    _tested=true;
                    break;
                }
            }
            // looks kinda backwards, but we want to see the list of those NOT tested, because they're in testing.
            return !_tested;
        });

        var _currentMFR="";
        for(var i=0;i<bt.current.phones.length;i++){
            var _currentPhone=bt.current.phones[i];
            if(_currentMFR!=_currentPhone.mfr.n){
                _currentMFR=_currentPhone.mfr.n;
                me.append('<div class="clear big">'+_currentMFR+'</div>');
            }
            me.append('<span>'+_currentPhone.n+'</span>');
        }

        jQuery('#phoneCount').html(bt.current.phones.length);
    });
}
bt.set_form_selection=function(){
    if(bt.getQS('vehicle')){
        jQuery('#vehicle').val(bt.getQS('vehicle')).change();
        if(bt.getQS('year')){
            jQuery('#year').val(bt.getQS('year')).change();
            if(bt.getQS('equip')){
                jQuery('#equip').val(bt.getQS('equip')).change();
                if(bt.getQS('mfg')){
                    jQuery('#mfg').val(bt.getQS('mfg')).change();
                    // I don't like putting this in the heart of this function, but it's the easiest way.
                    bt.setupSetupLabels();
                }
            }
        }
    }
}
bt.setupSetupLabels=function(){
    if(bt.pageid=='setup'){
        jQuery('#phoneYear2').html(jQuery('#year :selected').text());
        jQuery('#phoneVehicle2').html(jQuery('#vehicle :selected').text());
        var _equip=jQuery('#equip :selected').text();
        if(_equip!='Equipped With'){
            jQuery('#phoneEquip2').html(" with "+_equip);
        }
    }
}

bt.toggleDisclaimer = function(trigger){
    var disc = $("disclaimer");
    if(disc.style.display != "block"){
        var tempPhones=(('phones' in bt.current)&&('unshift' in bt.current.phones))?bt.current.phones.slice(0):[];
        bt.sortPhones(tempPhones,'alpha');
        var disclaimers=[bt.constants.DEFAULT_DISCLAIMER];
        jQuery(tempPhones).each(function(i){
            if(this.mfr.d!=disclaimers[disclaimers.length-1]){
                disclaimers.push(this.mfr.d);
            }
        });

        // wrap each with paragraph tags
        disclaimers=jQuery.map(disclaimers, function(n, i){
            // if it's blank or just spaces and nbsp, then return null, which means remove from the array of disclaimers.
            return (!n || /^\s*&nbsp;\s*$/.test(n))?null:('<p>'+n+'</p>');
        });

        jQuery('#disclaimerText').html(disclaimers.join(''));
        disc.style.display = "block";
    } else {
        disc.style.display = "none";
    }
    return false;
};
// one off custom footer for bluetooth 'find a phone'
jQuery(document).ready(function(){
  if(jQuery('div#find').length > 0)
    jQuery('div#gFooter').css({'background':'none', 'padding-top':'10px'});
});

// add onClicks so the disclaimer links only pop the disclaimer, and don't add to the URL

jQuery(document).ready(function(){ 
    jQuery("a[href='#disclaimer'],.discClose").click(function(){
    bt.toggleDisclaimer(jQuery(".discTrigger")); 
    return false;    
    });               
});
function extractPageName(hrefString){
    var arr = hrefString.split('/');
    return (arr.length < 2) ? hrefString : arr[arr.length - 2].toLowerCase() + arr[arr.length - 1].toLowerCase();
}

function setActiveMenu(arr, crtPage){
    for (var i = 0; i < arr.length; i++) {
        if (extractPageName(arr[i].href) == crtPage) {
            jQuery(arr[i]).addClass("current");
        }
    }
}

jQuery(document).ready(function(){

    var hrefString = document.location.href ? document.location.href : document.location;
    setActiveMenu(document.getElementById("gFooter").getElementsByTagName("a"), extractPageName(hrefString));
    
    var mailingListEmailValue = jQuery('#NissanMailingListEmail').val();
    var mailingListLabel = jQuery('#NissanMailingListForm label').text();
    var mailingListError = jQuery('#NissanMailingListEmailError').text();
    
    if (mailingListEmailValue != '') {
        jQuery('#NissanMailingListForm label').hide();
    }
    jQuery('#NissanMailingListEmail').focus(function(){
        jQuery('#NissanMailingListForm').removeClass('error');
        if (mailingListEmailValue != '') {
            jQuery('#NissanMailingListForm label').hide();
        }
        else {
            jQuery('#NissanMailingListForm label').text(mailingListLabel).addClass('faded');
        }
    });
    jQuery('#NissanMailingListEmail').blur(function(){
        jQuery('#NissanMailingListForm label').removeClass('faded');
    });
    jQuery('#NissanMailingListEmail').bind('keydown', function(){
        jQuery('#NissanMailingListForm label').hide();
        jQuery('#NissanMailingListForm').removeClass('error');
    });
    
    jQuery('#NissanMailingListForm').submit(function(){
        var mailingListEmailValue = jQuery('#NissanMailingListEmail').val();
        var validate = validateEmail(mailingListEmailValue);
        if (!validate) {
            jQuery('#NissanMailingListForm').addClass('error');
            jQuery('#NissanMailingListForm label').show().text(mailingListError);
            jQuery('#NissanMailingListEmail').val('');
            return false;
        };
            });
    
    function validateEmail(elementValue){
        var emailPattern = new RegExp("^[-A-Z-a-z0-9~!$%^&*_=+}{\'?]+(\.[-A-Z-a-z0-9~!$%^&*_=+}{\'?]+)*@([-A-Za-z0-9_][-A-Z-a-z0-9_]*(\.[-A-Z-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$");
        return emailPattern.test(elementValue);
    }
    
    /*
     * Facebook Event Handler
     */
    window.fbAsyncInit = function() {
        FB.init({
            appId  : '238312155374', 
            status : true, // check login status
            cookie : true, // enable cookies to allow the server to access the session
            xfbml  : true  // parse XFBML    
        });     
        
        // fired when the user clicks on likes
        FB.Event.subscribe('edge.create', function(response) {
             console.log("fb like");
        });
    }    
});

/* disable es shopping tools feedback */
if( location.pathname.indexOf('/buildyournissan/es') > -1 ){
document.write("\n<style>\n");
document.write("#gizmoS { display: none !important } \n");
document.write("</style>\n");
}




