////////////////////////////////////////////////////////////////////

var showErrors			= 0;
var showImages			= 1;

var aboutusTop1			= '920px';
var aboutusTop2			= '545px';
var aboutusHeight		= '370px';
var currentActiveDiv	= 0;

var flickrTimer			= 0;
var flickrIndex			= 0;
var flickrDelay			= 5000;
var flickrStart			= 0;
var flickrImageArray	= new Array();
var flickrLinkArray		= new Array();

var youtubeTimer		= 0;
var youtubeIndex		= 0;
var youtubeDelay		= 7000;
var youtubeStart		= 0;
var youtubeImageArray	= new Array();
var youtubeLinkArray	= new Array();

var twitterTimer		= 0;
var twitterIndex		= 0;
var twitterDelay		= 12000;
var twitterStart		= 0;
var twitterNameArray	= new Array();
var twitterDescArray	= new Array();
var twitterLinkArray	= new Array();

////////////////////////////////////////////////////////////////////

$(document).ready(function(){

	//--------------------------------------------------------------
	// loading
	$('.overlay').addClass('loading');
	
	
	//--------------------------------------------------------------
	// about us
	$('.aboutusbutton').click(function(){

		//this.blur();
		if (currentActiveDiv != 0) hidebox2();
		currentActiveDiv = $($(this).attr('href'));
		showbox();
	});
	
	$('.closebutton').click(function(){
		hidebox();
	});
	
	//--------------------------------------------------------------
	// used in truncating text elements
	$('.truncated').each(function(){truncateText($(this))});
	
	//--------------------------------------------------------------
	// add target to all external linkes
	$('a[href^="http://"]').attr("target", "_blank");
	
	//--------------------------------------------------------------
	// add rollover event to block gifs (overlay)
	$('div.overlay').mouseover(function(){
	
		var _parent = $(this).parent();
		if (_parent.get(0).id == 'flickr')	flickrStopCycle();
		if (_parent.get(0).id == 'youtube')	youtubeStopCycle();
		if (_parent.get(0).id == 'twitter')	twitterStopCycle();

		// max height
		mh = '240px'		
		myclass = $(this).attr('class');
		if (myclass.indexOf('shortHeight') > -1) mh = '150px';
		
		_parent.find('div.band').stop().animate({ height : mh }, 300);
		
    }).mouseout(function(){
		
		var _parent = $(this).parent();
		if (_parent.get(0).id == 'flickr')	flickrStartCycle();
		if (_parent.get(0).id == 'youtube')	youtubeStartCycle();
		if (_parent.get(0).id == 'twitter')	twitterStartCycle();
	
		_parent.find('div.band').stop().animate({ height : '40px' }, 200);
		
    });
    
    //--------------------------------------------------------------
    // rollover for top image (eyesponge) - must remove later
    /*
	$(".eyeImage")
		.mouseover(function() { 
			var src = $(this).attr("src").match(/[^\.]+/) + ".gif";
			$(this).attr("src", src);
		})
		.mouseout(function() {
			//var src = $(this).attr("src").replace("over", "");
			var src = $(this).attr("src").match(/[^\.]+/) + ".jpg";
			$(this).attr("src", src);
			flickrStartCycle()
		});
	*/
});

////////////////////////////////////////////////////////////////////
// Delay Plugin for jQuery
// - http://www.evanbot.com
// - © 2008 Evan Byrne

jQuery.fn.delay = function(time,func){
	this.each(function(){
		setTimeout(func,time);
	});
	
	return this;
};

////////////////////////////////////////////////////////////////////

function isArray(obj) {

	if (obj.length > 1)
		return true
	
	return false
/*	
	if (obj instanceof Array)
		return true
	if (obj.constructor.toString().indexOf("Array") == -1)
		return false;
*/

}

////////////////////////////////////////////////////////////////////

function runAjax(id, index) {

	var ref = '#' + id;
	if (id == 'blog') ref = ref + index;
	if (id == 'slideshare') ref = ref + index;
	
	var url	= './index.php/main/getlivedata/' + id + '/1/' + index;
	
	//alert(index + ' ' + id)
	
	$.ajax({
		type:		"POST",
		url:		url,
		data:		"",
		beforeSend:	function() {
						},

		success:	function(request) {
						
						//if (id == 'twitter') console.log(request);

						//$(ref + ' .heading').html(id + index + url);
						
						//--------------------------------------------------------------
						// parse JSON request
						
						request = $.evalJSON(request);
						
						//$(ref + ' .heading').html(request.heading);
						if (showImages) $(ref + ' .image img').attr("src", request.image);
						$(ref + ' .cover').addClass(request.coverClass);
						
						$(ref + ' .title').html((isArray(request.title) ? request.title : request.title[0]));
						$(ref + ' .description').html((isArray(request.description) ? request.description : request.description[0]));
						$(ref + ' .link').attr("href", (isArray(request.link) ? request.link : request.link[0]));
						
						//--------------------------------------------------------------
						// twitter tweets
						if (id == 'twitter') {

							twitterNameArray	= request.list_name;
							twitterDescArray	= request.list_desc;
							twitterLinkArray	= request.list_link;
							
							twitterStart = 1;
							twitterStartCycle();
						}
						
						//--------------------------------------------------------------
						// preload Flickr images & start cycling

						if (id == 'flickr') {
						
							$(ref + ' .bigImage').css({opacity: 0});
						
							flickrImageArray = request.image_list;
							flickrLinkArray = request.link_list;
							
							//$.preloadCssImages();
							
							for (var i in flickrImageArray) {
								$.preloadImages(ref, flickrImageArray[i]);
							}
							
							flickrStart = 1;
							flickrStartCycle();
							
							if (showImages) $(ref + ' .bigImage').attr("src", flickrImageArray[0]);
							$(ref + ' .bigImage').css({opacity: 1});
						
						}

						//--------------------------------------------------------------
						// preload Youtube images & start cycling

						if (id == 'youtube') {
						
							$(ref + ' .bigImage').css({opacity: 0});
						
							youtubeImageArray = request.image_list;
							youtubeLinkArray = request.link_list;
							for (var i in youtubeImageArray) {
								$.preloadImages(ref, youtubeImageArray[i]);
							}
							
							youtubeStart = 1;
							youtubeStartCycle();
							
							if (showImages) $(ref + ' .bigImage').attr("src", youtubeImageArray[0]);
							$(ref + ' .bigImage').css({opacity: 1});
						
						}
						
						//--------------------------------------------------------------
						// tidy up

						$(ref + ' .link').attr("target", "_blank");
						$('.truncated').each(function(){truncateText($(this))});

						$(ref + ' .overlay').delay(1000, function() {
							$(ref + ' .overlay').animate({opacity: 0}, 2000, function() {
								$(ref + ' .overlay').removeClass('loading');
							});
						});

						//--------------------------------------------------------------
						
					},

		error:		function(request, error) {
						if (showErrors) alert('ERROR:' + error + request.statusText + ' ' + request.status + ' ' + request.responseText);
					},

		parsererror: function (request, error) {
						if (showErrors) alert('PARSEERROR:' + request + ' ' + error.statusText);
					}
	});

}

////////////////////////////////////////////////////////////////////

jQuery.preloadImages = function() {

	if (!showImages) return;
	
	jQuery("<img>").attr("src", arguments[1]);
	$(arguments[0] + ' .bigImage').attr("src", arguments[1]);

	//for(var i = 0; i<arguments.length; i++) {
	//	jQuery("<img>").attr("src", arguments[i]);
	//	$(ref . ' .bigImage').attr("src", arguments[i]);
	//	//alert(arguments[i]);
	//}
}

////////////////////////////////////////////////////////////////////

function youtubeStartCycle() {	

	if (!showImages)		return;
	if (youtubeStart == 0)	return;
	if (youtubeTimer != 0)	return;
	
	// start timer
	youtubeTimer = window.setInterval(function() {
		$('#youtube .bigImage').stop().animate({opacity: 0}, 500, function() {

			youtubeIndex++;
			if (youtubeIndex >= youtubeImageArray.length) youtubeIndex = 0;

			$('#youtube .bigImage').attr("src", youtubeImageArray[youtubeIndex]).animate({opacity: 1}, 500);
			$('#youtube .link').attr("href", youtubeLinkArray[youtubeIndex]);
			//$('#youtube .heading').html('showing image' + youtubeIndex)

			//$('#youtube .bigImage').animate({opacity: 1}, 1000);

		});
		
	}, youtubeDelay);

}

function youtubeStopCycle() {
	
	if (youtubeTimer == 0) return;
	
	clearInterval(youtubeTimer);
	youtubeTimer = 0;
		
}

////////////////////////////////////////////////////////////////////

function flickrStartCycle() {	

	if (!showImages)		return;
	if (flickrStart == 0)	return;
	if (flickrTimer != 0)	return;
	
	// start timer
	flickrTimer = window.setInterval(function() {
		
		$('#flickr .bigImage').stop().animate({opacity: 0}, 500, function() {

			flickrIndex++;
			if (flickrIndex >= flickrImageArray.length) flickrIndex = 0;

			$('#flickr .bigImage').load(function () {
			
				var now = new Date();
				var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
				//$('#flickr .heading').html('img' + flickrIndex + ' ' + flickrTimer + ' ' + outStr);
		
			}).error(function () {
				//alert('error');
			}).attr('src', flickrImageArray[flickrIndex]).animate({opacity: 1}, 500);
			
			/*	
			$('#flickr .bigImage').attr("src", flickrImageArray[flickrIndex]).delay(250, function() {
				$('#flickr .bigImage').animate({opacity: 1}, 500);
			});
			*/
			$('#flickr .link').attr("href", flickrLinkArray[flickrIndex][0]);
			
			//$('#flickr .bigImage').animate({opacity: 1}, 1000);

		});
		
	}, flickrDelay);

}

function flickrStopCycle() {
	
	if (flickrTimer == 0) return;
	
	clearInterval(flickrTimer);
	flickrTimer = 0;
	
}

////////////////////////////////////////////////////////////////////

function twitterStartCycle() {	

	if (twitterStart == 0)	return;
	if (twitterTimer != 0)	return;
	
	// start timer
	twitterTimer = window.setInterval(function() {
		$('#twitter .description').stop().animate({opacity: 0}, 250);
		$('#twitter .title').stop().animate({opacity: 0}, 250, function() {

			twitterIndex++;
			if (twitterIndex >= twitterNameArray.length) twitterIndex = 0;

			$('#twitter .title').html(twitterNameArray[twitterIndex]).animate({opacity: 1}, 250);
			$('#twitter .description').html(twitterDescArray[twitterIndex]).animate({opacity: 1}, 500);
			$('#twitter .link').attr('href', twitterLinkArray[twitterIndex]);
			
		})}, twitterDelay);

}

function twitterStopCycle() {
	
	if (twitterTimer == 0) return;

	clearInterval(twitterTimer);
	twitterTimer = 0;
		
}

////////////////////////////////////////////////////////////////////

function showbox() {

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(hidebox);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(hidebox);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}

	} catch(e) {
		//nothing here
	}

	currentActiveDiv.css({top: aboutusTop1, height: '0'});
	currentActiveDiv.show();
	currentActiveDiv.stop().animate({height: aboutusHeight, top: aboutusTop2}, 400, showbox2);
	
	flickrStopCycle();
	youtubeStopCycle();
	twitterStopCycle();

}

function showbox2() {
	$('.closebutton').focus();
}

////////////////////////////////////////////////////////////////////

function hidebox() {

	currentActiveDiv.stop().animate({height: '0px', top: aboutusTop1}, 500, hidebox2);

}

function hidebox2() {

	tb_remove()

	currentActiveDiv.hide();
	currentActiveDiv.css({top: aboutusTop1, height: '0'});

	flickrStartCycle();
	youtubeStartCycle();
	twitterStartCycle();

}

////////////////////////////////////////////////////////////////////

String.prototype.trim = function () {
	return this.replace(/^\s*/, "").replace(/\s*$/, "").replace(/\s+/g," ");
}

////////////////////////////////////////////////////////////////////

function truncateText(o) {
    var save={'height':o.height(),'innerHeight':o.innerHeight()}
    o.removeClass('truncated');
    o.css('height','auto');
    var test={'height':o.height(),'innerHeight':o.innerHeight()}
    if (test.innerHeight>save.innerHeight) {
        var text =  o.html().trim();
        var words = text.replace( /\n/g, " <br/>").split(" ");
        var fin=false;
        var word_count=1;
        var sentence;

        while (!fin)
        {
            sentence = words.slice(0,word_count).join(" ")+"...";
            o.html( sentence );
            var test={'height':o.height(),'innerHeight':o.innerHeight()}
            if (test.innerHeight>save.innerHeight) {
                fin=true;
                sentence = words.slice(0,word_count-1).join(" ")+"...";
            } else {
                word_count++;
                if (word_count>=words.length)fin=true;
            }
        }
        o.html( sentence );
    }
    o.addClass('truncated');
    o.css('height',save.height);
}

////////////////////////////////////////////////////////////////////

/*

jQuery.preloadCssImages = function(settings){

	settings = jQuery.extend({
		statusTextEl: null,
		statusBarEl: null,
		errorDelay: 999, // handles 404-Errors in IE
		simultaneousCacheLoading: 2
	}, settings);
	
	var allImgs = [],
		loaded = 0,
		imgUrls = [],
		thisSheetRules,	
		errorTimer;

	function loadImgs(){
		//only load 1 image at the same time / most browsers can only handle 2 http requests, 1 should remain for user-interaction (Ajax, other images, normal page requests...)
		// otherwise set simultaneousCacheLoading to a higher number for simultaneous downloads
		if(imgUrls && imgUrls.length && imgUrls[loaded]){
			var img = new Image(); //new img obj
			img.src = imgUrls[loaded];	//set src either absolute or rel to css dir
			if(!img.complete){
				jQuery(img).bind('error load onreadystatechange', onImgComplete);
			} else {
				onImgComplete();
			}
			errorTimer = setTimeout(onImgComplete, settings.errorDelay); // handles 404-Errors in IE
		}
	}



function onImgComplete(){
		clearTimeout(errorTimer);
		if (imgUrls && imgUrls.length && imgUrls[loaded]) {
			loaded++;
			if (settings.statusTextEl) {
				var nowloading = (imgUrls[loaded]) ? 
					'Now Loading: <span>' + imgUrls[loaded].split('/')[imgUrls[loaded].split('/').length - 1] : 
					'Loading complete'; // wrong status-text bug fixed
				jQuery(settings.statusTextEl).html('<span class="numLoaded">' + loaded + '</span> of <span class="numTotal">' + imgUrls.length + '</span> loaded (<span class="percentLoaded">' + (loaded / imgUrls.length * 100).toFixed(0) + '%</span>) <span class="currentImg">' + nowloading + '</span></span>');
			}
			if (settings.statusBarEl) {
				var barWidth = jQuery(settings.statusBarEl).width();
				jQuery(settings.statusBarEl).css('background-position', -(barWidth - (barWidth * loaded / imgUrls.length).toFixed(0)) + 'px 50%');
			}
			loadImgs();
		}
	}
}

////////////////////////////////////////////////////////////////////

$(window).bind('load', function() {
	var preload = flickrImageArray;
	var img = document.createElement('img');
    $(img).bind('load', function() {
    	alert(2);
        if(preload[0]) {
            this.src = preload.shift();
        }
    }).trigger('load');

	alert(1);

});

*/