
// Sex with Javascript. raivof@gmail.com

$(function()
{
  $('#bottom_menu li').mouseenter(function()
  {
    var panel = $('.panel ', this);
    if ($(panel).data('h') == null)
    {
      $(panel).data('h', $(panel).height() );
    }
    else
      $(panel).css('height', $(panel).data('h')+'px');


    $(panel).stop().slideDown('slow');
    return;

    if ($(panel).data('h') == null)
    {
      $(panel).css('opacity', 0).css('display', 'block');
      var h = $(panel).height();
      var bottom1 = parseFloat($(panel).css('bottom'));
      var bottom2 = bottom1 - h;

      $(panel).data('bottom1', bottom1);
      $(panel).data('bottom2', bottom2);
      $(panel).data('h', h);
    }
    $('.panel', this).css('display', 'block');

    $(panel)
      .css('height', 0)
      .css('top', $(panel).data('h') + 'px')
      .css('opacity', 1);

    $(panel).stop().animate({
      top: 0,
      height: $(panel).data('h') + 'px'
    }, 1350);

  }).mouseleave(function()
  {
    var panel = $('.panel', this);
    $(panel).stop().slideUp('slow');

    return;

    $(panel).stop().animate({
      top: $(panel).data('h')+'px',
      height: 0
    }, 1350);
  });

});


function extractCssParam(attrib_value, prefix)
{
  if (attrib_value == null) return null;
  var a = attrib_value.split(' ');
  for (var i=0; i<a.length; i++)
  {
    if (a[i].substr(0, prefix.length) == prefix)
    {
      var c = a[i].split('-');
      return c[c.length-1];
    }
  }

  return null;
}


if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

var preloaded_images = [];

function preload_images(images)
{
  for (var i=0; i<images.length; i++)
  {
    var im = new Image();
    im.src = images[i];
    preloaded_images.push(im);
  }

}

function init_slides(slides)
{
  var sl = [];
  for (var i=0; i<slides.length; i++)
    sl.push(slides[i].image);

  preload_images(sl);

  var pic_i = 0;
  var act_i = 0;
  var lis;
  var bgs = [];
  var act_bg = 0;

  function showPic(i)
  {
    if (act_i == i) return;

    if (lis != null)
    {
      $(lis[act_i]).toggleClass('active');
      $(lis[i]).toggleClass('active');
    }

    act_i = i;

    var bg2 = $('#slidebg2').css('backgroundRepeat', 'no-repeat').css('backgroundImage');
    if (bg2 != '')
    {
      $('#slidebg').css('backgroundImage', bg2);
    }


    if (slides[i].is_video)
    {
      $('#slidebg2, #slidebg').stop().css('backgroundImage', 'none');

      clearInterval(tmr);
      init_video(slides[i].fullimage);
    }
    else
    {
      $('#slidebg2').stop().fadeTo(0, 0)
        .css('backgroundRepeat', 'no-repeat')
        .css('backgroundImage', 'url("'+slides[i].image+'")')
  //      .attr('href', slides[i].url.length > 0 ? slides[i].url : '#')
        .fadeTo(1000, 1.0);

    }

    $('#slides .desc').html(slides[i].desc);

  }

  function switchSlide()
  {
    pic_i++;
    if (pic_i >= slides.length) pic_i = 0;

    showPic(pic_i);
  }

  var tmr;
  var interval = 6000;

  function setUserPic(i)
  {
    var vbox = $('#videobox');
    if (vbox[0])
    {
      tmr = setInterval(switchSlide, interval);
    }
    vbox.remove();

    clearInterval(tmr);
    tmr = setInterval(switchSlide, interval);
    showPic(i);
    pic_i = i;
    return false;
  }

  $(document).ready(function()
  {
    bgs[0] = $('#slidebg')[0];
    bgs[1] = $('#slidebg2')[0];

    lis = $('#slides .switch li');

    lis.click(function()
    {
      var i = $(lis).index(this);

      setUserPic(i);

      return false;
    });

    $('#slides a.prev').mouseenter(function()
    {
      $('> .inner', this).stop().animate({ left: 0 }, 300);
    }).mouseleave(function()
    {
      $('> .inner', this).stop().animate({ left: -43 }, 300);
    });

    $('#slides a.next').mouseenter(function()
    {
      $('> .inner', this).stop().animate({ right: 0 }, 300);
    }).mouseleave(function()
    {
      $('> .inner', this).stop().animate({ right: -43 }, 300);
    });

    $('#slides a.prev').click(function()
    {
      var i = pic_i - 1;
      if (i < 0) i = slides.length-1;

      setUserPic(i);
      return false;
    });

    $('#slides a.next').click(function()
    {
      var i = pic_i + 1;
      if (i >= slides.length) i = 0;

      setUserPic(i);
      return false;
    });


    if (!slides[0].is_video)
      tmr = setInterval(switchSlide, interval);
    else
    {
      init_video(slides[0].fullimage);
    }

    onvideostop = function()
    {
      var i = pic_i + 1;
      if (i >= slides.length) i = 0;

      setUserPic(i);
    }

  });
}

function init_video(filename)
{
  if (!swfobject.hasFlashPlayerVersion("9.0.115")) return;

  $('#slidebg2').html('<div id="videobox"></div>').fadeTo(0, 1);
/*
  jwplayer('videobox').setup({
    flashplayer: '/scripts/components/jwplayer/player.swf',
    file: escape(filename),
    width: 982,
    height: 423,
    autostart: true,
    controlbar: 'none',
    'controlbar.idlehide': true
  });  */

  var flashvars = {
    file: escape(filename),
    mute: ($.cookie('sound_on') == null || $.cookie('sound_on') == 1) ? 0 : 1
  };

  swfobject.embedSWF("/scripts/vplayer.swf", "videobox", "982", "423", "9.0.115", "/scripts/components/swfobject/expressInstall.swf", flashvars, {allowScriptAccess: 'sameDomain', menu: 'false', wmode: 'transparent'}, {id: 'videobox'});


  return;

  var flashvars = {
    file: escape(filename),
    allowfullscreen: 'true',
    autostart: true,
    controlbar: 'none'
  };

  swfobject.embedSWF("/scripts/player.swf", "videobox", "982", "423", "9.0.115", "/scripts/components/swfobject/expressInstall.swf", flashvars, {allowScriptAccess: 'sameDomain', menu: 'false', wmode: 'transparent'}, {id: 'videobox'});

/*
  call_flash('videobox', 'gfsdafsdid', null, function()
  {
    var player = swfobject.getObjectById('videobox');
    alert(player);

  });
*/
}

var onvideostop = null;

function VPlayer_onVideoStop()
{
  if (onvideostop != null)
    onvideostop();

}

function VPlayer_onSoundToggle(sound_on)
{
  $.cookie('sound_on', sound_on ? 1 : 0, { expires: 30, path: '/'} );
}


function call_flash(id, fn, params, on_result)
{
  var m = swfobject.getObjectById(id);
  if (m != undefined && m[fn] != undefined)
  {
    var result =  m[fn](params);
    if (on_result)
      on_result(result);

    return result;
  }

  var wait_elapsed = 0;
  var wait_timeout = 5000;
  var wait_step = 50;

  var wait_t = setInterval(function ()
  {
    var m = swfobject.getObjectById(id);
    if (m == undefined || m[fn] == undefined)
    {
      wait_elapsed += wait_step;
      if (wait_elapsed >= wait_timeout)
        clearTimeout(wait_t);

     return;
    }

    clearTimeout(wait_t);

    var result =  m[fn](params);
    if (on_result)
      on_result(result);

  }, wait_step);
}

function init_bottom_menu(options)
{
  $(function()
  {
    var images = [];
    for (var id in options.images)
    {
      images.push(options.images[id]);
    }
    preload_images(images);

    $('#bottom_menu > li').mouseover(function()
    {
      var arrow = $('.m_arrow', this)[0];
      if (arrow == null) return;

      var pos = $(this).position();
      var w = $(this).innerWidth();
      var cx = pos.left + w / 2 - $(arrow).width() / 2;

      $(arrow).css('left', cx+'px').show();

    });

    $('#bottom_menu ul.menu > li').mouseover(function()
    {
      var id = extractCssParam($(this).attr('class'), 'pg-');
      var img = options.images[id];

      var panel = $(this).parents('div.panel:first')[0];

      if (!img) return;

      $('div.pic img', panel).attr('src', img).toggle(true);
    }).mouseout(function()
    {
      var li = $(this).parents('li:first')[0];
      var id = extractCssParam($(li).attr('class'), 'pg-');
      var img = options.images[id];
      var panel = $(this).parents('div.panel:first')[0];

      if (img)
        $('div.pic img', panel).attr('src', img).toggle(true);
      else
        $('div.pic img', panel).toggle(false);


    });

  });

}

function init_flexcroll(e, keep_pos)
{
  var flex = e.fleXcroll;
  if (flex)
  {
    flex.updateScrollBars();
    if (!keep_pos)
      flex.setScrollPos(false, 0);
  }
  else
    fleXenv.fleXcrollMain(e);

}


var current_lightbox = null;

function UniqueLightbox(options, $items)
{
  if (!options) options = {};
  if (!options.images || options.images.length == 0) return;

  if (!options.h_margin) options.h_margin = 5;
  if (!options.v_margin) options.v_margin = 5;

  this.options = options;

  this.images = options.images;
  this.links = [];

  this.current_i = null;
  this.current_img = null;

  this.h_margin = options.h_margin / 100;
  this.v_margin = options.v_margin / 100;

  this.lightbox = $('#lightbox')[0];

  var self = this;

  $items.each(function(i, a)
  {
    if ($(a)[0].tagName != 'A') return;

    var href = $(a).attr('href');
    if (!href || href == '' || href == '#') return;

    self.links.push(a);
//      images.push(href);


    $(a).click(function()
    {
//      $(this).attr('href', '#');
      current_lightbox = self;
      self.openImage(0); //links.indexOf(this));
      return false;
    });

  });

  if (!$(this.lightbox).hasClass('_inited'))
  {

    self.$$('.bg, a.close').click(function()
    {
      current_lightbox.closeLightbox();
    });

    $(window).resize(function()
    {
      if (current_lightbox.current_img != null)
      {
        current_lightbox.resizeImage(current_lightbox.current_img);
      }
    });

    self.$$('.prev').click(function()
    {
      current_lightbox.openImage(current_lightbox.current_i-1);
      return false;
    });

    self.$$('.next').click(function()
    {
      current_lightbox.openImage(current_lightbox.current_i+1);
      return false;
    });


    $(self.lightbox).addClass('_inited');
  }

}


UniqueLightbox.prototype.$$ = function(sel)
{
  return $(sel, this.lightbox);
};


UniqueLightbox.prototype.openImage = function(i)
{
  var self = this;
//      $$('.image').hide();
  self.$$('.info').hide();
  self.$$('.image').hide();
  self.$$('.loading').show();

  $(self.lightbox).show();

  var img = new Image();
  var prev_i = self.current_i;

  img.onload = function()
  {
    self.$$('.loading').hide();

    if (prev_i != null)
    {
      self.$$('.back')
        .css('left', (parseFloat(self.$$('.frame').css('left'))+1)+'px' )
        .css('top', (parseFloat(self.$$('.frame').css('top'))+1)+'px' )
        .css('width', self.$$('.image img').width()+'px' )
        .css('height', self.$$('.image img').height()+'px' )
        .load(function()
        {
          $(this).show()
            .fadeTo(0, 1);

        })
        .attr('src', self.images[prev_i]);

    }

    self.$$('.frame').fadeTo(0, 0);

    self.resizeImage(img);

    self.$$('.image img').attr('src', self.images[i]);
    self.$$('.image').show();

//        $$('.info .title').html( $('span.text', links[i]).html() );
//        $$('.info .desc').html( $('span.desc', links[i]).html() );
    self.$$('.info .title').html( $('span.text', self.links[0]).html() );

    self.$$('.info .desc').html( $('> div.desc', $(self.links[0]).parent()[0] ).html() );

    self.$$('.info').show();

    self.$$('.back').fadeTo(350, 0, function()
    {
      $(this).hide();
    });
    self.$$('.frame').fadeTo(350, 1);

  };
  img.src = self.images[i];

  self.current_i = i;
  self.current_img = img;

  self.$$('.prev').toggle(i > 0);
  self.$$('.next').toggle(i < self.images.length-1);
};


UniqueLightbox.prototype.closeLightbox = function()
{
  $(this.lightbox).hide();
  this.$$('.image').hide();
  this.current_i = null;
};

UniqueLightbox.prototype.resizeImage = function(img)
{
  var self = this;

  var l_width = $(self.lightbox).outerWidth();
  var l_height = $(self.lightbox).outerHeight();

  var frame_max_w = l_width - l_width * self.h_margin * 2;
  var frame_max_h = l_height - l_height * self.v_margin * 2;

  var img_width = img.width;
  var img_height = img.height;

  if (img_width > frame_max_w)
  {
    img_height = frame_max_w * (img_height / img_width);
    img_width = frame_max_w;
  }

  if (img_height > frame_max_h)
  {
    img_width = frame_max_h * (img_width / img_height);
    img_height = frame_max_h;
  }

  var x = (l_width - img_width) / 2;
  var y = (l_height - img_height) / 2;

  self.$$('.frame')
    .css('left', x+'px')
    .css('top', y+'px')
    .css('width', img_width+'px')
    .css('height', img_height+'px');

  self.$$('.image img')
    .css('width', img_width+'px')
    .css('height', img_height+'px');

};



(function( $ )
{

  $.fn.uniqueLightbox = function(options)
  {
    var lightbox = new UniqueLightbox(options, this);
  }

})( jQuery );


var projects_inited = false;

function init_projlist(options)
{
  $(function()
  {
    init_flexcroll($('#projlist_grid')[0]);

    $('#projlist_grid a').each(function(i, a)
    {
      var id = extractCssParam($(this).attr('class'), 'pr-');

      var images = [];
      images.push($(this).attr('href'));

      if (options.images[id])
      {
        for (var j=0; j<options.images[id].length; j++)
        {
          images.push(options.images[id][j]);
        }
      }

      $(this).uniqueLightbox({
        images: images
      });

    });

    $('#active_project').trigger('click');

    $('#projlist .menu a').click(function()
    {
      $('#projlist .menu li.active').removeClass('active');
      $(this).parent().addClass('active');

      var cls = $(this).attr('class');
      var cat_id = cls ? extractCssParam(cls, 'cat-') : 0;

      $('#projlist_grid td').each(function(i, td)
      {
        var cls = $(td).attr('class');
        if (cls == null) return;

        var id = extractCssParam(cls, 'cat-');

        if (cat_id == 0 || cat_id == id)
          $('a img', td).fadeTo(500, 1);
        else
          $('a img', td).fadeTo(500, 0.15);

      });

      return false;
    });

    projects_inited = true;
  });
}

function init_home_projects(options)
{
  $(function()
  {
    $('#projects div.left a').click(function()
    {
      window.location = '/'+options.lang+'/projekti?project='+$(this).attr('rel');
      return false;
    });

    $('#projects div.right a').click(function()
    {
      var div = $(this).parents('div.project:first');
      $('div.left a', div).trigger('click');
      return false;
    });

  });
}

function init_text()
{
  $(function()
  {
    init_flexcroll($('#projlist .text')[0]);
  });
}
