// ============================================== //

		// TIMER FUNCTIONS //

// ============================================== //

jQuery.fn.extend({everyTime:function(interval,label,fn,times,belay){return this.each(function(){jQuery.timer.add(this,interval,label,fn,times,belay)})},oneTime:function(interval,label,fn){return this.each(function(){jQuery.timer.add(this,interval,label,fn,1)})},stopTime:function(label,fn){return this.each(function(){jQuery.timer.remove(this,label,fn)})}});jQuery.extend({timer:{guid:1,global:{},regex:/^([0-9]+)\s*(.*s)?$/,powers:{'ms':1,'cs':10,'ds':100,'s':1000,'das':10000,'hs':100000,'ks':1000000},timeParse:function(value){if(value==undefined||value==null)return null;var result=this.regex.exec(jQuery.trim(value.toString()));if(result[2]){var num=parseInt(result[1],10);var mult=this.powers[result[2]]||1;return num*mult}else{return value}},add:function(element,interval,label,fn,times,belay){var counter=0;if(jQuery.isFunction(label)){if(!times)times=fn;fn=label;label=interval}interval=jQuery.timer.timeParse(interval);if(typeof interval!='number'||isNaN(interval)||interval<=0)return;if(times&&times.constructor!=Number){belay=!!times;times=0}times=times||0;belay=belay||false;if(!element.$timers)element.$timers={};if(!element.$timers[label])element.$timers[label]={};fn.$timerID=fn.$timerID||this.guid++;var handler=function(){if(belay&&this.inProgress)return;this.inProgress=true;if((++counter>times&&times!==0)||fn.call(element,counter)===false)jQuery.timer.remove(element,label,fn);this.inProgress=false};handler.$timerID=fn.$timerID;if(!element.$timers[label][fn.$timerID])element.$timers[label][fn.$timerID]=window.setInterval(handler,interval);if(!this.global[label])this.global[label]=[];this.global[label].push(element)},remove:function(element,label,fn){var timers=element.$timers,ret;if(timers){if(!label){for(label in timers)this.remove(element,label,fn)}else if(timers[label]){if(fn){if(fn.$timerID){window.clearInterval(timers[label][fn.$timerID]);delete timers[label][fn.$timerID]}}else{for(var fn in timers[label]){window.clearInterval(timers[label][fn]);delete timers[label][fn]}}for(ret in timers[label])break;if(!ret){ret=null;delete timers[label]}}for(ret in timers)break;if(!ret)element.$timers=null}}}});if(jQuery.browser.msie)jQuery(window).one("unload",function(){var global=jQuery.timer.global;for(var label in global){var els=global[label],i=els.length;while(--i)jQuery.timer.remove(els[i],label)}});


// ============================================== //

		// SHUFFLE ARRAY FUNCTIONS //

// ============================================== //

(function($){
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length)
        ? $(this).html($.shuffle(items))
        : this;
    });
  }
 
  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }
})(jQuery);

//
// ============================================== //

		// SLIDESHOW FUNCTIONS //

// ============================================== //
//

var imgArray = [];
var imgArrayLoaded = [];
var arrayItem = 0;
var arrayLoadItem = 0;
var arrayLength = 0;
var speed = 4000;
var zDepth = 50;
var prevItem = null;
//
initSlideShow = function(){
	// fix opacity problem in FIrefox (but not ie)
	if (!$.browser.msie) $('body').css('opacity', 0.9999);
	//
	var target= $('#img_slideshow');
	target.find('li').each(function(i) {
		$(this).animate({ opacity: 0 }, 0.001);
		$(this).css({ 'position' : 'absolute', 'top' : 0, 'left' : 0 });
		imgArray.push($(this).find('img').attr('src'));
		imgArrayLoaded.push(false);
		$(this).find('img').attr({'src': ''});
	});
	arrayLength = imgArray.length;
	//
	imgArray = $.shuffle(imgArray);
	//
	loadImage();
};

loadImage = function(){// load each main image in sequence and add events to thumbnails
	//
	var nextImage = imgArray[arrayLoadItem];
	var img = new Image();
	//
	$(img).load(function () {
		imgArrayLoaded[arrayLoadItem] = true;
		$('#img_slideshow').find('li').eq(arrayLoadItem).find('img').attr({'src': imgArray[arrayLoadItem]});
		if(arrayLoadItem==0){
			$('#img_slideshow').find('li').eq(arrayLoadItem).find('img').css('display', 'block').parent().animate({ opacity: 1 }, 500, function(){
				advanceImage();	
			});
		};
		if(arrayLoadItem<arrayLength){
			arrayLoadItem++;
			loadImage();
		};
	}).attr('src', nextImage);
};

advanceImage = function(){
	// hide previous image
	if(prevItem!=null){
		prevItem.animate({ opacity: 0 }, 0.001);
	}
	prevItem = $('#img_slideshow').find('li').eq(arrayItem);
	//
	if(arrayItem<(arrayLength-1)){
		arrayItem++
	}else{
		arrayItem = 0
	}
	startImgTimer();
};

startImgTimer = function(){
	var target= $('#img_slideshow');
	target.oneTime(speed, function() {
		if(imgArrayLoaded[arrayItem]){
			revealImage();	
		}else{
			startImgTimer();
		}
	});
};

revealImage = function(){
	//alert(arrayItem)
	zDepth++;
	$('#img_slideshow').find('li').eq(arrayItem).find('img').css('display', 'block').parent().css({ 'z-index' : zDepth}).animate({ opacity: 1 }, 500, advanceImage);
}

///////////////// Movie player


_getPageSize = function() {var xScroll, yScroll;if (window.innerHeight && window.scrollMaxY) {xScroll = window.innerWidth + window.scrollMaxX;yScroll = window.innerHeight + window.scrollMaxY;} else if (document.body.scrollHeight > document.body.offsetHeight){xScroll = document.body.scrollWidth;yScroll = document.body.scrollHeight;} else {xScroll = document.body.offsetWidth;yScroll = document.body.offsetHeight;};var windowWidth, windowHeight;if (self.innerHeight) {if(document.documentElement.clientWidth){windowWidth = document.documentElement.clientWidth;} else {windowWidth = self.innerWidth;};windowHeight = self.innerHeight;} else if (document.documentElement && document.documentElement.clientHeight) {windowWidth = document.documentElement.clientWidth;windowHeight = document.documentElement.clientHeight;} else if (document.body) {windowWidth = document.body.clientWidth;windowHeight = document.body.clientHeight;};if(yScroll < windowHeight){pageHeight = windowHeight;} else { pageHeight = yScroll;};if(xScroll < windowWidth){	pageWidth = xScroll;		} else {pageWidth = windowWidth;};arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize;};

_getPageScroll = function() {var xScroll, yScroll;if (self.pageYOffset) {yScroll = self.pageYOffset;xScroll = self.pageXOffset;} else if (document.documentElement && document.documentElement.scrollTop) {yScroll = document.documentElement.scrollTop;xScroll = document.documentElement.scrollLeft;} else if (document.body) {yScroll = document.body.scrollTop;xScroll = document.body.scrollLeft;};arrayPageScroll = new Array(xScroll,yScroll);return arrayPageScroll;};

loadFlash = function(flv_path){
	$('#lightbox-container-content').show();
	var flashvars = {
		file: flv_path
	};
	swfobject.embedSWF("includes/flash/movieplayer.swf", "lightbox-flash", "360", "288", "8.0.0", "expressInstall.swf", flashvars);
					 
					// <param name="flashvars" value="file=video.flv&image=preview.jpg" />
					 
					 //, flashvars);
	
};
		
positionMovie = function(){
	// Get page sizes
	var arrPageSizes = _getPageSize();
	// Style overlay and show it
	$('#jquery-overlay').css({
		width:		arrPageSizes[0],
		height:		arrPageSizes[1]
	});
	// Get page scroll
	var arrPageScroll = _getPageScroll();
	// Calculate top and left offset for the jquery-lightbox div object and show it
	$('#jquery-lightbox').css({
		top:	arrPageScroll[1] + (arrPageSizes[3] / 5),
		left:	arrPageScroll[0]
	});
};	


setMoviePlayer = function(target){

	
	var flv_path = target.getAttribute('href');
	var mov_title = target.getAttribute('title');
	
	//
	$('body').append('<div id="jquery-overlay"><\/div><div id="jquery-lightbox"><div id="lightbox-container"><div id="lightbox-container-content"><h2>'+mov_title+'<\/h2><a href=# title="Close window"><\/a><div id="lightbox-flash"><\/div><\/div><\/div><\/div>');
	//
	
	// Get page sizes
	var arrPageSizes = _getPageSize();
	//
	$('#jquery-overlay').css({
		backgroundColor:	'#040406',
		opacity:			0,
		width:				arrPageSizes[0],
		height:				arrPageSizes[1]
	}).animate({opacity: 0.9}, 250);
	//
	// Get page scroll
	var arrPageScroll = _getPageScroll();
	// Calculate top and left offset for the jquery-lightbox div object and show it
	$('#jquery-lightbox').css({
		top:	arrPageScroll[1] + (arrPageSizes[3] / 5),
		left:	arrPageScroll[0]
	}).show();
	
	//
	// Assigning click events in elements to close overlay
	$('#jquery-overlay,#jquery-lightbox,#lightbox-container-content a,').click(function() {
		clearTimeout(t);
		closeMoviePlayer();
		return false;	
	});
	
	$('#lightbox-container').click(function() {
		return false;						
	});
	
	$(window).resize(function() {
		positionMovie();
	});
	var t;
	$(window).scroll(function () { 
		clearTimeout(t);
		t = setTimeout(function() {positionMovie()}, 300); 
	});
	//
	positionMovie();
	$('#lightbox-container').animate({ width: 362},function() {loadFlash(flv_path);});
	//*/
};
		
closeMoviePlayer = function() {
	$('#jquery-lightbox').remove();
	$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
	// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
	$('embed, object, select').css({ 'visibility' : 'visible' });
	//
	$(window).resize(function() {
	});
};

initVideoPlayer = function(){
	
	$('a.vidPlayer').each(function(){
		$(this).unbind('click').click(function() {
			setMoviePlayer(this);
			return false;
		});
	});
	
	
};


//
$(document).ready(function(){
	if ($('#img_slideshow').length) {  
		initSlideShow();
	}
	if ($('a.vidPlayer').length){
		initVideoPlayer();
	}
});
