var SU = {};

SU.Ajax = {};

SU.Ajax.jsonRequest = function(params) {
	$.ajax({
		url:		params.url,
		data:		params.data,
		type:		'POST',
		dataType:	'json',
		success:	function(response) {
			if (response._success) {
				delete response._success;
				params.success(response);
			} else {
				SU.Dialog.Open.Error(response._msg);
				delete response._success;
				delete response._msg;
				params.error(response);
			}
		},
		error:		function(response) {
			SU.Dialog.Open.Error("Ajax Request Error");
			params.error(response);
		}
	});
};

SU.Persistence = {};
SU.Persistence.url = $.url();
SU.Persistence.params = {};

SU.Persistence.SetHash = function(){
	for (var key in SU.Persistence.params){
		if (!SU.Persistence.params[key]){
			delete(SU.Persistence.params[key])
		}
	}
	window.location.hash = $.param(SU.Persistence.params);
}

SU.Dialog = {};
SU.Dialog.Open = {};

$(function() {
	
	SU.Dialog.Generic = $("#generic-dialog");
	SU.Dialog.Generic.dialog({
		autoOpen :	false,
		draggable :	false,
		modal :		true,
		resizable :	false
	});
	SU.Dialog.Open.Message = function(dialogTitle, msg) {
		SU.Dialog.Generic
		.dialog('option', 'width', 300)
		.dialog('option', 'height', 150)
		.dialog('option', 'title', dialogTitle)
		.dialog('option', 'buttons', {
			'OK' : function() {
				SU.Dialog.Generic
				.dialog('close')
				.dialog('option', 'title', '')
				.html('');
			}
		})
		.html(msg)
		.dialog('open');	
	};
	
	SU.Dialog.Confirm = $("#confirm-dialog");
	SU.Dialog.Confirm.dialog({
		autoOpen :	false,
		draggable :	false,
		modal :		true,
		resizable :	false,
		width :		300,
		title :		'Confirm'
	});
	SU.Dialog.Open.Confirm = function(msg, yes, no, dialogHeight) {
		SU.Dialog.Confirm
		.dialog('option', 'height', dialogHeight)
		.dialog('option', 'buttons', {
			'Yes': function() {
				yes();
				SU.Dialog.Confirm
				.unbind('dialogclose')
				.dialog('close')
				.html('');
			},
			'No': function() {
				SU.Dialog.Confirm
				.dialog('close')
				.html('');
			}
		})
		.unbind('dialogclose')
		.bind('dialogclose', no)
		.html(msg)
		.dialog('open');
	};
	
	SU.Dialog.Error = $("#error-dialog");
	SU.Dialog.Error.dialog({
		autoOpen :	false,
		draggable :	false,
		modal :		true,
		resizable :	false,
		width :		300,
		height :	170,
		title :		'Error',
		buttons : {
			'OK' : function() {
				SU.Dialog.Error
				.dialog('close')
				.html('');
			}
		}
	});
	SU.Dialog.Open.Error = function(msg) {
		SU.Dialog.Error
		.html(msg)
		.dialog('open');	
	};
	
	$('#page .body > :first:not(.shaded-box)').addClass('first');
	$('#page .body > :last:not(.shaded-box)').addClass('last');
	
	$('a.disabled').live('click', function() {
		return false;
	});
	
	var $search = $('#search');
	if ($search.length > 0) {
		
		$search.find('input').bind('focus', function() {
			var $this = $(this);
			if ($this.hasClass('hint')) {
				$this.data('hint', $this.val());
				$this.val('');
				$this.removeClass('hint');
			}
		}).bind('blur', function() {
			var $this = $(this);
			if ($this.val() == '') {
				$this.addClass('hint');
				$this.val($this.data('hint'));
			}
		});
		
		$search.find('form').bind('submit', function() {
			var term = $(this).find('input').val()
			if (term.length < 2) {
				SU.Dialog.Open.Error('Sorry, but your search term has to be at least two letters long.');
			} else {
				window.location = '/search/' + term;
			}
			return false;
		});
	}
	
	$('button, a.button').button();
	$('form .date').datepicker();
	$('form .radio').buttonset();
	
	$('form .daterange').datepicker({
		numberOfMonths:	3,
		onSelect:		function(selectedDate) {
			var instance = $(this).data('datepicker');
			var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
			var parts = this.id.split('-');
			if ($(this).hasClass('daterange-from')) {
				$('form .daterange#' + parts[0] + '-to').datepicker('option', 'minDate', date);
			} else {
				$('form .daterange#' + parts[0] + '-from').datepicker('option', 'maxDate', date);
			}
		}
	});
	
	$('form .money, form .int').bind('blur', function() {
		$(this).parseNumber({format: '#,###', locale: 'gb'});
		$(this).formatNumber({format: '#,###', locale: 'gb'});
	});
	
	$('form input, form textarea').bind('focus', function() {
		$(this).parents('li').find('.hint').css('display', 'block')
			.end().find('.error').css('display', 'none');
	}).bind('blur', function() {
		$(this).parents('li').find('.hint').css('display', 'none');
	});
	
	$('form .multiset .add').bind('click', function() {
		var $lastSet = $('form .multiset .set:last');
		if ($lastSet.find('a.remove').length > 0) {
			$lastSet.clone().insertAfter($lastSet);
		} else {
			$lastSet.clone().append('<a href="#" class="remove">Remove</a>').insertAfter($lastSet);
		}
		return false;
	});
	$('form .multiset .remove').live('click', function() {
		$(this).parents('.set').remove();
		return false;
	});
	
	$('#nav .menu').hover(function() {
		$(this).addClass('hover').find('.sub').width($(this).width() - 2);
	}, function() {
		$(this).removeClass('hover');
	});
		
	$('.popup').bind('click', function() {
		var $popup = $('#' + $(this).attr('rel'));
		
		var submitButton = $popup.find('._submitButton').attr('rel');
		if (submitButton != ''){
			var buttons = {};
			buttons[submitButton] = function(event) {
				$(event.target).parent().addClass('submit');
				SU.Dialog.Generic.find('form').submit();
			};
			SU.Dialog.Generic.dialog('option', 'buttons', buttons);
		}
		
		SU.Dialog.Generic
		.dialog('option', 'width', $popup.find('._width').attr('rel'))
		.dialog('option', 'height', $popup.find('._height').attr('rel'))
		.dialog('option', 'title', $popup.find('._title').attr('rel'))
		.html($popup.html())
		.dialog('open');
		
		return false;
	});
	
	$('.scroll').bind('click', function() {
		$('html, body').animate({ scrollTop: $('#' + $(this).attr('rel')).offset().top - 20 }, { duration: 'slow', easing: 'swing'});
		if ($(this).hasClass('history')) {
			window.location.hash = $(this).attr('rel');
		}
		return false;
	});
	
	var $ajaxForm = $('form.ajaxForm');
	if ($ajaxForm.length > 0) {
		
		$ajaxForm.find('button[type="submit"]').removeAttr('disabled');
		
		$ajaxForm.find('button[type="submit"]').bind('click', function() {
			$ajaxForm.data('submitButton', $(this).attr('id'));
		});
		
		SU.Ajax.AjaxForm = function(event) {
			var $this = $(this);
			var $submitButton = $this.find('button[type="submit"]');
			if ($submitButton.length < 1) {
				$submitButton = $this.parents('.ui-dialog').find('button.submit');
			}
			$submitButton.button('option', 'disabled', true);
			if ($this.hasClass('ajaxLoader')) {
				var height = $this.height();
				$this.hide().after('<div id="ajaxLoader"></div>');
				$('#ajaxLoader').height(height);
			}
			var params = {};
			var cancel = false;
			var $firstError = '';
			$this.find('input[name], textarea, select').each(function() {
				var $each = $(this);
				if ($each.hasClass('required') && $each.val() == '') {
					cancel = true;
					$each.parents('li').find('.error').css('display', 'block')
						.find('.error-message').html('This field must be filled in');
					if (!$firstError) {
						$firstError = $each;
					}
				}
				if ($each.hasClass('money') || $each.hasClass('int')) {
					params[$each.attr('name')] = $each.parseNumber({format: '#,###', locale: 'gb'}, false).toString();
				} else if ($each.hasClass('checkinput')) {
					if (typeof params[$each.attr('name')] == 'undefined') {
						params[$each.attr('name')] = new Array();
					}
					if ($each.is(':checked')) {
						params[$each.attr('name')].push($each.val());
					}
				} else if ($each.hasClass('multisetinput')) {
					if (typeof params[$each.attr('name')] == 'undefined') {
						params[$each.attr('name')] = new Array();
					}
					params[$each.attr('name')].push($each.val());
				} else {
					params[$each.attr('name')] = $each.val();
				}
			});
			$this.find('input[type="radio"]:checked').each(function() {
				params[$(this).attr('name')] = $(this).val();
			});
			if ($ajaxForm.data('submitButton')) {
				params['submitButton'] = $ajaxForm.data('submitButton');
			}
			//console.log(params);
			if (cancel) {
				if ($firstError.hasClass('autocomplete-value')) {
					$firstError = $firstError.siblings('.autocomplete');
				}
				if ($this.hasClass('ajaxLoader')) {
					$this.show().next('#ajaxLoader').remove();
				}
				$submitButton.button('option', 'disabled', false).removeClass('ui-state-hover');
				$('html, body').animate({ scrollTop: $firstError.offset().top - 20 }, { duration: 'slow', easing: 'swing'});
				$firstError.focus();
				return false;
			}
			if ($this.find("input[name='persistence']").val() == 1) {
				delete(params.persistence);
				SU.Persistence.params = params;
				SU.Persistence.SetHash();
			}
			SU.Ajax.jsonRequest({
				url:		$this.attr('action'),
				data:		params,
				success:	function(response) {
					console.log(response);
					if ($this.hasClass('ajaxLoader')) {
						$this.show().next('#ajaxLoader').remove();
					}
					$submitButton.button('option', 'disabled', false).removeClass('ui-state-hover');
					
					if (response.redirect != undefined) {
						location.href = response.redirect;
					}
					if (response.replaceForm != undefined) {
						$this.replaceWith(response.replaceForm);
					}
					if (response.replaceElement != undefined) {
						$(response.replaceElement.element).html(response.replaceElement.replacement);
					}
					if (response.jumpToElement != undefined) {
						$('html, body').animate({ scrollTop: $(response.jumpToElement).offset().top - 20 }, { duration: 'slow', easing: 'swing'});
					}
					if (response.alterDialog != undefined) {
						if (response.alterDialog.dialogWidth != undefined) {
							SU.Dialog.Generic.dialog('option', 'width', response.alterDialog.dialogWidth);
						}
						if (response.alterDialog.dialogHeight != undefined) {
							SU.Dialog.Generic.dialog('option', 'height', response.alterDialog.dialogHeight);
						}
						if (response.alterDialog.dialogTitle != undefined) {
							SU.Dialog.Generic.dialog('option', 'title', response.alterDialog.dialogTitle);
						}
						if (response.alterDialog.okButton != undefined) {
							SU.Dialog.Generic.dialog('option', 'buttons', {
								'OK' : function() {
									SU.Dialog.Generic
									.dialog('close')
									.html('');
								}
							});
						}
						SU.Dialog.Generic.dialog('option', 'position', 'center');
					}
				},
				error:		function(response) {
					if ($this.hasClass('ajaxLoader')) {
						$this.show().next('#ajaxLoader').remove();
					}
					$submitButton.button('option', 'disabled', false).removeClass('ui-state-hover');
					//console.log(response);
					//console.log(response.responseText);
				}
			});
			return false;
		};
		
		$ajaxForm.bind('submit', SU.Ajax.AjaxForm);
		$ajaxForm.live('submit', SU.Ajax.AjaxForm);
	
		$('.pagination .changePage').live('click', function(){
			pageClicked = true;
			$ajaxForm.find('input[name="page"]').val($(this).attr('rel'));
			$ajaxForm.submit();
			pageClicked = false;
		});
		
		$ajaxForm.find('button[type="submit"]').bind('click', function(){
			$ajaxForm.find('input[name="page"]').val('1');
		});
	
		SU.Persistence.params = {}
		var count = 0;
		$ajaxForm.find('input[name], textarea, select').each(function() {
			var $each = $(this);
			var eachName = $each.attr('name');
			SU.Persistence.params[eachName] = SU.Persistence.url.fparam(eachName);
			count++;
			if (SU.Persistence.params[eachName] == undefined) {
				delete(SU.Persistence.params[eachName]);
				count--;
			} else {
				if ($each.hasClass('money') && SU.Persistence.params[eachName] == '0') {
				} else {
					$each.val(SU.Persistence.params[eachName]);
				}
			}
		});
		
		if (count > 0) {
			$ajaxForm.submit();
		}
		
		$ajaxForm.find('.form-option').bind('change', function(){
			var $this = $(this);
			$ajaxForm.find('li.togglable').each(function(){
				var $each = $(this);
				if ($each.find('.toggle-attribute').attr('rel') == $this.attr('rel')) {
					console.log($this.find(':checked').val());
					if ($each.find('.toggle-value').attr('rel') == $this.find(':checked').val()) {
						$each.removeClass('hidden');
					} else {
						$each.addClass('hidden');
					}
				}
			});
		});
	}
	
	///////////////////////////////////////////////////////////////////////
	// Ad - Generic
	///////////////////////////////////////////////////////////////////////
	
	var $adGeneric = $('#ad-letting, #ad-subletting, #ad-edit');
	if ($adGeneric.length > 0) {
		
		var $area = $adGeneric.find('#area-input');
		var areaPostcodes;
		
		$area
		.live('blur', function() {
			$adGeneric.find('#area-dropdown').css('display', 'none');
		})
		.autocomplete({
			source:		function(request, callback) {
				//console.log(request);
				SU.Ajax.jsonRequest({
						url:		'/ajax/ad/areaAutocomplete',
						data:		request,
						success:	function(response) {
							//console.log(response);
							areaPostcodes = response.postcodes;
							callback(response.areas);
						},
						error:		function(response) {
							//console.log(response.responseText);
							SU.Dialog.Open.Error('Error');
						}
				});
			},
			open:		function(event, ui) {
				$area.parents('li').find('.hint').css('display', 'none');
				$adGeneric.find('#area-dropdown').css('display', 'block');
			},
			focus:		function(event, ui) {
				$area.val(ui.item.label);
				return false;
			},
			select:		function(event, ui) {
				$adGeneric.find('#postcode option[value="' + areaPostcodes[ui.item.value] + '"]').attr('selected', 'selected');
				$adGeneric.find('#area').val(ui.item.value);
				ui.item.value = ui.item.label;
			}
		});
	}
	
	///////////////////////////////////////////////////////////////////////
	// Ad - Manage
	///////////////////////////////////////////////////////////////////////
		
	var $adManage = $('.ad-manage');
	if ($adManage.length > 0) {
		
		$adManage.find('.delete').bind('click', function() {
			var $this = $(this);
			SU.Dialog.Open.Confirm('Are you sure you want to delete this advert?',
				function() {
					var params = {
						id :	$this.attr('rel')
					}
					SU.Ajax.jsonRequest({
						url:		'/ajax/ad/deleteAdvert',
						data:		params,
						success:	function(response) {
							$this.parents('.item').remove();
							SU.Dialog.Open.Message('Advert Deleted', 'Your advert has been deleted successfully.');
						},
						error:		function(response) {
							//console.log(response);
							//console.log(response.responseText);
						}
					});
				},
				function() {},
				160
			);
			return false;
		});
		
	}
	
	var $sabbats = $('#home #sabbats');
	if ($sabbats.length > 0) {
		$sabbats.find('.sabbat.housesix .photo .inside').bind('dblclick', function() {
			var $parent = $(this).parent();
			$parent.css('background-image', 'url(/images/house-s7x.jpg)');
			setTimeout(function() {
				$parent.css('background-image', 'url(/images/house-six.jpg)');
			}, 3000);
		});
	}
	
	///////////////////////////////////////////////////////////////////////
	// Ad - View
	///////////////////////////////////////////////////////////////////////
	
	var $adView = $('#ad-view');
	if ($adView.length > 0) {
		
		$adView.find('.contact').bind('click', function() {
			SU.Dialog.Generic
			.dialog('option', 'width', 620)
			.dialog('option', 'height', 375)
			.dialog('option', 'title', 'Contact this person')
			.dialog('option', 'buttons', {
				/*'Send Message' : function() {
					SU.Dialog.Generic
					.dialog('close')
					.dialog('option', 'title', '')
					.html('');
				}*/
			})
			.html($adView.find('#contactForm').html())
			.dialog('open');
		});
		
	}
	
});
