var sustainability_ajax = (function()
{
    var global_context_path;
    return {
        setContextPath: function(path)
        {
            global_context_path = path;
        },

        getContextPath: function()
        {
            return global_context_path;
        }
    }
})();

function addBookmark(path, title, anchor)
{
    $j.ajax({
        data: {
            path: path,
            title: title
        },
        type: "POST",
        success: function(data, textStatus)
        {
            $j(anchor).html(" SAVED TO FAVORITES");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
        },
        url: sustainability_ajax.getContextPath() + "member/bookmarks"
    });
    return false;
}

function rate(path, title, rating, control)
{
    $j.ajax({
        data: {
            path: path,
            title: title,
            rating: rating
        },
        type: "POST",
        success: function(data, textStatus)
        {
          $j(control).parent(".stars").addClass("member");
          $j(control).removeClass("off").removeClass("half").addClass("on");
          $j(control).prevAll(".star").removeClass("off").removeClass("half").addClass("on");
          $j(control).nextAll(".star").removeClass("on").removeClass("half").addClass("off");
          $j(control).parent(".stars").children(".rating_label").html(" YOUR RATING: ");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
        },
        url: sustainability_ajax.getContextPath() + "member/ratings"
    });
    return false;
}

function openNewWindow(url,h,w) {
	window.open(url, 'ngwm', 'width='+w+',height='+h);
}

/* navigation drop down menu */
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;


function jsddm_open() {  jsddm_canceltimer();
   jsddm_close();
   ddmenuitem = $j(this).find('ul').css('visibility', 'visible');
   if ($j('#n2_about').css('visibility') == 'visible'){
     $j('#n1_about').addClass('aover');
   }
}

function jsddm_close() { if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
  $j('#n1_about').removeClass('aover');
}

function jsddm_timer(){ closetimer = window.setTimeout(jsddm_close, timeout);}

function jsddm_canceltimer() {
  if(closetimer) {
    window.clearTimeout(closetimer);
    closetimer = null;
  }
}
document.onclick = jsddm_close;

/* position breadcrumb links */
function wire_breadcrumb(){
  var navWidth = $j('#nav').width();
  var leftOffset = 1000 - navWidth;
  $j('#breadcrumbs').css('left', leftOffset);

}

/* add rollover state to About util menu */
function wire_about_menu(){
  $j('#n2_about').css('left', $j('#n1_about').position().left + 'px');
}

function wire_ratings()
{
  $j(".stars .star").hover(
      function()
      {
        $j(this).removeClass("nonselected").addClass("selected");
        $j(this).prevAll(".star").addClass("selected").removeClass("nonselected");
        $j(this).nextAll(".star").removeClass("selected").addClass("nonselected");
      },
      function()
      {

      }
      );
  $j(".stars").hover(
      function()
      {
        if($j(this).is(".member"))
        {
          $j(this).removeClass("member").addClass("_member");
          $j(this).children(".rating_message").html("Click to change rating");
        }
        else
        {
          $j(this).children(".rating_message").html("Click to submit rating");
        }
      },
      function()
      {

        if($j(this).is("._member"))
        {
          $j(this).removeClass("_member").addClass("member");
        }

        $j(this).children(".rating_message").html("&nbsp;");

        $j(this).children(".star").removeClass("selected");
        $j(this).children(".star").removeClass("nonselected");
      }
      );
  $j(".star").click(function()
  {
    if ($j(this).parent(".stars").is(".active"))
    {
      var rating = $j(this).prevAll(".star").size() + 1;
      var path = $j(this).attr("href");
      var title = $j(this).attr("title");

      rate(path, title, rating, this);
    }

    return false;
  });
}

function wire_admin_tables()
{
  $j(".admin table.sortable").tablesorter(
  {
    headers: { 0: {sorter:false} },
    textExtraction: function(elem)
    {
      return $j(elem).text();
    }
    });

  $j(".select_all").click(function(event)
  {
    $j(this).parents("form").find("input:checkbox[@name=" + $j(this).attr("name") + "]").not(".select_all").not(":selected").change();

    return false;
  });
}

function wire_profile_panels()
{
  $j(".profile .panel h2").click(function() {

    $j(".profile .panel form").hide();
    $j(this).next("form").show();
    $j(".success").remove();

  });
}

/* temporary buzz topic navigation */
function wire_buzztopics() {
  if ($j("ul.buzz_topics")) {
    var buzzLinks = $j("ul.buzz_topics li a");
    var buzzCount = buzzLinks.length;
    var currBuzz = 1;
    buzzLinks.each(function(i) {
      if ($j(this).hasClass("on")) {
        currBuzz = i+1;
      }
    });
    var nextBuzz = currBuzz < buzzCount ? currBuzz + 1 : 1;
    var prevBuzz = currBuzz > 1 ? currBuzz - 1 : buzzCount;
    $j("#prevBuzz").click(function(){
      $j(this).attr("href", $j("#buzz" + prevBuzz).attr("href"));
      location.href = $j(this).attr("href");
    });
    $j("#nextBuzz").click(function(){
      $j(this).attr("href", $j("#buzz" + nextBuzz).attr("href"));
      location.href = $j(this).attr("href");
    });
  }
}

/* set accordion and scrollTo actions for glossary */
function wire_glossary(){
  $j('#glossary_listing').accordion({ header: 'h5', active: false, autoHeight: false });
  $j('#glossary_listing').localScroll({
    target:'#glossary_frame'
  });
}

/* set scrollTo actions for calendar */
function wire_calendar(){
  $j('#calendar_listing').localScroll({
    target:'#calendar_frame'
  });
}

/* set external link target & action */
function wire_extLinks(){
  $j("a.pdf").each(function(){
    $j(this).attr({
      title: 'View PDF',
      rel: 'ext'
    });
  });
  $j("a[rel='ext']").attr('target','_blank');
  $j("a.print_page").click(function() {
    window.print();
    return false;
  });
  $j("a.void").click(function(){return false;})

}

/* set external link target & action */
function wire_frame_links(){
  $j('body.grid7 #header a').each(function(){
    $j(this).attr('target','_top');
  });
}

/* set column heights */
function setColumns(){
  if ($j('#main').length < 1 || $j('#sidebar').length < 1) return;
  var mainH = $j('#main').height();
  var sideH = $j('#sidebar').height();
  if (sideH > mainH){
    //alert('side: ' + sideH + ' & main: ' + mainH);
    $j('#main').height(sideH);
  } else if (mainH > sideH){
    $j('#sidebar').height(mainH);
  }
}

/* open selectmenu urls */
function goMenuURL(url){
  if (url.indexOf('http') != -1){
    window.open(url);
  } else if (url != ""){
    location.href = url;
  }
}

/* add state to form buttons for non-supporting browsers */
function wire_form_buttons(){
  $j("input.form_btn, input.btn_go")
   .mouseover(function(e) {
     $j(e.target).addClass('btn_over');
   })
    .mouseout(function(e) {
     $j(e.target).removeClass('btn_over');
   });
   $j('#ksearch #query').focus(function(){
     if ($j(this).attr('value') == 'search'){
       $j(this).attr('value','');
     }
   });
}

/* wire webinar links */
function wire_webinar_links(){
  $j("a.oembed").click(function() {
    var idArray =   $j(this).attr('id').split('_');
    var num = idArray[idArray.length-1];
    $j('#webinar_' + num).toggle(600);
    $j('#oembed_' + num).oembed();
    return false;
  });
}

/* Handle login popup */
function wire_please_login_modal() {
  $j("#please_login").jqm();
  $j("a.please_login").click(function() {
    if ($j(this).is(".addbookmark")) {
      $j("#please_login #register_or_login_to").html("To Add to Favorites");
    } else if ($j(this).is(".star")) {
      $j("#please_login #register_or_login_to").html("To Add Your Rating");
    } else {
      $j("#please_login #register_or_login_to").html("&nbsp;");
    };
    $j("#please_login").jqmShow();
    return false;
  });
}

/* Handle glossary links */
function wire_glossary_links() {
  $j("a[href^=glossary\:]").each(function() {
    var href = $j(this).attr("href");
    if(href.length > 0) {
      var glossary_id = href.substring(9);
      $j(this).attr("href",sustainability_ajax.getContextPath() + "view/page.basic/glossary/content.glossary/" + glossary_id);
      $j(this).attr("target","_blank");
    } else {
      $j(this).attr("href",sustainability_ajax.getContextPath() + "view/page.basic/glossary/");
      $j(this).attr("target","_blank");
    }
  });
}

/* Setup Subtopic Widget tooltips & accordian */
function wire_subtopicWidget(){
  if ($j('#subtopics_listing').length < 1) return;
  $j('#subtopics_listing').accordion({
    autoHeight: false,
    header: '.subcat',
    event: 'click'
    }
  );
  $j('a.more').click(function(event){ event.stopPropagation(); });
  $j('#subtopics_listing a.tool').tooltip({
    bodyHandler: function() {
     var subtopicRollover = ($j(this).next('div.tip').html())
     return subtopicRollover;
    },
    track: true,
    showURL: false
  });
}

function wire_footer() {
  $j('#vimeo_link').tooltip({
    bodyHandler: function() {
      return ($j('#vimeo_link_info').html());
    },
    track: false,
    showURL: false
  });
  $j('#twitter_link').tooltip({
    bodyHandler: function() {
      return ($j('#twitter_link_info').html());
    },
    track: false,
    showURL: false
  });
}

/* document ready inits */
$j(function() {

  
  $j('#nav > li, #utils > li').bind('mouseover', jsddm_open);
  $j('#nav > li, #utils > li').bind('mouseout',  jsddm_timer);
  wire_breadcrumb();
  wire_subtopicWidget();
  wire_about_menu();
  wire_ratings();
  wire_admin_tables();
  wire_buzztopics();
  wire_profile_panels();
  wire_extLinks();
  wire_glossary();
  wire_calendar();
  wire_form_buttons();
  wire_frame_links();
  wire_webinar_links();
  wire_please_login_modal();
  wire_glossary_links();
  //setColumns();
  //setClassTabs();
  wire_footer();
});



