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'
  });
  $j(".event_box_month").jqm({
    toTop: true
  });
  $j("table.month a.event_link").click(function() {
    var eventId = $j(this).attr("event_id");
    $j("#event_" + eventId).jqmShow();
    return false;
  });

  
  $j(".event").each(function() {
    if ($j(this).height() > 60) {
      $j(this).css('height','5.5em').css('overflow','hidden');
      $j(this).after("<span class='ellipses'>...</span>");
    }

  });

  // .css('height','5.5em').css('overflow','hidden');
  // $(this).after('<span class="elipsis">...</span> <a href="javascript:void(0);" class="disclose">&gt; MORE</a>');
}

/* 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(".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_glossary_terms() {
  $j('span.glossary-term').tooltip({
    bodyHandler: function() {
     var glossaryTermId = $j(this).attr("term-id");
     var glossaryDefinition = $j('#' + glossaryTermId);
     return "<div class='glossary-tooltip'><h3>" + glossaryDefinition.attr("title") + "</h3>" + glossaryDefinition.html() + '</div>';
    },
    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
  });
}

function wire_slideshow() {
  if ($j('#slideshow').length > 0) {
    $j('#slideshow ul').PikaChoose();

    $j("#slideshow ul").jcarousel({
      scroll:4,
      initCallback: function(carousel) {
        $j(carousel.list).find('img').click(function() {
          carousel.scroll(parseInt($j(this).parents('.jcarousel-item').attr('jcarouselindex')));
        });
      }
    });
  }
}

SCI = (window.SCI || {});
SCI.Alert = (function($) {
  var alert = {};

  function render(type,message) {
    var id = 'alert-' + Math.floor(Math.random()*999999997);
    $('#container').prepend('<div class="alert '+type+'" id="'+ id + '">' + message + '</div>');
    $('#'+id).hide().fadeIn(500);
    setTimeout( function() { $('#'+id).fadeOut(1000, function() { $('#'+id).remove(); } ) }, 5000 );
  }

  alert.error = function( message ) { render('error', message); };
  alert.info = function( message ) { render('info', message); };

  return alert;
})(jQuery);


SCI.Html =  (function() {
  var publix = {};
  function h(s) { return s!=null ? s.toString().replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;") : s }
  var ELEMENTS = ['div','button','form','ul','li','label','input','textarea','a','span','iframe','tr','td','img','p','h1','h2','h3',
                  'table','col','thead','tbody','tr','th','td'];
  function el(name) {
    return function(at) {
      var out = '<'+name;
      for (var k in at) out+= ' '+(k=='c'?'class':k)+'="'+h(at[k])+'"';
      out += name=='input'? '/>':'>';
      if (name =='input') return out;
      for (var i=1,l=arguments.length; i < l; i++) out += arguments[i];
      return out + '</'+name+'>';
     }
  }
  publix.elements = function() { var out = ''; for (var i=0,l=arguments.length;i<l;i++) out+=arguments[i]; return out; };  
  for (var i=0,n; n = ELEMENTS[i]; i++) publix[n] = el(n);
  function ocopy(o1,o2) { o2=o2||{}; for (var k in o1) o2[k] = o1[k]; return o2 }
  publix.hinput = function(o,n,v) { var o2={name:n,type:'hidden'}; if (v) o2.value=v; return publix.input(ocopy(o,ocopy(o2))); };
  return publix;
})();

SCI.Templatize = function( re, parameterizer, str ) {
  re.lastIndex = 0;
  var index = 0, li = 0, txt=[], variables = [];
  for ( var m = re.exec(str); m; m = re.exec(str) ) {
    txt[index++] = str.substring(li,m.index);
    variables[index++] = parameterizer(m);
    li = re.lastIndex;
  }
  txt[index++] = str.substring(li);
  return function(o) {
    for (var i=1, l=variables.length; i < l; i += 2) txt[i] = variables[i](o);
    return txt.join('');
  }
};

SCI.sortString = function( before, after ) {
  var code = '', i=0, b='A', a='Y', bc, ac;
  if ( before && before == after )
    after += 'Y';   // corruption work-around
  while (true) {
    b = before && i < before.length ? before.charAt(i) : undefined;
    a = after && i < after.length ? after.charAt(i) : undefined;
    ac = a ? a.charCodeAt(0) : 'Y'.charCodeAt(0) + 1;
    bc = b ? b.charCodeAt(0) : 'A'.charCodeAt(0) - 1;
    if ( (b || !a) && (ac-bc > 1) )
      return code + String.fromCharCode( bc + parseInt((ac-bc)/2) );
    code += b?b:'A';
    i++;
  }
};

SCI.randomKey = function() {
  var i=0, c, key = [], s  = parseInt(Math.random()*60466176) ;
  for ( i=0; i < 10; i++ ) {
    if ( i==5 )  s = parseInt(Math.random()*60466176);
    c = s%36;
    key.push((c>=10 ? 87 : 48) + c);
    s = parseInt(s/36);
  }
  return String.fromCharCode.apply(null, key);
}


SCI.dropWord = function($el) {
  var html = $el.html(), m = /^((.|\n|\r)*)[\s\n]+\S*$/.exec(html);
  if (! m) { $el.html(html.substring(0,20)+'...'); return false; }
  $el.html( m[1] + '...');
  return true;
};
SCI.countLines = function( $el ) {
  var height = $el.innerHeight() - parseInt($el.css('padding-top')) - parseInt($el.css('padding-bottom'));
  return parseInt( Math.round(height / parseInt($el.css('line-height')) ) );
};
SCI.truncateText = function( selector, width ) {
  jQuery(selector).each(function() {
    var $el = jQuery(this);
    while ( this.offsetWidth > width && SCI.dropWord($el) ) {}
  });
};
SCI.limitLines = function( selector, lines ) {
  jQuery(selector).each(function() {
    var $el = jQuery(this);
    if ( SCI.countLines($el) > lines ) $el.attr('title',$el.html().replace('&amp;','&'));
    while ( SCI.countLines($el) > lines && SCI.dropWord($el) ) {}
  });
};


/* 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();
  wire_slideshow();
  //setColumns();
  //setClassTabs();
  wire_footer();
  wire_glossary_terms();

  SCI.limitLines('.one-line',1);
});


