/**
 * Send element as form.
 */

/*
 * @copyright       © Copyright 2006-2014, epages GmbH, All Rights Reserved.
 *
 * @module          ep.sendasform
 */

/*jslint ass: false, unparam: true, nomen:true*/
/*globals define*/

define("ep/fn/sendasform", [
    "jquery",
    "ep",
    "util/storage",

    'jquery/cookie'
], function ($, ep, storage) {
    'use strict';

    var sendForm = function (elem, options) {
        var form = $('<form method="post" action="' + (options.additional.url ? options.additional.url : '?') + '" />'),
            cookies = $.cookie(),
            formOptions = options.formOptions,
            _key;

        if (options.additional.target) {
            form.attr('target', options.additional.target);
        }

        for (_key in formOptions) {
            if (formOptions.hasOwnProperty(_key)) {
                form.append('<input type="hidden" name="' + _key + '" value="' + formOptions[_key] + '" />');
            }
        }

        // check if security token exists and add hidden input with security cookie information
        if (cookies[options.additional.tokenName]) {
            form.append('<input type="hidden" name="' + options.additional.tokenName + '" value="' + cookies[options.additional.tokenName] + '" />');
        }

        // append form to document
        $(options.additional.body).append(form);

        // submit form
        if (options.additional.send) {
            form.trigger('submit');
        }
    };

    /**
     * Add a form to an element given by selector, inject a security token into and send it
     * @param  {Object}  options      Optional options
     * @param  {Object}  formOptions  key/value pairs representing name/value attributes for hidden inputs
     * @param  {Object}  additional   Additional options to control script
     * @param  {Object}  fn           Function that is executed when onclick-Event fires (before form is sent)
     * @param  {string}  body         Selector to identify the element into the form will be appended (default: 'body')
     * @param  {boolean} send         Indicator if the form is sent automatically (default: true)
     */
    ep.fn.sendAsForm = function (options) {
        var elem = this,
            additional = {
                target: false,
                tokenName: 'SecToken',
                body: 'body',
                send: true
            };

        options.additional = options.additional || {};

        // copy/overwrite additional
        $.extend(additional, options.additional);
        $.extend(options.additional, additional);

        elem.on('click', function (e) {
            e.preventDefault();

            if (typeof additional.fn === 'function') {
                additional.fn();
            }

            // delete product comparision from session storage on logout
            if (options.formOptions.ChangeAction && options.formOptions.ChangeAction === "Logout") {
                storage.sessionStorage('Product::ProductComparison', null);
            }

            sendForm(elem, options);
        });

        return this;
    };

    return ep;

});