var OUTER_RIMS = 71;
var COL_WIDTH = 161;

var currentPage = 1;	// will be overruled as soon as first pagination call is made
var callingAjax = false; // to hold off new ajax calls when still processing
var htmlToBeInserted;
var noMorePrev = false;

var dbModel = 'clients';

// overall flow:
// detect need for columns, e.g. at startup or at resize
// calculate number of columns needed
// request that number of columns
// if columns already exist, use last id as reference a point for cake
// receive them in column_set.ctp
// add them to div, next to already present columns
// iterate over columns, set all to invisible
// iterate over columns with timeout: make all appear


$(document).ready(function() {
	initPage();
	$(window).resize( resize );
	enablePrev();
	disableNext();
	startMainCarrousel();
	
});

function enablePrev(){
	$('#previousButton').click(getPrevSet);
	$('#prevSetButton').click(getPrevSet);
	$('#prev').click(getPrevSet);
	$('#prev').mouseover(function(){
		$('#'+this.id+' .navAppear').show();;
	});
	$('#prev').mouseout(function(){
		$('#'+this.id+' .navAppear').hide();;
	});
	$('#prev').css('cursor','pointer');
	$('#prevSetButton').css('text-decoration','none');
}
function disablePrev(){
	$('#prevButton').unbind('click');
	$('#prevSetButton').unbind('click');
	$('#prev').unbind('click');
	$('#prev').unbind('mouseover');
	$('#prev').unbind('mouseout');
	$('#prev').css('cursor','default');
	$('#prevSetButton').css('text-decoration','line-through');
	$('#prev .navAppear').hide();
	
	// also disable extra columns at resize
	noMorePrev = true;
}
function enableNext(){
	$('#nextButton').click(getNextSet);
	$('#nextSetButton').click(getNextSet);
	$('#next').click(getNextSet);
	$('#next').mouseover(function(){
		$('#'+this.id+' .navAppear').show();;
	});
	$('#next').mouseout(function(){
		$('#'+this.id+' .navAppear').hide();;
	});
	$('#next').css('cursor','pointer');
	$('#nextSetButton').css('text-decoration','none');
}
function disableNext(){
	$('#nextButton').unbind('click');
	$('#nextSetButton').unbind('click');
	$('#next').unbind('click');
	$('#next').unbind('mouseover');
	$('#next').unbind('mouseout');
	$('#next').css('cursor','default');
	$('#nextSetButton').css('text-decoration','line-through');
	$('#next .navAppear').hide();
}

function initPage(){
	var columnCount = calculateRows();
	
	// make ajax call
	if(!callingAjax){
		callingAjax = true;
		$.ajax({
			url: root+dbModel+"/nextSet/page:" + currentPage + "/limit:" + columnCount + "/filter:" + filter,
			cache: false,
			success:function(html){
				// fille div with hidden columns
				$('#columns').append(html);
				callingAjax = false;
				
				// make columns appear			
				var firstone = $('#columns').children()[0];
				$(firstone).fadeIn(1000);
				var counter = 1;
				$(firstone).nextAll().each(function(){
					$(this).oneTime(400*counter, appear);
					counter ++;
				});
			},
			error: function(){
				callingAjax = false;
			}
		});
	}
}


function calculateRows(){
	return Math.floor(($('body').innerWidth() - OUTER_RIMS) / COL_WIDTH);
}

function appear(){
	$(this).fadeIn(1000);
	cutTextColumns();
}

function resize(){
	cutTextColumns()
	var columns = calculateRows();
	if($('#columns').children().length > columns){
		// remove certain elements if the current amount of children is larger than maximum
		while($('#columns').children().length > columns){
			// as long as there are more children than max allowed: remove last
			$("#columns div:last").hide();
			$("#columns div:last").remove();
		}
		enablePrev();
	}else if($('#columns').children().length == columns){
		// nothing, amount is exactly right
	}else{
		if(!noMorePrev){
			getExtraColumns();
		}
	}
}
	
// below is unchecked

function getExtraColumns(){
	// add elements
	var columns = calculateRows();

	// if there are already columns present, start
	var columnOffset = $('#columns').children().length;
	
	if(!callingAjax){	
		callingAjax = true;
		
		$.ajax({
			url: "/"+dbModel+"/nextSet/page:" + currentPage + "/limit:" + columns + "/offset:" + columnOffset,
			cache: false,
			success:function(html){
				$('#columns').append(html);
				makeColumnsAppear(columnOffset-1);
			},
			error: function(){
				callingAjax = false;
			}
		});
	}
}

function makeColumnsAppear(startColumn){
	callingAjax = false;
	if(startColumn == -1){
		startColumn = 0;
	}

	var firstone = $('#columns').children()[startColumn];
	$(firstone).fadeIn(1000);
	var counter = 1;
	$(firstone).nextAll().each(function(){
		$(this).oneTime(400*counter, appear);
		counter ++;
	});
	
	resize(); // in case resize has resumed, but callingAjax blocked it sofar
}

function getPrevSet(){
	//alert('getNextSet');
	currentPage ++;
	
	var columns = calculateRows();
	// do not execute when other ajax calls are being made
	if(!callingAjax){
		callingAjax = true;
		
		filterString = filter == '' ? '' : '/filter:'+filter;
		
		$.ajax({
			url: "/"+dbModel+"/nextSet/page:" + currentPage + "/limit:" + columns + filterString,
			cache: false,
			success:function(html){
				htmlToBeInserted = html;
				var delayIndex = $('#columns').children().length;
	
				$('#columns').children().each(function(){
					$(this).oneTime(80*delayIndex, disappearFast);
					delayIndex --;
				});
			},
			error: function(){
				callingAjax = false;
			}
		});
	}
	return false;
}
function disappearFast(){
	// do not fadeOut in order to keep width
	$(this).fadeTo(500, 0.01, removeShowcase);
}
function removeShowcase(){
	// only if ended up fadingOut at last showcase
	if(this.id == $('#columns').children()[$('#columns').children().length-1].id){
		$('#columns').empty();
		$('#columns').append(htmlToBeInserted);
		makeColumnsAppearFast();		
	}
}
function makeColumnsDisappearFast(){
	// start disappearing from the right
	var delayIndex = $('#columns').children().length;
	
	$('#columns').children().each(function(){
		$(this).oneTime(80*delayIndex, disappearFast);
		delayIndex --;
	});
}
function makeColumnsAppearFast(){
	// set all showcases to opacity 0.01, to give width

	$('#columns div.column').css('display', 'inline');
	/* UGLY PATCH!!! to avoid IE 7 and below*/
	if($.browser.msie && $.browser.version < 8){

	}else{

		$('#columns div.column').css('opacity', 0.01);
	}
		var counter = $('#columns').children().length; //1;
	
		$('#columns').children().each(function(){
			$(this).oneTime(80*counter, appearFast);
			counter = counter-1;
		});	
	callingAjax = false;
}



/* NEXT & PREVIOUS */
function appearFast(){
	$(this).fadeTo(500, 1);
	cutTextColumns();
}



/* PREVIOUS */
function getNextSet(){

	//alert('getNextSet');
	currentPage --;
	
	var columns = calculateRows();
	// do not execute when other ajax calls are being made
	if(!callingAjax){
		callingAjax = true;
		
		filterString = filter == '' ? '' : '/filter:'+filter;
		
		$.ajax({
			url: "/"+dbModel+"/nextSet/page:" + currentPage + "/limit:" + columns + filterString,
			cache: false,
			success:function(html){
				htmlToBeInserted = html;
				makeColumnsDisappearReversed();
			},
			error: function(){
				callingAjax = false;
			}
		});
	}
	return false;
}
function makeColumnsDisappearReversed(){
	// start disappearing from the left
	var delayIndex = 1;
	
	$('#columns').children().each(function(){
		$(this).oneTime(80*delayIndex, disappearFastReversed);
		delayIndex ++;
	});
}
function disappearFastReversed(){
	// do not fadeOut in order to keep width
	$(this).fadeTo(500, 0.01, removeShowcaseReversed);
}
function removeShowcaseReversed(){
	// only if ended up fadingOut at last showcase
	if(this.id == $('#columns').children()[$('#columns').children().length-1].id){
		$('#columns').empty();
		$('#columns').append(htmlToBeInserted);
		makeColumnsAppearFastReversed();		
	}
}
function makeColumnsAppearFastReversed(){
	// set all showcases to opacity 0.01, to give width
	$('#columns div.column').css('display', 'inline');
	$('#columns div.column').css('opacity', 0.01);

	var counter = 0; //$('#columns').children().length; //1;

	$('#columns').children().each(function(){
		$(this).oneTime(80*counter, appearFast);
		counter = counter+1;
	});	
	
	callingAjax = false;
	resize(); // in case resize has resumed, but callingAjax blocked it sofar
}

function cutTextColumns() {
	$('.text_holder').css('height', 'auto');
	$height = $($('.text_holder')[0]).innerHeight();
	$h = $height - $($('.subheader1')[0]).outerHeight();
	$rest = $height % 12;
	$newHeight = $($('.text_holder')[0]).innerHeight() - $rest;
	$('.text_holder').css('height', $newHeight);
}

var col_counter = 0;

function startMainCarrousel(){
	$(this).oneTime(4000, swapColumnImage);

}
function swapColumnImage(){

	var target_col = Math.floor(Math.random() * $('.column').length);

	if($($('.column')[target_col]).find('.thumb').length > 1){

		$($('.column')[target_col]).find('.thumb:visible').each(function(){	

			$(this).fadeOut(1000, fadeInNext);
		});
	}else{
		$(this).oneTime(1000, swapColumnImage);
	}
}

function fadeInNext(){
	
	
	if($(this).next('img.thumb')[0] != undefined){
		$(this).next().fadeIn(1000);
	}else{
		$($(this).siblings('img.thumb')[0]).fadeIn(1000);
	}

	$(this).oneTime(800, swapColumnImage);
}
