/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
angular.module('689Cloud')

// JS
// 'https://bookend.keyring.net/js/beobj.js'

.factory( "BEObj", function () {
    
    return window.BEObj;
})

.factory( "ClientInfo", function () {
    
    var ClientInfo = {

        getOS: function(params) {

            //  navigatorオブジェクト(テストのため入れ替えられるようにしてあります)
            var nav = navigator;

            //	パラメータ処理
            if (params == undefined) {
                params = {};
            }
            var pack_ios = params.pack_ios ? true : false;
            if (params.navigator != undefined) {
                nav = params.navigator;
            }

            //	OS判定
            if (nav.platform.indexOf('Win') != -1) {
                return "Windows";
            }
            else if (nav.platform.indexOf('Mac') != -1) {
                return "Mac";
            }
            else if (nav.platform.indexOf('iPhone') != -1 || nav.appVersion.indexOf('iPhone') != -1) {
                return pack_ios ? "iOS" : "iPhone";
            }
            else if (nav.platform.indexOf('iPad') != -1 || nav.appVersion.indexOf('iPad') != -1) {
                return pack_ios ? "iOS" : "iPad";
            }
            else if (nav.platform.indexOf('iPod') != -1 || nav.appVersion.indexOf('iPod') != -1) {
                return pack_ios ? "iOS" : "iPod";
            }
            else if (nav.appVersion.indexOf('Android') != -1) {
                return "Android";
            }
            return "Other";
        },
                
        getOSVersion: function(params) {

            //  navigatorオブジェクト(テストのため入れ替えられるようにしてあります)
            var nav = navigator;

            var version = "";
            //  パラメータ処理
            if (params === undefined) {
                params = {};
            }
            var unique_name = params.unique_name ? true : false;
            if (params.navigator !== undefined) {
                nav = params.navigator;
            }

            //  バージョン取得
            var _ver = null;
            switch (ClientInfo.getOS(params)) {
                //  Windows
                case "Windows":
                    _ver = nav.oscpu ?
                            nav.oscpu.match(/Windows NT ((\d+\.?)+)/) : //  Firefox
                            nav.appVersion.match(/Windows NT ((\d+\.?)+)/);  //  IE, Safari, Chrome, Opera
                    if (_ver) {
                        version = _ver[1];
                    }
                    //  名称に変換
                    if (unique_name) {
                        switch (version) {
                            case "6.3":
                                version = "8.1";
                                break;
                            case "6.2":
                                version = "8";
                                break;
                            case "6.1":
                                version = "7";
                                break;
                            case "6.0":
                                version = "Vista";
                                break;
                            case "5.1":
                                version = "XP";
                                break;
                            case "5.0":
                                version = "2000";
                                break;
                        }
                    }
                    break;
                    //  Mac
                case "Mac":
                    if (window.opera) {
                        _ver = nav.appVersion.match(/Intel Mac OS X ((\d+\.?)+)/);  //  Opera
                    }
                    else {
                        _ver = nav.oscpu ?
                                nav.oscpu.match(/Intel Mac OS X ((\d+\.?)+)/) : //  Firefox
                                nav.appVersion.match(/Intel Mac OS X ((\d+_?)+)/);  //  Safari, Chrome
                    }
                    if (_ver) {
                        version = _ver[1].replace(/_/g, ".");
                    }
                    break;
                    //  Android
                case "Android":
                    _ver = nav.appVersion.match(/Android ((\d+\.?)+)/);
                    if (_ver) {
                        version = _ver[1];
                    }
                    break;
                    //  iOS
                case "iPhone":
                case "iPod":
                    _ver = nav.appVersion.match(/iPhone OS ((\d+_?)+)/);
                    if (_ver) {
                        version = _ver[1].replace(/_/g, ".");
                    }
                    break;
                case "iPad":
                    _ver = nav.appVersion.match(/OS ((\d+_?)+)/);
                    if (_ver) {
                        version = _ver[1].replace(/_/g, ".");
                    }
                    break;
            }
            return version;
        },
                
        getBrowser: function(params) {

            //  navigatorオブジェクト(テストのため入れ替えられるようにしてあります)
            var nav = navigator;

            //  パラメータ処理
            if (params == undefined) {
                params = {};
            }
            if (params.navigator != undefined) {
                nav = params.navigator;
            }

            //  "appName" include "Internet Explorer"
            if (nav.appName.indexOf("Internet Explorer") != -1 || nav.appVersion.match(/rv:((\d+\.?)+)/) != null) {
                if (nav.cpuClass == "x64") {
                    return "IE64";
                }
                return "IE";
            }
            //  "appName" include "Opera"
            else if (nav.appName.indexOf("Opera") != -1) {
                if (nav.appVersion.indexOf("Opera Mini") != -1) {
                    return "Opera Mini";
                }
                else if (nav.appVersion.indexOf("Opera Mobi") != -1) {
                    return "Opera Mobile";
                }
                else {
                    return "Opera";
                }
            }
            //  "appName" include "Netscape"
            else if (nav.appName == "Netscape") {
                //  for minor browsers
                //  *Thease browser check first bcause many browsers have same UserAgent for Chrome, Firefox, Safari.
                if (nav.appVersion.indexOf("iLunascape") != -1) {
                    return "iLunascape";
                }
                else if (nav.appVersion.indexOf("Mercury") != -1) {
                    return "Mercury";
                }
                //  Google Chrome
                //  *The string "CriOS" used on the iOS.
                else if (nav.appVersion.indexOf("Chrome") != -1 || nav.appVersion.indexOf("CriOS") != -1) {
                    return "Chrome";
                }
                //  Firefox
                else if (nav.userAgent.indexOf("Firefox") != -1) {
                    return "Firefox";
                }
                //  Safari
                //  *Most browsers matched this.
                else if (nav.appVersion.indexOf("Safari") != -1) {
                    return "Safari";
                }
                //  旧バージョンの beobj.js と互換性を取るための判定
                else if (nav.vendor.indexOf("Apple") != -1) {
                    return "Safari";
                }
            }
            return "Other";
        },
                
        getBrowserVersion: function(params) {
            //  navigatorオブジェクト(テストのため入れ替えられるようにしてあります)
            var nav = navigator;

            //  パラメータ処理
            if (params === undefined) {
                params = {};
            }
            if (params.navigator != undefined) {
                nav = params.navigator;
            }

            var version = "";
            switch (ClientInfo.getBrowser( {
                    navigator: nav})) {
                case "IE":
                case "IE64":
                    var _ver = nav.appVersion.match(/MSIE ((\d+\.?)+)/);  //  IE10以下の場合
                    if (_ver == null) {
                        _ver = nav.appVersion.match(/rv:((\d+\.?)+)/)
                    }  //  IE11の場合
                    if (_ver) {
                        version = _ver[1];
                    }
                    break;
                case "Opera":
                    var _ver = nav.userAgent.match(/Version\/((\d+\.?)+)/);
                    if (_ver) {
                        version = _ver[1];
                    }
                    break;
                case "Safari":
                    var _ver = nav.appVersion.match(/Version\/((\d+\.?)+)/);
                    if (_ver) {
                        version = _ver[1];
                    }
                    break;
                case "Chrome":
                    var _ver = nav.appVersion.match(/Chrome\/((\d+\.?)+)/);
                    if (_ver) {
                        version = _ver[1];
                    }
                    break;
                case "Firefox":
                    var _ver = nav.userAgent.match(/Firefox\/((\d+\.?)+)/);
                    if (_ver) {
                        version = _ver[1];
                    }
                    break;
            }
            return version;
        },
                
        getAdobeFlashPlayerVersion: function() {
            var ver = "";
            navigator.plugins.refresh(false);
            if (ClientInfo.getBrowser() === "IE") {
                try {
                    var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
                    ver = axo.GetVariable("$version").split(" ")[1].split(",").join(".");
                } catch (e) {
                }
            }
            else {
                navigator.plugins.refresh(false);
                var x = navigator.plugins["Shockwave Flash"];
                if (x && x.description) {
                    ver = x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".");
                }
            }
            return ver;
        },
                
        checkFlashPlayerInstall: function() {
            var flashPlayerVer = ClientInfo.getAdobeFlashPlayerVersion();
            if (flashPlayerVer.length === 0) {
                return false;
            }
            else
                return true;
        }
    };
    
    return ClientInfo;
})

// Bookend API
.factory( "Bookend", [ "BEObj", "_", function ( BEObj, _ ) {

    // Bookend obj
    var Bookend = function () {
        
        var supportedOS = ['android, windows, ios'];
        
        // Authen key
        var _kr_authkey = "AQEBAYAAU77/dwJbSo8o/sjOyqQDyhQu6WA07mIGj/Rq2DKhkL75eZR1jFItCy9CMhAEqTlIFMMxbGRdep63YqG5SQz6gckqBp7qpyA0msgzV8/9iM/n637nr8lRcuklCKLMkX0QjDFCf7lfXbJjE2X0YRRwUlD+RH4Un7ccMWqezJ/oAPMAABAAjhEDHD0oJiFihzZUgmJuvRUAAABKh2+1wR1ndyVs3l3GDMEcBsi3LrU=";
        
        var os =  BEObj.getOS2().toLowerCase();
        
        return {
            
            // Check whether support OS or not
            checkSupportOS: function () {
                
                return ( _.include ( supportedOS, os ) ) ? true : false;
            },
            
            // Check valid plugin adobe reader/flash based on type
            checkValidComponent: function ( type ) {
                
                switch ( type ) {
                    
                    case 1: // Download to viewer
                        
                        // Check os supported
                        if ( !_.include ( supportedOS, os ) )
                            
                            return false;
                        
                        // Block plug-in
                        if (BEObj.isBookendPluginBlocked() === true && os !== "Android") {
            
                            // Show warning
                            return false;
                        }
                        else {
                            
                            if (os !== "iOS" && os !== "Android" && BEObj.isAdobeReaderPluginInstalled() === false) {
                                
                                // Show warning
                                return false;
                            }
                        }
                        
                        return true;
                }
                
            },
            
            /**
             * Do download to HoGo viewer
             * @param {type} username
             * @param {type} title
             * @param {type} link
             * @param {type} license
             * @returns {undefined}
             */
            doDownloadToViewer: function ( username, title, link, license ) {
                
                // Create global download id
                var downloadId = BEObj.createDownloadID();
                
                // Convert date 
                var date = new Date( Date.parse( license.document_expiry_date) ),
                    year = date.getFullYear(), month = date.getMonth() + 1,
                    day = date.getDate(),
                    expiryDate = ( year === 9999 ) ? -1 : BEObj.timeDateToMinute(year.toString(), month.toString(), day.toString());
                
                // Set up links
                BEObj.setOption({
                    url_ins_win: "http://bookend.keyring.net/dl/clsw/hogo/bookendsetup_hogo.exe", // Windows
                    url_ins_ios: "http://itunes.apple.com/jp/app/hogo-viewer/id540674502?mt=8", // iOS
                    url_ins_and: "https://play.google.com/store/apps/details?id=net.keyring.hogo", // Android - Offical link: "http://" + _kr_host_hogo + "/dl/android", 
                    ins_app_name: "HoGo Viewer", //"bookendDesktop"
                    ins_img_logo: "http://www.hogodoc.com/HoGoImages/install_logo_hogo.jpg",
                    ins_img_win_dlbtn: "http://www.hogodoc.com/HoGoImages/install_bt_download_win.jpg"
                });

                // Create opts
                var options = {
                    AuthKey: [_kr_authkey],
                    ContentsType: "krpdf",
                    ContentsURL: link,
                    ThumbURL: link + '_thumb',
                    Title: title,
                    DistributorName: username,
                    Tag: license.folder,
                    ValidTerm: expiryDate,
                    NumberOfBrowsing: "-1",
                    NumberOfPrinting: license.prinable,
                    DownloadablePlatform: "win,ios,android",
                    CustomName: "hogo",
                    RedirectType: false, // 2
                    MaxSharedDevice: license.local_copies,
                    GlobalDownloadID: downloadId
                    // MinClientVerWin:"2.5.14"
                };
                // Do download
                BEObj.downloadContents( options );
            }
            // View online
        };
    };
    
    return Bookend();
    
}]);

