var APP = {};

APP.validation =
{ email     : /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
, username  : /^([a-záéíóúñÑÁÉÍÓÚA-Z\-])+$/
, text      : /^([a-záéíóúñÑÁÉÍÓÚA-Z \-])+$/
, password  : /(?=^.{8,}$)([0-9a-záéíóúñÑÁÉÍÓÚA-Z\-])+$/
, number    : /(?=^.{8,8}$)([0-9])+$/
}

APP.jobsDictionary = [];

Pusher.log = function(message) {
	if (window.console && window.console.log) {
		window.console.log(message);
	}
};

var pusher = new Pusher('0f1251f9cdd3135dbbd3');
// var channel = pusher.subscribe('appelo');
// channel.bind('hello', function(data) {
// 	alert(data.message);
// });

$(function () {

	var proxy
	  , $signupClient     = $('div.js-signup-client-holder')
	  , $signupUser       = $('div.js-signup-user-holder')
	  , $login            = $('div.js-login-holder')
	  , $logout           = $('a.js-logout')
	  , $scrollNavigation = $('a.js-scroll-navigation')
	  , $homeUser         = $('div.js-home-user-holder')
	  , $homeClient       = $('div.js-home-client-holder')
	  ;

	if ( bu.match('localhost') ) {
		bu = bu + '/appelo/';
	} else {
		bu = bu + '/';
	}

	proxy = bu + 'src/proxy.php?';

	APP.includes = {};
	APP.includes.scrollNavigation = function () {
		$scrollNavigation.on('click', function ( e ) {
			var $this = $(this);
			e.preventDefault();
			console.log($this.data('target'));
			$('html,body').animate({
				scrollTop: $('#'+$this.data('target')).offset().top
			}, 1000);
		} );
	}
	APP.includes.signupClient = function () {
		var $jobsHolder   = $('div.js-jobs-holder')
		  , $citiesSelect = $('div.js-cities-holder').find('select')
		  , $typeSelect   = $('div.js-type-holder').find('select')
		  , $submit       = $('button.js-btn-submit')
		  , $uploadImage  = $('input.js-upload-image')
		  , $fields       = $('input.js-signup-field')
		  , $checkboxes   = $('input[type="checkbox"]')
		  , $submitMessage = $('p.js-submit-message')
		  , $photoMessage  = $('p.js-photo-message')
		  , $staticSection2= $('div.js-static-section-2')
		  , $staticSection3= $('div.js-static-section-3')
		  , $staticSection4= $('div.js-static-section-4')
		  , imageUri
		  // fn declarations
		  , renderImage
		  , onSubmitSuccess
		  ;

		onBeforeSend = function () {
			$submit.attr('disabled','disabled');
			$submitMessage.hide();
		}

		onSubmitSuccess = function ( response ) {

			if ( response === 'ERROR_EMAIL_EXISTS' ) {
				$submit.removeAttr('disabled','disabled');
				$submitMessage.addClass('app-submit-message-error').show();
				$submitMessage.text('El email ya ha sido registrado');
			}if ( response === 'ERROR_DNI_EXISTS' ) {
				$submit.removeAttr('disabled','disabled');
				$submitMessage.addClass('app-submit-message-error').show();
				$submitMessage.text('El dni ya ha sido registrado');
			} else if ( response === 'OK_USER_SAVED' ) {
				$submit.attr('disabled','disabled');
				$submitMessage.removeClass('app-submit-message-error').text('Estilista registrado!').show();
				window.location.href = bu + 'ingresa';
			} else {
				$submit.removeAttr('disabled','disabled');
				$submitMessage.addClass('app-submit-message-error');
				$submitMessage.text('Error no registrado');			}
		}

		renderImage = function ( event ) {
			var reader = new FileReader()
			  , $image = $('img.js-uploader-image')
			  , imgData = event.target.files[0]
			  ;
			$image.attr('src','');
			if ( /^image/.test( imgData.type ) ) {
				reader.readAsDataURL(imgData);
				reader.onloadend = function () {
					if ( imgData.size < 251000 ) {
						$image.attr('src', this.result );
						imageUri = this.result;
						$photoMessage.hide();
					} else {
						$photoMessage.text('Imagen muy grande, por favor intentar con otra').show();
					}
				}
			}
		}

		$submitMessage.hide();
		$photoMessage.hide();
		$uploadImage.on('change', renderImage);

		$typeSelect.selectpicker({style: 'btn-primary app-btn-fix', menuStyle: 'dropdown-inverse'});
		$typeSelect.on('change', function () {
			if ( +$typeSelect.val() === 2 ) {
				window.location.href = bu + 'registrate/usuario';
			}
		});

		$.get( proxy + 'mode=get_jobs' ).then( function ( response ) {
			var res = $.parseJSON( response )
			  , jobs
			  ;
			$.each( res, function ( k, v ) {
				var job = $('<label class="checkbox" for="'+v.jobId+'"><input type="checkbox" value="" id="'+v.jobId+'" data-toggle="checkbox">'+v.name+'</label>');
				job.appendTo( $jobsHolder );
			} );
			$(':checkbox').checkbox();
		} );

		$.get( proxy + 'mode=get_cities' ).then( function ( response ) {
			var res = $.parseJSON( response )
			  , cities
			  ;
			$.each( res, function ( k, v ) {
				var city = $('<option>').attr('value',v.cityId).text(v.name);
				city.appendTo( $citiesSelect );
			} );
			$citiesSelect.selectpicker({style: 'btn-primary app-btn-fix', menuStyle: 'dropdown-inverse'});
		} );

		// form submit
		$fields.on('input', function () {
			var $this = $(this);
			if ( !APP.validation[ $this.attr('type') ].test( $this.val() ) ) {
				$this.parent().addClass('has-error');
			} else {
				$this.parent().removeClass('has-error');
			}
		} );

		// dont mess with android keyboard
		$fields.on('click', function () {
			$staticSection2.addClass('hidden-xs');
			$staticSection3.addClass('hidden-xs');
			$staticSection4.addClass('hidden-xs');
		} );

		$fields.on('blur', function () {
			$staticSection2.removeClass('hidden-xs');
			$staticSection3.removeClass('hidden-xs');
			$staticSection4.removeClass('hidden-xs');
		} );

		$submit.on('click', function () {
			var fields  = $fields
			  , isValid = false
			  , inputs  = {}
			  ;
			console.log('submit');
			$('div.js-cities-holder').find('select').val('1');
			isValid = APP.validation.text.test( $(fields[0]).val() ) &&
			APP.validation.email.test( $(fields[1]).val() ) &&
			APP.validation.number.test( $(fields[2]).val() ) &&
			APP.validation.password.test( $(fields[3]).val() ) &&
			APP.validation.password.test( $(fields[4]).val() ) &&
			$( fields[3] ).val() === $( fields[4] ).val() &&
			imageUri &&
			$('input[type="checkbox"]').is(':checked') &&
			!!$('div.js-cities-holder').find('select').val();

			if ( !!$.grep( $('input.js-signup-field'), function (n) { return !!$(n).val() === false } ).length ) {
				$submitMessage.addClass('app-submit-message-error').text('Complete los campos en blanco').show();
			}
			if ( !$('div.js-cities-holder').find('select').val() ) {
				$submitMessage.addClass('app-submit-message-error').text('Elija una ciudad').show();
			}
			if ( !$('input[type="checkbox"]').is(':checked') ) {
				$submitMessage.addClass('app-submit-message-error').text('Elija por lo menos una tarea').show();
			}
			if ( !imageUri ) {
				$submitMessage.addClass('app-submit-message-error').text('Debe elegir una foto de perfil').show();
			}


			if ( isValid ) {
				inputs.fullName = $(fields[0]).val();
				inputs.email    = $(fields[1]).val();
				inputs.dni      = $(fields[2]).val();
				inputs.password = btoa( $(fields[3]).val() );
				inputs.image    = encodeURIComponent(imageUri);
				inputs.jobs     = $.makeArray( $('label.checkbox.checked').map( function () { return $(this).attr('for') } ) ).join();
				inputs.cityId   = $('div.js-cities-holder').find('select').val();

				inputs = $.param( inputs );

				$.ajax( { url     : proxy + 'mode=save_client'
				        , type    : 'POST'
				        , data    : inputs
				        , success : onSubmitSuccess } )
			}
		} );
	}
	APP.includes.signupUser = function () {
		var $typeSelect    = $('div.js-type-holder').find('select')
		  , $submit        = $('button.js-btn-submit')
		  , $fields        = $('input.js-signup-field')
		  , $submitMessage = $('p.js-submit-message')
		  , $staticSection2= $('div.js-static-section-2')
		  , $staticSection3= $('div.js-static-section-3')
		  , $staticSection4= $('div.js-static-section-4')
		  // fn declarations
		  , onSubmitSuccess
		  , onBeforeSend
		  ;
		$submitMessage.hide();

		onBeforeSend = function () {
			$submit.attr('disabled','disabled');
			$submitMessage.hide();
		}

		onSubmitSuccess = function ( response ) {
			$submitMessage.show();
			if ( response === 'ERROR_EMAIL_EXISTS' ) {
				$submit.removeAttr('disabled','disabled');
				$submitMessage.addClass('app-submit-message-error');
				$submitMessage.text('El email ya ha sido registrado');
			} else if ( response === 'ERROR_USER_EXISTS' ) {
				$submitMessage.addClass('app-submit-message-error');
				$submit.removeAttr('disabled','disabled');
				$submitMessage.text('El usuario ya ha sido registrado');
			} else if ( response === 'OK_USER_SAVED' ) {
				$submitMessage.removeClass('app-submit-message-error');
				$submit.attr('disabled','disabled');
				$submitMessage.text('Usuario registrado');
				window.location.href = bu + 'ingresa';
			} else {
				$submit.removeAttr('disabled','disabled');
				$submitMessage.addClass('app-submit-message-error');
				$submitMessage.text('Error no registrado');
			}
		}

		$typeSelect.selectpicker({style: 'btn-primary app-btn-fix', menuStyle: 'dropdown-inverse'});
		$typeSelect.on('change', function () {
			if ( +$typeSelect.val() === 2 ) {
				window.location.href = bu + 'registrate/estilista';
			}
		});

		$fields.on('input', function () {
			var $this = $(this);
			if ( !APP.validation[ $this.attr('type') ].test( $this.val() ) ) {
				$this.parent().addClass('has-error');
			} else {
				$this.parent().removeClass('has-error');
			}
		} );
		// dont mess with android keyboard
		$fields.on('click', function () {
			$staticSection2.addClass('hidden-xs');
			$staticSection3.addClass('hidden-xs');
			$staticSection4.addClass('hidden-xs');
		} );

		$fields.on('blur', function () {
			$staticSection2.removeClass('hidden-xs');
			$staticSection3.removeClass('hidden-xs');
			$staticSection4.removeClass('hidden-xs');
		} );

		$( $fields[1] ).on('input', function () {
			var $this = $(this)
			  , $other = $( $fields[2] )
			  ;
			if ( $this.val() !== $other.val() ) {
				$this.parent().addClass('has-error');
				$other.parent().addClass('has-error');
			} else {
				$this.parent().removeClass('has-error');
				$other.parent().removeClass('has-error');
			}
		});

		$( $fields[2] ).on('input', function () {
			var $this = $(this)
			  , $other = $( $fields[1] )
			  ;
			if ( $this.val() !== $other.val() ) {
				$this.parent().addClass('has-error');
				$other.parent().addClass('has-error');
			} else {
				$this.parent().removeClass('has-error');
				$other.parent().removeClass('has-error');
			}
		});

		$submit.on('click', function () {
			var fields  = $fields
			  , isValid = false
			  , inputs  = {}
			  ;
			isValid = APP.validation.email.test( $( fields[0] ).val() ) &&
			APP.validation.password.test( $( fields[1] ).val() ) &&
			APP.validation.password.test( $( fields[2] ).val() ) &&
			$( fields[1] ).val() === $( fields[2] ).val();


			if ( !!$.grep( $('input.js-signup-field'), function (n) { return !!$(n).val() === false } ).length ) {
				$submitMessage.addClass('app-submit-message-error').text('Complete los campos en blanco').show();
			}

			if ( isValid ) {
				inputs.cityId       = 1;
				inputs.email        = $(fields[0]).val();
				inputs.password     = btoa( $(fields[1]).val() );
				inputs.fullName     = 'juan la jara'
				inputs.registration = 3;
				inputs = $.param( inputs );
				$.ajax( { url        : proxy + 'mode=save_user'
				        , type       : 'POST'
				        , data       : inputs
				        , beforeSend : onBeforeSend
				        , success    : onSubmitSuccess } );
			}

		} );
	}
	APP.includes.login = function () {
		var $submit        = $('button.js-btn-submit')
		  , $submitMessage = $('p.js-submit-message')
		  , $fields        = $('input.js-login-field')
		  , $staticSection2= $('div.js-static-section-2')
		  , $staticSection3= $('div.js-static-section-3')
		  , $staticSection4= $('div.js-static-section-4')
		  // fn declarations
		  , onBeforeSend
		  , onSubmitSuccess
		  ;

		onBeforeSend = function () {
			$submit.attr('disabled','disabled');
			$submitMessage.hide();
		}

		onSubmitSuccess = function ( response ) {
			var crendentials = {};
			crendentials.email = $($fields[0]).val();
			crendentials.key   = 'YXBwZWxv';
			$submitMessage.show();
			console.log( 'login onSubmitSuccess', response );
			if ( response === 'ERROR_EMAIL_DOESNT_EXISTS' ) {
				$submit.removeAttr('disabled','disabled');
				$submitMessage.addClass('app-submit-message-error');
				$submitMessage.text('El email no ha sido registrado');
			} else if ( response === 'ERROR_WRONG_PASSWORD' ) {
				$submit.removeAttr('disabled','disabled');
				$submitMessage.addClass('app-submit-message-error');
				$submitMessage.text('Password incorrecto');
			} else if ( response === 'OK_USER_CORRECT' ) {
				$.cookie('appelo', JSON.stringify(crendentials), { expires: 7, path: '/' });
				window.location.href = bu;
				// window.location.href = 'localhost:2013/appelo';
			}
			// $submitMessage.text(response);
		}

		$fields.on('input', function () {
			var $this = $(this);
			if ( !APP.validation[ $this.attr('type') ].test( $this.val() ) ) {
				$this.parent().addClass('has-error');
			} else {
				$this.parent().removeClass('has-error');
			}
		} );
		// dont mess with android keyboard
		$fields.on('click', function () {
			$staticSection2.addClass('hidden-xs');
			$staticSection3.addClass('hidden-xs');
			$staticSection4.addClass('hidden-xs');
		} );

		$fields.on('blur', function () {
			$staticSection2.removeClass('hidden-xs');
			$staticSection3.removeClass('hidden-xs');
			$staticSection4.removeClass('hidden-xs');
		} );

		$submit.on('click', function () {
			var fields  = $fields
			  , isValid = false
			  , inputs  = {}
			  ;

			isValid = APP.validation.email.test( $(fields[0]).val() ) &&
			APP.validation.password.test( $(fields[1]).val() );

			if ( isValid ) {
				inputs.email = $(fields[0]).val();
				inputs.password = btoa( $(fields[1]).val() );
				inputs = $.param( inputs );
				$.ajax( { url        : proxy + 'mode=login'
				        , type       : 'POST'
				        , data       : inputs
				        , beforeSend : onBeforeSend
				        , success    : onSubmitSuccess
				        } );
			}
		} );

	}

	APP.includes.homeUser = function () {
		var $searchClient    = $('button.js-btn-search-client')
		  , $searchCta       = $('div.js-search-now-cta-holder')
		  , $section1        = $('div.js-home-user-section-1')
		  , $section2        = $('div.js-home-user-section-2')
		// open panel
		  , $searchClientNow = $('img.js-search-client-now')
		  , $jobsHolder      = $('div.js-jobs-holder')
		  , $searchNowHolder = $('div.js-search-now-holder')
		  , $resultsHolder   = $('div.js-results-holder')
		  , map
		  , marker
		  , mapResults
		  , channel          = pusher.subscribe('appelo-'+JSON.parse( $.cookie('appelo') ).email)
		// fn declarations
		  , onSearchClientSuccess
		  , setLeafletMap
		  ;

		$searchNowHolder.hide();
		$section2.hide();

		channel.bind('response', function ( data ) {
			console.log( data );
			$section2.find('.cta').empty();
			$('<img class="thankyou-img">').attr('src','img/home/user/thankyou.png').appendTo( $section2.find('.cta') );
		} );

		onSearchClientSuccess = function ( response ) {
			var response              = JSON.parse( response )
			  , $jobsSearchedForTitle = $('span.js-searched-jobs')
			  , jobsSearchedFor       = $.makeArray( $('label.checkbox.checked').map( function () { return $(this).text() } ) )
			  , $submitRequestBtn     = $('button.js-btn-submit-request')
			  , resultsGroup          = []
			  , featureGroup
			  , userIsHere
			  , hasUserSelected       = false
			// fn declarations
			  , buildClient
			  ;

			$section1.slideUp();
			$section2.fadeIn();
			$submitRequestBtn.hide();
			mapResults = L.map('results-map').setView( [ JSON.parse( $.cookie('appelo-coords') ).latitude, JSON.parse( $.cookie('appelo-coords') ).longitude], 13 );
			L.tileLayer('http://{s}.tiles.mapbox.com/v3/wxo.i6oi4c23/{z}/{x}/{y}.png', {
			    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
			    maxZoom: 18
			}).addTo(mapResults);
			userIsHere = L.marker([ JSON.parse( $.cookie('appelo-coords') ).latitude, JSON.parse( $.cookie('appelo-coords') ).longitude]).addTo(mapResults).bindPopup('Ud. está aquí').openPopup();
			mapResults.scrollWheelZoom.disable();

			buildClient = function ( givens ) {
				var template
				  , img
				  , part1
				  , part2
				  , jobs
				  ;
				template = $('<div>').attr('class','result-holder').data('client-id',givens.clientId);
				part1    = $('<div>').attr('class','part part-1');
				part2    = $('<div>').attr('class','part part-2');
				img      = $('<img>').attr('src', 'img/profiles/'+givens.clientId+'.jpg');
				part1.append( img ).appendTo( template );
				part2.append( $('<h5>').text(givens.fullName) );
				part2.append( $('<p>').text( 'DNI: ' + givens.dni) );
				part2.appendTo( template );
				$(img).one('error', function () {
					$(this).attr('src', 'img/profiles/'+givens.clientId+'.png');
				} );
				template.append( $('<p>').attr('class','jobs-label').text('Tareas') );
				jobs = $('<ul>').attr('class','jobs').appendTo( template );
				console.log( APP.jobsDictionary );
				$.each( givens.jobs, function ( k, v ) {
					console.log( APP.jobsDictionary[ APP.jobsDictionary.map( function ( job ) { return job.id } ).indexOf( v.jobId ) ].name );
					$('<li>').append( $('<span>').text( APP.jobsDictionary[ APP.jobsDictionary.map( function ( job ) { return job.id } ).indexOf( v.jobId ) ].name ) ).appendTo( jobs );
				} );
				return template;
			}

			$.each( response, function ( k, v ) {
				var marker;
				buildClient( v ).appendTo( $resultsHolder );

				if ( $jobsSearchedForTitle.length > 2 ) {
					$jobsSearchedForTitle.text( jobsSearchedFor.join(', ') );
				} else {
					$jobsSearchedForTitle.text( jobsSearchedFor.join(' y ') );
				}
				marker = L.marker( [ v.latitude, v.longitude ] ).addTo( mapResults ).bindPopup( v.fullName );
				resultsGroup.push( marker );
				console.log(v, APP.jobsDictionary);
			} );

			$('div.result-holder').on( 'mouseover', function () {
				$(this).addClass('result-selected');
			} ).on('mouseleave', function () {
				$(this).removeClass('result-selected');
			});

			$('div.result-holder').on( 'click', function () {
				var $this = $(this);
				$('div.result-holder').off('mouseover').off('mouseleave');
				$this.addClass('result-selected');
				hasUserSelected = $this.data('client-id');
				$submitRequestBtn.fadeIn();
			} );

			$submitRequestBtn.on('click', function () {
				var requestGivens = {};
				requestGivens.userEmail = JSON.parse( $.cookie('appelo') ).email;
				requestGivens.clientId  = hasUserSelected;
				requestGivens.jobIds    = $.makeArray( $('label.checkbox.checked').map( function () { return $(this).attr('for') } ) ).join();
				requestGivens.address   = $('#address').val();

				if ( $('#address').val() ) {
					$.ajax( { url  : proxy + 'mode=user_request'
					        , type : 'POST'
					        , data : requestGivens
					        , success : function ( response ) {
					          console.log( 'loading', response );
					          $('html, body').animate({
					            scrollTop: $("div.navbar-header").offset().top
					          }, 400);
					          $section2.addClass('section2submitRequest').find('.cta').empty();
					          $section2.find('.cta').addClass('ctaSubmitRequest').html( '<h3 class="ff2">Esperando respuesta..</h3>' );
					        } } );
				} else {
					$('p.js-help-address').text('Ingrese una dirección');
				}

			} );

			resultsGroup.push( userIsHere );
			featureGroup = new L.featureGroup( resultsGroup );
			mapResults.fitBounds( featureGroup.getBounds(), { padding: [ 50, 50 ] } );
		}

		setLeafletMap = function () {
			console.log( JSON.parse( $.cookie('appelo-coords') ).latitude, JSON.parse( $.cookie('appelo-coords') ).longitude );
			map = L.map('map').setView([ JSON.parse( $.cookie('appelo-coords') ).latitude, JSON.parse( $.cookie('appelo-coords') ).longitude], 15);
			L.tileLayer('http://{s}.tiles.mapbox.com/v3/wxo.i6oi4c23/{z}/{x}/{y}.png', {
			    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
			    maxZoom: 18
			}).addTo(map);
			marker = L.marker([ JSON.parse( $.cookie('appelo-coords') ).latitude, JSON.parse( $.cookie('appelo-coords') ).longitude]).addTo(map);
			map.scrollWheelZoom.disable();
		}

		$searchClientNow.on('click', function () {
			$searchCta.slideUp();
			$searchNowHolder.fadeIn();
			map.invalidateSize();
		});

		$logout.on('click', function ( e ) {
			e.preventDefault();
			if ( JSON.parse( $.cookie('appelo') ).email === 'luishon02@gmail.com' ) {
				$.removeCookie('appelo-coords', { path: '/' });
			}
			$.removeCookie('appelo', { path: '/' });
			window.location.reload();
		} );

		$.get( proxy + 'mode=get_jobs' )
		.then( function ( response ) {
			var res = $.parseJSON( response )
			  , jobs
			  ;
			$.each( res, function ( k, v ) {
				var job = $('<label class="checkbox" for="'+v.jobId+'"><input type="checkbox" value="" id="'+v.jobId+'" data-toggle="checkbox">'+v.name+'</label>');
				job.appendTo( $jobsHolder );
				APP.jobsDictionary.push( { name: v.name, price: v.averagePrice, id: v.jobId } );
			} );
			$(':checkbox').checkbox();
		} );

		if ( JSON.parse( $.cookie('appelo') ).email !== 'luishon02@gmail.com' ) {
			if ( !$.cookie('appelo-coords') ) {
				$.geolocation.get( { success: function ( response ) {
					var email = JSON.parse( $.cookie('appelo') ).email;

					$.ajax( { url : proxy + 'mode=set_current_location'
					        , type : 'POST'
					        , data : 'email='+email+'&latitude='+response.coords.latitude+'&longitude='+response.coords.longitude
					        , success : function () {
					          console.log( 'geolocation', response.coords.latitude );
					          $.cookie('appelo-coords', JSON.stringify(response.coords), { expires: 7, path: '/' });
					          setLeafletMap();
					        } } );
				} } );
			} else {
				setLeafletMap();
			}
		} else {
			$.cookie('appelo-coords', JSON.stringify( {"longitude":-77.0809274,"latitude":-12.0844925} ), { expires: 7, path: '/' });
			setLeafletMap();
		}

		$searchClient.on('click', function () {
			console.log('sup $searchClient');
			var givens = {};
			givens.latitude  = JSON.parse( $.cookie('appelo-coords') ).latitude;
			givens.longitude = JSON.parse( $.cookie('appelo-coords') ).longitude;
			givens.jobs      = $.makeArray( $('label.checkbox.checked').map( function () { return $(this).attr('for') } ) ).join();
			$.ajax( { url  : proxy + 'mode=get_near_active_clients_by_user_and_jobs'
			        , type : 'POST'
			        , data : $.param( givens )
			        , success : onSearchClientSuccess } )
		} );

	}

	APP.includes.homeClient = function () {
		var channel             = pusher.subscribe('appelo-'+JSON.parse( $.cookie('appelo') ).email)
		  , appointmentResponse
		  , appointmentGivens   = {}
		  , $availableCheck     = $('div.app-available')
		  , $reponseBtn         = $('button.js-btn-submit-response')
		  , $waitingLabel       = $('h4.js-waiting-label')
		  , $mapHolder          = $('div.js-client-map-holder')
		  , $requestHolder      = $('div.js-request-holder')
		  , map                 = L.map('client-map')
		  , requestMap          = L.map('request-map')
		  , marker
		  // fn declarations
		  , setLeafletMap
		  , buildRequest
		  ;

		$reponseBtn.hide();
		$waitingLabel.hide();
		$requestHolder.hide();
		$availableCheck.bootstrapSwitch('setState',false);

		buildRequest = function ( givens ) {
			var $request       = $('<div>').addClass('request')
			  , $title         = $('<h3>').addClass('ff2').text('Un nuevo pedido')
			  , $forUser       = $('<p>').addClass('instructions').text('Para el usuario ' + givens.user.fullName)
			  , $jobsTitle     = $('<p>').addClass('instructions').text('Tareas')
			  , $jobsHolder    = $('<ul>').addClass('jobsHolder')
			  , $addressHolder = $('<p>').addClass('instructions').text( 'Dirección: ' + givens.address )
			  , requestMarker
			  ;
			$mapHolder.slideUp();

			$title.appendTo( $request );
			$forUser.appendTo( $request );
			$addressHolder.appendTo( $request );
			$jobsTitle.appendTo( $request );

			$.each( givens.jobs, function ( k, v ) {
				var $job = $('<li>').addClass('job btn btn-xs btn-info').text( v.name );
				$job.appendTo( $jobsHolder );
			} );

			$jobsHolder.appendTo( $request );

			requestMap.setView([ givens.user.latitude, givens.user.longitude ], 15);
			L.tileLayer('http://{s}.tiles.mapbox.com/v3/wxo.i6oi4c23/{z}/{x}/{y}.png', {
			  attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
			  maxZoom: 18
			}).addTo(requestMap);
			requestMarker = L.marker([ givens.user.latitude, givens.user.longitude ]).addTo(requestMap);
			requestMap.scrollWheelZoom.disable();

			$request.prependTo( $requestHolder );
			$reponseBtn.show();
			$requestHolder.show();
			requestMap.invalidateSize();
		}

		setLeafletMap = function () {
			map.setView([ JSON.parse( $.cookie('appelo-coords') ).latitude, JSON.parse( $.cookie('appelo-coords') ).longitude], 15);
			L.tileLayer('http://{s}.tiles.mapbox.com/v3/wxo.i6oi4c23/{z}/{x}/{y}.png', {
			  attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
			  maxZoom: 18
			}).addTo(map);
			marker = L.marker([ JSON.parse( $.cookie('appelo-coords') ).latitude, JSON.parse( $.cookie('appelo-coords') ).longitude]).addTo(map);
			map.scrollWheelZoom.disable();
		}

		channel.bind('request', function ( data ) {
			console.log( data );
			appointmentResponse = data;
			$waitingLabel.hide();
			buildRequest( data );
		} );

		$availableCheck.on( 'switch-change', function () {
			var isActiveGivens = {};
			console.log('switch-change');
			isActiveGivens.email = JSON.parse( $.cookie('appelo') ).email;
			if ( $availableCheck.bootstrapSwitch('status') ) {
				isActiveGivens.isActive = 1;
				$waitingLabel.fadeIn();
				$.ajax( { url  : proxy + 'mode=set_is_active'
				        , type : 'POST'
				        , data : isActiveGivens
				        , success : function () {
				          console.log( 'isActive true', isActiveGivens );
				        } } );
			} else {
				isActiveGivens.isActive = 0;
				$waitingLabel.hide();
				$.ajax( { url  : proxy + 'mode=set_is_active'
				        , type : 'POST'
				        , data : isActiveGivens
				        , success : function () {
				          console.log( 'isActive false', isActiveGivens );
				        } } );
			}
		} );

		$reponseBtn.on('click', function () {
			appointmentGivens.userId    = appointmentResponse.user.userId;
			appointmentGivens.clientId  = appointmentResponse.clientId;
			appointmentGivens.userEmail = appointmentResponse.user.email;
			console.log( 'appointmentGivens', $.param( appointmentGivens ) );
			$.ajax( { url     : proxy + 'mode=client_response'
			        , type    : 'POST'
			        , data    : appointmentGivens
			        , success : function ( response ) {
			          console.log( 'client_response', response );
			          $requestHolder.empty();
			          $requestHolder.html('<h3 class="ff2">Gracias por usar Appelo, ya lo están esperando.</h3>');
			          $availableCheck.bootstrapSwitch('setState',false);
			        } } );
		});

		$logout.on('click', function ( e ) {
			var logoutGivens = {};
			logoutGivens.email    = JSON.parse( $.cookie('appelo') ).email;
			logoutGivens.isActive = 0;
			e.preventDefault();
			$.removeCookie('appelo', { path: '/' });
			if ( logoutGivens.email === 'luishon02@gmail.com' ) {
				$.removeCookie('appelo-coords', { path: '/' });
			}
			$.ajax( { url  : proxy + 'mode=set_is_active'
			        , type : 'POST'
			        , data : logoutGivens
			        , success : function () {
			          console.log('sup logout');
			          window.location.reload();
			        } } );
		} );

		// if ( JSON.parse( $.cookie('appelo') ).email !== 'luishon02@gmail.com' ) {
			if ( !$.cookie('appelo-coords') ) {
					$.geolocation.get( { success: function ( response ) {
						var email = JSON.parse( $.cookie('appelo') ).email;
						$.cookie('appelo-coords', JSON.stringify(response.coords), { expires: 7, path: '/' });
						// if ( email !== 'juanlajara@gmail.com' ) {
							$.ajax( { url : proxy + 'mode=set_current_location'
							        , type : 'POST'
							        , data : 'email='+email+'&latitude='+response.coords.latitude+'&longitude='+response.coords.longitude
							        , success : function () {
							          console.log( 'geolocation', response.coords.latitude );
							          $.cookie('appelo-coords', JSON.stringify(response.coords), { expires: 7, path: '/' });
							          setLeafletMap();
							        } } );
						// } else {
						// 	setLeafletMap();
						// }
					} } );
			} else {
				setLeafletMap();
			}
		// } else {
		// 	$.cookie('appelo-coords', JSON.stringify( {"longitude":-77.0809274,"latitude":-12.0844925} ), { expires: 7, path: '/' });
		// 	setLeafletMap();
		// }

		$.post( proxy + 'mode=client_is_active', { email: JSON.parse( $.cookie('appelo') ).email } )
		.then( function ( response ) {
			console.log( 'is active', +response, !!+response );
			if ( +response ) {
				console.log( 'uno' );
				$availableCheck.bootstrapSwitch('setState',true);
			} else {
				$availableCheck.bootstrapSwitch('setState',false);
			}
		} );
	}

	$scrollNavigation.length && APP.includes.scrollNavigation();
	$signupUser.length       && APP.includes.signupUser();
	$signupClient.length     && APP.includes.signupClient();
	$login.length            && APP.includes.login();
	$homeUser.length         && APP.includes.homeUser();
	$homeClient.length       && APP.includes.homeClient();

} );