<commit_before>'use strict';

const BbPromise = require('bluebird'),
    Operations = require('./../Constants').Operations,
    Usage = require('./../Constants').Usage,
    StorageEntityType = require('./../Constants').StorageEntityType,
    AzuriteContainerRequest = require('./../model/AzuriteContainerRequest'),
    AzuriteBlobRequest = require('./../model/AzuriteBlobRequest'),
    sm = require('./../StorageManager'),
    // Validation modules
    ValidationContext = require('./../validation/ValidationContext'),
    AppendMaxBlobCommittedBlocksVal = require('./../validation/AppendMaxBlobCommittedBlocks'),
    BlobCreationSizeVal = require('./../validation/BlobCreationSize'),
    BlockPageSizeVal = require('./../validation/BlockPageSize'),
    SupportedBlobTypeVal = require('./../validation/SupportedBlobType'),
    CompatibleBlobTypeVal = require('./../validation/CompatibleBlobType'),
    MD5Val = require('./../validation/MD5'),
    ContentLengthExistsVal = require('./../validation/ContentLengthExists'),
    ContainerExistsVal = require('./../validation/ContainerExists'),
    BlobExistsVal = require('./../validation/BlobExists'),
    BlobCommittedVal = require('./../validation/BlobCommitted'),
    IsOfBlobTypeVal = require('./../validation/IsOfBlobType'),
    RangeVal = require('./../validation/Range'),
    PageAlignmentVal = require('./../validation/PageAlignment'),
    NumOfSignedIdentifiersVal = require('./../validation/NumOfSignedIdentifiers'),
    PutBlobHeaderVal = require('./../validation/PutBlobHeaders'),
    ConditionalRequestHeadersVal = require('./../validation/ConditionalRequestHeaders'),
    AppendBlobConditionalRequestHeadersVal = require('./../validation/AppendBlobConditionalRequestHeaders'),
    PageBlobHeaderSanityVal = require('./../validation/PageBlobHeaderSanity'),
    AssociatedSnapshotDeletion = require('./../validation/AssociatedSnapshotsDeletion'),
    LeaseActionsValidation = require('./../validation/LeaseActions'),
    LeaseDurationValidation = require('./../validation/LeaseDuration'),
    LeaseIdValidation = require('./../validation/LeaseId'),
    ContainerLeaseUsageValidation = require('./../validation/ContainerLeaseUsage'),
    ConflictingContainerVal = require('./../validation/ConflictingContainer'),
    BlobLeaseUsageValidation = require('./../validation/BlobLeaseUsage'),
    CopyStatusValidation = require('./../validation/CopyStatus');

module.exports = (req, res, next) => {
    BbPromise.try(() => {
        if (req.azuriteOperation === undefined || req.azuriteOperation === Operations.Blob.COPY_BLOB) {
            res.status(501).send('Not Implemented yet.');
            return;
        }
        const request = req.azuriteRequest;
        // const { containerProxy } = sm._getCollectionAndContainer(request.containerName);
        const o = sm._getCollectionAndContainer(request.containerName);
        const containerProxy = o.containerProxy;
        const { blobProxy } = sm._getCollectionAndBlob(request.containerName, request.id);
        const validationContext = new ValidationContext({
            request: request,
            containerProxy: containerProxy,
            blobProxy: blobProxy
        })
        validations[req.azuriteOperation](request, validationContext);
        next();
        // Refactor me: Move this to bin/azurite (exception needs to carry res object), and handle entire exception handling there
    }).catch((e) => {
        res.status(e.statusCode || 500).send(e.message);
        if (!e.statusCode) throw e;
    });
}

const validations = {};
validations[Operations.Account.LIST_CONTAINERS] = (request, valContext) => {
    // NO VALIDATIONS
}

validations[Operations.Container.CREATE_CONTAINER] = (request, valContext) => {
    valContext
        .run(ConflictingContainerVal);
}

validations[Operations.Container.DELETE_CONTAINER] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Delete });
}

validations[Operations.Blob.PUT_BLOB] = (request, valContext) => {
    valContext
        .run(MD5Val)
        .run(ContainerExistsVal)
        .run(CompatibleBlobTypeVal)
        .run(SupportedBlobTypeVal)
        .run(PutBlobHeaderVal)
        .run(BlobCreationSizeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Blob.APPEND_BLOCK] = (request, valContext) => {
    valContext
        .run(ContentLengthExistsVal)
        .run(ContainerExistsVal)
        .run(BlockPageSizeVal)
        .run(MD5Val)
        .run(AppendMaxBlobCommittedBlocksVal)
        .run(CompatibleBlobTypeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(AppendBlobConditionalRequestHeadersVal);
}

validations[Operations.Blob.DELETE_BLOB] = (request, valContext) => {
    valContext
        .run(BlobExistsVal)
        .run(AssociatedSnapshotDeletion, { collection: sm.db.getCollection(request.containerName) })
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
}

validations[Operations.Blob.GET_BLOB] = (request, valContext) => {
    valContext
        .run(BlobExistsVal)
        .run(BlobCommittedVal)
        .run(RangeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Read })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Read })
}

validations[Operations.Container.LIST_BLOBS] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal);
}

validations[Operations.Blob.PUT_BLOCK] = (request, valContext) => {
    valContext
        .run(ContentLengthExistsVal)
        .run(BlockPageSizeVal)
        .run(ContainerExistsVal)
        .run(MD5Val)
        .run(CompatibleBlobTypeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
}

validations[Operations.Blob.PUT_BLOCK_LIST] = (request, valContext) => {
    const blockList = request.payload;
    for (const block of blockList) {
        const blockName = `${request.containerName}-${request.blobName}-${block.id}`;
        // TODO: FIXME: This should be replaced with a BlockExists Validation
        valContext.run(BlobExistsVal, {
            blobProxy: { publicName: () => { return blockName } }
        });
    }
    valContext
        .run(ContainerExistsVal)
        .run(CompatibleBlobTypeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Blob.GET_BLOCK_LIST] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(IsOfBlobTypeVal, { entityType: StorageEntityType.BlockBlob })
        .run(BlobLeaseUsageValidation, { usage: Usage.Read });
}

validations[Operations.Blob.SET_BLOB_METADATA] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(BlobLeaseUsageValidation, { usage: Usage.Write });
}

validations[Operations.Blob.GET_BLOB_METADATA] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(BlobCommittedVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Read })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Read });
}

validations[Operations.Blob.GET_BLOB_PROPERTIES] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(BlobCommittedVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Read })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Read });
}

validations[Operations.Blob.SET_BLOB_PROPERTIES] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(BlobLeaseUsageValidation, { usage: Usage.Write });
}

validations[Operations.Container.SET_CONTAINER_METADATA] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Container.GET_CONTAINER_METADATA] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other });
}

validations[Operations.Container.GET_CONTAINER_PROPERTIES] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other });
}

validations[Operations.Blob.PUT_PAGE] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ContentLengthExistsVal)
        .run(IsOfBlobTypeVal, { entityType: StorageEntityType.PageBlob })
        .run(MD5Val)
        .run(BlockPageSizeVal)
        .run(PageAlignmentVal)
        .run(PageBlobHeaderSanityVal)
        .run(CompatibleBlobTypeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Blob.GET_PAGE_RANGES] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(PageAlignmentVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Read })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Container.SET_CONTAINER_ACL] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(NumOfSignedIdentifiersVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other });
}

validations[Operations.Container.GET_CONTAINER_ACL] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other });
}

validations[Operations.Blob.SNAPSHOT_BLOB] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(BlobLeaseUsageValidation, { usage: Usage.Read });
}

validations[Operations.Container.LEASE_CONTAINER] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(LeaseActionsValidation)
        .run(LeaseDurationValidation)
        .run(LeaseIdValidation)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Blob.LEASE_BLOB] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(LeaseDurationValidation)
        .run(LeaseIdValidation)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(LeaseActionsValidation);
}

validations[Operations.Blob.COPY_BLOB] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(CopyStatusValidation);
}<commit_msg>fixes #85<commit_after>'use strict';

const BbPromise = require('bluebird'),
    Operations = require('./../Constants').Operations,
    Usage = require('./../Constants').Usage,
    StorageEntityType = require('./../Constants').StorageEntityType,
    AzuriteContainerRequest = require('./../model/AzuriteContainerRequest'),
    AzuriteBlobRequest = require('./../model/AzuriteBlobRequest'),
    sm = require('./../StorageManager'),
    // Validation modules
    ValidationContext = require('./../validation/ValidationContext'),
    AppendMaxBlobCommittedBlocksVal = require('./../validation/AppendMaxBlobCommittedBlocks'),
    BlobCreationSizeVal = require('./../validation/BlobCreationSize'),
    BlockPageSizeVal = require('./../validation/BlockPageSize'),
    SupportedBlobTypeVal = require('./../validation/SupportedBlobType'),
    CompatibleBlobTypeVal = require('./../validation/CompatibleBlobType'),
    MD5Val = require('./../validation/MD5'),
    ContentLengthExistsVal = require('./../validation/ContentLengthExists'),
    ContainerExistsVal = require('./../validation/ContainerExists'),
    BlobExistsVal = require('./../validation/BlobExists'),
    BlobCommittedVal = require('./../validation/BlobCommitted'),
    IsOfBlobTypeVal = require('./../validation/IsOfBlobType'),
    RangeVal = require('./../validation/Range'),
    PageAlignmentVal = require('./../validation/PageAlignment'),
    NumOfSignedIdentifiersVal = require('./../validation/NumOfSignedIdentifiers'),
    PutBlobHeaderVal = require('./../validation/PutBlobHeaders'),
    ConditionalRequestHeadersVal = require('./../validation/ConditionalRequestHeaders'),
    AppendBlobConditionalRequestHeadersVal = require('./../validation/AppendBlobConditionalRequestHeaders'),
    PageBlobHeaderSanityVal = require('./../validation/PageBlobHeaderSanity'),
    AssociatedSnapshotDeletion = require('./../validation/AssociatedSnapshotsDeletion'),
    LeaseActionsValidation = require('./../validation/LeaseActions'),
    LeaseDurationValidation = require('./../validation/LeaseDuration'),
    LeaseIdValidation = require('./../validation/LeaseId'),
    ContainerLeaseUsageValidation = require('./../validation/ContainerLeaseUsage'),
    ConflictingContainerVal = require('./../validation/ConflictingContainer'),
    BlobLeaseUsageValidation = require('./../validation/BlobLeaseUsage'),
    CopyStatusValidation = require('./../validation/CopyStatus');

module.exports = (req, res, next) => {
    BbPromise.try(() => {
        if (req.azuriteOperation === undefined || req.azuriteOperation === Operations.Blob.COPY_BLOB) {
            res.status(501).send('Not Implemented yet.');
            return;
        }
        const request = req.azuriteRequest;
        // const { containerProxy } = sm._getCollectionAndContainer(request.containerName);
        const o = sm._getCollectionAndContainer(request.containerName);
        const containerProxy = o.containerProxy;
        const { blobProxy } = sm._getCollectionAndBlob(request.containerName, request.id);
        const validationContext = new ValidationContext({
            request: request,
            containerProxy: containerProxy,
            blobProxy: blobProxy
        })
        validations[req.azuriteOperation](request, validationContext);
        next();
        // Refactor me: Move this to bin/azurite (exception needs to carry res object), and handle entire exception handling there
    }).catch((e) => {
        res.status(e.statusCode || 500).send(e.message);
        if (!e.statusCode) throw e;
    });
}

const validations = {};
validations[Operations.Account.LIST_CONTAINERS] = (request, valContext) => {
    // NO VALIDATIONS
}

validations[Operations.Container.CREATE_CONTAINER] = (request, valContext) => {
    valContext
        .run(ConflictingContainerVal);
}

validations[Operations.Container.DELETE_CONTAINER] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Delete });
}

validations[Operations.Blob.PUT_BLOB] = (request, valContext) => {
    valContext
        .run(MD5Val)
        .run(ContainerExistsVal)
        .run(CompatibleBlobTypeVal)
        .run(SupportedBlobTypeVal)
        .run(PutBlobHeaderVal)
        .run(BlobCreationSizeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Blob.APPEND_BLOCK] = (request, valContext) => {
    valContext
        .run(BlobExistsVal)
        .run(ContentLengthExistsVal)
        .run(BlockPageSizeVal)
        .run(MD5Val)
        .run(AppendMaxBlobCommittedBlocksVal)
        .run(CompatibleBlobTypeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(AppendBlobConditionalRequestHeadersVal);
}

validations[Operations.Blob.DELETE_BLOB] = (request, valContext) => {
    valContext
        .run(BlobExistsVal)
        .run(AssociatedSnapshotDeletion, { collection: sm.db.getCollection(request.containerName) })
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
}

validations[Operations.Blob.GET_BLOB] = (request, valContext) => {
    valContext
        .run(BlobExistsVal)
        .run(BlobCommittedVal)
        .run(RangeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Read })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Read })
}

validations[Operations.Container.LIST_BLOBS] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal);
}

validations[Operations.Blob.PUT_BLOCK] = (request, valContext) => {
    valContext
        .run(ContentLengthExistsVal)
        .run(BlockPageSizeVal)
        .run(ContainerExistsVal)
        .run(MD5Val)
        .run(CompatibleBlobTypeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
}

validations[Operations.Blob.PUT_BLOCK_LIST] = (request, valContext) => {
    const blockList = request.payload;
    for (const block of blockList) {
        const blockName = `${request.containerName}-${request.blobName}-${block.id}`;
        // TODO: FIXME: This should be replaced with a BlockExists Validation
        valContext.run(BlobExistsVal, {
            blobProxy: { publicName: () => { return blockName } }
        });
    }
    valContext
        .run(ContainerExistsVal)
        .run(CompatibleBlobTypeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Blob.GET_BLOCK_LIST] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(IsOfBlobTypeVal, { entityType: StorageEntityType.BlockBlob })
        .run(BlobLeaseUsageValidation, { usage: Usage.Read });
}

validations[Operations.Blob.SET_BLOB_METADATA] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(BlobLeaseUsageValidation, { usage: Usage.Write });
}

validations[Operations.Blob.GET_BLOB_METADATA] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(BlobCommittedVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Read })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Read });
}

validations[Operations.Blob.GET_BLOB_PROPERTIES] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(BlobCommittedVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Read })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Read });
}

validations[Operations.Blob.SET_BLOB_PROPERTIES] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(BlobLeaseUsageValidation, { usage: Usage.Write });
}

validations[Operations.Container.SET_CONTAINER_METADATA] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Container.GET_CONTAINER_METADATA] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other });
}

validations[Operations.Container.GET_CONTAINER_PROPERTIES] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other });
}

validations[Operations.Blob.PUT_PAGE] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ContentLengthExistsVal)
        .run(IsOfBlobTypeVal, { entityType: StorageEntityType.PageBlob })
        .run(MD5Val)
        .run(BlockPageSizeVal)
        .run(PageAlignmentVal)
        .run(PageBlobHeaderSanityVal)
        .run(CompatibleBlobTypeVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Write })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Blob.GET_PAGE_RANGES] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(PageAlignmentVal)
        .run(BlobLeaseUsageValidation, { usage: Usage.Read })
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Container.SET_CONTAINER_ACL] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(NumOfSignedIdentifiersVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other });
}

validations[Operations.Container.GET_CONTAINER_ACL] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(ContainerLeaseUsageValidation, { usage: Usage.Other });
}

validations[Operations.Blob.SNAPSHOT_BLOB] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(BlobLeaseUsageValidation, { usage: Usage.Read });
}

validations[Operations.Container.LEASE_CONTAINER] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(LeaseActionsValidation)
        .run(LeaseDurationValidation)
        .run(LeaseIdValidation)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write });
}

validations[Operations.Blob.LEASE_BLOB] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(LeaseDurationValidation)
        .run(LeaseIdValidation)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(LeaseActionsValidation);
}

validations[Operations.Blob.COPY_BLOB] = (request, valContext) => {
    valContext
        .run(ContainerExistsVal)
        .run(BlobExistsVal)
        .run(ConditionalRequestHeadersVal, { usage: Usage.Write })
        .run(CopyStatusValidation);
}<|endoftext|>


<commit_before>var Mapbender = Mapbender || {};
$.extend(true, Mapbender, { layer: {
    'wms': {
        create: function(layerDef) {
            var layers = [];
            var queryLayers = [];
            $.each(layerDef.configuration.layers, function(idx, layer) {
                var layerDef = $.extend({},
                    { visible: true, queryable: false }, layer );
                if(layerDef.visible) {
                    layers.push(layerDef.name);
                }
                if(layerDef.queryable) {
                    queryLayers.push(layerDef.name);
                }
            });

            mqLayerDef = {
                type:        'wms',
                label:       layerDef.configuration.title,
                url:         layerDef.configuration.url,

                layers:      layers,
                queryLayers: queryLayers,
                allLayers:   layerDef.configuration.layers,

                transparent: layerDef.configuration.transparent,
                format:      layerDef.configuration.format,

                isBaseLayer: layerDef.configuration.baselayer,
                opacity:     layerDef.configuration.opacity,
                visible:     layerDef.configuration.visible,
                singleTile:  !layerDef.configuration.tiled,
                attribution: layerDef.configuration.attribution
            };
            return mqLayerDef;
        },

        featureInfo: function(layer, x, y, callback) {
            var queryLayers = layer.options.queryLayers ?
                layer.options.queryLayers :
                layer.options.layers;

            var params = $.param({
                REQUEST: 'GetFeatureInfo',
                VERSION: layer.olLayer.params.VERSION,
                EXCEPTIONS: "application/vnd.ogc.se_xml",
                SRS: layer.olLayer.params.SRS,
                BBOX: layer.map.center().box.join(','),
                WIDTH: $(layer.map.element).width(),
                HEIGHT: $(layer.map.element).height(),
                X: x,
                Y: y,
                LAYERS: queryLayers.join(','),
                QUERY_LAYERS: queryLayers.join(',')
            });

            // this clever shit was taken from $.ajax
            requestUrl = layer.options.url;
            requestUrl += (/\?/.test(layer.options.url) ? '&' : '?') + params;

            $.ajax({
                url: Mapbender.configuration.proxies.open,
                data: {
                    url: requestUrl
                },
                success: function(data) {
                    callback({
                        layerId: layer.id,
                        response: data
                    });
                },
                error: function(error) {
                    callback({
                        layerId: layer.id,
                        response: 'ERROR'
                    });
                }
            });
        },

        loadFromUrl: function(url) {
            var dlg = $('

').attr('id', 'loadfromurl-wms'),
                spinner = $('')
                    .attr('src', Mapbender.configuration.assetPath + 'bundles/mapbenderwms/images/spinner.gif')
                    .appendTo(dlg);
            dlg.appendTo($('body'));

            $('


<commit_before>/*
 * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved.
 */
define(function(require, exports, module) {
    // Load dependent modules
    var CommandManager      = require("CommandManager")
    ,   Commands            = require("Commands")
    ,   NativeFileSystem    = require("NativeFileSystem").NativeFileSystem
    ,   ProjectManager      = require("ProjectManager")
    ,   DocumentManager     = require("DocumentManager")
    ,   Strings             = require("strings");
    ;

    /**
     * Handlers for commands related to file handling (opening, saving, etc.)
     */

    var _editor, _title, _currentFilePath, _currentTitlePath,
        _isDirty = false,
        _savedUndoPosition = 0;

    var _ignoreEditorChanges = false;

    function init(editor, title) {
        _editor = editor;
        _title = title;

        _editor.setOption("onChange", function() {
            updateDirty();
        });

        // Register global commands
        CommandManager.register(Commands.FILE_OPEN, handleFileOpen);
        // TODO: For now, hook up File > New to the "new in project" handler. Eventually
        // File > New should open a new blank tab, and handleFileNewInProject should
        // be called from a "+" button in the project
        CommandManager.register(Commands.FILE_NEW, handleFileNewInProject);
        CommandManager.register(Commands.FILE_SAVE, handleFileSave);
        CommandManager.register(Commands.FILE_CLOSE, handleFileClose);
    };

    exports.getEditor = function getEditor() {
        return _editor;
    };

    exports.isDirty = function isDirty() {
        return _isDirty;
    };

    function updateDirty() {
        // Don't send out spurious dirty-bit notifications while populating editor with the contents
        // of a newly-opened file, or when clearing editor while closing a file.
        if (_ignoreEditorChanges)
            return;

        // If we've undone past the undo position at the last save, and there is no redo stack,
        // then we can never get back to a non-dirty state.
        var historySize = _editor.historySize();
        if (historySize.undo < _savedUndoPosition && historySize.redo == 0) {
            _savedUndoPosition = -1;
        }
        var newIsDirty = (_editor.historySize().undo != _savedUndoPosition);
        if (_isDirty != newIsDirty) {
            _isDirty = newIsDirty;
            updateTitle();

            DocumentManager.temp_updateDirty(_isDirty);
        }
    }

    function updateTitle() {
        _title.text(
            _currentTitlePath
                ? (_currentTitlePath + (_isDirty ? " \u2022" : ""))
                : "Untitled"
        );
    }

    function handleFileOpen(fullPath) {
        // TODO: In the future, when we implement multiple open files, we won't close the previous file when opening
        // a new one. However, for now, since we only support a single open document, I'm pretending as if we're
        // closing the existing file first. This is so that I can put the code that checks for an unsaved file and
        // prompts the user to save it in the close command, where it belongs. When we implement multiple open files,
        // we can remove this here.
        var result;
        if (_currentFilePath) {
            result = new $.Deferred();
            CommandManager
                .execute(Commands.FILE_CLOSE)
                .done(function() {
                    doOpenWithOptionalPath(fullPath)
                        .done(function() {
                            result.resolve();
                        })
                        .fail(function() {
                            result.reject();
                        });
                })
                .fail(function() {
                    result.reject();
                });
        }
        else {
            result = doOpenWithOptionalPath(fullPath);
        }
        result.always(function() {
            _editor.focus();
        });
        return result;
    }

    function doOpenWithOptionalPath(fullPath) {
        var result;
        if (!fullPath) {
            // Prompt the user with a dialog
            // TODO: we're relying on this to not be asynchronous--is that safe?
            NativeFileSystem.showOpenDialog(false, false, Strings.OPEN_FILE, ProjectManager.getProjectRoot().fullPath,
                ["htm", "html", "js", "css"], function(files) {
                    if (files.length > 0) {
                        result = doOpen(files[0]);
                        return;
                    }
                });
        }
        else {
            result = doOpen(fullPath);
        }
        if (!result)
            result = (new $.Deferred()).reject();
        return result;
    }

    function doOpen(fullPath) {
        var result = new $.Deferred();
        if (!fullPath) {
            console.log("doOpen() called without fullPath");
            return result.reject();
        }

        var reader = new NativeFileSystem.FileReader();

        // TODO: we should implement something like NativeFileSystem.resolveNativeFileSystemURL() (similar
        // to what's in the standard file API) to get a FileEntry, rather than manually constructing it
        var fileEntry = new NativeFileSystem.FileEntry(fullPath);

        // TODO: it's weird to have to construct a FileEntry just to get a File.
        fileEntry.file(function(file) {
            reader.onload = function(event) {
                _currentFilePath = _currentTitlePath = fullPath;

                // In the main toolbar, show the project-relative path (if the file is inside the current project)
                // or the full absolute path (if it's not in the project).
                _currentTitlePath = ProjectManager.makeProjectRelativeIfPossible(fullPath);

                // TODO: move to EditorManager listener
                _ignoreEditorChanges = true;
                _editor.setValue(event.target.result);
                _ignoreEditorChanges = false;

                DocumentManager.showInEditor(fileEntry);

                // Make sure we can't undo back to the previous content.
                _editor.clearHistory();

                // This should be 0, but just to be safe...
                _savedUndoPosition = _editor.historySize().undo;
                updateDirty();

                result.resolve();
            };

            reader.onerror = function(event) {
                showFileOpenError(event.target.error.code, fullPath);
                result.reject();
            }

            reader.readAsText(file, "utf8");
        },
        function fileEntry_onerror(event) {
            showFileOpenError(event.target.error.code, fullPath);
            result.reject();
        });

        return result;
    }

    function handleFileNewInProject() {
        // Determine the directory to put the new file
        // If a file is currently selected, put it next to it.
        // If a directory is currently selected, put it in it.
        // If nothing is selected, put it at the root of the project
        var baseDir,
            selected = ProjectManager.getSelectedItem() || ProjectManager.getProjectRoot();

        baseDir = selected.fullPath;
        if (selected.isFile)
            baseDir = baseDir.substr(0, baseDir.lastIndexOf("/"));

        // Create the new node. The createNewItem function does all the heavy work
        // of validating file name, creating the new file and selecting.
        // TODO: Use a unique name like Untitled-1, Untitled-2, etc.
        return ProjectManager.createNewItem(baseDir, "Untitled.js", false);
    }

    function handleFileSave() {
        var result = new $.Deferred();
        if (_currentFilePath && _isDirty) {
            // TODO: we should implement something like NativeFileSystem.resolveNativeFileSystemURL() (similar
            // to what's in the standard file API) to get a FileEntry, rather than manually constructing it
            var fileEntry = new NativeFileSystem.FileEntry(_currentFilePath);

            fileEntry.createWriter(
                function(writer) {
                    writer.onwriteend = function() {
                        _savedUndoPosition = _editor.historySize().undo;
                        updateDirty();
                        result.resolve();
                    }
                    writer.onerror = function(event) {
                        showSaveFileError(event.target.error.code, _currentFilePath);
                        result.reject();
                    }

                    // TODO (jasonsj): Blob instead of string
                    writer.write(_editor.getValue());
                },
                function(event) {
                    showSaveFileError(event.target.error.code, _currentFilePath);
                    result.reject();
                }
            );
        }
        else {
            result.resolve();
        }
        result.always(function() {
            _editor.focus();
        });
        return result;
    }

    function handleFileClose() {
        var result = new $.Deferred();
        if (_currentFilePath && _isDirty) {
            brackets.showModalDialog(
                  brackets.DIALOG_ID_SAVE_CLOSE
                , Strings.SAVE_CLOSE_TITLE
                , Strings.format(Strings.SAVE_CLOSE_MESSAGE, _currentTitlePath)
            ).done(function(id) {
                if (id === brackets.DIALOG_BTN_CANCEL) {
                    result.reject();
                }
                else {
                    if (id === brackets.DIALOG_BTN_OK) {
                        CommandManager
                            .execute(Commands.FILE_SAVE)
                            .done(function() {
                                doClose();
                                result.resolve();
                            })
                            .fail(function() {
                                result.reject();
                            });
                    }
                    else {
                        // This is the "Don't Save" case--we can just go ahead and close the file.
                        doClose();
                        result.resolve();
                    }
                }
            });
            result.always(function() {
                _editor.focus();
            });
        }
        else {
            doClose();
            _editor.focus();
            result.resolve();
        }
        return result;
    }

    function doClose() {
        // TODO: When we implement multiple files being open, this will probably change to just
        // dispose of the editor for the current file (and will later change again if we choose to
        // limit the number of open editors).
        _ignoreEditorChanges = true;
        _editor.setValue("");
        _ignoreEditorChanges = false;

        _editor.clearHistory();
        _currentFilePath = _currentTitlePath = null;
        _savedUndoPosition = 0;
        _isDirty = false;
        updateTitle();
        _editor.focus();

        DocumentManager.closeCurrentDocument();
    }

    function showFileOpenError(code, path) {
        brackets.showModalDialog(
              brackets.DIALOG_ID_ERROR
            , Strings.ERROR_OPENING_FILE_TITLE
            , Strings.format(
                    Strings.ERROR_OPENING_FILE
                  , path
                  , getErrorString(code))
        );
    }

    function showSaveFileError(code, path) {
        brackets.showModalDialog(
              brackets.DIALOG_ID_ERROR
            , Strings.ERROR_SAVING_FILE_TITLE
            , Strings.format(
                    Strings.ERROR_SAVING_FILE
                  , path
                  , getErrorString(code))
        );
    }

    function getErrorString(code) {
        // There are a few error codes that we have specific error messages for. The rest are
        // displayed with a generic "(error N)" message.
        var result;

        if (code == FileError.NOT_FOUND_ERR)
            result = Strings.NOT_FOUND_ERR;
        else if (code == FileError.NOT_READABLE_ERR)
            result = Strings.NOT_READABLE_ERR;
        else if (code == FileError.NO_MODIFICATION_ALLOWED_ERR)
            result = Strings.NO_MODIFICATION_ALLOWED_ERR;
        else
            result = Strings.format(Strings.GENERIC_ERROR, code);

        return result;
    }

    // Define public API
    exports.init = init;
});

<commit_msg>Fix updating of file-name title above editor. It was only working before because it relied on a spurious dirty-bit change that was getting dispatched in the middle of loading a new file.<commit_after>/*
 * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved.
 */
define(function(require, exports, module) {
    // Load dependent modules
    var CommandManager      = require("CommandManager")
    ,   Commands            = require("Commands")
    ,   NativeFileSystem    = require("NativeFileSystem").NativeFileSystem
    ,   ProjectManager      = require("ProjectManager")
    ,   DocumentManager     = require("DocumentManager")
    ,   Strings             = require("strings");
    ;

    /**
     * Handlers for commands related to file handling (opening, saving, etc.)
     */

    var _editor, _title, _currentFilePath, _currentTitlePath,
        _isDirty = false,
        _savedUndoPosition = 0;

    var _ignoreEditorChanges = false;

    function init(editor, title) {
        _editor = editor;
        _title = title;

        _editor.setOption("onChange", function() {
            updateDirty();
        });

        // Register global commands
        CommandManager.register(Commands.FILE_OPEN, handleFileOpen);
        // TODO: For now, hook up File > New to the "new in project" handler. Eventually
        // File > New should open a new blank tab, and handleFileNewInProject should
        // be called from a "+" button in the project
        CommandManager.register(Commands.FILE_NEW, handleFileNewInProject);
        CommandManager.register(Commands.FILE_SAVE, handleFileSave);
        CommandManager.register(Commands.FILE_CLOSE, handleFileClose);
    };

    exports.getEditor = function getEditor() {
        return _editor;
    };

    exports.isDirty = function isDirty() {
        return _isDirty;
    };

    function updateDirty() {
        // Don't send out spurious dirty-bit notifications while populating editor with the contents
        // of a newly-opened file, or when clearing editor while closing a file.
        if (_ignoreEditorChanges)
            return;

        // If we've undone past the undo position at the last save, and there is no redo stack,
        // then we can never get back to a non-dirty state.
        var historySize = _editor.historySize();
        if (historySize.undo < _savedUndoPosition && historySize.redo == 0) {
            _savedUndoPosition = -1;
        }
        var newIsDirty = (_editor.historySize().undo != _savedUndoPosition);
        if (_isDirty != newIsDirty) {
            _isDirty = newIsDirty;
            updateTitle();

            DocumentManager.temp_updateDirty(_isDirty);
        }
    }

    function updateTitle() {
        _title.text(
            _currentTitlePath
                ? (_currentTitlePath + (_isDirty ? " \u2022" : ""))
                : "Untitled"
        );
    }

    function handleFileOpen(fullPath) {
        // TODO: In the future, when we implement multiple open files, we won't close the previous file when opening
        // a new one. However, for now, since we only support a single open document, I'm pretending as if we're
        // closing the existing file first. This is so that I can put the code that checks for an unsaved file and
        // prompts the user to save it in the close command, where it belongs. When we implement multiple open files,
        // we can remove this here.
        var result;
        if (_currentFilePath) {
            result = new $.Deferred();
            CommandManager
                .execute(Commands.FILE_CLOSE)
                .done(function() {
                    doOpenWithOptionalPath(fullPath)
                        .done(function() {
                            result.resolve();
                        })
                        .fail(function() {
                            result.reject();
                        });
                })
                .fail(function() {
                    result.reject();
                });
        }
        else {
            result = doOpenWithOptionalPath(fullPath);
        }
        result.always(function() {
            _editor.focus();
        });
        return result;
    }

    function doOpenWithOptionalPath(fullPath) {
        var result;
        if (!fullPath) {
            // Prompt the user with a dialog
            // TODO: we're relying on this to not be asynchronous--is that safe?
            NativeFileSystem.showOpenDialog(false, false, Strings.OPEN_FILE, ProjectManager.getProjectRoot().fullPath,
                ["htm", "html", "js", "css"], function(files) {
                    if (files.length > 0) {
                        result = doOpen(files[0]);
                        return;
                    }
                });
        }
        else {
            result = doOpen(fullPath);
        }
        if (!result)
            result = (new $.Deferred()).reject();
        return result;
    }

    function doOpen(fullPath) {
        var result = new $.Deferred();
        if (!fullPath) {
            console.log("doOpen() called without fullPath");
            return result.reject();
        }

        var reader = new NativeFileSystem.FileReader();

        // TODO: we should implement something like NativeFileSystem.resolveNativeFileSystemURL() (similar
        // to what's in the standard file API) to get a FileEntry, rather than manually constructing it
        var fileEntry = new NativeFileSystem.FileEntry(fullPath);

        // TODO: it's weird to have to construct a FileEntry just to get a File.
        fileEntry.file(function(file) {
            reader.onload = function(event) {
                _currentFilePath = _currentTitlePath = fullPath;

                // In the main toolbar, show the project-relative path (if the file is inside the current project)
                // or the full absolute path (if it's not in the project).
                _currentTitlePath = ProjectManager.makeProjectRelativeIfPossible(fullPath);

                // TODO: move to EditorManager listener
                _ignoreEditorChanges = true;
                _editor.setValue(event.target.result);
                _ignoreEditorChanges = false;

                DocumentManager.showInEditor(fileEntry);
                updateTitle();

                // Make sure we can't undo back to the previous content.
                _editor.clearHistory();

                // This should be 0, but just to be safe...
                _savedUndoPosition = _editor.historySize().undo;
                updateDirty();

                result.resolve();
            };

            reader.onerror = function(event) {
                showFileOpenError(event.target.error.code, fullPath);
                result.reject();
            }

            reader.readAsText(file, "utf8");
        },
        function fileEntry_onerror(event) {
            showFileOpenError(event.target.error.code, fullPath);
            result.reject();
        });

        return result;
    }

    function handleFileNewInProject() {
        // Determine the directory to put the new file
        // If a file is currently selected, put it next to it.
        // If a directory is currently selected, put it in it.
        // If nothing is selected, put it at the root of the project
        var baseDir,
            selected = ProjectManager.getSelectedItem() || ProjectManager.getProjectRoot();

        baseDir = selected.fullPath;
        if (selected.isFile)
            baseDir = baseDir.substr(0, baseDir.lastIndexOf("/"));

        // Create the new node. The createNewItem function does all the heavy work
        // of validating file name, creating the new file and selecting.
        // TODO: Use a unique name like Untitled-1, Untitled-2, etc.
        return ProjectManager.createNewItem(baseDir, "Untitled.js", false);
    }

    function handleFileSave() {
        var result = new $.Deferred();
        if (_currentFilePath && _isDirty) {
            // TODO: we should implement something like NativeFileSystem.resolveNativeFileSystemURL() (similar
            // to what's in the standard file API) to get a FileEntry, rather than manually constructing it
            var fileEntry = new NativeFileSystem.FileEntry(_currentFilePath);

            fileEntry.createWriter(
                function(writer) {
                    writer.onwriteend = function() {
                        _savedUndoPosition = _editor.historySize().undo;
                        updateDirty();
                        result.resolve();
                    }
                    writer.onerror = function(event) {
                        showSaveFileError(event.target.error.code, _currentFilePath);
                        result.reject();
                    }

                    // TODO (jasonsj): Blob instead of string
                    writer.write(_editor.getValue());
                },
                function(event) {
                    showSaveFileError(event.target.error.code, _currentFilePath);
                    result.reject();
                }
            );
        }
        else {
            result.resolve();
        }
        result.always(function() {
            _editor.focus();
        });
        return result;
    }

    function handleFileClose() {
        var result = new $.Deferred();
        if (_currentFilePath && _isDirty) {
            brackets.showModalDialog(
                  brackets.DIALOG_ID_SAVE_CLOSE
                , Strings.SAVE_CLOSE_TITLE
                , Strings.format(Strings.SAVE_CLOSE_MESSAGE, _currentTitlePath)
            ).done(function(id) {
                if (id === brackets.DIALOG_BTN_CANCEL) {
                    result.reject();
                }
                else {
                    if (id === brackets.DIALOG_BTN_OK) {
                        CommandManager
                            .execute(Commands.FILE_SAVE)
                            .done(function() {
                                doClose();
                                result.resolve();
                            })
                            .fail(function() {
                                result.reject();
                            });
                    }
                    else {
                        // This is the "Don't Save" case--we can just go ahead and close the file.
                        doClose();
                        result.resolve();
                    }
                }
            });
            result.always(function() {
                _editor.focus();
            });
        }
        else {
            doClose();
            _editor.focus();
            result.resolve();
        }
        return result;
    }

    function doClose() {
        // TODO: When we implement multiple files being open, this will probably change to just
        // dispose of the editor for the current file (and will later change again if we choose to
        // limit the number of open editors).
        _ignoreEditorChanges = true;
        _editor.setValue("");
        _ignoreEditorChanges = false;

        _editor.clearHistory();
        _currentFilePath = _currentTitlePath = null;
        _savedUndoPosition = 0;
        _isDirty = false;
        updateTitle();
        _editor.focus();

        DocumentManager.closeCurrentDocument();
    }

    function showFileOpenError(code, path) {
        brackets.showModalDialog(
              brackets.DIALOG_ID_ERROR
            , Strings.ERROR_OPENING_FILE_TITLE
            , Strings.format(
                    Strings.ERROR_OPENING_FILE
                  , path
                  , getErrorString(code))
        );
    }

    function showSaveFileError(code, path) {
        brackets.showModalDialog(
              brackets.DIALOG_ID_ERROR
            , Strings.ERROR_SAVING_FILE_TITLE
            , Strings.format(
                    Strings.ERROR_SAVING_FILE
                  , path
                  , getErrorString(code))
        );
    }

    function getErrorString(code) {
        // There are a few error codes that we have specific error messages for. The rest are
        // displayed with a generic "(error N)" message.
        var result;

        if (code == FileError.NOT_FOUND_ERR)
            result = Strings.NOT_FOUND_ERR;
        else if (code == FileError.NOT_READABLE_ERR)
            result = Strings.NOT_READABLE_ERR;
        else if (code == FileError.NO_MODIFICATION_ALLOWED_ERR)
            result = Strings.NO_MODIFICATION_ALLOWED_ERR;
        else
            result = Strings.format(Strings.GENERIC_ERROR, code);

        return result;
    }

    // Define public API
    exports.init = init;
});

<|endoftext|>


<commit_before>var append = require('append');
var fs = require('fs');
var path = require('path');
var sha1 = require('sha1');
var md5 = require('MD5');
var querystring = require('querystring');
var async = require('async');
var MongoDB = require('mongodb').Db;
var MongoServer = require('mongodb').Server;
var Pingback = require('pingback');

// constructor
var Comments = module.exports = function Comments(opt) {

  // Default options
  var defaultOpt = {
    host: 'localhost',
    port: 27017,
    name: 'website',
    comments: 'comments',
    pingbacks: 'pingbacks',
    publicDirectory: process.cwd(),
    urlPrefix: 'http://example.com/'
  };

  this.opt = append(defaultOpt, opt);
};

// method: connect
Comments.prototype.connect = function connect(connected) {
  var self = this,
      opt = this.opt;

  // Server connection
  self.server = new MongoServer(opt.host, opt.port, { auto_reconnect: true });
  // DB connection
  var dbConnector = new MongoDB(opt.name, self.server);

  dbConnector.open(function(err, db) {
    if (err)
      return connected(err);

    // DB connection
    self.db = db;

    // open collections and ensure indexes
    async.parallel({
      comments: function (cb) {
        db.collection(opt.comments, function (err, col) {
          if (err)
            return cb(err);

          self.comments = col;

          async.parallel([
            function (ensured) {
              col.ensureIndex('res', ensured);
            },
            function (ensured) {
              col.ensureIndex('modified', ensured);
            }
          ], function (err) {
            if (err)
              return cb(err);

            cb(null, col);
          });
        });
      },
      pingbacks: function (cb) {
        db.collection(opt.pingbacks, function (err, col) {
          if (err)
            return cb(err);

          self.pingbacks = col;

          cb(null, col);
        });
      }
    }, connected);
  });
};

// method: getCollection
Comments.prototype.getCollections = function getCollection(done) {
  // If connection hasn't already been established
  if (typeof this.comments == 'undefined'
      || typeof this.pingbacks == 'undefined')
    // try to connect
    this.connect(done);

  // otherwise simply use existing collection
  else
    done(null, this.comments, this.pingbacks);
};

// method: saveComment
Comments.prototype.saveComment = function saveComment(res, comment, saved) {
  // resource
  comment.res = res;

  // email address and hash
  if (comment.email) {
    var email = comment.email;
    comment.email = {
      address: email,
      hash: md5(email)
    };
  }

  // modified
  comment.modified = new Date();

  // hash the comment, necessary for future comment editing
  comment.hash = sha1(JSON.stringify(comment));

  // get collection and save comment
  this.getCollections(function(err, col) {
    if (err)
      return saved(err);

    col.comments.save(comment, { safe: true }, saved);
  });
};

// method: getComments
Comments.prototype.getComments = function getComments(res, props, opt,
    received) {
  var defaultOpt = {
    sort: 'modified'
  };

  var defaultProps = {
    _id: true,
    author: true,
    'email.hash': true,
    website: true,
    modified: true,
    message: true,
    regular: true
  };

  // set properties and options
  if (arguments.length == 2) {
    received = props;
    props = defaultProps;
    opt = defaultOpt;
  } else if (arguments.length == 3) {
    received = opt;
    opt = defaultOpt;
    props = append(defaultProps, props);
  } else {
    opt = append(defaultOpt, opt);
    props = append(defaultProps, props);
  }

  var query = {};
  if (res !== null)
    query.res = res;

  // get collection and find comments
  this.getCollections(function(err, col) {
    if (err)
      return received(err);

    col.comments.find(query, props, opt, received);
  });
};

// method: count
Comments.prototype.count = function count(res, counted) {
  try {
    this.getComments(res, function(err, results) {
      results.count(counted);
    });
  } catch(err) {
    counted(err);
  }
};

// method: close
Comments.prototype.close = function close(done) {
  if (this.db)
    return this.db.close(done);

  done();
};

// method: getCommentsJSON
Comments.prototype.getCommentsJSON = function getCommentsJSON(res, resp,
    received) {
  // if resource is not defined
  if (typeof res == 'undefined') {
    resp.writeHead(404);
    resp.end();
    return received(new Error('No resource given.'));
  }

  // request comments for this resource from the db
  this.getComments(res, function receiveComments(err, results) {
    if (err) {
      throw err;
      resp.writeHead(404);
      resp.end();
      return received(err);
    }

    // count the comments
    results.count(function count(err, count) {
      var i = 0;

      if (err) {
        throw err;
        resp.writeHead(404);
        resp.end();
        return received(err);
      }

      resp.writeHead(200, { 'Content-Type': 'application/json' });

      // start JSON array output
      resp.write('[');

      // for each comment in the result set
      results.each(function (err, comment) {
        if (err)
          return;

        if (!comment) {
          // end the output when there are no more comments
          resp.end(']');
          return received();
        }

        resp.write(JSON.stringify(comment));
        // seperate comments by a comma
        if (++i < count)
          resp.write(',');
      });
    });
  });
};

// method: parseCommentPOST
Comments.prototype.parseCommentPOST = function parseCommentPOST(res, req,
    parsed) {
  var data = '';

  // add chunks to data
  req.on('data', function(chunk) {
    data += chunk;
  });

  // when data is complete
  req.on('end', function() {
    parsed(null, querystring.parse(data));
  });

  // when connection is closed, before data is complete
  req.on('close', function(err) {
    parsed(err);
  });
};

// method: setCommentJSON
Comments.prototype.setCommentJSON = function setCommentJSON(res, comment,
    resp, saved) {
  if (typeof res == 'undefined') {
    resp.writeHead(404);
    resp.end();
    return saved(new Error('Invalid argument. `res` must not be undefined.'));
  }

  if (comment === false) {
    resp.writeHead(412); // precondition failed
    resp.end();
    return saved(new Error('Precondition failed.'));
  }

  comment.regular = true;

  // save comment
  this.saveComment(res, comment, function(err, comment) {
    if (err) {
      resp.writeHead(500);
      resp.end();
      return saved(err);
    }

    // everything ok
    resp.writeHead(200);
    resp.end();
    saved();
  });
};

// method: sendPingbacks
Comments.prototype.sendPingbacks = function sendPingbacks(res, pinged) {
  var self = this;

  this.getCollections(function (err, col) {
    if (err)
      return pinged(err);

    // check if document already has sent pingbacks
    col.pingbacks.find({ _id: res, sent: true }).count(function (err, num) {
      if (err)
        return pinged(err);

      // if not, send pingbacks
      if (num == 0)
        fs.readFile(path.resolve(self.opt.publicDirectory, res), 'utf8',
            function (err, html) {
          if (err)
            return pinged(err);

          Pingback.scan(html, self.opt.urlPrefix+res, function (err, pb) {
            if (err)
              return;

            // set sent to true for this document and push pb.href to targets
            col.pingbacks.update({ _id: res }, {
              $set: { sent: true },
              $push: { targets: pb.href }
            }, { safe: true, upsert: true }, function (err) {
              if (err)
                return pinged(err);
              pinged(pb);
            });
          });
        });
    });
  });
};

// method: handlePingback
Comments.prototype.handlePingback
    = function handlePingback(req, resp, callback) {
  var self = this;

  Pingback.middleware(function (source, target) {
    var ping = this;

    // if target.pathname starts with slash, remove it
    if (target.pathname[0] == '/')
      target.pathname = target.pathname.substr(1);

    fs.stat(path.resolve(self.opt.publicDirectory, target.pathname),
        function (err, stats) {
      if (err || !stats.isFile())
        return;

      // save the pingback as a comment
      self.saveComment(target.pathname, {
        message: ping.excerpt,
        website: source.href
      }, function (err) {
        if (err)
          console.log('Failed to add pingback from '+source.href);
        else
          console.log('Added pingback from '+source.href);
      });
    });
  })(req, resp, callback);
};
<commit_msg>Fix pingbacks<commit_after>var append = require('append');
var fs = require('fs');
var path = require('path');
var sha1 = require('sha1');
var md5 = require('MD5');
var querystring = require('querystring');
var async = require('async');
var MongoDB = require('mongodb').Db;
var MongoServer = require('mongodb').Server;
var Pingback = require('pingback');

// constructor
var Comments = module.exports = function Comments(opt) {

  // Default options
  var defaultOpt = {
    host: 'localhost',
    port: 27017,
    name: 'website',
    comments: 'comments',
    pingbacks: 'pingbacks',
    publicDirectory: process.cwd(),
    urlPrefix: 'http://example.com/'
  };

  this.opt = append(defaultOpt, opt);
};

// method: connect
Comments.prototype.connect = function connect(connected) {
  var self = this,
      opt = this.opt;

  // Server connection
  self.server = new MongoServer(opt.host, opt.port);
  // DB connection
  var dbConnector = new MongoDB(opt.name, self.server);

  dbConnector.open(function(err, db) {
    if (err)
      return connected(err);

    // DB connection
    self.db = db;

    // open collections and ensure indexes
    async.parallel({
      comments: function (cb) {
        db.collection(opt.comments, function (err, col) {
          if (err)
            return cb(err);

          self.comments = col;

          async.parallel([
            function (ensured) {
              col.ensureIndex('res', ensured);
            },
            function (ensured) {
              col.ensureIndex('modified', ensured);
            }
          ], function (err) {
            if (err)
              return cb(err);

            cb(null, col);
          });
        });
      },
      pingbacks: function (cb) {
        db.collection(opt.pingbacks, function (err, col) {
          if (err)
            return cb(err);

          self.pingbacks = col;

          cb(null, col);
        });
      }
    }, connected);
  });
};

// method: getCollections
Comments.prototype.getCollections = function getCollections(done) {
  // If connection hasn't already been established
  if (typeof this.comments == 'undefined'
      || typeof this.pingbacks == 'undefined')
    // try to connect
    this.connect(done);

  // otherwise simply use existing collection
  else
    done(null, { comments: this.comments, pingbacks: this.pingbacks });
};

// method: saveComment
Comments.prototype.saveComment = function saveComment(res, comment, saved) {
  // resource
  comment.res = res;

  // email address and hash
  if (comment.email) {
    var email = comment.email;
    comment.email = {
      address: email,
      hash: md5(email)
    };
  }

  // modified
  comment.modified = new Date();

  // hash the comment, necessary for future comment editing
  comment.hash = sha1(JSON.stringify(comment));

  // get collection and save comment
  this.getCollections(function(err, col) {
    if (err)
      return saved(err);

    col.comments.save(comment, { safe: true }, saved);
  });
};

// method: getComments
Comments.prototype.getComments = function getComments(res, props, opt,
    received) {
  var defaultOpt = {
    sort: 'modified'
  };

  var defaultProps = {
    _id: true,
    author: true,
    'email.hash': true,
    website: true,
    modified: true,
    message: true,
    regular: true
  };

  // set properties and options
  if (arguments.length == 2) {
    received = props;
    props = defaultProps;
    opt = defaultOpt;
  } else if (arguments.length == 3) {
    received = opt;
    opt = defaultOpt;
    props = append(defaultProps, props);
  } else {
    opt = append(defaultOpt, opt);
    props = append(defaultProps, props);
  }

  var query = {};
  if (res !== null)
    query.res = res;

  // get collection and find comments
  this.getCollections(function(err, col) {
    if (err)
      return received(err);

    col.comments.find(query, props, opt, received);
  });
};

// method: count
Comments.prototype.count = function count(res, counted) {
  try {
    this.getComments(res, function(err, results) {
      results.count(counted);
    });
  } catch(err) {
    counted(err);
  }
};

// method: close
Comments.prototype.close = function close(done) {
  if (this.db)
    return this.db.close(done);

  done();
};

// method: getCommentsJSON
Comments.prototype.getCommentsJSON = function getCommentsJSON(res, resp,
    received) {
  // if resource is not defined
  if (typeof res == 'undefined') {
    resp.writeHead(404);
    resp.end();
    return received(new Error('No resource given.'));
  }

  // request comments for this resource from the db
  this.getComments(res, function receiveComments(err, results) {
    if (err) {
      throw err;
      resp.writeHead(404);
      resp.end();
      return received(err);
    }

    // count the comments
    results.count(function count(err, count) {
      var i = 0;

      if (err) {
        throw err;
        resp.writeHead(404);
        resp.end();
        return received(err);
      }

      resp.writeHead(200, { 'Content-Type': 'application/json' });

      // start JSON array output
      resp.write('[');

      // for each comment in the result set
      results.each(function (err, comment) {
        if (err)
          return;

        if (!comment) {
          // end the output when there are no more comments
          resp.end(']');
          return received();
        }

        resp.write(JSON.stringify(comment));
        // seperate comments by a comma
        if (++i < count)
          resp.write(',');
      });
    });
  });
};

// method: parseCommentPOST
Comments.prototype.parseCommentPOST = function parseCommentPOST(res, req,
    parsed) {
  var data = '';

  // add chunks to data
  req.on('data', function(chunk) {
    data += chunk;
  });

  // when data is complete
  req.on('end', function() {
    parsed(null, querystring.parse(data));
  });

  // when connection is closed, before data is complete
  req.on('close', function(err) {
    parsed(err);
  });
};

// method: setCommentJSON
Comments.prototype.setCommentJSON = function setCommentJSON(res, comment,
    resp, saved) {
  if (typeof res == 'undefined') {
    resp.writeHead(404);
    resp.end();
    return saved(new Error('Invalid argument. `res` must not be undefined.'));
  }

  if (comment === false) {
    resp.writeHead(412); // precondition failed
    resp.end();
    return saved(new Error('Precondition failed.'));
  }

  comment.regular = true;

  // save comment
  this.saveComment(res, comment, function(err, comment) {
    if (err) {
      resp.writeHead(500);
      resp.end();
      return saved(err);
    }

    // everything ok
    resp.writeHead(200);
    resp.end();
    saved();
  });
};

// method: sendPingbacks
Comments.prototype.sendPingbacks = function sendPingbacks(res, pinged) {
  var self = this;

  this.getCollections(function (err, col) {
    if (err)
      return pinged(err);

    // check if document already has sent pingbacks
    col.pingbacks.find({ _id: res, sent: true }).count(function (err, num) {
      if (err)
        return pinged(err);

      // if not, send pingbacks
      if (num == 0)
        fs.readFile(path.resolve(self.opt.publicDirectory, res), 'utf8',
            function (err, html) {
          if (err)
            return pinged(err);

          Pingback.scan(html, self.opt.urlPrefix+res, function (err, pb) {
            if (err)
              return;

            // set sent to true for this document and push .href to targets
            col.pingbacks.update({ _id: res }, {
              $set: { sent: true },
              $push: { targets: pb.href }
            }, { safe: true, upsert: true }, function (err) {
              if (err)
                return pinged(err);
              pinged(pb);
            });
          });
        });
    });
  });
};

// method: handlePingback
Comments.prototype.handlePingback
    = function handlePingback(req, resp, next) {
  var self = this;

  var ping = new Pingback(req, resp);
  ping.on('ping', function (source, target, next) {
    // if target.pathname starts with slash, remove it
    if (target.pathname[0] == '/')
      target.pathname = target.pathname.substr(1);

    // check if it’s a file
    fs.stat(path.resolve(self.opt.publicDirectory, target.pathname),
        function (err, stats) {
      if (err)
        return next(Pingback.TARGET_DOES_NOT_EXIST);
      if (!stats.isFile())
        return next(Pingback.TARGET_CANNOT_BE_USED);

      self.getCollections(function (err, col) {
        if (err)
          return next(Pingback.TARGET_CANNOT_BE_USED);

        // check if the pingback already has been registered
        col.comments.find({
          res: target.pathname,
          pingback: true,
          website: source.href
        }).count(function (err, count) {
          if (err)
            return next(Pingback.TARGET_CANNOT_BE_USED);
          if (count)
            return next(Pingback.ALREADY_REGISTERED);

          next();
        });
      });
    });
  });
  ping.on('fault', function (code, msg) {
    next(new Error(
      'Received bad pingback from '
      + this.source.href + '.'
      + ' Fault Code: ' + code
      + ' - Message: ' + msg
    ));
  });
  ping.on('error', function () {
    resp.writeHead(404);
    resp.end();
  });
  ping.on('success', function (source, target) {
    // save the pingback as a comment
    self.saveComment(target.pathname, {
      message: '[…] '+ping.excerpt+' […]',
      author: source.title,
      website: source.href,
      pingback: true
    }, function (err) {
      if (err)
        return next(new Error('Failed to add pingback from '
            +source.href+'.'));
    });
  });
  req.pipe(ping);
};
<|endoftext|>


<commit_before>var account_transferws = (function(){
    "use strict";
    var $form ;
    var account_from , account_to ,account_bal;
    var currType, MLTBal,MFBal,MLCurrType,MFCurrType;
    var availableCurr= [] ;
    var availableAccounts =[];

    var init = function(){
        $form = $('#account_transfer');
        $("#success_form").hide();
        $("#client_message").hide();
        account_bal = 0;

        BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "initValues"}});
        BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "payout_currencies"}});

        $form.find("button").on("click", function(e){
            e.preventDefault();
            e.stopPropagation();

            if(validateForm() === false){
                return false;
            }

            BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "transfer_between_accounts"}});
        });

        $form.find("#transfer_account_transfer").on("change",function(){
            var accounts = $("#transfer_account_transfer option:selected").text();
            var matches = accounts
                            .split('(')
                            .filter(function(v){
                                return v.indexOf(')') > -1;})
                            .map( function(value) {
                                return value.split(')')[0];
                        });

            account_from = matches[0];
            account_to = matches[1];

            if(account_from.substring(0,2) == "MF"){
                account_bal = MFBal;
                currType = MFCurrType;
            }else if(account_from.substring(0,2) == "ML"){
                account_bal = MLTBal;
                currType = MLCurrType;
            }

            $form.find("#currencyType").html(currType);

            BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "payout_currencies"}});

        });
    };
    var validateForm =function(){

        var amt = $form.find("#acc_transfer_amount").val();
        var isValid = true;

        if(amt.length <=0 ){
            $form.find("#invalid_amount").text(text.localize("Invalid amount. Minimum transfer amount is 0.10, and up to 2 decimal places."));
            isValid = false;
        }
        if($.inArray(currType, availableCurr) == -1)
        {
            $form.find("#invalid_amount").text(text.localize("Invalid currency."));
            isValid = false;
        }

        if(($.inArray(account_from, availableAccounts) == -1) || ($.inArray(account_to, availableAccounts) == -1))
        {
            $form.find("#invalid_amount").text(text.localize("Invalid Account."));
            isValid = false;
        }

        return isValid;
    };

    var apiResponse = function(response){
        var type = response.msg_type;
        if (type === "transfer_between_accounts" || (type === "error" && "transfer_between_accounts" in response.echo_req)){
           responseMessage(response);

        }
        else if(type === "payout_currencies" || (type === "error" && "payout_currencies" in response.echo_req))
        {
            responseMessage(response);
        }
        else if(type === "authorize" || (type === "error" && "authorize" in response.echo_req))
        {
            isAuthorized(response);
        }
    };

    var isAuthorized =  function(response){
        if(response.echo_req.passthrough){
            var option= response.echo_req.passthrough.value ;
            var amt = $form.find("#acc_transfer_amount").val();

            switch(option){
                case   "initValues":
                        BinarySocket.send({
                            "transfer_between_accounts": "1",
                            "passthrough" : {"value" : "set_client"}
                        });
                        break;
                case   "transfer_between_accounts" :
                        BinarySocket.send({
                            "transfer_between_accounts": "1",
                            "account_from": account_from,
                            "account_to": account_to,
                            "currency": currType,
                            "amount": amt
                        });
                        break;
                case   "payout_currencies" :
                        BinarySocket.send({
                            "payout_currencies": "1"
                        });
                        break;
            }

        }
    };

    var responseMessage = function(response) {
        var resvalue ;
        var str;
        if("error" in response) {
                if("message" in response.error) {
                    $("#client_message").show();
                    $("#client_message p").html(text.localize(response.error.message));
                    $("#success_form").hide();
                    $form.hide();
                    return false;
                }
                return false;
        }
        else if("payout_currencies" in response){

            availableCurr = response.payout_currencies;
        }
        else if ("transfer_between_accounts" in response){

            if(response.echo_req.passthrough.value == "get_new_balance"){

                $.each(response.accounts,function(key,value){
                    $form.hide();
                    $("#success_form").show();
                    $("#client_message").hide();

                    if(value.loginid == account_from){
                        $("#loginid_1").html(value.loginid);
                        $("#balance_1").html(value.balance);
                    }
                    else if(value.loginid == account_to){
                        $("#loginid_2").html(value.loginid);
                        $("#balance_2").html(value.balance);

                    }
                });
            }
            else if(response.echo_req.passthrough.value =="set_client"){
                var optionMF, optionML ;
                var firstbal,secondbal,firstacct,secondacct,firstCurrType,SecondCurrType;
                $.each(response.accounts, function(index,value){
                    if(index === 0){
                        firstbal = value["balance"];
                        firstCurrType = value["currency"];
                        firstacct  = value["loginid"];
                    }
                    else{
                        secondbal = value["balance"];
                        SecondCurrType = value["currency"];
                        secondacct = value["loginid"];
                    }

                    if(value["loginid"].substring(0,2) == "MF"){
                        MFBal = value["balance"];
                        MFCurrType  = value["currency"];
                        availableAccounts.push(value["loginid"]);
                    }
                    else if(value["loginid"].substring(0,2) == "ML")
                    {
                        MLTBal = value["balance"];
                        MLCurrType = value["currency"];
                        availableAccounts.push(value["loginid"]);
                    }

                    if($.isEmptyObject(firstbal) || (firstbal === 0))
                    {
                        account_from = secondacct;
                        firstbal = secondbal;
                        currType = SecondCurrType;

                        account_to = firstacct;
                        secondbal = firstbal;
                    }
                    else{
                        account_from = firstacct;
                        firstbal = firstbal;

                        secondbal = secondbal;

                        account_to = secondacct;
                        currType = firstCurrType;
                    }

                });

                account_bal = firstbal;

                if((firstbal <=0) && (account_to !== undefined) ){
                    $("#client_message").show();
                    $("#success_form").hide();
                    $form.hide();
                    return false;
                }
                else if(account_to === undefined || account_from === undefined || $.isEmptyObject(account_to))
                {
                    $("#client_message").show();
                    $("#client_message p").html(text.localize("The account transfer is unavailable for your account."));
                    $("#success_form").hide();
                    $form.hide();
                    return false;
                }
                else if(account_to == secondacct && account_from == firstacct){
                    $form.find("#currencyType").html(currType);

                    if(account_from.substring(0,2) == "MF"){

                        optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                        str = text.localize("from financial account (" + account_from + ") to gaming account (" + account_to + ")");
                        optionMF.text(str);
                        optionMF.attr('selected', 'selected');
                        if(secondbal > 0){
                            str  = text.localize("from gaming account (" + account_to + ") to financial account (" + account_from + ")");
                            optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                            optionML.text(str);

                        }
                        else{
                            optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                            optionML.remove();
                        }
                    }
                    else if(account_from.substring(0,2) == "ML")
                    {
                        str  = text.localize("from gaming account (" + account_from + ") to financial account (" + account_to + ")");
                        optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                        optionML.text(str);
                        optionML.attr('selected', 'selected');

                        if(secondbal > 0){
                            optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                            str = text.localize("from financial account (" + account_to + ") to gaming account (" + account_from + ")");
                            optionMF.text(str);
                        }
                        else{
                            optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                            optionMF.remove();

                        }
                    }

                }
                else if(account_to == firstacct && account_from == secondacct)
                {
                    $form.find("#currencyType").html(currType);
                    if(account_from.substring(0,2) =="MF"){
                        optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                        str = text.localize("from financial account (" + account_from + ") to gaming account (" + account_to + ")");
                        optionMF.text(str);
                        optionMF.attr('selected', 'selected');
                        optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                        optionML.remove();
                    }
                    else if(account_from.substring(0,2) == "ML")
                    {
                        str  = text.localize("from gaming account (" + account_from + ") to financial account (" + account_to+ ")");
                        optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                        optionML.text(str);
                        optionML.attr('selected', 'selected');

                        optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                        optionMF.remove();
                    }

                }

            }
            else{
                BinarySocket.send({
                    "transfer_between_accounts": "1",
                    "passthrough" : {"value" : "get_new_balance"}
                });

            }
        }

    };

    return {
        init : init,
        apiResponse : apiResponse
    };

})();

pjax_config_page("cashier/account_transferws", function() {
    return {
        onLoad: function() {
        	if (!getCookieItem('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }
            if((/VRT/.test($.cookie('loginid')))){
                window.location.href = ("/");
            }

        	BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);
                    if (response) {
                        account_transferws.apiResponse(response);
                    }
                }
            });

            account_transferws.init();
        }
    };
});<commit_msg>Removing available accounts checking<commit_after>var account_transferws = (function(){
    "use strict";
    var $form ;
    var account_from , account_to ,account_bal;
    var currType, MLTBal,MFBal,MLCurrType,MFCurrType;
    var availableCurr= [] ;
    var availableAccounts =[];

    var init = function(){
        $form = $('#account_transfer');
        $("#success_form").hide();
        $("#client_message").hide();
        account_bal = 0;

        BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "initValues"}});
        BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "payout_currencies"}});

        $form.find("button").on("click", function(e){
            e.preventDefault();
            e.stopPropagation();

            if(validateForm() === false){
                return false;
            }

            BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "transfer_between_accounts"}});
        });

        $form.find("#transfer_account_transfer").on("change",function(){
            var accounts = $("#transfer_account_transfer option:selected").text();
            var matches = accounts
                            .split('(')
                            .filter(function(v){
                                return v.indexOf(')') > -1;})
                            .map( function(value) {
                                return value.split(')')[0];
                        });

            account_from = matches[0];
            account_to = matches[1];

            if(account_from.substring(0,2) == "MF"){
                account_bal = MFBal;
                currType = MFCurrType;
            }else if(account_from.substring(0,2) == "ML"){
                account_bal = MLTBal;
                currType = MLCurrType;
            }

            $form.find("#currencyType").html(currType);

            BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "payout_currencies"}});

        });
    };
    var validateForm =function(){

        var amt = $form.find("#acc_transfer_amount").val();
        var isValid = true;

        if(amt.length <=0 ){
            $form.find("#invalid_amount").text(text.localize("Invalid amount. Minimum transfer amount is 0.10, and up to 2 decimal places."));
            isValid = false;
        }
        if($.inArray(currType, availableCurr) == -1)
        {
            $form.find("#invalid_amount").text(text.localize("Invalid currency."));
            isValid = false;
        }

        return isValid;
    };

    var apiResponse = function(response){
        var type = response.msg_type;
        if (type === "transfer_between_accounts" || (type === "error" && "transfer_between_accounts" in response.echo_req)){
           responseMessage(response);

        }
        else if(type === "payout_currencies" || (type === "error" && "payout_currencies" in response.echo_req))
        {
            responseMessage(response);
        }
        else if(type === "authorize" || (type === "error" && "authorize" in response.echo_req))
        {
            isAuthorized(response);
        }
    };

    var isAuthorized =  function(response){
        if(response.echo_req.passthrough){
            var option= response.echo_req.passthrough.value ;
            var amt = $form.find("#acc_transfer_amount").val();

            switch(option){
                case   "initValues":
                        BinarySocket.send({
                            "transfer_between_accounts": "1",
                            "passthrough" : {"value" : "set_client"}
                        });
                        break;
                case   "transfer_between_accounts" :
                        BinarySocket.send({
                            "transfer_between_accounts": "1",
                            "account_from": account_from,
                            "account_to": account_to,
                            "currency": currType,
                            "amount": amt
                        });
                        break;
                case   "payout_currencies" :
                        BinarySocket.send({
                            "payout_currencies": "1"
                        });
                        break;
            }

        }
    };

    var responseMessage = function(response) {
        var resvalue ;
        var str;
        if("error" in response) {
                if("message" in response.error) {
                    $("#client_message").show();
                    $("#client_message p").html(text.localize(response.error.message));
                    $("#success_form").hide();
                    $form.hide();
                    return false;
                }
                return false;
        }
        else if("payout_currencies" in response){

            availableCurr = response.payout_currencies;
        }
        else if ("transfer_between_accounts" in response){

            if(response.echo_req.passthrough.value == "get_new_balance"){

                $.each(response.accounts,function(key,value){
                    $form.hide();
                    $("#success_form").show();
                    $("#client_message").hide();

                    if(value.loginid == account_from){
                        $("#loginid_1").html(value.loginid);
                        $("#balance_1").html(value.balance);
                    }
                    else if(value.loginid == account_to){
                        $("#loginid_2").html(value.loginid);
                        $("#balance_2").html(value.balance);

                    }
                });
            }
            else if(response.echo_req.passthrough.value =="set_client"){
                var optionMF, optionML ;
                var firstbal,secondbal,firstacct,secondacct,firstCurrType,SecondCurrType;
                $.each(response.accounts, function(index,value){
                    if(index === 0){
                        firstbal = value["balance"];
                        firstCurrType = value["currency"];
                        firstacct  = value["loginid"];
                    }
                    else{
                        secondbal = value["balance"];
                        SecondCurrType = value["currency"];
                        secondacct = value["loginid"];
                    }

                    if(value["loginid"].substring(0,2) == "MF"){
                        MFBal = value["balance"];
                        MFCurrType  = value["currency"];
                        availableAccounts.push(value["loginid"]);
                    }
                    else if(value["loginid"].substring(0,2) == "ML")
                    {
                        MLTBal = value["balance"];
                        MLCurrType = value["currency"];
                        availableAccounts.push(value["loginid"]);
                    }

                    if($.isEmptyObject(firstbal) || (firstbal === 0))
                    {
                        account_from = secondacct;
                        firstbal = secondbal;
                        currType = SecondCurrType;

                        account_to = firstacct;
                        secondbal = firstbal;
                    }
                    else{
                        account_from = firstacct;
                        firstbal = firstbal;

                        secondbal = secondbal;

                        account_to = secondacct;
                        currType = firstCurrType;
                    }

                });

                account_bal = firstbal;

                if((firstbal <=0) && (account_to !== undefined) ){
                    $("#client_message").show();
                    $("#success_form").hide();
                    $form.hide();
                    return false;
                }
                else if(account_to === undefined || account_from === undefined || $.isEmptyObject(account_to))
                {
                    $("#client_message").show();
                    $("#client_message p").html(text.localize("The account transfer is unavailable for your account."));
                    $("#success_form").hide();
                    $form.hide();
                    return false;
                }
                else if(account_to == secondacct && account_from == firstacct){
                    $form.find("#currencyType").html(currType);

                    if(account_from.substring(0,2) == "MF"){

                        optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                        str = text.localize("from financial account (" + account_from + ") to gaming account (" + account_to + ")");
                        optionMF.text(str);
                        optionMF.attr('selected', 'selected');
                        if(secondbal > 0){
                            str  = text.localize("from gaming account (" + account_to + ") to financial account (" + account_from + ")");
                            optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                            optionML.text(str);

                        }
                        else{
                            optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                            optionML.remove();
                        }
                    }
                    else if(account_from.substring(0,2) == "ML")
                    {
                        str  = text.localize("from gaming account (" + account_from + ") to financial account (" + account_to + ")");
                        optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                        optionML.text(str);
                        optionML.attr('selected', 'selected');

                        if(secondbal > 0){
                            optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                            str = text.localize("from financial account (" + account_to + ") to gaming account (" + account_from + ")");
                            optionMF.text(str);
                        }
                        else{
                            optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                            optionMF.remove();

                        }
                    }

                }
                else if(account_to == firstacct && account_from == secondacct)
                {
                    $form.find("#currencyType").html(currType);
                    if(account_from.substring(0,2) =="MF"){
                        optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                        str = text.localize("from financial account (" + account_from + ") to gaming account (" + account_to + ")");
                        optionMF.text(str);
                        optionMF.attr('selected', 'selected');
                        optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                        optionML.remove();
                    }
                    else if(account_from.substring(0,2) == "ML")
                    {
                        str  = text.localize("from gaming account (" + account_from + ") to financial account (" + account_to+ ")");
                        optionML  = $form.find("#transfer_account_transfer option[value='gtf']");
                        optionML.text(str);
                        optionML.attr('selected', 'selected');

                        optionMF = $form.find("#transfer_account_transfer option[value='ftg']");
                        optionMF.remove();
                    }

                }

            }
            else{
                BinarySocket.send({
                    "transfer_between_accounts": "1",
                    "passthrough" : {"value" : "get_new_balance"}
                });

            }
        }

    };

    return {
        init : init,
        apiResponse : apiResponse
    };

})();

pjax_config_page("cashier/account_transferws", function() {
    return {
        onLoad: function() {
        	if (!getCookieItem('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }
            if((/VRT/.test($.cookie('loginid')))){
                window.location.href = ("/");
            }

        	BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);
                    if (response) {
                        account_transferws.apiResponse(response);
                    }
                }
            });

            account_transferws.init();
        }
    };
});<|endoftext|>