/**
 * @author	Jonathan Cochran <jono.cochran@gmail.com>
 *			COPYRIGHT (c) 2009
 * --------------------------------------------------------- */

$(document).ready(function() {
	
	/**
	 * MESSAGES
	 * --------------------------------------------------------- */
	$objMessage = $('#message');
	if ( $objMessage.length > 0 )
	{
		$objMessage.fadeTo(3500, 1).fadeTo(2000, 0, function() { $(this).remove() } );
	}
	
	/**
	 * SIDEBAR
	 * --------------------------------------------------------- */
	$objSidebarQuote = $('.sidebar-quote');
	if ( $objSidebarQuote.length > 0 )
	{
		$objSidebarQuote.after('<div class="sidebar-quote-tip-right"><img src="'+ hostname +'images/sidebar-info-btm-right.gif" /></div>');
	}

	/**
	 * USER OVERVIEW PAGE (DASHBOARD)
	 * --------------------------------------------------------- */
	var $objTabs = $('#dashboard');
	if ( $objTabs.length > 0 )
	{
		//Create quote...
		$('.new-quote').click(function() {
			$('#overview-create-quote').show();
			
			//Check if the client is selected...
			$('.next-step:first').click(function() {
				if ($('#next-step-clients').val() == '0')
				{
					alert('You must select a client first');
					return false;
				}
			});
			
			//Close teal boxes
			$('.close-teal-box').click(function() {
				$(this).parent('div').parent('div').hide();
			})
			
			//Append user id to uri
			$('#next-step-clients').change(function() {
				var uri = hostname +'quote/'+ $(this).val();
				$('.next-step').attr('href', uri);
			});	
			
			//Add new client
			$('.add-new-client').click(function() {
				$('#overview-create-quote').hide();				
				$('#overview-create-client').show();				
				
			});
			
			//Choose existing client
			$('.choose-existing-client').click(function() {			
				$('#overview-create-client').hide();
				$('#overview-create-quote').show();	
			});
			
			//Toggle client fields
			$('.toggle-client-more').click(function() {
				$('.add-client-more').toggle();
				if ( $('.add-client-more').is(':visible') )
				{					
					$(this).css('background-image', 'url('+ hostname +'images/arrow-up.png)').html('less fields');
				}
				else
				{
					$(this).css('background-image', 'url('+ hostname +'images/arrow-down.png)').html('more fields');
				}
			});
			
			//Ajax add client
			$('.add-client').click(function() {
				
				// check fields
				if ( $('#input-client-company').val() == "" || $('#input-client-first-name').val() == "" || $('#input-client-last-name').val() == "" || $('#input-client-email').val() == "" )
				{
					alert('Company, first & last name, email required');
					return false;
				}
				
				//ajax call
				$.post(
					hostname +'user/add_client',
					{
						// required...
						company_name	: $('#input-client-company').val(),
						first_name		: $('#input-client-first-name').val(),
						last_name		: $('#input-client-last-name').val(),
						email			: $('#input-client-email').val(),
						// additional...
						address1 		: $('#input-address1').val(),
						address2 		: $('#input-address2').val(),
						city 			: $('#input-city').val(),
						state 			: $('#input-state').val(),
						country			: $('#input-country').val(),
						zip 			: $('#input-zip').val(),
						url 			: $('#input-url').val(),
						phone 			: $('#input-phone').val(),
						fax 			: $('#input-fax').val(),
						personal_phone	: $('#input-person-phone').val(),
						mobile			: $('#input-person-mobile').val()
					},
					function(data)
					{
						if (data === 0)
						{
							alert('All fields required');
							return false;
						}						
						else
						{
							location.href = hostname +'quote/'+ data;
						}
					}					
				);
			});
				
		});
		
		// Check if the client has 0 quotes, trigger new quote inline prompt..
		if ( $('#no-quotes').length > 0 )
		{
			$('.new-quote').trigger('click');
		}
		
		//Sortable tables
		$.tablesorter.addParser({
		        // set a unique id
		        id: 'custom-date',
		        is: function(s) {
		                // return false so this parser is not auto detected
		                return false;
		        },
		        format: function(s) {
		            // split
		            var a = s.split(' ');
		            // get month num
		            a[0] = this.getMonth(a[0]);
		            // glue and return a new date
					var newDate = new Date(a.join("/")).getTime();
		            return newDate;
		        },
		        getMonth: function(s) {
		            var m =	['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
		            var l = m.length;
		            for(var i=0; i < l; i++) {
		                if(m[i] == s.toLowerCase()) {
		                    return (i+1);
		                }
		            }
		        },
		        // set type, either numeric or text
		        type: 'numeric'
		}); 
		$('table.user-table').each(function() {
			$(this).tablesorter( { sortList : [[0,1]], dateFormat: 'mm/dd/yyy', headers: {0: {sorter: "custom-date"}} });
		});
		$('table.user-table tr').click(function() {
			//var id = $('span.meta-data', $(this)).attr('id');
			var id = $(this).attr('id');
			location.href = hostname +'quote/view/'+ id;
		});
		
		//Numeric format
		$('span.total').formatCurrency({ symbol : currency });
	}
	
	/**
	 * CLIENTS PAGE
	 * --------------------------------------------------------- */
	if ( $('#clients').length > 0 )
	{
		//Table sorter...
		$('table').tablesorter({ sortList : [[0,1]] });
		$('table tr').click(function() {
			var id = $('span', $(this)).attr('id');
			location.href = hostname +'user/clients/'+ id;
		});
		
		//Search clients...
		var $objSearch = $('input[name="search-clients"]');
		$objSearch.click(function() {
			if ( $objSearch.val() == "Search Clients" )
			{
				$objSearch.val('');
			}
		});		
		$objSearch.autocomplete(hostname +'index.php?c=user&m=search_clients', { minChars : 2 } ).result(function(event, item) {
			var id = item[1];
			location.href = hostname +'user/clients/'+ id;
		});
		
		
		//Autocomplete Locations...
		$('input[name="input-city"]').autocomplete(cities);
		$('input[name="input-state"]').autocomplete(states);
		$('input[name="input-country"]').autocomplete(countries);

		//Ajax add client //$('#input-company-name').val() == "" ||
		$('.client-add').click(function() {
			if ( $('#input-person-first-name').val() == "" || $('#input-person-last-name').val() == "" || $('#input-person-email').val() == "" )
			{
				alert('First & Last name, Email Required');
				return false;
			}
			ajaxPostClient('add_client');
		});
		
		//Ajax save client... //$('#input-company-name').val() == "" ||
		$('.client-save').click(function() {
			if ( $('#input-person-first-name').val() == "" || $('#input-person-last-name').val() == "" || $('#input-person-email').val() == "" )
			{
				alert('Company name, First & Last name, Email Required');
				return false;
			}
			ajaxPostClient('save_client/'+ $('#input-client-id').val());
		});
		
		//Ajax
		function ajaxPostClient(action)
		{
			$.post(
				hostname +'user/'+ action,
				{
					company_name 	: $('#input-company-name').val(),
					address1 		: $('#input-address1').val(),
					address2 		: $('#input-address2').val(),
					city 			: $('#input-city').val(),
					state 			: $('#input-state').val(),
					country			: $('#input-country').val(),
					zip 			: $('#input-zip').val(),
					url 			: $('#input-url').val(),
					phone 			: $('#input-phone').val(),
					fax 			: $('#input-fax').val(),
					first_name		: $('#input-person-first-name').val(),
					last_name		: $('#input-person-last-name').val(),
					email			: $('#input-person-email').val(),
					personal_phone	: $('#input-person-phone').val(),
					mobile			: $('#input-person-mobile').val()
				},
				function(data) {
					if ( !isNaN(data) )
					{
						location.href = hostname +'user/clients/'+ data +'/success';
					}
					else
					{
						alert('Something went wrong, please refresh the page');
					}
				}
			);
		}
		
		// Delete client
		$('.remove-client').click(function() {
			if ( confirm('Deleting a client will remove any associated quotes. Do you wish to continue?'))
			{
				return true;
			}
			return false;
		});
		
		/**
		 * Removed for now.. 
		 * Used to add multiple people per client
		 */
		//Add person...
		$('.client-person-add').click(function() {
			if ( parseInt( $('.client-person:last').length) > 0 )
			{
				var $objPerson = $('.client-person:last');
				var $objClone = $objPerson.clone(true);	
				$('input', $objClone).val(''); //empty form values
				
				//add remove person button
				if ( $('.client-person-remove', $objClone).length  < 1 ) 
				{ 
					$('.form-item', $objClone).append('<div class="clearfix"><a href="javascript" class="client-person-remove">Remove Person</a></div>');
				}	
				
				//initialize ajax remove..
				initRemovePerson();
				
				//clones the last row...
				$objClone.insertAfter( $objPerson );
			} 
			return false;
		});
		
		//Remove person
		function initRemovePerson()
		{
			$('.client-person-remove').click(function() {
				
				//var iPersonId = $(this).parent('div');
				
				$.post(
					hostname +'user/remove_person',
					{ 
						id : iPersonId
					},
					function(data)
					{
					
					}
				);
			});
		}

	}
	
	/**
	 * WELCOME PAGE
	 * --------------------------------------------------------- */
	if ( $('#user-welcome').length > 0 )
	{
		$('.user-welcome-submit a').click(function() {
			
			// simple validation...
			if ( $('#personal-company-name').val() == "" || $('#personal-full-name').val() == "" || $('#client-first-name').val() == "" || $('#client-last-name').val() == "" || $('#client-email').val() == "" )
			{
				alert('Bold fields are all required');
				return false;
			}			
			if ( !isValidEmail($('#client-email').val()))
			{
				alert('Please provide a valid client email address');
				return false;
			}
			
			// ajax save personal info
			$.post(
				hostname +'user/save_settings',
				{
					// required...
					company_name	: $('#personal-company-name').val(),
					full_name		: $('#personal-full-name').val(),
					phone			: $('#personal-phone').val(),
					website			: $('#personal-website').val()
				},
				function(data)
				{
					if (data != 1)
					{
						// alert(data);
						// return false;
					}
				}
			);
			
			// ajax add client
			$.post(
				hostname +'user/add_client',
				{
					// required...
					company_name	: $('#client-company-name').val(),
					first_name		: $('#client-first-name').val(),
					last_name		: $('#client-last-name').val(),
					email			: $('#client-email').val(),
					address1		: '',
					address2		: '',
					city			: '',
					state			: '',
					country			: '',
					zip				: '',
					url				: '',	
					phone			: '',
					fax				: '',
					personal_phone	: '',
					mobile			: ''
				},
				function(data)
				{
					window.location = hostname +"quote/"+ data;
				}
			);
			
		});
	}
	
	
	/**
	 * SETTINGS / PROFILE PAGE
	 * --------------------------------------------------------- */
	if ( $('#user-home').length > 0 )
	{
		
		// Ajax save 
		$('.settings-save').click(function() {
			
			var strPassword = $('#input-password').val();
			var strPassword2 = $('#input-password-confirm').val();
			
			// New password is set
			if (strPassword != "" || strPassword2 != "")
			{
				// One of the passwords was left out...
				if (strPassword == "" || strPassword2 == "")
				{
					alert('Please fill in both password fields');
					return false;
				}
				
				// See if they match
				if (strPassword != strPassword2)
				{
					alert('Passwords do not match, please try again');
					return false;
				}
			}
			
			$('.settings-form').trigger('submit');
			
		});
	}
	
	function isValidEmail(str) {
	   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	}
});
