// JavaScript Document
	
// objects of type posts;

		
// social
	var Body =  Class.create (
	{
		initialize: function(_doc, _extended_body)
		{
			this._doc = _doc;
			this._init();
		},
		
		_init :  function (_specific_)
		{
			_all = (_specific_) ? false : true;
			
			// links
			if ( _specific_ == 'links' || _all ) this._doc.select('a').each ( function (_link) { this._link_actions (_link) }, this );
				
			// social buttons
			if ( _specific_ == 'social buttons' || _all ) this._doc.select('._social_button_action').each ( function (_button) { this._social_actions(_button) }, this );
				
			// forms
			if ( _specific_ == 'forms' || _all ) this._doc.select('form').each ( function (_form) { this._form_actions (_form) }, this );
			
			// content types;
			if ( _specific_ == 'contents' || _all ) this._doc.select ('.js_content_object').each ( function (_content) { _content = new Content (_content) }, this );
				
			// extra extension;
				
			if ( _all )	Object.extend(this, _extended_body);
		},
		
		_form_actions : function (_form)
		{
			// auto_height
				_form.select ('textarea.auto_resize_height').each
				(
					function (_textarea, _index)
					{	
						var _textarea_txt = _textarea;
						var _textarea_height = _textarea_txt.rows-1;
				
						_textarea.onkeydown = function (_e)
						{	
							c = 0; r = 2; t = _textarea_txt.value;
							
							for(var i=0; i<t.length; i++) 
							{
								if (t.substr(i,1) == '\n') {
									c = 0;
									r++;
								} else {
									c++;
									if(c >= _textarea_txt.cols) { c=0; r++; }
								}
							}
							
							if (r>_textarea_height){
								_textarea_txt.rows = r;				
							}
						}
					}
				)
				
			// submit	
				if (_form.hasClassName('no_form_submit_magic') == false)
				{
					_form.onsubmit = function (_e)
					{
						_valid = true;
						
						_process_html  = '<dl class="clearfix submit_spin_icon warn inform"><dt class="title"><b>un</b> <span>momento</span></dt>'
						_process_html += '<dd class="story"><p>processing.</p></dd><dd class="tag">please, be patient &ndash; it does <em>tend</em> to take awhile.</dd></dl>';
										
						_form.select('.required').each 
						(
							function (	_field )
							{
								if ( _field.tagName.toLowerCase()  == 'label') 
								{	
									_value = ( $( _field.readAttribute('for') ) ) ? $( _field.readAttribute('for') ).getValue() : null;
								} else {
									_value = _field.getValue();
								}
								
								if ( _value.empty() == true ) {
									_field.addClassName('error');
									_valid = false;
								} else {
									_field.removeClassName('error');
								}
							}
						)
						
						if ( _valid == true ) 
						{ 
							if (! $('form_processing'))
							{
								_process = document.createElement( 'div');
									Element.extend (_process);
								_process.update ( _process_html);
								_process.id = 'form_processing';
								_process.addClassName ('form_processing');
									
								_form.insert( {'top':  _process } );
							} else {
								$('form_processing').show();	
							}
							_form.select('fieldset').invoke('hide');
						} else {
							_e.stop() ;
						}
					}
				}
				
			// switch panels;
				
				
				this._doc.select ('.js_form_panels .point').each
				(
					function (_p, i)
					{
						if ( _b = $( _p.down('a').hash.sub(/#/, '') ) )
						{
							_p.observe ('click', function (_e) {
								
								_form.select('.js_form_panel').invoke('hide');
								
								_p.up('.js_form_panels').select('.point').each ( function ( _h ) { _h.removeClassName('selected'); } );
								
								_p.addClassName('selected');
								
								$( _p.down('a').hash.sub(/#/, '') ).show();
								
								_e.stop();
							});
						}
					}.bind(_form)
				);
				//alert(this._doc.select ('.js_form_panels .point'));
			
		},
		
		_link_actions : function (_link)
		{
			
			if ((_link.protocol == 'http:' || _link.protocol == 'https:') && window.location.host != _link.hostname)
			{
				_link.target = '_blank';
			}
		},
		
		_social_actions : function (_button)
		{
			_button.stopObserving('click');
			
			_button.observe('click', function(_e)
			{
				_e.stop();	
				window_opener = window.open(_button.href, '', "status=1,toolbar=0, location=0, width=540, height=320"); 
				window_opener.moveTo((document.viewport.getDimensions().width - 480)/2, (document.viewport.getDimensions().height - 320)/2);
				
			});			
		},
		
		sleep: function (milliseconds) // http://blog.maestropublishing.com/prototype-js-sleep-function
		{   
			var start = new Date().getTime();   
			   
			for (var i = 0; i < 1e7; i++) {   
				if ((new Date().getTime() - start) > milliseconds) {   
					break;   
				}   
			}   
		}   
	});
	
	var Gallery_Image = Class.create(
	{
		initialize : function (img)
		{
			this.temp_src = '/views/boom/images/ui/bgs/1.png';
			
			this.img = img;
			this.original_src = this.img.src;
			
			this.thumb_src = img.src.replace(/([^\/]+)\.([\w]{3})$/, 'thumb_$1.$2');
			//	this.img.src = this.thumb_src;
			
			
		},
		
		_stall: function()
		{
			this.img.src = this.temp_src;
		}
		
	});
	
	var Gallery = Class.create (
	{
		initialize : function (obj)
		{
			this.obj = obj;
			this.items_index = 0;
			this.obj.addClassName('clearfix gallery_image_set');
			
			this.obj.observe ( 'click', function(_e) { this.swap() }.bind(this) );
			
			this.list = obj.select('li');
			
				_label_html = '<div class="clearfix gallery_image_set_counter">';
					_label_html += '<span class="counter"><strong>' + _append_zero(eval(this.items_index+1) )+ '</strong>' + _append_zero( this.list.length ) + '</span>';
					_label_html += '<span class="help">click on the image+foto to view others</span>';
				_label_html += '</div>';
				
			this.obj.insert( {'before': _label_html });	
			
			this._images = new Array (this.list.length);
			
			this.list.each
			(
				function(_item, _index)
				{
					this._images[_index] = new Gallery_Image (_item.down('img'));
					if (_index > 0) { _item.hide() };
				},
				this
			)
		},
		
		swap: function()
		{
			
			new Effect.BlindUp(this.list[this.items_index], { duration: 0.5, queue: { position: 'start', scope: 'gallery_image_slide_up', limit: 1 } });
			this.items_index  = (this.items_index + 1 < this.list.length) ? this.items_index + 1 : 0;
			
			new Effect.SlideDown(this.list[this.items_index], { duration: 0.5, queue: { position: 'end', scope: 'gallery_image_slide_down', limit: 1 } });		
				this.obj.up('.story').down('.gallery_image_set_counter span strong').update(_append_zero(eval(this.items_index+1)));
		}
	});
	
	var Content = Class.create (
	{
		initialize : function (obj)
		{
			this.obj = obj;
			// object ajax;
			if ( _ajax_object['type'] = this._get_object_type(obj) )
			{
				// title;
					//	obj.select ('.ajax_title_edit').each( function ( _n ) { this._object_edit_title ( _n ) }, this  );
				// love
					obj.select ('.ajax_post_show_love').each( function ( _n ) { this._object_show_love ( _n ) }, this  );
					
				// tags
					//	obj.select ('.ajax_tags_edit').each( function ( _n ) { this._object_edit_tags ( _n ) }, this  );
					
				// comments
					obj.select ('.ajax_response_object').each( function ( _n ) { this._object_response_manage ( _n ) }, this  );
					
					// commenting
					obj.select ('.respond form').each(
						function (_f)
						{
							_f.observe ('submit', function (_e) { _e.stop(); this._object_response_post (_f, _e) }.bind (this) )	
						},
						this
					)
					
			}
			
			// gallery
				this._gallery (obj);
				
			// videos
				this._videos (obj);
		},
		
		_object_response_post: function (_form, _e)
		{
			/*
				should the time come that I have make sure a comment has preceding comments before it, it will done by
				find the last id of the previous comment, then using that to check how many comments came after 
				and loop through the creation to show 'em here;
			*/
			_form.action = _form.action.replace ('#respond', '.json');
			
			_tpl = '<li id="response-#{reponse_id}" class="item #{odd}  ajax_response_object ajax_#{object_type}_object  response clearfix" style="display: none">#{response}</li>';			
			var _response_template = new Template(_tpl);
		
			_form.request (
			{
				onComplete: function (_t) 
				{ 
					if (_d = _t.responseText.evalJSON(true)) { 
					
					
						_r = _d[_ajax_object['type']].comments[_d[_ajax_object['type']].comments.length-1];
						
						_response_url =  _ajax_object['url'] + '/comments/' + _r.response_id + '/panel.file';
						
						new Ajax.Request (
							_response_url,
							 {
								 method: 'get',
								 onComplete: function (_tr) 
								{
									_odd = ( ( _d[_ajax_object['type']].comments.length-1 ) % 2 == 0 ) ? '' : 'odd';
																		
									_response_tpl_string = { reponse_id: _r.response_id, response:  _tr.responseText, odd: _odd, object_type: _ajax_object['type'] 	}
									
									_response_html = _response_template.evaluate ( _response_tpl_string );
									
									if (typeof this.obj.down ('.comments .replies') == 'undefined') {
										
										_ol = document.createElement( 'ol'); Element.extend (_ol);
										_ol.addClassName ('replies list');
											
										this.obj.down ('.comments').insert( {'bottom':  _ol } );
									}
									
									this.obj.down ('.comments .replies').insert( {'bottom':  _response_html } );
									
									_r_item = $ ('response-' + _r.response_id); Effect.toggle ( _r_item, 'appear' );
									
									this._object_response_manage ( _r_item );

								}.bind (this)
							 }
						);					
					}
					
					_form.reset ();
					_form.action = _form.action.replace ('.json', '#respond');
					_form.select('fieldset').invoke('show');
					
					$('form_processing').hide();
					
				}.bind (this),
				
				onFailure: function(transport) { alert('Comment edit failed') }
 
			}, this)
		},
		
		_object_response_manage : function ( _n ) 
		{
			
			var _total_indicator = _n.up('.comments').down('.total');
			var _response_id = _n.id.sub(/\D+/, '');
			
			var _response_container = $('response-'+_response_id);
			var _response_old_copy = _response_container.down('.story').innerHTML;	
		
		
		// edit
			_ajax = new Ajax.InPlaceEditor
			(
				_response_container.down('.story'), 
				 _ajax_object['url'] + '/comments/' + _response_id + '/edit.json', 
				{ 
					loadTextURL: _ajax_object['url'] + '/comments/' + _response_id + '/edit.text?get=response/comment/comment',
					callback: function (form, value) { return 'comment[comment]=' + encodeURIComponent (value) },
					
					externalControlOnly: true,
					externalControl: _n.down('a.ajax_response_edit'),				
					
					rows:8, cols:48, clickToEditText: '',
					formClassName: "inplaceeditor-form clearfix",
					
					onComplete: function (_t) 
					{
						if (_d = _t.responseText.evalJSON(true))
						{
							_response_container.down('.story').update('');
						
							if (_d.errors) {										
								_response_container.down('.story').update(_response_old_copy);
								alert('Comment edit failed');
								return false;
							};
							
							_get_url = _ajax_object['url'] + '/comments/' + _response_id + '.json';
							
							_ajax_inside = new Ajax.Request	(
							_get_url, 
							{
								method: 'get',
								onComplete: function ( _rt ) 
								{
									if (_d = _rt.responseText.evalJSON(true)) { _response_container.down('.story').update(_d.response.comment.comment); }
								}
							});
						}
					},
					onFailure: function(transport){
						alert('Comment edit failed');
					}
				}
			);
		
	
			_n.down('.ajax_response_delete').observe 
			(
				'click', 
			
				function(_e) 
				{
					
					if ( confirm ('Are you sure you want to delete this comment') )
					{
						_ajax = new Ajax.Request
						(
							_ajax_object['url'] + '/comments/' + _response_id  + '/delete.json', 
							{
								method: 'post',
								parameters: {'response_id' : _response_id},
								
								onComplete: function ( transport )
								{
									if ( _d = transport.responseText.evalJSON(true)) 
									{
										_html = ( _d [_ajax_object['type']].comments ) ? _append_zero( _d[_ajax_object['type']].comments.length ) : 0 ;							
										_total_indicator.update(_html);
										
										Effect.toggle ( $('response-' + _response_id), 'appear' );
									}
								},
								
								onFailure: function(_t){ alert ('Comment delete failed') }
							}
						);
					}
					_e.stop();
				}
			);
		},
		
		_object_edit_tags : function ( _n )
		{
			_ajax = 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 (_t)
					{	
						if (_d = _t.responseText.evalJSON(true))
						 {
							
							$('ajax_tags_editor').hide();
							
							_html = '';
							if ( _d[_ajax_object['type']].tags )
							{
								
								_d[_ajax_object['type']].tags.each( function(s, index)
								{
									switch(_ajax_object['type'])
									{
										case 'photograph':
												_html += '<a href="' + data.photograph.space.url + '/tags/' + s.tag + '">' + s.clean + '</a>';
											break;
										case 'stream':
												_html += '<a href="/broadcast/stream/tags/' + s.tag + '">' + s.clean + '</a>';
											break;
										case 'post':
												_html += '<a href="/words/tags/' + s.tag + '">' + s.clean + '</a>';
											break;
									};
									
									if (index+1 < _d[_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');	
					}
				}
			);
		},
		
		_object_edit_title : function ( _n )
		{
			 _ajax = new Ajax.InPlaceEditor	
			 (
				_n, 
				_ajax_object['url'] + '/edit.json', 
				{ 
				callback: function(form, value) 
				{ 
						r = 'title=' + encodeURIComponent (value);
					if ( _ajax_object['type'] == 'post' ) { r = 'title=' + encodeURIComponent(value) };
					
					return r;
				},
				
				cols: 52,
				
				onComplete: function (_t) 
				{
					if (_d = _t.responseText.evalJSON(true))
					{	
						_html = ( _ajax_object['type'] == 'post' ) ? _d[_ajax_object['type']].title : _d [_ajax_object['type']].title ;
						_n.update(_html);
					}
				}
			});
		},
		
		_object_show_love : function ( _n )
		{
			var _love_making = false;
						
			_n.observe 
			( 
				'click', 
				function(_e) 
				{
					_e.stop();
					var _love_icon = _n.down('img').src;
				
					if (_love_making == false)
					{
						_love_making = true;
						_n.down('img').src = '/public/images/icons/spinner.gif';
						_ajax = new Ajax.Request
						(
							_n.href + '.json', 
							{
								method: 'post',
								onSuccess: function (_t) 
								{
									if (_d = _t.responseText.evalJSON (true) ) 
									{
																				
										if ( _d [ _ajax_object ['type'] ].loving )
										{
											_total = _append_zero( _d [_ajax_object ['type'] ].loving.total );
											
											_total_update = (_d [_ajax_object ['type'] ].loving.total > 0) ? '.' + _total : '' ;
											
											_n.up(0).down('span').update( _total_update );
										}
									}
								},
								
								onFailure: function () { _n.down('img').src = _love_icon; alert ('Sorry, we failed to make love to this.') },
								
								onComplete: function( _t ) 
								{		
									_d = _t.responseText.evalJSON(true);
									_n.down('img').src = ( _d [ _ajax_object ['type'] ].loving.colour )  ? '/public/images/icons/heart_red.png' : '/public/images/icons/heart_gray.png' ;
									_love_making = false;
								}
							}
						);
					} else {  alert('Sorry, one lover at a time.')	}
				}
			);
		},
		
		
		_gallery : function (el)
		{
			el.select('.story_gallery_images').each ( function(_n)  { _g = new Gallery (_n)	} );
		},
		
		_videos : function (_el)
		{
			var playlist = [];
			
			_el.select('.inline_video_object').each
			(
				function(_n, _i) 
				{
					_n.id = 'video_player_' + _i;
					playlist [_i] =
					
					{
						_i:{ 
							id: _n.id,
							src: _n.down('video source').src , 
							type: _n.down('video source').type 
						},
						config: {
							_id: _n.down('video').id,
							_width:  _n.down('video').width,
							_height: _n.down('video').height,
						}
					};
					
				}
			);
			
			jQuery(document).ready
			(
				function() 
				{
				
					if ( playlist ) { 
						jQuery.each 
						(
							playlist, 
							function(index, value)  { 
								projekktor (
									'#'+value.config._id, 
									{
										controls: true,
										playerFlashMP4: 	'/public/projekktor/jarisplayer.swf',
										playerFlashMP3: 	'/public/projekktor/jarisplayer.swf',
										volume: 0.5
									}
								);
							}
						);
					}
				}
			);
		},
		
		_get_object_type: function (obj)
		{
			_type = false;
			
			if (obj.hasClassName('js_content_object_type_stream')) _type = 'stream';
			if (obj.hasClassName('js_content_object_type_post')) _type = 'post';		
			
			return _type;
		}
		
	});
	
	var _extended_body = 
	{
		_extend : function ()
		{
			this._list_item_reposition (this._doc);	
			//this._doc.select ('._js_quick_love').each ( function (_n) { this._quick_love (_n) } );
			
			//alert (this._doc);
		},
		
		_old_list_item_reposition : function (_el)
		{
			_el.select('.js_reposition_item').each
			(
				function(_item) 
				{
					i_h  = _item.getHeight();
					il_h = _item.down('.word_wrap').getHeight();
					ia_h = _item.down('.title').down('a').getHeight();
					
					d_h = 135 - ia_h;
					
					_item.down('.word_wrap').setStyle(
					{
						top: d_h + 'px'
					});
				}
			);
		},
		
		_list_item_reposition : function (_el)
		{
			_el.select('.old_new_archive .archive').each 
			( 
				function(_item)  
				{ 
					_item.select ('.word').each 
					(
						function (_w)
						{
							if (_w.getHeight () < _item.getHeight())
							{
								_old_pad = Math.round( (_item.getHeight() - _w.getHeight () ) / 2 ) ;
								_w.down('.thumb_link').setStyle(
								{
									paddingBottom: _old_pad + 'px',
									paddingTop: _old_pad + 'px'
								});	
							}
						}
					)
				} 
			);
			
			_el.select('.old_new_archive .new .word').each 
			( 
				function(_item)  
				{ 
					//_item.makePositioned();
					if (_item.hasClassName ('no_height_adjust') == false )
					{
						_m = eval(_item.up('.old_new_archive').down('.old').getHeight() - _item.down ('.title_date_wrap').getHeight());
						
						if ( _item.down('.activity') ){	_m = _m - _item.down('.activity').getHeight() }
						
						_m = Math.ceil( ( _m - _item.down('.thumb_link').getHeight() - 25 ) /2);
						
						_item.down('.thumb_link').setStyle(
						{
							paddingBottom: _m + 'px',
							paddingTop: _m + 'px'
						});
					}
				}
			);
		}
	};
	
	
	function _apply_general_actions()
	{	
		$$('body').each
		(
			function(_n)
			{
				_doc = new Body (_n, _extended_body);	
				// extentions
					if (typeof _doc._extend) _doc._extend ();
			}
		);
	}
	
	_apply_action('_apply_general_actions');
	
	
	
	




