function __d(m) {var u='undefined';if (typeof console != u){var c=console;if ((typeof c.log != u) && c.log) c.log(m);}}

var $j = jQuery.noConflict();
// http://www.corrupt-system.de/jquery/backgroundPosition/jquery.backgroundPosition.js
/**
 * @author Alexander Farkas
 *
 *
 * garry@magnetised.info:
 * fixed to work with -ve background positions
 *
 */
(function($) {
  $.extend($.fx.step,{
    backgroundPosition: function(fx) {
      if (fx.state == 0 && typeof fx.end == 'string') {
        var start = $.curCSS(fx.elem,'backgroundPosition');
        start = toArray(start);
        fx.start = [start[0],start[2]];
        var end = toArray(fx.end);
        fx.end = [end[0],end[2]];
        fx.unit = [end[1],end[3]];
        fx.running = true
      }
      if (fx.running) {
        var nowPosX = [];
        nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
        nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1]; 
        fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];
      }
      function toArray(strg){
        strg = strg.replace(/left|top/g,'0px');
        strg = strg.replace(/right|bottom/g,'100%');
        strg = strg.replace(/(\d+)(\s|\)|$)/g,"$1px$2");
        var res = strg.match(/(\-?\d+)(px|\%|em|pt)\s(\-?\d+)(px|\%|em|pt)/);
        return [parseFloat(res[1]),res[2],parseFloat(res[3]),res[4]];
      }
    }
  });

  })(jQuery);


var Meta = null;

Meta = {
  pid: null,
  zoom_width: 0,
  list: [],
  wrapper: null,
  layout: null,
  icon: {small: {width: 110, height: 72, offset: true}, large: {width: 346,height: 230, offset: false}},
  zoomed: true,
  init: function() {
    if ($j('#about_'+$m.pid).length == 0) {
      
    } else {
      
      $j(".openabout").click(function(e) {Meta.toggle_about(e, this)}).fadeIn()
    }
    // hide the images
    $m.grid().hide();
    // then use the html as a db to load the images
    $j($m.gid() + ' li').each(function() {
      var o = {zoomed: false};
      $j("strong", this).each(function() {
        o.id = this.id.split(/_/)[1]
        o.title = $j(this).html()
      })
      $j("a", this).each(function() {o.href = this.href})
      $j("input", this).each(function() {
        if (this.name == "fullscreen") {
          var p = this.value.split(/;/)
          o.fullscreen = {src: p[0], width: parseInt(p[1]), height:parseInt(p[2])}
        } else if (this.name == "offset") {
          try {
            var off = this.value.split(/,/);
            o.offset = {left: parseInt(off[0] || 0), top: parseInt(off[1] || 0)}
          } catch (e) {
            o.offset = {left: 0, top: 0}
          }
        } else if (this.name == "preview") {
          var p = this.value.split(/;/)
          o.width = p[1];
          o.height = p[2];
        }
      });
      $j("img", this).each(function() {
        o.src = this.src;
      })
      $m.list.push(o)
    });
    
    $m.grid().html('');
    $m.wrapper = $m.e('div', {style: 'display:none'})
    $m.layout = $m.get_layout();
    $m.images().append($m.wrapper);
    $m.display();
    
    $m.layout.zoom($m.list[0])
    // $j(window).bind('resize',$m.resize)
    
    
    $j('ul.sub-navigation li ul li').bind('mouseover', function() {$m.ltr_nav_on(this)}).bind('mouseout', function() {$m.ltr_nav_off(this)}).bind('hovering', function() { $j('a', this).addClass('hover') }).bind('nothovering', function() { $j('a', this).removeClass('hover') })
  },
  ltr_nav_on: function(li) {
    if (li.id && li.id.match(/page_\d+/)) {
      var id = li.id.split(/_/)[1]
      $j('#grid_'+id).trigger('hovering')
    }
  },
  ltr_nav_off: function(li) {
    if (li.id && li.id.match(/page_\d+/)) {
      var id = li.id.split(/_/)[1]
      $j('#grid_'+id).trigger('nothovering')
    }
  },
  rtl_nav_on: function(id) {
    $j('#page_'+id).trigger('hovering')
  },
  rtl_nav_off: function(id) {
    $j('#page_'+id).trigger('nothovering')
  },
  resize: function(event) {
    var o = $m.layout.cols;
    var n = $m.calculate_columns();
    if (o != n) {
      $m.reset();
      $m.display();
    }
  },
  reset: function() {
    $m.wrapper.html('');
  },
  display: function() {
    $m.layout = $m.get_layout();
    $m.layout.draw();
    $m.wrapper.show();
  },
  bg_position: function(e, size, b) {
    var l = 0, t = 0;
    if (size.offset) {
      l = parseInt(e.offset.left);
      t = parseInt(e.offset.top);
    }
    return (b ? '(' : '') + parseInt(l + (size.width - e.width)/2)+'px '+parseInt(t + (size.height - e.height)/2)+'px'+(b ? ')' : '')
  },
  transpose_size: function(e, size) {
    // if (parseInt(e.height) > parseInt(e.width)) {
    //   return {width: e.width, height: e.height};
    // }
    // return {width: size.width, height:e.height};

    return {width: e.width, height: e.height};
  },
  calculate_columns: function() {
    var ww = $j(window).width(), cols = 10;
    if (ww > 960) {
      cols = 10;
      if (ww >= 1196) {
        cols = 12;
      }
    }
    return cols;
  },
  
  get_layout: function() { // generates a layout manager based on current window size
    var ww = $j(window).width(), cols = 10, zw = 6; // zw is column width of zoomed image
    cols = this.calculate_columns();
    var g = (function(cols, zw) {
      return {
        _setup: false,
        cols: cols,
        zw: zw,
        active: false,
        draw: function(images) {
          if (!this._setup) this.setup();
          this.empty();
          var row_index = 0, c = 0;
          for (var i=0; i < $m.list.length; i++) {
            var iw = this.item_width($m.list[i]);
            c += iw;
            if (c >= this.cols) {
              row_index += 1;
              c = iw;
            }
            var e = this.item_entry($m.list[i]);
            $m.list[i].li = $j('div',e)
            $m.list[i].row = this.rows[row_index];
            this.rows[row_index].list.append(e);
          };
        },
        item_entry: function(e) {
          var t = $m.e('td', {'id':'grid_'+e.id, 'class': (e.zoomed ? 'active' : ''), style: ''});
          var l = $m.e('div', {style: 'width: '+$m.icon.small.width+'px; height:'+$m.icon.small.height+'px;background: #000 url("'+e.src+'") '+$m.bg_position(e, $m.icon.small) + ' no-repeat'})
          var h;
          h = $m.e('div', {'class': "hover-bar", style: 'width: 100%; height: 1px; line-height: 0px; font-size: 0px;border-top: solid 1px #fff; background-color: transparent; position: absolute;top: 0;display: none'})
          l.layout = this;
          l.meta = e;
          l.click(function(event) {
            l.layout.zoom(l.meta);
            return false;
          })
          if (e.href) {
            if (e.zoomed) {
              l.attr('title',"Click for details of " + e.title);
            } else {
              l.attr('title', e.title)
            }
          } else {
            if (e.zoomed) {
              l.bind('click', function() {tb_show($j, e.title, e.fullscreen.src);this.blur();})
            }
          }
          l.append(h)
          t.append(l)
          e.image = l
          t[0].hover_bar = h;
          t[0].page_id = e.id
          t.bind('hovering', function() {this.hover_bar.show()})
          t.bind('nothovering', function() {this.hover_bar.hide()})
          t.bind('mouseover', function() {$j(this).trigger('hovering'); $m.rtl_nav_on(this.page_id)})
          t.bind('mouseout', function() {$j(this).trigger('nothovering');  $m.rtl_nav_off(this.page_id)})
          return t;
        },
        item_width: function(i) {
          if (i.zoomed) {
            if (i.width > i.height) {
              return 2 * Meta.zoom_width;
            } else {
              return 2 * Meta.zoom_width - 1;
            }
          }
          return 2;
        },
        zoom: function(e) {
          var prev = null;
          if (this.active) {
            prev = this.active
            if (e == this.active) {
              if (this.active.href) {
                window.location.href = this.active.href;
                
              }
              return
            } else {
              this.active.zoomed = false;
              this.active = e;
              e.zoomed = true
            }
          } else {
            if (e) {
              this.active = e
              e.zoomed = true;
            }
          }
          var to = $m.icon.large, from = $m.icon.small, duration = 500;
          var redraw = function() {
              if (prev) {
                prev.row.title.title_text.css('display', 'none');
                prev.row.title.css('height', 0);
              }
              with ($m.layout) {
                draw();
                to = $m.transpose_size(active, to)
                if (active) {
                  var t = show_title()
                  active.row.title.animate({height: 22}, {queue:false, duration:duration}).animate({opacity: 1}, {queue:false, duration:duration})
                  active.row.title.title_text.animate({opacity: 1}, {queue: false, duration: duration})
                  t.animate({width: to.width}, {queue:false, duration:duration})
                  active.image.animate({backgroundPosition: $m.bg_position(active, to, true)}, {queue:false, duration:duration})
                  active.li.eq(0).animate(to, duration)
                }
              }
            }
          if (prev) {
            var d = duration / 2
            if (!this.active) {
              d = duration
            }
            prev.row.title.animate({height: 0}, {queue:false, duration:d}).animate({opacity: 0}, {queue:false, duration:d})
            prev.row.title.animate({opacity: 0}, {queue:false, duration:d})
            prev.row.title.title_text.animate({width: $m.icon.small.width}, {queue:false, duration:d}).animate({opacity: 0}, {queue:false, duration:d})
            prev.image.animate({backgroundPosition: $m.bg_position(prev, $m.icon.small, true)}, {queue:false, duration:d})
            prev.li.eq(0).animate({width:from.width, height: from.height}, d, 'linear', redraw)
          } else {
            redraw()
          }
        },
        show_title: function() {
          if (this.active) {
            if (this.active.row.title.title_text) {
              this.active.row.title.title_text.html(this.active.title);

              this.active.row.title.css('display', 'block')
              var a = this.active.li.offset().left;
              var r = this.active.row.title.offset().left
              this.active.row.title.title_text.css('left', (a - r) + 'px')
              this.active.row.title.title_text.css('width', '0')
              this.active.row.title.css('opacity', 0)
              return this.active.row.title.title_text;
            }
          }
        },
        setup: function() {
          // creates the wrapper divs for the rows
          this.rows = []
          for (var i = 0; i < this.row_count(); i++) {
            var tb = this.image_list();
            var r = {
             row: this.row_div(),
             title: this.title_div(),
             list: $j('tr', tb)
            }
            r.row.append(r.title);
            r.row.append(tb);
            this.rows.push(r);
            
            $m.wrapper.append(r.row)
          }
          this._setup = true;
        },
        empty: function() {
          for (var i = this.rows.length - 1; i >= 0; i--){
            this.rows[i].list.html('')
          };
        },
        row_count: function() {
          // works out the no of rows we need
          // an unzoomed image takes 2 columns, 
          // but we also need to take into account the size of a zoomed image
          var need = Meta.zoom_width + ($m.list.length)*2.0
          return Math.ceil(need / this.cols) + 2;
        },
        row_div: function() {
          return $m.e('div', {'class': 'grid-row', 'style': 'margin-bottom: 8px'})
        },
        title_div: function() {
          var d = $m.e('div', {'class': 'grid-row-title', 'style': 'height: 0; display: none;'})
          var t = $m.e('p', {'style': 'position: relative; top: 0; margin: 0; background:transparent url(/i/bg_line_dotted.gif) repeat-x scroll left top; display:block; font-size:12px; font-weight:normal; height:18px; padding:3px 0 0; width: 0;'})
          d.append(t)
          d.title_text = t;
          return d;
        },
        image_list: function() {
          var tb = $m.e('table', {'class': 'image-grid', 'style': ''});
          var tr = $m.e('tr');
          tb.append(tr);
          return tb;
        }
      }
    })(cols, zw)
    return g;
  },
  toggle_about: function(e, a) {
    if (a.showing) {
      $m.about().hide();
      this.reveal($j('#summary_text_' + $m.pid));
      this.reveal($m.images());
      $j(a).toggleClass('active')
      a.showing = false;
    } else {
      $j('#summary_text_' + $m.pid).slideUp(200)
      $m.images().hide();
      this.reveal($m.about());
      $j(a).toggleClass('active')
      a.showing = true;
    }
  },
  reveal: function(e) {
    $j(e).show(200);
  },
  gid   : function() { return '#grid_'+$m.pid },
  grid  : function() { return $j($m.gid()) },
  about : function() { return $j('#about_'+$m.pid) },
  images: function() { return $j('#images_'+$m.pid) },
  e: function(e, a, c) {
    var d = document.createElement(e);
    if (typeof a == 'undefined') a = {};
    $j.each(a, function(n,v) {
      d.setAttribute(n, v)
      if (n == 'style') {
        d.style.cssText = v;
      }
    });
    
    if (typeof c != 'undefined') $j(d).html(c)
    return $j(d);
  }
}

$j(window).load(function() {Meta.init()});


var $m = Meta;

