﻿/*

  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 gallery media elements (such as a photo gallery or timeline component)
$.fn.galleryToggle = function() {

  if( !$("#video").attr("id") ) {
  
    var elementId = (location.hash).substring(1);

    if (elementId) {  
      var playerURL = "http://photos.america.gov/galleries/amgov" + elementId;
      $.fn.galleryToggle.swap(playerURL,elementId);
    } else if ( !(elementId) && ($(".player").attr("class")) ) {
      var playerURL = $(".collection-box li:eq(0) a.gallerylink").attr("href");
      var elementId = playerURL.split('amgov')[1];
      $.fn.galleryToggle.swap(playerURL,elementId);
    }

    this.each(function() {
      $(this).find(".collection-box li").click(function () {
        var playerURL = $(this).find("a.gallerylink").attr("href");
        var elementId = playerURL.split('amgov')[1];
        $.fn.galleryToggle.swap(playerURL,elementId);
        return false;
      });
    });
  }
};

$.fn.galleryToggle.swap = function(playerURL,elementId) {
  $(".player").html('<iframe src="' + playerURL + '" frameborder=0 width=616 height=418 scrolling=no></iframe>');
  parent.location.hash = elementId;
  $.fn.galleryToggle.activeHighlight(playerURL);
};

$.fn.galleryToggle.activeHighlight = function(playerURL) {
  $(".collection-box").find("li").removeClass("active");
    
  var matchContent = $("a[href=" + playerURL + "]:eq(1)").text();    
  var tabName = $(".collection-box ul:contains('" + matchContent + "')").attr("title");

  if(matchContent && tabName) {
    $(".collection-nav").find("li").removeClass();
    $(".collection-box").find(".elements").hide();

    $(".collection-box ul:contains('" + matchContent + "')").show();
    $(".collection-box li:contains('" + matchContent + "')").addClass("active");
    $(".collection-nav li:contains('" + tabName + "')").addClass("active");
  }
};


// Tabbed Displays in which the tab is on the left (calendars, etc)
$.fn.tab = function() {
  this.each(function(){
    var columnWidth = $(this).width();
    if(columnWidth < 316) 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).prepend("<ul class='collection-nav'></ul>");
  
  var i = 0;
  while ((i + 1) <= $(p).find(".elements").length) {
    var currentElement = $(p).find(".elements:eq(" + i + ")");
    var tabName = $(currentElement).attr("title");
    var tabID = "tab" + Math.floor(Math.random()*1001)
    $(p).find(".collection-nav").append("<li><a href='#" + tabID + "' rel='#" + tabID + "'>" + tabName + "</a>");
    $(currentElement).attr({"id":tabID});
    i++;
  };
  
  $(p).find(".collection-nav li:eq(0)").addClass("active");
  $(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("rel");
    //elementList = elementList.hash;
    $(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");
    if(elementId != "#undefined") $.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")).enlarge();

  if($.browser.msie && ($.browser.version < 7)) { //This is a *really* dirty IE6 hack. C'est la vie.
    $(p).find(".webchat-current").empty();
    $(elementId).clone().appendTo($(p).find(".webchat-current")).enlarge();
  }
};

//Quiz Function
$.fn.quiz = function () {
  p = this;
  var questionCurrent = 0;
  var questionsTotal = $(p).find(".question").length;
  $(p).find(".box-body").append("<div class='details'><span class='status'>پرسش   از " + questionsTotal + "</span> <a href='#' class='next button'>پرسش بعدی</a></div>");
  $(p).find(".question").slice(1,questionsTotal).hide();
  
  $(p).find(".answers li").click(function () {
    $(p).find(".result").show();
    if($(p).find(".result").length < 1)
      $(p).find(".details").before("<div class='result'><p class='title'></p><p class='description'></p></div>");

    if($(this).hasClass("correct")) {

      $(this).addClass("clicked-correct");
      $(p).find(".title").text("آفرین، پاسخ شما درست است.").removeClass("incorrect").addClass("correct");
      $(p).find(".next").show();

      if((questionCurrent + 1) == questionsTotal) {
        $(p).find(".details .next").addClass("end").text("از شرکت شما در آزمون ما سپاسگزاریم");
        $(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("متاسفیم، پاسخ شما نادرست است. لطفاً یک پاسخ دیگر را انتخاب کنید.").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, #ejournals").webchatSwap();
  $(".tabbed-collection").tabbedCollection(); //Top tabs function, active state on content elements. Used for video, webchats, photos
  $("#photo .tabbed-collection").galleryToggle();

  $(".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");
  
});