angular.module('mediaModalTemplates', []).run(['$templateCache', function($templateCache) {
  'use strict';

  $templateCache.put('camera.html',
    "<div ng-controller=\"cameraController\" class=\"media-resource1\">\n" +
    "    <h3>Upload Media</h3>\n" +
    "    <div>\n" +
    "        <form id=\"fileupload\" action=\"{{upload_url}}\" method=\"POST\" enctype=\"multipart/form-data\" data-file-upload=\"options\" data-ng-class=\"{'fileupload-processing': processing() || loadingFiles}\">\n" +
    "            <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->\n" +
    "            <div class=\"row fileupload-buttonbar\">\n" +
    "                <div class=\"col-lg-7\">\n" +
    "                    <!-- The fileinput-button span is used to style the file input field as button -->\n" +
    "                            <span class=\"btn btn-success fileinput-button\" ng-class=\"{disabled: disabled}\">\n" +
    "                                <i class=\"glyphicon glyphicon-plus\"></i>\n" +
    "                                <span>Add files...</span>\n" +
    "                                <input type=\"file\" name=\"files[]\" multiple ng-disabled=\"disabled\" accept=\"image/*\" capture=\"camera\">\n" +
    "                            </span>\n" +
    "                    <button type=\"button\" class=\"btn btn-primary start\" data-ng-click=\"submit()\">\n" +
    "                        <i class=\"glyphicon glyphicon-upload\"></i>\n" +
    "                        <span>Start upload</span>\n" +
    "                    </button>\n" +
    "                    <button type=\"button\" class=\"btn btn-warning cancel\" data-ng-click=\"cancel()\">\n" +
    "                        <i class=\"glyphicon glyphicon-ban-circle\"></i>\n" +
    "                        <span>Cancel upload</span>\n" +
    "                    </button>\n" +
    "                    <!-- The global file processing state -->\n" +
    "                    <span class=\"fileupload-process\"></span>\n" +
    "                </div>\n" +
    "                <!-- The global progress state -->\n" +
    "                <div class=\"col-lg-5 fade\" data-ng-class=\"{in: active()}\">\n" +
    "                    <!-- The global progress bar -->\n" +
    "                    <div class=\"progress progress-striped active\" data-file-upload-progress=\"progress()\"><div class=\"progress-bar progress-bar-success\" data-ng-style=\"{width: num + '%'}\"></div></div>\n" +
    "                    <!-- The extended global progress state -->\n" +
    "                    <div class=\"progress-extended\">&nbsp;</div>\n" +
    "                </div>\n" +
    "            </div>\n" +
    "            <div>\n" +
    "                <div class=\"row media-resource files ng-cloak\">\n" +
    "                    <div ng-repeat=\"file in queue\" class=\"image-container\" ng-click=\"selectImage(file)\" data-ng-class=\"{'processing': file.$processing()}\">\n" +
    "                        <div class=\"col-xs-6 col-sm-3 col-md-2 col-lg-2\">\n" +
    "                            <div class=\"media-wrapper\" ng-class=\"{selected: file.selected}\">\n" +
    "                                <div class=\"image-wrapper\">\n" +
    "                                    <div class=\"centered\">\n" +
    "                                        <img ng-src=\"{{file.url}}\" class=\"img-responsive\"/>\n" +
    "                                    </div>\n" +
    "                                </div>\n" +
    "                                <div class=\"image-title\">{{file.name}}</div>\n" +
    "                            </div>\n" +
    "                            <div class=\"progress progress-striped active fade\" data-ng-class=\"{pending: 'in'}[file.$state()]\" data-file-upload-progress=\"file.$progress()\">\n" +
    "                                <div class=\"progress-bar progress-bar-success\" data-ng-style=\"{width: num + '%'}\"></div>\n" +
    "                            </div>\n" +
    "                            <div class=\"text-center\">\n" +
    "                                <button class=\"btn btn-primary\" data-ng-controller=\"FileDestroyController\" data-ng-click=\"file.$destroy()\" data-ng-hide=\"!file.$destroy\">\n" +
    "                                    <i class=\"fa fa-trash\"></i> Delete\n" +
    "                                </button>\n" +
    "                            </div>\n" +
    "                        </div>\n" +
    "\n" +
    "                    </div>\n" +
    "                    <div ng-repeat=\"file in filequeue\" class=\"image-container\" ng-click=\"selectImage(file)\" data-ng-class=\"{'processing': file.$processing()}\">\n" +
    "                        <div class=\"col-xs-6 col-sm-3 col-md-2 col-lg-2\">\n" +
    "                            <div class=\"media-wrapper\" ng-class=\"{selected: file.selected}\">\n" +
    "                                <div class=\"image-wrapper\">\n" +
    "                                    <div class=\"centered\">\n" +
    "                                        <img ng-src=\"{{file.url}}\" class=\"img-responsive\"/>\n" +
    "                                    </div>\n" +
    "                                </div>\n" +
    "                                <div class=\"image-title\">{{file.name}}</div>\n" +
    "                            </div>\n" +
    "                            <div class=\"progress progress-striped active fade\" data-ng-class=\"{pending: 'in'}[file.$state()]\" data-file-upload-progress=\"file.$progress()\">\n" +
    "                                <div class=\"progress-bar progress-bar-success\" data-ng-style=\"{width: num + '%'}\"></div>\n" +
    "                            </div>\n" +
    "                            <div class=\"text-center\">\n" +
    "                                <button class=\"btn btn-primary\" data-ng-controller=\"FileDestroyController\" data-ng-click=\"file.$destroy()\" data-ng-hide=\"!file.$destroy\">\n" +
    "                                    <i class=\"fa fa-trash\"></i> Delete\n" +
    "                                </button>\n" +
    "                            </div>\n" +
    "                        </div>\n" +
    "\n" +
    "                    </div>\n" +
    "\n" +
    "                </div>\n" +
    "            </div>\n" +
    "        </form>\n" +
    "    </div>\n" +
    "</div>"
  );


  $templateCache.put('gallery.html',
    "<div class=\"container-fluid\" id=\"otonomic-media-modal\">\n" +
    "    <uib-tabset>\n" +
    "        <uib-tab ng-repeat=\"resource in availableResources\" select=\"tabSelected(resource)\">\n" +
    "            <uib-tab-heading>\n" +
    "                <i ng-class=\"resource.icon\"></i>\n" +
    "                <span>{{resource.title}}</span>\n" +
    "            </uib-tab-heading>\n" +
    "            <div ng-include=\"resource.viewPath\"></div>\n" +
    "        </uib-tab>\n" +
    "    </uib-tabset>\n" +
    "</div>\n" +
    "<span us-spinner spinner-on=\"appState.loading\"></span>"
  );


  $templateCache.put('galleryWindow.html',
    "<div class=\"modal-header\">\n" +
    "    <h2 class=\"modal-title\">Add Image</h2>\n" +
    "</div>\n" +
    "<div class=\"modal-body\">\n" +
    "    <div ng-include=\"'gallery.html'\"></div>\n" +
    "</div>\n" +
    "<div class=\"modal-footer\">\n" +
    "    <button class=\"btn btn-default\" type=\"button\" ng-click=\"cancel()\"><i class=\"fa fa-remove\"></i>Cancel</button>\n" +
    "    <button class=\"btn btn-primary\" type=\"button\" ng-click=\"selectImages()\" data-ng-disabled=\"!selectedImages.length\"><i class=\"fa fa-ok\"></i>Add Images</button>\n" +
    "</div>"
  );


  $templateCache.put('upload.html',
    "<div ng-controller=\"uploadController\" class=\"media-resource1\">\n" +
    "    <h3>Upload Media</h3>\n" +
    "    <div>\n" +
    "        <form id=\"fileupload\" action=\"{{upload_url}}\" method=\"POST\" enctype=\"multipart/form-data\" data-file-upload=\"options\" data-ng-class=\"{'fileupload-processing': processing() || loadingFiles}\">\n" +
    "            <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->\n" +
    "            <div class=\"row fileupload-buttonbar\">\n" +
    "                <div class=\"col-lg-7\">\n" +
    "                    <!-- The fileinput-button span is used to style the file input field as button -->\n" +
    "                            <span class=\"btn btn-success fileinput-button\" ng-class=\"{disabled: disabled}\">\n" +
    "                                <i class=\"glyphicon glyphicon-plus\"></i>\n" +
    "                                <span>Add files...</span>\n" +
    "                                <input type=\"file\" name=\"files[]\" multiple ng-disabled=\"disabled\">\n" +
    "                            </span>\n" +
    "                    <button type=\"button\" class=\"btn btn-primary start\" data-ng-click=\"submit()\">\n" +
    "                        <i class=\"glyphicon glyphicon-upload\"></i>\n" +
    "                        <span>Start upload</span>\n" +
    "                    </button>\n" +
    "                    <button type=\"button\" class=\"btn btn-warning cancel\" data-ng-click=\"cancel()\">\n" +
    "                        <i class=\"glyphicon glyphicon-ban-circle\"></i>\n" +
    "                        <span>Cancel upload</span>\n" +
    "                    </button>\n" +
    "                    <!-- The global file processing state -->\n" +
    "                    <span class=\"fileupload-process\"></span>\n" +
    "                </div>\n" +
    "                <!-- The global progress state -->\n" +
    "                <div class=\"col-lg-5 fade\" data-ng-class=\"{in: active()}\">\n" +
    "                    <!-- The global progress bar -->\n" +
    "                    <div class=\"progress progress-striped active\" data-file-upload-progress=\"progress()\"><div class=\"progress-bar progress-bar-success\" data-ng-style=\"{width: num + '%'}\"></div></div>\n" +
    "                    <!-- The extended global progress state -->\n" +
    "                    <div class=\"progress-extended\">&nbsp;</div>\n" +
    "                </div>\n" +
    "            </div>\n" +
    "            <div>\n" +
    "                <div class=\"row media-resource files ng-cloak\">\n" +
    "                    <div ng-repeat=\"file in queue\" class=\"image-container\" ng-click=\"selectImage(file)\" data-ng-class=\"{'processing': file.$processing()}\">\n" +
    "                        <div class=\"col-xs-6 col-sm-3 col-md-2 col-lg-2\">\n" +
    "                            <div class=\"media-wrapper\" ng-class=\"{selected: file.selected}\">\n" +
    "                                <div class=\"image-wrapper\">\n" +
    "                                    <div class=\"centered\">\n" +
    "                                        <img ng-src=\"{{file.url}}\" class=\"img-responsive\"/>\n" +
    "                                    </div>\n" +
    "                                </div>\n" +
    "                                <div class=\"image-title\">{{file.name}}</div>\n" +
    "                            </div>\n" +
    "                            <div class=\"progress progress-striped active fade\" data-ng-class=\"{pending: 'in'}[file.$state()]\" data-file-upload-progress=\"file.$progress()\">\n" +
    "                                <div class=\"progress-bar progress-bar-success\" data-ng-style=\"{width: num + '%'}\"></div>\n" +
    "                            </div>\n" +
    "                            <div class=\"text-center\">\n" +
    "                                <button class=\"btn btn-primary\" data-ng-controller=\"FileDestroyController\" data-ng-click=\"file.$destroy()\" data-ng-hide=\"!file.$destroy\">\n" +
    "                                    <i class=\"fa fa-trash\"></i> Delete\n" +
    "                                </button>\n" +
    "                            </div>\n" +
    "                        </div>\n" +
    "\n" +
    "                    </div>\n" +
    "                    <div ng-repeat=\"file in filequeue\" class=\"image-container\" ng-click=\"selectImage(file)\" data-ng-class=\"{'processing': file.$processing()}\">\n" +
    "                        <div class=\"col-xs-6 col-sm-3 col-md-2 col-lg-2\">\n" +
    "                            <div class=\"media-wrapper\" ng-class=\"{selected: file.selected}\">\n" +
    "                                <div class=\"image-wrapper\">\n" +
    "                                    <div class=\"centered\">\n" +
    "                                        <img ng-src=\"{{file.url}}\" class=\"img-responsive\"/>\n" +
    "                                    </div>\n" +
    "                                </div>\n" +
    "                                <div class=\"image-title\">{{file.name}}</div>\n" +
    "                            </div>\n" +
    "                            <div class=\"progress progress-striped active fade\" data-ng-class=\"{pending: 'in'}[file.$state()]\" data-file-upload-progress=\"file.$progress()\">\n" +
    "                                <div class=\"progress-bar progress-bar-success\" data-ng-style=\"{width: num + '%'}\"></div>\n" +
    "                            </div>\n" +
    "                            <div class=\"text-center\">\n" +
    "                                <button class=\"btn btn-primary\" data-ng-controller=\"FileDestroyController\" data-ng-click=\"file.$destroy()\" data-ng-hide=\"!file.$destroy\">\n" +
    "                                    <i class=\"fa fa-trash\"></i> Delete\n" +
    "                                </button>\n" +
    "                            </div>\n" +
    "                        </div>\n" +
    "\n" +
    "                    </div>\n" +
    "\n" +
    "                </div>\n" +
    "            </div>\n" +
    "        </form>\n" +
    "    </div>\n" +
    "</div>"
  );


  $templateCache.put('webService.html',
    "<div ng-controller=\"webServicesController\" ng-init=\"setWebServiceType(resource.webServiceType)\">\n" +
    "    <h3><i ng-class=\"resource.icon\"></i>{{resource.title}}</h3>\n" +
    "    <form ng-submit='search()'>\n" +
    "        <div class=\"input-group search-container\" ng-show=\"showSearcher()\">\n" +
    "            <input type=\"text\" class=\"form-control\" ng-model=\"imageFilter\" placeholder=\"search\"/>\n" +
    "            <span class=\"input-group-btn\">\n" +
    "               <button type=\"submit\" class=\"btn btn-primary\" ng-click='search()'>\n" +
    "                   <i class=\"fa fa-search\"></i>\n" +
    "               </button>\n" +
    "            </span>\n" +
    "        </div>\n" +
    "    </form>\n" +
    "\n" +
    "    <div class=\"row media-resource\">\n" +
    "        <div ng-repeat=\"image in images\" class=\"image-container\" ng-click=\"selectImage(image)\">\n" +
    "            <div class=\"col-xs-6 col-sm-3 col-md-2 col-lg-2\">\n" +
    "                <div class=\"media-wrapper\" ng-class=\"{selected: image.selected}\">\n" +
    "                    <div class=\"image-wrapper\">\n" +
    "                        <div class=\"centered\">\n" +
    "                            <img ng-src=\"{{image.thumbnail}}\" class=\"img-responsive\"/>\n" +
    "                        </div>\n" +
    "                    </div>\n" +
    "                    <div class=\"image-title\">{{image.title}}</div>\n" +
    "                </div>\n" +
    "            </div>\n" +
    "        </div>\n" +
    "    </div>\n" +
    "\n" +
    "    <div class=\"row text-center\">\n" +
    "        <button class=\"btn btn-primary\" ng-click=\"loadMore()\">Load More</button>\n" +
    "    </div>\n" +
    "\n" +
    "</div>"
  );

}]);

angular.module("mediaModal", ["ui.bootstrap", "angularSpinner", "flow", "images-resizer", "mediaModalTemplates", "blueimp.fileupload"]);
angular.module("mediaModal")
    .config([
        '$httpProvider', 'fileUploadProvider', '$sceDelegateProvider',
        function ($httpProvider, fileUploadProvider, $sceDelegateProvider) {

            $sceDelegateProvider.resourceUrlWhitelist([
                'self',
                'http://business.otonomic.com/**'
            ]);

            delete $httpProvider.defaults.headers.common['X-Requested-With'];
            fileUploadProvider.defaults.redirect = window.location.href.replace(
                /\/[^\/]*$/,
                '/cors/result.html?%s'
            );
            // Uploader settings:
            angular.extend(fileUploadProvider.defaults, {
                autoUpload: true,
                forceIframeTransport: true,
                // Enable image resizing, egrunt devxcept for Android and Opera,
                // which actually support image resizing, but fail to
                // send Blob objects via XHR requests:
                disableImageResize: /Android(?!.*Chrome)|Opera/
                    .test(window.navigator.userAgent),
                /*maxFileSize: 9990000,*/
                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
            });
        }
    ])
    .constant("flickrApiKey", "b5245e9b9cbaeecee26ea278bfa20253")
    .constant("upload_url", "http://business.otonomic.com/api/v1/?cmd=upload")
    .constant("instagramApiKey", "44171713.10d405b.25e232f920f94ac9907d8c0ea34ce1de")
    //.constant("facebookApiKey", "CAACEdEose0cBAJuIrBZCXQZBpMRGixqcQun3gJAwUL2cfGZB0iuvLu5lpDJy3txqnhAbdbFneQHpZACHiWQsymYxZCtFbH3GuB87NpQdZB8DvtUGIpmZCF3yip71ZBqqajhgw8uPcuaerccTBYZC1gXtGZAV11gvcrYOodJNnT87aJQ1ZBR9T4AX7NHJZCQfmJIIOd6k6oR55ubMZBy7R6ZBAYylzC")
    .constant("facebookApiKey", "CAANkofzWtSoBAG0FcIPXZAFFUJjZBdZAiejDxnPXXapvIP1UZA9ZBKiryHlB3GZCjrY1P3rgnKO70AWYQ1bLFp03MxZAuYTaimqsETawQxE9PRhCuLKHZCxDd9wrzJQrqXMsscI80UzPapvPoQKa9WeE7NHIN8H30lb48AhXqZAbVbX7w33nuEhI8ZCPc56VnTS2IZD")
    .constant("pexelsApiKey", "563492ad6f9170000100000183fb18af4b5f4b5c6a67f7e6433578ba")

    .factory("availableResources", ["enums", function(enums){
        return [{
            title: "Camera",
            icon: "fa fa-camera",
            viewPath: "camera.html"
        },{
            title: "Upload",
            icon: "fa fa-cloud-upload",
            viewPath: "upload.html"
        },{
            title: "Flickr",
            icon: "fa fa-flickr",
            viewPath: "webService.html",
            webServiceType: enums.webServiceTypes.flickr
        },{
            title: "Instagram",
            icon: "fa fa-instagram",
            viewPath: "webService.html",
            webServiceType: enums.webServiceTypes.instagram
        },{
            title: "Background Patterns",
            icon: "fa fa-star",
            viewPath: "webService.html",
            webServiceType: enums.webServiceTypes.backgroundPatterns
        },{
            title: "Facebook Photos",
            icon: "fa fa-facebook",
            viewPath: "webService.html",
            webServiceType: enums.webServiceTypes.facebookPhotos
        },{
            title: "Facebook Users",
            icon: "fa fa-facebook-official",
            viewPath: "webService.html",
            webServiceType: enums.webServiceTypes.facebookUsers
        },{
            title: "Pexels",
            icon: "fa fa-picture-o",
            viewPath: "webService.html",
            webServiceType: enums.webServiceTypes.pexels
        }];
    }]);
/**
 * Created by lobanovana on 23.03.2016.
 */
angular.module("mediaModal")
.controller("cameraController", ['$scope', '$http', 'upload_url', function ($scope, $http, upload_url) {
        $scope.upload_url = upload_url;
        $scope.options = {
            url: upload_url
        };
        $scope.loadingFiles = true;
        $http.get(upload_url)
            .then(
                function (response) {
                    $scope.loadingFiles = false;
                    $scope.filequeue = response.data.files || [];
                    //console.log($scope.queue);
                },
                function () {
                    $scope.loadingFiles = false;
                }
            );

        $scope.selectImage = function(image){

            //console.log(image);

            image.selected = !image.selected;
            image.thumbnail = image.url;
            if ($scope.selectedImages){
                if (image.selected){
                    $scope.selectedImages.push(image);
                    return;
                }
                var imageIndex = $scope.selectedImages.indexOf(image);
                if (imageIndex != -1){
                    $scope.selectedImages.splice(imageIndex, 1);
                }
            }
        };

        $scope.$on('fileuploaddone', function(e, data){
            // Your code here
            $.each(data.result.files, function (index, file) {
                $scope.selectImage(file);
            });
        });

    }
]);
angular.module("mediaModal")
    .controller('FileDestroyController', [
    '$scope', '$http', 'upload_url',
    function ($scope, $http, upload_url) {
        var file = $scope.file,
            state;
        if (file.url) {
            file.$state = function () {
                return state;
            };
            file.$destroy = function () {
                state = 'pending';
                return $http({
                    url: file.deleteUrl,
                    method: file.deleteType
                }).then(
                    function () {
                        state = 'resolved';
                        $scope.clear(file);
                    },
                    function () {
                        state = 'rejected';
                    }
                );
            };
        } else if (!file.$cancel && !file._index) {
            file.$cancel = function () {
                $scope.clear(file);
            };
        }
    }
]);
(function(){
    angular.module("mediaModal").controller("GalleryController", ["$scope", "availableResources", "$uibModalInstance", function($scope, availableResources, $uibModalInstance) {

        $scope.availableResources=availableResources;
        $scope.appState = {};
        $scope.selectedImages = [];

        $scope.tabSelected = function(resource){
            $scope.$broadcast("currentResourceChanged", resource.webServiceType)
        };

        $scope.cancel = function(){
            $uibModalInstance.dismiss("cancel");
        };

        $scope.selectImages = function(){
            $uibModalInstance.close($scope.selectedImages);
        }
    }]);
}());
angular.module("mediaModal")
.controller("uploadController", ['$scope', '$http', 'upload_url', function ($scope, $http, upload_url) {
    $scope.upload_url = upload_url;
    $scope.options = {
        url: upload_url
    };
    $scope.loadingFiles = true;
    $http.get(upload_url)
        .then(
            function (response) {
                $scope.loadingFiles = false;
                $scope.filequeue = response.data.files || [];
            },
            function () {
                $scope.loadingFiles = false;
            }
        );

    $scope.selectImage = function(image){

        //console.log(image);

        image.selected = !image.selected;
        image.thumbnail = image.url;
        if ($scope.selectedImages){
            if (image.selected){
                $scope.selectedImages.push(image);
                return;
            }
            var imageIndex = $scope.selectedImages.indexOf(image);
            if (imageIndex != -1){
                $scope.selectedImages.splice(imageIndex, 1);
            }
        }
    };
    $scope.$on('fileuploaddone', function(e, data){
        // Your code here
        $.each(data.result.files, function (index, file) {
            $scope.selectImage(file);
        });
    });
}
]);
angular.module("mediaModal")
.controller("webServicesController", ["$scope", "webStorage", "enums", function($scope, webStorage, enums){
        $scope.currentPage = 0;
        $scope.itemsOnPage = 25;
        $scope.search = function(){
            $scope.appState.loading = true;
            webStorage.search($scope.webServiceType, $scope.imageFilter, $scope.currentPage, $scope.itemsOnPage)
                .then(
                    function(result){
                        $scope.fullImagesCount = result.count;
                        $scope.images = result.images;
                    }
                )
                .finally(
                    function(){
                        $scope.appState.loading = false;
                    }
                );
        };

        $scope.loadMore = function(){
            $scope.appState.loading = true;
            webStorage.loadMore($scope.webServiceType)
                .then(function(result){
                    if (!$scope.images){
                        $scope.images = [];
                    }
                    $scope.images = $scope.images.concat(result.images);
                })
                .finally(function(){
                    $scope.appState.loading = false;
                });
        };

        $scope.setWebServiceType = function(webServiceType){
            $scope.webServiceType = webServiceType;
        };

        $scope.selectImage = function(image){
            image.selected = !image.selected;
            if ($scope.selectedImages){
                if (image.selected){
                    $scope.selectedImages.push(image);
                    return;
                }
                var imageIndex = $scope.selectedImages.indexOf(image);
                if (imageIndex != -1){
                    $scope.selectedImages.splice(imageIndex, 1);
                }
            }
        };

        $scope.showSearcher = function(){
            return $scope.webServiceType !== enums.webServiceTypes.backgroundPatterns;
        };

        $scope.$on("currentResourceChanged", function(event, resourceType){
            if ($scope.webServiceType === enums.webServiceTypes.backgroundPatterns && resourceType === enums.webServiceTypes.backgroundPatterns){
                $scope.search();
            }
        })
    }]
);
angular.module("mediaModal")
    .factory("enums", function(){
        return {
            webServiceTypes: {
                flickr: 1,
                instagram: 2,
                backgroundPatterns: 3,
                facebookUsers: 4,
                pexels: 5
            }
        }
    }
);
angular.module("mediaModal")
    .factory("backgroundPatterns", ["$http", "$q", function($http, $q){
        var _currentPage = 0;
        var _count = 20;

        function search(searchString, page, count){
            return $http.jsonp("http://www.colourlovers.com/api/patterns/top?format=json&jsonCallback=JSON_CALLBACK&numResults=" + _count + "&resultOffset=" + _currentPage)
                .then(function(response){
                    _currentPage++;
                    return {
                        count: 0,
                        images: response.data.map(function(image){
                            return {
                                thumbnail: image.imageUrl,
                                full: image.imageUrl,
                                title: image.title
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        function loadMore(){
            return $http.jsonp("http://www.colourlovers.com/api/patterns/top?format=json&jsonCallback=JSON_CALLBACK&numResults=" + _count + "&resultOffset=" + _currentPage)
                .then(function(response){
                    _currentPage++;
                    return {
                        count: 0,
                        images: response.data.map(function(image){
                            return {
                                thumbnail: image.imageUrl,
                                full: image.imageUrl,
                                title: image.title
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search,
            loadMore: loadMore
        }
    }]
);
angular.module("mediaModal")
    .factory("facebookPhotos", ["$http", "facebookApiKey", "$q", function($http, facebookApiKey, $q){
        var _nextUrl;
        function search(searchString, page, count){
            return $http.get("https://graph.facebook.com/v2.5/" + searchString + "/photos?access_token=" + facebookApiKey)
                .then(function(response){
                    _nextUrl = response.data.paging.next;
                    return {
                        count: 0,
                        images: response.data.data.map(function(user){
                            return {
                                thumbnail: "http://graph.facebook.com/" + user.id + "/picture?type=normal",
                                full: "http://graph.facebook.com/" + user.id + "/picture?type=large",
                                title: user.name
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }

        function loadMore(){

            if (!_nextUrl){
                return $q.reject("no more images");
            }

            return $http.get(_nextUrl)
                .then(function(response){
                    _nextUrl = response.data.paging.next;
                    return {
                        count: 0,
                        images: response.data.data.map(function(user){
                            return {
                                thumbnail: "http://graph.facebook.com/" + user.id + "/picture?type=normal",
                                full: "http://graph.facebook.com/" + user.id + "/picture?type=large",
                                title: user.name
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search,
            loadMore: loadMore
        }
    }]
);
angular.module("mediaModal")
    .factory("facebookUsers", ["$http", "facebookApiKey", "$q", function($http, facebookApiKey, $q){
        var _nextUrl;
        function search(searchString, page, count){
            return $http.get("https://graph.facebook.com/v2.2/search?q=" + searchString + "&type=user&access_token=" + facebookApiKey)
                .then(function(response){
                    _nextUrl = response.data.paging.next;
                    return {
                        count: 0,
                        images: response.data.data.map(function(user){
                            return {
                                thumbnail: "http://graph.facebook.com/" + user.id + "/picture?type=normal",
                                full: "http://graph.facebook.com/" + user.id + "/picture?type=large",
                                title: user.name
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }

        function loadMore(){
            if (!_nextUrl){
                return $q.reject("no more images");
            }
            return $http.get(_nextUrl)
                .then(function(response){
                    _nextUrl = response.data.paging.next;
                    return {
                        count: 0,
                        images: response.data.data.map(function(user){
                            return {
                                thumbnail: "http://graph.facebook.com/" + user.id + "/picture?type=normal",
                                full: "http://graph.facebook.com/" + user.id + "/picture?type=large",
                                title: user.name
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search,
            loadMore: loadMore
        }
    }]
);
angular.module("mediaModal")
.factory("flickr", ["$http", "flickrApiKey", function($http, flickrApiKey){
        var _lastPage = 1;
        var _count = 50;
        var _searchString = "";
        function search(searchString, page, count){
            _lastPage = 1;
            _count = count;
            _searchString = searchString;
            return $http.get("https://api.flickr.com/services/rest/?api_key=" + flickrApiKey +
                "&format=json&nojsoncallback=1&method=flickr.photos.search&format=json&page=" + page + "&per_page="
                + count +"&text=" + searchString)
                .then(function(response){

                    return {
                        count: +response.data.photos.total,
                        images: response.data.photos.photo.map(function(photo){
                            return {
                                thumbnail: "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_t.jpg",
                                full: "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg"
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        function loadMore(){
            _lastPage++;
            return $http.get("https://api.flickr.com/services/rest/?api_key=" + flickrApiKey +
                "&format=json&nojsoncallback=1&method=flickr.photos.search&format=json&page=" + _lastPage + "&per_page="
                + _count +"&text=" + _searchString)
                .then(function(response){
                    return {
                        count: +response.data.photos.total,
                        images: response.data.photos.photo.map(function(photo){
                            return {
                                thumbnail: "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_t.jpg",
                                full: "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg"
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search,
            loadMore: loadMore
        }
    }]
);
angular.module("mediaModal")
    .factory("gallery", ["$q", "$uibModal", function($q, $uibModal){
        function open(animate){
            return $uibModal.open({
                animation: animate,
                templateUrl: 'galleryWindow.html',
                controller: 'GalleryController',
                size: "lg"
            }).result;
        }
        return {
            open: open
        }
    }]
);
angular.module("mediaModal")
.factory("instagram", ["$http", "instagramApiKey", "$q", function($http, instagramApiKey, $q){
        var _nextUrl;
        function search(searchString, page, count){
            return $http.jsonp("https://api.instagram.com/v1/tags/" + searchString +"/media/recent?access_token=" + instagramApiKey + "&callback=JSON_CALLBACK&count=20")
                .then(function(response){
                    _nextUrl = response.data.pagination.next_url;
                    return {
                        count: 0,
                        images: response.data.data.map(function(image){
                            return {
                                thumbnail: image.images.thumbnail.url,
                                full: image.images.standard_resolution.url,
                                title: image.caption.text.substr(0, 50)
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }

        function loadMore(){
            if (!_nextUrl){
                return $q.reject("no more images");
            }
            return $http.jsonp(_nextUrl + "&callback=JSON_CALLBACK")
                .then(function(response){
                    _nextUrl = response.data.pagination.next_url;
                    return {
                        count: 0,
                        images: response.data.data.map(function(image){
                            return {
                                thumbnail: image.images.thumbnail.url,
                                full: image.images.standard_resolution.url,
                                title: image.caption.text.substr(0, 50)
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search,
            loadMore: loadMore
        }
    }]
);
angular.module("mediaModal")
.factory("pexels", ["$http", "pexelsApiKey", "$q", function($http, pexelsApiKey, $q){
        function search(searchString, page, count){
            return $http.get("http://api.pexels.com/v1/search?query=" + searchString + "&per_page=" + count + "&page=" + (page + 1), {
                    headers: {
                        "Authorization": pexelsApiKey
                    }
                })
                .then(function(response){
                    return {
                        count: response.data.total_results,
                        images: response.data.photos.map(function(photo){
                            return {
                                thumbnail: photo.src.square,
                                full: photo.src.large,
                                title: photo.photographer
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search
        }
    }]
);
angular.module("mediaModal")
.factory("webStorage", ["enums", "flickr", "instagram", "backgroundPatterns", "facebookUsers", "pexels", "facebookPhotos", function(enums, flickr, instagram, backgroundPatterns, facebookUsers, pexels, facebookPhotos){
        function getService(serviceType){
            switch (serviceType){
                case enums.webServiceTypes.flickr:
                    return flickr;
                case enums.webServiceTypes.instagram:
                    return instagram;
                case enums.webServiceTypes.backgroundPatterns:
                    return backgroundPatterns;
                case enums.webServiceTypes.facebookUsers:
                    return facebookUsers;
                case enums.webServiceTypes.pexels:
                    return pexels;
                case enums.webServiceTypes.facebookPhotos:
                    return facebookPhotos;
            }
        }
        function search(storageType, searchString, page, count){
            return getService(storageType).search(searchString, page, count);
        }

        function loadMore(storageType){
            return getService(storageType).loadMore();
        }

        return{
            search: search,
            loadMore: loadMore
        }
    }]
);