
/****************************************************/
/*** attach validation							  ***/
/*** how to use:								  ***/
/*** add a class called 'required' to the element ***/
/****************************************************/
function attachValidation(form_id) {
	form_id.validate();
	

	form_id.find('input.required').each(function() {
		$("#email").rules('add', {
			required: true,
		    email: true
		});
	});	
	
	// input element
	form_id.find('input.required').each(function() {
		$(this).rules('add', {
			required: true,
		    messages: {
		       	required: '*required'
			}
		});
	});


	
	// select element
	form_id.find('select.required').each(function() {
		$(this).rules('add', {
			required: true,
		    messages: {
		       	required: '*required'
			}
		});
	});
}



/********************************/
/*** initialize tab 		  ***/
/*** for tabs in modal window ***/
/********************************/
function initializeTab(container) {
	var tabs = container ? container : '.tabs';
		
	$(tabs).each(function() {
		var nav = $('.nav', this),
			content = $('.tab-content', this),
			id = '';

		if(content.length > 1) {
			$('a', nav).click(function() {
				if(!$(this).is('.current')) {
					id = $(this).attr('href').substr($(this).attr('href').indexOf('#'));
							
					content.hide().filter(id).show();
					$('.current', nav).removeClass('current');
					$(this).addClass('current');
					
					// re-initialise jScrollPane
					var temp = content.filter(id).find('.scroll-pane');
					var api = temp.data('jsp');
					if (api) {
						api.reinitialise();
					}
					api = temp.find('.residence-box-ph').data('jsp');
					if (api) {
						api.reinitialise();
					}
				}		

				return false;
			});					
		} else {
			$('a:first', nav).addClass('current');
		}
				
		$('a:first', nav).click();
	});
}



/***************************************/
/*** initialize state drop down list ***/
/***************************************/
function initializeStateDropDownList() {
	$('#state').selectmenu({
		style:'dropdown', 
		width: '58px',
		menuWidth: '58px'
	});
}



/***************************/
/*** remove dialog window ***/
/***************************/
function removeDialogWindow(dialog_window_id) {
	$('.hide').remove();
	dialog_window_id.remove();
}


	
$(document).ready(function() {
	
	/*** attach jScrollPane ***/
	function attachJScrollPane() {
		
		// residence box placeholder
		$('.residence-box-ph').each(function() {
			$(this).jScrollPane({
				showArrows: true,
				autoReinitialise: true/*,
				autoReinitialiseDelay: 1000
				*/
			});
		});
		
		// items container
		$('.scroll-pane').each(function() {
			var temp = $(this).find('li.item').length;
			temp = 268 + 285 * (temp - 1);
			$(this).find('.items-container').css('width', temp + 'px');
			
			$(this).jScrollPane({
				showArrows: true,
				//autoReinitialise: true,
				//autoReinitialiseDelay: 1000,
				horizontalGutter: 26,
				horizontalDragMinWidth: 215,
				horizontalDragMaxWidth: 215
			});
		});
		
		
		$('.residence-box-ph').each(function() {
			var api = $(this).data('jsp');
			
			// re-initialise jScrollPane
			/*
			if (api) {
				//api.reinitialise();
				alert(api.getIsScrollableH());
			}
			*/
		});
		
	}
	/*
	function reInitializeJScrollPane() {
		$('.scroll-pane').each(function() {
			var pane = $(this);
			var api = pane.data('jsp');
			api.reinitialise();
		});
	}
	*/
	
	
	
	/********************/
	/***   REGISTER   ***/
	/********************/
	
	// my notebook > register
	$('#mn-register-button').live('click', function(e) {
		e.preventDefault();
		
		$('<div class="hide"></div>').appendTo('body').load('/my-notebook/load-register', function(data) {
			$('#my-notebook-register', this).dialog({
				autoOpen: false,
				dialogClass: 'dialog-window my-notebook-window',
				draggable: false,
				resizeable: false,
				modal: true,
				width: 880,
				closeText: 'Close',
				close: function(event, ui) {
					removeDialogWindow($('#my-notebook-register'));
				},
				create: function() {
					initializeTab($(this));
					initializeStateDropDownList();
				}
			});
			// open dialog
			$('#my-notebook-register').dialog('open');
			// attach validation (function definition is in my-notebook.js)
			// attachValidation($('#log-in-form'));
		});
	});
	
	// register button
	$('#register-button').live('click', function(e) {
		e.preventDefault();
		
		if($('#register-form').valid()) {
			var dataString = $('form#register-form').serialize();
				
			$.getJSON('/my-notebook/register',
				dataString,
				function(json_object) {
					if (json_object.status == 'success') {
						removeDialogWindow($('#my-notebook-register'));
						$('#mn-button').trigger('click');
						$('#mn-register-button').hide();
						$('#separator').hide();
						$('#mn-log-in-button').html('log out').attr('id', 'mn-log-out-button');
						
					} else if (json_object.status == 'email already used') {
						alert("Please use another email address");
					} else {
						alert("Passwords don't macth. Please try again");
					}
			});
		}
	});
	
	// already registered log in button
	$('#already-registered-log-in-button').live('click', function(e) {
		e.preventDefault();
		
		removeDialogWindow($('#my-notebook-register'));
		$('#mn-log-in-button').trigger('click');
	});
	
	
	
	/******************************/
	/***   MY NOTEBOOK / VIEW   ***/
	/******************************/
	
	// my notebook > view
	$('#mn-button').live('click', function(e) {
		e.preventDefault();
		
		// check if notebook session variable is set or not 
		$.getJSON('/my-notebook/is-notebook-session-var-set',
			function(json_object) {
				
				// notebook session variable is set
				if (json_object.isNotebookSessionVarSet == 'true') {
					
					// open view dialog window
					$('<div class="hide"></div>').appendTo('body').load('/my-notebook/load-view', function(data) {
						$('#my-notebook-view', this).dialog({
							autoOpen: false,
							dialogClass: 'dialog-window my-notebook-window',
							draggable: false,
							resizeable: false,
							modal: true,
							width: 880,
							closeText: 'Close',
							close: function(event, ui) {
								removeDialogWindow($('#my-notebook-view'));
							},
							create: function() {
								initializeTab($(this));
								initializeStateDropDownList();
							}
						});
						// open dialog
						$('#my-notebook-view').dialog('open');
						// attach jScrollPane
						attachJScrollPane();
					});
					
				} else {
					// open log in dialog window
					$('#mn-log-in-button').trigger('click');
				}
			}
		)
	});
	
	// account info > save button
	$('#save-button').live('click', function(e) {
		e.preventDefault();
		
		if($('#account-info-form').valid()) {
			var dataString = $('form#account-info-form').serialize() + '&email=' + $('#account-info-form input#email').val();
				
			$.getJSON('/my-notebook/save-account-info',
				dataString,
				function(json_object) {
					if (json_object.status == 'success') {
						$('h6.status').html('Account Info saved');
					} else if (json_object.status == 'password_not_match') {
						$('h6.status').html('Password not match');
					} else {
						$('h6.status').html('Account Info not saved');
					}
					setTimeout("$('h6.status').html('')", 3000);
			});
		}
	});
	
	// saved plans > remove community button
	$('#saved-plans .remove-community-button').live('click', function(e) {
		e.preventDefault();
		
		var _this = $(this),
			community_id = _this.next('#community-id').val(),
			dataString = 'community_id=' + community_id;
		$.getJSON('/my-notebook/remove-community',
			dataString,
			function(json_object) {
				if (json_object.status == 'success') {
					// update items container width
					if (_this.parents('.item').hasClass('last-item')) {
						_this.parents('.item').prev('.item').addClass('last-item');
					}
					_this.parents('.items-container').css('width', '-=285');
					
					// remove residence
					_this.parents('.item').find('.residence-box .remove-residence-button').each(function() {
						$(this).trigger('click');
					});
					
					// update num of saved communities
					var num_of_saved_communities_element = $('#saved-plans #num-of-saved-communities');
					num_of_saved_communities_element.html(num_of_saved_communities_element.html() - 1);
					
					var api = _this.parents('.scroll-pane').data('jsp');
					
					_this.parents('.item').remove();
					
					// re-initialise jScrollPane
					if (api) {
						api.scrollToX(0);
						api.reinitialise();
					}
					
					$('input[value="' + community_id + '"]').prev('.saved-community-button').removeClass('saved-community-button').addClass('add-community-button');
				}
		});
	});
	
	// saved plans > remove residence button
	$('#saved-plans .remove-residence-button').live('click', function(e) {
		e.preventDefault();
		
		var _this = $(this),
			residence_id = _this.next('#residence-id').val(),
			dataString = 'residence_id=' + residence_id;
		$.getJSON('/my-notebook/remove-residence',
			dataString,
			function(json_object) {
				if (json_object.status == 'success') {
					var residence_box_ph = _this.parents('.residence-box-ph');
					var api = residence_box_ph.data('jsp');
					
					_this.parents('.residence-box').remove();
					
					// re-initialise jScrollPane
					if (api) {
						api.reinitialise();
					}
					
					// update residence box background color
					residence_box_ph.find('.residence-box').each(function(index) {
						if(index % 2 == 0) {
				       		$(this).addClass('grey');
				     	} else {
				       		$(this).removeClass('grey');
				     	}
					});
					
					// update num of saved residences
					var num_of_saved_residences_element = $('#saved-plans #num-of-saved-residences');
					num_of_saved_residences_element.html(num_of_saved_residences_element.html() - 1);
					
					$('input[value="' + residence_id + '"]').prev('.saved-residence-button').removeClass('saved-residence-button').addClass('add-residence-button');
				}
		});
	});
	
	// recently viewed > remove community button
	$('#recently-viewed .remove-community-button').live('click', function(e) {
		e.preventDefault();
		
		var _this = $(this),
			dataString = 'community_id=' + $(this).next('#community-id').val();
		$.get('/my-notebook/delete-recent-community-session-variable',
			dataString,
			function() {
				// update items container width
				if (_this.parents('.item').hasClass('last-item')) {
					_this.parents('.item').prev('.item').addClass('last-item');
				}
				_this.parents('.items-container').css('width', '-=285');
					
				// remove residence
				_this.parents('.item').find('.residence-box .remove-residence-button').each(function() {
					$(this).trigger('click');
				});
					
				var api = _this.parents('.scroll-pane').data('jsp');
				
				_this.parents('.item').remove();
					
				// re-initialise jScrollPane
				if (api) {
					api.scrollToX(0);
					api.reinitialise();
				}
		});
	});
	
	// recently viewed > remove residence button
	$('#recently-viewed .remove-residence-button').live('click', function(e) {
		e.preventDefault();
		
		var _this = $(this),
			residence_id = _this.next('#residence-id').val();
		var dataString = 'residence_id=' + residence_id;
		$.get('/my-notebook/delete-recent-residence-session-variable',
			dataString,
			function() {
				var residence_box_ph = _this.parents('.residence-box-ph');
				var api = residence_box_ph.data('jsp');
					
				_this.parents('.residence-box').remove();
					
				// re-initialise jScrollPane
				if (api) {
					api.reinitialise();
				}
					
				// update residence box background color
				residence_box_ph.find('.residence-box').each(function(index) {
					if(index % 2 == 0) {
						$(this).addClass('grey');
				     } else {
				     	$(this).removeClass('grey');
				     }
				});
		});
	});
	
	
	
	/******************/
	/***   LOG IN   ***/
	/******************/

	// my notebook > log in
	$('#mn-log-in-button').live('click', function(e) {
		e.preventDefault();
		
		// load content
		$('<div class="hide"></div>').appendTo('body').load('/my-notebook/load-log-in', function(data) {
			$('#my-notebook-log-in', this).dialog({
				autoOpen: false,
				dialogClass: 'dialog-window my-notebook-window',
				draggable: false,
				resizeable: false,
				modal: true,
				width: 392,
				closeText: 'Close',
				close: function(event, ui) {
					removeDialogWindow($('#my-notebook-log-in'));
				},
				create: function() {
					initializeTab($(this));
				}
			});
			// open dialog
			$('#my-notebook-log-in').dialog('open');
			// attach validation (function definition is in my-notebook.js)
			// attachValidation($('#log-in-form'));
		});
	});
	
	// log in button
	$('#log-in-button').live('click', function(e) {
		e.preventDefault();
		
		// form is valid
		if($('#log-in-form').valid()) {
			var dataString = $('#log-in-form').serialize();
							
			$.getJSON('/my-notebook/log-in',
				dataString,
				function(json_object) {
					if (json_object.status == 'success') {
						removeDialogWindow($('#my-notebook-log-in'));
						$('#mn-button').trigger('click');
						$('#mn-register-button').hide();
						$('#separator').hide();
						$('#mn-log-in-button').html('log out').attr('id', 'mn-log-out-button');
						
						// change add to saved community button
						var saved_communities = json_object.saved_communities,
							length,
							community_id;
						length = saved_communities.length;
						for(var i = 0; i < length; i++) {
							community_id = saved_communities[i].community_id;
							$('input[value="' + community_id + '"]').prev('.add-community-button').removeClass('add-community-button').addClass('saved-community-button');
						}
						
						// change add to saved residence button
						var saved_residences = json_object.saved_residences,
							residence_id;
						length = saved_residences.length;
						for(var i = 0; i < length; i++) {
							residence_id = saved_residences[i].residence_id;
							$('input[value="' + residence_id + '"]').prev('.add-residence-button').removeClass('add-residence-button').addClass('saved-residence-button');
						}
						
					} else {
						alert("User account doesn't exist. Please try again");
					}
			});
		}
	});
	
	// forgot username or password button
	$('#forgot-username-or-password-button').live('click', function(e) {
		e.preventDefault();
		
		removeDialogWindow($('#my-notebook-log-in'));
		openForgotDialogWindow();
	});
	
	// need to register button
	$('#need-to-register-button').live('click', function(e) {
		e.preventDefault();
		
		removeDialogWindow($('#my-notebook-log-in'));
		$('#mn-register-button').trigger('click');
	});
	
	
	
	/*******************/
	/***   LOG OUT   ***/
	/*******************/
	
	// log out button
	$('#mn-log-out-button, #log-out-button').live('click', function(e) {
		e.preventDefault();
		
		$.getJSON('/my-notebook/log-out',
			function(json_object) {
				if (json_object.status == 'success') {
					location.href = window.location.pathname;
				}
			});
	});
	
	
	/******************/
	/***   FORGOT   ***/
	/******************/
	
	// my notebook > forgot
	function openForgotDialogWindow() {
		$('<div class="hide"></div>').appendTo('body').load('/my-notebook/load-forgot', function(data) {
			$('#my-notebook-forgot', this).dialog({
				autoOpen: false,
				dialogClass: 'dialog-window my-notebook-window',
				draggable: false,
				resizeable: false,
				modal: true,
				width: 392,
				closeText: 'Close',
				close: function(event, ui) {
					removeDialogWindow($('#my-notebook-forgot'));
				},
				create: function() {
					initializeTab($(this));
				}
			});
			$('#my-notebook-forgot').dialog('open');
		});
	}
	
	// forgot button
	$('#forgot-button').live('click', function(e) {
		e.preventDefault();
		
		// form is valid
		if($('#forgot-form').valid()) {
			var dataString = $('#forgot-form').serialize();
							
			$.getJSON('/my-notebook/forgot',
				dataString,
				function(json_object) {
					if (json_object.status == "success") {
						
						// show send password confirmation
						$('#forgot-form').hide();
						$('.copy-under-header').html('Your new password is sent to your email.');
						//removeDialogWindow($('#my-notebook-forgot'));
						
					} else {
						alert("User account doesn't exist. Please try again");
					}
			});
		}
	});
	
	
	
	/****************************************************/
	/***   MY NOTEBOOK > RECENTLY VIEWED: COMMUNITY   ***/
	/****************************************************/
	
	$('.tip-content a.button-arrow.community, .tip-content .tip-description h2 a, .offert a.thumbnail, .offert .offert-title a, .offert a.button-arrow.community, .offert a.button-arrow.floorplans').live('click', function(e) {
		//e.preventDefault();
		
		// set recent community session variable
		var dataString;
		if ($(this).parents('.tip-content').find('input#community-id').val()) {
			dataString = 'community_id=' + $(this).parents('.tip-content').find('input#community-id').val();
		} else {
			dataString = 'community_id=' + $(this).parents('.offert').find('input#community-id').val();
		}
		
		$.get('/my-notebook/set-recent-community-session-variable',
			dataString,
			function() {
		});
	});
	
	
	
	/****************************************************/
	/***   MY NOTEBOOK > RECENTLY VIEWED: RESIDENCE   ***/
	/****************************************************/
	
	$('.floorplan-item a.button-arrow.floorplans').live('click', function(e) {
		//e.preventDefault();
		
		// set recent community session variable
		var dataString = 'community_id=' + $('input#community-id').val();
		$.get('/my-notebook/set-recent-community-session-variable',
			dataString,
			function() {
		});
		
		// set recent residence session variable
		var dataString = 'residence_id=' + $(this).parents('.floorplan-item').find('input#residence-id').val();
		$.get('/my-notebook/set-recent-residence-session-variable',
			dataString,
			function() {
		});
	});
	
	
	
	/***********************************************************/
	/***   MY NOTEBOOK > SAVED ITEMS: ADD/REMOVE COMMUNITY   ***/
	/***********************************************************/

	// add community button
	$('.add-community-button').live('click', function(e) {
		e.preventDefault();
		
		var _this = $(this),
			dataString = 'community_id=' + _this.next('#community-id').val();
		
		// check if notebook session variable is set or not
		$.getJSON('/my-notebook/is-notebook-session-var-set',
			function(json_object) {
				
				// notebook session variable is set
				if (json_object.isNotebookSessionVarSet == 'true') {
					
					// add community to my notebook
					$.getJSON('/my-notebook/add-community',
						dataString,
						function(json_object) {
							if (json_object.status == 'success') {
								_this.removeClass('add-community-button').addClass('saved-community-button');
							}
					});
				}
				// notebook session variable isn't set
				else {
					
					// set temporary community session variable
					$.get('/my-notebook/set-temporary-community-session-variable',
						dataString,
						function() {
							_this.removeClass('add-community-button').addClass('saved-community-button');
					});
				}
		});
	});
	
	// saved community button
	$('.saved-community-button').live('click', function(e) {
		e.preventDefault();
		
		var _this = $(this),
			dataString = 'community_id=' + _this.next('#community-id').val();
		
		// check if notebook session variable is set or not 
		$.getJSON('/my-notebook/is-notebook-session-var-set',
			function(json_object) {
				
				// notebook session variable is set
				if (json_object.isNotebookSessionVarSet == 'true') {
					
					// remove community from my notebook
					$.getJSON('/my-notebook/remove-community',
						dataString,
						function(json_object) {
							if (json_object.status == 'success') {
								_this.removeClass('saved-community-button').addClass('add-community-button');
							}
					});
					
					// remove residences belongs to this community
					$('.saved-residence-button').each(function() {
						$(this).trigger('click');
					});
				}
				// notebook session variable isn't set
				else {
					
					// delete temporary community session variable
					$.get('/my-notebook/delete-temporary-community-session-variable',
						dataString,
						function() {
							_this.removeClass('saved-community-button').addClass('add-community-button');
					});
					
					// delete residences belongs to this community
					$('.saved-residence-button').each(function() {
						$(this).trigger('click');
					});
				}
		});
	});
	
	
	
	/***********************************************************/
	/***   MY NOTEBOOK > SAVED ITEMS: ADD/REMOVE RESIDENCE   ***/
	/***********************************************************/
	
	// add residence button
	$('.add-residence-button').live('click', function(e) {
		e.preventDefault();
		
		var _this = $(this),
			dataString = 'residence_id=' + $(this).next('input#residence-id').val();
		
		// check if notebook session variable is set or not 
		$.getJSON('/my-notebook/is-notebook-session-var-set',
			function(json_object) {
				
				// notebook session variable is set
				if (json_object.isNotebookSessionVarSet == 'true') {
					$('.add-community-button').trigger('click');
					
					// add residence to my notebook
					$.getJSON('/my-notebook/add-residence',
						dataString,
						function(json_object) {
							if (json_object.status == 'success') {
								_this.removeClass('add-residence-button').addClass('saved-residence-button');
							}
						});
				}
				// notebook session variable isn't set
				else {
					$('.add-community-button').trigger('click');
					
					// set temporary residence session variable
					$.get('/my-notebook/set-temporary-residence-session-variable',
						dataString,
						function() {
							_this.removeClass('add-residence-button').addClass('saved-residence-button');
					});
				}
		});
	});
	
	// saved residence button
	$('.saved-residence-button').live('click', function(e) {
		e.preventDefault();
		
		var _this = $(this),
			dataString = 'residence_id=' + _this.next('input#residence-id').val();
		
		// check if notebook session variable is set or not 
		$.getJSON('/my-notebook/is-notebook-session-var-set',
			function(json_object) {
				
				// notebook session variable is set
				if (json_object.isNotebookSessionVarSet == 'true') {
					
					// remove residence from my notebook
					$.getJSON('/my-notebook/remove-residence',
						dataString,
						function(json_object) {
							if (json_object.status == 'success') {
								_this.removeClass('saved-residence-button').addClass('add-residence-button');
							}
					});
				}
				// notebook session variable isn't set
				else {
					
					// delete temporary residence session variable
					$.get('/my-notebook/delete-temporary-residence-session-variable',
						dataString,
						function() {
							_this.removeClass('saved-residence-button').addClass('add-residence-button');
					});
				}
		});
	});

});

