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

		// 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 target = null;
var navTarget = null;

var imgArray = [];
var imgArrayLoaded = [];
var arrayItem = 0;
var arrayLoadItem = 0;
var arrayLength = 0;
var speed = 6000;
var zDepth = 50;
var prevItem = null;


initSlideShow = function(){
	// fix opacity problem in FIrefox (but not ie)
	if (!$.browser.msie) $('body').css('opacity', 0.9999);
	//
	target= $('#photo ul');
	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);
	//
	$('body').oneTime(300, function() {
		target.css({'display' : 'block'});
	});
	//
	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;
		target.find('li').eq(arrayLoadItem).find('img').attr({'src': imgArray[arrayLoadItem]});
		if(arrayLoadItem==0){
			//
			target.find('li').eq(arrayLoadItem).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 = target.find('li').eq(arrayItem);
	//
	if(arrayItem<(arrayLength-1)){
		arrayItem++
	}else{
		arrayItem = 0
	}
	startImgTimer();
};

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

revealImage = function(){
	//alert(arrayItem)
	zDepth++;
	target.find('li').eq(arrayItem).css({ 'z-index' : zDepth}).animate({ opacity: 1 }, 1600, advanceImage);
};


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

		// NAV SLIDESHOW FUNCTIONS //

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

var prevNumber = 0;
var nextNumber = null;
var slideNavOpen = true;
var startNum = 0;

initSlideNav = function(){
	navTarget = $('#photo_nav');
	navTargetLength = navTarget.find('li').length;
	//
	if(window.location.hash) {
		var query_string=document.location.href;
		query_string=query_string.split('#');
		startNum = parseInt(query_string[1])-1;
		prevNumber = startNum;
		//
		var pageHtml = navTarget.find('li').eq(startNum).find('div.project_content').html();
		$('#content_box').html(pageHtml);
	}
	//
	target= $('#photo ul:first');
	prevItem = target.find('li').eq(0);
	//
	
	$('body').oneTime(300, function() {
		$('#photo ul').css({'display' : 'block'});
	});
	//
	target.find('li').each(function(i) {
		$(this).css({ 'position' : 'absolute', 'top' : 0, 'left' : 0 });
		if(i!=startNum){
			$(this).animate({ opacity: 0 }, 0.001);
		}
		//width:69px;
	});
	//
	if(navTargetLength>4){
		navTarget.find('li').each(function(i) {
			$(this).css({'width' : 69});					
		});
	}
	//
	navTarget.children('p').html('<a href="#"></a>');
	//
	setClickDown = function(){
		navTarget.children('p').children('a').unbind('click').bind('click', function(){
			target.stopTime();									   
			navTarget.stop().animate({'top':433, opacity: 0.6},300, function(){
				$(this).find('p:first').children('a').css({backgroundPosition: '4px 2px'});									   
			});
			//
			setClickUp();
		})	
	};
	setClickUp = function(){
		navTarget.children('p').children('a').unbind('click').bind('click', function(){
			target.stopTime();									   
			navTarget.stop().animate({'top':363, opacity: 1},200, function(){
				$(this).find('p:first').children('a').css({backgroundPosition: '4px -58px'});										   
			});	
			//
			setClickDown();
		})	
	};
	//
	setClickDown();
	//
	navTarget.children('ul').find('li').each(function(i){
		
		var tempTarget = $(this).find('a:first');
		tempTarget.data('i', i);
		//
		tempTarget.hover(function() {
			//
			//navTarget.children('p').children('a').text($(this).attr('title'));
			navTarget.children('p.photo_text').children('a').text($(this).attr('title'));
			//
			$(this).stop().animate({'opacity':.4},100);
		}, function() {
			navTarget.children('p.photo_text').children('a').text('');
			$(this).stop().animate({'opacity':1},200);
		}).bind('click', function(){
			nextNumber = $(this).data('i');
			if(navTarget.find('li').eq(nextNumber).find('div.project_content').html()!=null){
				if(nextNumber!=prevNumber){
					slideNavShow();
				}
				return false;
			}
		});
	});
	//
	$('#photo').hover(function() {
		target.stopTime();
		navTarget.stop().animate({'top':363, opacity: 1},200, function(){
			$(this).find('p:first').children('a').css({backgroundPosition: '4px -58px'});										   
		});		
		setClickDown();
		//
	}, function() { 
		//
		target.oneTime(500, function() {
			navTarget.stop().animate({'top':433, opacity: 0.6},300, function(){
				$(this).find('p:first').children('a').css({backgroundPosition: '4px 2px'});									   
			});
		});
	});
};

slideNavShow = function(){	
	zDepth++;
	navTarget.css({ 'z-index' : (zDepth+1)});
	
	$('#content_box').animate({ opacity: 0 }, 200, function(){
		var newHtml = navTarget.find('li').eq(nextNumber).find('div.project_content').html();
		$(this).html(newHtml).animate({ opacity: 1 }, 200);								
	});																							
	//
	target.find('li').eq(nextNumber).css({ 'z-index' : zDepth}).animate({ opacity: 1 }, 500, function(){
		target.find('li').eq(prevNumber).animate({ opacity: 0 }, 0.001);
		prevNumber = nextNumber;
	});
};

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

		// NEWS TICKER //

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

var newsTarget = null;
var liHeight = null;
var liLength = null;
var liPrev = -1;
var liCurrent = 0;
var newsSpeed = 4000;

initNewsTicker = function(){
	newsTarget = $('#message ul');
	liHeight = $('#message ul').height();
	liLength =$('#message ul li').length;
	//
	newsTarget.find('li').css({'position': 'absolute', 'top' : liHeight, 'left' : 0  });
	//
	newsTarget.css({'display' : 'block'});
	newsTarget.oneTime(500, scrollUpNews);
};

scrollUpNews = function(){
	newsTarget.find('li').eq(liCurrent).animate({'top' : liHeight}, 0.001, function(){
		newsTarget.find('li').eq(liPrev).animate({'top' : (liHeight*-1)}, 500);
		$(this).animate({'top' : 0}, 500,advanceNews);
	});
};

advanceNews = function(){
	liPrev = liCurrent;
	if(liCurrent<(liLength-1)){
		liCurrent++;
	}else{
		liCurrent=0;
	}
	//
	newsTarget.stopTime().oneTime(newsSpeed, scrollUpNews);
};

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

		// PEOPLE PAGE VIEWER //

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

var peopleTarget = null;
var peopleLength = null;
var noRepeat = null;
var currentPerson = 0;
var prevPerson = 0;
var posXArray = new Array();
var posYArray = new Array();
var posFilled = new Array();
var firstRun = true;
var peopleSpeed = 10;

initPeople = function(){
	peopleTarget = $('#people_viewer');
	peopleLength = peopleTarget.find('li').length;
	//
	var thisHtml = '<div id="people_over"><p></p></div>';
	peopleTarget.append(thisHtml);
	//
	for(j=0; j<=6; j++){//each row
		for(i=0; i<=10; i++){ // cycle through columns
			posXArray.push(i*51);
			posYArray.push(j*64);
			posFilled.push(false);
		}
	}
	//
	peopleTarget.find('li').each(function(i) {
		var thisTitle = $(this).find('a').attr('title');
		$(this).find('a').data('myTitle', thisTitle).attr('title', '');
		//
		$(this).css({ 'position' : 'absolute', 'top' : 0, 'left' : 0 }).hide().animate({opacity: 0},0.001, function(){
			$(this).show();										   
		});
		//
		$(this).find('a').hover(function() {
			var thisText = $(this).data('myTitle');
			$('#people_over').find('p').html(thisText);
			//
			var myNum = $(this).parent().data('myPos');
			var leftOffset = 51;
			if(posXArray[myNum]>255){
				leftOffset = -102;
			}
			$('#people_over').css({'left' : posXArray[myNum]+leftOffset, 'top' : posYArray[myNum]}).show();
		}, function() {
			$('#people_over').hide();
		});
		
	});
	//
	peopleTarget.css({'display' : 'block'});
	showPerson();
};

advancePerson= function(){
	if(currentPerson<(peopleLength-1)){
		currentPerson++;
	}else{
		currentPerson=0;
		firstRun = false;
		peopleSpeed = 1000;
	}	
	//
	if(firstRun){
		loadPerson();
	}else{
		hidePerson();	
	}
}
//
loadPerson = function(){
	var nextImage = peopleTarget.find('li').eq(currentPerson).find('img').attr('src');
	var img = new Image();
	//
	$(img).load(function () {
		showPerson();
	}).attr('src', nextImage);	
}
//
hidePerson = function(){
	peopleTarget.find('li').eq(prevPerson).animate({opacity: 0},400, function(){
		var thisId = $(this).data('myPos')	;
		posFilled[thisId] = false;
		noRepeat = thisId;
		showPerson();
	});
	//
	if(prevPerson<(peopleLength-1)){
		prevPerson++;
	}else{
		prevPerson=0;
	}
}
//
showPerson = function(){
	var thisTarget = peopleTarget.find('li').eq(currentPerson);
	for(i=0; i<=posXArray.length; i++){
		var numRand = Math.floor(Math.random()*(posXArray.length-1));
		if(!posFilled[numRand] && numRand!=noRepeat){
			break;
		}
	}
	posFilled[numRand] = true;
	//
	thisTarget.data('myPos', numRand).css({ 'top' : posYArray[numRand], 'left' : posXArray[numRand] }).animate({opacity: 1},800, function(){
		peopleTarget.oneTime(peopleSpeed, function() {
			advancePerson();
		});																																  
	});
}

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

		// SPLIT LONG LIST //

// ============================================== //
//
initSplitUl = function(){
	var $bigList = $('ul#nav_categories'), group = $bigList.find('li:lt(12)').remove();
	
  	while(group.length){
    	$('<ul/>').append(group).appendTo('#sub_navigation');
    	group = $bigList.find('li:lt(12)').remove();
  	}
	
	$('ul#nav_categories').remove();
	var thisHtml = '<p id="sub_nav_pag"><a href="#">Next ><\/a><\/p>';
	$('#sub_navigation').append(thisHtml).find('ul').eq(1).hide().animate({opacity: 0},0.001);
	$('#sub_nav_pag a').click(function(){
		$(this).unbind('click');
		ulNext();
		return false;
	});
	
	$('#sub_navigation').css({'display' : 'block'});
};

ulNext = function(){
	$('#sub_navigation').find('ul').eq(0).animate({opacity: 0},400, function(){
		$(this).hide();
		$('#sub_navigation').find('ul').eq(1).show().animate({opacity: 1},400);
		//
		$('#sub_nav_pag a').html('< Previous').click(function() {
			$(this).unbind('click');
			ulPrev();
			return false;
		});
	});
};

ulPrev = function(){
	$('#sub_navigation').find('ul').eq(1).animate({opacity: 0},400, function(){
		$(this).hide();
		$('#sub_navigation').find('ul').eq(0).show().animate({opacity: 1},400);
		//
		$('#sub_nav_pag a').html('Next >').click(function() {
			$(this).unbind('click');
			ulNext();
			return false;
		});
	});
};


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

		// SPLIT CLIENT LIST //

// ============================================== //
//
var currentClient = 0;
var clientTotal = 0;

initSplitClient = function(){
	$('#clientlist').hide();
	
	$('#content_left').prepend('<div id="clientlist_holder"><\/div>');
	
	var $bigList = $('#clientlist'), group = $bigList.find('li:lt(22)').remove();
	
  	while(group.length){
    	$('<ul/>').append(group).appendTo('#clientlist_holder');
    	group = $bigList.find('li:lt(22)').remove();
	}
	$('ul#clientlist').remove();
	$('#content_left').css({ 'overflow' : 'hidden'}).find('ul').each(function(i) {
		$(this).addClass('clientlist');
		if(i>1){
			$(this).hide().animate({opacity: 0},0.001);
		}
	});
	//
	clientTotal = Math.ceil($('#content_left ul').length/2);
	//
	var thisHtml = '<div id="client_pag"><a href="#" id="client_prev">< Previous<\/a><a href="#" id="client_next">Next ><\/a><\/div>';
	$('#content_left').append(thisHtml);
	$('a#client_prev').hide();
	$('#client_next').click(function(){
		fadeClient(1);
		return false;
	});
	$('#client_prev').click(function(){
		fadeClient(-1);
		return false;
	});
};


fadeClient = function(clDir){
	var thisClient = currentClient;
	//
	currentClient+=clDir
	//
	if(currentClient>(clientTotal-2)){
		$('a#client_next').hide();
	}else{
		$('a#client_next').show();
	}
	//
	if(currentClient>0){
		$('a#client_prev').show();
	}else{
		$('a#client_prev').hide();
	}
	//
	$('#content_left').find('ul.clientlist').eq(thisClient*2).stop().animate({opacity: 0},200, function(){
		$(this).hide();
		$('#content_left').find('ul.clientlist').eq(currentClient*2).show().stop().animate({opacity: 1},200);
	});
	$('#content_left').find('ul.clientlist').eq((thisClient*2)+1).stop().animate({opacity: 0},200, function(){
		$(this).hide();
		$('#content_left').find('ul.clientlist').eq((currentClient*2)+1).show().stop().animate({opacity: 1},200);
	});
};

//
///////////////// INITIALISE
//

$(document).ready(function(){
	
	if ($('#photo').length) {  
		if($('#photo_nav').length){
			initSlideNav();
		}else{
			if ($('#people_viewer').length) {  
				initPeople();
			} else if ($('#photo ul li').length>1) { 
				initSlideShow();
			}
			if ($('#photo ul li').length==1) { 
				$('#photo ul').show();
			}
			
		}
	}
	//
	if ($('#message ul li').length>1) { 
		initNewsTicker();
	}
	//
	if($('#nav_categories li').length>13){
		initSplitUl();
	}else{
		$('#sub_navigation').css({'display' : 'block'});
	}
	//
	if($('#clientlist li').length>22){
		initSplitClient();
	}
	//
	$('a img.english-text').click(function(e){
		e.preventDefault();
		$('.english-text').hide();
		$('.arabic-text').show();
	});
	
	$('p.arabic-text a').click(function(e){
		e.preventDefault();
		$('.english-text').show();
		$('.arabic-text').hide();
	});
	
	$('.faq-answer').hide();
	
	$('.faq-question a').click(function(e){
		e.preventDefault();
		//
		if($(this).parent().hasClass('faq-open')){
			$('.faq-open').removeClass('faq-open').siblings('.faq-answer').hide();
		}else{
			$('.faq-open').removeClass('faq-open').siblings('.faq-answer').hide();
			$(this).parent().addClass('faq-open').siblings('.faq-answer').show();
		};
	});
});

