/*

  America.gov Site JavaScript: Misc Functions
  
  America.gov Web Site
  United States Department of State
  Last Edited: Jan 2008 by Darren W Krape (krapedw@state.gov)

*/

// Returns the number only pixel of a given item
var num = function(el, prop) {
  return parseInt($.css(el.jquery?el[0]:el,prop))||0;
};

// Returns the outerHeight of a given item
var outerHeight = function(element) {
  outerWidthResult = element.height() + num(element,'borderTopWidth') + num(element, 'borderBottomWidth') + num(element, 'paddingTop') + num(element, 'paddingBottom') + num(element, ',marginTop') + num(element, 'marginBottom');
  return outerWidthResult;
}

// Returns the outerWidth of a given item
var outerWidth = function(element) {
  outerWidthResult = element.width() + num(element,'borderLeftWidth') + num(element, 'borderRightWidth') + num(element, 'paddingLeft') + num(element, 'paddingRight') + num(element, ',marginLeft') + num(element, 'marginRight');
  return outerWidthResult;
}

$.fn.popUp = function() {
  $(this).click(function () {  
    var hrefLocation = $(this).attr("href");
    window.open(hrefLocation, 'popup', 'toolbar=0,scrollbars=yes,location=1,statusbar=0,menubar=1,resizable=1,width=820,height=580,left=20,top=20');
    return false;
  });
};

//Swaps out brightcove media elements (such as a video or photo gallery component)
$.fn.brightcoveToggle = function() {

  if( $("#video").attr("id") ) var brightcoveType = "video"; else var brightcoveType = "story";

  var playerId = (location.hash).substring(1);

  if (playerId) {
    $.fn.brightcoveToggle.swap(playerId,brightcoveType);
  } else if ( $(".player").attr("class") ) {
    var playerId = ($(".collection-box li a:eq(0)").attr("href")).substring(1);
    $.fn.brightcoveToggle.swap(playerId,brightcoveType);
  }

  if (playerId){ $.fn.brightcoveToggle.swap(playerId,brightcoveType); }

  this.each(function() {

    $(this).find(".collection-box li").click(function () {
      var playerId = ($(this).find("a:eq(0)").attr("href")).substring(1);
      $.fn.brightcoveToggle.swap(playerId,brightcoveType);
      return false;
    });

  });
};

$.fn.brightcoveToggle.swap = function(playerId,brightcoveType) {

  if(brightcoveType == "video")
    $(".player").html('<OBJECT classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" WIDTH="400" HEIGHT="349" id="americaVideoPlayer4"><PARAM NAME=movie VALUE="http://www.america.gov/americaVideoPlayer4.swf?playerId=' + playerId + '&flashId=americaVideoPlayer4"><PARAM NAME=quality VALUE=high><PARAM NAME=bgcolor VALUE=#FFFFFF><PARAM NAME=allowScriptAccess VALUE=always /><EMBED src="http://www.america.gov/americaVideoPlayer4.swf?playerId=' + playerId + '&flashId=americaVideoPlayer4" quality=high bgcolor=#FFFFFF WIDTH="400" HEIGHT="349" NAME="americaVideoPlayer4" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="always"></EMBED></OBJECT>');
  else
    $(".player").html('<embed src="http://mstories.vo.llnwd.net/o1/federated/shell.swf?storeID=bcmeta&expID=' + playerId + '&flashID=flashObj&proxyURL=http://dp.storymaker-se.com/DaliDataProxy/x.aspx" bgcolor="#ffffff" base="http://admin.brightcove.com" name="flashObj" width="616" height="325" seamlesstabbing="false" type="application/x-shockwave-flash" swLiveConnect="true" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" wmode="transparent"></embed>');    

  parent.location.hash = playerId;
};

// Tabbed Displays in which the tab is on the left (calendars, etc)
$.fn.tab = function() {
  this.each(function(){
    var columnWidth = $(this).parent().width();
    if(columnWidth < 600) var column = "narrow"; else var column = "wide";
    $(this).find(".box-body:eq(0)").addClass("modified " + column);

    var tabHeight = outerHeight($(this).find(".tab-nav:eq(0)"));
    var i = 0;
    while ((i + 1) <= $(this).find(".tab-content").length) {
      if(i != 0) {
        var moveTabHeight = tabHeight * i;
        $(this).find(".tab-content:eq(" + i + ")").css({marginTop:-moveTabHeight});
      }
      i++;
    };

  });
  $(".tab-nav").click(function () {  
    $(this).parent().parent().find("li").removeClass("active");
    $(this).parent().addClass("active");
    return false;
  });
};

//Tabbed Collection Boxes (Such as on the video, photo gallery or webchat pages)
$.fn.tabbedCollection = function() {

  var p = $(this);
  $(p).find(".collection-box li:eq(0)").addClass("active");

  $(p).find(".elements").hide();
  $(p).find(".elements:eq(0)").show();

  $(p).find(".collection-box li").click(function () {
    $(".collection-box li").removeClass("active");
    $(this).addClass("active");
  });

  $(p).find(".collection-nav li").click(function () {  
    $(this).parent().find("li").removeClass("active");
    $(this).addClass("active");

    var elementList = $(this).find("a").attr("href");
    $(p).find(".elements").hide();
    $(p).find(elementList).show();

    return false;
  });
};

// Search Text Hint Show/Hide
// By Remy Sharp: http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
$.fn.hint = function () {
  return this.each(function (){
    var p = $(this); 
    var title = p.attr('title'); 
    if (title) { 
      p.blur(function (){ if (p.val() == '') { p.val(title); p.addClass('blur'); } });
      p.focus(function (){ if (p.val() == title) { p.val(''); p.removeClass('blur'); } });
      p.parents('form:first()').submit(function(){ if (p.val() == title) { p.val(''); p.removeClass('blur'); } });
      p.blur();
    }
  });
}

//Swap web chat elements from the hidden list
$.fn.webchatSwap = function () {
  var p = this;
  $(p).find("#webchat-items").hide();

  var elementId = location.hash;
  if (elementId) {
    $.fn.webchatSwap.swap(elementId,p);
  } else {
    var elementId = "#" + $(p).find("#webchat-items div:eq(0)").attr("id");
    $.fn.webchatSwap.swap(elementId,p);
  }

  $(this).find(".collection-box li").click(function () {  
    var elementId = $(this).find("a:eq(0)").attr("href");
    $.fn.webchatSwap.swap(elementId,p);
    parent.location.hash = elementId;
    return false;
  });
}

$.fn.webchatSwap.swap = function(elementId,p) {
  $(p).find(".webchat-current").empty();
  $(elementId).clone().appendTo($(p).find(".webchat-current"));
};

//Quiz Function
$.fn.quiz = function () {
  p = this;
  var questionCurrent = 0;
  var questionsTotal = $(p).find(".question").length;
  $(p).find(".box-body").append("<div class='result'><p class='title'>Please choose an answer from the above choices.</p><p class='description'></div><div class='details'><span class='status'>Question 1 of " + questionsTotal + "</span> <a href='#' class='next button'>Next Question</a></div>");
  $(p).find(".question").slice(1,questionsTotal).hide();
  
  $(p).find(".answers li").click(function () {
    $(p).find(".result").show();
    if($(this).hasClass("correct")) {

      $(this).addClass("clicked-correct");
      $(p).find(".title").text("Congratulations, you are correct!").removeClass("incorrect").addClass("correct");
      $(p).find(".next").show();

      if((questionCurrent + 1) == questionsTotal) {
        $(p).find(".details .next").addClass("end").text("Thank you for taking our quiz");
        $(p).find(".status").text("Quiz End");
      }
      
      $(p).find(".question:eq(" + questionCurrent + ") .answers li:not(.correct)").hide();
     $(p).find(".result .description").replaceWith($(p).find(".question:eq(" + questionCurrent + ") .description"));

    } else {
      $(this).addClass("clicked-incorrect");
      $(p).find(".result .title").text("Sorry, you are incorrect. Please make another choice.").removeClass("correct").addClass("incorrect");
    }

    return false;
  });

  $(p).find(".next").click(function () {
    if(!((questionCurrent + 1) == questionsTotal)) {
      questionCurrent = questionCurrent + 1;
      $(p).find(".title, .result .description").text("");
      $(p).find(".result, .question, .next").hide();
      $(p).find(".status").text("Question " + (questionCurrent + 1) + " of " + questionsTotal);
      $(p).find(".question:eq(" + questionCurrent + ")").show();
    }
    return false;
  });
}

$(function() {

  $(".tabbed").tab();
  $(".search-text").hint();

  $("#webchats").webchatSwap();
  $(".tabbed-collection").tabbedCollection(); //Top tabs function, active state on content elements. Used for video, webchats, photos
  $("#video .tabbed-collection, #photo .tabbed-collection").brightcoveToggle();

  $(".quiz").quiz();

  $("a[href*='#popup']").popUp();

  $(".print a").click(function () { window.print(); return false; });
  $(".back").click(function () { history.go(-1); return false; });

  //Preserves the mouse-over on top-level menu elements when hovering over children
  $("#menu ul ul").each(function(i){
    $(this).hover(function(){
      $(this).parent().find("a").slice(0,1).addClass("maintainHover"); 
    },function(){ 
      $(this).parent().find("a").slice(0,1).removeClass("maintainHover"); 
    });
  });

  // IE6 Fix: Drop-down fix due to lack of support for :hover on list elements
  if($.browser.msie && ($.browser.version < 7)) {
    $("#menu ul").each(function(i){
      $(this).find("li").hover(function(){
        $(this).find("ul").addClass("ieHover");
      },function(){ 
        $(this).find("ul").removeClass("ieHover"); 
      });
    });
  }

  // IE6 Fix: Corrects IE6' lack of :first-child support 
  if($.browser.msie && ($.browser.version < 7)) {
    //$("#index .package-list li:last-child").css({ border: "none", marginBottom: "0", paddingBottom: "0" }); <-- Not needed?
    $("#footer li:last-child").css({ border: "none", marginRight: "0", paddingRight: "0" });
    $("#package .rss-items li:last-child").css({ border: "none" });
  }

  //Zebra Striping for tables
  $("tr:nth-child(odd)").addClass("odd");
  
});

