var preferenceControllers = angular.module('mindinkControllers');

preferenceControllers.controller('updateAccountCtrl',  ['$scope', '$rootScope', '$modal', '$location', '$interval', '$timeout', 'userFactory', '$http', '$cookies', function($scope, $rootScope, $modal, $location, $interval, $timeout, userFactory, $http, $cookies) {

    var stop;

    $scope.init = function(){
        $scope.hasAvatar=false;

        $scope.showOverlay = false;
        $scope.showAddSubjects = false;
        $scope.showAddUni = false;
        $scope.showAddBooks = false;
        $scope.showAddProfilePic = false;
        $scope.showUpdateName = false;
        $scope.showWelcome=false;
        $scope.showAddBooks = true;

        $scope.nameTagZIndex=false;
        $scope.picZIndex=false;
        $scope.uniZIndex=false;
        $scope.subjectZIndex=false;

        $scope.showPicArrow=false;
        $scope.showNameArrow=false;
        $scope.showUniArrow=false;
        $scope.showSubjectArrow=false;
        $scope.showBookArrow=false;

        $scope.allSubLeft = 0;
        $scope.allSubPreviousHold = false;
        $scope.allSubNextHold = false;
        $scope.onHold = false;

        $scope.getUserInfo();
        $scope.getRegisteredUniversities();
        $scope.getUniversities();
    };

    $scope.getUserInfo = function(){
        userFactory.getUserInfo().then(function(user){
            // success
            $scope.user = user;
            $scope.userId = user.id;
            $scope.doPref = !user.onboarded;
        }, function(){
            // error
            console.log("cannot find user.")
        });
    };

    $scope.getRegisteredUniversities = function() {
        userFactory.getRegisteredUniversities().then(function(response){
            if (response && response.status == "SUCCESS") {
                var length = response.universities.length;
                $scope.universityCount = length;

                $scope.uniCarousel = {"width": "276px"};
                $scope.registeredUniversities = response.universities;
                if($scope.registeredUniversities.length == 0) {
                    $scope.hasUni = false;
                }
                else {
                    $scope.hasUni = true;
                }
                if($scope.registeredUniversities.length > 0) {
                    selectedUni = $scope.registeredUniversities[0].id;
                    $scope.activeUni = selectedUni;

                }
                else if($scope.registeredUniversities.length > 1) {
                    $scope.selectedUniSort();
                }
                if ($scope.doPref == true) {

                    $scope.doPref = false;
                    $scope.preferenceWalkThrough = true;
                    $scope.showOverlay = true;
                    $scope.showWelcome = true;
                    $scope.showAddBooks = false;

                }

                // finished preference and user has uni
                if ($scope.hasUni && $scope.showAddBooks) {
                    $scope.getRegisteredBooks();
                    $scope.searchbooksByField(''); // empty means get all.

                    // set onboarded flag for user
                    userFactory.markAsOnboarded();
                }
            }
            else {
                // not successful
            }
        }, function(){
            // error
        })
    };

    $scope.getUniversities = function() {
        userFactory.getUniversities().then(function(response){
            if (response && response.status == "SUCCESS") {
                $scope.universities = response.universities;
                $scope.allUniStyle = {"left": "0px", "width": "auto", "display": "inline"};
            }
            else{
                // not successful
            }
        }, function(){
            // error
        })
    };

    $scope.clearScreen = function() {
        $scope.showOverlay = false;
        $scope.showAddSubjects = false;
        $scope.showAddUni = false;
        $scope.showAddBooks = false;
        $scope.showAddProfilePic = false;
        $scope.showUpdateName = false;
        $scope.showAddBooks = false;
        $scope.showWelcome=false;

        $scope.nameTagZIndex=false;
        $scope.picZIndex=false;
        $scope.uniZIndex=false;
        $scope.subjectZIndex=false;
        $scope.bookZIndex=false;

        $scope.showPicArrow=false;
        $scope.showNameArrow=false;
        $scope.showUniArrow=false;
        $scope.showSubjectArrow=false;
        $scope.showBookArrow=false;
        $scope.showAddBooks = true;
    }

    $scope.signout = function() {
        userFactory.emailSignout().then(function(response){
            if (response && response.status == "SUCCESS") {
            	$location.path('/index');
            }
            else {
               // unsuccessfull
            }
        }, function(){
            // error
        });
    };

    $scope.getStarted = function() {
        $scope.showOverlay = false;
        $scope.showWelcome = false;

        $scope.profile();
    }

    //profile pic
    $scope.profile = function() {
        $scope.clearScreen();
        $scope.showAddBooks = false;
        $scope.showAddProfilePic=true;
        $scope.showOverlay=true;
        $scope.picZIndex = true;
        $scope.showPicArrow=true;
        $scope.msg = "Choose pic selected";
    }

    var profileUploadValidated = false;
    $scope.fileuploadMsg = '';
    $scope.fileuploadMsgType = 'errorMsg';
    $scope.$watch('myFile', function(file){
        if (!!file){

           if(file.type != "image/png" && file.type != "image/jpeg" && file.type != "image/gif") {
               $scope.preUpload = undefined;
               profileUploadValidated = false;
               $scope.fileuploadMsgType = 'errorMsg';
               $scope.fileuploadMsg = "Please use the image format png, jpg or gif";

           }
           else if(file.size > 5242880) {
               $scope.preUpload = undefined;
               profileUploadValidated = false;
               $scope.fileuploadMsgType = 'errorMsg';
               $scope.fileuploadMsg = "please use an image smaller then 5mb";
           }
           else {
            profileUploadValidated = true;
             $scope.fileuploadMsgType = 'successMsg';
            $scope.fileuploadMsg = 'File ready to upload!';
           }

        }
    });

    //upload pic
    $scope.updatePic = function() {
        var file = $scope.myFile;
        var uploadUrl = '/content/users/uploadAvatar';

        if(!!$scope.preUpload && profileUploadValidated) {

            var fd = new FormData();
            fd.append('file', file);
            $http.post(uploadUrl, fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            })
                .success(function(data, status, headers, config){
                    $scope.fileuploadMsgType = 'successMsg';
                    $scope.fileuploadMsg = "";

                    if ($scope.preferenceWalkThrough)
                        $scope.changeName();
                    else
                        $scope.clearScreen();

                })
                .error(function(data, status, headers, config){
                    $scope.fileuploadMsgType = 'errorMsg';
                    $scope.fileuploadMsg = "Something went wrong with the update! Please try again or contact hello@mindink.com";

                    $scope.preUpload = undefined;
                    $scope.profile();
                });

        }else {
            $scope.fileuploadMsgType = 'errorMsg';
            //$scope.fileuploadMsg = "Please choose an appropriate file to upload.";
        }

    }

    $scope.skipPicUpload = function() {
        $scope.preUpload = undefined;
        $scope.myFile = undefined;
        if ($scope.preferenceWalkThrough)
            $scope.changeName();
        else
            $scope.clearScreen();
    }

    //name
    $scope.changeName = function () {
        $scope.userFullname = $scope.user;
        $scope.clearScreen();
        $scope.showAddBooks = false;
        document.getElementById('update-first-name').focus();
        $scope.showUpdateName=true;
        $scope.showOverlay=true;
        $scope.nameTagZIndex = true;
        if($scope.preferenceWalkThrough)
            $scope.showNameArrow=true;
    }

    $scope.updateName = function(user) {
    	if($scope.user.firstName != null && $scope.user.lastName != null) {
            userFactory.updateFullName(user.firstName, user.lastName).then(function(response){
	            if (response && response.status == "SUCCESS") {
	            	$scope.user = $scope.userFullname;
		        }
		        else {
		        	// not success
		        }
            }, function(){
                // error
            })
        }
        else {
            $scope.changeName();
        }
        if($scope.preferenceWalkThrough) {
            $scope.chooseUni();
        }
        else {
            $scope.clearScreen();
        }

    };

    //University
    $scope.chooseUni = function () {
        $scope.clearScreen();
        $scope.showAddBooks = false;
        document.getElementById('university-name').focus();
        $scope.msg = "Choose uni selected";
        $scope.showAddUni=true;

        if($scope.preferenceWalkThrough) {
            $scope.uniZIndex = true;
            $scope.showOverlay=true;
            $scope.showUniArrow=true;
        }

        if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
            $scope.$apply();
        };

    }

    $scope.activateUni = function(uniId) {
        selectedUni = uniId;
        $scope.chooseUni();
        $scope.selectedUniSort();
    }

    $scope.selectedUniSort = function() {
        var i = -1

        if($scope.universityCount > 1 && selectedUni != 0 && $scope.registeredUniversities != undefined) {
            for(var i=0; i<$scope.registeredUniversities.length;i++) {
                if($scope.registeredUniversities[i].id == selectedUni) {
                    var temp=$scope.registeredUniversities[0];
                    $scope.registeredUniversities[0] = $scope.registeredUniversities[i];
                    $scope.registeredUniversities[i] = temp;
                    break;
                }
            }
            selectedUni = $scope.registeredUniversities[0].id;
            $scope.activeUni = selectedUni;
        }
    }

    $scope.addUniversity = function(uniId) {
        if($scope.registeredUniversities.length >= 2) {
            alert("Maximum two universities at a time");
        }
        else {
            userFactory.addUniversity(uniId).then(function(response){
                if (response && response.status == "SUCCESS") {
                    $scope.getRegisteredUniversities();
                    $scope.getUniversities();
                    $scope.hasUni = true;
                }
                else {
                    // fail
                }
            }, function(){
                // error

            });
        }
    }

    $scope.deleteUniversity = function(uniId) {
        userFactory.deleteUniversity(uniId).then(function(response){
            if (response && response.status == "SUCCESS") {
                $scope.getRegisteredUniversities();
                $scope.getUniversities();
            }
            else {
                // fail
            }
        }, function(){
            // error
        });
    }

    $scope.saveAndNextUni = function() {
        $scope.clearScreen();
        $scope.subjects();
    }

    //Subjects
    $scope.subjects = function() {
        if($scope.universityCount == 0 ) {
            $scope.chooseUni();
            alert('please add a university');
        }
        else {

            $scope.clearScreen();
            $scope.showAddBooks = false;
            $scope.msg = "subjects clicked";
            $scope.showAddSubjects = true;

            if($scope.preferenceWalkThrough) {
                $scope.showOverlay=true;
                $scope.subjectZIndex=true;
            }
        }
        $scope.getRegisteredSubjects(selectedUni);
        $scope.getAllSubjectsByUniId(selectedUni);
        document.getElementById('subject-name').focus();
    }

    $scope.getRegisteredSubjects = function(selUni){
        userFactory.getRegisteredSubjects(selUni).then(function(response){
            if (response && response.status == "SUCCESS") {
                $scope.registeredSubjects = response.subjects;
                // set the width of the carousel
                $scope.mySubjectStyle = {"left": "0px", "width": 10000 + "px"};
            }
            else {
                // fail
            }
        }, function(){
            // error
        });
    }

    $scope.getAllSubjectsByUniId = function(selUni){
        userFactory.getAllSubjectsByUniId(selUni)
            .then(function(response){
                if (response && response.status == "SUCCESS") {
                    $scope.allSubjects = response.subjects;
                    // set the width of the carousel
                    $scope.allSubjectStyle = {"left": "0px", "width": 10000 + "px"};
                }
                else {
                    // fail
                }
            }, function(){
                // error
            });
    }

    $scope.addSubject = function(subjectId) {
        userFactory.addSubjectBySubjectId(subjectId)
            .then(function(response){
                if (response && response.status == "SUCCESS") {
                    $scope.getRegisteredSubjects(selectedUni);
                    $scope.getAllSubjectsByUniId(selectedUni);
                }
                else {
                    // fail
                }
            }, function(){
                // error
            });
    }

    $scope.deleteSubject = function(subjectId) {
        userFactory.deleteSubjectBySubjectId(subjectId)
            .then(function(response){
                if (response && response.status == "SUCCESS") {
                    $scope.getRegisteredSubjects(selectedUni);
                    $scope.getAllSubjectsByUniId(selectedUni);
                }
                else {
                    // fail
                }
            }, function(){
                // error
            });
    }

    $scope.saveAndNextSubject = function() {
        $scope.clearScreen();
        $scope.showAddBooks = false;
        //incase minds are changed
        if($scope.preferenceWalkThrough) {
            $scope.books();
        }
//		else
    }

    //Books
    $scope.books = function() {
        $scope.clearScreen();
        //$scope.showAddBooks = true;
        document.getElementById('book-name').focus();
        if($scope.preferenceWalkThrough) {
            $scope.showBookArrow=true;
            $scope.bookZIndex=true;
            $scope.showOverlay=true;
        }

        $scope.bookSearchField = '';
        $scope.searchBooks = [];
        $scope.getRegisteredBooks();
        $scope.searchbooksByField(''); // empty means get all.
    }

    $scope.getRegisteredBooks = function(){
        userFactory.getRegisteredBooks()
            .then(function(response){
                if (response && response.status == "SUCCESS") {
                    $scope.userBooks = response.books;
                    $scope.ulStyle = {"left": "0px", "width": 10000 + "px"};
                }
                else {
                    // fail
                }
            }, function(){
                // error
            });
    }

    $scope.searchbooksByField = function(searchText){
        userFactory.searchBooks(searchText)
            .then(function(response){
                if (response && response.status == "SUCCESS") {
                    $scope.searchBooks = response.books;
                    $scope.searchBookstyle = {"left": "0px", "width": 10000 + "px"};
                }
                else {
                    // fail
                }
            }, function(){
                // error
            });
    }

    $scope.addBook = function(bookId) {
        userFactory.addBookByBookId(bookId)
            .then(function(response){
                if (response && response.status == "SUCCESS") {
                    $scope.getRegisteredBooks();
                    $scope.searchbooksByField(($scope.bookSearchField != undefined) ? $scope.bookSearchField : "");
                }
                else {
                    // fail
                }
            }, function(){
                // error
            });
    }

    $scope.deleteBook = function(bookId) {
        userFactory.deleteBookByBookId(bookId)
            .then(function(response){
                if (response && response.status == "SUCCESS") {
                    $scope.getRegisteredBooks();
                    $scope.searchbooksByField(($scope.bookSearchField != undefined) ? $scope.bookSearchField : "");
                }
                else {
                    // fail
                }
            }, function(){
                // error
            });
    }

    $scope.saveAndNextBook = function () {
        $scope.preferenceWalkThrough = false;
        $scope.clearScreen();
        // set onboarded flag for user
        userFactory.markAsOnboarded();
    }

    //
    // [ML] 14th May: new carousel scroll implementation
    // really should be a directive but required too much
    // time to reinvent in existing project
    //
    $scope.$on('ngRepeatFinished', function (e, id) {

        // calculate width of content
        var scrollable = angular.element( document.querySelector( '#' + id) );
        var mod = scrollable[0].children[0].children[0].clientWidth + 10;
        var width = scrollable[0].children[0].children.length * mod;

        angular.element(scrollable[0].children[0]).css('width',width + 'px');

    });

    //t: current time, b: begInnIng value, c: change In value, d: duration
    var easeInOutQuad = function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t + b;
        return -c/2 * ((--t)*(t-2) - 1) + b;
    }

    var freeScrollActive = false;
    var freeScrollSpeed = 150;
    $scope.freeScrollStop = function(){
        freeScrollActive = false;
    }
    $scope.freeScrollCarousel = function(control, style, direction){

        freeScrollActive = true;

        // initial scroll
        $scope.scrollCarouselOnce(freeScrollSpeed, control, style, direction);

        var interval = setInterval(function(){
            // button released
            if (!freeScrollActive) {
                clearInterval(interval);
            }
            // button held
            else {
                $scope.scrollCarouselOnce(freeScrollSpeed, control, style, direction);
            }
        }, freeScrollSpeed);

    }

    var timeouts = {};
    $scope.scrollCarouselOnce = function(duration, control, style, direction){

        !!timeouts[style] && timeouts[style].skip();

        var scrollable = angular.element( document.querySelector( '#' + control) );
        var mod = scrollable[0].children[0].children[0].clientWidth + 10;
        var widthlimit = scrollable[0].children[0].children.length * mod - scrollable[0].clientWidth;
        var current = scrollable[0].scrollLeft;

        var mod = direction == "forward" ? mod : mod * -1;

        // limit scroll
        if (current + mod > widthlimit || current + mod < 0){
            mod = mod >= 0 ? widthlimit - current : 0 - current ;
        }

        timeouts[style] = (function(scrollable, duration, start, end){

            var step = duration/10;
            var amnt = (end - start) / (duration) * step;
            var t = 0;

            scrollable[0].scrollLeft = easeInOutQuad(null, 0, start, (end - start), duration);
            var interval = setInterval(function(){

                scrollable[0].scrollLeft = easeInOutQuad(null, ++t * (duration / step), start, (end - start), duration);

                if (amnt > 0 ? scrollable[0].scrollLeft >= end : scrollable[0].scrollLeft <= end)
                    clearAll();

            }, duration / step);

            var clearAll = function(){
               clearInterval(interval);
               //scrollable[0].scrollLeft = end;
            }

            return {
                skip: function() {
                   clearAll();
                }
            };

        })(scrollable, duration, current, current + mod);


    }

    // [ML] END

    $scope.stopScroll = function() {
        if (angular.isDefined(stop)) {
            $interval.cancel(stop);
            stop = undefined;
        }
    };

    $scope.scrollNewCarousel = function(onHold, control, style, direction) {
        $scope.onHold = onHold;

        if ($scope.onHold) {
            $scope.startNewScroll(control, style, direction);
        }
        else{
            $scope.stopScroll();
        }
    }

    $scope.startNewScroll = function(control, style, direction) {
        var ul = angular.element( document.querySelector( '#' + control) );

         stop = $interval(function() {
            var left = (ul[0].offsetLeft) ? ul[0].offsetLeft : 0;

            if (ul[0].children.length > 0){
                var liWidth = (ul[0].children[0].clientWidth != undefined) ? ul[0].children[0].clientWidth + 10 : 0;
                var totalWidth = liWidth *  ul[0].children.length;

                if (direction == "forward")
                {
                    if (left > (totalWidth - liWidth) * -1) {
                        left = left - liWidth;

                        if (left <= (totalWidth - liWidth) * -1)
                            $scope[style] = {"left": (totalWidth - liWidth) * -1 + "px", "width": totalWidth + "px"};
                        else
                            $scope[style] = {"left": left + "px", "width": totalWidth + "px"};

                    } else {
                        $scope.stopScroll();
                    }
                }
                else if (direction == "backward"){
                    if (left < 0) {
                        left = left + liWidth;
                        left = (left >= 0) ? 0 : left;
                        $scope[style] = {"left": left + "px", "width": totalWidth + "px"};
                    } else {
                        $scope.stopScroll();
                    }
                }
            }
        }, 150);
    };

    $scope.slideBookDetails = function(book){
        $scope.showBookDetails = 'showBookDetails';
        $scope.showBookDetailsOverlay = true;

        $scope.purchaseClose = '';
        $scope.bookDetailsObj = book;

        $scope.paymentToken = $scope.user.paymentToken;
        $scope.billFirstName  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? $scope.user.billingFirstName : "";
        $scope.billLastName  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? $scope.user.billingLastName : "";
        $scope.billAddress  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? $scope.user.billingAddress : "";
        $scope.billSuburb  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? $scope.user.billingSuburb : "";
        $scope.billState  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? $scope.user.billingState : "";
        $scope.billPostcode  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? $scope.user.billingPostcode : "";
        $scope.ccName  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? $scope.user.cardName : "";
        $scope.ccNo  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? $scope.user.cardNumber : "";
        $scope.ccMonth  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? "xx"  : "";
        $scope.ccYear  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? "xx" : "";
        $scope.ccCvv  = ($scope.paymentToken != "" && $scope.paymentToken != undefined) ? "xxx" : "";

        $scope.paymentFieldDisabled = ($scope.paymentToken != "" && $scope.paymentToken != undefined);
        $scope.modifyCardClicked = false;
        $scope.modifyCard =  ($scope.paymentToken != "" && $scope.paymentToken != undefined);
    };

    $scope.slideBookPurchaseDetails = function() {
        $scope.showBookDetails = 'showPaymentDetails';
        $scope.purchaseClose = 'purchaseCloseButton';
    };

    $scope.modifyPaymentDetails = function(){
        $scope.billFirstName  = "";
        $scope.billLastName  = "";
        $scope.billAddress  = "";
        $scope.billSuburb  = "";
        $scope.billState  = "";
        $scope.billPostcode  = "";

        $scope.ccName = "";
        $scope.ccNo = "";
        $scope.ccMonth = "";
        $scope.ccYear = "";
        $scope.ccCvv = "";
        $scope.paymentFieldDisabled = false;
        $scope.modifyCardClicked = true;
    };

    $scope.closeBookDetails = function(){
        $scope.showBookDetails = '';
        $scope.showBookDetailsOverlay = false;
    };

    $scope.closePurchaseCompleted = function(){
        $scope.showPurchaseCompleted = '';
        $scope.showBookDetailsOverlay = false;
    };

    $scope.viewBook = function(path) {
        $location.path(path);
    };

    $scope.toggleBookDesc = false;
    $scope.toggleBookDetailsDesc = function() {
        $scope.toggleBookDesc = !$scope.toggleBookDesc;
        $scope.bookDetailsDescStyle =  ($scope.toggleBookDesc) ? 'seeAll' : '';
    };

    $scope.purchaseBook = function(){
        $scope.showPaymentInProgress = true;

        if ($scope.paymentToken == undefined || $scope.paymentToken == "" || $scope.modifyCardClicked) {
            $scope.purchaseBookWithNewCard();
        }
        else {
            $scope.purchaseBookWithToken();
        }
    };

    $scope.purchaseBookWithNewCard = function() {
        userFactory.purchaseBook($scope.bookDetailsObj.id, $scope.billFirstName, $scope.billLastName, $scope.billAddress, $scope.billSuburb, $scope.billState, $scope.billPostcode).then(function(response){
            // success
            if (response.resultCode == "0"){
                var r = response;

                var eWayForm = document.createElement("form");
                eWayForm.setAttribute('method',"post");
                eWayForm.setAttribute('id',"ewayPost");
                eWayForm.setAttribute('name',"ewayPost");
                eWayForm.setAttribute('action',response.paymentUrl);

                var EWAY_ACCESSCODE = document.createElement("input");
                EWAY_ACCESSCODE.setAttribute("type", "hidden");
                EWAY_ACCESSCODE.setAttribute("name", "EWAY_ACCESSCODE");
                EWAY_ACCESSCODE.setAttribute("value", response.paymentAccessCode);
                var EWAY_PAYMENTTYPE = document.createElement("input");
                EWAY_PAYMENTTYPE.setAttribute("type", "hidden");
                EWAY_PAYMENTTYPE.setAttribute("name", "EWAY_PAYMENTTYPE");
                EWAY_PAYMENTTYPE.setAttribute("value", "Credit Card");
                var EWAY_CARDNAME = document.createElement("input");
                EWAY_CARDNAME.setAttribute("type", "text");
                EWAY_CARDNAME.setAttribute("name", "EWAY_CARDNAME");
                EWAY_CARDNAME.setAttribute("value", $scope.ccName);
                var EWAY_CARDNUMBER = document.createElement("input");
                EWAY_CARDNUMBER.setAttribute("type", "text");
                EWAY_CARDNUMBER.setAttribute("name", "EWAY_CARDNUMBER");
                EWAY_CARDNUMBER.setAttribute("value", $scope.ccNo);
                var EWAY_CARDEXPIRYMONTH = document.createElement("input");
                EWAY_CARDEXPIRYMONTH.setAttribute("type", "text");
                EWAY_CARDEXPIRYMONTH.setAttribute("name", "EWAY_CARDEXPIRYMONTH");
                EWAY_CARDEXPIRYMONTH.setAttribute("value", $scope.ccMonth);
                var EWAY_CARDEXPIRYYEAR = document.createElement("input");
                EWAY_CARDEXPIRYYEAR.setAttribute("type", "text");
                EWAY_CARDEXPIRYYEAR.setAttribute("name", "EWAY_CARDEXPIRYYEAR");
                EWAY_CARDEXPIRYYEAR.setAttribute("value", $scope.ccYear);
                var EWAY_CARDCVN = document.createElement("input");
                EWAY_CARDCVN.setAttribute("type", "text");
                EWAY_CARDCVN.setAttribute("name", "EWAY_CARDCVN");
                EWAY_CARDCVN.setAttribute("value", $scope.ccCvv);
                var submit = document.createElement("input");
                submit.setAttribute('type',"submit");
                submit.setAttribute('value',"Submit");

                eWayForm.appendChild(EWAY_ACCESSCODE);
                eWayForm.appendChild(EWAY_PAYMENTTYPE);
                eWayForm.appendChild(EWAY_CARDNAME);
                eWayForm.appendChild(EWAY_CARDNUMBER);
                eWayForm.appendChild(EWAY_CARDEXPIRYMONTH);
                eWayForm.appendChild(EWAY_CARDEXPIRYYEAR);
                eWayForm.appendChild(EWAY_CARDCVN);
                eWayForm.appendChild(submit);

                // call eWAY to process the request
                eWAY.process(eWayForm, {
                    autoRedirect: false,
                    onComplete: function (data) {

                        // this is a callback to hook into when the requests completes
                        if (data.Errors == null && data.IsComplete) {
                            userFactory.purchaseSendAccessCode(data.AccessCode).then(function(response){
                                var sendResponse = response;
                                if (response.resultCode == "0"){
                                    $scope.completePurchase();
                                }
                                else{
                                    $scope.showPurchaseError();
                                }
                            }, function(e){
                                $scope.showPurchaseError();
                            });
                        }
                        else {
                            $scope.showPurchaseError();
                        }
                    },
                    onError: function (e) {
                        $scope.showPurchaseError();
                    },
                    onTimeout: function (e) {
                        $scope.showPurchaseError();
                    }
                });
            }
            else {
                $scope.showPurchaseError();
            }
        }, function(){
            $scope.showPurchaseError();

        });
    } ;

    $scope.purchaseBookWithToken = function(){
        userFactory.purchaseBookWithToken($scope.bookDetailsObj.id).then(function(response) {
            if (response.resultCode == "0") {
                $scope.completePurchase();
            }
            else{
                $scope.showPurchaseError();
            }
        }, function() {
            $scope.showPurchaseError();
        })
    };

    $scope.completePurchase = function() {
        $timeout(function(){
            $scope.showPaymentInProgress = false;

            $scope.getRegisteredBooks();

            if ($scope.bookSearchField != undefined) {
                console.log('do search for ' + $scope.bookSearchField);
                $scope.searchbooksByField($scope.bookSearchField);
            }

            $scope.closeBookDetails();

            $scope.showPurchaseCompleted = 'show';
            $scope.showBookDetailsOverlay = true;
            $scope.purchaseCompletedContainerStyle = {
                background: 'url(/content/mindink/books/' + $scope.bookDetailsObj.isbn  + '/cover/small)'
            };
        });
    };

    $scope.showPurchaseError = function(){
        $timeout(function(){
            $scope.showPaymentInProgress = false;
            $scope.paymentError = true;
        }, 100);
    };

    var timer=false;
    $scope.$watch('bookSearchField', function(){
        if(timer){
            $timeout.cancel(timer)
        }
        timer= $timeout(function(){
            if ($scope.bookSearchField != undefined) {
                console.log('do search for ' + $scope.bookSearchField);
                $scope.searchbooksByField($scope.bookSearchField);
            }
        },1000)
    });
}]);

preferenceControllers.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

preferenceControllers.directive('resize', function ($window) {
    return {
        link: function (scope, element, attrs) {
            var w = angular.element($window);
            var element = angular.element(element);
            var ratio = attrs.widthratio;

            scope.getWindowDimensions = function () {
                return { 'windowHeight': w[0].offsetHeight, 'windowWidth': w[0].offsetWidth, 'elementHeight': element[0].offsetHeight};
            };

            scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
                scope.windowHeight = newValue.windowHeight;
                scope.windowWidth = newValue.windowWidth;
                if (newValue.elementHeight != 0) scope.liWidth = {"width": newValue.elementHeight * ratio + "px"};
            }, true);

            w.bind('resize', function () {
                scope.$apply();
            });
        }
    }
});

preferenceControllers.factory('formDataObject', function () {
    return function(data) {
        var fd = new FormData();
        angular.forEach(data, function(value, key) {
            fd.append(key, value);
        });
        return fd;
    };
});