/*

  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, .box-body 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'>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($(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("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, #ejournals").webchatSwap();
  $(".tabbed-collection").tabbedCollection(); //Top tabs function, active state on content elements. Used for video, webchats, photos
  $("#photo .tabbed-collection, #photo .scroll").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");
  
});


/*-------------------------------------------------------------------------------------------------------------------------------------------
	=> ACCORDION MENU -:- The following script initializes the accordion menu system, which is called by the Accordion (folder) template 
	=> 5/13/10
	=> Steve Swanson
-------------------------------------------------------------------------------------------------------------------------------------------*/
function initMenu() {
	$('#accWrapper').css("height", ($('#accordion').find('div.scroll').size() * $('#accordion').find('span.clickHeader').height()) + 500 + "px");	
	$('#accordion div').slideUp('slow');
	$('#accordion div:first').slideDown('slow');
	$('#accordion span:first').css({ 'background-position' : '0px -28px', 'color' : '#990000' });
	
	$('#accordion li span.clickHeader').click(
		function() {
			var checkElement = $(this).next();
			if((checkElement.is('div')) && (checkElement.is(':visible'))) {
				checkElement.slideUp('slow');
				checkElement.find('div').css("display", "none");	
				checkElement.parent().find('span.clickHeader').css({ 'background-position' : '0px 0px', 'color' : '#295890' });
				return false;
			}
			if((checkElement.is('div')) && (!checkElement.is(':visible'))) {
				$('#accordion div:visible').slideUp('slow');     
				$('#accordion div:visible').parent().find('span.clickHeader').css({ 'background-position' : '0px 0px', 'color' : '#295890' });
				checkElement.slideDown('slow');
				checkElement.find('div').css("display", "block");				
				checkElement.parent().find('span.clickHeader').css({ 'background-position' : '0px -28px', 'color' : '#990000' });
				return false;
			}
		}
	);
}

function expandAll(expand) {
	if(expand) {
		$('#accWrapper').css("height", $('#accordion').find('div.scroll').size() * $('#accordion').find('span.clickHeader').height() + 500);
		$('#accordion').find('div').slideUp('normal');
		$('#accordion li span.clickHeader').css({ 'background-position' : '0px 0px', 'color' : '#295890' });
	}
	else {
		$('#accWrapper').css("height", $('#accordion').find('div.scroll').size() * ($('#accordion').find('span.clickHeader').height() + 300));		
		$('#accordion').find('div').slideDown('normal');
		$('#accordion li span.clickHeader').css({ 'background-position' : '0px -28px', 'color' : '#990000' });
	}
}
/* ENDOF ACCORDION MENU */



/*------------------------------------------------------------------------------------------------------------------------------------
|	NAME		:	document ready
|	CALLED BY	:	dom loading
|	PURPOSE		:	Performs a number of actions to prepare the previewing and formating of the widget manager
------------------------------------------------------------------------------------------------------------------------------------*/
$( function() {
	if( !$('.widgetList').size() ) return false;
	
	$('.wWrapper').find('.widget').find('img').each( function(){	//Replaces all of the small gear images with something spiffier
		$(this).attr('src', '/widget-manager/widget.gif').show();
		$(this).parent().addClass('widgetLink');
		$(this).parent().parent().show();
	});
	
	$('.previewW').each( function(index) {		//Adds a click event to launch the preview window. Had to do it this way rather than an
		$(this).click( function(e) {			//inline onclick event because IE doesn't properly translate the click event to jquery
			previewWidget('widget'+(index), e);
			return false;
		});
		$(this).parent().parent().find('.widget:eq(0)').attr('id', 'widget' + index);
	});

	
	$('.wTitle').each( function(index) {		//Resets height of the title boxes to see if any of them have a bunch of text, then resizes the text
		$(this).css({
			'min-height': 22, 
			'height' : 'auto'
		}); 
		if( $(this).height() > 22 )
			$(this).css({ 'font-size' : '8px' , 'line-height' : '10px' });
	});
});


/*------------------------------------------------------------------------------------------------------------------------------------
|	NAME		:	previewWidget
|	CALLED BY	:	An attached function to links that have the .previewW class
|	PURPOSE		:	
------------------------------------------------------------------------------------------------------------------------------------*/
function previewWidget(wId,event) {
	$('#frameWrap').fadeOut('medium').remove();
	var track='';
	var wParams = '#' + wId;	
		wParams = $(wParams).find('script:eq(0)').html().match(/{.*}/)[0];	//This nasty thing grabs the parameters for a widget out of a script tag
	var wWidget = eval( '(' + wParams + ')' );	//And this turns it into an object
	var wWrap =	$('<div id="frameWrap"></div>').hide();
	var wClose = $('<a href="#" class="closeBtn">Close</a>').appendTo(wWrap).click( function() {
			$(this).parent().fadeOut('medium', function() { $(this).remove() });
			return false;
		});
		
	var wFrame = $('<iframe id="displayWidget"></iframe>').css({
		'height' : wWidget.height + 20,
		'width' : wWidget.width + 20
	}).attr('src', '/widget-manager/sample.html').appendTo(wWrap).load( function(){
		$(this).contents().find('#testIt').html( wParams );
	});
	
	wWrap.css({ 'left' : event.pageX , 'top' : event.pageY }).appendTo('body');
	$('#frameWrap').fadeIn('medium');
}
