$(document).ready(function(){

  /*******************************
  *  Misc button and link click 
  *  functions
  *******************************/

  // sharethis article button
  $('.sharethis-icon').click(function(){
    //sharethis div doesnt play nice with tooltip so we remove any tip that might currently be showing
    //the tooltip plugin might need some more tweaks too
    $('#tooltip').remove();
    return false;
  });

  // my bookmarks show/hide toggle
  $('.my-bookmarks-link').click(function(){ 
    $(this).toggleClass('down');
    $('.my-bookmarks-slide').toggle(); 
    return false;
  }); 



  /*******************************
  *  User features
  *******************************/

  // add username popup class to js enabled browsers
  if($.browser.msie && $.browser.version < 7) { 
    // @todo:  provide alternate version for IE6?
  } else {
    // temoporarily? removed
    //$('.username-theme').addClass('user-popup');
  }
  
  // provide drop down options when a username is clicked
  $('.user-popup').click(function(){
    
    // array of pipe seperated use properties, not currently keyed
    rel = $(this).attr('rel');
    rel = rel.substr(13, rel.length - 14);
    userinfo = rel.split("|");

    href = $(this).attr('href');
    
    // hide drop down options on second click @todo: add better toggling
    if($('.user-popup-actions-' + userinfo[0]).length > 0) {
      // fadeout and remove
      $('.user-popup-actions-' + userinfo[0]).fadeOut('fast', function () {
        $(this).remove();
      });
    // if the drop down does not already exist
    } else {
      // hide any other user popups currently showing
      if($('.user-popup-actions').length > 0) {
        $('.user-popup-actions').remove();
      }
      
      // build snippet
      usercode = '<div class="user-popup-actions user-popup-actions-' + userinfo[0] + '"><ul>';
      usercode += '<li><a href="' + href + '">View ' + userinfo[1] + '\'s profile</a></li>';
      usercode += '<li><a href="/privatemsg/new/' + userinfo[0] + '">Send ' + userinfo[1] + ' a private message</a></li>';
      usercode += '</ul></div>';
      $(usercode).appendTo('body');
      $('.user-popup-actions').hide();
      // move popup box
      coord = getCumulativeOffset(this);
      $('.user-popup-actions').top(coord[0]+20);
      $('.user-popup-actions').left(coord[1]);
      $('.user-popup-actions').fadeIn('fast');
    }
    
    return false;
  });


  
  /*******************************
  *  Image captioning
  *******************************/

  $(".node .show-caption .image-featured").each(function(i) {
      var imgwidth = $(this).width();
      var imgheight = $(this).height();
      var captiontext = $(this).attr('title');
      var alignment = $(this).attr('align');
      $(this).attr({align:""});
      $(this).wrap("<div class=\"image-caption-container\" style=\"float:" + alignment + "\"></div>");
      $(this).parents('.image-attach-body').css({'width':'200px'});
      $(this).parent().width(imgwidth);
      $(this).parent().append("<div class=\"image-caption\">" + captiontext + "</div>");
  });

  /*******************************
  *  Admin menu
  *******************************/
  
  $('.sift-admin-toggle').click(function() {
    $('.sift-admin-options').toggle();
    return false;
  });


  /*******************************
  *  Tabbed divs
  *******************************/

  function makeTabBox(divArray, tabsId) {
  
    headingTag = 'h3';
    
    makeBox = true;
    for (i=0;i<divArray.length;i++) {
      if($(divArray[i]).length <= 0) {
        makeBox = false;
      }
    }
    if(makeBox==true) {
      // should use wrap all when using proper jquery version
//$('#block-views-anyanswers_answered').add('#block-views-anyanswers_best_answers').add('#block-views-anyanswers_unanswered').wrapAll('<div id="anyanswers-tabs"></div>');
      
      $(divArray[0]).before('<div id="' + tabsId + '" class="generic-tabs"></div>');
      
      var tabLinks = new Array();
      
      for(i=0;i<divArray.length;i++) {
        $(divArray[i]).appendTo("#" + tabsId);
        tabLinks[i] = $(divArray[i]).children(headingTag).html();
        $(divArray[i]).children(headingTag).remove();
      }
      
      // create and add tab links
      
      //temporary site specific 
      tabsLinksHtml = '<div class="' + tabsId + '-block generic-tabs-block">';
      
      tabsLinksHtml += '<ul id="' + tabsId + '-links" class="generic-tabs-links">';
      for(j=0;j<tabLinks.length;j++) {
        tabsLinksHtml += '<li><a href="#">' + tabLinks[j] + '</a></li>';
      }
      tabsLinksHtml += '</ul>';
      
      //temporary site specific 
      tabsLinksHtml += '<span class="clear"></span></div>';
      
      $("#" + tabsId).prepend(tabsLinksHtml);
      
      //needs .equalHeight() when jquery is added
      
      $('#' + tabsId + ' div.block-views').hide();
      $(divArray[0]).show();
      $('#' + tabsId + '-links a:eq(0)').parents('li').addClass('active-tab');
      
      
      $('#' + tabsId + '-links a').click(function(){
        tabNo = $('#' + tabsId + '-links a').index(this);
        $('#' + tabsId + ' div.block-views').hide();
        $('#' + tabsId + '-links li').removeClass('active-tab');
        $('#' + tabsId + '-links a:eq('+tabNo+')').parents('li').addClass('active-tab');
        $(divArray[tabNo]).show();
        return false;
      });
    }
  }  
  
  // implement the above code for the following elements
  
  var anyAnswersTabs = new Array("#block-views-anyanswers_answered","#block-views-anyanswers_unanswered");
  makeTabBox(anyAnswersTabs, 'anyanswers-tabs');
  
  var mostTabs = new Array("#block-views-most_read","#block-views-most_commented");
  makeTabBox(mostTabs, 'most-tabs');
  
  var mostTabsAa = new Array("#block-views-most_read_aa","#block-views-most_commented_aa");
  makeTabBox(mostTabsAa, 'most-tabs-aa');
  
  /*******************************
  *  Tags
  *******************************/
  
  $('.tags-bg h2').after('<div class="tags-add"><a href="#">Add your tags</a></div>');
  
  $('.tags-add').click(function() {
    $('#edit-tags-wrapper').toggle();
    return false;
  });
  

  
  /*******************************
  *  Manipulate og tables
  *******************************/

  $('.view-content-og table .view-field-og-description').hide();
  

  /*******************************
  *  Group control panel
  *******************************/

  //$('#block-og-0').wrap('<div id=\"groups-cp\"></div>');
  title = $('#block-og-0').children('h3').text();
  $('#groups-cp').prepend('<a href="#" class=\"groups-cp-text\">Options for: <strong>' + title + '</strong> (<span class="groups-click-toggle">click to expand</span>)</a>');
  //$('#block-og-0').hide();
  
  $('#block-og-0 h3 a').text('Go to the ' + $('#block-og-0 h3 a').text() + ' homepage');
  
  $('.groups-cp-text').click(function(){ 
    $('#block-og-0').toggle();
    if($('.groups-click-toggle').text() == 'click to expand') {
      $('.groups-click-toggle').text('click to collapse');
    } else {
      $('.groups-click-toggle').text('click to expand');
    }
    return false;
  });
  
  
  
  
  
  
  
  
}); //ready

/*******************************
*  Helper functions and plugins
*******************************/

/*******************************
*  return coordinates of
*  an element
*******************************/

var getCumulativeOffset = function (obj) {
  var left, top;
  left = top = 0;
  if (obj.offsetParent) {
    do {
      left += obj.offsetLeft;
      top  += obj.offsetTop;
    } while (obj = obj.offsetParent);
  }
  return [top, left];
};

/*******************************
*  Tooltip widget
*
*  can't remember excatly where
*  this came from
*
*  amended so as not to clash 
*  with sharethis object
*******************************/

this.tooltip = function(){	
	
  xOffset = 10;
  yOffset = 20;		
    
  $(".tooltip").hover(function(e){

  if(this.title!="") {
    this.t = this.title;
    this.title = "";									  
    $("body").append("<p id='tooltip'>"+ this.t +"</p>");
    $("#tooltip")
      .css("top",(e.pageY - xOffset) + "px")
      .css("left",(e.pageX + yOffset) + "px")
      .fadeIn("fast");
  }
      	
  },
  // mouseout callback
  function(){
  
    if(this.t!=""&&this.t!="undefined") {
  
    this.title = this.t;		
    $("#tooltip").remove();
    
    }
    
    });	
  $(".tooltip").mousemove(function(e){
    $("#tooltip")
      .css("top",(e.pageY - xOffset) + "px")
      .css("left",(e.pageX + yOffset) + "px");
  });	
};

/*******************************
*  IE specific ad relocation
*******************************/

function relocateAd(iframeObj, divName) { 
  
  var iframeDoc, allScripts; 
  iframeDoc = iframeObj.contentWindow.document; 
  allScripts = iframeDoc.getElementsByTagName('script'); 
  // 'unset' all scripts
  for (s = 0; s < allScripts.length; s++) if (allScripts[s].src) allScripts[s].src = ''; 
    
  document.getElementById(divName).insertAdjacentElement('beforeEnd', iframeDoc.getElementById('adDiv')); 

}
   