


function makehtml_carousel(item, classname, def) {
	var t_url = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_" + def.sizereal + ".jpg";
	var p_url = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_" + "z.jpg"; // b for superbig
	return '<li><a title="' + item.title + '" rel="flickr_' + classname + '" href="' + p_url + '" class="' + classname + '">' + '<img title="' + item.title + ' (click to enlarge)" src="' + t_url + '" style="' + def.style + '" />' + '</a></li>';
	};


function makehtml_gallery(item, classname, def) {
	var t_url = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_" + def.sizereal + ".jpg";
	var p_url = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_" + "z.jpg"; // b for superbig
	return '<a style="float:left" title="' + item.title + '" rel="flickr_' + classname + '" href="' + p_url + '" class="' + classname + '">' + '<img title="' + item.title + '" src="' + t_url + '" style="' + def.style + '" />' + '</a>';
	};



var make_carousel=function(data, tag, def)
{
		var item;
		var $links = $();
		var l=''; 
		var c=0;
		var classname = tag + '_colorbox';
		
		while (item = data.photos.photo.shift()) {
			l += makehtml_carousel(item,classname,def);
			c++;
		}
		
		// we need to add some blank list items so that we can scroll onto last page (the carousel does not handle this for us...)
		// we get the mod and subtract it from the total displayed
		var needed = def.display - (c % def.display);
		
		if(needed != def.display)
		{
		while(needed > 0)
			{
				l +='<li></li>';
				needed--;
			}
		}
		
			
		var tagid = "#tag_" + tag;

		// a lot of this markup is there to override stuff that drupal forces on us.	
		var r = '<div style=""><table style="margin:0px;padding:0px; border-spacing:0;"><tr>';
		r += '<td class="carousel_prev carousel_hover" style="cursor:pointer;background:#fdf9f0;color:#ccc;vertical-align:center;font-weight:bold;font-size:20px;padding:0px 0px;">&laquo;</td>';
		r += '<td style="padding:0 2px;"><div style="margin:0px 0 -4px 0; padding:0px;" class="jCarouselLite_' + classname + '">';
		r += '<ul class="atagpadding">' + l + '</ul>';
		r += '</div><div class="clear"></div></td>';
		r += '<td class="carousel_next carousel_hover" style="cursor:pointer;background:#fdf9f0; color:#ccc;vertical-align:center; font-weight:bold;font-size:20px; padding:0px 0px;" >&raquo;</td>';	
		r += '</tr></table></div>';


		$(tagid).append(r);
		
		$('.atagpadding a').css({margin:'0px 2px 0px 2px'});
		$('.atagpadding li').css({margin:'0',padding:'0'});
		
		$('.carousel_hover').hover(
		function(){
		$(this).css({background:'#FCAF00',color:'#fff'});
		},
		function(){
		$(this).css({background:'#fdf9f0',color:'#ccc'});
		});


		$(tagid + ' .jCarouselLite_' + classname).jCarouselLite({
			btnNext: tagid + " .carousel_next",
			btnPrev: tagid + " .carousel_prev",
			scroll: def.display,		// number to scroll by this is a pain - it wont show the last 1 or 2 if the pics dont fit into 3
			visible: def.display,
			starts: 0,
			circular: false // true was causing problems
			});

	$('.'+classname).colorbox({
			rel: 'flickr_' + classname,
			speed: 0
		});

};

// translates small, thumbnail, etc into something flickr can handle.
var sizetranslation = {
	'small':'t',			// yes - this is the wrong way around (with thumbnail) - but it is more logical
	'thumbnail':'s',
	'medium':'m',	
	'large':'z',
	'giant':'b'	
	}

// this is not done yet - it defines default heigts based in the size of the image specified. It can be over-ridden.	
var heightwidthtranslation = {
	'small':'height:75',			// yes - this iswidth the wrong way around (with thumbnail) - but it is more logical
	'thumbnail':'height:75;width:75px;',
	'medium':'m',	
	'large':'z',
	'giant':'b'	
	}	

var make_gallery=function(data, tag, def)
{
		var item;
		var $links = $();
		var l=''; 
		var c=0;
		var classname = tag + '_colorbox';

		var heightwidth='';

		while (item = data.photos.photo.shift()) {
			l += makehtml_gallery(item,classname,def);
		}
		
		
		var tagid = "#tag_" + tag;

		var r = '<div class="atagpadding">';
			r += l;
			r += '</div>';
			r += '<div class="clear"></div>';

			$(tagid).append(r);

	$('.'+classname).colorbox({
			rel: 'flickr_' + classname,
			speed: 0
		});

};


function makeCarouselsAndGalleries() {

	var tag,url,def;
	
	$('.flickr_carousel').each(
	function(index) {

	// set sane defaults
		def={};
		def.style ='height:127px;width:167px'; 	// height and width seem to be required by the carousel - these allow 3 across the page
		def.size = '';  			// we will set this dynamically		
		def.sizereal='m'; 			// this translates to medium
		def.maximum = 100;			// maximum number possible to get from flickr
		def.display = 3;	  		// number to display on screen			
	
	if(typeof($.metadata.get(this))=='object')
		{
			$.extend(def,$.metadata.get(this));
		};
	
	// translate the named size to the appropriate letter.
	if (typeof(sizetranslation[def.size])=='string')
		{

			def.sizereal=sizetranslation[def.size];
		}
		
		
		tag = this.id.substring(4);
		url = 'http://api.flickr.com/services/rest/?format=json&per_page='+def.maximum+'&tag_mode=all&tags=' + tag + '&method=flickr.photos.search&user_id=70077825@N05&api_key=c53ac56ff2f73ad0ada952d57829f393&jsoncallback=?';

		getFromFlickr(url, tag, make_carousel, def);
	
	});
	
	
	$('.flickr_gallery').each(
	function(index) {


	// set sane defaults
		def={};
		def.style = '';
		def.size = '';  			// we will set this dynamically
		def.sizereal = 's';		// our version of thumbnail
		def.display = 20;			// max number to display - same as number got from flickr	
	
	if(typeof($.metadata.get(this))=='object')
		{
			$.extend(def,$.metadata.get(this));
		}
	
	// translate the named size to the appropriate letter.
	if (typeof(sizetranslation[def.size])=='string')
		{
			def.sizereal=sizetranslation[def.size];
		};
	
	tag = this.id.substring(4);
			
	url = 'http://api.flickr.com/services/rest/?format=json&per_page='+def.display+'&tag_mode=all&tags=' + tag + '&method=flickr.photos.search&user_id=70077825@N05&api_key=c53ac56ff2f73ad0ada952d57829f393&jsoncallback=?';
	
	getFromFlickr(url, tag, make_gallery, def);

	})	
	
}; // end make carousels

function getFromFlickr(url, tag, callback, def) {

	$.getJSON(url, function(data) {

		callback(data, tag, def);
		
	});
	
} // end function makeCarousels






/* =========================================== start of makeDonationsReportClass ========================================== */
var makeDonationsReportClass = function() {


this.handle=function()
{

// get the current donations state - we need this once only
	var dpack=getDonations();
	var our_carousel_elements=''; // we will overwrite this later
	var our_ordinary_element='';  // we will overwrite this later	
	
// make any donation carousels.

$('.donations_carousel').each(
		function(index) {
			our_carousel_elements=''; // reset...
			
			// we can force set the inner and outer width in the enclosing div
			var def={};
				def.innerwidth='470px';
				def.outerwidth='540px';
			
			// copy the metadata over.		
			if(typeof($.metadata.get(this))=='object')
				{
					$.extend(def,$.metadata.get(this));
				};
			
				 var innerwidth='width:'+def.innerwidth +';'
				 var outerwidth='width:'+def.outerwidth +';'
				// var innerwidth='';
				// var outerwidth='';
			
			
				$('.donations_carousel .donationsSasayamaCarousel').each(
					function(index) {
						type='carousel';
						our_carousel_elements += makeDonationElement(type,getDonations(),this,innerwidth);	
					});
	
					if(our_carousel_elements !='')
					{
						// append to dom
						makeDonationsCarousel(our_carousel_elements,def,outerwidth,this);	
					};
					
}); // end outer each	
	
	
// make any ordinary donation boxes - non-carousel.
	$('.donationsSasayamaOrdinary').each(
		function(index) {
			type='ordinary';


			var def={};
				def.owidth='470px';
			
			// copy the metadata over - do this now as we want to keep 	makeDonationElement generic.
			if(typeof($.metadata.get(this))=='object')
				{
					$.extend(def,$.metadata.get(this));
				};		
		
			var owidth='width:'+def.owidth +';'
					
		var our_ordinary_element=makeDonationElement(type,dpack,this,owidth);
		// append straight to the dom
		$(this).append(our_ordinary_element);
		
		});


// appended everything to the dom, so add a currency changer	
// var f = new CurrencyChangerClass();	
//		 f.init();	
	
} // end method this.handle

	
//  make a single element	
var makeDonationElement=function(type,dpack,othis,innerwidth)
{
	
	var markup_element=''; //will hold each elements as we make it.
	var all_elements=''; // will hold all the elements
	
	// set sane defaults
		def={};
		def.language ='english'; // 'english' or 'japanese'
		def.layout ='standard'; // 'english' or 'japanese' 
		
			
	// copy the metadata over.		
	if(typeof($.metadata.get(othis))=='object')
		{
			$.extend(def,$.metadata.get(othis));
		};
		
	// were we passed an identifier and does it identify something in our donations pack?
	if(def.identifier && typeof(dpack[def.identifier])=='object')
	{
		// yes - so create basic markup 
		markup_element=createMarkup(dpack[def.identifier], def,innerwidth);
		
		// is it for a carousel? Encase in list tags
		if(type=='carousel'){markup_element = '<li>'+markup_element+'</li>';}
		
		// add it to our running sxcore
		all_elements+=markup_element;
		
	}else{ /* nothing - fail silently */ alert('failed'); }
	
	// pass the markup back to be appended to the dom
	return 	all_elements;
	
} // end method

// fdf9f0
var makeDonationsCarousel=function(all_elements,metadata,outerwidth,othis)
{
	var identifier=othis.id;
	
	// a lot of this markup is there to override stuff that drupal forces on us.	
	var r = '<div style="padding:0px;"><table style="margin:0px;padding:0px;border-spacing:0;border:1px solid #FCAF00;'+outerwidth+'"><tr>';
	r += '<td class="carousel_prev carousel_hover" style="cursor:pointer;background:#fdf9f0;color:#ccc;vertical-align:center;font-weight:bold;font-size:20px;padding:0px 0px;">&laquo;</td>';
	r += '<td style="padding:10px 2px;background-color:#fefefe"><div style="margin:0 auto;padding:0;" class="jCarouselLite_' + identifier + '">';
	r += '<ul class="doncarpadding">' + all_elements + '</ul>';
	r += '</div><div class="clear"></div></td>';
	r += '<td class="carousel_next carousel_hover" style="cursor:pointer;background:#fdf9f0; color:#ccc;vertical-align:center; font-weight:bold;font-size:20px; padding:0px 0px;" >&raquo;</td>';	
	r += '</tr></table></div>';
	
	var tagid='#' + identifier;
	
	 $(othis).empty().append(r); // append to dom

		$('.doncarpadding a').css({margin:'0px 2px 0px 2px'});
		$('.doncarpadding li').css({margin:'0',padding:'0'});

	// 0px 0 -8px 0
		
	// set some sane defaults
	var cardef={
		scroll:1,
		visible:1,
		starts:0,
		auto:null,
		speed:null,
		circular:false,
		btnNext: tagid + " .carousel_next",
		btnPrev: tagid + " .carousel_prev"
	};
	
	// copy the metadata over.
	// we will actually potentially copy over outerwidth and innerwidth, but they have no meaning in the jcarouslelite and can be passed in
	// safely enough...
			
	if(typeof(metadata)=='object')
		{
			$.extend(cardef,metadata);
		};
	
	// run the carousel code on it
	$(tagid + ' .jCarouselLite_' + identifier).jCarouselLite(cardef);
		
}; // end method	
	
	



var createMarkup=function(dp,def,innerwidth)
{
	dp.target_bar_width=400; // width of bar in pixels
	dp.raised_bar_width=1 // width of "amount raised" bar - default to 1 and change below
		
	if(dp.sponsors && dp.sponsors !=0)
	{
		dp.raised_bar_width =  parseInt( ( dp.sponsors / dp.totalblocks) * dp.target_bar_width, 10);
		dp.raised_percent	= parseInt( ( dp.sponsors / dp.totalblocks) * 100, 10);
		
		if( typeof(dp.raised)=='string' && dp.raised == 'autogenerate')
		{
			dp.raised = dp.blockcost * dp.sponsors;
		}
		
		if( typeof(dp['target'])=='string' && dp['target']== 'autogenerate')
		{
			dp['target']= dp.blockcost * dp.totalblocks;
		}		
	};
	
	// get number of remaining blocks
	dp.remainingblocks = dp.totalblocks - dp.sponsors;
	
	
	var link='';
	var h='';
	
	if(def.lang && def.lang=='jp')
	{
	
	// do we want to post a link?
		if(def['link'] && def['link']=='yes' && dp.jp['link'])
		{
			link='[<a href="'+dp.jp['link']+'">詳細はこちら</a>]';
		}
	
	h+='<div style="margin:auto;'+innerwidth+'">';

		if(def['layout']=='standard')
		 {	
			h+='<div><span style="font:bold 15px/15px arial">'+dp.jp['title']+'</span> '+link+' <br>'+ dp.jp['text'] +'のスポンサーになる<span class="currency" style="color:#0669BD;font-weight:bold;font-size:14px">'+ numberFormatSuffix(dp.blockcost,'円') +'</span>から　または、寄付する</div>';
		 };
			h+='<div class="topmargin_15px" style="margin-bottom:10px;"><b>'+dp.totalblocks+'</b>ユニットのうち残<b>'+dp.remainingblocks+'</b>ユニット <span style="font-size:11.5px">[ 目標<span class="currency">'+ numberFormatSuffix(dp['target'],'円') +'</span> 12年2月15日現在 <span class="currency">'+ numberFormatSuffix(dp.raised,'円') +'</span> ]</span></div>';

		h+='<div style="float:left;">';
		h+='<div style="width:'+dp.target_bar_width+'px;background:#999;height:18px;">';
		h+='<div style="width:'+dp.raised_bar_width+'px;background:#FCAF00;height:18px"></div>';
		h+='</div>';
		h+='</div>';
		h+='<div style="float:left;padding:0px 0 0 8px"> <b>'+dp.raised_percent+'%</b>';
		h+='</div>';
		h+='<div class="clear" style="clear:both"></div>';	
		h+='</div>';
	}
	else
	{
	
	// assume English
	
	// do we want to post a link?
		if(def['link'] && def['link']=='yes' && dp.en['link'])
		{
			link='[<a href="'+dp.en['link']+'">more info</a>]';
		}
	

	h+='<div style="margin:auto;'+innerwidth+'">';

		if(def['layout']=='standard')
		 {	
			h+='<div><span style="font:bold 15px/15px arial">'+dp.en['title']+'</span> appeal.  '+link+' <br>Help sponsor '+ dp.en['text'] +' for from <span class="currency" style="color:#0669BD;font-weight:bold;font-size:14px">'+ numberFormat(dp.blockcost,'&yen;') +'</span>, or donate.</div>';
		 };
			h+='<div class="topmargin_15px" style="margin-bottom:10px;"><b>'+dp.remainingblocks+'</b> units remain of <b>'+dp.totalblocks+'</b> <span style="">[ <span class="currency">'+ numberFormat(dp.raised,'&yen;') +'</span> raised of <span class="currency">'+ numberFormat(dp['target'],'&yen;') +'</span> as of 15th Feb \'12 ]</span></div>';

		h+='<div style="float:left;">';
		h+='<div style="width:'+dp.target_bar_width+'px;background:#999;height:18px;">';
		h+='<div style="width:'+dp.raised_bar_width+'px;background:#FCAF00;height:18px"></div>';
		h+='</div>';
		h+='</div>';
		h+='<div style="float:left;padding:0px 0 0 8px"> <b>'+dp.raised_percent+'%</b>';
		h+='</div>';
		h+='<div class="clear" style="clear:both"></div>';	
		h+='</div>';
	};
	
	
	return h;
	
}; // end method


// This function formats numbers by adding commas
var	numberFormat = function (nStr,prefix){
	    var prefix = prefix || '';
	    nStr += '';
	    x = nStr.split('.');
	    x1 = x[0];
	    x2 = x.length > 1 ? '.' + x[1] : '';
	    var rgx = /(\d+)(\d{3})/;
	    while (rgx.test(x1))
	        x1 = x1.replace(rgx, '$1' + ',' + '$2');
	    return prefix + x1 + x2;
	}; // end method

var	numberFormatSuffix = function (nStr,suffix){
	    var suffix = suffix || '';
	    nStr += '';
	    x = nStr.split('.');
	    x1 = x[0];
	    x2 = x.length > 1 ? '.' + x[1] : '';
	    var rgx = /(\d+)(\d{3})/;
	    while (rgx.test(x1))
	        x1 = x1.replace(rgx, '$1' + ',' + '$2');
	    return x1 + x2 + suffix;
	}; // end method




var getDonations=function()
	{
	
	var res=[];
	res['d_block']={
			sponsors:13,
			totalblocks:410,
			blockcost:300000,
			raised:'autogenerate',
			target:'autogenerate',
			en:{
				title:'Dog Kennels Building',
				text:'a Dog Kennel',
				link:'http://arkbark.net/?q=en/node/3908#dogkennels'
			},
			jp:{
				title:'犬舎',
				text:'犬舎',
				link:'http://arkbark.net/?q=ja/node/3962#dogkennels'
			}			
			};
			
	res['c_block']={
			sponsors:11,
			totalblocks:320,
			blockcost:280000,
			raised:'autogenerate',
			target:'autogenerate',
			en:{
				title:'The Cattery',
				text:'a Cat Unit',
				link:'http://arkbark.net/?q=en/node/3908#cattery'
			},
			jp:{
				title:'猫舎',
				text:'猫舎ユニット',
				link:'http://arkbark.net/?q=ja/node/3962#cattery'
			}			
			};

	res['e_block']={
			sponsors:25,
			totalblocks:500,
			blockcost:70000,
			raised:'autogenerate',
			target:'autogenerate',
			en:{
				title:'Education/Training Building',
				text:'the Education Training Building',
				link:'http://arkbark.net/?q=en/node/3908#education'
			},
			jp:{
				title:'トレーニング・教育棟',
				text:'トレーニング・教育棟',
				link:'http://arkbark.net/?q=ja/node/3962#education'
			}
			};
			

	res['w_block']={
			sponsors:25,
			totalblocks:500,
			blockcost:60000,
			raised:'autogenerate',
			target:'autogenerate',
			en:{
				title:'Warehouse',
				text:'the Sasayama Warehouse',
				link:'http://arkbark.net/?q=en/node/3908#warehouse'
			},
			jp:{
				title:'倉庫',
				text:'倉庫',
				link:'http://arkbark.net/?q=ja/node/3962#warehouse'
			}
			};


	res['dl_road']={
			sponsors:28,
			totalblocks:100,
			blockcost:12000,
			raised:'autogenerate',
			target:'autogenerate',
			en:{
				title:'Dog Land road',
				text:'the Dog Land road',
				link:'http://arkbark.net/?q=en/node/3908#dogland'
			},
			jp:{
				title:'ドッグランドアクセス道路',
				text:'ドッグランドアクセス道路',
				link:'http://arkbark.net/?q=ja/node/3962#dogland'
			}			
			};

	res['dl_ground']={
			sponsors:25,
			totalblocks:100,
			blockcost:20000,
			raised:'autogenerate',
			target:'autogenerate',
			en:{
				title:'Dog Land ground-work',
				text:'the Dog Land ground-work',
				link:'http://arkbark.net/?q=en/node/3908#dogland'
			},
			jp:{
				title:'ドッグランド新しい土を入れる造成工事',
				text:'ドッグランド造成工事',
				link:'http://arkbark.net/?q=ja/node/3962#dogland'
			}		
			};

	res['dl_fence']={
			sponsors:127,
			totalblocks:225,
			blockcost:10000,
			raised:'autogenerate',
			target:'autogenerate',
			en:{
				title:'Dog Land fence',
				text:'the Dog Land fence',
				link:'http://arkbark.net/?q=en/node/3908#dogland'
				
			},
			jp:{
				title:'ドッグランドフェンス',
				text:'ドッグランドフェンス',
				link:'http://arkbark.net/?q=ja/node/3962#dogland'
			}
			};
	// last updated....						
	res['updated_en']='10th Jan 2012';
	res['updated_jp']='10th Jan 2012';
		
	return res;	
			
		}; // end method
}; // end class makeDonationsReportClass


/* =========================================== start of CurrencyChangerClass ========================================== */
var CurrencyChangerClass=function()
{

this.init=function()
{
	
	// step 1 - copy the primary (yen) currency value into the rel
	$('.currency').each(
	function(index) {	
		val=$(this).html();
		stripped =  val.replace(/[^0-9]+/g,'');
		$(this).attr({ "rel": stripped});
	});
	
	// step 2 sets up the change currency floater
	var currencies=_getCurrency();
	var h='';
	
	
	
	for (x in currencies)
	{
	 if (currencies.hasOwnProperty(x)) {
		h+='<span title="click to see yen converted (approximately) to '+currencies[x]['name']+'" style="font:bold 10px/11px arial;color:#666;cursor:pointer;" class="change_currency {to:\'' + x + '\'}">' + currencies[x].menu + '</span>'+ ' : ';
		}
	} 
	
	

	$('.currencychanger').empty().append( h.slice(0,-2) +'&nbsp;');
}


$('.change_currency').die().live("click",function(){
	
	var o=$.metadata.get(this)
	
	changeCurrency(o.to);
})



var changeCurrency=function(towhat)
	{
			var stripped='',newcurrency='';
			var currencies=_getCurrency();
			
			$('.currency').each(
			function(index) {
			
				val=$(this).attr('rel');
				newcurrency = convertToNewCurrency(towhat, val, currencies);
				$(this).html(newcurrency);
			});

	}	




var convertToNewCurrency=function(to,val,currencies)
{
	var r='';
	if(typeof(currencies[to])=='object')
	{
	 	r=numberFormat(	parseInt( val * ( 1 / currencies[to].rate), 10 ) , currencies[to].symbol);
	
		if(to!='jpy'){r='<span style="cursor:pointer;" title="Approximate: &yen;'+numberFormat(val,'') +'@&yen;'+currencies[to].rate+'/'+currencies[to].menu+'1. Actual cost in ' + currencies[to].menu + ' depends on prevailing exchange rate.">'+r+'*</span>'};
	
	}
	return r;
}


	// data pack of currencies against yen - last changed Jan 10th 2012
	var _getCurrency=function()
	{
		var currency=[];
			currency['usd']={name:'US Dollars',rate:77,symbol:'~US$',menu:'USD'};
			currency['sterling']={name:'Pound Sterling',rate:118,symbol:'~&pound;',menu:'GBP'};
			currency['aud']={name:'Australian Dollars',rate:79,symbol:'~AU$',menu:'AUD'};
			currency['cad']={name:'Canadian Dollars',rate:75,symbol:'~CA$',menu:'CAD'};
			currency['euro']={name:'Euros',rate:98,symbol:'~&euro;',menu:'Euro'};
			currency['nzd']={name:'New Zealand Dollars',rate:60,symbol:'~NZ$',menu:'NZD'};
			currency['jpy']={name:'back to Japanese Yen',rate:1,symbol:'&yen;',menu:'JPY'};															
	return currency;

	}; //end method


	// This function formats numbers by adding commas
	var	numberFormat = function (nStr,prefix){
		    var prefix = prefix || '';
		    nStr += '';
		    x = nStr.split('.');
		    x1 = x[0];
		    x2 = x.length > 1 ? '.' + x[1] : '';
		    var rgx = /(\d+)(\d{3})/;
		    while (rgx.test(x1))
		        x1 = x1.replace(rgx, '$1' + ',' + '$2');
		    return prefix + x1 + x2;

		}; // end method

	
}



// wait until the dom is ready before firing
$(document).ready(function() {
	var NICKSTUFF={}; // global scope
	
	makeCarouselsAndGalleries();
	NICKSTUFF.d = new makeDonationsReportClass();
	NICKSTUFF.d.handle();
	
	var nickF = new CurrencyChangerClass();	
		nickF.init();
	



});

