<repo_name>maurohn/catawba-mobile<file_sep>/www/js/controllers.js
angular.module('RedHat-Forum.controllers', [])

.config(function($ionicConfigProvider) {
    $ionicConfigProvider.scrolling.jsScrolling(false);
    $ionicConfigProvider.backButton.text('').icon('ion-android-arrow-back');
    $ionicConfigProvider.platform.ios.navBar.alignTitle('center'); 
    $ionicConfigProvider.platform.android.navBar.alignTitle('center');
    $ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left');
	$ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back');	

	$ionicConfigProvider.views.transition('android'); 
//	$ionicConfigProvider.platform.ios.views.transition('ios'); 
//	$ionicConfigProvider.platform.android.views.transition('android');
    $ionicConfigProvider.views.swipeBackEnabled(false);
})

.run(function($rootScope, $ionicPlatform, $ionicPopup, $http, $ionicLoading, $localStorage) {
    

    //Localization.locate(true);
    $ionicPlatform.registerBackButtonAction(function (event) {
        event.preventDefault();
          $ionicPopup.confirm({
            title: 'Ops!',
            template: 'Are you sure you want to quit?',
            cancelText: 'Cancel',
            okText: 'Close'
          }).then(function(res){
            if( res ){
              navigator.app.exitApp();
            }
          })
    }, 100);
    
})


.controller('AuthCtrl', function($scope, $ionicConfig) {

})

.controller('WalkthroughCtrl', function($rootScope, $state, $templateCache, $q, $rootScope, $localStorage, $http, $ionicLoading, $ionicPopup) {
    
    if($localStorage.user_session) {
        $state.go('app.feeds-categories');
    } else {
    $rootScope.forums = [];
    $rootScope.data = [];
    $rootScope.data.selectedForum = 1;
      //inicia el evento cargando y bloquea la pantalla
        $ionicLoading.show({
			template: '<ion-spinner icon="android"></ion-spinner>'
		}); 
    
      $http({
            method: 'GET',
            url: url_backend + FORUMS,
            params:{},
            headers: {'Accept': 'application/json'}
         }).success(function(response){
              //Apaga el evento cargando
             $ionicLoading.hide();
             //alert(JSON.stringify(response));
             $rootScope.forums = response;
        }).error(function(data, status){
                //Apaga el evento cargando
                $ionicLoading.hide();
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: status + ' Call service error!',
                        okText: 'OK!'
                    }); 
        });
    
    $ionicPopup.alert({
                        title: 'Select a Forum',
                        template: 'Please select a forum: <select  ng-options="opt.id as opt.city for opt in forums" ng-model="data.selectedForum" style="background-color: azure;"></select>',
                        scope: $rootScope, 
                        buttons: [
                          {
                            text: 'Save',
                            type: 'button-positive',
                            onTap: function(e) {
                              $localStorage.forumId = $rootScope.data.selectedForum;
                              var forum = _.find($rootScope.forums, {id: $rootScope.data.selectedForum}); 
                              $localStorage.forum_survey_url = forum.survey_url;
                            }
                          }
                        ]
                      });  
    
    }
    
})

// APP
.controller('AppCtrl', function($scope, $ionicConfig, $localStorage) {
  $scope.user = JSON.parse($localStorage.user_session);
})

//LOGIN
.controller('LoginCtrl', function($scope, $state, $templateCache, $q, $rootScope, $localStorage, $http, $ionicLoading, $ionicPopup) {
	
	$scope.user = {};

	// $scope.user.email = "<EMAIL>";
	// $scope.user.password = "<PASSWORD>";
      $scope.doLogIn = function(){
        
        //inicia el evento cargando y bloquea la pantalla
        $ionicLoading.show({
			template: '<ion-spinner icon="android"></ion-spinner>'
		}); 
        
         $http({
            method: 'GET',
            url: url_backend + OAUTH,
            params:{'email': $scope.user.email, 'pass': $scope.user.password},
            headers: {'Accept': 'application/json'}
         }).success(function(response){
              //Apaga el evento cargando
             $ionicLoading.hide();
             //alert(JSON.stringify(response));
             $scope.user = response;
             //$scope.user.name = response.first_name + ' ' + response.last_name;
             $localStorage.user_session = JSON.stringify(response);
             $state.go('app.feeds-categories');
        }).error(function(data, status){
                //Apaga el evento cargando
                $ionicLoading.hide();
                if(status == 705){
                 $ionicPopup.alert({
                        title: 'Ups!',
                        template: data.error + ', please Sing Up first!',
                        okText: 'OK!'
                    });     
                 $state.go('auth.signup');
                } else if (status == 706){
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: data.error + ', please try again!',
                        okText: 'OK!'
                    }); 
                } else {
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: status + ' Call service error!',
                        okText: 'OK!'
                    }); 
                }
         
        });
      
	};


      

	// We need this for the form validation
	$scope.selected_tab = "";

	$scope.$on('my-tabs-changed', function (event, data) {
		$scope.selected_tab = data.title;
	});

})

.controller('SignupCtrl', function($scope, $state, $templateCache, $q, $rootScope, $localStorage, $http, $ionicLoading, $ionicPopup) {
	$scope.user = {};

//	$scope.user.email = "<EMAIL>";
//    $scope.user_inexistent = false;
    
    $scope.countries = [ 
    {name: 'Afghanistan', code: 'AF'},
    {name: 'Åland Islands', code: 'AX'},
    {name: 'Albania', code: 'AL'},
    {name: 'Algeria', code: 'DZ'},
    {name: 'American Samoa', code: 'AS'},
    {name: 'Andorra', code: 'AD'},
    {name: 'Angola', code: 'AO'},
    {name: 'Anguilla', code: 'AI'},
    {name: 'Antarctica', code: 'AQ'},
    {name: 'Antigua and Barbuda', code: 'AG'},
    {name: 'Argentina', code: 'AR'},
    {name: 'Armenia', code: 'AM'},
    {name: 'Aruba', code: 'AW'},
    {name: 'Australia', code: 'AU'},
    {name: 'Austria', code: 'AT'},
    {name: 'Azerbaijan', code: 'AZ'},
    {name: 'Bahamas', code: 'BS'},
    {name: 'Bahrain', code: 'BH'},
    {name: 'Bangladesh', code: 'BD'},
    {name: 'Barbados', code: 'BB'},
    {name: 'Belarus', code: 'BY'},
    {name: 'Belgium', code: 'BE'},
    {name: 'Belize', code: 'BZ'},
    {name: 'Benin', code: 'BJ'},
    {name: 'Bermuda', code: 'BM'},
    {name: 'Bhutan', code: 'BT'},
    {name: 'Bolivia', code: 'BO'},
    {name: 'Bosnia and Herzegovina', code: 'BA'},
    {name: 'Botswana', code: 'BW'},
    {name: 'Bouvet Island', code: 'BV'},
    {name: 'Brazil', code: 'BR'},
    {name: 'British Indian Ocean Territory', code: 'IO'},
    {name: 'Brunei Darussalam', code: 'BN'},
    {name: 'Bulgaria', code: 'BG'},
    {name: 'Burkina Faso', code: 'BF'},
    {name: 'Burundi', code: 'BI'},
    {name: 'Cambodia', code: 'KH'},
    {name: 'Cameroon', code: 'CM'},
    {name: 'Canada', code: 'CA'},
    {name: 'Cape Verde', code: 'CV'},
    {name: 'Cayman Islands', code: 'KY'},
    {name: 'Central African Republic', code: 'CF'},
    {name: 'Chad', code: 'TD'},
    {name: 'Chile', code: 'CL'},
    {name: 'China', code: 'CN'},
    {name: 'Christmas Island', code: 'CX'},
    {name: 'Cocos (Keeling) Islands', code: 'CC'},
    {name: 'Colombia', code: 'CO'},
    {name: 'Comoros', code: 'KM'},
    {name: 'Congo', code: 'CG'},
    {name: 'Congo, The Democratic Republic of the', code: 'CD'},
    {name: 'Cook Islands', code: 'CK'},
    {name: 'Costa Rica', code: 'CR'},
    {name: '<NAME>', code: 'CI'},
    {name: 'Croatia', code: 'HR'},
    {name: 'Cuba', code: 'CU'},
    {name: 'Cyprus', code: 'CY'},
    {name: 'Czech Republic', code: 'CZ'},
    {name: 'Denmark', code: 'DK'},
    {name: 'Djibouti', code: 'DJ'},
    {name: 'Dominica', code: 'DM'},
    {name: 'Dominican Republic', code: 'DO'},
    {name: 'Ecuador', code: 'EC'},
    {name: 'Egypt', code: 'EG'},
    {name: 'El Salvador', code: 'SV'},
    {name: 'Equatorial Guinea', code: 'GQ'},
    {name: 'Eritrea', code: 'ER'},
    {name: 'Estonia', code: 'EE'},
    {name: 'Ethiopia', code: 'ET'},
    {name: 'Falkland Islands (Malvinas)', code: 'FK'},
    {name: 'Faroe Islands', code: 'FO'},
    {name: 'Fiji', code: 'FJ'},
    {name: 'Finland', code: 'FI'},
    {name: 'France', code: 'FR'},
    {name: 'French Guiana', code: 'GF'},
    {name: 'French Polynesia', code: 'PF'},
    {name: 'French Southern Territories', code: 'TF'},
    {name: 'Gabon', code: 'GA'},
    {name: 'Gambia', code: 'GM'},
    {name: 'Georgia', code: 'GE'},
    {name: 'Germany', code: 'DE'},
    {name: 'Ghana', code: 'GH'},
    {name: 'Gibraltar', code: 'GI'},
    {name: 'Greece', code: 'GR'},
    {name: 'Greenland', code: 'GL'},
    {name: 'Grenada', code: 'GD'},
    {name: 'Guadeloupe', code: 'GP'},
    {name: 'Guam', code: 'GU'},
    {name: 'Guatemala', code: 'GT'},
    {name: 'Guernsey', code: 'GG'},
    {name: 'Guinea', code: 'GN'},
    {name: 'Guinea-Bissau', code: 'GW'},
    {name: 'Guyana', code: 'GY'},
    {name: 'Haiti', code: 'HT'},
    {name: 'Heard Island and Mcdonald Islands', code: 'HM'},
    {name: 'Holy See (Vatican City State)', code: 'VA'},
    {name: 'Honduras', code: 'HN'},
    {name: 'Hong Kong', code: 'HK'},
    {name: 'Hungary', code: 'HU'},
    {name: 'Iceland', code: 'IS'},
    {name: 'India', code: 'IN'},
    {name: 'Indonesia', code: 'ID'},
    {name: 'Iran, Islamic Republic Of', code: 'IR'},
    {name: 'Iraq', code: 'IQ'},
    {name: 'Ireland', code: 'IE'},
    {name: 'Isle of Man', code: 'IM'},
    {name: 'Israel', code: 'IL'},
    {name: 'Italy', code: 'IT'},
    {name: 'Jamaica', code: 'JM'},
    {name: 'Japan', code: 'JP'},
    {name: 'Jersey', code: 'JE'},
    {name: 'Jordan', code: 'JO'},
    {name: 'Kazakhstan', code: 'KZ'},
    {name: 'Kenya', code: 'KE'},
    {name: 'Kiribati', code: 'KI'},
    {name: 'Korea, Democratic People\'s Republic of', code: 'KP'},
    {name: 'Korea, Republic of', code: 'KR'},
    {name: 'Kuwait', code: 'KW'},
    {name: 'Kyrgyzstan', code: 'KG'},
    {name: 'Lao People\'s Democratic Republic', code: 'LA'},
    {name: 'Latvia', code: 'LV'},
    {name: 'Lebanon', code: 'LB'},
    {name: 'Lesotho', code: 'LS'},
    {name: 'Liberia', code: 'LR'},
    {name: '<NAME>', code: 'LY'},
    {name: 'Liechtenstein', code: 'LI'},
    {name: 'Lithuania', code: 'LT'},
    {name: 'Luxembourg', code: 'LU'},
    {name: 'Macao', code: 'MO'},
    {name: 'Macedonia, The Former Yugoslav Republic of', code: 'MK'},
    {name: 'Madagascar', code: 'MG'},
    {name: 'Malawi', code: 'MW'},
    {name: 'Malaysia', code: 'MY'},
    {name: 'Maldives', code: 'MV'},
    {name: 'Mali', code: 'ML'},
    {name: 'Malta', code: 'MT'},
    {name: '<NAME>', code: 'MH'},
    {name: 'Martinique', code: 'MQ'},
    {name: 'Mauritania', code: 'MR'},
    {name: 'Mauritius', code: 'MU'},
    {name: 'Mayotte', code: 'YT'},
    {name: 'Mexico', code: 'MX'},
    {name: 'Micronesia, Federated States of', code: 'FM'},
    {name: 'Moldova, Republic of', code: 'MD'},
    {name: 'Monaco', code: 'MC'},
    {name: 'Mongolia', code: 'MN'},
    {name: 'Montserrat', code: 'MS'},
    {name: 'Morocco', code: 'MA'},
    {name: 'Mozambique', code: 'MZ'},
    {name: 'Myanmar', code: 'MM'},
    {name: 'Namibia', code: 'NA'},
    {name: 'Nauru', code: 'NR'},
    {name: 'Nepal', code: 'NP'},
    {name: 'Netherlands', code: 'NL'},
    {name: 'Netherlands Antilles', code: 'AN'},
    {name: 'New Caledonia', code: 'NC'},
    {name: 'New Zealand', code: 'NZ'},
    {name: 'Nicaragua', code: 'NI'},
    {name: 'Niger', code: 'NE'},
    {name: 'Nigeria', code: 'NG'},
    {name: 'Niue', code: 'NU'},
    {name: 'Norfolk Island', code: 'NF'},
    {name: 'Northern Mariana Islands', code: 'MP'},
    {name: 'Norway', code: 'NO'},
    {name: 'Oman', code: 'OM'},
    {name: 'Pakistan', code: 'PK'},
    {name: 'Palau', code: 'PW'},
    {name: 'Palestinian Territory, Occupied', code: 'PS'},
    {name: 'Panama', code: 'PA'},
    {name: 'Papua New Guinea', code: 'PG'},
    {name: 'Paraguay', code: 'PY'},
    {name: 'Peru', code: 'PE'},
    {name: 'Philippines', code: 'PH'},
    {name: 'Pitcairn', code: 'PN'},
    {name: 'Poland', code: 'PL'},
    {name: 'Portugal', code: 'PT'},
    {name: 'Puerto Rico', code: 'PR'},
    {name: 'Qatar', code: 'QA'},
    {name: 'Reunion', code: 'RE'},
    {name: 'Romania', code: 'RO'},
    {name: 'Russian Federation', code: 'RU'},
    {name: 'Rwanda', code: 'RW'},
    {name: '<NAME>', code: 'SH'},
    {name: '<NAME> and Nevis', code: 'KN'},
    {name: '<NAME>', code: 'LC'},
    {name: '<NAME> and Miquelon', code: 'PM'},
    {name: '<NAME> and the Grenadines', code: 'VC'},
    {name: 'Samoa', code: 'WS'},
    {name: 'San Marino', code: 'SM'},
    {name: '<NAME>', code: 'ST'},
    {name: 'Saudi Arabia', code: 'SA'},
    {name: 'Senegal', code: 'SN'},
    {name: 'Serbia and Montenegro', code: 'CS'},
    {name: 'Seychelles', code: 'SC'},
    {name: 'Sierra Leone', code: 'SL'},
    {name: 'Singapore', code: 'SG'},
    {name: 'Slovakia', code: 'SK'},
    {name: 'Slovenia', code: 'SI'},
    {name: 'Solomon Islands', code: 'SB'},
    {name: 'Somalia', code: 'SO'},
    {name: 'South Africa', code: 'ZA'},
    {name: 'South Georgia and the South Sandwich Islands', code: 'GS'},
    {name: 'Spain', code: 'ES'},
    {name: 'Sri Lanka', code: 'LK'},
    {name: 'Sudan', code: 'SD'},
    {name: 'Suriname', code: 'SR'},
    {name: 'Svalbard and <NAME>', code: 'SJ'},
    {name: 'Swaziland', code: 'SZ'},
    {name: 'Sweden', code: 'SE'},
    {name: 'Switzerland', code: 'CH'},
    {name: 'Syrian Arab Republic', code: 'SY'},
    {name: 'Taiwan, Province of China', code: 'TW'},
    {name: 'Tajikistan', code: 'TJ'},
    {name: 'Tanzania, United Republic of', code: 'TZ'},
    {name: 'Thailand', code: 'TH'},
    {name: 'Timor-Leste', code: 'TL'},
    {name: 'Togo', code: 'TG'},
    {name: 'Tokelau', code: 'TK'},
    {name: 'Tonga', code: 'TO'},
    {name: 'Trinidad and Tobago', code: 'TT'},
    {name: 'Tunisia', code: 'TN'},
    {name: 'Turkey', code: 'TR'},
    {name: 'Turkmenistan', code: 'TM'},
    {name: 'Turks and Caicos Islands', code: 'TC'},
    {name: 'Tuvalu', code: 'TV'},
    {name: 'Uganda', code: 'UG'},
    {name: 'Ukraine', code: 'UA'},
    {name: 'United Arab Emirates', code: 'AE'},
    {name: 'United Kingdom', code: 'GB'},
    {name: 'United States', code: 'US'},
    {name: 'United States Minor Outlying Islands', code: 'UM'},
    {name: 'Uruguay', code: 'UY'},
    {name: 'Uzbekistan', code: 'UZ'},
    {name: 'Vanuatu', code: 'VU'},
    {name: 'Venezuela', code: 'VE'},
    {name: 'Vietnam', code: 'VN'},
    {name: 'Virgin Islands, British', code: 'VG'},
    {name: 'Virgin Islands, U.S.', code: 'VI'},
    {name: 'Wallis and Futuna', code: 'WF'},
    {name: 'Western Sahara', code: 'EH'},
    {name: 'Yemen', code: 'YE'},
    {name: 'Zambia', code: 'ZM'},
    {name: 'Zimbabwe', code: 'ZW'}
  ];
    
    
 	$scope.doSignUp = function(){
		
           //inicia el evento cargando y bloquea la pantalla
        $ionicLoading.show({
			template: '<ion-spinner icon="android"></ion-spinner>'
		}); 
        
         $http({
            method: 'GET',
            url: url_backend + SING_UP,
            params:{'email': $scope.user.email, 'pass': $<PASSWORD>},
            headers: {'Accept': 'application/json'}
         }).success(function(response){
              //Apaga el evento cargando
             $ionicLoading.hide();
//             alert(JSON.stringify(response));
             $scope.user = response;
             //$scope.user.name = response.first_name + ' ' + response.last_name;
             $scope.user_inexistent = true; 
             //$state.go('app.feeds-categories');
        }).error(function(data, status){
                //Apaga el evento cargando
                $ionicLoading.hide();
                if(status == 705){
                   $scope.user_inexistent = true; 
                       
                } else if (status == 707){
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: data.error + ', please login!',
                        okText: 'OK!'
                    }); 
                    $state.go('auth.login');
                } else {
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: status + ' Call service error!',
                        okText: 'OK!'
                    }); 
                }
         
        });
        
	};
    
    $scope.doRegister = function(){
            
           //inicia el evento cargando y bloquea la pantalla
            $ionicLoading.show({
                template: '<ion-spinner icon="android"></ion-spinner>'
            }); 
        
         $http({
            method: 'GET',
            url: url_backend + REGISTER,
            params:{'email': $scope.user.email, 'pass': <PASSWORD>, 'country': $scope.user.country.code, 'name': $scope.user.name, 'job_title': $scope.user.job_title, 'company': $scope.user.company, 'age': $scope.user.age, 'bio': $scope.user.bio},
            headers: {'Accept': 'application/json'}
         }).success(function(response){
              //Apaga el evento cargando
             $ionicLoading.hide();
             //alert(JSON.stringify(response));
             $scope.user = response;
             //$scope.user.name = response.first_name + ' ' + response.last_name;
             $localStorage.user_session = JSON.stringify(response);
             $state.go('app.feeds-categories');
         }).error(function(data, status){
                //Apaga el evento cargando
                $ionicLoading.hide();
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: status + ' Call service error!',
                        okText: 'OK!'
                    }); 
        });
    };
})

.controller('ForgotPasswordCtrl', function($scope, $state) {
	$scope.recoverPassword = function(){
		$state.go('app.feeds-categories');
	};

	$scope.user = {};
})

.controller('ProfileCtrl', function($scope, $state, $http, $localStorage, $ionicLoading, $ionicPopup) {
	
    $scope.user = JSON.parse($localStorage.user_session);
    
    
     $scope.doUpdate = function(){
            
           //inicia el evento cargando y bloquea la pantalla
            $ionicLoading.show({
                template: '<ion-spinner icon="android"></ion-spinner>'
            }); 
        
         $http({
            method: 'GET',
            url: url_backend + UPDATE_USER,
            params:{'shared_user': $scope.user.shared_user, 'persistence_token': $scope.user.persistence_token},
            headers: {'Accept': 'application/json'}
         }).success(function(response){
              //Apaga el evento cargando
             $ionicLoading.hide();
             //alert(JSON.stringify(response));
         }).error(function(data, status){
                //Apaga el evento cargando
                $ionicLoading.hide();
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: status + ' Call service error!',
                        okText: 'OK!'
                    }); 
        });
    };
    
})


.controller('SponsorsCtrl', function($scope, $state, $http, $localStorage) {
	$scope.sponsors = {};

	$http.get('sponsors.json').success(function(response) {
		$scope.sponsors = response.sponsors;
	});
})
    
.controller('LogoffCtrl', function($scope, $state, $http, $localStorage) {
	
    delete $localStorage.user_session;
    $scope.user = {};
    $state.go("auth.walkthrough");
})

.controller('ProfileUserCtrl', function($scope, $state, $http, $stateParams, $localStorage, $ionicLoading, $ionicPopup) {
    
    $scope.user = JSON.parse($localStorage.user_session);
    $scope.userId = $stateParams.user_Id;
    $scope.user_det = {};

    $scope.getUserby = function(){
            
           //inicia el evento cargando y bloquea la pantalla
            $ionicLoading.show({
                template: '<ion-spinner icon="android"></ion-spinner>'
            }); 
        
         $http({
            method: 'GET',
            url: url_backend + USER_BY,
            params:{'user_id': $scope.userId, 'persistence_token': $scope.user.persistence_token},
            headers: {'Accept': 'application/json'}
         }).success(function(response){
              //Apaga el evento cargando
             $ionicLoading.hide();
             //alert(JSON.stringify(response));
             $scope.user_det = response;
         }).error(function(data, status){
                //Apaga el evento cargando
                $ionicLoading.hide();
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: status + ' Call service error!',
                        okText: 'OK!'
                    }); 
        });
    };
	
})

.controller('RateApp', function($scope) {
	$scope.rateApp = function(){
		if(ionic.Platform.isIOS()){
			//you need to set your own ios app id
			AppRate.preferences.storeAppURL.ios = '1234555553>';
			AppRate.promptForRating(true);
		}else if(ionic.Platform.isAndroid()){
			//you need to set your own android app id
			AppRate.preferences.storeAppURL.android = 'market://details?id=ionFB';
			AppRate.promptForRating(true);
		}
	};
})

.controller('SendMailCtrl', function($scope) {
	$scope.sendMail = function(){
		cordova.plugins.email.isAvailable(
			function (isAvailable) {
				// alert('Service is not available') unless isAvailable;
				cordova.plugins.email.open({
					to:      '<EMAIL>',
					cc:      '<EMAIL>',
					// bcc:     ['<EMAIL>', '<EMAIL>'],
					subject: 'Greetings',
					body:    'How are you? Nice greetings from IonFullApp'
				});
			}
		);
	};
})

.controller('MapsCtrl', function($scope, $ionicLoading) {

	$scope.info_position = {
		lat: 43.07493,
		lng: -89.381388
	};

	$scope.center_position = {
		lat: 43.07493,
		lng: -89.381388
	};

	$scope.my_location = "";

	$scope.$on('mapInitialized', function(event, map) {
		$scope.map = map;
	});

	$scope.centerOnMe= function(){

		$scope.positions = [];

		$ionicLoading.show({
			template: 'Loading...'
		});

		// with this function you can get the user’s current position
		// we use this plugin: https://github.com/apache/cordova-plugin-geolocation/
		navigator.geolocation.getCurrentPosition(function(position) {
			var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			$scope.current_position = {lat: pos.G,lng: pos.K};
			$scope.my_location = pos.G+", "+pos.K;
			$scope.map.setCenter(pos);
			$ionicLoading.hide();
		});
	};
})

.controller('AdsCtrl', function($scope, $ionicActionSheet, AdMob, iAd) {

	$scope.manageAdMob = function() {

		// Show the action sheet
		var hideSheet = $ionicActionSheet.show({
			//Here you can add some more buttons
			buttons: [
				{ text: 'Show Banner' },
				{ text: 'Show Interstitial' }
			],
			destructiveText: 'Remove Ads',
			titleText: 'Choose the ad to show',
			cancelText: 'Cancel',
			cancel: function() {
				// add cancel code..
			},
			destructiveButtonClicked: function() {
				console.log("removing ads");
				AdMob.removeAds();
				return true;
			},
			buttonClicked: function(index, button) {
				if(button.text == 'Show Banner')
				{
					console.log("show banner");
					AdMob.showBanner();
				}

				if(button.text == 'Show Interstitial')
				{
					console.log("show interstitial");
					AdMob.showInterstitial();
				}

				return true;
			}
		});
	};

	$scope.manageiAd = function() {

		// Show the action sheet
		var hideSheet = $ionicActionSheet.show({
			//Here you can add some more buttons
			buttons: [
			{ text: 'Show iAd Banner' },
			{ text: 'Show iAd Interstitial' }
			],
			destructiveText: 'Remove Ads',
			titleText: 'Choose the ad to show - Interstitial only works in iPad',
			cancelText: 'Cancel',
			cancel: function() {
				// add cancel code..
			},
			destructiveButtonClicked: function() {
				console.log("removing ads");
				iAd.removeAds();
				return true;
			},
			buttonClicked: function(index, button) {
				if(button.text == 'Show iAd Banner')
				{
					console.log("show iAd banner");
					iAd.showBanner();
				}
				if(button.text == 'Show iAd Interstitial')
				{
					console.log("show iAd interstitial");
					iAd.showInterstitial();
				}
				return true;
			}
		});
	};
})

// FEED
//brings all feed categories
.controller('FeedsCategoriesCtrl', function($scope, $state, $localStorage, $http, $ionicLoading, $ionicPopup) {
	$scope.events = [];

	 //inicia el evento cargando y bloquea la pantalla
            $ionicLoading.show({
                template: '<ion-spinner icon="android"></ion-spinner>'
            }); 
        
         $http({
            method: 'GET',
            url: url_backend + EVENTS,
            params:{'id': $localStorage.forumId, 'persistence_token': $scope.user.persistence_token},
            headers: {'Accept': 'application/json'}
         }).success(function(response){
              //Apaga el evento cargando
             $ionicLoading.hide();
             //console.log(JSON.stringify(response));
             $scope.events = response;
         }).error(function(data, status){
                //Apaga el evento cargando
                $ionicLoading.hide();
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: status + ' Call service error!',
                        okText: 'OK!'
                    }); 
        });
    
})

//brings all contacts
.controller('MembersCtrl', function($scope, $state, $templateCache, $q, $rootScope, $localStorage, $http, $ionicLoading, $ionicPopup) {
	$scope.members = [];
	$scope.total_members = "";

       //inicia el evento cargando y bloquea la pantalla
            $ionicLoading.show({
                template: '<ion-spinner icon="android"></ion-spinner>'
            }); 
        
         $http({
            method: 'GET',
            url: url_backend + FORUM_MEMBERS,
            params:{'id': $localStorage.forumId, 'persistence_token': $scope.user.persistence_token},
            headers: {'Accept': 'application/json'}
         }).success(function(response){
              //Apaga el evento cargando
             $ionicLoading.hide();
             //console.log(JSON.stringify(response));
             $scope.members = response.members;
		     $scope.total_members = response.total_members;
         }).error(function(data, status){
                //Apaga el evento cargando
                $ionicLoading.hide();
                    $ionicPopup.alert({
                        title: 'Ups!',
                        template: status + ' Call service error!',
                        okText: 'OK!'
                    }); 
        });
    
    
})

.controller('ForumSurveyCtrl', function($scope, $http, $localStorage) {
	$scope.survey_url = $localStorage.forum_survey_url;

})


// FORUM
//bring specific forum providers
.controller('EventDetailCtrl', function($scope, $http, $stateParams, $cordovaSocialSharing, $sce) {
	$scope.event_sources = [];
    $scope.showfooter = false;
	$scope.eventId = $stateParams.eventId;
    $scope.rate = 3;
    $scope.max = 5;
    
  
	$http.get('eventdetail.json').success(function(response) {
		var event = _.find(response, {id: $scope.eventId});
		$scope.eventTitle = event.title;
		$scope.event_sources = event;
        $scope.event_survey_url = $sce.trustAsResourceUrl($scope.event_sources.survey_url);
	});
    

    $scope.sendComment = function() {
        alert($scope.msgcomment);
    };  
    
    $scope.shareit = function() {
        var subject = "Hey, I'm RedhatForum!";
        var message = $scope.event_sources.message_to_share;
        var link = $scope.event_sources.link_to_share;
        
        $cordovaSocialSharing.share(message, subject, null, link) // Share via native share sheet
        .then(function(result) {
          // Success!
        }, function(err) {
          // An error occured. Show a message to the user
            console.error(err);
        });

    };
})

//bring specific category providers
.controller('CategoryFeedsCtrl', function($scope, $http, $stateParams) {
	$scope.category_sources = [];

	$scope.categoryId = $stateParams.categoryId;

	$http.get('feeds-categories.json').success(function(response) {
		var category = _.find(response, {id: $scope.categoryId});
		$scope.categoryTitle = category.title;
		$scope.category_sources = category.feed_sources;
	});
})

//this method brings posts for a source provider
.controller('FeedEntriesCtrl', function($scope, $stateParams, $http, FeedList, $q, $ionicLoading, BookMarkService) {
	$scope.feed = [];

	var categoryId = $stateParams.categoryId,
			sourceId = $stateParams.sourceId;

	$scope.doRefresh = function() {

		$http.get('feeds-categories.json').success(function(response) {

			$ionicLoading.show({
				template: 'Loading entries...'
			});

			var category = _.find(response, {id: categoryId }),
					source = _.find(category.feed_sources, {id: sourceId });

			$scope.sourceTitle = source.title;

			FeedList.get(source.url)
			.then(function (result) {
				$scope.feed = result.feed;
				$ionicLoading.hide();
				$scope.$broadcast('scroll.refreshComplete');
			}, function (reason) {
				$ionicLoading.hide();
				$scope.$broadcast('scroll.refreshComplete');
			});
		});
	};

	$scope.doRefresh();

	$scope.bookmarkPost = function(post){
		$ionicLoading.show({ template: 'Post Saved!', noBackdrop: true, duration: 1000 });
		BookMarkService.bookmarkFeedPost(post);
	};
})

// SETTINGS
.controller('SettingsCtrl', function($scope, $ionicActionSheet, $state) {
	$scope.airplaneMode = true;
	$scope.wifi = false;
	$scope.bluetooth = true;
	$scope.personalHotspot = true;

	$scope.checkOpt1 = true;
	$scope.checkOpt2 = true;
	$scope.checkOpt3 = false;

	$scope.radioChoice = 'B';

	// Triggered on a the logOut button click
	$scope.showLogOutMenu = function() {

		// Show the action sheet
		var hideSheet = $ionicActionSheet.show({
			//Here you can add some more buttons
			// buttons: [
			// { text: '<b>Share</b> This' },
			// { text: 'Move' }
			// ],
			destructiveText: 'Logout',
			titleText: 'Are you sure you want to logout? This app is awsome so I recommend you to stay.',
			cancelText: 'Cancel',
			cancel: function() {
				// add cancel code..
			},
			buttonClicked: function(index) {
				//Called when one of the non-destructive buttons is clicked,
				//with the index of the button that was clicked and the button object.
				//Return true to close the action sheet, or false to keep it opened.
				return true;
			},
			destructiveButtonClicked: function(){
				//Called when the destructive button is clicked.
				//Return true to close the action sheet, or false to keep it opened.
				$state.go('auth.walkthrough');
			}
		});

	};
})

// TINDER CARDS
//.controller('TinderCardsCtrl', function($scope, $http) {
//
//	$scope.cards = [];
//
//
//	$scope.addCard = function(img, name) {
//		var newCard = {image: img, name: name};
//		newCard.id = Math.random();
//		$scope.cards.unshift(angular.extend({}, newCard));
//	};
//
//	$scope.addCards = function(count) {
//		$http.get('http://api.randomuser.me/?results=' + count).then(function(value) {
//			angular.forEach(value.data.results, function (v) {
//				$scope.addCard(v.user.picture.large, v.user.name.first + " " + v.user.name.last);
//			});
//		});
//	};
//
//	$scope.addFirstCards = function() {
//		$scope.addCard("https://dl.dropboxusercontent.com/u/30675090/envato/tinder-cards/left.png","Nope");
//		$scope.addCard("https://dl.dropboxusercontent.com/u/30675090/envato/tinder-cards/right.png", "Yes");
//	};
//
//	$scope.addFirstCards();
//	$scope.addCards(5);
//
//	$scope.cardDestroyed = function(index) {
//		$scope.cards.splice(index, 1);
//		$scope.addCards(1);
//	};
//
//	$scope.transitionOut = function(card) {
//		console.log('card transition out');
//	};
//
//	$scope.transitionRight = function(card) {
//		console.log('card removed to the right');
//		console.log(card);
//	};
//
//	$scope.transitionLeft = function(card) {
//		console.log('card removed to the left');
//		console.log(card);
//	};
//})


// BOOKMARKS
.controller('BookMarksCtrl', function($scope, $rootScope, BookMarkService, $state) {

	$scope.bookmarks = BookMarkService.getBookmarks();

	// When a new post is bookmarked, we should update bookmarks list
	$rootScope.$on("new-bookmark", function(event){
		$scope.bookmarks = BookMarkService.getBookmarks();
	});

	$scope.goToFeedPost = function(link){
		window.open(link, '_blank', 'location=yes');
	};
	$scope.goToWordpressPost = function(postId){
		$state.go('app.post', {postId: postId});
	};
})

// WORDPRESS
.controller('WordpressCtrl', function($scope, $http, $ionicLoading, PostService, BookMarkService) {
	$scope.posts = [];
	$scope.page = 1;
	$scope.totalPages = 1;

	$scope.doRefresh = function() {
		$ionicLoading.show({
			template: 'Loading posts...'
		});

		//Always bring me the latest posts => page=1
		PostService.getRecentPosts(1)
		.then(function(data){
			$scope.totalPages = data.pages;
			$scope.posts = PostService.shortenPosts(data.posts);

			$ionicLoading.hide();
			$scope.$broadcast('scroll.refreshComplete');
		});
	};

	$scope.loadMoreData = function(){
		$scope.page += 1;

		PostService.getRecentPosts($scope.page)
		.then(function(data){
			//We will update this value in every request because new posts can be created
			$scope.totalPages = data.pages;
			var new_posts = PostService.shortenPosts(data.posts);
			$scope.posts = $scope.posts.concat(new_posts);

			$scope.$broadcast('scroll.infiniteScrollComplete');
		});
	};

	$scope.moreDataCanBeLoaded = function(){
		return $scope.totalPages > $scope.page;
	};

	$scope.bookmarkPost = function(post){
		$ionicLoading.show({ template: 'Post Saved!', noBackdrop: true, duration: 1000 });
		BookMarkService.bookmarkWordpressPost(post);
	};

	$scope.doRefresh();
})

// WORDPRESS POST
.controller('WordpressPostCtrl', function($scope, post_data, $ionicLoading) {

	$scope.post = post_data.post;
	$ionicLoading.hide();

	$scope.sharePost = function(link){
		window.plugins.socialsharing.share('Check this post here: ', null, null, link);
	};
})


.controller('ImagePickerCtrl', function($scope, $rootScope, $cordovaCamera) {

	$scope.images = [];

	$scope.selImages = function() {

		window.imagePicker.getPictures(
			function(results) {
				for (var i = 0; i < results.length; i++) {
					console.log('Image URI: ' + results[i]);
					$scope.images.push(results[i]);
				}
				if(!$scope.$$phase) {
					$scope.$apply();
				}
			}, function (error) {
				console.log('Error: ' + error);
			}
		);
	};

	$scope.removeImage = function(image) {
		$scope.images = _.without($scope.images, image);
	};

	$scope.shareImage = function(image) {
		window.plugins.socialsharing.share(null, null, image);
	};

	$scope.shareAll = function() {
		window.plugins.socialsharing.share(null, null, $scope.images);
	};
})

;
