$(document).ready(
	function()
	{
		//
		// Open a message box and retreive it's content
		// via an AJAX request to the specified url.
		//
		function openAjaxMessageBox(url, data, options)
		{
			$.post(
				GLOBALS.webBasepath+ url,
				data,
				function(data)
				{
					$.fn.messageBox.closeLast();
					if (data != null && data != '')
					{
						$.fn.messageBox(options);
						$.fn.messageBox.open(data);
					}
				}
			);
		}	
		
		//
		// Download box 
		//
		$('.pitch .download').click(
			function(event)
			{
				var pitchId = $(this).attr('rel');
				openAjaxMessageBox('/ajax/pitch-downloads/', {'pitchId' : pitchId});
				event.preventDefault();
			}
		);
		
		//
		// Appointment box
		//
		appointmentButton = null;
		$('.pitch .appointment').live(
			'click',
			function(event)
			{
				appointmentButton = $(this);
				var pitchId = appointmentButton.attr('rel');
				openAjaxMessageBox('/ajax/pitch-appointment/', {'pitchId' : pitchId});
				event.preventDefault();
			}
		);
		
		//
		// Short description popup 
		//
		$('.pitch .show-description').click(
			function(e)
			{
				var description = $(this).parent().find('.description');
				
				$.fn.messageBox.closeLast();
				$.fn.messageBox();
				$.fn.messageBox.open(description.html());
				
				e.preventDefault();
			}
		);
		
		//
		// Appointment form submission
		//
		$('.popup-appointment .submit').live(
			'click',
			function(event)
			{
				$.post(
					GLOBALS.webBasepath+ '/ajax/pitch-appointment/',
					collectFieldValues(),
					function(data)
					{
						if (data != null && data != '')
						{
							$('#messageBox_0 .messageBox_inner').html(data);
						}
						else
						{
							appointmentButton.attr('class', 'disabled');
							$.fn.messageBox.closeLast();							
						}
					}
				);
				event.preventDefault();
			}
		);
		
		//
		// Collect field values
		//
		function collectFieldValues()
		{
			var values = {};
			
			// radio buttons
			$('form input:radio:checked').each(
				function()
				{
					var $field = $(this);
					values[$field.attr('name')] = $field.val();
				}
			);
			
			// checkboxes
			$('form input:checkbox:checked').each(
				function()
				{
					var value  = 'on';
					var $field = $(this);					
					if ($field.val() != '')
					{
						value = $field.val();
					}					
					values[$field.attr('name')] = value;
				}
			);
			
			// text fields / textareas
			$('form input:text, form textarea, form input:hidden').each(
				function()
				{
					var $field = $(this);					
					values[$field.attr('name')] = $field.val();
				}
			);
			
			return values;
		}
		
		//
		// Clear fields on enter
		//
		var $fields = $('.clear_on_enter');
		$fields.live(
			'click',
			function()
			{
				$(this).val('');
			}
		);
				
		//
		// agency rating
		//
		
		// css-loader
		function loadCSS(path)
		{
			var fullpath = GLOBALS.webBasepath+ '/' +path;
			var el = '<link rel="stylesheet" href="' +fullpath+ '" type="text/css" />;';
			$('head').append(el);
		}
		
		loadCSS('resources/styles/agencyrating.css');
		ratingButton = $('.rate-agency');
		ratingButton.click
		(
			function(ev)
			{
				ev.preventDefault();
				
				var ids 		= $(ev.target).parent().attr('rel');
				var pitch_id	= ids.substring(0,ids.indexOf('|'));
				var agency_id	= ids.substring(ids.indexOf('|')+1);
				$.ajax({
					type	:	'POST',
					url		:	GLOBALS.webBasepath+"/ajax/rate-agency",
					data	:	{
									'agency_id'		: agency_id,
									'pitch_id'		: pitch_id,
									'mode'			: 'getForm'
								},
					dataType:	'html',
					cache	:	false,
					success	:	function(data, status)
								{
									$.fn.messageBox.closeLast();
									$.fn.messageBox
									(
										{
											buttons			:	new Array
											(
												{
													caption	: 'abbrechen',
													action	: function(){$.fn.messageBox.close($(this).parent('.messageBox'));ratingButton.attr('class', '');}
												},
													
												{
													caption	: 'Bewertung abgeben',
													action	: submitRatingForm
												}
											)
										}
									);
									$.fn.messageBox.open($(data));
									ratingButton.attr('class', 'disabled');
								},
					error:	function(request, status, error)
								{
									$.fn.messageBox.closeLast();
									$.fn.messageBox();
									$.fn.messageBox.open($(request.responseText));
								}
				});
			}
		)
		
		function submitRatingForm()
		{
			$.ajax({
				type	:	'POST',
				url		:	GLOBALS.webBasepath+"/ajax/rate-agency",
				data	:	{
								'agency_id'		: $('span#agency_id').text(),
								'pitch_id'		: $('span#pitch_id').text(),
								'rating_price'	: getValueFromScale('price'),
								'rating_terms'	: getValueFromScale('terms'),
								'rating_service': getValueFromScale('service'),
								'mode'			: 'processRating'
							},
				dataType:	'html',
				cache	:	false,
				success	:	function(data, status)
							{
								$.fn.messageBox.closeLast();
								$.fn.messageBox();
								$.fn.messageBox.open($(data));
							},
				error:	function(request, status, error)
							{
								$.fn.messageBox.closeLast();
								$.fn.messageBox();
								$.fn.messageBox.open($(request.responseText));
							}
			});
		}
		
		function getValueFromScale(classname)
		{
			var text =  $('ol.' + classname +' > li.selected:last').text();
			var value = parseInt(text);
			
			if(isNaN(value))
			{
				value = 0
			}
			return value;
		}
				
		function calculateTotal()
		{
			var price	= getValueFromScale('price');
			var terms	= getValueFromScale('terms');
			var service	= getValueFromScale('service');
			var total = String((price + terms + service)/30);
			if(total.indexOf('.') == -1)
			{
				total += '.0';
			}
			var p1 = total.substr(0,total.indexOf('.'));
			if(p1 == '')
			{
				p1='0';
			}
			var p2 = total.substr(total.indexOf('.')+1,1);
			if(p2 == '')
			{
				p2='0';
			}
			return p1 + ',' + p2;
		}
		
		$('ol.scale li')
		.live
		(
			'click',
			function(ev)
			{
				$li = $(ev.target);
				$li.addClass('selected');
				$li.prevAll('li').addClass('selected');
				$li.nextAll('li').removeClass('selected');
				$('span.total').text(calculateTotal());
			}
		)
	}
);
