var importedPackages = ["keosu-last-article","keosu-base","angularJs","jQuery","keosu-push","keosu-menu"];
var app = angular.module('keosuApp', ['angular-chrono', 'angularSpinner','angular-carousel','ngSanitize', 'ngTouch', 'ngRoute','angular-inview','LocalStorageModule','CacheManagerModule']);

app.controller('main_Controller', function($http, $scope) {
		$http.get('data/globalParam.json').success( function (data) {
			$scope.appName = data.name;
		}); 
		//alert("Connection :"+navigator.connection.type);
		$scope.offline=false;
		document.addEventListener("offline",
				function(){
					$scope.offline=true;
					alert("Network unreachable. The page will be reload soon as possible.");
					document.addEventListener("online",function(){
						$scope.offline=false;
						alert("Reconnection !");
						document.removeEventListener("online",function(){},false);
						location.reload();
				}, false);
		}, false);
});

// Don't forget to take a look at exportListener.php before edit this file
app.directive('keosuPush', function(){
	return {
		restrict : 'E',
		templateUrl : 'plugins/keosu-push/templates/default.html',
		controller : ['$scope','$http', function ($scope, $http) {

			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

			$scope.init = function() {
				console.log('function init');
				document.addEventListener('deviceready', function() {
					console.log('i\'m ready');
					// if push notification is enabled
					pushNotification = window.plugins.pushNotification;
					if(typeof(device) != 'undefined' && typeof(pushNotificationData) != 'undefined') {
						$http.get('data/globalParam.json').success(function(data) {
							$scope.host = data.host;
							if(device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos") {
								$scope.androidPush();
							} else {
								$scope.applePush();
							}
						});
					}
				},false);
			};

			////////////////////////
			// Android part
			////////////////////////
			$scope.androidPush = function() {
				appAndroid = {
					successHandler: function(result) {
						console.log("Push success : "+result);
					},
					errorHandler: function(error) {
						console.log("Push error : "+error);
					},
					onNotification: function(e) {
						switch( e.event ) {
							case 'registered':
							if ( e.regid.length > 0 ) {
								$http.post($scope.host+'service/push/plugin/addDevice/2','token='+e.regid);
							}
							break;

							case 'message':
							// this is the actual push notification. its format depends on the data model from the push server
							console.log('message = '+e.message+' msgcnt = '+e.msgcnt);
							break;

							case 'error':
							console.log('GCM error = '+e.msg);
							break;

							default:
							console.log('An unknown GCM event has occurred');
							break;
						}
					}
				};

				pushNotification.register(
					appAndroid.successHandler,
					appAndroid.errorHandler,
					{'senderID':pushNotificationData.senderID+"",'ecb': "appAndroid.onNotification" }
				);
			};
		
			/////////////////////
			// Apple part
			/////////////////////
			$scope.applePush = function() {
				console.log('I\'m an Iphone...');
				appPushNotification = {
					tokenHandler: function(result) {
						console.log('iphone id');
						console.log(result);
						if( result.length > 0 ) {
							$http.post($scope.host+'service/push/plugin/addDevice/1','token='+result);
						}
					},
					errorHandler: function(error){console.log('the eoor is '+error)},
					onNotificationAPN: function(event) {
						if( event.alert )
							navigator.notification.alert(event.alert);
						if( event.sound ) {
							var snd = new Media(event.sound);
							snd.play();
						}
						if( event.badge )
							pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
					}
				};

				pushNotification.register(
					appPushNotification.tokenHandler,
					appPushNotification.errorHandler,
					{
						'badge' : 'true',
						'sound' : 'true',
						'alert' : 'true',
						'ecb'   : 'appPushNotification.onNotificationAPN'
					}
				);
			};

		}]
	};
});


app.config(function($routeProvider,$locationProvider){
	$routeProvider.when("/Page/:pageName",{
		templateUrl: function(params) {
			return params.pageName+".html";
		}
	})
	.otherwise({redirectTo:"/Page/1"});
});/************************************************************************
	Pockeit is an open source CMS for mobile app
	Copyright (C) 2013  Vincent Le Borgne

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ************************************************************************/



//Main function
app.controller('keosu-last-articleController', function ($scope, $http, $sce, usSpinnerService, cacheManagerService) {	

	$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

	$scope.parts = function (isList, isArticle) {
		$scope.isList = isList;
		$scope.isArticle = isArticle;
	}
	$scope.close = function () {
		$scope.slide="fadeIn";
		$scope.parts(true, false);
		
	};
	$scope.open = function (page) {
		$scope.article = page;
		$scope.parts(false, true);
	};
	$scope.next = function(){
		if(!$scope.isLastPage){
			$scope.isFirstPage = true;
			$scope.isLastPage = true;
			$scope.slide="slideInRight";
			$scope.activePage++;
			$scope.getPage($scope.activePage,true);
		}
		
	};
	$scope.previous = function(){
		if(!$scope.isFirstPage){
			$scope.isFirstPage = true;
			$scope.isLastPage = true;
			$scope.slide="slideInLeft";
			$scope.activePage--;
			$scope.getPage($scope.activePage,true);
		}
	};
	$scope.more = function(){
		$scope.activePage++;
		$scope.getPage($scope.activePage,false);
	}
	/*
	 * @pageNum : page number requested.
	 * @resetPages : if true, clean the array pages. 
	 */
	$scope.getPage = function(pageNum,resetPages){
		if(resetPages){
			$scope.pages = [];
		}
		usSpinnerService.spin('spinner'); // While loading, there will be a spinner
		cacheManagerService.get($scope.param.host+'service/gadget/lastarticle/'+$scope.param.gadgetId+'/'+pageNum+'/json').success(function(data) {
			usSpinnerService.stop('spinner');
			$scope.isFirstPage = data.isFirst;
			$scope.isLastPage = data.isLast;
			start = $scope.pages.length;
			for (i = 0; i < data.data.length; i++) {
				$scope.pages[start+i] = data.data[i];
				$scope.pages[start+i].content = $sce.trustAsHtml(decodedContent(data.data[i].content));
				$scope.pages[start+i].title = decodedContent(data.data[i].title);
			}	
		});
	}
	$scope.init = function (params){
		$scope.slide="fadeIn";
		$scope.param = params;
		$scope.pages = new Array();
		$scope.parts(true, false);
		$scope.activePage=0;
		$scope.isFirstPage = true;
		$scope.isLastPage = true;
		$scope.getPage($scope.activePage,true);
	};
});

/************************************************************************
	Keosu is an open source CMS for mobile app
	Copyright (C) 2013  Vincent Le Borgne

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ************************************************************************/
app.controller('keosu-menuController', function ($scope, $http,$location) {
	$scope.init = function (params) {
		$scope.pages = params.gadgetParam.pages;
	};

	// @see https://stackoverflow.com/questions/12592472/how-to-highlight-a-current-menu-item-in-angularjs
	$scope.getClass = function(page) {
		return $location.path() == "/Page/"+page ? "active" : ""
	}
});
