function AppController($scope, $http, $window)
{

    $scope.trip;

    console.log($window.sessionStorage);

    $scope.getTripDirectory = function(id, mapReset)
    {


        $http({ method: 'GET',
                url: '/Trip/public/index.php/api/v1/trip/'+id+'/directory',
                headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Token': $window.sessionStorage.token
                }
        }).
            success(function(data, status, headers, config)
            {
                $scope.trip = data.trip;

                if(mapReset)
                {
                    setMapForTrip(data.trip);
                }

                $scope.updateTypeList();
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }

    $scope.getTripDirectory(1,true);

    $scope.$on('refreshTripMenu', function()
    {
        if($scope.trip) $scope.getTripDirectory($scope.trip.id,false);
    });

    $scope.updateTypeList = function()
    {
        $scope.trip.types = [];

        if( $scope.trip.areas[0] )
        {
            angular.forEach($scope.trip.areas[0].types, function(value, key)
            {
                $scope.trip.types.push({
                    id: value['id'],
                    name: value['name']
                });
            });
        }
        console.log($scope.trip.types);
    }

	$scope.numberOfType = function() {
		var count = 0;
		angular.forEach($scope.trip.areas.types.places, function() {
			count += todo.done ? 0 : 1;
		});
		return count;
	};
}



function PlaceEntry($scope, $http)
{
	$scope.getPlaceEntryForID = function(id)
	{
 		$http({method: 'GET', url: '/Trip/public/index.php/api/v1/place/'+id+'/all'}).
    		success(function(data, status, headers, config)
    		{
    			$scope.place = data.place;
                showPlaceInfo();
    		}).
    		error(function(data, status, headers, config)
    		{
    			console.log(status);
		   	}
		);
    }
}


function AddArea($scope, $http)
{
    $scope.area = {};

    $scope.processAreaData = function()
    {
        $scope.area.trip_id = $scope.trip.id;
        //console.log('Process Area Data');
        //console.log($scope.areaData);
        $scope.createNewArea();
    }

    $scope.createNewArea = function(area)
    {
        $http(
        {
            method: 'POST',
            url: '/Trip/public/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/area',
            data: $.param($scope.area),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    console.log(data.success);
                    $scope.$emit('refreshTripMenu');
                    newAreaAdded();
                }
                else
                {
                    if(data.errors.name) $scope.messageName = data.errors.name[0];
                    if(data.errors.trip_id) $scope.messageTrip = data.errors.trip_id[0];
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log("Connection Error");
            }
        );
    }
}

function AddPlace($scope, $http)
{
    $scope.place = {};
    $scope.place.location = {};
    $scope.place.links = [];
    $scope.place.attachments = [];

    $scope.processPlaceData = function()
    {
        //console.log($scope.place);
        $scope.createNewPlace();
    }

    $scope.updatePlaceGeoCoords = function(geolat, geolng)
    {
        $scope.$apply(function()
        {
            $scope.place.location.geolat = geolat;
            $scope.place.location.geolng = geolng;
        });
    }

    $scope.createNewPlace = function(area)
    {
        console.log($scope.place);
        $http(
        {
            method: 'POST',
            url: '/Trip/public/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/place',
            data: $.param($scope.place),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    //console.log(data.success);
                    $scope.$emit('refreshTripMenu');
                    newPlaceAdded(data.success);
                }
                else
                {
                    if(data.errors.name) $scope.messageName = data.errors.name[0];
                    if(data.errors.area) $scope.messageArea = data.errors.area[0];
                    if(data.errors.type) $scope.messageType = data.errors.type[0];
                    if(data.errors.location) $scope.messageLocation = data.errors.location[0];
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log("Connection Error");
            }
        );
    }

    $scope.addLink = function()
    {
        var id = $scope.linkID;
        $scope.linkID++;

        $scope.place.links.push( 
        {
            id: id,
            name: '',
            address: ''
        });

    }

    $scope.removeLink = function(id)
    {
        angular.forEach($scope.place.links, function(link, key)
        {
            if(link.id === id)
            {
                $scope.place.links.splice(key,1);
            }
        });
    }

    $scope.attachmentID = 0;

    $scope.addAttachment = function()
    {
        var id = $scope.attachmentID;
        $scope.attachmentID++;

        $scope.place.attachments.push( 
        {
            id: id,
            name: '',
            address: ''
        });
    }

    $scope.removeAttachment = function(id)
    {
        angular.forEach($scope.place.attachments, function(attachment, key)
        {
            if(attachment.id === id)
            {
                //console.log(key);
                $scope.place.attachments.splice(key,1);
            }
        });
    }
}

function EditArea($scope, $http)
{
    $scope.area = {};

    $scope.setupEditForArea = function(id)
    {
        $http({method: 'GET', url: '/Trip/public/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/area/'+id }).
            success(function(data, status, headers, config)
            {
                $scope.area = data.area;
                console.log($scope.area);
                areaEditSetupComplete();
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }

    $scope.processAreaData = function()
    {
        $scope.editAreaWithData();
    }

    $scope.editAreaWithData = function()
    {
        $http(
        {
            method: 'PATCH',
            url: '/Trip/public/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/area',
            data: $.param($scope.area),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    console.log(data.success);
                    $scope.$emit('refreshTripMenu');
                    areaEditComplete();
                }
                else
                {
                    if(data.errors.name) $scope.messageName = data.errors.name[0];
                    if(data.errors.trip_id) $scope.messageTrip = data.errors.trip_id[0];
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log("Connection Error");
            }
        );
    }
}

function EditPlace($scope, $http)
{
    $scope.place = {};
    $scope.original = {};

    $scope.setupEditForPlace = function(id)
    {
        $scope.place.id = id;
        $http({method: 'GET', url: '/Trip/public/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/place/'+id }).
            success(function(data, status, headers, config)
            {
                $scope.place = data.place;

                // Record Original Place Location
                $scope.original.geolat = $scope.place.location.geolat;
                $scope.original.geolng = $scope.place.location.geolng;

                // Run Additional Functions when Conplete
                placeEditSetupComplete(id);

            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }

    $scope.processPlaceData = function()
    {
        //console.log($scope.place);
        $scope.editPlaceWithData();
    }

    $scope.updatePlaceGeoCoords = function(geolat, geolng)
    {
        $scope.$apply(function()
        {
            $scope.place.location.geolat = geolat;
            $scope.place.location.geolng = geolng;
        });
    }

    $scope.editPlaceWithData = function()
    {
        console.log($scope.place);
        $http(
        {
            method: 'PATCH',
            url: '/Trip/public/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/place',
            data: $.param($scope.place),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    console.log(data.success);
                    $scope.$emit('refreshTripMenu');
                    placeEditComplete($scope.place.id);
                }
                else
                {
                    if(data.errors.name) $scope.messageName = data.errors.name[0];
                    if(data.errors.area) $scope.messageArea = data.errors.area[0];
                    if(data.errors.type) $scope.messageType = data.errors.type[0];
                    if(data.errors.location) $scope.messageLocation = data.errors.location[0];
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log("Connection Error");
            }
        );
    }

    $scope.addLink = function()
    {
        var id = $scope.linkID;
        $scope.linkID++;

        $scope.place.links.push( 
        {
            id: id,
            name: '',
            address: ''
        });

    }

    $scope.removeLink = function(id)
    {
        angular.forEach($scope.place.links, function(link, key)
        {
            if(link.id === id)
            {
                $scope.place.links.splice(key,1);
            }
        });
    }

    $scope.attachmentID = 0;

    $scope.addAttachment = function()
    {
        var id = $scope.attachmentID;
        $scope.attachmentID++;

        $scope.place.attachments.push( 
        {
            id: id,
            name: '',
            address: ''
        });
    }

    $scope.removeAttachment = function(id)
    {
        angular.forEach($scope.place.attachments, function(attachment, key)
        {
            if(attachment.id === id)
            {
                //console.log(key);
                $scope.place.attachments.splice(key,1);
            }
        });
    }
}




function Login($scope, $http, $window)
{
    $scope.active = false;

    console.log($window.sessionStorage);

    
    $scope.checkUserActive = function(token)
    {
        $http(
        {
            method: 'GET',
            url: '/Trip/public/index.php/api/v1/auth',
            data: $.param(token),
            headers: { 
                'Content-Type': 'application/x-www-form-urlencoded',
                'Token': token
            }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    console.log(data.success);
                }
                else
                {
                    console.log(data.errors);
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }

    $scope.init = function()
    {
        if($window.sessionStorage.token)
        {
            // Check token is valid
            console.log("Token is valid");
            $scope.checkUserActive($window.sessionStorage.token);            
        }
    }

    $scope.init();

    $scope.processLoginData = function(credentials)
    {
        // Reset Messages
        $scope.messagePassword = '';

        if(credentials) $scope.checkUserCredentials(credentials);
    }

    $scope.checkUserCredentials = function(credentials)
    {
        $http(
        {
            method: 'POST',
            url: '/Trip/public/index.php/api/v1/login',
            data: $.param(credentials),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    $window.sessionStorage.token = data.success;
                    console.log($window.sessionStorage);
                }
                else
                {
                    console.log(data.errors);
                    if(data.errors) $scope.messagePassword = data.errors;
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }
}

