//globals. 
var _gallery_title = "t413.com";
var _trans = false; //used to detect css transition support.
var _supports_history = false; //used to detect html5 history support.
var page_ajax_cache = {};
var albums_ajax_cache = {};
var _last_filter = "";
var _last_active_sidebar_link = 0; //when updating the sidebar, holds last active link
var _my_tag_priority = "5star,4star,green";
var _loaded_browse = 1;

/* clicked_link()
 * called from every a's onclick event
 */
function clicked_link() {
	var page = this.href.split("/").splice(3,6).join("/"); //remove hostname.
	if (this.href.charAt(0) === "/") { page = this.href.substr(1); } //fix for IE 6 and 7
	load_page(page);
	return false;
}

function get_current_page(){
	if (_supports_history) { return location.pathname; }
	else { return location.hash.substr(1); }
}

function load_page(page_url){
	if (_supports_history) {
		if (page_url[0]!=="/") { page_url = "/"+page_url; }
		history.pushState(null, null, page_url);
		hash_changed_function(page_url);
	}
	else { jQuery.history.load(page_url); }
}
	
function get_filtered_alb_img_array(alb, the_filter, tag_list){
	if (!is('Object', alb) || !is('String',the_filter)) { return -1; } //needs album object
	
	the_filter = the_filter.split(",");
	//console.log("filtering with: "+ the_filter.toString() );
	
	var tag_limited_list = []; //returns this ordered list of [0,1,2,3]=>key numbers (0,3,4,8)
	if (!is('Object', tag_list)) var tag_list = {}; //also (optionally) saves an array of what tags are in the album to tag_list
	for (var i in alb.images) {  //loop through each image
		for (var j in alb.images[i].tags){ //loop through each image's tags
			tag_list[alb.images[i].tags[j]] = (!is('Number',tag_list[alb.images[i].tags[j]]))? 1:(tag_list[alb.images[i].tags[j]]+1) ;
			for (var k=0; k<the_filter.length; k++) { //loop through each of the to-be-included tags
				if (alb.images[i].tags[j] === the_filter[k]) {
					tag_limited_list.push(i);
				}
			}
		}
		if (the_filter[0]==='all') { tag_limited_list.push(i); }
	}
	//console.log("found: "+ tag_limited_list.toString() );
	return tag_limited_list;
}

function change_page_by_offset(offset){
	var page_type = decode_page_url_type(get_current_page());
	if ( !is('Array',page_type)) { return; }
	if (page_type[0] === 'image'){
		var my_alb = find_album_in_chache(page_type[1]);
		if ( !is('Object', my_alb)) { return; }
		var alb_default = _my_tag_priority; //TODO: make it configurable "alb.data.default_tag"
		var tags = {};
		var tag_limited_list = get_filtered_alb_img_array(my_alb, (_last_filter==="")? alb_default : _last_filter, tags);
		
		for (var i in tag_limited_list) {
			if (my_alb.images[tag_limited_list[i]].file===page_type[2]) {
				var next_img = my_alb.images[ tag_limited_list[i*1+offset*1] ];
				if (is('Object', next_img)) {
					load_page(page_type[1]+"/"+next_img.file+".php");
					return;
				} else { return; } //end or beginning of album
			}
		}
		_last_filter = "all";  //if we get here then we didn't find the image. 
		change_page_by_offset(offset);
	}
	else if (page_type[0] === 'browse'){
		var num_albums = (albums_ajax_cache[0])? (albums_ajax_cache[0]['page_of']):10;
		var new_p = (page_type[1]*1+offset*1); //get the new page in NUMBER form (thanks JS)
		new_p = (new_p<1)? 1: (new_p>num_albums)? num_albums:new_p; //limit the new page #'s range between 1 and the number of pages
		load_page("page/browse/"+new_p);
	}
	//add album keynav
}

/* decode_page_url_type()
 * returns the general type of page we're viewing.
 * Input: the url, excluding the host or leading /, that's generating us.
 * Output: EITHER a string: home, news, pages, or page
 * or ['browse',page# ], ['image',alb,img ], ['album',alb,page# ]
 */
function decode_page_url_type(this_hash){
	if (this_hash[0]==="/") { this_hash = this_hash.substr(1); }
	var hash_split = this_hash.split("/");
	if ((this_hash === 'all')||(this_hash === '')) { return 'home'; }
	else if (hash_split[0] === "news") { return 'news'; }
	else if (hash_split[0] === "pages") { return 'pages'; }
	else if ((hash_split[0] === "page") && (hash_split[1] === "browse")) {
		var page_num = hash_split[2];
		if (!page_num) { page_num = 1; }
		return ['browse',page_num];
	}
	else if (hash_split[0] === "page") { return 'page'; }
	else {
		if (rslts = /(.*)\/page\/([0-9]+)\/?/i.exec(this_hash)) {
			return ["album",rslts[1], rslts[2]]; //album, page
		}
		else if (rslts = /(.*)\/(.*).php\/?/.exec(this_hash)){
			return ["image",rslts[1], rslts[2]]; //album, image
		}
		else { 
			if (this_hash.charAt(this_hash.length-1) === '/') { this_hash = this_hash.slice(0, -1); }  //fixed for IE 6 and 7
			return ["album",this_hash, 1]; 
		} //album, page
	}
}

function hash_changed_function(this_hash){
	if ((this_hash === "")||(this_hash === "/")) { this_hash = "all"; }
	if ( is('String', this_hash) && (this_hash[0]==="/")) { this_hash = this_hash.substr(1); }
	var page_type = decode_page_url_type(this_hash);
	
	if (!( is('Array', page_type) && (page_type[0]==='image'))) { $('#img_display').hide(); }
	
	if ( is('Array',page_type)) {
		load_json_content(page_type);
		
		var sidebar_links = document.getElementById("nav").getElementsByTagName('a');
		if (_last_active_sidebar_link) { $(_last_active_sidebar_link).removeClass('current'); }
		$(sidebar_links[1]).addClass('current');
		_last_active_sidebar_link = sidebar_links[1];
		$('ul.tabs li').removeClass('current');
		$('.tab_photos').addClass('current');
	}
	else { //(all, news, pages)
		$('#top,#nav').show(); $('#stories').width('600px');
		update_breadcrumb(page_type);
		if (page_ajax_cache[this_hash]) { changePage(page_type,page_ajax_cache[this_hash],this_hash); }
		else {
			$('#stories').html("<img src='/themes/timpage/i/ajax-loader.gif' />");
			$.get('/index.php',{"p":"ajax","type":"index","id":this_hash}, 
				function(returned_data){
					changePage(page_type,returned_data,this_hash);
					if (this_hash !== "page/cart/") { //disable caching on cart page.
						page_ajax_cache[this_hash] = returned_data;
					}
					if (window['localStorage']) {
						localStorage.setItem('index',  JSON.stringify(page_ajax_cache) );
						localStorage.setItem('index_time', (new Date()).getTime() );
					}
				},"html");
		}
	}
}


function load_json_content(page_type, callback) {
	/* ------------------------------------------- */
	/* ---- BROWSE view (load lots of albums) ---- */
	if (page_type[0] === 'browse') {
		var found = 0;
		for (var key in albums_ajax_cache){
			if (albums_ajax_cache[key]['page'] == page_type[1]){ found = 1; break; }
		}
		if (found){ 
			if (is('Function',callback)) { callback(page_type[1]); }
			else { 
				build_browse(page_type[1]); 
				display_header_page(page_type[1]); 
				update_breadcrumb(page_type); 
			}
		}
		else {
			if ( ! is('Function',callback)) { $('#stories').html("<img src='/themes/timpage/i/ajax-loader.gif' />"); }
			$.getJSON('/index.php',{"p":"ajax","type":"dyn_browse","page":page_type[1]}, 
				function(new_data){
					for (var key in new_data){
						var id = new_data[key]['data']['sort_key']
						albums_ajax_cache[id] = new_data[key];
					}
					if (is('Function',callback)) { callback(page_type[1]); } 
					else {
						build_browse(page_type[1]); 
						update_breadcrumb(page_type);
					}
					build_header_page(page_type[1]);
					if (window['localStorage']) {
						localStorage.setItem('index_dyn',  JSON.stringify(albums_ajax_cache) );
						localStorage.setItem('index_time', (new Date()).getTime() );
					}
				});
		}
	}
	/* ------------------------------------------ */
	/* ---- ALBUM view (load lots of photos) ---- */
	else if (page_type[0] === 'album'){
		var this_album = find_album_in_chache(page_type[1]);
		if ( is('Object',this_album)){
			if (typeof(this_album['images']) !== "undefined"){
				if (is('Function',callback)) { cfback(page_type[1]); }
				else { build_album(this_album); update_breadcrumb(page_type); }
			}
			else {
				if ( ! is('Function',callback)) { $('#stories').html("<img src='/themes/timpage/i/ajax-loader.gif' />"); }
				$.getJSON('/index.php',{"p":"ajax","type":"dyn_alb","alb":page_type[1]}, 
					function(new_data){
						this_album['images'] = new_data;
						if (is('Function',callback)) { callback(page_type[1]); }
						else { build_album(this_album); update_breadcrumb(page_type); }
						if (window['localStorage']) {
							localStorage.setItem('index_dyn',  JSON.stringify(albums_ajax_cache) );
							localStorage.setItem('index_time', (new Date()).getTime() );
						}
					});
			}
		}
		else {
			load_json_content(['browse', _loaded_browse ], //load the missing album page
				function(){ load_json_content(page_type); } ); //and call this whole thing back again
			_loaded_browse += 1;
		}
	}
	/* ----------------------------------------------------------- */
	/* ---- IMAGE view (make sure browse and album are ready) ---- */
	else if (page_type[0] === 'image'){
		var my_alb = find_album_in_chache(page_type[1]);
		if (is('Object', my_alb)){
			var my_img = find_image_in_album(my_alb,page_type[2]);
			if (is('Object',my_img)){
				build_image(my_img.img);
				update_breadcrumb(page_type);
				preload_image(my_img.key*1+1, my_alb);
			}
			else {
				load_json_content(['album',page_type[1]], //load the missing album page
					function(){ load_json_content(page_type); } ); //and call this whole thing back again
			}
		}
		else {
			load_json_content(['browse', _loaded_browse ], //load the missing album page
				function(){ load_json_content(page_type); } ); //and call this whole thing back again
			_loaded_browse += 1;
		}
	}
}



function build_browse(which_page){
	var container = document.getElementById('stories');
	var new_page = make_element("div", "albums");
	$('#top,#nav').show(); $('#stories').width('600px');
	
	build_header_page(which_page);
	if (albums_ajax_cache[0]) { //check to see if we'll be able to see how many pages there are
		var num_albums = albums_ajax_cache[0]['page_of']+1;
		build_pagenav(which_page,num_albums,new_page); //build page navigation bar
	}
	
	for (var i in albums_ajax_cache){
		if (albums_ajax_cache[i]['page'] != which_page) { continue; }
		var new_album = make_element("div", "","album",{},new_page);
		  var new_a = make_element("a", "", "albumthumb", {'href':albums_ajax_cache[i]['data']['url'],'title':albums_ajax_cache[i]['data']['title']} , new_album);
		    var new_img = make_element("img","","", {'src':albums_ajax_cache[i]['data']['bthumb']}, new_a);
		  var new_title = make_element("div","","albumtitle", {}, new_album);
		    var new_h3 = make_element("h3","","", {}, new_title);
		    var new_date = make_element("span","","zp_uneditable_album_date", {'html':albums_ajax_cache[i]['data']['date']}, new_title);
		     var new_a_tlt = make_element("a","","", {'html':albums_ajax_cache[i]['data']['title'], 'href':albums_ajax_cache[i]['data']['url'],'title':albums_ajax_cache[i]['data']['title']}, new_h3);
		  var new_desc = make_element("div","","albumdesc", {'html':albums_ajax_cache[i]['data']['desc']}, new_album);
	}
	container.innerHTML = ""; //clear old content
	container.appendChild(new_page); //add our new stuff!
	convert_all_links(container); //attatch the listener events to the new links
}

function build_album(alb){
	if (is('String', alb)) alb = find_album_in_chache(alb);
	if ( !is('Object', alb)) { return -1; } //double checking
	$('#top,#nav').show(); $('#stories').width('600px');
	
	var imgs = alb['images'];
	var subs = alb['subalbums'];
	var new_alb = make_element("div", "albums");
		
	/*---build the album's subalbums---*/
	for (var i in subs){
		var new_album = make_element("div", "","album",{},new_alb);
		  var new_a = make_element("a", "", "albumthumb", {'href':subs[i]['data']['url'],'title':subs[i]['data']['title']} , new_album);
		    var new_img = make_element("img","","", {'src':subs[i]['data']['bthumb']}, new_a);
		  var new_title = make_element("div","","albumtitle", {}, new_album);
		    var new_h3 = make_element("h3","","", {}, new_title);
		    var new_date = make_element("span","","zp_uneditable_album_date", {'html':subs[i]['data']['date']}, new_title);
		     var new_a_tlt = make_element("a","","", {'html':subs[i]['data']['title'], 'href':subs[i]['data']['url'],'title':subs[i]['data']['title']}, new_h3);
		  var new_desc = make_element("div","","albumdesc", {'html':subs[i]['data']['desc']}, new_album);
	}

	var tags = {}; //build an object of "tag"=>#of instances
	var alb_default = _my_tag_priority; //TODO: make it configurable "alb.data.default_tag"
	var shown_items = get_filtered_alb_img_array(alb, (_last_filter==="")? alb_default : _last_filter, tags);
	if ((shown_items.length < 1) || ((shown_items.length < 4) && (_last_filter===""))) shown_items = get_filtered_alb_img_array(alb, (_last_filter="all"), tags);
	tags['all'] = imgs.length; //make a tags list entry that says 'all'
	/*---build ul of tags, clickable to filter---*/
	var images_cont = make_element("div", "images_cont");
	var new_ul = make_element("ul","tag_filter","",{}, new_alb);
	for (var tagname in tags){
		var new_li = make_element("li","",(_last_filter===tagname)?"current":"",{}, new_ul);
		var this_a = make_element("a","","",{'html':tagname+" ("+tags[tagname]+" images)",'title':tagname}, new_li);
		this_a.onclick = function(){ _last_filter = this.title; build_album(alb); };
	}
	/*---build the album's images---*/
	for (var p in shown_items){
		var i = shown_items[p];
		var new_a = make_element("a", "",'tag'+imgs[i].tags[0],{'href':imgs[i].link,'title':imgs[i].ti}, images_cont);
		 make_element("img", "","",{'src':imgs[i].thumb,'alt':imgs[i].ti}, new_a);
	}
	var conta = document.getElementById('stories');
	conta.innerHTML = ""; //clear old content
	var exif_div = make_element("div", "exif_charts","",{},conta);
	var exif_link = make_element("a", "","",{'html':'Show charts and statistics','href':'javascript:void(0);'}, exif_div);
	exif_link.onclick = function(){ show_graphs(); };
	conta.appendChild(new_alb); //add our new stuff!
	conta.appendChild(images_cont); //add our new stuff!
	convert_all_links(conta); //attatch the listener events to the new links
}

function build_image(which_image, which_album){
	if (!is('Object', which_image)) { which_image = albums_ajax_cache[which_album]['images'][which_image]; }
	if (!is('Object', which_image) || (which_image == null)) { return -1; } //double checking

	$('#top,#nav').hide(); $('#stories').width('95%');
	
	var cont = document.getElementById('stories');
	cont.innerHTML = ""; //clear old content
	var main_image = make_element("div", "main_image", "", {} , cont);
	  var prev_i = make_element("a", "prev", "prev", {'html':' &laquo; prev','href':'javascript:void(0)'} , main_image);
	   prev_i.onclick = function(){change_page_by_offset(-1);return false;}
	  var next_i = make_element("a", "next", "next", {'html':'next  &raquo;','href':'javascript:void(0)'} , main_image);
	   next_i.onclick = function(){change_page_by_offset(1);return false;}
	  var image_area = make_element("div", "image_area", "", {} , main_image);
	    var mainImg = make_element("img", "mainImg", "", {'src':which_image.i_src} , image_area);
		mainImg.height = which_image.h;
		mainImg.width = which_image.w;
	    var spinner = make_element("img", "spinner", "", {'src':'/themes/timpage/i/ajax-loader.gif'} , image_area);
	var below_images = make_element("div", "below_images", "", {} , cont);
		var image_actions = make_element("div", "image_actions", "", {} , below_images);
		  //TODO: make this better integrated into the cart.
		  if (1) { var buy_this = make_element("a", "buy_this", "actns", {'html':'Order Prints'} , image_actions); }
		  var playSlide = make_element("a", "playSlide", "actns", {'html':'Play'} , image_actions);
		  if (is('String',which_image.full)) { make_element("a", "download_this", "actns", {'html':'Download','href':which_image.full} , image_actions); }
		if (is('String',which_image.desc)) { make_element("div", "descptn", "", {'html':which_image.desc} , below_images); }
		var exif_info = make_element("div", "exif_info", "", {} , below_images);
		  var exif_info = make_element("a", "show_all", "", {'html':'show image info','href':'javascript:;'} , exif_info);
			
			exif_info.onclick = function(){
				var this_page = decode_page_url_type( get_current_page() );
				var old_table = document.getElementById('_data')
				var exif_cont = document.getElementById('exif_info');
				if (old_table){
					exif_cont.removeChild(old_table);
					document.getElementById('show_all').innerHTML = 'show image info';
					return;
				}
				
				document.getElementById('show_all').innerHTML = 'hide image info';
				function build_table(data){
					var alb_meta = jsonParse(data);
					var whi_alb = find_album_in_chache(this_page[1]);
					var whi_img = find_image_in_album(whi_alb, which_image.file );
					
					/*--this builds the image exif info--*/
					var tabl = make_element("table", "_data", "", {} , exif_cont);
					  var tbody = make_element('tbody', "", "", {} , tabl);
					  for (var item in alb_meta[whi_img.key]){
					  	var tr = make_element('tr', "", "", {} , tbody);
					  	make_element('td', "", "label", {'html':item} , tr);
					  	make_element('td', "", "value", {'html':alb_meta[whi_img.key][item].value} , tr);
					  }
				}
				if ((window['localStorage']) && (store = localStorage.getItem( 'exif_data_'+this_page[1] ))) { build_table( store ); }
				else {
					$.get('/index.php',{"p":"ajax","type":"alb_exif","alb":this_page[1]}, 
						function(ret){ 
							if (window['localStorage']) {localStorage.setItem( 'exif_data_'+this_page[1] , ret );}
							build_table(ret);
						} ,"html");
				}
				
			};
	

	/*$(main_img).bind("load", function () {
		main_img.style.display = 'block';
		spin_img.style.display = 'none';
	});
	setTimeout(show_image_anyway, 2000); //this is in case the .bind("load") event doesn't fire (happends a lot)
	*/
	//make_element("img", "","",{'src': which_image.i_src,'alt': which_image.ti}, contai);
	convert_all_links(cont); //attatch the listener events to the new links
}

//this is in case the .bind("load") event doesn't fire (happends a lot)
function show_image_anyway(){ document.getElementById('mainImg').style.display='block'; document.getElementById('spinner').style.display='none'; }

function close_image_display(){
	decode_page_url_type(location.pathname);
	var page_type = decode_page_url_type(get_current_page());
	if (!is('Array', page_type)) { return; }
	var new_url = page_type[1]+"/";
	
	if (_supports_history) {
		history.pushState(null, null, "/"+new_url);
		hash_changed_function(new_url);
	}
	else { jQuery.history.load(new_url); }
}


var cache = []; // for preloading images
function preload_image(key, album){
	if (document.images) { //if we support preloading images..
		if ((key >= 0) && (key in album.images)){
			cacheImage = new Image(); 
			cacheImage.src = album.images[key].i_src; 
			cache.push(cacheImage);
		}
	}
}



function update_breadcrumb(page_type) {
	var bc = document.getElementById('breadcrumb');
	/* ---- clear/set default breadcrumb ---- */
	bc.innerHTML = '';
	var home_li = make_element("li", "bc_home","home",{}, bc);
	make_element("a", "","",{'href':'/','html':'Home'}, home_li);
	
	/* ---- un-highlight the current album in the header ---- */
	if (!(( is('Array', page_type)) && (page_type[0] == "album"))) { $('#top_slider .current').removeClass('current'); }
		
	/* ---- build breadcrumb ---- */
	if ( is('Array', page_type)) {
		$(bc).slideDown(200);
		if (page_type[0] == "browse") {
			build_header_page(page_type[1]); display_header_page(page_type[1]);
			var new_li = make_element("li", "bc_browse","",{}, bc);
			var new_a  = make_element("a", "","",{'href':'/page/browse','html':'Browse'}, new_li);
			$(bc).slideDown();
			document.title = _gallery_title+" - Browse page "+page_type[1];
		}
		if ((page_type[0] == "album") || (page_type[0] == "image")){
			var alb = find_album_in_chache(page_type[1]);
			build_header_page(alb.page); display_header_page(alb.page);
			/* ---- highlight the current album in the header ---- */
			var sli_ims = document.getElementById('slider_p_'+alb.page);
			if (sli_ims != null) {
				sli_ims = sli_ims.children;
				for (var i=0;i<sli_ims.length;i++){
					sli_ims[i].className = (sli_ims[i].title==alb.data.name)? "current" : "";
				}
			}
			
			var new_li = make_element("li", "bc_browse","",{}, bc);
			make_element("a", "","",{'href':'/page/browse','html':'Browse'}, new_li);
			var new_alb = make_element("li", "bc_alb","",{}, bc);
			make_element("a", "","",{'href':alb.data.url,'html':alb.data.title}, new_alb);
			if (page_type[0] == "image") {
				var img = find_image_in_album(alb, page_type[2]);
				var img_li = make_element("li", "bc_image","",{}, bc);
				make_element("a", "","",{'href':img.img.link,'html':img.img.ti}, img_li);
				document.title = _gallery_title+" - "+alb.data.title+" - "+img.img.ti;
			}
			else { document.title = _gallery_title+" - "+alb.data.title; }
		}
	}
		// Output: EITHER a string: home, news, pages, or page
		// or ['browse',page# ], ['image',alb,img ], ['album',alb,page# ]
	else if (page_type == "home") { $(bc).slideUp(200); document.title = _gallery_title; }
	else if (page_type == "pages") { $(bc).slideUp(200); document.title = _gallery_title+" - Pages"; } //TODO: make this actually show interesting info
	else if (page_type == "news") {
		var news_li = make_element("li", "bc_news","",{}, bc);
		make_element("a", "","",{'href':'/news','html':'News'}, news_li);
		$(bc).slideDown(200);
		document.title = _gallery_title+" - News"; //TODO: make this actually show interesting info
	}
	convert_all_links(bc);
}



/* show_header_page()
 * Downloads and sets up the sliding image header.
 * Input: the page to be at. -1 is the regular, big header.
 * Input: callback function to run after done. (Made for display_header_page)
 */
function build_header_page(which_page){
	var conta = document.getElementById("slider_p_"+which_page);
	if (conta == null){
		conta = document.getElementById('top_slider');
		var new_slider = make_element("div", "slider_p_"+which_page, "slider_p",{}, conta);
		for (var i in albums_ajax_cache){
			if (albums_ajax_cache[i]['page'] != which_page) { continue; }
			var new_a = make_element("a", "", "",{'title':albums_ajax_cache[i].data.name,'href':albums_ajax_cache[i].data.url}, new_slider);
			make_element("img", "", "",{'src':albums_ajax_cache[i].data.bthumb}, new_a);
			make_element("span", "", "hover_info",{'html':albums_ajax_cache[i].data.title}, new_a);
			if (!_trans){
				new_a.onmouseover = function() { $(this.getElementsByTagName('div')[0]).animate({ opacity: "1"}, 300); }
				new_a.onmouseout  = function() { $(this.getElementsByTagName('div')[0]).animate({ opacity: "0"}, 300); }
			}
		}
		convert_all_links(conta);
	}
}



/* display_header_page()
 * Updates the sliding image header.
 * Input: the page to be at. -1 is the regular, big header.
 */
function display_header_page(page){
	page = parseInt(page);
	if ( !is('Number', page)) { return;}
	if (page == (-1)) {
		$("#top").removeClass("album_nav");
		$("#top_slider").animate({ height: "225px", left: "0px"}, 200, function(){});
	}
	else {
		$("#top").addClass("album_nav");
		$("#top_slider").animate({ height: "112px", left: "-"+900*page+"px"}, 200, function(){
			//$("#top img").animate({ width: "0px",opacity: 0}, 200, function(){});
		});
	}
}

/* build_pagenav()
 * makes a nice looking pagelist navigation style.
 * Input: the page we're on now.
 * Input: the total number of pages out there
 * Input: the dom element to append to the bottom of. 
 */
function build_pagenav(current_page,total_pages,append_to){
	var pagelist = make_element("ul", "","pagelist button_style",{},append_to);
	if (!is('Number', current_page)) { current_page = parseInt(current_page); }
	var li_prev = make_element("li", "",(current_page > 1)?"prev":"prev disabled",{},pagelist);
	if (current_page > 1) { make_element("a", "", "", {'href':"/page/browse/"+(current_page-1.0)+'/','html':"Prev"} , li_prev); } 
	else { li_prev.innerHTML = 'Prev'; }
	for (var page = 1; page < total_pages; page++) {
		var li_page = make_element("li", "",(page==current_page)?"current":"",{},pagelist);
		make_element("a", "", "", {'href':"/page/browse/"+page+'/','html':page} , li_page);
	}
	var li_next = make_element("li", "",((current_page+1)<total_pages)?"next":"next disabled",{},pagelist);
	if ((current_page+1)<total_pages) { make_element("a", "", "", {'href':"/page/browse/"+(current_page+1.0)+'/','html':"Next"} , li_next); } 
	else { li_next.innerHTML = 'Next'; }
}


function show_graphs(album) {
	var exif_charts = document.getElementById('exif_charts');
	
	if (typeof(Highcharts) !== 'object') {
		var oHead = document.getElementsByTagName('HEAD').item(0);
		var oScript= document.createElement("script");
		oScript.type = "text/javascript";
		oScript.src="/themes/timpage/js/highcharts.js";
		oHead.appendChild( oScript);
		if ( !is('DOMWindow',document.getElementById('charts_spinner'))) //make a loading spinner
			{ make_element("img", "charts_spinner", "", {'src':'/themes/timpage/i/ajax-loader.gif'} , exif_charts); }
		setTimeout ( "show_graphs("+album+")", 400 );
		return;
	}
	if ( $('#chart_area').length ) { $('#chart_area').slideUp(400,function(){ exif_charts.removeChild(document.getElementById('chart_area')); }); return; }
	else { var chart_area = make_element("div", "chart_area", "", {'style':"display:none;"} , exif_charts); }
	
	var this_page = decode_page_url_type( get_current_page() );
	

	function chart_return(res){
		var alb_meta = jsonParse(res);
		var num_photos = alb_meta.length;
		if ( $('#charts_spinner').length ) { exif_charts.removeChild(document.getElementById('charts_spinner')); }
		
		//make an object of value=>(freq of occurrence) .. ex: 'f/2.8' => 8 times, 'f/8'=>2 times
		var stat_object = {'EXIFISOSpeedRatings':{},'EXIFExposureTime':{},'EXIFFNumber':{},'EXIFModel':{}}; //also could add 'EXIFFlash':{}
		for (var im=0; im<alb_meta.length; im++) {  //loop through each line, each photo's metadata
			for (var ex in stat_object){  //loop through each type I want to make a (value=>freq of occurrence) record of
				var exif_value = alb_meta[im][ex]['value']; //get the value (example, f/2.8)
				stat_object[ex][exif_value] = (is('Number',stat_object[ex][exif_value]))? (stat_object[ex][exif_value]+1):(1);
			}			
		}
		for (var ekind in stat_object){
			var exif_array = [];
			for (var jo in stat_object[ekind]) { exif_array.push([jo, stat_object[ekind][jo]]); }
			exif_array.sort(function(a,b){return b[1] - a[1]});
			make_element("div", ekind+"_chart", "charts",{'style':'width:280px;height:250px;float:left;'},chart_area);
			var display_name = alb_meta[0][ekind].display;
			new Highcharts.Chart({
				chart: { renderTo: ekind+"_chart" },
				title: { text: display_name }, credits:{enabled: (ekind==="EXIFISOSpeedRatings")?true:false},
				plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: false } }},
				tooltip: { formatter: function() { return '<b>'+ this.point.name +'</b>: '+ Math.round(this.y/num_photos*1000)/10 +'% ('+this.y+' photos)'; } },
				series: [{ type: 'pie', data: exif_array }]
			});
		}
		
		var album_obj = find_album_in_chache( this_page[1] );
		var shutter_array = [];
		var f_array = [];
		var iso_array = [];
		for (var i=0; i<alb_meta.length; i++) {  //loop through each line, each photo's metadata
			var this_date = new Date(alb_meta[i]['EXIFDateTimeOriginal'].value.replace(/(\d{4}):(\d{2}):(\d{2})[ tT](.*)/gi,"$2/$3/$1 $4"));
			var this_shutter = parseInt(alb_meta[i]['EXIFExposureTime'].value.replace(/1\/([0-9]+) sec/gi,"$1"));
			var this_f = parseFloat(alb_meta[i]['EXIFFNumber'].value.replace(/f\/([0-9.]+)/gi,"$1"));
			var this_iso = parseInt(alb_meta[i]['EXIFISOSpeedRatings'].value);
			shutter_array.push( {'x':this_date.getTime(), 'y':this_shutter, 'file':album_obj.images[i].thumb, 'link':album_obj.images[i].link, 'name':album_obj.images[i].ti });
			f_array.push( {'x':this_date.getTime(), 'y':this_f, 'file':album_obj.images[i].thumb, 'link':album_obj.images[i].link, 'name':album_obj.images[i].ti });
			iso_array.push( {'x':this_date.getTime(), 'y':this_iso, 'file':album_obj.images[i].thumb, 'link':album_obj.images[i].link, 'name':album_obj.images[i].ti });
		}
		chart_area.insertBefore(make_element("div", "date_chart", "charts",{'style':'width:590px;height:300px;'}),chart_area.childNodes[0]);
		new Highcharts.Chart({
			chart: {
				renderTo: 'date_chart',
				type: 'spline'  //line, spline, area, areaspline, column, bar, pie and scatter
			},
			plotOptions: {
				series: { point: { events: {click: 
					function() {
						/*----this function runs when a point is clicked----*/
						console.log('at '+this.pageX+' '+this.pageY+' -> '+this.link); 
						//load_page(this.link); 
						
						var click_prvw = document.getElementById('click_prvw');
						if (click_prvw == null) { 
							click_prvw = make_element("div", "click_prvw", "", {'style':'position:fixed; top:'+(this.pageY-100)+'px; left:'+(this.pageX-100)+'px;'} , document.getElementById('stories'));							
							var clk_a = make_element("a", "", "", {'href':this.link} , click_prvw);
							var clk_img = make_element("img", "", "", {'src':this.file} , clk_a);
							
							make_element("span", "", "", {'html':'Image: '+this.name+', click image to view.'} , click_prvw);
						}
						else { 
							click_prvw.children[0].src = this.file;
							click_prvw.setAttribute('style', 'position:fixed; top:'+ (this.pageY-100) +'px; left:'+ (this.pageX-100) +'px;');
						}
						convert_all_links('click_prvw');
						
					} //done with the function.
				} } }
			},
			title: { text: 'Shutter Speed, ISO, and F/stop vs Time' }, 
			credits:{enabled: false},
			subtitle: { text: 'All on seperate axis, hover to view details.' },
			xAxis: { type: 'datetime' },
			yAxis: [ 
				{ title: { text: 'ISO / Shutter value'    } },
				{ title: { text: 'F/stop'}, labels: { align: 'right' } }
			],
			tooltip: {
				crosshairs: true,
				formatter: function() {
					
					var hover_prvw = document.getElementById('hover_prvw');
					if (hover_prvw == null) { make_element("img", "hover_prvw", "", {'src':this.point.file} , document.getElementById('nav')); }
					else { hover_prvw.src = this.point.file }
					
					return this.point.name+'<br/><b>'+ this.series.name +'</b>' +
						((this.series.name==="Shutter Speed")? ("1/"+this.y+" sec") : ((this.series.name==="F/stop")? ("f/"+this.y) : (this.y))) +
						'<br/>'+Highcharts.dateFormat('%a %b %e %y, %I:%M %P', this.x) +
						'<br/> -> click to view';
				}
			},
			series: [
				{ name:"Shutter Speed", data: shutter_array, yAxis: 0 }, 
				{ name:"ISO", data: iso_array, yAxis: 0 },
				{ name:"F/stop", data: f_array, yAxis: 1 }, 
			]
		});
		
		make_element("a", "charts_close", "",{'html':'Close graphs'},chart_area);
		$('#chart_area').slideDown();
	}
	
	if ((window['localStorage']) && (store = localStorage.getItem( 'exif_data_'+this_page[1] ))) { chart_return( store ); }
	else {
		$.get('/index.php',{"p":"ajax","type":"alb_exif","alb":this_page[1]}, 
			function(ret){ 
				if (window['localStorage']) {localStorage.setItem( 'exif_data_'+this_page[1] , ret );}
				chart_return(ret);
			} ,"html");
	}
	
	/*chart = new Highcharts.Chart({
		chart: {
			renderTo: 'chart',
			plotBackgroundColor: null,
			plotBorderWidth: null,
			plotShadow: false
		},
		title: {
			text: 'Browser market shares at a specific website, 2010'
		},
		tooltip: {
			formatter: function() {
				return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
			}
		},
		plotOptions: {
			pie: {
				allowPointSelect: true,
				cursor: 'pointer',
				dataLabels: {
					enabled: true,
					//color: Highcharts.theme.textColor || '#000000',
					//connectorColor: Highcharts.theme.textColor || '#000000',
					formatter: function() {
						return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
					}
				}
			}
		},
		series: [{
			type: 'pie',
			name: 'Browser share',
			data: [
				['Firefox',   45.0],
				['Safari',    8.5],
				['Opera',     6.2],
				['Others',   0.7]
			]
		}]
	});*/
}


/* changePage()
 * Updates the page content area, sidebar navigation, and header
 * Input: page_type, the type of page as decoded
 * Input: url of this page (without host)
 * Input: data to place in content area
 */
function changePage(page_type, incoming_data, this_hash){
	/* --------------------------------- */
	/* ---- Update the content area ---- */
	$('#stories').html(incoming_data);
	convert_all_links(document.getElementById('stories'));
	var hash_split = page_type.split("/");
		
	/* --------------------------- */
	/* ---- Change the Header ---- */
	display_header_page(-1);
	
	
	/* ---------------------------- */
	/* ---- Modify the sidebar ---- */
	var sidebar_links = document.getElementById("nav").getElementsByTagName('a');
	var new_active_link = 0;
	if ((page_type == 'home')||(page_type == '')) { new_active_link = sidebar_links[0]; }
	else { 
		for (i = 0; i < (sidebar_links.length); i++) {
			var compare = sidebar_links[i].href.split("/").splice(3,6).join("/"); //remove hostname.
			if (compare == this_hash){ 
				new_active_link = sidebar_links[i];
				break;
			}
		}
	}
	if (_last_active_sidebar_link) { $(_last_active_sidebar_link).removeClass('current'); }
	$(new_active_link).addClass('current');
	_last_active_sidebar_link = new_active_link;
	
	/* ------------------------------------ */
	/* ---- Modify the topbar (header) ---- */
	$('ul.tabs li').removeClass('current');
	if (page_type == "pages/about/") { $('.tab_about').addClass('current'); }
	else if (page_type.match(/page\/browse/i)) { $('.tab_photos').addClass('current'); }
	else if (page_type.split("/")[0] == 'news') { $('.tab_blog').addClass('current'); }
	else { $('.tab_explore').addClass('current'); }
	
}


/* find_album_in_chache()
 * Finds the album in the albums_ajax_cache object
 * Input: album (string) to look for
 * Input: (optional) cache reference point, defaults to albums_ajax_cache
 */
function find_album_in_chache(album,cache){
	if (typeof(cache)  === "undefined") { cache = albums_ajax_cache; }
	for (var key in cache){
		if (cache[key].data.name == album){
			return cache[key];
		}
		else if (cache[key]['subalbums'].length){
			var res = find_album_in_chache(album, cache[key]['subalbums']);
			//if ((typeof(res) != "object") && (res >= 0)){ res = [res]; }
			if ( is('Object', res)) { return res; } //(res.push(key));
		}
	}
	return -1; //not found
}

/* find_image_in_album()
 * searches for the image with filename in album
 * Input: album to look in. Pass reference object
 * Input: image filename to look for
 */
function find_image_in_album(alb, img){
	if (!is('Object', alb)) { return null; }
	for (var jey in alb.images)
		if (alb.images[jey].file==img) {
			return {img:alb.images[jey], key:jey};
		}
	return -1;
}


//fix for the admin box toggle function
function toggle(id) {
	var e = document.getElementById(id);
	if (e.style.display == 'block') { e.style.display = 'none'; }
	else { e.style.display = 'block'; }
}



$(document).ready(function() {
	/* ---- detect support for css transitions ---- */
	_trans = support_transition();
	_supports_history = !!(window.history && history.pushState);
	
	/* ---- index's dynamic loading ability ---- */
	if ($('#main').length){
		
		/* ---- load localstorage data into js cache ---- */
		if ((window['localStorage']) && (date = localStorage.getItem('index_time'))) {
			var delta_sec = ((new Date()).getTime() - (new Date()).setTime(date)) / 1000;
			if (delta_sec < 60*60*2){  //if the cache is new enough.
				if (store = localStorage.getItem('index')) { page_ajax_cache = jsonParse( store ); }
				if (store_dyn = localStorage.getItem('index_dyn')) { albums_ajax_cache = jsonParse( store_dyn ); }
			}
		}
	
		if (_supports_history) {
			window.addEventListener("popstate", function(e) {
				hash_changed_function(location.pathname);
			});
			hash_changed_function(location.pathname);
			if (window.location.hash.length > 1) {
				hash_changed_function("/" + window.location.hash.substr(1));
				history.replaceState(null, null, "/" + window.location.hash.substr(1));
				//window.location.hash = '';
			}
		} else {
			//change the loaded ajax page based on the hash
			if (location.pathname !== "/") { window.location = "http://" + window.location.host + "#" + window.location.pathname.substr(1); }
			$.history.init(hash_changed_function,{ unescape: ",/" });
		}

			
		convert_all_links();
		
		if ($('#close_me').length){
			document.getElementById('close_me').onclick = close_image_display;
			document.getElementById("prev").onclick = function(){change_page_by_offset(-1);return false;}
			document.getElementById("next").onclick = function(){change_page_by_offset( 1);return false;}
		}
		
		//create a link to clear the localStorage cache
		if (window['localStorage']) { (clear_a=document.createElement('a')).id='clear_localStorage';clear_a.href='/';clear_a.onclick=function(){localStorage.clear();};clear_a.innerHTML='clear local cache';document.getElementById('footer').appendChild(clear_a);}
	}
	
	$(document).keydown(function(e){
		if (e.keyCode == 37) { //left arrow
			change_page_by_offset(-1);
		}
		else if (e.keyCode == 39) { //right arrow
			change_page_by_offset(1);
		}
		else if (e.keyCode == 27) { //esc
			close_image_display();
		}
	});

		
	/*---- Cart toolbox ----*/
	if ($('#cart-toolbox').length) {
		$('#cart_data').hide();
		$('#cart-toolbox').hoverIntent({timeout:800,over:showMenu,out:hideMenu});
		$.get('/index.php', {"p":"ajax","type":"addtocart","r": "ajax"}, function(data){ updateCartToolbox(data)}, "text");
	}
    

});

function showMenu(){ $('#cart_data').slideDown(100); }
function hideMenu(){ $('#cart_data').slideUp(100); }

function updateCartToolbox(data){
	if (data !== "none"){
		cartData = jsonParse(data);
		$('#jsAdded').html("Latest added image: <div id=\"latestAdded\"></div>");
		$('#latestAdded').append('<a href="'+cartData.latestImage.data.pageURL+'">'+
					 '<img src="'+cartData.latestImage.data.thumbURL+'" />'+
					 '('+cartData.latestSize+')</a>'); //cartData.latestImage.data.title
	}
}

function convert_all_links(parent_element){
	if (typeof(parent_element)  === 'undefined') { var rent_ele = document; }
	else if (is('String', parent_element)) { var rent_ele = document.getElementById(parent_element); }
	else if (typeof(parent_element) === 'object') { var rent_ele = parent_element; }
	else { return; }
	var lot_of_links = rent_ele.getElementsByTagName('a');
	var compare_host = location.host;
	for (i = 0; i < (lot_of_links.length); i++){   // hash_table.length = total images in the album.
		if ( ! is('Function', lot_of_links[i].onclick)) {
			if ((lot_of_links[i].href.split("/")[2]==compare_host) || (lot_of_links[i].href.charAt(0) === "/")) {  //2nd condition is fix for IE 6 and 7
				lot_of_links[i].onclick = clicked_link;
			} 
		}
	}
}


/* make_element()
 * builds a html element with lots of options
 * Input: type of element (ie: 'div', 'a', etc)
 * Input: id (optional)
 * Input: class (optional)
 * Input: other optional options. ex: {'src':hi, 'title':"hi"}
 * Input: element to appendChild to (optional)
 */
function make_element(what_kind, what_id, what_class, what_else, append_to) {
	new_elm = document.createElement(what_kind);
	if (what_id) { new_elm.id = what_id; }
	if (what_class) { new_elm.className = what_class; }
	if (typeof(what_else) !== 'undefined'){
		if (what_else['src']) { new_elm.src = what_else['src']; }
		if (what_else['href']) { new_elm.href = what_else['href']; }
		if (what_else['title']) { new_elm.title = what_else['title']; }
		if (what_else['alt']) { new_elm.alt = what_else['alt']; }
		if (what_else['html']) { new_elm.innerHTML = what_else['html']; }
		if (what_else['style']) { new_elm.setAttribute('style', what_else['style']); }
	}
	//console.log("make_element " + Object.prototype.toString.call(append_to) );
	if ( typeof(append_to) === 'object') { append_to.appendChild(new_elm); }
	return new_elm;
}


// from http://bonsaiden.github.com/JavaScript-Garden/#types.typeof
function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

//IE doesn't have the indexOf function.. redefinition here
if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(needle) {
        for(var i = 0; i < this.length; i++) {
            if(this[i] === needle) {
                return i;
            }
        }
        return -1;
    };
}


/*jQuery history plugin, The MIT License, 2010-09-11 */
(function($){var e={put:function(a,b){(b||window).location.hash=this.encoder(a)},get:function(a){var b=((a||window).location.hash).replace(/^#/,'');try{return $.browser.mozilla?b:decodeURIComponent(b)}catch(error){return b}},encoder:encodeURIComponent};var f={id:"__jQuery_history",init:function(){var a='<iframe id="'+this.id+'" style="display:none" src="javascript:false;" />';$("body").prepend(a);return this},_document:function(){return $("#"+this.id)[0].contentWindow.document},put:function(a){var b=this._document();b.open();b.close();e.put(a,b)},get:function(){return e.get(this._document())}};function initObjects(d){d=$.extend({unescape:false},d||{});e.encoder=encoder(d.unescape);function encoder(b){if(b===true){return function(a){return a}}if(typeof b=="string"&&(b=partialDecoder(b.split("")))||typeof b=="function"){return function(a){return b(encodeURIComponent(a))}}return encodeURIComponent}function partialDecoder(b){var c=new RegExp($.map(b,encodeURIComponent).join("|"),"ig");return function(a){return a.replace(c,decodeURIComponent)}}}var g={};g.base={callback:undefined,type:undefined,check:function(){},load:function(a){},init:function(a,b){initObjects(b);h.callback=a;h._options=b;h._init()},_init:function(){},_options:{}};g.timer={_appState:undefined,_init:function(){var a=e.get();h._appState=a;h.callback(a);setInterval(h.check,100)},check:function(){var a=e.get();if(a!=h._appState){h._appState=a;h.callback(a)}},load:function(a){if(a!=h._appState){e.put(a);h._appState=a;h.callback(a)}}};g.iframeTimer={_appState:undefined,_init:function(){var a=e.get();h._appState=a;f.init().put(a);h.callback(a);setInterval(h.check,100)},check:function(){var a=f.get(),location_hash=e.get();if(location_hash!=a){if(location_hash==h._appState){h._appState=a;e.put(a);h.callback(a)}else{h._appState=location_hash;f.put(location_hash);h.callback(location_hash)}}},load:function(a){if(a!=h._appState){e.put(a);f.put(a);h._appState=a;h.callback(a)}}};g.hashchangeEvent={_init:function(){h.callback(e.get());$(window).bind('hashchange',h.check)},check:function(){h.callback(e.get())},load:function(a){e.put(a)}};var h=$.extend({},g.base);if($.browser.msie&&($.browser.version<8||document.documentMode<8)){h.type='iframeTimer'}else if("onhashchange"in window){h.type='hashchangeEvent'}else{h.type='timer'}$.extend(h,g[h.type]);$.history=h})(jQuery);

/* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+ * <http://cherne.net/brian/resources/jquery.hoverIntent.html> */
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

//jQuery Color Animations plugin
(function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(fx.state==0){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end)}fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")"}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];return colors[jQuery.trim(color).toLowerCase()]}function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body"))break;attr="backgroundColor"}while(elem=elem.parentNode);return getRGB(color)};var colors={white:[255,255,255]}})(jQuery);

// Parses a string of well-formed JSON text. http://code.google.com/p/json-sans-eval/
// json_sans_eval.js  --  Fast, secure but Not validating
var jsonParse=(function(){var number='(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';var oneChar='(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'+'|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';var string='(?:\"'+oneChar+'*\")';var jsonToken=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]'+'|'+number+'|'+string+')','g');var escapeSequence=new RegExp('\\\\(?:([^u])|u(.{4}))','g');var escapes={'"':'"','/':'/','\\':'\\','b':'\b','f':'\f','n':'\n','r':'\r','t':'\t'};function unescapeOne(_,ch,hex){return ch?escapes[ch]:String.fromCharCode(parseInt(hex,16))}var EMPTY_STRING=new String('');var SLASH='\\';var firstTokenCtors={'{':Object,'[':Array};var hop=Object.hasOwnProperty;return function(json,opt_reviver){var toks=json.match(jsonToken);var result;var tok=toks[0];var topLevelPrimitive=false;if('{'===tok){result={}}else if('['===tok){result=[]}else{result=[];topLevelPrimitive=true}var key;var stack=[result];for(var i=1-topLevelPrimitive,n=toks.length;i<n;++i){tok=toks[i];var cont;switch(tok.charCodeAt(0)){default:cont=stack[0];cont[key||cont.length]=+(tok);key=void 0;break;case 0x22:tok=tok.substring(1,tok.length-1);if(tok.indexOf(SLASH)!==-1){tok=tok.replace(escapeSequence,unescapeOne)}cont=stack[0];if(!key){if(cont instanceof Array){key=cont.length}else{key=tok||EMPTY_STRING;break}}cont[key]=tok;key=void 0;break;case 0x5b:cont=stack[0];stack.unshift(cont[key||cont.length]=[]);key=void 0;break;case 0x5d:stack.shift();break;case 0x66:cont=stack[0];cont[key||cont.length]=false;key=void 0;break;case 0x6e:cont=stack[0];cont[key||cont.length]=null;key=void 0;break;case 0x74:cont=stack[0];cont[key||cont.length]=true;key=void 0;break;case 0x7b:cont=stack[0];stack.unshift(cont[key||cont.length]={});key=void 0;break;case 0x7d:stack.shift();break}}if(topLevelPrimitive){if(stack.length!==1){throw new Error();}result=result[0]}else{if(stack.length){throw new Error();}}if(opt_reviver){var walk=function(holder,key){var value=holder[key];if(value&&typeof value==='object'){var toDelete=null;for(var k in value){if(hop.call(value,k)&&value!==holder){var v=walk(value,k);if(v!==void 0){value[k]=v}else{if(!toDelete){toDelete=[]}toDelete.push(k)}}}if(toDelete){for(var i=toDelete.length;--i>=0;){delete value[toDelete[i]]}}}return opt_reviver.call(holder,key,value)};result=walk({'':result},'')}return result}})();

function support_transition(){ 
    var thisBody = document.body || document.documentElement,
    thisStyle = thisBody.style,
    support = thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.OTransition !== undefined || thisStyle.transition !== undefined;
    
    return support; 
}



