var synchro_counter = 1;
var image_resize = true;
var header_footer_height = 128;

var choice = {
	year: 'all',
	category: 'any',
	view: 'index'	
};

var choiceYear;
var choiceCategory;
var choicePos;
var choiceView;

var xmlDataSet;
var slideCount;

var currentRandom = true;
var currentSlide = 0; 
var currentSlideVariants = 1;

var currentSlideXML;
var currentView; // or 'index'

function changeCSS(x) {
// other colors and css properties can be changed here

//	$("body").css('backgroundColor',$(x).css('backgroundColor'));
	$("body").animate({ backgroundColor: $(x).css('backgroundColor') }, 350);

};

function updateIndexView() {
// update the index view
// populate #index1 with all the thumbnails
// works only if currentView is index

if (currentView == 'index' ) {

	var trackYear;
	var idx = $('#index1');
	idx.html('');
	var size = $('image', xmlDataSet).length;
	
	$($('image', xmlDataSet).get().reverse()).each(function(i) {
		var category = $(this).find("category").text();
		var choice = $(this).find("year").text();
		
		if (($(this).find("category").text() == choiceCategory || choiceCategory == 'any') && ($(this).find("year").text() == choiceYear || choiceYear == 'all')) {

			var img = new Image();
			var title = $(this).find("title").text();
			var year = $(this).find("year").text();
			
			//$(img).attr('src', $(this).find("src").text()).attr('alt', $(this).find("title").text()).attr('height', 160);

			// year div (if undefined or different then previous one)
			if ( trackYear == undefined || ( trackYear != undefined && trackYear != year )) {
				idx.append('<div class="year_div">' + year + '</div>');
			}
			trackYear = year;
			
			var tmpHTML;
			tmpHTML = '<div style="float:left"><a class="feature01" href="#year=' + year + '&view=detail&pos=' + (size-i-1).toString() + '"><span class="overlay01"><span class="caption01">' + title +'</span></span>';
			$('src', this).each(function () {
				//var src = this.textContent;
				src = $(this).text();
				// all pngs are replced with jpgs in thumbs
				// tmpHTML += '<img src="' + src.replace(/kunst\//,"thumb/").replace(/.png/,".jpg") + '"/>';
				tmpHTML += '<img src="';
				//var src2 = 'thumb/' + src.substr(5);
				//if ( src2.slice(length(src2)))
				if (src != undefined ) {
					tmpHTML += src.replace(/kunst\//,"thumb/").replace(/.png/,".jpg");
				}
				//tmpHTML += src2
				tmpHTML += '"/>';
				//idx.append('<div style="float:left"><img src="' + src.replace(/kunst\//,"thumb/") + '"/><p style="text-align:center;">\n' + title + '\n</p></div>');				
			});
			tmpHTML += '</a></div>';
			idx.append(tmpHTML);
			
		};
		
	});	
	
};

};

function updateView() {
// make sure that the currentView is equal choiceView

	if (currentView != choiceView) {
		toggleView(choiceView);	
	}

}

function toggleView(view) {
// change the view from index to detail and back

	if (view == 'index') {
	// if we need to show index then
	// if index div does not exists
	// then create it
	// show it with appropriate filter (rebuild if necessary)
		$('#slideshow2').hide();	
		$('#index1').show();
		currentView = 'index';
		updateIndexView();
		
	} else {
	// if we need to hide the index
	// then hide it (and call the update still)
		$('#index1').hide();
		$('#slideshow2').show();
		currentView = 'detail';
		updateCurrentSlide();

	};
	
};

function changeClass(x) {
// I'll have to get the parent and then set all parents to ggnav only and only this element to ggnav and selection


	$("li > a", $(x).parents("ul")).each(function() {	
//		if ($(this).text() == choiceYear || $(this).text() == choiceCategory) {
//			$(this).addClass("selection");
//		} else {
//			$(this).removeClass("selection");
//		}
		if ($(this).text() == $(x).text()) {
			$(this).parent().addClass("selection");
		} else {
			$(this).parent().removeClass("selection");
		}
	});
	//$(x).addClass("selection");	
};

function updateTexts() {

var d1 = $('#alt_text');		// work details
var d2 = $('#caption_text');	// image curr of slideCount
var d3 = $('#section_title');	// selection text

var strHTML;
var category_description;
switch (choiceCategory) {
case 'any':
	category_description = '';
	break;
case 'painting':
	category_description = ' (painting | drawing)';
	break;
case 'sculpture':
	category_description = ' (sculpture | installation)';
	break;
case 'performance':
	category_description = ' (performance)';
	break;
}

strHTML = 'selected work:' + ((choiceYear == 'all') ? '' : ' ' + choiceYear ) +  category_description;

// for categories
d3.html(strHTML);
		
if (currentView == 'detail') {

	if (slideCount > 0) {

		d1.html("<i>" + currentSlideXML.find("title").text() + "</i>&nbsp;&nbsp;|&nbsp;&nbsp;");
		// year
		d1.append(currentSlideXML.find("year").text());
		// description
		d1.append("&nbsp;&nbsp;|&nbsp;&nbsp;" + currentSlideXML.find("description").text());
		// size
		d1.append("&nbsp;&nbsp;|&nbsp;&nbsp;" + currentSlideXML.find("size").text());	
		// details 
		//d1.append("<p>" + currentSlideXML.find("details").text() + "</p>");
		d2.html(currentSlide + ' of ' + slideCount);

	} else {
	
		d1.html('No image in selected year with selected type');
		d2.html('0');
	}

} else {

	d1.html('');
	d2.html(slideCount);
	
}
	
}

function updateCurrentSlide() {
// If the current view is detail
// then update #slideshow2

	if (choicePos != undefined) {
		currentSlideXML = $($('image', xmlDataSet).get(choicePos));
	}

	if (currentSlideXML == undefined) {
		browseXML();
	}

	var s = $('#slideshow2');
	// var oldimg = $(':first-child', s);

	// remove all existing images
	while (s.children().size() > 0) {
		$(':first-child', s).remove();
	}
	
	//oldimg = $(':first-child', s);	
	var status = $('#status > img');	
	
	if (slideCount != 0) {	

		if (currentView == 'detail') {

			synchro_counter++;
			status.show();
			
			currentSlideXML.find("src").each(function () {
			
				/* var img = new Image(); */
				var img = document.createElement('img');
				/*$(img).hide();*/
				//console.debug($(this).text());
				function myOnLoad(e) {
					/* $(img).hide(); */
					$(this).hide();
					
					if (e.data.counter == synchro_counter) {
						if (image_resize) {
							if (this.height > ($(window).height() - header_footer_height)) {
							//  FIX: IE resizes and messes the aspect ratio so I am setting both height and widht
								var newWidth = parseInt( ( $(window).height() - header_footer_height ) * this.width / this.height );
								$(this).attr( 'height', $(window).height() - header_footer_height );
								$(this).attr( 'width', newWidth );
							}
						}
						//var s_internal = $('#slideshow2');
						// FIX - how to guarantee the 
						s.append(img);
						$(img).fadeIn('slow');
						$(status).hide();
					}
					
				}

				$(img).bind( "load", {counter: synchro_counter}, myOnLoad );
			
				//$(img).load( myOnLoad );
				
				$(img).attr('src', $(this).text()).attr('alt', currentSlideXML.find("title").text()).css("position", "relative");	
				/*img.src = img.src;*/
				
			});

		} else {
		
			//d1.html('');

		};

	// slideCount is 0
	} else {

		
//		oldimg.fadeOut('slow');
		status.hide();

	}
	
	updateTexts();

};

function browseXML() {
	//strHTML = currentSlide + ' Year: ' + choiceYear + ' Category: ' + choiceCategory;
	// browse through the xmlDataSet for the records that match what we need and build the thing for the slideshow2

	currentSlide = 0;
	slideCount = 0;

	// count them - sets the count
	$('image', xmlDataSet).each(function(i) {
		var category = $(this).find("category").text();
		var choice = $(this).find("year").text();
		if (($(this).find("category").text() == choiceCategory || choiceCategory == 'any') && ($(this).find("year").text() == choiceYear || choiceYear == 'all')) {
			slideCount++;		
		};
	});

	if (slideCount > 0) {
		if (currentRandom) {
			currentSlide = Math.ceil(Math.random()*slideCount);
			currentRandom = false;
		} else {
			currentSlide = 1;
		}
	}
	
	// get the first one that satisfies the criteria and also the total count
	var loopCount = 0;
	var found = false;
	var tmpCurrentSlideXML;
	$('image', xmlDataSet).each(function(i) {
		var category = $(this).find("category").text();
		var choice = $(this).find("year").text();
		if (($(this).find("category").text() == choiceCategory || choiceCategory == 'any') && ($(this).find("year").text() == choiceYear || choiceYear == 'all')) {
			loopCount++;
			if (i == choicePos) {
				found = true;
				currentSlide = loopCount++;
				currentSlideXML = $(this);
			}			
			if (loopCount == currentSlide) {
				tmpCurrentSlideXML = $(this);
			}
		};
	});
	
	if (!found) {
		currentSlideXML = tmpCurrentSlideXML;
	};

	//updateCurrentSlide();
	//updateIndexView();
	
	//setupCycle(s);
	// then call fillDetailsForCurrentSlide
	//$('#alt_text').html(strHTML);
	
};

function moveToXML(d, to_pos) {
// d is either +1 or -1
// to_pos is absolute position

	var pos;
	if ( to_pos == undefined ) {
		if ( slideCount != 0 ) {
			if ((currentSlide + d) <= 0) {
				currentSlide = slideCount;
			} else if ((currentSlide + d) > slideCount) {
				currentSlide = 1;
			} else {
				currentSlide += d;
			}	
		}
	}

	// get the first one that satisfies the criteria and also the total count
	var loopCount = 0;	
	$('image', xmlDataSet).each(function(i) {
		var category = $(this).find("category").text();
		var choice = $(this).find("year").text();
		if ((category == choiceCategory || choiceCategory == 'any') && (choice == choiceYear || choiceYear == 'all')) {
			loopCount++;		
			if ( to_pos != undefined ) {
				if ( to_pos == i ) {
					currentSlide = loopCount;
					currentSlideXML = $(this);
					link_to( 'pos', i );
				}
			} else {
				if ( currentSlide == loopCount ) {
					currentSlideXML = $(this);
					link_to( 'pos', i );
				}
			}
		}
	});
	slideCount = loopCount;
	
	return false;
	
};

function parse_fragments() {
// get 

	var temp = $.fragment().year;
	if ( temp != undefined ) {
		choiceYear = temp;
	}
	temp = $.fragment().category;
	if ( temp != undefined ) {
		choiceCategory = temp;
	}
	temp = $.fragment().pos;
	if ( temp != undefined ) {
		choicePos = temp;
	}
	temp = $.fragment().view;
	if ( temp != undefined ) {
		choiceView = temp;
	}

};

function link_to( param, value ) {
// this function sets url
// also it trigers fragmentChange
// some values are cleaned

	var fr = $.fragment();
	
	if ( param == 'year' || param == 'category' ) {
		if (fr[ param ] != value) {
			delete fr.pos;
		}
	}

	if ( param == 'view' ) {
		if (fr[ param ] != value) {
			delete fr.pos;
		}
	}

	
	if ( param == 'year' ) {
		if ( fr[ param ] != value && value != 'all' ) {
			// FIX ME: it could be kept if we would have a function to check if it exists in the filter
			choicePos = undefined;
			currentSlideXML = undefined;
		}
	}
	
	if ( param == 'category' ) {
		if ( fr[ param ] != value && value != 'any' ) {
			// FIX ME: it could be kept if we would have a function to check if it exists under the filter
			choicePos = undefined;
			currentSlideXML = undefined;
		}
	}	
	
// do the actual change	
	fr[ param ] = value;

	if ( fr.view == 'index' ) {
		choicePos = undefined;
		delete fr.pos;
	}	
	
	if ( fr.year == 'all' ) {
		delete fr.year;
	}
	if ( fr.category == 'any' ) {
		delete fr.category;
	}	

	$.setFragment( fr, 2 );  // force replace
	
}

function update_view() {
	// get the fragment	
	var triggerUpdateCurrentSlide = 0;
	var fr = $.fragment();
	if ( fr.view == undefined ) { fr.view = 'index'; }
	if ( fr.year == undefined ) { fr.year = 'all'; }
	if ( fr.category == undefined ) { fr.category = 'any'; }
	
	// changing the view
	if (fr.view != choiceView) {
		choiceView = fr.view ;
		updateView();				// what if the index is not in the current selection?
		updateTexts();				// update the texts
		if (fr.view == 'detail') {
			triggerUpdateCurrentSlide = 1;
		}
	}
	
	// changing the position
	if (fr.pos != undefined) {
	// update the currentSlide
		if (fr.pos != choicePos) {
			choicePos = fr.pos;
			triggerUpdateCurrentSlide = 1;
		} else {
			choicePos = undefined;
		}
	}
	
	// changing the filter
	if (fr.year != choiceYear || fr.category != choiceCategory) {
	// filter XML
		if (fr.year != choiceYear) {
			changeClass($('#year_' + fr.year.replace(/ /,"_")));
		}
		if (fr.category != choiceCategory) {
			changeClass($('#category_' + fr.category));
		}
	
		choiceYear = fr.year;
		choiceCategory = fr.category;
		if (choiceView == 'index') {
			browseXML();
			updateIndexView();
			updateTexts();
		} else {
			browseXML();
			updateTexts();
			triggerUpdateCurrentSlide = 1;
		}
	}
	
	if (triggerUpdateCurrentSlide == 1) {
		updateCurrentSlide();	// updates the title and position
	}
	
}

$(function() {

	$.ajax({
		type: "GET",
		url: "images.xml",
		dataType: "xml",
		async: false,
		success: function(xml) {
			xmlDataSet = xml;
			// before browsing I should check for the variables passed to the page
			// this will trigger only once 
			update_view();
/*			parse_fragments();
			updateView();
			
			// browseXML
			// updateCurrentSlide();*/

		}
	});

	// activate the event
	$.fragmentChange( 100 );
	$(document).bind('fragmentChange', function (e) {

		update_view();
		/*
		parse_fragments();
		// update index or detail
		updateView();
		// update the year and category
		// FIX ME - write this
		// move to the right position
		browseXML();
		moveToXML(0, choicePos);*/
		
	});

});