
var categories = {};
var galleries;
var galleriesLoaded = 0;
var cache = {};
var categoryId;
var leftmargin = '5%';
// main entry point
$(document).ready(function() {	
	// find out page left margin (according to window width)
	leftmargin = Math.round(($(window).width() - 850) / 2) + 'px';
	$('#recent').css('margin-left', leftmargin);
	$('#icon').css('margin-left', leftmargin);
	$('#likeFrame').css('margin-left', leftmargin);
	
	// icon click leads to main page
	$('#icon').click(function() {
		location.href = 'index.html';
	});
	
	// bind resize event to recalculate margin
	$(window).resize(function() {
		leftmargin = Math.round(($(window).width() - 850) / 2) + 'px';
		$('#recent').css('margin-left', leftmargin);
		$('#icon').css('margin-left', leftmargin);		
		$('#artichoke').css('margin-left', leftmargin);
		$('#likeFrame').css('margin-left', leftmargin);
	});
	// start loading data...
	categoryId = getParam('category');
	// get category list
	getJson('categories=true', buildToolbar);	
});

// get json from server, according to parameters
function getJson(params, callback) {
	$.ajax({
			url: 'content/jsonApi.php?' + params,
			dataType: 'json',
			success: function(data) {callback(data);}
		});
}

// build toolbar
function buildToolbar(data) {
	// make a hash out of 'categories'
	for (var i in data) {
		categories[data[i].id] = data[i].name;
	}
	var html = '<div id="artichoke" class="artichoke" style="margin-left:' + leftmargin + '"><a href="index.html" style="color:red;">MyArtichoke</a></div><div>';
	for (var i in data) {		
		html = html + '<a href="index.html?category=' + data[i].id + '"'; 
		if (data[i].id == categoryId) {
			html = html + ' class="selected" id="activatedlink"';
		}
		html = html + '>' + data[i].name + '</a>';
	}
	
	html = html + '<a id="infolink" href="index.html?info=true">Info</a>';
	html = html + '<a id="contactlink" href="index.html?contact=true">Contact</a></div>';	
	$('#toolbar').html(html);
	
	getJson('id=0', buildGalleriesPreview);	
}
// get latest galleries


function buildGalleriesPreview(data) {
	galleries = data;
	var html = '';
	// gallery data is sorted from latest, so now we can build previews
	if (categoryId == null) { // all galleries preview
		for (var i in categories) {
			// look for the latest gallery belonging to category
			for (var j=0; j<galleries.length; j++) {
				if (i == galleries[j].category_id) {
					buildGalleryPreview(galleries[j]);
					$('#recent').css('visibility', 'visible');
					break;
				}			
			}
		}		
	} else {	
		for (var j=0; j<galleries.length; j++) {
			if (categoryId == galleries[j].category_id) {
				buildGalleryPreview(galleries[j]);
				$('#recent').css('visibility', 'visible');
				break;
			}			
		}	
	}
	
	if (getParam('info') != null) {
		showInfo();
	} else if (getParam('contact') != null) {
		showContact();
	} else {
		// see if we're in category mode
		if (categoryId == null) {
			buildGalleries(data);
		} else {
			getJson('id=0&category_id=' + categoryId, buildGalleries);
		}	
		
	}
}

function buildGalleries(data) {
	galleries = data;
	getGalleryDetails(galleries[0].id, galleryLoaded);	
}

function getGalleryDetails(id, callback) {
	// see if gallery details are in cache
	if (cache[id] == undefined) {
		getJson('gallery_id=' + id, callback);
	} else { // hit, but callback needs arrayed data
		var ret = [];
		ret.push(galleries[cache[id]]);
		callback(ret);
	}
}

function buildGalleryPreview(galleryDetails) {	
	var galleryId = parseInt(galleryDetails.id);
	var category = categories[galleryDetails.category_id];	
	var galleryPreviewDiv = $('<div class="preview"/>');
	// build gallery preview div
	if (categoryId == null) {
		galleryPreviewDiv.html('<div class="previewheader"><a href="index.html?category=' 
																+ galleryDetails.category_id + '">' 
																+ category + '</a></div>'
																);	
	} else {
		$('#recentheader').html(category);
		galleryPreviewDiv.html('<div class="previewheader">Recent Work</div>');
	}
	
	if (galleryDetails.thumb_path != '') { // gallery thumb
		galleryPreviewDiv.append($('<div class="previewthumb"><a href="index.html?category=' + 
									galleryDetails.category_id + '"><img border="0" src="content/' + 
									galleryDetails.thumb_path + '" height=100></img></a></div>')
									);
	} else { // put place holder?
		
	}
	
	galleryPreviewDiv.append($('<div class="previewname">' + galleryDetails.name + '</div>'));		
	galleryPreviewDiv.append($('<div class="previewdescription">' + galleryDetails.description + '</div>'));

	// append to 'recent' frame
	$('#recent').append(galleryPreviewDiv);	
	// category description
	if (categoryId != null) {
		$('#recent').append($('<div class="categorydescription">' + categoryDescription[category] + '</div>'));
	}
	
}

function galleryLoaded(data) {	
	galleries[galleriesLoaded].data = data;
	buildGallery(galleriesLoaded);
	galleriesLoaded++;	
	
	var maxLength = galleries.length;
	if (categoryId == null) { // in case we're in main page
		maxLength = 7;
	}
	
	if ( galleriesLoaded < maxLength) { // get next gallery
		getGalleryDetails(galleries[galleriesLoaded].id, galleryLoaded);	
	} else {
		$('#content').css('visibility', 'visible');
	}		
}

function buildGallery(idx) {
	var galleryDetails = galleries[idx];
	var imagesrc = '';
	if (galleryDetails.data.length > 0) {
		imagesrc = galleryDetails.data[0].path;
	}
	var galleryDiv = $('<div class="gallery"/>');
	var galleryHtml = '<div class="galleryname">' + galleryDetails.name + '</div>';
	galleryHtml = galleryHtml + '<div class="gallerycategory">' + categories[galleryDetails.category_id] + '</div>';
	// image div id is img-[idx]
	galleryHtml = galleryHtml + '<div id="img-'+ idx + '"><img src="content/' + imagesrc + '"></img></div>';	
	// create link for each picture, only if there's more than one...	
	if (galleryDetails.data.length > 1) {
		var linksdivid = 'gallerylinks-' + idx;
		galleryHtml = galleryHtml + '<div class="gallerylinks" id="' + linksdivid + '">';
		var activeclass = ' class="activated" ';
		for (var i=0; i<galleryDetails.data.length; i++) {
			imgsrc = galleryDetails.data[i].path;
			var linkid = 'link-' + idx + '-' + i; // id for link (to mark as active)
			galleryHtml = galleryHtml + ' <a ' + activeclass + ' id="' + linkid + '" href="javascript:switchImage(\'img-' 
									  + idx + '\', \'' + imgsrc + '\' , \'' +  linksdivid + '\',\'' + linkid + '\')";>' 
									  + (i+1) + ' </a>';
			activeclass = ''; // activeclass only for the 1st image link
		}	
		galleryHtml = galleryHtml + '</div>';
	}
	
	galleryHtml = galleryHtml + '<div class="gallerydescription">' + galleryDetails.description + '</div>';
	
	if (galleryDetails.url != null && galleryDetails.url != '') {
		galleryHtml = galleryHtml + '<div class="galleryurl"><a href="' + galleryDetails.url + '">Visit site</a></div>';
	}	
	galleryDiv.html(galleryHtml);
	$('#content').append(galleryDiv);
}

// switches images on div
function switchImage(divid, src, linksdivid, linkid) {
	// cancel all activated in linksdivid
	$('#' + linksdivid).children().each(function() {
		$(this).removeClass('activated');		
	});
	// activate link
	$('#' + linkid).addClass('activated');
	
	var imgsrc = '<img src="content/' + src + '"></img>';
	$('#' + divid).html(imgsrc);
	
}

function showInfo() {	
	// hide content div
	$('#content').css('display', 'none');
	// show info div
	$('#info').css('display', 'block');
	// mark info toolbar as active
	
	$('#infolink').addClass('selected');
	
}

function showContact() {	
	// hide content div
	$('#content').css('display', 'none');
	// show contact div
	$('#contact').css('display', 'block');
	// mark contact toolbar as active, rest as non active	
	$('#contactlink').addClass('selected');
}

var categoryDescription = {
	'ID' : '"I\'d say that there are aspects of my life I\'m very content with, and yet I\'ll always be consumed with an intense yearning, and I think that\'s necessary. -total contentment can be a dangerous thing for a creative person."<div class="credit">Chip Kidd</div>',
	'Web' : '"I like the fact that design is audience-related. I like the fact that it\'s not "art" and that you\'re typically collaborating with other people."<br/><div class="credit">Stefan Sagmeister</div>',
	'Illustration' : '"My inspiration comes from everyday world: a bit of graffiti, an imperfect photo, signage, odd ephemera, textures or postcards, a good shot in a film or a piece of architecture."<div class="credit">Andy Potts</div> ',
	'Print' : '"I think that, to some degree, this is part of my character as a designer: To keep moving and not get stuck in my own past. This is what I try very hard to do."<div class="credit">Milton Glaser</div>'
};
