/*globals define, require, start*/
/*jslint nomen: true*/

define([
    'jquery',
    '$ready!'
    /**
     * linkpicker test case: main view and controller
     * @param  {[type]} QUnit      [description]
     * @param  {[type]} $          [description]
     * @param  {[type]} Linkpicker [description]
     * @return {[type]}            [description]
     */
], function ($) {
    'use strict';

    var container = $('#qunit-fixture'),
        data = {},
        options = {
            linkUrl: '',
            callback: function (_title, _url, _newFlag, _linkType) {
                data = {
                    linkText: _title,
                    linkUrl: _url,
                    is_linkTargetBlank: _newFlag,
                    linkType: _linkType
                };
            }
        },

        //fake ajax
        treeResult = [{
            "children": [{
                "metadata": {
                    "WebUrl": "http://www.DemoShop.de/Shop.sf/?ObjectPath=/Shops/DemoShop/Products/ho_40407",
                    "parentId": "16375",
                    "WebUrlSSL": "http://www.DemoShop.de/Shop.sf/?ObjectPath=/Shops/DemoShop/Products/ho_40407",
                    "id": "16524",
                    "type": "Product",
                    "ClassID": "16447"
                },
                "data": {
                    "icon": "Product",
                    "title": "Jack Wolfskin Blizzard Jacket"
                }
            }, {
                "metadata": {
                    "WebUrl": "http://www.DemoShop.de/Shop.sf/?ObjectPath=/Shops/DemoShop/Products/lt_0401107001",
                    "parentId": "16375",
                    "WebUrlSSL": "http://www.DemoShop.de/Shop.sf/?ObjectPath=/Shops/DemoShop/Products/lt_0401107001",
                    "id": "16491",
                    "type": "Product",
                    "ClassID": "16368"
                },
                "data": {
                    "icon": "Product",
                    "title": "Leatherman Tool Survival"
                }
            }, {
                "metadata": {
                    "WebUrl": "http://www.DemoShop.de/Shop.sf/?ObjectPath=/Shops/DemoShop/Products/eg_1000111010",
                    "parentId": "16375",
                    "WebUrlSSL": "http://www.DemoShop.de/Shop.sf/?ObjectPath=/Shops/DemoShop/Products/eg_1000111010",
                    "id": "16497",
                    "type": "Product",
                    "ClassID": "16462"
                },
                "data": {
                    "icon": "Product",
                    "title": "Eureka El Capitan IV"
                }
            }],
            "metadata": {
                "WebUrl": "http://www.DemoShop.de/Shop.sf/?ObjectPath=/Shops/DemoShop/Categories",
                "childCount": 15,
                "parentId": "16350",
                "WebUrlSSL": "http://www.DemoShop.de/Shop.sf/?ObjectPath=/Shops/DemoShop/Categories",
                "id": "16375",
                "ClassID": "3671"
            },
            "data": {
                "icon": "StartPage",
                "title": "Home page"
            },
            "state": "open"
        }],

        advancedLinksResult = [{
            "Alias": "Advanced search",
            "Link": "?ViewAction=ViewDetailSearchProducts&ObjectPath=%2FShops%2FDemoShop"
        }, {
            "Alias": "New registration",
            "Link": "?ViewAction=ViewRegistration&ObjectPath=%2FShops%2FDemoShop"
        }, {
            "Alias": "Sign in",
            "Link": "?ViewAction=ViewRegistrationRedirect&HideNotice=1&ObjectPath=%2FShops%2FDemoShop"
        }, {
            "Alias": "Basket",
            "Link": "?ChangeAction=CreateBasket&ObjectPath=%2FShops%2FDemoShop"
        }, {
            "Alias": "Newsletters",
            "Link": "?ViewAction=ViewNewsletter&ObjectPath=%2FShops%2FDemoShop"
        }],

        fileManager = [{
            "currentGallerySize": "1344",
            "children": [{
                "files": [{
                    "width": null,
                    "extension": ".swf",
                    "name": "promo.swf",
                    "path": "promo.swf",
                    "height": null,
                    "directory": "/MediaGallery/",
                    "modified": 1200994146,
                    "size": 67089,
                    "fullpath": "/WebRoot/promo.swf",

                    "selectable": 1,
                    "mimetype": "application/x-shockwave-flash"
                }, {
                    "width": null,
                    "extension": ".png",
                    "name": "promo.png",
                    "path": "/promo.png",
                    "height": null,
                    "directory": "/MediaGallery",
                    "modified": 1200994146,
                    "size": 67089,
                    "fullpath": "/WebRoot/promo.png",
                    "selectable": 1,
                    "mimetype": "image/png"
                }],
                "children": [],
                "metadata": {
                    "displayname": "MediaGallery",
                    "type": "MediaGallery",
                    "path": ""
                },
                "data": "MediaGallery",
                "state": "closed"
            }],
            "maxGallerySize": "102400"
        }],

        _ajax = $.ajax,

        do_apply = function (_node) {
            $(_node).uiDialog('option', 'buttons')[0].trigger('click');
        };

    $.ajax = function (o) {

        var result = $.Deferred(),
            jqXHR = result.promise();

        if (o.data) {
            if (o.data.ViewAction === "JSONChildrenJSTree") {
                o.success.call(o.context, treeResult, 'success', jqXHR);
            }
            if (o.data.ViewAction === "JSONAdvancedLinks") {
                result.resolve(advancedLinksResult);
            }
            if (o.data.ViewAction === "JSONInitMediaGallery") {
                result.resolve(fileManager);
            }
        } else {
            return _ajax(o);
        }
        return result;
    };

    require([
        'testsuite/qunit',
        'de_epages/shop/linkpicker'
    /**
     * [ description]
     * @param  {[type]} linkpicker [description]
     * @return {[type]}            [description]
     */
    ], function (QUnit, linkpicker) {

        QUnit.module("de_epages/shop/linkpicker");

        QUnit.test("Linkpicker Prototype", function () {

            $.each([
                'initialize',
                'open',
                'render',
                '_getCorrectProtocol',
                '_getCorrectUrl',
                '_getActiveTabAndSetOptions',
                '_clearViewDataExceptFor',
                '_setLinkText',
                '_setLinkUrl',
                '_setLinkTarget'], function (i, fn) {

                QUnit.deepEqual($.isFunction(linkpicker[fn]), true, "Check whether " + fn + " is a function: $.isFunction(  $.linkpicker.prototype['" + fn + "'] )");
            });

        });

        QUnit.test("One instance of dialog initialized", function () {

            linkpicker.open(options);
            QUnit.strictEqual($('.linkpickerDialog').length, 1, "Check if one instance of dialog is present $('.linkpickerDialog').length === 1");
            linkpicker.close();
        });

        // let's push in some options
        $.extend(options, {
            linkText: 'Test Link',
            linkUrl: 'www.google.de',
            is_linkTargetBlank: true,
            linkType: 'tree'
        });

        QUnit.test("Check various linkTypes and open tabs", function () {

            linkpicker.open(options);
            QUnit.strictEqual($('.ep-linkpicker-tabpanelnode').tabs('option', 'active'), 0, "LinkType: Tree - ActiveTab: 0");
            linkpicker.close();

            options.linkType = 'filemanager';
            linkpicker.open(options);
            QUnit.strictEqual($('.ep-linkpicker-tabpanelnode').tabs('option', 'active'), 1, "LinkType: Filemanager - ActiveTab: 1");
            linkpicker.close();

            options.linkType = 'additional';
            linkpicker.open(options);
            QUnit.strictEqual($('.ep-linkpicker-tabpanelnode').tabs('option', 'active'), 2, "LinkType: Additional - ActiveTab: 2");
            linkpicker.close();

            options.linkType = 'external';
            linkpicker.open(options);
            QUnit.strictEqual($('.ep-linkpicker-tabpanelnode').tabs('option', 'active'), 3, "LinkType: External - ActiveTab: 3");
            linkpicker.close();

        });

        QUnit.test("Check passed parameters", function () {

            linkpicker.open(options);

            QUnit.strictEqual($('#ep-linkpicker-linkText').val(), options.linkText, "Check if passed value is inserted correctly: link text");
            QUnit.strictEqual($('#ep-linkpicker-linkTargetBlank').val(), options.is_linkTargetBlank ? 'on' : 'off', "Check if passed value is inserted correctly: blank target");
            $.each($('.ep-linkpicker-linkPreview'), function (i, node) {
                QUnit.strictEqual($(node).attr('title'), options.linkUrl, "Check if passed value is inserted correctly: Preview URL");
            });

            linkpicker.close();
        });

        QUnit.test("Check if button arrangement is still correct and trigger apply to check return values", function () {

            linkpicker.open(options);
            do_apply('.linkpickerDialog');

            QUnit.strictEqual(data.linkText, options.linkText, "Check if return value is correct: link text");
            QUnit.strictEqual(data.linkUrl, options.linkUrl, "Check if return value is correct: link url");
            QUnit.strictEqual(data.is_linkTargetBlank, options.is_linkTargetBlank, "Check if return value is correct: link target");
            QUnit.strictEqual(data.linkType, options.linkType, "Check if return value is correct: link type");

            linkpicker.close();

        });

        // etxtend our options
        $.extend(options, {
            use_absolute: true,
            use_ssl: true
        });

        QUnit.test("Check external link: Absolute and SSL", function () {

            options.linkType = 'external';
            linkpicker.open(options);

            $('#ep-linkpicker-externalUrl').val('www.google.de');
            $('#ep-linkpicker-externalUrl').trigger('keyup');
            do_apply('.linkpickerDialog');

            QUnit.strictEqual(data.linkUrl, 'http://www.google.de', "Check if return value is correct: link text");

            linkpicker.close();
        });

        QUnit.test("Check additional pages: convert relative to absolute, check if predefined value is not overwritten", function () {

            options.linkType = 'additional';
            linkpicker.open(options);

            $('input[name="additionalpages"][value="?ViewAction=ViewNewsletter&ObjectPath=%2FShops%2FDemoShop"]')
                .attr('checked', 'checked')
                .trigger('change');

            // check if text and url are set correctly
            QUnit.strictEqual($('#ep-linkpicker-linkText').val(), 'Test Link', 'Check if link text is not changed on select when picker is initialized with predefined value');
            $.each($('.ep-linkpicker-linkPreview'), function (i, node) {
                QUnit.strictEqual($(node).attr('title'), 'https://www.DemoShop.de/Shop.sf?ViewAction=ViewNewsletter&ObjectPath=%2FShops%2FDemoShop', 'Absolute ssl link path: https://www.DemoShop.de/?ViewAction=ViewNewsletter&ObjectPath=%2FShops%2FDemoShop');
            });

            linkpicker.close();
        });

        QUnit.test("Check filemanager: file urls are converted correctly", function () {

            options.linkType = 'filemanager';
            linkpicker.open(options);

            // displayable file
            $('#ep-linkpicker-filemanager button').trigger('click');
            $($('li.ep-mediagallery-fileContainer')[1]).addClass('ui-selected');
            do_apply('.fileManagerDialog');
            QUnit.strictEqual($('.ep-linkpicker-linkPreview').attr('title'), 'https://www.DemoShop.de/WebRoot/promo.png', 'Absolute file path: https://www.DemoShop.de/WebRoot/promo.png');
            QUnit.strictEqual($('.ep-linkpicker-filemanager-preview > img').attr('src'), '/WebRoot/promo.png', 'Preview image is correct');
            QUnit.strictEqual($('.ep-linkpicker-filemanager-previewLabel').html(), 'promo.png', 'Label is set correctly');

            // not displayable file
            $('#ep-linkpicker-filemanager button').trigger('click');
            $($('li.ep-mediagallery-fileContainer')[0]).addClass('ui-selected');
            do_apply('.fileManagerDialog');
            QUnit.strictEqual($('.ep-linkpicker-linkPreview').attr('title'), 'https://www.DemoShop.de/WebRoot/promo.swf', 'Absolute file path: https://www.DemoShop.de/WebRoot/promo.swf');
            QUnit.ok(
                $('.ep-linkpicker-filemanager-preview > img').attr('src').match(/ico_unknowndocumentpreview\.png$/),
                'Preview image is correct (placeholder)'
            );
            QUnit.strictEqual($('.ep-linkpicker-filemanager-previewLabel').html(), 'promo.swf', 'Label is set correctly');

            linkpicker.close();
        });

        QUnit.test("Check tree: Change title, convert absolute to relative, check absolute protocol change (to https)", function () {

            // tree (convert abs to rel url)
            options.linkType = 'tree';
            options.use_absolute = false;
            options.linkText = '';
            options.linkUrl = '';

            linkpicker.open(options);

            $('.jstree-leaf:first a').trigger('click');
            QUnit.strictEqual($('#ep-linkpicker-linkText').val(), 'Jack Wolfskin Blizzard Jacket', 'Title was changed to "Jack Wolfskin Blizzard Jacket"');
            QUnit.strictEqual($('.ep-linkpicker-linkPreview').attr('title'), '?ObjectPath=/Shops/DemoShop/Products/ho_40407', 'Url converted to relative');

            linkpicker.close();

            options.use_absolute = true;
            options.use_ssl = true;

            linkpicker.open(options);

            $('.jstree-leaf:first a').trigger('click');
            QUnit.strictEqual($('.ep-linkpicker-linkPreview').attr('title'), 'https://www.DemoShop.de/Shop.sf/?ObjectPath=/Shops/DemoShop/Products/ho_40407', 'Protocol changed to https');

            linkpicker.close();
        });
    });
});