$.ts = new Object ;
$.ts.popup = new Object ;
$.ts.logos = new Object ;
$.ts.roles = new Object ;
$.ts.credit = new Object ;


$.ts.firstAncestorThat = function(node, predicate) {
  if (node.parentNode == null) { return null ; }
  else if (predicate(node.parentNode)) { return node.parentNode ; }
  else { return $.ts.firstAncestorThat(node.parentNode, predicate) ; }
}  

$.ts.hasGI = function(node, gi) {
  return ((node.nodeName).toLowerCase() == gi) ;
}

$.ts.popup.greyout = function() {
  $("body").children().not("#popupframe").addClass("greyout") ;
}  

$.ts.popup.displayPage = function(url) {
  $('#popupframe').css("top", $(document).scrollTop() + ($(window).height()-$('#popupframe').height())/2).fadeIn(400, $.ts.popup.greyout) ;
//  if (url != $.ts.popup.currentUrl) {
    try {
      $('#content').load(url + " div.popup>div", $.ts.popup.showNewFirst) ;
    } catch(ex) {
      alert("Trouble loading content: " + ex ) ;
      $('div#content').html("<h1>Content Not Loaded</h1>") ;
    } finally {
      $.ts.popup.currentUrl = url ;
    }
//  } else {
//    $.ts.popup.showFirst() ;
//  }
}

$.ts.popup.showNewFirst = function(response, status, xhr) {
  if (status != "error") {
    $('div#content>div>img').wrap("<p class='centeredImage'></p>") ;
    $.ts.popup.showFirst() ;
  } else {
    $('div#content').html("<h1>Not Found. (" + status + ")</h1>") ;
  }
}

$.ts.popup.showFirst = function() {
  $('div#content').children().hide() ; 
  $('div#content>div:first').show() ;
  $.ts.popup.handleFirstAndLast() ;
}

$.ts.popup.showPrevious = function() {
  var currentShown = $('div#content>div:not(:hidden)').get(0) ;
  var position = $('div#content>div').index(currentShown)
  var toShow = (position > 0) ?  
                  $('div#content>div').get(position - 1) : 
                  $('div#content>div:last').get(0) ;
  $(currentShown).hide() ;
  $(toShow).show() ;
  $.ts.popup.handleFirstAndLast() ;
}

$.ts.popup.showNext = function() {
  var currentShown = $('div#content>div:not(:hidden)').get(0) ;
  var toShow = ($('div#content>div:not(:hidden) ~ div:first').size() > 0) ?  
                  $('div#content>div:not(:hidden) ~ div:first').get(0) : 
                  $('div#content>div:first').get(0) ;
  $(currentShown).hide() ;
  $(toShow).show() ;
  $.ts.popup.handleFirstAndLast() ;
}

$.ts.popup.returnToMainPage = function() {
  $("#content").html("<div></div>");
  $("#popupframe").fadeOut(400) ;
  $("body *").removeClass("greyout") ;
}

$.ts.popup.handleFirstAndLast = function() {
  if ( $('div#content>div:last').is(':hidden') ) {
    $('#next').show();
  } else {
    $('#next').hide();
  } 
  if ( $('div#content>div:first').is(':hidden') ) {
    $('#previous').show();
  } else {
    $('#previous').hide();
  } 
}

$.ts.logos.instrument = function() {

  $("img[src*=companylogos/]").not("[class*=casestudy]").addClass("logo").attr("id",function() {
     var path = $(this).attr("src") ;
     var filenameRegex = /.*\/([^\/]+)\.[^\/\.]*/ ;
     var result = path.match(filenameRegex) ;
     if (result != null ) {
       return result[1] ;
     } else {
       return "error"
     }
   } )
  $("img[id=error]").removeAttr("id") ;
   
  var logotable = $.ts.firstAncestorThat($("img.logo:first").get(0), 
                                         function(node) { return $.ts.hasGI(node, 'table') }) ;
  $(logotable).attr("id", "logotable") ;
    
  $("#logotable td").filter(function() { return $(this, "img.logo") }).
                                 mouseover(function() {
                                 var logo = $(this).find("img.logo").get(0) ;
                                 $.ts.logos.displayBalloon(logo) ;
                                 return false ;
                               }) ;
                               
  $("table:first").mouseover(function() {
                             $.ts.logos.hideBalloon() ;
                             return false ;
                             }) ;
}

$.ts.logos.displayBalloon = function(logo) {
  if (logo.id != $.ts.logos.currentLogo) {
    try {
      var url = "portfolio/balloons/balloondata.html" ;
      $('#balloon').load(url + " div#" + logo.id, function() {$.ts.logos.showNewBalloon(logo)} ) ;
      $.ts.logos.currentLogo = logo.id ;
    } catch(e) {
      // $("<h1>Trouble loading balloon. " + e + "</h1>").prependTo($("body")) ;
    }
  } else {
    $.ts.logos.showBalloon(logo) ;
  }
}

$.ts.logos.showNewBalloon = function(logo) {
  $("<p class='popupLink'>view samples &gt;</p>").insertAfter($("#balloon h1.hasLink")).click(function() { 
                                   $.ts.popup.displayPage("portfolio/" + logo.id + ".html") 
                                 }) ;
  $.ts.logos.showBalloon(logo) ;
}

$.ts.logos.showBalloon = function(logo) {
  var enclosing_td = $.ts.firstAncestorThat(logo, function(node) { return $.ts.hasGI(node, 'td') }) ;
  var left_td = $(enclosing_td).parent().find('td').filter(':first') ;
  var td_width = $(enclosing_td).outerWidth() ;
  var position = $(left_td).offset() ;
  position.left = position.left + 0.5 * td_width 
  var width = td_width + 5 ;
  var yoverflow = (position.top - $(document).scrollTop()) + $("#balloon").height() - $(window).height() ;
  var correctedTop = (yoverflow > 0) ? 
                        (position.top - yoverflow) : 
                        Math.max(position.top, $(document).scrollTop()) ;
  if (position != null) {
    $("#balloon").css("left", position.left).css("top", correctedTop).css("width", width) ;
    $("#balloon").show() ;
  } else {
    $("#balloon").css("left", "40%").css("top", "40%") ;  
    $("#balloon").show() ;
  }
}


$.ts.logos.hideBalloon = function() {
  $("#balloon").hide() ;
}

$.ts.roles.instrument = function() {
  $.getJSON("ts/roleData.json","",$.ts.roles.instrumenth) ;
}

$.ts.roles.instrumenth = function(roleData, status) {
  var wrappedBs = $($.ts.firstAncestorThat($("td i").filter(':contains("role per project")').get(0),
                                      function(node) { return $.ts.hasGI(node, 'td') })).find('b') ;
  wrappedBs.addClass('role').hover(function() {  
                    $(this).addClass('highlight') ;
                    $("img.logo").addClass('whiteout') ;
                    var logonames = roleData[$(this).attr('id')] ;
                    for (var count = 0; count < logonames.length; count++) {
                      theName = logonames[count];
                      $("img.logo").each(function(n) {
                        var result = $(this).attr('src').match(theName) ;
                        if (result != null) {
                          $(this).removeClass('whiteout') ;
                        }
                      })
                    }
                  },
                  function() { 
                    $(this).removeClass('highlight') ;
                    $(".logo").removeClass('whiteout')
                  }) ;
}

$.ts.credit.hideCredit = function() {
  $("#balloon").hide() ;
}

$.ts.credit.showCredit = function() {
  var position = $("#creditLink").offset() ;
  var yoverflow = (position.top - $(document).scrollTop()) + $("#balloon").height() - $(window).height() ;
  var correctedTop = (yoverflow > 0) ? 
                        (position.top - yoverflow) : 
                        Math.max(position.top, $(document).scrollTop()) ;
  $("#balloon").css("left", position.left).css("top", correctedTop) ;
  $("#balloon").show() ;
}

$(document).ready(function() {
  if ($("body#home").get(0) != null) {
    $.ts.credit.hideCredit() ;
    $("#creditLink").click($.ts.credit.showCredit) ;
    $("<div id='closer'><img src='ts/closer.gif' width='18px' /></div>").prependTo("#balloon") ;
    $("#closer").click($.ts.credit.hideCredit) ;
  } else {
    $.ts.popup.currentUrl = '';
    $.ts.logos.currentBalloon = '';
    $("<div id='balloon' />").prependTo($("body")).hide() ;
    $("<div id='popupframe'><div id='content' /><div id='navigation'/><div id='closer'><img src='ts/closer.gif' width='24px' /></div></div>").prependTo($("body")) ;
    $("#popupframe").css("left", ($(window).width() - $("#popupframe").width())/2) ;
    $("<p><span id='controls'><span id='previous'>&lt;&nbsp;previous</span><span id='next'>&nbsp;&nbsp;&nbsp;next&nbsp;&gt;</span></span></p>").prependTo($("#navigation")) ;
    $("#previous").click($.ts.popup.showPrevious) ;
    $("#next").click($.ts.popup.showNext) ;
    $("#return").click($.ts.popup.returnToMainPage) ;
    $("#closer").click($.ts.popup.returnToMainPage) ;
    $("#authentecCaseStudy").click(function() {$.ts.popup.displayPage("portfolio/authentec.html")} ) ;
    $.ts.logos.instrument() ;
    $.ts.roles.instrument() ;
  }
})




