/**
 * @package settings
 * @namespace settings
 */
Phx.namespace('Phx.Application.Modules.vcard', new function () {

    var _dialog = null;

    /**
     * helper for AJAX-calls
     */
    var _call = function(key, params, callback, module)
    {
        if (!key) {
            return;
        }

        if (! module) {
            module = 'Vcard';
        }

        Phx.Application.RequestRegistry.append({
            1:  module + '_' + key,
            2:  ((typeof callback !== 'function') ? function() {} : callback),
            3:  '',
            4:  params
        });
    };

    /**
     * remoces the edit vcard form on cancel and rebind click handler
     **/
    var _onCancelVcardForm = function()
    {
        if (_dialog == null || _dialog.length === 0) {
            return;
        }
        
        _dialog.close();
        _dialog = null;
    };

    /**
     * gets an empty vcard form
     */
    var _getVcardForm = function()
    {
        var _inputElement = $('#consumerName');

        if (_inputElement.length === 0) {
            return;
        }

        var _param = '&consumerName=' + _inputElement.val();

        _call('getVcardForm', _param, _showVcardForm);
    };

    this.showEmptyVcardForm = function(_name, _module) {
        _call('getVcardForm', '&consumerName=' + _name, _showVcardForm, _module);
    };

    this.showVcardForm = function(_vcardId, _module) {
        _call('getVcardForm', '&vcardId=' + _vcardId, _showVcardForm, _module);
    };

    /**
     * gets an prefilled vcard form
     */
    var _editAvailableCard = function()
    {
        var _inputElement = $('input[name=currentVcardId]', $(this).parent());

        if (_inputElement.length === 0) {
            return;
        }

        var _vcardId = _inputElement.val();

        var _param = '&vcardId=' + _vcardId;

        _call('getVcardForm', _param, _showVcardForm);
    };

    /**
     * displays the vcard form
     *
     * @param {Object} response = html-template
     */
    var _showVcardForm = function(response)
    {
        _dialog = Phx.UI.Dialog.HTML(i18n.getPText('vcard_dialog_headline'), {
            message : response.module.data.html
        });

        _dialog.show();

        if (!$.browser.msie) {
            $('#PhxCover').css({height: '100%', position: 'fixed'});
        }

        Phx.Application.Modules.EditVcard.initBindings();
        Phx.Application.Modules.Accordion.init();
    };

    var _bindEditLinks = function()
    {
        var _link = $('.vcard-list-edit');

        if (_link.length === 0) {
            return;
        }

        _link.unbind('click.vcard').bind('click.vcard', _editAvailableCard);
    }

    var _formSubmit = function(event, response) {

        var _ids = response.module.data.ids;

        _dialog.close();

        var _liste = $('#vcard-choose-list');

        // if no choose list is found, try to replace the new vcard name for
        // the myservice pagelet
        if (_liste.length === 0) {
            var _textElements = $('.vcard-name' + _ids);
            if (_textElements.length === 0) {
                return;
            }

            _textElements.html(response.module.data.newname);

            return;
        }

        // check if element for this vcard id already exist and replace it
        var _existingElement = $('#vcard' + _ids);

        if (_existingElement.length !== 0) {
            _existingElement.parent().replace(response.module.data.newcardhtml);
        } else {
            // else prepend new element to list and check ist
            _liste.prepend(response.module.data.newcardhtml);
        }

        // rebind edit links
        _bindEditLinks();

        // check new or edited element
        var _input = $('#vcard' + _ids);

        if (_input.length === 0) {
            return;
        }

        _input.attr('checked', 'checked');

    };

    var _bindInvitationLinks = function()
    {
        var _links = $('.inviteFriends');

        if (_links.length === 0) {
            return;
        }

        _links.unbind('click.vcard').bind('click.vcard', function() {
            var _name = $(this).prev().attr('name');
            _call('getFriendsInviteList', '&consumerId='+$(this).prev().val()+'&consumerName='+$(this).prev().attr('name'), function(response){
                _showInviteFriendsDialog(response, _name);

            })
        });
    };
    
    this.showInviteFriendsDialog = function(response, name, module) {
        _showInviteFriendsDialog(response, name, module);
    }

    var _showInviteFriendsDialog = function(response, name, module)
    {
        var _htmlDialog = Phx.UI.Dialog.HTML(i18n.getPText('vcard_invite_dialog_title', name), {
            message : response.module.data.html
        });

        _htmlDialog.show();

        Phx.Application.ListManager.init({
            leftList : '#friendsInRemaninglist',
            rightList : '#friendsInFriendlist',
            moveLeftButton : '#removeFriendFromFriendlist',
            moveRightButton : '#addFriendToFriendlist',
            deactivated : 'deactivated',
            highlighting : 'selected',
            selectAllCheckbox : '#selectAll',
            idPrefixLeftEntries : 'left_',
            idPrefixRightEntries : 'right_',
            search: {
                searchField: '#search-field',
                searchContent : '.name',
                matchHightlighting: 'match'
            }
        });

        var _save = $('#Mod-Vcard-ManageFriends-Save');

        if (_save.length > 0) {
            _save.unbind('click.vcard').bind('click.vcard', function() {
                var _result = Phx.Application.ListManager.getResult();
                _inviteFriends(_result.join('&friendIdList[]='), module);
                _htmlDialog.close();
            });
        }

        var _cancel = $('#Mod-Vcard-ManageFriends-Cancel');

        if (_cancel.length > 0) {
            _cancel.unbind('click.vcard').bind('click.vcard', function() {
                _htmlDialog.close();
            });
        }
    };

    var _inviteFriends = function(friendIdList, module)
    {
        if (friendIdList.length > 0) {
          _call('saveFriendsInviteList', '&consumerId='+$('#consumerId').val()+'&friendIdList[]=' + friendIdList + '&token=' + $('#invite-token').val() + '&message=' + $('#invite-message').val() + '&image=' + $('#invite-image').val(), function() {}, module);
        }
    };

    /**
     * init function
     */
    this.init = function ()
    {
        _bindEditLinks();

        _bindInvitationLinks();

        $(Phx.Application.Modules.EditVcard).bind('cancelEditVcardForm', _onCancelVcardForm);

        $(Phx.Application.Modules.EditVcard).bind('submitEditVcardFormSuccessful', _formSubmit);

        var _newLink = $('#vcard-new-link');

        var hash = window.location.hash;

        if (_newLink.length === 0) {
            return;
        }

        _newLink.unbind('click.vcard').bind('click.vcard', _getVcardForm);

        if (hash.length > 0) {
            var ahref = $(hash);
            if (ahref.length > 0) {
              //ahref.click();
              $(ahref).trigger('click');
            }
        }
        
    };
}());