/* Greybox Redux
 * Required: http://jquery.com/
 * Written by: John Resig
 * Based on code by: 4mir Salihefendic (http://amix.dk)
 * License: LGPL (read more in LGPL.txt)
 */

var IDEA = IDEA || {};

IDEA.GB = {};
IDEA.GB.height = 450;
IDEA.GB.width = 600;

function GB_create(title, opts) {
  var theme='rounded', close_btn='/misc/greybox/close.gif';
  opts = opts || {};
  if (typeof(opts) != 'undefined') {
    if (typeof(opts.theme) != 'undefined') { theme = opts.theme; }
    if (typeof(opts.close_btn)!= 'undefined') { close_btn = opts.close_btn; }
    if (typeof(opts.gbclass)!= 'undefined') { theme += ' '+opts.gbclass; }
  }

  jQuery("#GB_overlay").remove();
  jQuery("#GB_window").remove();

  var callback = false;

  var markup = '<div id="GB_overlay"></div><div id="GB_window" class="clear-block '+theme+'">';
  markup += '<div class="gb-bg"></div>';
  markup += '<div class="gb-tl"><div class="gb-tr"><div class="gb-tc"></div></div></div>';
  markup += '<div class="gb-cl"><div class="gb-cr"><div class="gb-c clear-block">';
  close_class = '';
  if (title) {
    markup += '<div id="GB_header" class="clear-block"><h1 class="title" id="GB_title">'+title+'</h1>';
  }
  else {
    close_class += 'no-header';
  }
  markup += '<div id="GB_close" class="'+close_class+' clear-block"><img class="GB_close" src="'+close_btn+'"></div>';
  if (title) {
    markup += '</div>';
  }
  markup += '<div id="GB_content"><div class="content-wrap"></div></div></div></div></div>';
  markup += '<div class="gb-bl"><div class="gb-br"><div class="gb-bc"></div></div></div>';

  if (1) {
    markup += GB_help_markup();
  }
  markup += '</div>';

  jQuery(document.body).append(markup);

  jQuery("#GB_overlay").click(GB_hide);
  jQuery(".GB_close").click(GB_hide);
  jQuery(window).bind('resize', {}, IDEA.GB.updatePosition);
  if (callback) {
    callback();
  }
}

function GB_help_markup() {
  var markup = '';
  markup += '<div id="GB_help"><div id="GB_help_content" style="height:0; display:none;"><div class="content">';
  markup += '<h1 class="title"></h1>';
  markup += '<div class="content-inner"></div>';
  markup += '</div></div><div id="GB_help_btn" class="clear-block"><a href="#help" onclick="return GB_toggle_help()">Help</a></div></div>';
  return markup;
}

function GB_is_open() {
  return (jQuery("#GB_window").size() > 0) ? 1 : 0;
}

var _help_btn_label = 'Help';
function GB_toggle_help() {
  var C = jQuery("#GB_help_content"), B = jQuery("#GB_help_btn"), Ba = jQuery("a", B);
  Ba.blur();
  var h = C.height();
  if (h) {
    jQuery("#GB_help_content div.content").fadeOut(50, function() {
      C.animate({'height':'0px'}, 150, function() {
        C.hide();
        Ba.text(_help_btn_label);
      });
    });
  }
  else {
    C.animate({'height':'300px'}, 150, function() {
      jQuery("#GB_help_content div.content").fadeIn(100);
      Ba.text('Close');
    });
  }
  return false;
}

function GB_inline(title, content, height, width, callback, opts) {
  IDEA.GB.height = height || 400;
  IDEA.GB.width = width || 600;

  GB_create(title, opts);

  var cnt = jQuery('#GB_content');
  var cntw = jQuery('.content-wrap', cnt);
  if (cntw.size()) {
    cntw.html(content);
  }
  else {
    cnt.html(content);
  }

  jQuery("#GB_overlay").show();
  IDEA.GB.updatePosition();
  jQuery("#GB_window").show();

  if (callback) {
    callback();
  }
}

function GB_expose(sel, title, opts, callback) {
  IDEA.GB.height = (opts && opts.height) || 400;
  IDEA.GB.width = (opts && opts.width) || 600;

  GB_create(title, opts);

  var elem = jQuery(sel);
  var parent = elem.parent();

  jQuery("#GB_window").data('callback', GB_dexpose).data('parent', parent).data('opts', opts);

  jQuery(sel).show().appendTo("#GB_content .content-wrap");

  jQuery("#GB_overlay").show();
  IDEA.GB.updatePosition();
  jQuery("#GB_window").show();
  if (callback) { callback(); }

  return false;
}

function GB_dexpose() {
  var w = jQuery("#GB_window");
  var parent = w.data('parent');
  var opts   = w.data('opts');
  var hide_chillu
  if (parent) {
    var chilluns = jQuery("#GB_content .content-wrap").children();
    if (opts && opts.dexpose_hide) {
      chilluns.hide();
    }
    chilluns.appendTo(parent);
  }
}

function GB_ajax(title, url, height, width, qparams, callback, opts) {
  IDEA.GB.height = height || 400;
  IDEA.GB.width = width || 600;

  GB_create(title, opts);
  GB_ajax_request(url, 'GB_content', qparams, callback);

  jQuery("#GB_overlay").show();
  IDEA.GB.updatePosition();
  jQuery("#GB_window").show();
}

function GB_throb() {
  jQuery('#GB_window').addClass('throbbing');
}
function GB_throb_off() {
  jQuery('#GB_window').removeClass('throbbing');
}

function GB_throb_ajaxsubmit(f) {
  jQuery('.ajax-throbber', jQuery(f)).addClass('throbbing');
}
function GB_throb_ajaxsubmit_off(f) {
  jQuery('.ajax-throbber', jQuery(f)).removeClass('throbbing');
}


function GB_needs_jsonp(url) {
  if (url.indexOf('://')>0) {
    var dom = url.match(/:\/\/(.[^/]+)/)[1];
    var cur = String(window.location).match(/:\/\/(.[^/]+)/)[1]
    return (cur != dom);
  }
  return false;
}

function GB_ajax_request(url, div_id, qparams, callback, request_type) {
  GB_throb();
  qparams = qparams || {};
  qparams.ajax = true;

  if (GB_needs_jsonp(url)) {
    qparams.jsonp = true;
  }
  request_type = request_type || 'GET';
  var data_type = qparams.jsonp ? 'jsonp' : 'json';
  jQuery.ajax({url: url, dataType: data_type, data: qparams, type: request_type,
    success: function (R) {
      GB_ajax_request_callback(R, div_id, callback);
    }
  });
}

function GB_ajax_request_callback(R, div_id, callback) {
  GB_throb_off();
  if (!GB_is_open()) {
    GB_show_scroll();
  }
  if (R.status) {
    var markup = false;
    var data   = (typeof(R.data) != 'undefined') ? R.data : R;

    if (typeof(R.html) != 'undefined') {
      markup = R.html;
    }
    else if (typeof(data.html) != 'undefined') {
      markup = data.html;
    }


    var target = (typeof(data.target_id) != 'undefined') ? data.target_id : div_id;
    if (markup !== false && target!='') {
      jQuery("#"+target).empty().append(markup);
    }
    if (callback) {
      callback();
    }

    if (typeof(data.js) != 'undefined' && data.js != '') {
      eval(data.js);
    }

    if (typeof(data.help) != 'undefined') {
      GB_init_help(data.help.title, data.help.content);
    }

  }
}

function GB_init_help(title, content, tab_title) {

  var parent = $('#GB_window');
  var _help = $('#GB_help');
  if (parent.size() == 0) {
    parent = $('body');
  }

  if (_help.size() == 0) {
    parent.append(GB_help_markup());
  }


  if (typeof(title) != 'undefined') {
    jQuery("#GB_help_content h1.title").html(title);
  }
  if (typeof(content) != 'undefined') {
    jQuery("#GB_help_content div.content-inner").html(content);
    jQuery("#GB_help").addClass('enabled');
  }

  if (typeof(tab_title) != 'undefined') {
    _help_btn_label = tab_title;
    jQuery("#GB_help_btn a").html(_help_btn_label);
  }
}


function GB_update_content(markup) {
  var C = jQuery("#GB_content");
  var CW = jQuery(".content-wrap",C);
  var U = (CW.size()) ? CW : C;
  U.html(markup);
}

function GB_update_title(val) {
  jQuery("#GB_header h1.title").html(val);
}

function GB_update_html(sel, content) {
  jQuery(sel).html(content);
}
function GB_append_html(sel, content) {
  jQuery(sel).append(content);
}
function GB_replace_html(sel, content) {
  jQuery(sel).replaceWith(content);
}

function GB_redirect(url) {
  window.top.location = url;
}

function GB_hide() {
  GB_show_scroll();

  var callback = jQuery("#GB_window").data('callback');
  if (typeof (callback) == 'function') {
    callback();
  }

  jQuery("#GB_window,#GB_overlay").hide().remove();

  jQuery(window).unbind('resize', IDEA.GB.updatePosition);

  return false;
}

function GB_hide_scroll() {
  var wh = jQuery(window).height();
  if (!(jQuery.browser.msie)) {
    jQuery('body').css('overflow', 'hidden').height(wh);
    jQuery('#GB_window').css('overflow', 'visible');
  }
}
function GB_show_scroll() {
  if (!(jQuery.browser.msie)) {
    jQuery('body').css('overflow', 'auto').css('height', 'auto');
  }
}


function GB_parse_classes(cls) {
  var info = cls.split(' ');
  cls = '';
  for (i in info) {
    // DK - don't know why, but  in my testing, info[i] isn't a string - it's a function (at least some of the time!)
    // Didn't drill down any further. 2010-11-05.
    if (typeof(info[i]) == 'string') {
      if ('gb-class' == info[i].substr(0, 8)) {
        cls += info[i].substr(9) + ' ';
      }
    }
  }
  return cls;
}

function GB_init_links() {
  jQuery("a.gb-ajax:not(.gb-ajax-processed)").each(function() {
    var title = jQuery(this).attr('title');
    var rel   = jQuery(this).attr('rel');
    var cls   = GB_parse_classes(jQuery(this).attr('class'));
    var opts  = {'gbclass' : cls}

    var help_id = jQuery(this).attr('gbhelpid');
    if (typeof(help_id) != 'undefined') {
      opts.help_id = help_id;
      var helptitle = jQuery(this).attr('gbhelptitle');
      var helpstr = jQuery(this).attr('gbhelpstring');
      opts.help_str = helpstr || 'Help';
      opts.help_title = helptitle || 'Help';
    }

    if (typeof(title) == 'undefined') { title = ''; }


    if (is_safe(rel) && rel != '' && rel != 'nofollow' && !parseInt(rel)) {
      title = String(unescape(rel)).replace(/\++/g, " ") + title;
    }
    var self = this;
    jQuery(this).click(function() {
      var href  = IDEA.GB.getDataAttr(self, 'href');
      var h = IDEA.GB.getDataAttr(self, 'height');
      var w = IDEA.GB.getDataAttr(self, 'width');
      if (function_exists('btAllOff')) { btAllOff(); }
      if (function_exists('optDropAllOff')) { optDropAllOff(); }
      GB_ajax(title, href, h, w, {ajax:true}, 0, opts);
      return false;
    }).addClass('gb-ajax-processed');
  });
}

function GB_init_updates() {
  jQuery("a.gb-update:not(.gb-update-processed)").each(function() {
    var self = jQuery(this);

    var clik = self.attr('onclick');
    if (typeof(clik) == 'function') {
      self.attr('data-click', clik);
      self.removeAttr('onclick');
    }

    self.click(function(event) {
      var self = jQuery(this);
      var clik = self.attr('data-click', clik);
      if (typeof(clik) == 'function') {
        if (false === clik(event)) {
          if (function_exists('optDropAllOff')) { optDropAllOff(); }
          return false;
        }
      }

      var href = IDEA.GB.getDataAttr(this, 'href');
      var is_action = self.hasClass('gb-action') ? 1 : 0;
      var tgt = is_action ? '' : 'GB_content';




      if (is_action && function_exists('optDropAllOff')) {
        optDropAllOff();
      }

      var h = IDEA.GB.getDataAttr(self, 'height');
      var w = IDEA.GB.getDataAttr(self, 'width');
      var _resize = function() { var _w=w; var _h=h; IDEA.GB.resize(_w,_h); }

      callback = null;

      ico = self.find('.ico')
      if (ico.size() > 0) {

        cls = String(ico.attr('class')).replace('ico','');
        new_cls = 'ico throbbing' + (ico.hasClass('ilb') ? ' ilb' : '');
        ico.data('cls', cls).removeClass().addClass(new_cls);
        callback = function() { var old = cls; ico.addClass(old).removeClass('throbbing'); _resize(); };
      }
      else {
        callback = _resize;
      }

      GB_ajax_request(href, tgt, {ajax:true}, callback);
      return false;
    }).addClass('gb-update-processed');
  });
}

(function($) {

  IDEA.GB.getDataAttr = function(elem, attr) {
    var k = 'data-'+attr;
    var v = $(elem).attr(k);
    if (typeof(v) == 'undefined' || !v) {
      v = $(elem).attr(attr);
    }
    return v;
  }

  IDEA.GB.updatePosition = function() {
    var dh = $(document).height(),
        wh = $(window).height(), ww = $(window).width();
    $("#GB_overlay").height(dh);

    if (GB_is_open()) {
      GB_hide_scroll();
    }


    $("#GB_window").css('top', '15px').css('z-index', 99999);
    if (!$.browser.msie || parseInt($.browser.version) > 6) {
      $("#GB_window").css('position', 'fixed');
    }


    var ah = wh - (15*2) - (20*2);
    var h = (IDEA.GB.height < ah) ? IDEA.GB.height : ah;

    $("#GB_window").css({width: IDEA.GB.width+"px", left: ((ww - IDEA.GB.width)/2)+"px"});
    $("#GB_window .gb-c").css("height", h +"px");

    var hh = $('#GB_header').height() + 20;
    $("#GB_content").css("height", (h-hh) +"px");
  }

  IDEA.GB.resize = function(w,h) {
    IDEA.GB.width = w || IDEA.GB.width;
    IDEA.GB.height = h || IDEA.GB.height;
    IDEA.GB.updatePosition();
  }


  IDEA.GB.link = function(a, url) {
    var self = $(a);
    var t = IDEA.GB.getDataAttr(self, 'title');
    var u = url || IDEA.GB.getDataAttr(self, 'href');
    var h = IDEA.GB.getDataAttr(self, 'height');
    var w = IDEA.GB.getDataAttr(self, 'width');
    GB_ajax(t, u, h, w, {ajax:true});
    return false;
  }

})(jQuery);

function GB_init() {
  GB_init_links();
  GB_init_updates();
}

function zIndexFix(sel, start) {
  if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= 7) {
    var z = start || 2000;
    zIndexAdd(sel, z--);
    jQuery(sel+' div').each(function() {
      jQuery(this).css('zIndex', z--);
    });
  }
}

function zIndexAdd(sel, i) {
  jQuery(sel).css('zIndex', i);
}


/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4259 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */

(function($){

jQuery.dimensions = {
  version: '1.2'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each( [ 'Height', 'Width' ], function(i, name){

  // innerHeight and innerWidth
  jQuery.fn[ 'inner' + name ] = function() {
    if (!this[0]) return;

    var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
        borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right

    return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
  };

  // outerHeight and outerWidth
  jQuery.fn[ 'outer' + name ] = function(options) {
    if (!this[0]) return;

    var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
        borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right

    options = jQuery.extend({ margin: false }, options || {});

    var val = this.is(':visible') ?
        this[0]['offset' + name] :
        num( this, name.toLowerCase() )
          + num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
          + num(this, 'padding' + torl) + num(this, 'padding' + borr);

    return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
  };
});

// Create scrollLeft and scrollTop methods
jQuery.each( ['Left', 'Top'], function(i, name) {
  jQuery.fn[ 'scroll' + name ] = function(val) {
    if (!this[0]) return;

    return val != undefined ?

      // Set the scroll offset
      this.each(function() {
        this == window || this == document ?
          window.scrollTo(
            name == 'Left' ? val : jQuery(window)[ 'scrollLeft' ](),
            name == 'Top'  ? val : jQuery(window)[ 'scrollTop'  ]()
          ) :
          this[ 'scroll' + name ] = val;
      }) :

      // Return the scroll offset
      this[0] == window || this[0] == document ?
        self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
          jQuery.boxModel && document.documentElement[ 'scroll' + name ] ||
          document.body[ 'scroll' + name ] :
        this[0][ 'scroll' + name ];
  };
});

jQuery.fn.extend({
  position: function() {
    var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;

    if (elem) {
      // Get *real* offsetParent
      offsetParent = this.offsetParent();

      // Get correct offsets
      offset       = this.offset();
      parentOffset = offsetParent.offset();

      // Subtract element margins
      offset.top  -= num(elem, 'marginTop');
      offset.left -= num(elem, 'marginLeft');

      // Add offsetParent borders
      parentOffset.top  += num(offsetParent, 'borderTopWidth');
      parentOffset.left += num(offsetParent, 'borderLeftWidth');

      // Subtract the two offsets
      results = {
        top:  offset.top  - parentOffset.top,
        left: offset.left - parentOffset.left
      };
    }

    return results;
  },

  offsetParent: function() {
    var offsetParent = this[0].offsetParent;
    while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
      offsetParent = offsetParent.offsetParent;
    return jQuery(offsetParent);
  }
});

function num(el, prop) {
  return parseInt(jQuery.curCSS(el.jquery?el[0]:el,prop,true))||0;
};

})(jQuery);



// ADD CLASS ON HOVER
(function($) {
  $.extend({
    pinnableUpdate: function() {
      var ws = $(window).scrollTop();
      $('.pinnable').each(function() {
        var _t  = $(this);
        var settings = _t.data('pintotop');
        var top_px = settings.top+'px';

        if (settings.onScroll && typeof(settings.onScroll) == 'function') {
          settings.onScroll();
        }

        var _to = _t.offset();
        if (_t.hasClass('pinnedBot')) {
          if (ws < (_to.top- settings.top)) {
            _t.removeClass('pinnedBot').css({position: 'fixed', top: top_px});
          }
        }
        else if (_t.hasClass('pinned')) {
          var data = _t.data('info');
          if (ws <= (data.thisTop - settings.top)) {
            $(this).css({position: 'static', top: top_px}).removeClass('pinned');
          }

          var maxTop = data.parentTop + data.parentHeight - data.thisHeight - settings.bot;
          if (ws >= maxTop) {
            _t.css({position: 'absolute', top: data.parentHeight-data.thisHeight+settings.top-settings.bot}).addClass('pinnedBot').parent().css('position', 'relative');
          }
        }
        else {
          if (ws > (_to.top - settings.top)) {
            var w = _t.width();
            var parent = _t.parent();
            var data = {
              thisTop: _to.top,
              thisHeight: _t.height(),
              parentTop: parent.offset().top,
              parentHeight: parent.height()
            };
            _t.data('info', data).css({
              width: w+'px',
              position: 'fixed',
              top: top_px
            }).addClass('pinned');
          }
        }
      });
    }
  });

  $.fn.pinToTop = function(opts) {
    $(window).scroll(function() { $.pinnableUpdate(); });

    var settings = $.extend({'top': 10, 'bot': 0, 'onScroll': false}, opts || {});

    return $(this).addClass('pinnable').data('pintotop', settings);
  };
})(jQuery);


jQuery.fn.pulse = function( prop, speed, times, easing, callback ) {
    if ( isNaN(times) ) {
        callback = easing;
        easing = times;
        times = 1;
    }

    var optall = jQuery.speed(speed, easing, callback),
        queue = optall.queue !== false,
        largest = 0;

    for (var p in prop) {
        largest = Math.max(prop[p].length, largest);
    }

    optall.times = optall.times || times;

    return this[queue?'queue':'each'](function(){
        var counts = {},
            opt = jQuery.extend({}, optall),
            self = jQuery(this);

        pulse();

        function pulse() {
            var propsSingle = {}, doAnimate = false;
            for (var p in prop) {
                // Make sure counter is setup for current prop
                counts[p] = counts[p] || {runs:0,cur:-1};

                // Set "cur" to reflect new position in pulse array
                if ( counts[p].cur < prop[p].length - 1 ) {
                    ++counts[p].cur;
                } else {
                    // Reset to beginning of pulse array
                    counts[p].cur = 0;
                    ++counts[p].runs;
                }

                if ( prop[p].length === largest ) {
                    doAnimate = opt.times > counts[p].runs;
                }
                propsSingle[p] = prop[p][counts[p].cur];
            }
            if (self.hasClass('stop')) {
              console.log('has stop');
            }
            opt.complete = pulse;
            opt.queue = false;

            if (doAnimate) {
                self.animate(propsSingle, opt);
            } else {
                optall.complete.call(self[0]);
            }
        }
    });
};



(function($) {
  $(document).ready(function() {
    GB_init();
  });
})(jQuery);


