/**
 * @author	Jonathan Cochran <jono.cochran@gmail.com>
 * --------------------------------------------------------- */
$(document).ready(function() {
	var origEmail = $('#input-email').val();
	
	/**
	 * MESSAGES
	 * --------------------------------------------------------- */
	$objMessage = $('#message');
	if ( $objMessage.length > 0 )
	{
		$objMessage.fadeTo(3500, 1).fadeTo(2000, 0, function() { $(this).remove() } );
	}
	
	/**
	 * CORNER MESSAGES
	 * --------------------------------------------------------- */
	$objCorMsg = $('#cornerMsg');
	if ( $objCorMsg.length > 0 )
	{
		$(this).meow({
			message:	$objCorMsg.val(),
		});
	}
	
	/**
	 * 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>');
	}

	/**
	 * DASHBOARD
	 * --------------------------------------------------------- */
	var $objTabs = $('#dashboard');
	if ( $objTabs.length > 0 )
	{

		// store client / template id's for next step
		var clientId = 0;
		var templateId = 0;
				
		var createQuoteRunning = false;
		//Create quote...
		$('.new-quote').click(function() {
			
			$('#overview-create-client').hide();
			$('#overview-create-quote').show();
						
			// 	prevent multiple iterations of this function from running
			//  when 'create quote' button pressed
			if (createQuoteRunning) return false;
			else createQuoteRunning = true;
			
			// save client id on select change
			$('#next-step-clients').change(function() {
				clientId = $(this).val();
			});
			
			// save template id on select change
			$('#next-step-templates').change(function() {
				templateId = $(this).val();
			});						
			
			//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;
				}
				
				/*
				if ($('#next-step-templates').val() == '0')
				{
					alert('You must select a template first.');
					return false;					
				}
				*/
				
				var uri = hostname +'quote/create/'+ clientId + '/' + templateId;
				$(this).attr('href', uri);
				//alert(uri);
				//return false;
			});
			
			//Close teal boxes
			$('.close-teal-box').click(function() {
				$(this).parent('div').parent('div').hide();
			})
			
			//Add new client
			$('.add-new-client').click(function() {
				// clear input fields
				$('#input-client-company').val('');
				$('#input-client-first-name').val('');
				$('#input-client-last-name').val('');
				$('#input-client-email').val('');
				// additional...
				$('#input-address1').val('');
				$('#input-address2').val('');
				$('#input-city').val('');
				$('#input-state').val('');
				$('#input-country').val('');
				$('#input-zip').val('');
				$('#input-url').val('');
				$('#input-phone').val('');
				$('#input-fax').val('');
				$('#input-person-phone').val('');
				$('#input-person-mobile').val('');
				
				// ensure normal beginning state for additional input field
				$('.add-client-more').hide();
				$('.toggle-client-more').css('background-image', 'url('+ hostname +'images/arrow-down.png)').html('more fields');
				
				$('#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(e) {
				
				// check fields
				if ( $.trim($('#input-client-first-name').val()) == "" || $.trim($('#input-client-last-name').val()) == "" || $.trim($('#input-client-email').val()) == "" )
				{
					alert('First & last name, email required');
					return false;
				}
				
				if ( !isValidEmail($.trim($('#input-client-email').val()) ) )
				{
					alert('Please provide a valid client email address');
					return false;
				}
				
				if ( $.trim($('#input-client-company').val()) == "" )
				{
					$('#input-client-company').val( $.trim($('#input-client-first-name').val()) + ' ' + $.trim($('#input-client-last-name').val()))
				}
				
				//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/create/'+ 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, .client-save').click(function(e) {
			if ( $.trim($('#input-person-first-name').val()) == "" || $.trim($('#input-person-last-name').val()) == "" || $.trim($('#input-person-email').val()) == "" )
			{
				alert('First & Last name, and Email Required');
				return false;
			}
			
			if ( !isValidEmail($.trim($('#input-person-email').val()) ) )
			{
				alert('Please provide a valid client email address');
				return false;
			}
			
			if ( $.trim($('#input-company-name').val()) == '')
			{
				$('#input-company-name').val( $.trim($('#input-person-first-name').val()) + ' ' + $.trim($('#input-person-last-name').val()))
			}
			
			if ( $(this).hasClass('client-add'))
				ajaxPostClient('add_client');
			else 
				ajaxPostClient('save_client');
				
			// Prevent href following
			e.preventDefault();
		});

		//Ajax
		function ajaxPostClient(action)
		{
			$.post(
				hostname +'user/'+ action,
				{
					client_id		: $('#input-client-id').val(),
					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 ( $.trim($('#personal-full-name').val()) == "" || $.trim($('#client-first-name').val()) == "" || $.trim($('#client-last-name').val()) == "" || $.trim($('#client-email').val()) == "" )
			{
				alert('Bold fields are all required');
				return false;
			}			
			
			if ( !isValidEmail($.trim($('#client-email').val()) ) )
			{
				alert('Please provide a valid client email address');
				return false;
			}
			
			// if nothing is entered for client company name, make it main contact's name
			if ( $.trim($('#client-company-name').val()) == '')
			{
				$('#client-company-name').val($.trim($('#client-first-name').val()) + ' ' + $.trim($('#client-last-name').val()) )
			}
			// 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 +"user/";
				}
			);
			
		});
	}
	
	
	/**
	 * SETTINGS / PROFILE PAGE
	 * --------------------------------------------------------- */
	if ( $('.settings-profile').length > 0 )
	{
		// Ajax save 
		$('.settings-save').click(function() {
			
			// submit form if it isn't the company settings section (reqs validation)
			if ( !$('#input-password').length > 0) 
			{
				$('.settings-form').trigger('submit');
				return true;
			}
			var strPassword = $('#input-password').val();
			var strPassword2 = $('#input-password-confirm').val();
			var strEmail = $('#input-email').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;
				}
			}
			// added by Randy
			//  validate email and
			//  remind customers to use their new login if they change email			
			if (! isValidEmail(strEmail)) 
			{
				alert('There seems to be an error in your email address, please try again');
				return false;
			}
			if (origEmail != strEmail) alert ('Reminder: changing your email address changes your login name. Next time you login, remember to use ' + strEmail + '.');
			
			$('.settings-form').trigger('submit');
			
		});
	}
	
	/**
	 * Take the users to the upgrade form
	 */	
	if ( $('#settings-plans').length > 0 )
	{
		$('#settings-plans tr').click(function() {
			var link = $(this).find('a').attr('href');
			if ( link != undefined )window.location.href =  link;
		});
	}
	
	// added by Randy
	// a slightly more robust email validater (still not great)
	function isValidEmail(str) 
	{
		str =$.trim(str);
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		return (reg.test(str));
	}
/*	
	function isValidEmail(str) {
	   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	}
*/	

	
});

