// define your app as a jquery extension

$.ca = {

	"debug" : false,

	// holds the XML for your app, once loaded
	"xml" : false,
	
	// callback to execute once x-objects has initialized
	"after_init" : function( xml ) {
	
		// save xml for local use
		$.ca.xml = xml;
					
		// clear notices
		$( '.notice').html('');
		// if present, initialize event log manager
		if ( $('div.event-log').length)
			$.xevents.show($('div.event-log'));


	
	},

	"init" : function( context ) {

		// when document is ready...
		$( document ).ready( function() {
		
			if ( $( '.area-suggestions').length ) {
	
				var window_width = $(window).width();   // returns width of browser viewport
				var doc_width = $('#wrap').width();   // returns width of doc
				var offset = 30;
			
				var suggest_width = (.175 * window_width) + offset; 
				
				console.log('Window: ' + window_width + ', Doc: ' + doc_width + ', Suggest: ' + suggest_width );
			
				//now set the size for suggest area through css
				$( '.area-suggestions').css('width', suggest_width);
				
			}
			// show admin records
			if ( $('div.service-manage-list').length ) {
				$('div.AdminListRecord').addClass('view-mode').show();
			}
			// config ajax editor
			if ( $('div.ajax-editor').length)
				$.xo.ajax_editor.configure();
			
			$.ajaxSetup( {
			
				cache : false
			});
		
			$(document).ajaxStart( function() {
			
				$('.ajax').show();
				$('.notice').removeClass('success error').html('please wait...');
				
				// disable all controls
				$( 'button , input, select, textarea').attr('disabled','disabled');
				
			});
			
			$(document).ajaxStop( function() {
			
				$('.ajax').hide();
				
				// enable all controls
				$( 'button , input, select, textarea').removeAttr('disabled');

			});
			
			// initialize x-objects
			$.xo.init( 'caravan' , $.ca.after_init, context );
			
		});		
		
	},
	
	// handle mailing list
	"ml" : {
	
		"click_input" : function( e , elem ) {
		
			$( elem ).val('').addClass('clicked').removeClass('error');
		},
		
		// after the api call 
		"after_create" : function( result) {
		
			// hide form
			$( 'form.ml-form').addClass('hidden');
			// show result
			$( 'span.ml-result').html("You've been subscribed!");
			$( 'div.ml-result').removeClass('hidden');
		
		},
		
		// submit handler
		"submit" : function( e, elem) {
		
			// use api to create subscription
			$.xo.api.call( 'business/mailing_list/new', $.ca.ml.after_create , 
				'args=<create><email>' + $( 'input#ml_email').val() + '</email><industry>' + $( 'input#industry').val() +
				'</industry></create>');
			
		}
	
	},
	
	// areas submodule
	"areas" : {
	
		// select an area
		"select" : function( id, text ) {
		
			$( '#area').val( text.charAt(0).toUpperCase() + text.slice(1) );
		
		}
	
	},
	
	// user interface
	"ui" : {
	
		// hide/show past listings
		"hide_past" : function( e, elem ){
		
			if ( $( elem ).is(':checked') ) 
				$( '.past_listing').fadeOut('fast');
			else
				$( '.past_listing').fadeIn('fast');
		
		},
	
		// toggle between view and edit mode
		"toggle_view_edit" : function( e, elem ) {
		
			// can't edit past listings
			if ( $( elem ).hasClass('past_listing') ) {
				$( '.notice').addClass('error').html("can't edit past listings");
				return false;
			}
		
			// get listing id
			var matches = /listingid\-([0-9]+)/.exec( $( elem ).attr('class') );
			var listingid = '.' + matches[0];
			
			//console.log( listingid );
			
		
			if ( $( elem ).hasClass('view') ) {
			
				$( elem).removeClass( 'view').addClass('edit');
				
				// change all children
				$(listingid + ' span.view-mode'  ).removeClass( 'view-mode' ).addClass( 'edit-mode' );
				$( listingid + ' input.view-mode'  ).removeClass( 'view-mode').addClass( 'edit-mode' );
				$( listingid + ' select.view-mode').removeClass('view-mode').addClass('edit-mode');
				$( listingid + ' textarea.view-mode').removeClass('view-mode').addClass('edit-mode');
				$( listingid + ' div.save-controls').removeClass('view-mode').addClass('edit-mode');
				$( listingid + ' label.listing-edit-label').removeClass('view-mode').addClass('edit-mode');
				
				
				// set revert
				$.ca.listing.set_reverts_for( matches[1] );
				
				
			} 
		}
		
	
	},
	
	// listing module
	"listing" : {
	
		// update the view fields
		"update_view_fields" : function( id ) {
		
			// set event date
			$( 'div.listingid-' + id + ' span.event-date').html( 
				$( 'div.listingid-' + id + ' select.event-date option:selected').text().substring( 5) );
				
			// event address
			$( 'div.listingid-' + id + ' span.address').html( 
				$( 'div.listingid-' + id + ' input.address').val() );

			// start time
			$( 'div.listingid-' + id + ' span.start-time').html( 
				$( 'div.listingid-' + id + ' select.start-time option:selected').text() + ' - ' );
				
			// end time
			$( 'div.listingid-' + id + ' span.end-time').html( 
				$( 'div.listingid-' + id + ' select.end-time option:selected').text()  );
				
			
				
		
		},
	
		// set view/edit mode
		"set_view_edit" : function( listingid, which ) {
					
			var alternate = which == 'view' ? 'edit' : 'view';
			
			$( 'div.listingid-' + listingid ).removeClass( alternate ).addClass( which );
				
			$( 'div.listingid-' + listingid + ' span.' + alternate + '-mode'  ).removeClass( alternate + '-mode' ).addClass( which + '-mode' );
			$( 'div.listingid-' + listingid + ' input.' + alternate + '-mode'  ).removeClass( alternate + '-mode').addClass( which + '-mode' );
			$( 'div.listingid-' + listingid + ' select.' + alternate + '-mode').removeClass(alternate + '-mode').addClass(which + '-mode');
			$( 'div.listingid-' + listingid + ' textarea.' + alternate + '-mode').removeClass(alternate + '-mode').addClass(which + '-mode');
			
			$( 'div.listingid-' + listingid + ' div.save-controls').removeClass(alternate + '-mode').addClass(which + '-mode');
			$( 'div.listingid-' + listingid + ' label.listing-edit-label').removeClass(alternate + '-mode').addClass(which + '-mode');
			
		
		},
	
		// set reverts for a listing
		"set_reverts_for" : function( id ) {
			
			// empty reverts
			$( 'div.listingid-' + id + ' div.revert-changes').empty();
			
			// for each applicable element select set a revert
			$( 'div.listingid-' + id + ' select').each( function() {
					
				$( 'div.listingid-' + id + ' div.revert-changes').append(
						'<div id="' + $(this ).attr('id') + '">' + $( 'div.listingid-' + id + ' select#' + $(this).attr('id') + ' option:selected').val() + '</div>'
					);
					
				});
				
			// also for each applicable input
			$( 'div.listingid-' + id + ' input').each( function() {
					
				$( 'div.listingid-' + id + ' div.revert-changes').append(
						'<div id="' + $(this ).attr('id') + '">' + $( 'div.listingid-' + id + ' input#' + $(this).attr('id') ).val() + '</div>'
					);
					
				});
				
			// also for each applicable textarea
			$( 'div.listingid-' + id + ' textarea').each( function() {
					
				$( 'div.listingid-' + id + ' div.revert-changes').append(
						'<div id="' + $(this ).attr('id') + '">' + $( 'div.listingid-' + id + ' textarea#' + $(this).attr('id') ).html() + '</div>'
					);
					
				});
				
			return true;
		
		},
	
		"queue_change" : function( e, elem ) {
		
			// get the id
			var id = $( elem ).attr('id');
			
			if  ( $.ca.debug )
				console.log( id);
			
			// get type of element
			var type = $( elem ).get(0).nodeName.toLowerCase();
			
			if  ($.ca.debug )
				console.log( type);
			
			// get listingid
			var matches = /listingid-([0-9]+)/.exec( $( elem ).attr('class') );
			if  ($.ca.debug )
				console.log( matches );
			var listingid = matches[1];

			
			
			// get the value based on the type of node
			var val = '';
			switch ( type ) {
			
				case 'select':
					val = $( '#' + id + ' option:selected').val();
			
				break;
				case 'input':
					val = $(  '#' + id  ).val();
			
				break;
				case 'textarea':
				
					val = $(   '#' + id  ).val();
			
				break;
				
				
			}
			
			if  ( $.ca.debug )
				console.log( val );
			
			// strip off listing id from id
			var matches = /l[0-9]+_([a-z|A-Z|0-9|_]+)/.exec( id );
			var new_id = matches[1];
			
			// if doesn't exist yet
			if ( ! $( 'div.listingid-' + listingid + ' div.pending-changes div#' + new_id ).length ) 
			
			
				$( 'div.listingid-' + listingid + ' div.pending-changes').append('<div id="' + new_id + '">' + val + '</div>');
			else
				// otherwise update it
				$( 'div.listingid-' + listingid + ' div.pending-changes div#' + new_id ).html( val );
				
			//$( '.notice').html('listing has unsaved changes');
			$( 'button.listing-' + listingid ).addClass('pending-changes');
			// clear confirmations of cancel
			$( 'div.listingid-' + listingid + ' button.cancel-listing').removeClass('confirmed');
		},
		
		// callback after update
		"update_cb" : function( result ) {
		
			if ( /saved/.test( result ) ) {

				// get the id
				var matches = /saved ([0-9]+)/.exec( result );
				var id = matches[1];
				console.log( id );
				
				// remove pending changes class
				$( 'div.listingid-' + id + ' button.save-control').removeClass('pending-changes');
				
				// remove queued changes
				$( 'div.listingid-' + id + ' div.pending-changes').empty();
				
				// set reverts
				$.ca.listing.set_reverts_for( id );
				
				// change mode
				$.ca.listing.set_view_edit( id, 'view');
				
				// update view fields
				$.ca.listing.update_view_fields( id );
			
			} else 
				$( '.notice').addClass('error').html('an error occured saving');
		
		},
	
		// update a listing
		"update" : function( e , elem ) {

			// get listing id
			var lid = $( elem ).attr('id').substring(1);
		
			// if any fields in error, don't save
			if ( $( '.listingid-' + lid + '.error').length ) {
				$('.notice').html('please correct errors before saving');
				return false;
			}
		
			// if no changes, let the user know
			if ( ! $( elem ).hasClass('pending-changes') ) {
				$( '.notice').html("no changes to save");
				return false;
			}
			
			
			// send changes via api
			var url = 'business/listing/' + lid + '/update';
			var args = 'args=<div>' + $( 'div.listingid-' + lid + ' div.pending-changes').html() + '</div>';
			
			$.xo.api.call( url, $.ca.listing.update_cb , args);
			
		},
		
		// cancel saving
		"cancel_save" : function( e, elem ) {
		
			// get listing id
			var matches = /listing-([0-9]+)/.exec( $(elem).attr('class') );
			var listingid = matches[1];

			// if no changes, just revert
			if ( $(elem).hasClass('pending-changes') ) {
			
				if ( ! $(elem).hasClass('confirmed') ) {
					$( elem).addClass('confirmed');
					$( '.notice').html('really discard changes?  click again for yes');
					return false;
				} 
			}
			
			// just revert
			// change all children
			$( elem ).removeClass('confirmed');
			$( 'div.listingid-' + listingid ).removeClass('edit').addClass('view');
				
			$( 'div.listingid-' + listingid + ' span.edit-mode'  ).removeClass( 'edit-mode' ).addClass( 'view-mode' );
			$( 'div.listingid-' + listingid + ' input.edit-mode'  ).removeClass( 'edit-mode').addClass( 'view-mode' );
			$( 'div.listingid-' + listingid + ' select.edit-mode').removeClass('edit-mode').addClass('view-mode');
			$( 'div.listingid-' + listingid + ' textarea.edit-mode').removeClass('edit-mode').addClass('view-mode');
			
			$( 'div.listingid-' + listingid + ' div.save-controls').removeClass('edit-mode').addClass('view-mode');
			$( 'div.listingid-' + listingid + ' label.listing-edit-label').removeClass('edit-mode').addClass('view-mode');
			
			
			// remove pending and reverted
			$( 'div.listingid-' + listingid + ' div.pending-changes').empty();
			$( 'div.listingid-' + listingid + ' div.revert-changes').children().each( function() {
			
				//console.log( 'found a change to revert');
			
				// get id
				var id = $( this).attr('id');
				// get value
				var val = $( this).html();
				
				// revert
				$( 'div.listingid-' + listingid + ' #' + id + ' option' ).removeAttr('selected');
				$( 'div.listingid-' + listingid + ' #' + id + ' option[value="' + val + '"]').attr('selected','selected');
			
			});
			$( 'div.listingid-' + listingid + 'div.revert-changes').empty();
			
			return true;
			
		},
	
		// approve or delist
		"approve_delist" : function ( e , elem ) {
			
			// get the id
			var id = $( elem ).attr('id');
			// set action
			var action = $( elem ).hasClass('approved') ? 'delist' : 'approve';
			// set url
			var url = 'business/listing/' + id + '/' + action;
			
			// call the api
			$.xo.api.call( url, $.ca.listing.approve_cb );
			
		
		},
		
		// callback after approve/delist
		"approve_cb" : function ( result ) {
		
			if ( /approve/.test( result ) ) {
				var id = parseInt( $.trim( result.substring(8) ) );
				$( 'button.approve-' + id ).removeClass('unapproved').addClass('approved');
				$( '.notice').addClass('success').html('listing approved');
			}
			else 
				if ( /delist/.test( result ) ) {
					var id = parseInt( $.trim( result.substring( 7) ) );
					$( 'button.approve-' + id ).removeClass('approved').addClass('unapproved');
					$('.notice').addClass('success').html('listing de-listed');
				}
		}
		

	
	},
	
	// manage
	"manage" : {
	
		// show/hide deleted
		"show_deleted" : function ( e, elem ) {
		
			if ( $( elem ).is(':checked') )
				$( 'div.deleted').fadeIn('fast');
			else
				$( 'div.deleted').fadeOut('fast');
		
		}
	
	},
	
	"password" : {
	
		"reset" : function ( e, elem ) {
		
			// prevent form submission
			e.preventDefault();
			
			var email = $( '#login_email').val();
			
			var url = 'business/caravan_user/email:' + email + '/reset_password';
			
			$.xo.api.call(url, $.ca.password.reset_cb);
			
			// prevent form submission
			return false;
		},
	
		"reset_cb" : function( result ) {
		
			if ( result == 'error' ) {
				console.log( result );
			}
			
			if ( result == 'ok' ) {
				console.log ( result );
				
			}
			
			$('.userform').addClass('hidden');
            $('.after_reset').removeClass('hidden');
			
		},
		
		"change" : function ( e, elem ) {
		
			e.preventDefault();
			
			var pword = $( '#new_password' ).val();
			
			//console.log(pword);
								
			var url = 'business/caravan_user/' + $( '#userid' ).val() + '/change_password' ;		
			
			$.xo.api.call(url, $.ca.password.change_cb, 'new_password=' + pword);
		
			return false;
		
		},
		
		"change_cb" : function ( result ) {
			
			//console.log( result );
		
			$('.userform').addClass('hidden');
			$('.responses').removeClass('hidden');
		
			if ( /error/.test(result) ) {
				$('.error').removeClass('hidden');
			}
			
			if ( /ok/.test( result ) ) {				
				$('.success').removeClass('hidden');				
			}	
			
		}
		
	},
	
	// business object management
	"business" : {
	
			// recycle a listing 
		"delete" : function( e, elem ) {
		
			// get the key
			var keyset = /business-([a-z|_]+)/.exec( $( elem).attr('class') );
			var key = keyset[1];
			
			//console.log( key );
		
			// get the id
			var id = $( elem ).attr('id').substring( 4);
			
			// get action
			var action = $( elem).hasClass('deleted') ? 'restore' : 'recycle';
			
			// set url
			var url = 'business/' + key + '/' + id + '/' + action;
			
			// call the api
			$.xo.api.call( url, $.ca.business.delete_cb );
		
		},
				
		// callback after recycle
		"delete_cb" : function ( result ) {

			if ( /recycle/.test( result ) ) {
			
				var id = result.substring( 8 );
				
				$( 'button.admin-' + id ).addClass('deleted');
			
				$( 'div#' + id ).addClass('deleted');
			
				$('.notice').addClass('success').html('listing deleted');
				
				setTimeOut( window.location.reload , 3000);
			
			} else if ( /restore/.test( result ) ) {
			
				var id = result.substring( 8 );
				
				$( 'button.admin-' + id ).removeClass('deleted');
				
				$( 'div#' + id ).removeClass('deleted');
			
				$('.notice').addClass('success').html('listing restored');

				setTimeOut( window.location.reload , 3000);
			
				
			}
		}

	
	},
	
	// user module
	"user" : {
	
		// reset password
		"reset_password" : function ( e , elem ) {
			
			// get the id
			var id = $( elem ).attr('id').substring( 4);
			
			// set url
			var url = 'business/caravan_user/' + id + '/reset_password';
			
			// call the api
			$.xo.api.call( url, $.ca.user.reset_cb );
			
		
		},
		
		// callback after approve/delist
		"reset_cb" : function ( result ) {

			if ( result == 'ok' )
				$('.notice').addClass('success').removeClass('error warning').html('password reset link sent');
			else
				$('.notice').addClass('error').removeClass('success').html('error resetting password');
		},
		
	
		// lock/unlock
		"lock" : function ( e , elem ) {
			
			// get the id
			var id = $( elem ).attr('id').substring( 5);
			
			// set action
			var action = $( elem ).hasClass('locked') ? 'unlock' : 'lock';
			
			// set url
			var url = 'business/caravan_user/' + id + '/' + action;
			
			// call the api
			$.xo.api.call( url, $.ca.user.lock_cb );
			
		
		},
		
		// callback after approve/delist
		"lock_cb" : function ( result ) {
				
			if ( /unlock/.test( result ) ) {
					var id = result.substring( 7);
					var prefix = "button.lock-";
					var query = prefix.concat(id);
					//console.log( query );
					$( query ).removeClass('locked').addClass('unlocked');
					$('.notice').addClass('success').html('user unlocked');
				} else
		
			if ( /lock/.test( result ) ) {
				var id = result.substring(5);
					var prefix = "button.lock-";
					var query = prefix.concat(id);
					//console.log( query );
				$( query ).removeClass('unlocked').addClass('locked');
				$( '.notice').addClass('success').html('user locked');
			}
			
		}
		
	},
	
	"paginate" : {
	
		"direction" : "next",
		
		"page_first" : 1,
	
		// page cb
		"page_cb" : function ( result ) {
		
			var classname = $.xo.context == 'manage' ? '.AdminListRecord' : '.caravan-listing-view';
			
			$( classname ).fadeOut( "fast").remove();
				
			$( result ).insertAfter( '.pagination');
			// config ajax editor
			$.xo.ajax_editor.configure();
			
			// get num results
			var num_results = $ ( classname).length
			var page_max = $.ca.paginate.page_first + num_results -1;
			
			// update pagination
			$( 'input#page_first' ).val( $.ca.paginate.page_first);
			$( 'input#page_last').val( page_max );
			$( 'span.page-status').html( 'Viewing records ' + $.ca.paginate.page_first + ' to ' + page_max + ' of ' + $( 'input#record_last').val() );
			
			if ( parseInt( $('input#page_last').val() ) == parseInt( $( 'input#record_last').val()) )
				$( 'button.page-next').removeClass('visible').addClass('hidden');
			else
				$( 'button.page-next').removeClass('hidden').addClass('visible');
				
			if ( parseInt( $('input#page_first').val() ) > 1 )
				$( 'button.page-prev').removeClass('hidden').addClass('visible');
			else $( 'button.page-prev').removeClass('visible').addClass('hidden');
		
		},
	
		// next prev
		"next_prev" : function( e, elem ) {
		
			var first = parseInt( $( 'input#page_first').val() );
		
			var direction = /next/.test( $( elem ).attr('class') ) ? 'next' : 'prev';
			$.ca.paginate.direction = direction;
			
			// get key
			var matches = /key-([a-z|_]+)/.exec( $( elem ).attr('class'));
			var key = matches[1];
			
			// get offset
			var offset = direction == 'next' ? first + 9 : first - 11;
			$.ca.paginate.page_first = offset + 1;
			
			var views = '/bo-' + key + '-admin-list-view/bo-' + key + '-admin-none-view';
			if ( $.xo.context == 'my-listings' )
				 views = '/caravan-listing-view/caravan-listing-none';
			
			
			// prepare api call
			$.xo.api.call (
				'recordset/' + key + '/offset:' + offset + views,
				$.ca.paginate.page_cb
			);
	
		}
	
	}
	
	
};
