//
//  SDK.js
//  CoverPage
//
//  Created by Richard Anaya on 1/9/2013.
//  Copyright (c) 2013 Evernote. All rights reserved.
//

if(!window.Evernote){
    window.Evernote = {};
}

//
//  ENCPPlatform.js
//  CoverPage
//
//  Created by Zdzislaw Losvik on 26/09/2013.
//  Copyright (c) 2013 Evernote. All rights reserved.
//

var oldScroll = $.fn.scrollTop;
window.$encpJquery = $.noConflict(); // $ is restored & $encpJquery now points to our jquery
$encpJquery.fn.scrollTop = function() {
    if(arguments.length == 0 ){
        return oldScroll.apply(this,arguments);
    }
    else {
        //var top = oldScroll.apply(this,[]);
        var newTop = arguments[0];
        var distance = Math.abs($encpJquery(document).scrollTop()-newTop);
        $encpJquery("html, body").animate({scrollTop: newTop}, distance/window.innerHeight*200);
        //$encpJquery(window).smoothScroll({direction: 'top', offset:100});
    }
};

function ENCPPlatform() {
}

ENCPPlatform.prototype = {

    host: function() {
        if (window.encpPlatformLink) {
            return window.encpPlatformLink;
        }

        window.encpPlatformLink = { // dummy host link
            didClickMediaWithParameters: function(params) {},
            requestDocumentInformationForURL: function(url, succsessCallback, errorCallback) {},
            didReachEndOfNote: function(count) {},
            beep: function() {},
            didParseMediaItems: function(mediaInfo) {},
            willStartLayouting: function() {},
            didFinishLayouting: function() {},
            didFinishPageLoad: function() {},
            didFinishStyleUpdate: function() {},
            didScrollToPosition: function(position) {},
            navigateToNextNote: function() {},
            navigateToPreviousNote: function() {},
            showLog: function(logText, caller) {}
        };

        return window.encpPlatformLink;
    },

    /*
     * Notify the host about the user clicking an image or document
     * Typically, the host will open the document viewer (gallery mode).
     *
     * @param params   An object with fields: 'src', 'mime' and 'mediaFrame'
     */
    didClickMediaWithParameters: function(params) {
        this.host().didClickMediaWithParameters(params);
    },

    /**
     * For a document/image URL calls success callback with the a boolean if it is a document (PDF, office) and
     * how many pages the document has.
     * @param url               Request information about url
     * @param successCallback   Called when information has been successfully retrieved
     *                          successCallback parameters:
     *                           isDocument       Do we need to display it as a document?
     *                           numberOfPages    How many pages are there?
     *                           isRetina         Is image high DPI?
     *                           predefinedName   ?
     * @param errorCallback     Called when information could not be retrieved
     *                          errorCallback has no parameters.
     */
    requestDocumentInformationForURL: function(url, mime, successCallback, errorCallback) {
        this.host().requestDocumentInformationForURL(url, successCallback, errorCallback);
    },

    /**
     * Get attachment information
     * @param url - to be requested.
     * @param callback - to be handled later on once data got.
     */
    attachmentInfo: function(url, callback) {
        // nothing right now
    },

    /**
     * Notifies the host about the user reaching the end of the note.
     * @param count   Used to display the tooltip at the end. count = 0 clears the tooltip. count > 0 shows the tooltip.
     *                Tooltip shows user how to open the next note.
     */
    didReachEndOfNote: function(count) {
        this.host().didReachEndOfNote(count);
    },

    /**
     * Sound an alert
     */
    beep: function() {
        this.host().beep();
    },

    /**
     * Notify the host about the all media links in the note
     * @param mediaInfo  Contains an array of media objects with
     *                   {src : Media URL, mime : Media MIME}
     */
    didParseMediaItems: function(mediaInfo) {
        this.host().didParseMediaItems(mediaInfo);
    },

    /**
     * Notify host when just before layouting the page.
     */
    willStartLayouting: function() {
        this.host().willStartLayouting();
    },

    /**
     * Notify host when we're done layouting the page.
     */
    didFinishLayouting: function() {
        this.host().didFinishLayouting();
    },

    /**
     * Notify host when we're done loading the page.
     */
    didFinishPageLoad: function() {
    },

    /**
     * Notify host when we're done updating style.
     */
    didFinishStyleUpdate: function() {
        // nothing right now.
    },

    /**
     * Notify host about new scroll position
     * @param position   New vertical scroll offet
     */
    didScrollToPosition: function(position) {
        this.host().didScrollToPosition(position);
    },

    /**
     * Ask host to open the next note.
     */
    navigateToNextNote: function() {
        this.host().navigateToNextNote();
    },

    /**
     * Ask host to open the previous note.
     */
    navigateToPreviousNote: function() {
        this.host().navigateToPreviousNote();
    },

    /**
     * Record log on Evernote log system
     * @param logText  String to be logged
     * @param caller   String containing caller information
     */
    showLog: function(logText, caller) {
        this.host().showLog(logText, caller);
    },

    /**
     * Prefix for media path.
     */
    EMBEDDED_MEDIA_PATH_PREFIX: "http://encoverpage.localhost/",

    /**
     * Process media in the note
     * @param rootElement Root element of elements to be processed
     */
    fixEmbeddedMedia : function (rootElement) {
        var self = this;
        $encpJquery(rootElement).find("embed[id^='en-media']").replaceWith(function () {
            var embed = $encpJquery(this);
            var img = $encpJquery("<img class='en-media'/>");
            var src = embed.attr("src");
            img.attr("src", self.EMBEDDED_MEDIA_PATH_PREFIX + src);
            img.addClass(embed.attr("class"));
            img.addClass("encp-document-viewer");
            return img;
        });
    },

    /**
     * Process media in the note
     * @param rootElement Root element of elements to be processed
     */
    markBrokenNoteLinks: function(rootElement) {
    },

    markBrokenNoteLinksAsync: function(rootElement) {
        var promises = [];
        function getNoteId_Success(el, promise, noteId) {
            if (noteId == '0') $encpJquery(el).addClass('encp-broken-link');
            promise.resolve();
        }
        function getNoteId_Error(el, promise, error) {
            $encpJquery(el).addClass('encp-broken-link');
            promise.resolve();
        }
        $encpJquery(rootElement).find('a[href^="evernote:"]').each(function () {
            var res;
            var rej;
            var promise = new Promise(function (resolve, reject) {
                res = resolve;
                rej = reject;
            });
            promise.resolve = res;
            promise.reject = rej;
            promises.push(promise);
            window.getNoteId(this.href, getNoteId_Success.bind(null, this, promise), getNoteId_Error.bind(null, this, promise));
        });
        return Promise.all(promises);
    },

    /**
     * Set viewPort size of the screen.
     * @param viewPortSize - to be set
     */
    setViewPortSize: function(viewPortSize) {
        // nothing right now.
    },

    /**
     * Get viewPort size of the screen.
     * @returns {*} width:  width of the viewPort, height: height of viewPort.
     */
    viewPort: function() {
        return {
            width: window.innerWidth,
            height: window.innerHeight
        }
    },

    /**
     * Check if platform should handle window resize.
     * @returns true if resize should be handled, otherwise false
     */
    shouldHandleResizing: function() {
        return true;
    },

    /**
     * Check viewPort size has been set or not.
     * @returns true if viewPort size has been set.
     */
    hasViewPortBeenOverriden: function() {
        return false;
    },

    /**
     * Get images to be size adjustment required.
     * @param sourceType - source type of the contents to be considered.
     * @returns jQuery objects if required, otherwise null.
     */
    imagesToBeAdjusted: function(sourceType) {
        if (sourceType === 'notesource') {
            return $encpJquery('img');
        }
        return null;
    },

    /**
     * Zoom level adjustment value
     */
    ADDITIONAL_ZOOM_PERCENT: 10,

    /**
     * Adjust zoom level for web source notes.
     * @param targetObj - target object to be modified
     * @param referenceResolution - reference resolution to determine zoom level of contents
     */
    adjustZoomLevel: function(targetObj, referenceResolution) {
        if (referenceResolution == 0) {
            return;
        }
        var zoomPercent = (this.viewPort().width * 100 / referenceResolution) + this.ADDITIONAL_ZOOM_PERCENT;
        $encpJquery(targetObj).css('zoom', '' + (zoomPercent / 100));
    }

};

window.encpPlatform = new ENCPPlatform();

Evernote.startPresentation = function(guids,index){
    Evernote._presentationInstance = new PresentationUIController(window.notePresenter);
    Evernote._presentationInstance.start(guids,index, function() {
        Evernote._presentationInstance.showUI();
    });
};