// general actions that require ajax stuff

	/* templates */
	
	_fotos_list_html = '<ol class="list #{smallerThumbs} clearfix">';
		_fotos_list_item_html = '<li class="item thumb #{last} #{selected}">#{thumb}</li>';
	_fotos_list_html += '#{items}';
	_fotos_list_html += '</ol>';
	
	var _fotos_list_tpl = new Template(_fotos_list_html);
	var _fotos_list_item_tpl = new Template(_fotos_list_item_html);
	
	_foto_thumb_html = '<a class="image clearfix #{smaller}" href="#{url}">';
	_foto_thumb_html += '<img width="#{width}" height="#{height}" alt="" src="#{src}" title="#{title}"/>';
	_foto_thumb_html += '</a>';
	_foto_thumb_html += '#{options}';
		_foto_thumb_options_html = '<ul class="options #{smaller} clearfix">'
				_foto_thumb_options_html_comments = '<li class="point comments"><a class="_icon comments_icon" href="#{url}#comments">#{comments}</a></li>';
		_foto_thumb_options_html += '#{items}'
		_foto_thumb_options_html += '</ul>';
	
	var _thumb_tpl = new Template(_foto_thumb_html);
	var _thumb_options_tpl = new Template(_foto_thumb_options_html);
	var _thumb_options_comments_tpl = new Template(_foto_thumb_options_html_comments);	
	
	function _apply_go_black(n)
	{
		n.observe('click', function(e)
		{
			// image swapping?
			var black_bg_images = new Array(2);
			black_bg_images[0] = '/views/movement/images/icons/white_to_black_gray.png';
			black_bg_images[1] = '/views/movement/images/icons/black_to_white_gray.png';
			
			//alert(black_bg_images);
			
			if (n.up('body').hasClassName('go_black')){
				n.up('body').removeClassName('go_black');
				n.up('body').removeClassName('go_slide_show');
				n.down('img').src = black_bg_images[0];
			} else {
				n.up('body').addClassName('go_black');
				n.up('body').addClassName('go_slide_show');
				n.down('img').src = black_bg_images[1];
			}
			
			e.stop();
		});
	}
	
	function _show_love(n)
	{
		var _love_making = false;
		
		n.observe('click', function(e)
		{
			e.stop();
			//alert(_love_making);
			
			var _love_icon = n.down('img').src;
			
			if (_love_making == false){
				_love_making = true;
				
				n.down('img').hide();
				n.addClassName('ajax_spin_icon');
				
				new Ajax.Request
				(
					n.href + '.json', 
					{
						method: 'get',
						onSuccess: function (transport){
							if (data = transport.responseText.evalJSON(true)) {
								if (data.photograph.love){
									total = (data.photograph.love.total<10 && data.photograph.love.total>0) ? '0' + data.photograph.love.total : data.photograph.love.total;
									n.up(0).down('.total').update(total);
									if (data.photograph.love.you){
										_love_icon = _love_icon.sub('gray', 'red');
									} else {
										_love_icon = _love_icon.sub('red', 'gray');
									}
								}
							}
							
							_loveMaking = false;
						},
						
						onFailure: function(){
							alert('Sorry, love making failed.');
						},
						
						onComplete: function(){
							n.down('img').src = _love_icon;
							_love_making = false;
							n.removeClassName('ajax_spin_icon');
							n.down('img').show();
						
						}
					}
				);
				
				
			} else {
				alert('Sorry, one lover at a time.');	
			}
		});
	}
	
	function _share_object (n)
	{
		n.observe('click', function(e)
		{
			//alert('sharing');
			n.up('.share').down('.networks').toggle();
			e.stop();
		});
		
	}
	
	function _camera_object (n)
	{
		n.observe('click', function(e)
		{
			//alert(n.down('a')innerHTML);
			if (n.down('a').innerHTML=='+'){
				n.down('a').update('&ndash;');
			} else {
				n.down('a').update('+');
			}
			n.up('.ajax_camera_object').down('.exif').toggle();
			
			e.stop();
		});
	}
	
	// object stuff;
	var _ajax_object = new Array(3);
	
	function _get_ajax_object_type (n)
	{
		_type = false;
		
		if (n.hasClassName('ajax_photograph_object')){
			_type = 'photograph';	
		} else if (n.hasClassName('ajax_article_object')){
			_type = 'post';	
		} else if (n.hasClassName('ajax_note_object')){
			_type = 'note';
		} else if (n.hasClassName('ajax_book_object')){
			_type = 'book';
		} else if (n.hasClassName('ajax_book_photograph_object')){
			_type = 'photograph';
		} 	
		
		return _type;
	}
		
	function _ajax_edit_tags (n)
	{
		_ajax_object['type'] = _get_ajax_object_type(n);
		if (_ajax_object['type'])
		{
			new Ajax.InPlaceEditor (
				$('ajax_tags_editor'), 
				 _ajax_object['url'] + '/edit.json', 
				{ 
					
					callback: function(form, value) { return 'tagged=' + encodeURIComponent(value) },
					externalControlOnly: true,
					externalControl: n,
					rows:4,
					cols:17,
					loadTextURL: _ajax_object['url'] + '.text?get='+_ajax_object['type']+'/tagged',
					
					onComplete: function (transport){	
						if (transport){
							$('ajax_tags_editor').hide();
							if (data = transport.responseText.evalJSON(true)) {
								_html = '';
								if (data[_ajax_object['type']].tags){
									//alert(data[type].tags
									data[_ajax_object['type']].tags.each(function(s, index){
										switch(_ajax_object['type']){
											case 'photograph':
													_html += '<a href="' + data.photograph.space.url + '/tag/' + s.tag + '">' + s.clean + '</a>';
												break;
											case 'note':
													_html += '<a href="/notes/tag/' + s.tag + '">' + s.clean + '</a>';
												break;
											case 'post':
													_html += '<a href="/journal/tag/' + s.tag + '">' + s.clean + '</a>';
												break;
										};
										
										if (index+1<data[_ajax_object['type']].tags.length){
											_html += ', ';
										}
									});
								}
								
								$('ajax_tags_editor').update(_html);
								$('ajax_tags_editor').show()
							}
						}
					},
					onFailure: function(transport){
						alert('Sorry, we failed to process that request');	
					}
				}
			);
		}
	}
	
	function _ajax_edit_title (n)
	{
		_ajax_object['type'] = _get_ajax_object_type(n);
		
		if (_ajax_object['type'])
		{
			 new Ajax.InPlaceEditor 
			 (
				 n, 
				 _ajax_object['url'] + '/edit.json', 
				{ 
					callback: function(form, value) { 
						r = 'title=' + encodeURIComponent(value);
						if (_ajax_object['type']=='post'){
							r = 'article[title]=' + encodeURIComponent(value)	
						}
						return r;
					},
					cols: 52,
					onComplete: function (transport){
						if (transport){
							n.hide();
							if (data = transport.responseText.evalJSON(true)) {
								
								if (_ajax_object['type']=='post'){
									_html = data[_ajax_object['type']].article.title;
								} else {
									_html = data[_ajax_object['type']].title;
								}
								
								n.update(_html);
								n.show();
							}
						}
					}
				}
			);
		}	
	}
	
	function _ajax_response_manage (n)
	{
		_ajax_object['type'] = _get_ajax_object_type(n);
		
		_total_indicator = n.up('.comments').down('.total');
			
		var _response_id = n.id.sub(/\D+/, '');
		var _response_container = $('ajax_comment_container_'+_response_id);
		var _response_old_copy = _response_container.innerHTML;	
		
		// edit
		new Ajax.InPlaceEditor(
			_response_container, 
			 _ajax_object['url'] + '/comment/' + _response_id + '/edit.json', 
			{ 
				callback: function(form, value) { return 'comment[comment]=' + encodeURIComponent(value) },
				externalControlOnly: true,
				externalControl: n.down('a.ajax_response_edit'),
				loadTextURL: _ajax_object['url'] + '/comment/' + _response_id + '/edit.text?get=response/comment/comment',
				rows:8,
				cols:48,
				clickToEditText: '',
				onComplete: function(transport) {
					if (transport){
						_response_container.update('');
						if (data = transport.responseText.evalJSON(true)) {
							if (data.errors){										
								_response_container.update(_response_old_copy);
								alert('Comment edit failed');
							} else {
								new Ajax.Request
								(
									_ajax_object['url'] + '/comment/' + _response_id + '.json', 
									{
										method: 'get',
										onComplete: function(transport){
											if (data = transport.responseText.evalJSON(true)) {
												_html = data.response.comment.comment.unescapeHTML();
												//@TODO a better way is required
												_response_container.update(_html);	
											}
										}
									}
								);
							}
						}
					}
					
				},
				onFailure: function(transport){
					alert('Comment edit failed');
				}
			}
		);
		
		// delete
		n.down('.ajax_response_delete').observe('click', function(e)
		{
			
			if (confirm('Are you sure you want to delete this comment')){
				new Ajax.Request
				(
					_ajax_object['url'] + '/comment/' + _response_id  + '/delete.json', 
					{
						method: 'post',
						parameters: {'response_id' : _response_id},
						onComplete: function(transport){
							if (data = transport.responseText.evalJSON(true)) {
								_total = 0;
								if (data[_ajax_object['type']].comments){
									_total = _append_zero(data[_ajax_object['type']].comments.length);
								}
								_html  ='<a href="' + _ajax_object['url'] + '#comments">' + _total + '</a> Comment(s)';
								_total_indicator.update(_html);
								
								Effect.toggle(_response_container.up('.item'), 'appear');
							}
						},
						onFailure: function(transport){
							alert('Comment delete failed');
						}
					}
				);
			}
			
			e.stop();
		});
	}
	
	function _ajax_edit_copyright (n)
	{		
		new Ajax.InPlaceCollectionEditor(
		$('ajax_copyright_id'), 
		 _ajax_object['url'] + '/edit.json', 
			{ 
				collection:[['1', 'All Rights Reserved'], ['0', 'Some Rights Reserved']],
				callback: function(form, value) { return 'copyright=' + encodeURIComponent(value) },
				externalControlOnly: true,
				externalControl: n,
				okControl: 'link',
				onComplete: function (transport)
				{
					if (transport){
						if (data = transport.responseText.evalJSON(true)) {
							
							discribe = data.photograph.copyrights['description'].capitalize();
							
							if (data.photograph.copyright==1){ 
								_html = '&copy; ' + discribe;
							} else { // Creative Commons
								_html = '<a class="_icon cc_icon" href="' + data.photograph.copyrights['url'] + '" title="Creative Commons - Attribution-Noncommercial-Share Alike 2.5 South Africa - Some Rights Reserved" rel="external"> ';
								_html += discribe + '</a>';
							}
							
							$('ajax_copyright_id').update(_html);
						}
					}
				}
			}
		);
	}
	
	
	function _ajax_foto_zoom(n)
	{
		var _zooming = 'out';
		var _original_image =  n.up('.view').down('.image');
		var _image_holder = n.up('.view').down('.image_holder');
		var _foto_url = _ajax_object['url'];
		
		n.observe('click', function(e)
		{
			e.stop();
			// _original_image.hide();		
			if (n.up('.foto_view').hasClassName('foto_view_larger')){ // out
				_zoom_icon = n.down('img').src.sub('out', 'in');
				_zooming = 'out';
				_foto_url = _ajax_object['url'] + '.json';
			} else { // in
				_foto_url = _ajax_object['url'] + '/larger.json';
				_zoom_icon = n.down('img').src.sub('in', 'out');
				_zooming = 'in';
			}
			
			n.down('img').hide();
			n.addClassName('ajax_spin_icon');
			
			
			new Ajax.Request
			(
				_foto_url, 
				{
					method: 'get',
					onSuccess: function (transport){
						if (data = transport.responseText.evalJSON(true)) {
							_width = data.photograph.image_size[0];
							_height = data.photograph.image_size[1];
							if (_zooming == 'in'){ // actually this is out;
								_src = data.photograph.large.url;
								n.up('.foto_view').addClassName('foto_view_larger');
								n.up('.foto_view').addClassName('two').removeClassName('three');
								n.up('.foto_view').down('.y').hide();
								
								//alert('traverse-on-the-inside');
								
								n.up('.foto_view').down('._foto_traverse').update(n.up('.foto_view').down('.y').innerHTML);
								n.up('.foto_view').down('._foto_traverse').show();
							} else {
								_src = data.photograph.medium.url;
								n.up('.foto_view').removeClassName('foto_view_larger');
								n.up('.foto_view').addClassName('three').removeClassName('two');
								n.up('.foto_view').down('.y').show();
								
								n.up('.foto_view').down('._foto_traverse').update(n.up('.foto_view').down('.y').innerHTML);
								n.up('.foto_view').down('._foto_traverse').hide();
							}
							
						}
					},
					
					onFailure: function(){
						alert('Sorry, failed to zoom in/out.');
					},
					
					onComplete: function(){
						n.down('img').src = _zoom_icon;
						
						_original_image.width = _width;
						_original_image.height = _height;
						_original_image.src = _src;
						
						n.removeClassName('ajax_spin_icon');
						n.down('img').show();
					
					}
				}
			);
		});
	}
	
	function _update_refresh_bar (_block, _stats)
	{
		_fotos = _append_zero(_stats.photographs);
		_comments = _append_zero(_stats.dialogue);
		if (data.stats.messages){
			_messages = _append_zero(_stats.messages);
		} else {
			_messages = null;
		}
		// udpating columns;
		if (_messages!=null) {
			_block.down('.messages').show();
			_block.down('.messages').down('a').update(_messages);
		}
		_block.down('.fotos').show();
		_block.down('.fotos').down('a').update(_fotos);
		
		_block.down('.comments').show();
		_block.down('.comments').down('a').update(_comments);
		_block.show();
		
		if (_fotos > 0 || _comments > 0 || _messages!=null){
			return true;
		}
		return false;
	}
	
	
	
	function _prepare_thumb(foto, comments, _size)
	{
		_size = (_size) ? _size : 49;
		_html = '';
		_thumb_options = '';
		_options_items = '';
		
		if (comments){
			show = {
				url: foto.url,
				comments: _append_zero(comments)
			}
			
			_options_items += _thumb_options_comments_tpl.evaluate(show);
		}
		
		if (_options_items){
			show = {
				items: _options_items
			}
			_thumb_options += _thumb_options_tpl.evaluate(show);
		}
		
		_foto_title = (foto.title) ? foto.title : '(untitled)';
		
		show = {
			title: 	_foto_title.unescapeHTML() + ' &ndash; ' +  foto.owner.alias.unescapeHTML(),
			url: foto.url, 
			src: foto.thumb.url,
			smaller: 'smaller',
			width: _size,
			height: _size,
			options: _thumb_options
		};
		
		_html = _thumb_tpl.evaluate(show);
		
		return _html;
	}
	
	function _list_thumbs(_fotos, list_type, limit)
	{
		_html = '';
		_items_html = '';
		
		switch (list_type){
			case 'dialogue':
					foto_index = 'photograph';
				break;
			default:
					foto_index = null;
			break;
		}
		
		_fotos.each(function(_foto, index)
		{	
			
			if (foto_index){
				_foto_thumb_html = _prepare_thumb(_foto[foto_index] , _foto.total);
			} else {
				_foto_thumb_html = _prepare_thumb(_foto);
			}
			
			_last = ((index + 1) % limit == 0 && index != 0) ? 'last' : '';
			show = {
				thumb: _foto_thumb_html,
				last: _last
			}
			
			_items_html += _fotos_list_item_tpl.evaluate(show);
		});
		
		show = {
			items: _items_html,
			smallerThumbs: 'smallerThumbs'
		}
		
		_html = _fotos_list_tpl.evaluate(show);
		
		return _html
		
	}
	
	function _show_refreshed_items (_block, _data)
	{	
		_html = '';
		if (_data.stats.photographs>0) // fotographs
		{
			_html = _list_thumbs(data.photographs['new'], null, 7);//'';
			_block.down('.ajax_refresh_fotos').down('.panel').update(_html);
			_block.down('.ajax_refresh_fotos').show();
		}
		
		if (_data.stats.dialogue>0){ // comments
			_html = _list_thumbs(data.dialogue, 'dialogue', 7);//'';
			_block.down('.ajax_refresh_comments').down('.panel').update(_html);
			_block.down('.ajax_refresh_comments').show();
		}
		if (_html){
			$('spine').show();	
			new Effect.SlideDown($('spine').down('.eleven'), { duration: 1, queue: 'front' });
		}
	}
	
	function _get_fresh_items(n)
	{
		var _r = n.down('._ajax_refresh_point').down('a');
		var _items = null;

		var _refreshing = false;
		var _refresh_notify = n.down('.notify');
		var _refresh_items = n.down('.points');
				
		n.down('._ajax_refresh_point').observe('click', function(e)
		{
			e.stop();
			
			$('spine').hide();
			$('spine').down('.eleven').hide();	
			
			
			_refresh_items.hide();
			
			if (_refreshing==false){						
				_refreshing = true;
				
				_r.removeClassName('refresh_icon').addClassName('spin_icon');
				
				new Ajax.Request
				(
					'/index.json', 
					{
						method: 'get',
						onSuccess: function (transport){
							if (data = transport.responseText.evalJSON(true)) {
								
								_items = data;
							}
							n.down('.notify').hide();
						},
						
						onFailure: function(){
							n.down('.notify').show();
							n.down('.notify').update('Sorry, failed to get refresh data.');	
						},
						
						onComplete: function(){
							
							_r.removeClassName('spin_icon').addClassName('refresh_icon');
							
							if (_update_refresh_bar(_refresh_items, data.stats)){
								// flout layer
								_show_refreshed_items($('spine'), data);
							}
								
							_refreshing = false;
						
						}
					}
				);
				
			} else {
				n.down('.notify').show();
				n.down('.notify').update('Already running previous request.');	
			}
		});
	}
	
	
	function gen_ajax_actions()
	{
		//	refresher
		$$('._ajax_refresher_block').each(function(n){	
			n.down('._ajax_refresh_point').show();
			_get_fresh_items(n);
		});
			
			//	refresher
			$$('.ajax_close_bar').each(function(n){	
				n.observe('click', function(e)
				{
					e.stop();	
					Effect.toggle($('spine'), 'slide', { duration: 1 });
					
				});
				
			});
			
		// generic objects;
			// all 
			
				// title ajax_title_edit ajax_photograph_object
				$$('.ajax_title_edit').each(function(n){
					_ajax_edit_title(n);
				});
				
				// tags ajax_tags_edit ajax_photograph_object
				$$('.ajax_tags_edit').each(function(n){
					_ajax_edit_tags(n);
				});
				
				// response -- ajax_response_object
				$$('.ajax_response_object').each(function(n){
					_ajax_response_manage(n);
				});
				
			// foto
				// love
				$$('.foto_view .ajax_foto_show_love').each(function(n){
					_show_love(n);
				});
				
				// copyright
				$$('.foto_view .ajax_copyright_controller').each(function(n){
					_ajax_edit_copyright(n);
				});
				// black bg; foto_view
				$$('.foto_view .ajax_switch_background').each(function(n){
					_apply_go_black(n);
				});
				
				// black bg; foto_view
				$$('.foto_view .ajax_foto_zoom').each(function(n){
					_ajax_foto_zoom(n);
				});
		
		
		// share
		$$('.share .ajax_share_object').each(function(n){
			
			_share_object(n);
		});
		
		// camera show
		$$('.ajax_camera_object .selector').each(function(n){
			_camera_object(n);
		});
		
	}
	
	_apply_action('gen_ajax_actions');
	
	
	
	