//| Copyright © 2011, Pontus Östlund - http://www.poppa.se
//|
//| License GNU GPL version 3
//|
//| cinematic.js is free software: you can redistribute it and/or modify
//| it under the terms of the GNU General Public License as published by
//| the Free Software Foundation, either version 3 of the License, or
//| (at your option) any later version.
//|
//| cinematic.js is distributed in the hope that it will be useful,
//| but WITHOUT ANY WARRANTY; without even the implied warranty of
//| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//| GNU General Public License for more details.
//|
//| You should have received a copy of the GNU General Public License
//| along with cinematic.js. If not, see <http://www.gnu.org/licenses/>.

var Cinematic =
{
  config: {
    basePath: '/assets/js/cinematic/',
    imageLeft: 'left.png',
    imageRight: 'right.png',
    imageDot: 'dot.png',
    imageDotActive: 'dot-active.png',
    dotbg: 'cinematic-bg.png',
    css: 'cinematic.css',
    delay: 10,
    transitionSpeed: 'medium'
  },

  isReady: false,

  getAsset: function(which)
  {
    // Check for ending slash
    if (!(/\/$/.test(this.config.basePath)))
      this.config.basePath += '/';

    if (this.config[which])
      return this.config.basePath + this.config[which];
  },
  
  Dot: function(index, callback)
  {
    this.index = index;
    this.url = Cinematic.getAsset('imageDot');
    this.onUrl = Cinematic.getAsset('imageDotActive');
    this.image = $('<img src="' + this.url + '" class="dot" alt="" width="13" height="13" />')
                  .css('cursor','pointer');
    this.isActive = false;

    var my = this;
    this.activate = function()
    {
      this.isActive = true;
      my.image.attr('src', my.onUrl).removeClass('dot-on');
      return my;
    };

    this.deActivate = function()
    {
      this.isActive = false;
      my.image.attr('src', my.url).addClass('dot-on');
      return my;
    };

    this.addClass = function(cls)
    {
      my.image.addClass(cls);
      return my;
    };
    
    this.removeClass = function(cls)
    {
      my.image.removeClass(cls);
      return my;
    };
    
    this.image.click(function() {
      if (!my.isActive)
	callback(my);
    });
  }
};

jQuery.fn.extend(
{
  cinema: function(imgArray, conf)
  {
    if (imgArray.length < 2)
      return false;

    var owner = this;

    function theCinema() {
      $(owner).addClass('__cinematic');
  
      if (!conf)
	conf = Cinematic.config;
      else {
	for (var n in Cinematic.config)
	  if (!conf[n])
	    conf[n] = Cinematic.config[n];
      }
  
      var my = {
	owner: owner,
	conf: conf,
	div1: null,
	div2: null,
	imgContainer: null,
	img: imgArray,
	index: 0,
	toggles: 0,
	iv: null,
	dotContainer: null,
	dots: [],
	activeDot: null,
	inTransition: false,

	changeDot: function(idx)
	{
	  my.activeDot.deActivate();
	  my.activeDot = my.dots[idx].activate();
	},

	load: function(idx, onInit)
	{
	  if (my.inTransition) {
	    trace("Load: in transition...skip");
	    return;
	  }
	  my.index = idx - 1;
	  run(0, onInit);
	},
  
	next: function(cb)
	{
	  if (my.inTransition) {
	    trace("Next: in transition...skip");
	    return;
	  }

	  if (my.index >= my.img.length-1)
	    my.index = -1;
  
	  my.toggles++;
	  my.index++;

	  return my._setImage(cb);
	},
  
	prev: function(cb)
	{
	  if (my.inTransition) {
	    trace("Prev: in transition...skip");
	    return;
	  }

	  if (my.index < 1)
	    my.index = my.img.length;
  
	  my.toggles++;
	  my.index--;

	  return my._setImage(cb);
	},

	_setImage: function(cb)
	{
	  var img = $('<img src="'+my.img[my.index].path+'"/>').load(
	    function() {
	      my.changeDot(my.index);
	      if (cb) cb(this);
	    }
	  );

	  if (my.img[my.index].url.length) {
	    img.click(function() {
	      document.location.href = my.img[my.index].url;
	    }).css('cursor','pointer');;
	  }

	  return img;
	}
      };
      
      function setTransparency(level)
      {
	my.owner.find('img.arrow,div.dots').animate(getOpac(level), 500);
      }

      function getOpac(level)
      {
      	if (document.all)
      	  return { filter : 'alpha(opacity=' + (level*100) + ')' };
      	else
      	  return { opacity : level };
      }
      
      function init()
      {
      	var img = my.owner.find('img');

  	if (!img.length)
	  return false;

	var firstUrl = my.owner.find('a');
	var height = my.owner.height();
	var width = my.owner.width();

	var p = {
	  width: width,
	  height: height,
	  opacity: 1,
	  position: 'absolute'
	};

  	my.dotContainer = $('<div class="dots"></div>');

	for (var i = 0; i < my.img.length; i++) {
	  var b = new Cinematic.Dot(i, function(dot) {
	    if (my.inTransition) {
	      trace("In transition in dot");
	      return;
	    }

	    dot.activate();
	    my.activeDot.deActivate();
	    my.load(dot.index);
	    return false;
	  });

	  if (i == 0) {
	    b.activate();
	    my.activeDot = b;
	  }

	  my.dots.push(b);
	  my.dotContainer.append(b.image);
	}

	if (firstUrl && firstUrl.length) {
	  img.click(function() {
	    document.location.href = firstUrl.attr('href');
	    return false;
	  }).css('cursor','pointer');
	}

	//return false;
	
	my.div1 = $('<div id="cinema-1"></div>').css(p).append(img);
	my.div2 = $('<div id="cinema-2"></div>').css(p).hide();
	my.imgContainer = $('<div class="imgs"></div>');
	my.owner.find('a').remove();
	
	my.owner.append(my.imgContainer
	                          .append(my.div1)
	                          .append(my.div2)
	                       ).append(my.dotContainer);

        img.ready(function() {
	  my.imgContainer.css({
	    height: img.outerHeight()
	  });
        });
	return true;
      }

      function run(direction, onInit)
      {
      	if (my.inTransition) {
      	  trace("In transition in run...");
      	  return;
      	}

      	clearInterval(my.iv);

	var idiv, odiv;
  
	if (my.toggles % 2 == 0) {
	  odiv = my.div1;
	  idiv = my.div2;
	}
	else {
	  odiv = my.div2;
	  idiv = my.div1;
	}
	
	var func = direction ? my.prev : my.next;
	idiv.append(func(function() {
	  my.inTransition = true;
	  idiv.fadeIn(my.conf.transition);
	  odiv.fadeOut(my.conf.transition, function() {
	    my.inTransition = false;
	    $(this).empty();
	    my.iv = setInterval(function() {
	      clearInterval(my.iv);
	      run();
	    }, my.conf.delay*1000);
	  });
	}));
      }

      //owner.css({ height: owner.height(), width: owner.width() });

      if (init()) {
      	my.iv = setInterval(function() {
	  run(0);
      	}, my.conf.delay*1000);
      }
    }

    return this.each(function(i, el) {
      theCinema();
    });
  }
});

$(function()
{
  var cssString = "" +
    ".__cinematic, .__cinematic * {line-height: 1px;} " +
    ".__cinematic .imgs {" +
    "position: relative; " +
    "overflow: hidden; " +
    "height: 220px; " +
    "} " +
    ".__cinematic .dots { " +
    "width: auto; " +
    "position: relative; " +
    "padding: 10px 10px; " +
    "background: url(" + Cinematic.getAsset('dotbg') + ") repeat-x; " +
    "text-align: center; " +
    "height: 13px; " +
    "} " +
    ".__cinematic .dot { " +
    "margin-right:3px; " +
    "} ";

  $('head').append('<style type="text/css">' + cssString + "</style>");
  Cinematic.isReady = true;
});
