
var TITLE = ' | Justine Petersen';
var PAGE_FADE_DELAY = 500;
var CACHE_AJAX_PAGES = true;
var pageCache = {};
var historyData = {};
var SUB_NAV_LOADER;

var homeFeatureLinks = new Array();
homeFeatureLinks['nickco'] = '/small_business/start-up_businesses/';
homeFeatureLinks['minerva'] = '/small_business/existing_businesses/ ';
homeFeatureLinks['jerry'] = '/homeownership/first-time_home_buyers/';
homeFeatureLinks['ken'] = '/small_business/existing_businesses/';
homeFeatureLinks['darrow'] = '/credit_building/credit_building_tools/';


function initHomePageTwitter() {
  var tweetsEl = $("#tweet-data-wrapper");
  $.ajax({
    url : "http://twitter.com/statuses/user_timeline/justinepetersen.json?count=1&callback=?",
    dataType : "json",
    timeout:15000,
    success : function(data)
    {
      var newText ='';
      //for (i=0; i< data.length; i++)
      for (i=0; i< 1; i++)
      {
        var date = data[i].created_at;
        var text = data[i].text.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i,'<a target="_blank" href="$1">$1</a>').replace(/(^|\s)@(\w+)/g,'$1@<a href="http://www.twitter.com/$2">$2</a>').replace(/(^|\s)#(\w+)/g,'$1<a target="_blank" href="http://twitter.com/search?q=%23$2">#$2</a>');
        newText +=('<div id="tweet-message">' + text +"</div>");
        newText +=('<div id="tweet-date">Posted ' + prettyDate(date) +"</div>");
        //newText += '<b>posted ' + (prettyDate(date) +": </b>"+text);
      }
      tweetsEl.html(newText);
      tweetsEl.hide().fadeIn(800);
    },
    error : function()
    {
      tweetsEl.html("Error: Twitter could not be initialized.");
    }
  });
}

var addEvent = (function () {
  if (document.addEventListener) {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.addEventListener(type, fn, false);
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  } else {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  }
})();

function log(s)
{
  var onscreenLog = false;
  try {console.log(s)} catch (e) {}
  if (onscreenLog) {
    var logEl = $('#anthumLogContent');
    if (logEl.length == 0)
    {
      logEl = $('<div id="anthumLog" ontouchstart="$(this).remove()" style="border-color: #dddddd; border-style: solid; border-width: 1px 1px 0 0; padding: 2px; position: fixed; bottom: 15px; left: 0px;background: black; color: green; font-size: 11px; font-family: arial;">\
                 <div style="color: #aaaaaa !important; text-align: right;font-size: 9px"><a style="color: #aaaaaa !important; " href="javascript:void(0)" onclick="$(\'#anthumLog\').remove()">clear</a></div>\
                 <div id="anthumLogContent" style="padding: 5px;"></div>\
               </div>');
      $('body').append(logEl);
      logEl = $('#anthumLogContent');
    }
    logEl.append(s+'<br />');
  }
}

// uses DIV start/stop markers to format the boxes
// @o jq element to search within
function formatWideContentBoxes(o) {
  var start= $('div.wide_box_start');
  var end= $('div.wide_box_end');
  //content = start.nextUntil('div.wide_box_end');
  //content.wrapAll('<div class="wideBox" />');
  start.remove();
  end.remove();
}

function initSubNavLoader() {
  if (false) { //history.pushState) {
    // create html5 loader to handle dynamic pages
    SUB_NAV_LOADER = new SubNavLoader();
    SUB_NAV_LOADER.init();
  }
}

// HTML5 loader for subnav pages. Don't use on non-html5 browsers
var SubNavLoader = function() {
  var histories; // history of text shown, indexed by url
  var pageContent; // div of content
  var pageTitle; // div of page title <h1>
  var ul; // <ul> containing the <a> subnav links
  
  this.init = function() {
    histories = [];
    pageContent = $('#content .left');
    pageTitle = $('#pageTitle');
    ul = $('#subNavList');

    ul.children('li').children('a').click(function() {
      return loadPage($(this));
    });
    addEvent(window, 'popstate', function (event) {
      if (event.state) {updatePageContentFromHistory([event.state]);}
    });    
  }
  
  
  var loadPage = function(a) {
    ul.children('li').removeClass('active');
    a.parent('li').addClass('active');
    var url = a.attr('href');
    var title = (a.children('img').length !=0)? a.children('img').attr('alt') : a.text();
    saveCurrentState();
    history.pushState(url,title,url);
    updatePageContent(title,title);
    return false;
  }

  var updatePageContentFromHistory = function(url) {
    var hist = histories[url];
    updatePageContent(hist.title,hist.content);
  }
  
  var updatePageContent = function(title,content) {
    document.title = title + " | Justine Petersen";
    pageTitle.text(title);
    pageContent.html(content);
  }
  
  var saveCurrentState = function() {
    histories[window.location] = {"title": pageTitle.text(), "content" : pageContent.html()};
  }
}

// set spacing in subnav <ul>
function initSubNavMenu() {
  var ul = $('#subNavList');
  
  var lis = ul.children('li');
  var imgs = lis.children('a').children('img');

  //log('images: '+imgs.length);
    
  if (ul.length +=0 && lis.length !=0)
  {
    if (imgs.length == 0) {
      setSubNavMenuWidth(ul,lis);
      ul.css('visibility','visible');
    } else {
      // wait for images to load and set their width
      var imgsLoaded = 0;

      imgs.each(function() {
        $(this).bind('load',function() {
          imgsLoaded++;
          if (imgsLoaded == imgs.length) {
            setSubNavMenuWidth(ul,lis);
            ul.hide().css('visibility', 'visible').fadeIn(300);
          }
        }).bind('error',function() {
          imgsLoaded++;
          log('could not load image: '+$(this).attr('src'));
          if (imgsLoaded == imgs.length) {
            setSubNavMenuWidth(ul,lis);
            ul.hide().css('visibility', 'visible').fadeIn(300);
          }
        });
      });
    }
  }
}


function changeSubnavPage(a) {
  if (!history.pushState) {
    return true;
  } else {

    var url = a.attr('href');
    var title = (a.children('img').length !=0)? a.children('img').attr('alt') : a.text();
    var contentDiv = $('#content .left');

    if (CACHE_AJAX_PAGES) {
      pageCache[window.location] = contentDiv.html();
    }
    
    //log(title+': '+url);
    document.title=title+TITLE;
    $('#pageTitle').text(title);
    a.parent('li').parent('ul').children('li').removeClass('active');
    a.parent('li').addClass('active');


    if (CACHE_AJAX_PAGES && pageCache[url] != null) {
      contentDiv.fadeOut(PAGE_FADE_DELAY,function() {
        setNewPageContent(url,contentDiv,pageCache[url]);
        historyData[url] = {"title":document.title, "content":pageCache[url]};
        history.pushState(url,title,url);
      });
    } else
    {
      contentDiv.fadeOut(PAGE_FADE_DELAY,function() {
        $.ajax({
          url: "/ajax/page?callback=?",
          type: "POST",
          dataType: 'html',
          timeout: 8000,
          data: {"url":url},
          success: function(data) {
            //log('success in page load');
            //log(data);
            setNewPageContent(url,contentDiv,data);
            historyData[url] = {"title":document.title, "content":data};
            history.pushState(url,title,url);
          },
          error: function(o, msg, e) {
            setNewPageContent(url,contentDiv,'Page could not be loaded. Please try again: '+msg);
            //history.pushState(title,title,url);
          }
        });
      });
    }
    return false;
  }
}


function setNewPageContent(url,o,data) {
  o.html(data);
  o.fadeIn(PAGE_FADE_DELAY).show();
}

function setSubNavMenuWidth(ul,lis) {
  var w = ul.width();
  var lisWidth = 0;
  var space;
  
  lis.each(function() {
    lisWidth += $(this).width();
    //log('lisWidth: '+lisWidth);
  });
  space = w-lisWidth;
  lis.css('margin-right', (space/(lis.length-1))+'px');
  lis.last().css('margin-right','0');
}

// @el must have rel attribte 
function showHomeFeatureTab(el) {
  var id = $(el).attr('rel');
  $('#header').attr('class','').addClass('bg-'+id+'-on');
  $('#home-feature-tabs td').removeClass('active').filter('[rel="'+id+'"]').addClass('active');
  $('.home-feature-landing-button').hide();
  $('#home-feature-landing-button-'+id).show();
  $('.home-feature-content-detail').hide();
  $('#home-feature-detail-buttons').hide();
}

// clicked once a tab is active
function showHomeFeatureDetail(el) {
  var id = $(el).attr('rel');
  $('.home-feature-landing-button').hide();
  $('.home-feature-content-detail').hide().filter('[rel="'+id+'"]').show();
  $('#home-feature-detail-buttons').show();
  $('#header').attr('class','bg-'+id+'-over');
  $('#home-feature-button-back').attr('rel',id);
  
  var moreLink = (homeFeatureLinks[id])? homeFeatureLinks[id] : "javascript:void(0)";
  $('#home-feature-button-more').attr('href',moreLink);
}


function showFeatureContent(i) {
  // take EE index down one
  i--;

  var features = new Array();
  features['nikko'] = {'bgClass':''};
  features['minerva'] = {'bgClass':''};
  features['jerry'] = {'bgClass':''};
  features['ken'] = {'bgClass':''};
  features['darrow'] = {'bgClass':''};

  $('#home-feature-tabs td').removeClass('active');
  $($('#home-feature-tabs td')[i]).addClass('active');
  $('#home-feature-content').fadeOut(500, function() {
    var content = $('.feature-content');
    log(content.length);
    content.hide();
    $(content[i]).show();
    $(this).fadeIn(500);
  });
}


$(document).ready(function() {

  $('#scroll-test').liScroll();
  if($('#news-ticker-wrapper').length > 0) {
    $("#news-ticker-list").liScroll({travelocity: 0.04});
  }
});

