jQuery(function($){

  window['_'] = {
    h : Math.max($('div#trans_parent').height(),$(window).height())
  , w : $(window).width()

  , img_line_width   : 25
  , hl_width         : 40
  , th_padtop        : 50
  , rl_width         : 0
  , menu_top         : 0
  , nudge_amount     : 0
  , horiz_line_speed : 200
  , thumb_show_speed : 200
  , loading_thumbs   : false
  , galimg_ids       : location.hash.slice(1).split('.')

  , $thumbs : $('div#gallery_thumbs')
  , $galwin : $('div#gallery_window')
  , $headrs : $('div.galleryHead', 'div#gallery_menu')

  , initGallery : function() {

    if( location.hash ) _.showOriginal(3000); 

      _.$galwin.add('div#gallery_wrapper,div#container').height(_.h);
      _.$thumbs.css('margin-left', _.hl_width);
      _.menu_top = $('div#header').outerHeight();

      //console.log('het');

      $('div#gallery_menu').css('margin-top', _.menu_top)
      .css('margin-left','10px')
      .onImagesLoaded(function() {

        _.initNav(0);

        _.$galwin.removeClass('mloading');
        _.$headrs = $('div.galleryHead','div#gallery_menu');

        var l = _.$headrs.length-1;
        (function(i) {
          var fn = arguments.callee,
              $h = _.$headrs.eq(i),
          // check if last gallery and init the thumbs if so
          _next=function() {
            if(i===l) {
              _.$headrs.initHeader();
              var lh = Math.max(_.h,$(document).height());
              $('#_big_vert_line').fadeIn(1000).animate({height:lh+'px'},
                {duration:1000,queue:false,easing:'easeOutExpo'});
            }
            else
              fn(i+1); // fade_next
          };

          if( i===0 )
            $h.css({opacity:0,display:'block'}).fadeTo(300,.5,_next);
          else // galB
            $h.css({opacity:0,display:'block',marginTop:0}).fadeTo(300,0.5,_next);
        })(0);

      });
    }
  , initNav : function(cli) {
      var w = 2, $nm = $('div#nav_menu');

      $nm.fadeTo(0,0).find('div.nav')
      .hover(function(){ 
          $(this).not('.sel').addClass('hover').css('cursor','pointer');
      },function(){ $(this).removeClass('hover'); })
      .click(function( e ){
          
        e.stopImmediatePropagation();
        e.stopPropagation();

        //console.log( 'header_click' );

        if( $(this).is('.sel') || $(':animated', _.$galwin).length )
          return; // avoid breakage...

        $('div.nav.sel').removeClass('sel');
        $(this).removeClass('hover').addClass('sel').showContent();
         /* some day...
         h$img = $n.parent('div#nav_menu').prev('img'),
       left_px = h$img.offset().left + h$img.width() - $n.width();

        $n.css({position:'absolute'}).animate({left: left_px}
              ,{duration:300,queue:false ,complete:function(){ $n.showContent(); }}); */
      }).fadeIn()
        .end()
      .fadeTo(0,1).slideDown(300,function(){
        if( cli !== undefined ) $nm.find('div.nav').eq(cli).click();
      });
    }
  , setRLwidth : function() {

      this.rl_width = Math.floor(
        $('#_big_vert_line').offset().left -
        $('div.thumb').offset().left -
        $('div.thumb').outerWidth()
      ) + 1;

      this.nudge_amount = this.rl_width * .5;
    }
  , showThumbs : function() { //console.log('showThumbs');

      if( _.$thumbs.hasClass('faded') )
        _.fadeThumbs();

      _.loading_thumbs = true;

      var $h = $('div.galleryHead.sel').removeClass('hover'),
        g_id = $h.id(),
         h_h = $h.outerHeight(),
         h_i = _.$headrs.index($h),
         l_t = h_i*h_h + Math.floor(h_h/2); //top for _horiz_line

      //console.log( g_id + 'g_id' );

      $h.fadeTo(200,1)
      .find('div.pWrapper').addClass('loading')
      .find('img.galleryPreview').fadeTo(200,0.5);

      // fill #gallery_thumbs, hide the imgs, and get height
      _.$thumbs.html($('div#hidden_thumbs div#thumbs-'+g_id).clone());
      _.$thumbs.find('div.thumb').each(function(){
        var id = $(this).id();
        $(this).html('<div class="_img_line"></div> <img id="img-'+id+'" src="imageSaver.php?id='+id+'&amp;type=thumb" /> <div class="_right_line"></div>');
      })

      _.$thumbs.onImagesLoaded(function() { //console.log('showthumbs() > _.$thumbs.onImagesLoaded(...');

        _.$thumbs.show();

        // hide any content shoowing
        $('div.galleryContent.showing').stop(false,true).fadeOut(200).removeClass('showing');
        $('div.nav.sel').removeClass('sel');

        $h.find('div.pWrapper').removeClass('loading')
          .find('img.galleryPreview').fadeTo(200,1);

         var t_mt0 = l_t,
               t_h = _.$thumbs.outerHeight(),
               t2h = t_h/2,
                 b = t_h/_.$thumbs.find('div.thumb').length,
             t_mt1 = t_mt0 - t2h,
             t_mt1 = (t_mt0 + t2h > _.h) ? _.h-t_h-b : t_mt1,
             t_mt1 = (t_mt1 < _.th_padtop) ? _.th_padtop : t_mt1;

        _.t_mt0 = t_mt0; // save this

        _.$thumbs.spaceout().css('margin-top', t_mt0+'px').addClass('active')
        .find('img').hide();

        if( t_mt1 < 80 ) t_mt1 = 80;

        $('#_horiz_line').css({top:l_t}).animate({width:_.hl_width,right:'-='+_.hl_width},{
          duration:_.horiz_line_speed,
          complete:function() {

            _.$thumbs.animate({height:t_h,marginTop:t_mt1},{
              duration:_.thumb_show_speed,
              complete:function(){

                $('div.thumb',_.$thumbs).hover(
                  function() {
                    if( $(this).is('.loaded') ) {
                      $(this).not('.sel').find('div._right_line').addClass('hover')
                      .end() .find('img').fadeTo(100,0.65);
                    }
                  },
                  function() {
                    $(this).not('.loading').find('div._right_line').removeClass('hover')
                    .end() .find('img').fadeTo(100,1);
                  }
                ).click(function( e ){
                  e.stopImmediatePropagation();
                  e.stopPropagation();

                  if( $(this).is('.sel') && _.$thumbs.hasClass('active') && _.$thumbs.hasClass('faded') ) {
                    $('div.galleryImage.faded').fadeIn();
                    _.fadeThumbs();
                    return;
                  }
                  else if( $(this).is('.sel, .loading') ) return;

                  location.hash = $(this).id() + '.' + $h.id();

                  $('div.thumb.sel').removeClass('sel')
                    .find('div._img_line').animate({width:'-='+_.nudge_amount},{duration:500,easing:'easeOutElastic'})
                  .end()
                    .find('img').animate({marginLeft:'-='+_.nudge_amount},{duration:500,easing:'easeOutElastic'})
                  .end()
                    .find('div._right_line').animate({width:'+='+_.nudge_amount,left:'-='+_.nudge_amount},{duration:500,easing:'easeOutElastic'});

                  if( _.$thumbs.hasClass('faded') )
                    _.fadeThumbs();

                  $(this).showImage().addClass('sel')
                    .find('div._right_line').not('.loaded')
                      .stop(false,true)
                      .end()
                    .animate({width:'-='+_.nudge_amount,left:'+='+_.nudge_amount},{duration:150})
                  .end()
                    .find('img').fadeTo(150,1).animate({marginLeft:'+='+_.nudge_amount},{duration:150,queue:false})
                  .end()
                    .find('div._img_line').animate({width:'+='+_.nudge_amount},{duration:150});
                })
                .each(function(){

                  var $img = $(this).find('img'),
                      $il  = $(this).find('div._img_line'),
                     fade2 = ($('div#galimg-'+$img.id()).hasClass('loaded'))?1:0.3;

                  $img.css({opacity:0,display:'block'}).fadeTo(250,fade2);
                  $il.css('top', $(this).outerHeight()/2)
                    .animate({width:_.img_line_width},{duration:250});

                  _.setRLwidth();

                });

                _.loadImages();

                $('div.galleryHead.sel').css('cursor','default');
                _.loading_thumbs = false;
              }
            });
          }
        });
      });
    }
  , hideThumbs : function(_cbfn) {

      _.$thumbs.find(':animated').stop(true,false); // finish so we dont get stuck/fucked
      _.$galwin.find('div.galleryImage.showing').fadeOut(100).removeClass('showing');
      _.loading_thumbs = true;

      var l = $('div._img_line', _.$thumbs).length,
          c = 0,
         $h = $('div.galleryHead.sel'),
      _done = function() {
        _.loading_thumbs = false;
        $('div.galleryHead.sel').removeClass('sel').fadeTo(200,.5);
        if( typeof _cbfn === 'function' ) _cbfn();
      };

      $('div.galleryHead.sel').replaceHeadImage();

      _.$thumbs.removeClass('active')
      .find('img')
        .fadeOut(120)
        .end()
      .find('div._img_line,div._right_line').animate({width:0},{
        duration:100,
        complete:function() { if( ++c === l ) { // wait for the last one

          _.$thumbs.animate({height:0,marginTop:_.t_mt0},{
            duration:100,
            complete:function() {
              $('#_horiz_line').animate({width:0,right:'+='+_.hl_width},
                {duration:50,complete:_done});

              _.$thumbs.css('height','').empty().hide();
            }
          });
        }}
      });
    }
  , fadeThumbs : function() {
      if( _.$thumbs.hasClass('faded') ) {
        _.$thumbs.removeClass('faded');
        $('div.galleryContent.showing').removeClass('showing').hide();
        $('div#gallery_menu div,div#gallery_menu img,div#gallery_thumbs div,div#gallery_thumbs img').fadeTo(200,1);
        $('div.galleryImage.faded').removeClass('faded');
        $('div#gallery_thumbs').css('border-left-color','');
        $('div#gallery_menu div.galleryHead.faded').removeClass('faded');
        $('div#_horiz_line').css('border-color','');
        $('div.nav.sel').removeClass('sel');
        $('div.galleryHead.sel','div#gallery_menu').css('cursor','default');
        $('div.thumb.sel','div#gallery_thumbs').css('cursor','default');
      }
      else if( _.$thumbs.hasClass('active') ) {
        _.$thumbs.addClass('faded');
        $('div.galleryHead.sel','div#gallery_menu').css('cursor','pointer');
        $('div#gallery_thumbs').css('border-left-color','#ddd');
        $('div#gallery_menu div.galleryHead.sel').addClass('faded');
        $('div#_horiz_line').css('border-color','#eee');
        $('div.thumb.sel','div#gallery_thumbs').css('cursor','crosshair');
        $('div#gallery_menu div,div#gallery_menu img,div#gallery_thumbs div,div#gallery_thumbs img').fadeTo(500,0.38);
      }
    }
  , loadImages : function() { //console.log('loadImages');

      var _gal_id = _.$thumbs.find('div.thumbs')
                        .find('div.thumb').addClass('loading')
                    .end().id(),
      _ok2go = function() { // c-gun
        return( _gal_id===$('div.galleryHead.sel').id()
          && _.$thumbs.hasClass('active')
        );
      };

      (function(i) {
        
        var $thumbs = _.$thumbs.find('div.thumb');
        if( i===$thumbs.length || !_ok2go() ) return;

        var _next = arguments.callee,
              $th = $thumbs.eq(i),
              $rl = $th.find('div._right_line'),
             $img = $th.find('img'),
           img_id = $th.id(),
          $galimg = $('div#galimg-'+img_id).removeClass('loaded');

        $rl.css({
          top  : Math.floor($th.outerHeight()/2),
          left : $img.outerWidth()+_.img_line_width
        }).animate({width:_.rl_width},{ duration:60000 });

        $galimg.onImagesLoaded(function() {

          if( !_ok2go() ) return;

          $th.removeClass('loading').addClass('loaded');
          $rl.stop(false,true).addClass('loaded');

          $galimg.addClass('loaded');
          //click-i
          if( _.galimg_ids.length === 2 && img_id == _.galimg_ids[0] )
          {
            $rl.stop(false,true);
            $th.click().find('div._img_line').stop(false,true);
          }
          else if( (_.galimg_ids.length === 1||_.galimg_ids[1]!=$('div.galleryHead.sel').id()) && $thumbs.filter('.sel').length===0 && $('div.galleryHead.sel img.galleryPreview').id()===img_id )
          {
            $rl.stop(false,true);
            $th.click().find('div._img_line').stop(false,true);
          }

          $img.fadeTo(300,1);
          
        });
        _next(i+1);
        
      })(0);
    }
    , closeOriginal : function() {
        $('#trans_parent').fadeOut(1000);
        $('#original_image').fadeOut(580);
        $tp.css('background-image','url(/images/loading.gif)');
    }
    , showOriginal : function(timeout) {
      var $oi = $('img#original_image'),
          $tp = $('div#trans_parent').fadeIn();

      $oi.attr('src','imageSaver.php?type=large&id='+_.galimg_ids[0])
      .onImagesLoaded(function(){
        var i_w = $oi.width() * .5,
            t_w = $tp.width() * .5;

        $tp.css('background-image','none');
        $oi.fadeIn().css('left',Math.ceil((t_w-i_w)/(t_w*2)*100)+'%');
        if( timeout || 0 )
          setTimeout(function(){ _.closeOriginal(); }, timeout);
        else
          $tp.unbind('click').click(function(){
            _.closeOriginal();
          });
      });
    }
  }; // window._ objects \\

  $(window).hashchange(function(){
    _.galimg_ids = location.hash.slice(1).split('.');
    _.closeOriginal();

    if( ! $('div.removeMe').length )
    {
      if( $('div.galleryHead.sel').id() != _.galimg_ids[1])
        $('div#gallery-'+_.galimg_ids[1]).click();
      else if( _.galimg_ids[0])
        $('div#thumb-'+_.galimg_ids[0]).click();
    }
  });

  $.extend($.fn, {
    id : function() { 
      if( $(this).attr('id') != undefined )
        return $(this).attr('id').split('-')[1];
    }
  , showContent : function() {
      return this.each( function() {

        var _id = $(this).id(),
         _show = function() {
          _.$galwin.find('div#content-'+_id).fadeIn('fast').addClass('showing');
         };

        if( _.$thumbs.hasClass('active') && !_.$thumbs.hasClass('faded') ) {
//          _.hideThumbs(function(){ _show(); });
          if( $('div.galleryImage.showing').length )
            $('div.galleryImage.showing').addClass('faded').fadeOut(function(){ _show(); });
          else _show();

          _.fadeThumbs();
        }
        else if( $('div.galleryContent.showing').length )
          _.$galwin.find('div.galleryContent.showing').fadeOut('fast',function(){ _show(); })
            .removeClass('showing');
        else _show();
      })
    ;}
  , initHeader : function() {
      return this.each(function() {
        $(this).hover(
          function() { if(_.loading_thumbs) $(this).css('cursor','wait');
            else $(this).not('.sel,.loading').addClass('hover').fadeTo(200,1).css('cursor','pointer');
        },function(){
          $(this).not('.sel,.loading').removeClass('hover').fadeTo(200,.5);
        }).click(
          function( e ) {
            e.stopImmediatePropagation();
            e.stopPropagation();
            
            if( $(this).is('.sel') && _.$thumbs.hasClass('faded') ) {
              $('div.galleryImage.faded').fadeIn();
              _.fadeThumbs();
              return;
            }
            else if( _.loading_thumbs || $(this).is('.sel') ) return;

            var $t = $(this),
              _idx = _.$headrs.index($t);

            //console.log( $t, _idx );
            if( _.$thumbs.hasClass('active') ) {
              _.hideThumbs(function(){
                $t.addClass('sel');
                _.showThumbs();
              });
            } else {
              $t.addClass('sel');
              _.showThumbs();
            }
        });

        if( _.galimg_ids.length === 2 && $(this).id() === _.galimg_ids[1])
          $(this).click();
        else if( _.galimg_ids.length === 1 && _.$headrs.index(this) === 0 )
          $(this).click();
      });
    }
  , replaceHeadImage : function() {
      return this.each(function() {

        var $gp = $(this).find('img.galleryPreview');

        if( $gp.id() === img_id || !$('div.thumb.sel',_.$thumbs).length )
          return;

        var img_id = $('div.thumb.sel',_.$thumbs).id(),
           new_src = $gp.attr('src').replace(/id=[0-9]{1,3}/,'id='+img_id);

        $gp.attr('src',new_src).attr('id','pvimg-'+img_id);
      });
    }
  , showImage : function() {
      return this.each(function() {

        var img_id = $(this).id(),
          curr$img = _.$galwin.find('div.galleryImage.showing'),
             $show = _.$galwin.find('div#galimg-'+img_id);

        $('img',curr$img).fadeTo(200,.5);
        _.$galwin.addClass('loading');
        $('div.mainImageWrapper', $show).html(
          '<img id="img-'+img_id+'" class="main_image" src="imageSaver.php?id='+img_id+'&amp;type=large" />'
        );

        $show.onImagesLoaded(function() {

          if( img_id = _.galimg_ids[0] || _.galimg_ids.length === 1 )
          {
            curr$img.removeClass('showing').hide();
            $show.show().sizeImage().addClass('showing loaded').fadeTo(200,1).unbind('click').click(function(){
              _.showOriginal();
            });
            _.$galwin.removeClass('loading');
          }
              
        });
      });
    }
  , sizeImage : function() {
      return this.each(function() {

        //if( $(this).hasClass('sized') ) return;
        //else $(this).addClass('sized');

        var img$wrapper = $(this).find('div.mainImageWrapper'),
                   $bot = $(this).find('div.image_bottom'),
                   $img = img$wrapper.find('img'),
                      w = $img.width(),
                      h = $img.height();

        $bot.height(30);
        var w_width = _.$galwin.width(),
           w_height = _.$galwin.height() - $bot.outerHeight()*2, // for div.image_bottom
                car = w / h,
                war = w_width / w_height;

        (car >= war)
          ? (w > w_width  ? (h*=(w_width/w),  w=w_width ) : 0)
          : (h > w_height ? (w*=(w_height/h), h=w_height) : 0);

        if( w === w_width || h === w_height ) {
          w-=(w*0.1);
          h-=(h*0.1);
        }

        var hmargin = (w_width - w) / 2,
            vmargin = (w_height- h) / 2;

        img$wrapper.height(w_height).width(w_width);
        $bot.width(w).css('margin-top', -vmargin);
        $img.css({
          width       : Math.floor(w),
          height      : Math.floor(h),
          marginTop   : Math.floor(vmargin),
          marginLeft  : Math.floor(hmargin)
        });
      });
    }
  , spaceout : function() {
      return this.each(function() {

        var L = $('div.thumb',this).length,
            b = Math.floor(_.$thumbs.innerHeight() / L),
            x = -b/2,
           dx = b/(L-1);

        $(this).find('div.thumb').each(function(i) {
          if( i===L-1 && x > 25 ) x = Math.floor(x)-1;
          $(this).css('top',x);
          x += dx;
        });

      });
    }
  , onImagesLoaded : function(_cb, dbg) {
      return this.each(function() {
        dbg = dbg || 0;

        var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this),
            _cont = this,
                i = 0,
        _done=function() {
          if( typeof _cb === 'function' ) _cb(_cont);
        };

        if( $imgs.length ) {
          $imgs.each(function() {
            var _img = this,
               _prev = 0,
            _checki=function(e) {
              if((_img.complete && _prev!==$(_img).id() ) // for opera <3
              || (_img.readyState=='complete'&&e.type=='readystatechange') )
              {
                _prev = $(_img).id();
                if( ++i===$imgs.length ) _done();
              }
              else if( _img.readyState === undefined && _prev!==$(_img).id() ) // dont for IE
              {
                $(_img).attr('src',$(_img).attr('src'));
              }
            }; // _checki

            $(_img).bind('load readystatechange', function(e){_checki(e);});
            _checki({type:'readystatechange'});
          });
        } else _done();
      });
    }
  , makePlayTriangle : function() {
      return this.each(function() {
        var w = $(this).width(),
            h = $(this).height(),
           Ym = $(this).height() / 2;

        if( Ym % 2 === 0 ) {
          $(this).height(h+1); 
          ++Ym;
        }

        var dx = w / Ym,
            $l = $('<div class="scanline"></div>'),
             x = 0;

        for(var i=0; i < Ym; ++i,$l.width(x),x+=dx)
          $(this).append($l.clone());

        $(this).append($l.width(x=w).clone());

        for(var i=0; i < Ym; ++i,$l.width(x-=dx))
          $(this).append($l.clone());
      });
    }
  }); // $.extent($.fn.........................................................

  // -- wonky init stuff -------------------------???????????????????
  $('div#header').css('margin-top',-30).onImagesLoaded(function(){
    $('div#header').fadeIn(3000).animate({marginTop:0},{duration:1000,queue:false});
    $('div#footer').fadeIn(10000);
  });

  $('div.removeMe').remove();

  // --START----------------------------------------------->
  _.initGallery();


});

Array.prototype.remove = function(from, to){
  this.splice(from, !to
    || 1 + to - from + (!(to < 0 ^ from >= 0) && (to < 0 || -1) * this.length)
  );
  return this.length;
};

if(!Array.indexOf){ //FUCK U IE!
  Array.prototype.indexOf = function(obj){
   for(var i=0; i<this.length; i++){
    if(this[i]==obj){
     return i;
    }
   }
   return -1;
  };
}

