// globals
dialog_is_open = 0;
reload_period = 5*60*1000;

function bind_handlers(){
	// capture ajax links
	$("a.ajax_link")
	.unbind( 'click' )
	.bind('click', function(e){
					ajax_block( $(this).attr('href'),
								$(this).closest('.response_container').attr('id'), 1, 1 );
					return false;
						  });
	// capture ajax form submition
	$('form.ajax_form')
	.unbind( 'submit' )
	.bind('submit', function(e) {
				ajax_form( $(this).attr('id'), 'POST', 1, 0 );
				return false;
					}); // end bind

	// bind toolbar options
	$('.entry-toolbar a')
	.unbind( 'click' )
	.bind( 'click',
		  function(){
			  dialog_is_open = 1;
			  var dom_link = $(this);
			  var dialog_title = $(this).find('.ui-icon').attr('title');
			  $('<div id="modal_dialog"><img src="/SpryAssets/spinner_small.gif" hspace="10" vspace="10" border="0" align="center" /></div>')
			  .appendTo('body')
			  .load( dom_link.attr('href'), 'caller=ajax', bind_newly_loaded ) // end load
			  .dialog({ width: 450, minWidth: 400, bgiframe: true, modal: true, resizable: true,
					  title: dialog_title,
					  position: 'top',
					  close: function(event, ui) {
						  $(this).remove();
						  dialog_is_open = 0;
					  }
					  });
			  return false;
	}); // end toolbar bind

} // end bind_handlers

function bind_newly_loaded(responseText, textStatus, XMLHttpRequest) {
   // find and bind newly loaded form
   $(this).find('form.ajax_form:first')
   .unbind( 'submit' )
  .bind('submit', function(e) {
				dom_form = $(this);
				var form_id = dom_form.attr('id');
//				alert(form_id);
				if( form_id == 'tell_a_friend' ){
					ajax_form( form_id, 'POST', 2, 1 );
				}else{
					ajax_form( form_id, 'POST', overwrite, inner_response );
				}
				return false;
				}); // end inner bind
}
// page refresh function
function timed_reload() {
	if( dialog_is_open )
	{
		setTimeout("timed_reload()", reload_period);
		return;
	}
	location.reload(true);
}

$(document).ready(function() {
	bind_handlers();
	// global settings for all ajax calls
	$.ajaxSetup({
				type: 'POST', // default
				data: 'caller=ajax',
				complete: bind_handlers // unbind and rebind handlers
	});// end ajaxSetup, remeber last comma

	// options icon hover
	$('.entry-toolbar a').hover(
					function() { $(this).addClass('ui-state-hover'); },
					function() { $(this).removeClass('ui-state-hover'); }
		);
	
}); // end ready
