/* 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");
        }
    
});


/* 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");
        }
    
});


// SET Global Variable // 
var flashMajorVer = swfobject.getFlashPlayerVersion().major;
var biPageType;
flashMajorVer > 0 ? biPageType = "Flash" : biPageType = "HTML";
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);


// SET Initial Bi Tag //
    function localZip()
    {
        var e = document.getElementById("localZip").value;
        if (e == "" || isNaN(e)) {
            return false;
        }
        else {
            var link = "http://local.nissanusa.com/zip.aspx?regionalZipCode=" + e + "&vehicle=null&intcmp=Regional.Promo.Homepage.Home.P3"
            location.href = link;
        }
        }
    function locateDealer()
    {
        var lang  = jQuery('body').attr('class');
        if (lang == "es"){
            var link ="/tools/espanol";
        }
        else{
            var link ="/tools";
        }
        
        var e = document.getElementById("zipCode").value;
        
        if (e == "" || isNaN(e)) {
            return false;
        }
        else {
            //crmSetCookie("ZipCode", e, 365);
            if (flashMajorVer < 0) {
                link += "/locate/?zipCode=" + e + "&tool=home.locator&tool=HTML";
            }
            else {
                link += "/locate/?zipCode=" + e + "&tool=home.locator&tool=Flash"
            }
            location.href = link;
        }
    }   
   
  // SALES EVENT NOW : SET Initial Bi Tag //
    function salesZip()
    {
        var e = document.getElementById("salesZip").value;
        
        if (e == "" || isNaN(e)) {
            //e="";
            return false;
        }
        else {
            var lang = jQuery('body').attr('class');
            if (lang == "es") {
                var link = "http://local.nissanusa.com/espanol";
            }
            else {
                var link = "http://local.nissanusa.com";
            }
            
            link += "/zip.aspx?regionalZipCode=" + e + "&vehicle=null&next=Homepage.pfa.year_end_sales.local_offers.Home.button_zip"
            window.open(link);
            
        }
     }
     

    /**
     * Use this for calling local offers on the PFA
     * Pass in the id of the input
     */
    function pfaLocalOffersZip(inputID){
        
        var $inputElement = jQuery("#"+inputID);
        var inputValue    = ($inputElement.val() == "" || isNaN($inputElement.val())) ? "" : $inputElement.val();
        
        if(inputValue == "Enter ZIP" || inputValue == "Ingresa tu C.P." || inputValue !== "" || inputValue == "éƒµé?žå?€è™Ÿ"){
            inputValue == "";
        }

        var lang = jQuery('body').attr('class');
        var link = "";

        if(lang == "es") {
            link = "http://local.nissanusa.com/espanol";
        }else {
            link = "http://local.nissanusa.com";
        }
        
        link += "/zip.aspx?regionalZipCode=" + inputValue + "&vehicle=null";
        
        //add different tracking depending if there's a zip entered
        if(inputValue == ""){
            link += "&next=Homepage.pfa.year_end_sales.local_offers.Home.button_no_zip";
        }else{
            link += "&next=Homepage.pfa.year_end_sales.local_offers.Home.button_zip";
        }
        //location.href = link;
        window.open(link);
    }

    
    
/*
Used for Winter Sales Event, left here for reference
    function salesZip()
    {
        var e =document.getElementById("salesZip").value;
        var link = "http://local.nissanusa.com/zip.aspx?regionalZipCode="+e+"&vehicle=null&next=home.regional_vlp.saleseventpfa.button1."       
        window.open(link);
    }
    */

/* originally this was an on document ready call, but has been changed to be a post-flash nav call */
homepage = {
    globalNavReady : function(){
        //if(window.console){ console.log('global nav ready'); }

        // SET Initial Bi Tag //
        //var initTagName = jQuery('.slide_0').attr('name');
        //crmEvent1({"num":"1", "placement":"Auto", "name":initTagName, "pageType":biPageType, "flashHTML":biPageType});

        // hover icons  
        jQuery("#mainBuild a,#mainQuote a,#mainValue a,#buildAltima a,#getTrade a,#buildFrontier a,#learnJuke a,#exploreLeaf a").blend({speed:300});
        //jQuery("#promoOne a").blend({speed:300});
        //jQuery("#promoTwo a").blend({speed:300});

    }
}



jQuery(document).ready(function($) {


/**                    VIDEO GALLERY LAUNCHER - TEMP
 *_____________________
 *
 */
    jQuery("#yese-video a").videoplayermodal();
    jQuery("#yese-video-2 a").videoplayermodal();
    jQuery("#innovation-for-all-video a").videoplayermodal();
    jQuery("#innovation-for-all-video-2 a").videoplayermodal();
    jQuery("#leaf-birthday-video a").videoplayermodal();
    jQuery("#leaf-birthday-video-2 a").videoplayermodal();
    
    /**
     * Once it hits July 4th show the video links
     */
    var currentDate     = new Date();
    var videoLaunchDate = new Date("July 4, 2011 00:09:00");
    
    if(currentDate > videoLaunchDate){
        jQuery("#innovation-altimaWatch, #innovation-altimaWatch-2").show();
        jQuery(".en #innovation-exploreAltima").removeClass("no-commercial");
    }else{
        jQuery(".en #innovation-exploreAltima").addClass("no-commercial");
    }


/*
 * SLIDE SHOW with CALLBACKS
 * added by Arjay
 */
    var hompageSlideShow = new HomepageSlideShow();

// END SLIDE SHOW
    
    
   /* jQuery("#get-trade-in a,#salesZip,#salesZipButton").click(function (event){
        event.stopPropagation();
    });*/
    
    // mouseover promos
    jQuery('#promoBlocks').children().hover(function() {
        jQuery(this).siblings().find("a").stop().fadeTo(350,0.65);
    }, function() {
        jQuery(this).siblings().find("a").stop().fadeTo(350,1);
    });
    
    // slide span text      
    jQuery('#secList').children().hover(function() {     
        jQuery(this).stop().find("span").animate({ paddingLeft: '14px'});
        jQuery(this).find("img").animate({ opacity: "show" }, "normal");
    },  function() {
        jQuery(this).stop().find("img").animate({ opacity: "hide" }, 120);
        jQuery(this).find("span").animate({ paddingLeft: '0px'});  
    });
    
    // display local offers zip code field
    jQuery('#secOne:not(.zip-field) a').css({backgroundPosition: "0 0"}).toggle(function(){
          jQuery(this).stop().animate(
              {backgroundPosition: "(0 -5px)"}, 
              {duration:300});
          jQuery(this).find("img,span").animate({ opacity: "hide" }, 200);
          jQuery('#localZipForm').animate({ opacity: "show" }, 500);
          jQuery('#secOne').addClass('zip-field');
    }, function() {
        jQuery(this).animate(
            {backgroundPosition: "(0 0)"}, 
            {duration:300});
        jQuery('#localZipForm').animate({ opacity: "hide" }, 200);
        jQuery(this).find("img,span").animate({ opacity: "show" }, 500);     
        jQuery('#secOne').removeClass('zip-field');
    });
    
    // remove broken links
    jQuery('img').error(function() {
        jQuery(this).remove();
    });
    
    // external sites in a new window
    jQuery("a[rel=external]").attr('target', '_blank');      
    
    //getting the form input values
    var salesZipValue = jQuery("#salesZip").val();
    var localZipValue = jQuery("#localZip").val();
    var zipCodeValue = 'Enter ZIP'; //default : hard coded into the component
    
    // enter zipcode    
    jQuery("#zipCode").bind("focus", function() {
       if (jQuery(this).val() == "Enter ZIP" || jQuery(this).val() == "Ingresa tu C.P." || jQuery(this).val() !== "") {
        jQuery(this).val("");
        jQuery(this).attr('maxlength', 5);
        if (!isNaN(parseInt(jQuery("#salesZip").val())) || !isNaN(parseInt(jQuery("#localZip").val()))) {
            jQuery("#salesZip").val(salesZipValue);
            jQuery("#localZip").val(localZipValue);
        }
       }
    });
    jQuery("#localZip").bind("focus", function() {
         if (jQuery(this).val() == "Enter ZIP" || jQuery(this).val() == "Ingresa tu C.P." || jQuery(this).val() !== "") {
            jQuery(this).val("");
            jQuery(this).attr('maxlength', 5);
            if (!isNaN(parseInt(jQuery("#zipCode").val())) || !isNaN(parseInt(jQuery("#salesZip").val()))) {
                jQuery("#salesZip").val(salesZipValue);
                jQuery("#zipCode").val(zipCodeValue);
            }
        }
    });
    jQuery("#salesZip").bind("focus", function() {
        if (jQuery(this).val() == "Enter ZIP" || jQuery(this).val() == "Ingresa tu C.P." || jQuery(this).val() !== "") {
            jQuery(this).val("");
            jQuery(this).attr('maxlength', 5);
            
            if (!isNaN(parseInt(jQuery("#zipCode").val())) || !isNaN(parseInt(jQuery("#localZip").val())) ){  
                jQuery("#localZip").val(localZipValue);
                jQuery("#zipCode").val(zipCodeValue);
            }
        }
    });
    jQuery("#zipCode,#localZip,.en #salesZip").blur(function() {
            if (jQuery(this).val() == "") {
            jQuery(this).attr('maxlength', 9);
            jQuery(this).val("Enter ZIP");           
        }
    }); 
    jQuery(".es #salesZip").blur(function() {
            if (jQuery(this).val() == "") {
            jQuery(this).attr('maxlength', 15);
            jQuery(this).val("Ingresa tu C.P.");           
        }
    });
    
    jQuery(".cn #salesZip").blur(function() {
            if (jQuery(this).val() == "") {
            jQuery(this).attr('maxlength', 48);
            jQuery(this).val("éƒµé?žå?€è™Ÿ");           
        }
    });


    /**
     * GENERAL ZIP INPUT
     */
    var currentInputValue = "";
    
    jQuery(".zip-input").bind("focus", function() {
         
        currentInputValue = jQuery(this).val();
        
         if (currentInputValue == "Enter ZIP" || currentInputValue == "Ingresa tu C.P." || currentInputValue == "éƒµé?žå?€è™Ÿ") {
            jQuery(this).val("");
            jQuery(this).attr('maxlength', 5);
            if (!isNaN(parseInt(jQuery(this).val())) || !isNaN(parseInt(jQuery(this).val()))) {
                jQuery(this).val(currentInputValue);
            }
        }
    })
    .bind("blur", function(){
        if (jQuery(this).val() == "") {
            jQuery(this).val(currentInputValue);
            jQuery(this).attr('maxlength', 50);
        }
    })
    .keypress(function(e) { 
        if(e.which == 13) { 
            pfaLocalOffersZip(jQuery(this).attr("id"), "");
        }
        else if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
            return false;
        }
    });;
    
    
    
    // zip code fields
    jQuery("#zipCode").keypress(function(e) { 
        if(e.which == 13) { 
            locateDealer();
        }
        else if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
            return false;
        }
    }); 
    jQuery("#localZip").keypress(function(e) { 
        if(e.which == 13) { 
            localZip();
        }
        else if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
            return false;
        }
    });
        jQuery("#salesZip").keypress(function(e) { 
        if(e.which == 13) { 
            salesZip();
        }
        else if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
            return false;
        }
    });
    
    
    
/* WSE
jQuery("#salesZip").attr('value', 'Enter ZIP');
        
        jQuery("#salesZip").focus(function () {
            //if (jQuery(this).val() == "Enter ZIP") {
                jQuery(this).val("");
                jQuery(this).attr('maxlength', 5);
            //}
        });
        jQuery("#salesZip").blur(function () {
            if (jQuery(this).val() == "") {
                jQuery(this).attr('maxlength', 9);
                jQuery(this).val("Enter ZIP");
            }
        });     
        
        // enter key takes you to Sales event
        jQuery('#salesZip').bind('keypress', function(e) {
             if(e.keyCode==13){
                salesZip();
            }
            else if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
                return false;
            }
        });*/
        
    // swap flash-only links for alert message
    if (biPageType == "HTML" ) {
        jQuery('.no-flash').attr({
            'href' : '#',
            'rel' : 'popup-flash-install',
            'class' : 'poplight?w=400'
        });
        
        //to be removed when we are able to redo homepage to properly support non-flash 
        jQuery('#linkFarm .linkfarm').hide();
    }
        
    // When you click on a link with class of poplight and the href starts with a # 
    jQuery('a[class*=poplight]').click(function() {
        var popID = jQuery(this).attr('rel'); //Get Popup Name
        var popURL = jQuery(this).attr('href'); //Get Popup href to define size
        var popW = jQuery(this).attr('class'); 
                
        // Pull Query & Variables from href URL
        var query= popW.split('?');
        var dim= query[1].split('&');
        var popWidth = dim[0].split('=')[1]; //Gets the first query string value
 
        // Fade in the Popup and add close button
        jQuery('#' + popID).fadeIn().css({ 'width': Number( popWidth ) });
        
        // Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
        var popMargTop = (jQuery('#' + popID).height() + 80) / 2;
        var popMargLeft = (jQuery('#' + popID).width() + 80) / 2;
        
        // Apply Margin to Popup
        jQuery('#' + popID).css({ 
            'margin-top' : -popMargTop,
            'margin-left' : -popMargLeft
        });
        
        // Fade in Background
        var fadeHeight = jQuery(document).height();

        jQuery('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
        
        // Check for IE6
        if( jQuery.browser.msie && parseInt(jQuery.browser.version) <= 6 ) { 
            jQuery('#fade').css({'height' : fadeHeight});
        }
        
        // Check for Apple products
        if (agentID) {
            jQuery('#fade').css({'height' : fadeHeight}); 
        }       
        
        jQuery('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer         
        return false;
    }); 
    
    // Close Popups and Fade Layer
    jQuery('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
        jQuery('#fade , .popup-block').fadeOut(); //fade them both out
        jQuery('#fade').remove();
        return false;
    });
    
    //alert(isFlashRedirect);
    var isFlashRedirect = getQueryParam("flashredirect");
    if(isFlashRedirect == "true"){
        popFade(isFlashRedirect);
    }
    
    // MouserOver Global Nav Fade
    function popFade(e){
        var fadeHeight = jQuery(document).height();
        var ee = e;
        var ipad = navigator && navigator.platform && navigator.platform.match(/^(iPad|iPod|iPhone)jQuery/) ? ipad = "true" : ipad = "false";
        if(ee=="true"){     
            if(ipad == "false"){                                
                jQuery('#popup-flash-install').fadeIn().css({ 'width': '400px' });   
                var popMargTop = (jQuery('#popup-flash-install').height() + 80) / 2;
                var popMargLeft = (jQuery('#popup-flash-install').width() + 80) / 2; 
                // Apply Margin to Popup
                jQuery('#popup-flash-install').css({ 
                    'margin-top' : -popMargTop,
                    'margin-left' : -popMargLeft
                });                 
            }else{
                jQuery('#popup-flash-ipad').fadeIn().css({ 'width': '400px' });  
                var popMargTop = (jQuery('#popup-flash-ipad').height() + 80) / 2;
                var popMargLeft = (jQuery('#popup-flash-ipad').width() + 80) / 2;    
                // Apply Margin to Popup
                jQuery('#popup-flash-ipad').css({ 
                    'margin-top' : -popMargTop,
                    'margin-left' : -popMargLeft
                });     

            }
        }
        
            jQuery('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
            if( jQuery.browser.msie && parseInt(jQuery.browser.version) <= 6 ) { 
                jQuery('#fade').css({'height' : fadeHeight});
            }
            jQuery('#fade').css({'filter' : 'alpha(opacity=20)', 'z-index':'500'}).fadeIn(); //Fade in the fade layer        
            jQuery('#movFlashGlobalNav').css({"z-index":"25000"});
    
        
    }
    
       
    jQuery('#movFlashGlobalNav').mouseover(function(){
        popFade();
    });
    jQuery('#movFlashGlobalNav').mouseout(function(){
        jQuery('#fade').fadeOut(500);jQuery('#fade').remove();
    });

});  

function setBannerListImages(){
    var bannerElement = jQuery('#banner-window > li');
    var slideElement = jQuery('#banner-desc > li');
    var arrayBannerImages = [];
    jQuery('#banner-window > li').css({backgroundPosition:'99999em 99999em'});
    jQuery('#banner-content, #banner-desc, #banner-desc > li').height(770);
    for (i = 0; i < bannerElement.length; i++) {
        arrayBannerImages.push(jQuery(bannerElement[i]).css('backgroundImage'));
    }
    for (j = 0; j < slideElement.length; j++ ){
        jQuery(slideElement[j]).css({
            background: '' + arrayBannerImages[j] + ' no-repeat -118px -75px'
        });
    }
}   
function setBgrPosition(){
    var wwidth = jQuery(window).width();
    if (wwidth < 966) {
        setBannerListImages();
    } else {
        jQuery('#banner-window > li').css({backgroundPosition:'top center'});
    }
}  

// Query String to get the query variables from the url
function getQueryVariable(variable) 
{ 
  var query = window.location.search.substring(1); 
  var vars = query.split("&"); 
  for (var i=0;i<vars.length;i++) 
  { 
    var pair = vars[i].split("="); 
    if (pair[0] == variable) 
    { 
      return pair[1]; 
    } 
  } 
  //alert('Query Variable ' + variable + ' not found'); 
}

// To check for the respective PFA's
var urlNo = getQueryVariable('pfa');
// alert('The pfa number you entered is = ' + urlNo);



/* ------------ DOM READY ------------- */
jQuery(function(){
    setBgrPosition();
    jQuery(window).resize(function(e){
        setBgrPosition();
    });
    
   /* ------------ NAV ------------- */   
   var position = 0;
    jQuery('#feedUp').bind('click', function(){
        
        
        if(position <= 1){
            jQuery('#feedUp').css({'color': '#ccc'});
            jQuery('#feed').animate({
                'top': '0px'
            }, 200, 'swing');
            position = 0;
        }
        else if (position > 1) { 
            jQuery('#feed').animate({
                'top': ((position-1)*46)*-1
            }, 200, 'swing');
            jQuery('#feedUp, #feedDown').css({'color': '#666'});
           position--;

        } else {
            jQuery(this).css({
                'cursor': 'pointer',
                'color': '#ccc'
            });
            return;
        }
    });
    jQuery('#feedDown').bind('click', function(){
        
        var max = jQuery('.tweet').length - 1;
        
        
        if (position == max){
            jQuery('#feed').stop(true).animate({
                'top': (position*46)*-1
            }, 200, 'swing' );
            jQuery('#feedDown').css({'color': '#ccc'});
            position = max;
        }
        else if (position < max) {
            jQuery('#feed').stop(true).animate({
                'top': ((position+1)*46)*-1
            }, 200, 'swing' );
            jQuery('#feedUp, #feedDown').css({'color': '#666'});
            position++;
            
        }
        else {
            jQuery(this).css({
                'cursor': 'pointer',
                'color': '#ccc'
            });
            return;
        }
    });
    /* ------------ END NAV ------------- */ 
    
}); //end dom ready

function getTwitterFeed(feedUrl, maxToShow){
    var max = maxToShow;
    var twitterUrl = feedUrl;
    ///********** PARSE JSON ********** \\\
    jQuery.ajax({
        url: twitterUrl,
        cache: false,
        dataType: 'json',
        timeout : 8000,
        error: function(jqXHR, textStatus, errorThrown){ 
            jQuery('#feed').html('<p class="tweet error">We\'re sorry. The server is not responding and we are unable to display this message.</p>')
        },
        success: function(feed){
        

            var limit = (max != null || max != undefined) ? max : feed.length;
            if (feed.length > 0) {
                jQuery('#feedNav').fadeIn();
                var html = '';
               jQuery.each(feed, function(i, item){
                  if (i < limit) {
                    var text = item.text;
                    var source = item.source;
                    var time = (jQuery.browser.msie) ? parseTwitterDate(item.created_at) : item.created_at; 
                    html += '<p class="tweet">' + trimContent(text, 200) + '  <em class="timeago"> ' + prettyDate(time) + '</em><a class="intent reply" href="https://twitter.com/intent/tweet?in_reply_to=' + item.id_str + '">Reply</a><a class="intent retweet" href="https://twitter.com/intent/retweet?tweet_id=' + item.id_str + '">Retweet</a></p>';
                  }
                });
                
                jQuery('#feed').html(html);
            } else {
                jQuery('#feed').html('<p class="tweet error">We\'re sorry. The server is not responding and we are unable to display this message.</p>')
            }
        }//end success
    });
};

function trimContent (content, index){
        if (content.length > parseInt(index)) {
            var temp = content.slice(0, index);
            var spaceIndex = temp.lastIndexOf(' ');
            var linkText = temp.slice(0, spaceIndex) + '...';
            linkText = linkText.replace(/((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):[A-Za-z0-9\/](([A-Za-z0-9$_\.\+!\*\(\),;\/\?:@&~=-])|%[A-Fa-f0-9]{2})+(#([a-zA-Z0-9][a-zA-Z0-9$_\.\+!\*\(\),;\/\?:@&~=%-]*))?)/g, '<a href="$1" target="_blank">$1</a>');
            linkText = linkText.replace(/(\s+)@([a-zA-Z0-9_]+)/g, '1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
            return linkText;
        } else {
            var linkText = content;
            linkText = linkText.replace(/((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):[A-Za-z0-9\/](([A-Za-z0-9$_\.\+!\*\(\),;\/\?:@&~=-])|%[A-Fa-f0-9]{2})+(#([a-zA-Z0-9][a-zA-Z0-9$_\.\+!\*\(\),;\/\?:@&~=%-]*))?)/g, '<a href="$1" target="_blank">$1</a>');
            linkText = linkText.replace(/(\s+)@([a-zA-Z0-9_]+)/g, '1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
            return linkText;
        }
    } ;
function parseTwitterDate(text) {
    var newtext = text.replace(/(\+\S+) (.*)/, '$2 $1')
    var date = new Date(Date.parse(newtext)).toLocaleDateString();
    var time = new Date(Date.parse(newtext)).toLocaleTimeString();
    return date +' : ' + time;
};
/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
    //var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
    var date = new Date((time || "").replace(/-/g,"/")),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);
            
    if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31  )
        return;
            
    return day_diff == 0 && (
            diff < 60 && "just now" ||
            diff < 120 && "1 minute ago" ||
            diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
            diff < 7200 && "1 hour ago" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
        day_diff == 1 && "Yesterday" ||
        day_diff < 7 && day_diff + " days ago" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
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;
        };
            });
            
    var partsLink = jQuery('#cat2 ul li a')[4];
    if (partsLink !== undefined){
    jQuery(partsLink).click(function(e){
        
        e.preventDefault();
        try{
            crmEvent600();
        }catch(e){}
        var endLink = jQuery(this).attr('href');
        setTimeout(function(){
            window.open (endLink);
         },500); 
    }); 
    }
    


 
    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);
    }
});
 
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");
}




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");
}




