
/*  new/common/templates/widgets/widget_tagging/js/script.js  */
(function($) {
    /**
     * Routines to track events to Google Analytics
     * @param {String} sType Holds the type of the event (Category field on Google Analytics)
     * @param {String} sAction Action identifier
     * @param {String} sLabel Additional data or Action Label
     * @param {Function} fCallback Receive the callback function triggered after event track
     */
    $.fn.send_ga_event_tagging = function (sType, sAction, sLabel, fCallback) {
        if (_gaq && sAction) {
            _gaq.push(['_set', 'hitCallback', null]); //cleaning callback
            if (fCallback && typeof fCallback == 'function') {
                _gaq.push(['_set', 'hitCallback', fCallback]); //registering callback
            }
            _gaq.push(['_trackEvent', sType + ':' + ((tracking['cid'] != 1508) ? tracking['cid'] :  'DO ' + tracking['petition-id']), sAction, sLabel || 'no data']); //registering event
        } else {
            if (fCallback && typeof fCallback == 'function') {
                fCallback(); //running callback anyway
            }
        }
    }

    selectedFriendsCounter = 0;
    
    $.fn.selectFriendsCounter = function(category) {
        switch (window.selectedFriendsCounter) {
            case 2:
                $.fn.send_ga_event_tagging(category, 'Select Friends', 'Selected 1+');
                break;

            case 6:
                $.fn.send_ga_event_tagging(category, 'Select Friends', 'Selected 5+');
                break;

            case 11:
                $.fn.send_ga_event_tagging(category, 'Select Friends', 'Selected 10+');
                break;

            case 26:
                $.fn.send_ga_event_tagging(category, 'Select Friends', 'Selected 25+');
                break;

            case 51:
                $.fn.send_ga_event_tagging(category, 'Select Friends', 'Selected  50+');
                break;

            case 101:
                $.fn.send_ga_event_tagging(category, 'Select Friends', 'Selected 100+');
                break;
        }
    };

    /**
     * Tracks custom events to Optimizely
     * @param {String} sEventName Event name to track
     */
    $.fn.sendOptimizelyEvent = function(sEventName) {
        window['optimizely'] = window['optimizely'] || [];
        window.optimizely.push(['trackEvent', sEventName]);
    };

    $.fn.FBTagFriendsWidget = function(options) {
        var oOptions = {
            iTaggingLimit: parseInt($(this).data('tagging-limit'), 10) || 0,
            scope: 'user_friends'
        };

        if ($(this).data('pid')) {
            oOptions.iPid = parseInt($(this).data('pid'), 10) || 0;
        }
        
        var sAccessToken = null,
            aAuthResponse = null,
            sUserId = null,
            self = this,
            bIsLoggedIn = false,
            bInitialized = false,
            oRunPeriodsTimer,
            bFinishedSharing,
            bSignAndShareInvoked,
            iBoxIndex = 0,
            bProcessingPost = false,
            suggestedCounter = 0,
            all_taggable_friends_response = null;

        self.cid = 0;

        //private references to elements
        var sPopupId = $(this).attr('id');
        var jList = $('#' + sPopupId + 'List');
        var jButton = $('#' +sPopupId + 'Button');
        var jSearch = $('#' + sPopupId + 'SearchField');
        var jMessage = $('#' + sPopupId + 'Message');
        var jTitle = $('#' + sPopupId + 'Title');
        var jDescription = $('#' + sPopupId + 'Text');
        var jLink = $('#' + sPopupId + 'Link');

        $.extend(oOptions, options || {});

        var default_values;

        //register events
        jButton.click(function() {
            if (!bProcessingPost) {
                bProcessingPost = true;
                tagFriends();
            }
            return false;
        });

        jSearch.keyup(function() {
            var sSearchString = $(this).val().toUpperCase();
            if ($.trim(sSearchString) === '') {
                $('li.fbFriendLi').each(function() {
                    $(this).show();
                });
                $('#clear_search').hide();
            } else {
                $('li.fbFriendLi').each(function() {
                    var sTempName = $(this).data('fname').toUpperCase();
                    if (sTempName.indexOf(sSearchString) < 0) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
                $('#clear_search').show();
            }
        });

        $('#clear_search').on('click', function(){
            jSearch.val('');
            jSearch.trigger('keyup');
            jSearch.focus();
        });

        this.close = function() {
            if (oOptions.bForceFinishedCallback) {
                oOptions.finishedCallback();
            } else {
                $.colorbox.close();

                var condition = oOptions.finishedCallback && typeof oOptions.finishedCallback == 'function' &&
                    bSignAndShareInvoked;

                if (condition) {
                    oOptions.finishedCallback();
                }
            }

            $('body').trigger('sharing_complete');
        };

        //the main public method - does all necessary cheks and show the popup
        this.process = function(bCalledFromSignAndShare, custom_cid) {
            self.cid = custom_cid || cid;
            bFinishedSharing = false;
            bSignAndShareInvoked = bCalledFromSignAndShare;

            if (!bInitialized) {
                registerGlobalCallbacks();
            }
            $(document).trigger('tagging_tool:ready');
            if (bCalledFromSignAndShare && oOptions.bIntegrateSignAndShare) {
                bIsLoggedIn = true;
                sAccessToken = FB.getAccessToken();
                sUserId = FB.getUserID();
                aAuthResponse = FB.getAuthResponse();
                self.show();
            } else if (window.bTaggingToolFirstCall) {
                bIsLoggedIn = true;
                window.bTaggingToolFirstCall = false;
                friendCounterAndLoadFriends();
            } else {
                if (!bIsLoggedIn) {
                    runFBLogin();
                } else {
                    self.show();
                }
            }
        };

        function runFBLogin () {
            var oLoginOptions = getLoginOptions();
            var sUrl = '/act/facebook_login.php?' + $.param(oLoginOptions);
            window.open(sUrl,'fbLoginWindow','height=600,width=900');
        }

        function getLoginOptions() {
            var oLoginOptions = {
                'action': 'login',
                'failedOption': 'shareDialog',
                'link': getShareLink(),
                'picture': getSharePicture(),
                'name': getShareName(),
                'description': getShareDescription(),
                'cid': self.cid,
                'auth_type': 'rerequest',
                'scope': getScope()
            };
            return oLoginOptions;
        }

        function getShareDescription() {
            var sDescription = jDescription.html();
            if (isFacebookShareDataDefined()) {
                sDescription = share_data[self.cid].facebook.description;
            }
            return sDescription;
        }

        function getShareName() {
            var sName = jTitle.html();
            if (isFacebookShareDataDefined()) {
                sName = share_data[self.cid].facebook.name;
            }
            return sName;
        }

        function isFacebookShareDataDefined() {
            return typeof share_data[self.cid].facebook !== 'undefined'
        }

        function getSharePicture() {
            var sPicture = $('meta[property="og:image"]').attr('content');
            return (sPicture != undefined) ? sPicture : '';
        }

        function getShareLink() {
            var sLink = $('<textarea />').html(jLink.html()).text();
            return sLink.replace(/\?fbdm|\?d/, '?f');
        }

        function friendCounterAndLoadFriends() {
            if (oOptions.sMethod === 'tagging') {
                all_taggable_friends_response = null;
                get_all_taggable_friends(
                    function (response) {
                        if (response && !response.error && response.data) {
                            window.iFriendsCounter = parseInt(response.data.length);
                            loadContactsTable(false);
                        }
                    }, null
                );
            }
        }

        //shows the colorbox with contacts
        this.show = function() {
            bProcessingPost = false;

            if (jList.children().length === 0  && !window.bFbFriendsPermissionGranted) {
                friendCounterAndLoadFriends();
            }

            //if used along S&S, and user has entered a reason,
            //fetch the entered message into the message field,
            //move the message field to the bottom of the widget
            //and hide the 'suggested message' box
            var jTextarea = $('textarea#fb_reason');
            var jContainer = $('#dialogTagFBShareMessageContainer');
            if (jTextarea.length !== 0) {
                if ($.trim(jTextarea.val()) !== '') {
                    $('#suggestedMessageWrapper').hide();
                    jMessage.val(jTextarea.val());
                    if (typeof tracking['petition-id'] === 'undefined') {
                        jContainer.addClass('bottom');
                        jContainer.parent().append(jContainer);
                    }
                } else {
                    jContainer.removeClass('bottom');
                    jContainer.parent().append(jContainer);
                }
                if ($('#dialogTagFBFriendsMessage').val().length > 0) {
                    $('#dialogTagFBFriendsMessage').trigger('change');
                }
            }

            //selector all
            $('#dialogTagFBSelectorAll').click(function() {
                $('#dialogTagFBFriendsSelectors li').removeClass('active');
                $(this).addClass('active');
                //Check all checkboxes and trigger checkBoxChange for the last one
                $('.fb-friends-list input', self).prop('checked', true).trigger('checkBoxChange', true).last().trigger('checkBoxChange');
            });

            //selector none
            $('#dialogTagFBSelectorNone').click(function() {
                $('#dialogTagFBFriendsSelectors li').removeClass('active');
                $(this).addClass('active');
                //Uncheck all checkboxes and trigger checkBoxChange for the last one
                $('.fb-friends-list input', self).prop('checked', false).trigger('checkBoxChange', true).last().trigger('checkBoxChange');
            });

            $('#dialogTagFBFriendsDoneSending').click(function() {
                $.fn.send_ga_event_tagging(oOptions.sMethod, 'Done Sending');
                self.close();
            });

            $('#dialogTagFBFriendsCloseButton').click(function() {
                self.close();
            });

            jMessage.keyup(function() {
                checkSendButtonEnabling();
            });

            jMessage.change(function() {
                checkSendButtonEnabling();
            });

            $.colorbox({
                opacity: 0.5,
                inline: true,
                overlayClose: false,
                scrolling: false,
                href: 'div#' + sPopupId,
                showClose: false,
                closeButton: false,
                onComplete: function() {

                    $.fn.send_ga_event_tagging(oOptions.sMethod, 'Open');

                    dialogTagFBFriendsMessageChange = false;
                    $('#dialogTagFBFriendsMessage').keyup(function(e){
                        if (dialogTagFBFriendsMessageChange == false){
                            dialogTagFBFriendsMessageChange = true;
                            $.fn.send_ga_event_tagging(oOptions.sMethod, 'Message');
                        }
                        return true;
                    });

                    $.InFieldLabelsSetPosition();
                    
                    if (oOptions.sMethod === 'tagging') {
                        $('#dialogTagFBFriendsSelectors').hide();
                    }
                },

                onClosed:function() {
                    $.fn.send_ga_event_tagging(oOptions.sMethod, 'Close');
                }

            });
        };

        this.init_new_form = function (data) {
            loadContactsTable(true);
            set_form_values(data);
            $('#dialogTagFBFriendsMessage').val('').trigger('change');
        };

        function set_form_values(data) {
            set_default_values();
            var values = $.extend(default_values, data);
            for (var h in values) {
                set_value(h, values[h]);
            }
        }

        function set_value (key, value) {
            switch (key) {
            case 'title':
                $('#dialogTagFBFriendsTitle').html(value);
                break;
            case 'text':
                $('#dialogTagFBFriendsText').html(value);
                break;
            case 'href':
                $('#dialogTagFBFriendsLink').html(value);
                break;
                case 'header_title':
                    $('#dialogTagFBFriendsHeaderTitle').html(value);
                    break;
                case 'header_text':
                    $('#dialogTagFBFriendsHeaderMessage').html(value);
                    break;
            }
        }

        function set_default_values () {
            if (!default_values) {
                default_values = {
                    title: $('#dialogTagFBFriendsTitle').html(),
                    text: $('#dialogTagFBFriendsText').html(),
                    href: $('#dialogTagFBFriendsLink').html(),
                    header_title: $('#dialogTagFBFriendsHeaderTitle').html(),
                    header_text: $('#dialogTagFBFriendsHeaderMessage').html(),
                    suggested: $('#suggestedMessageText').data('text')
                };
            }
        }

        function checkSendButtonEnabling() {
            if (window.selectedFriendsCounter > 0) {
                jButton.removeClass('disabled');
            } else {
                jButton.addClass('disabled');
            }

            if (window.selectedFriendsCounter != 1) {
                $('#placeholder-message-blurb').html(oFbMessageBlurbs.messageButtonLabelPlural);
            } else {
                $('#placeholder-message-blurb').html(oFbMessageBlurbs.messageButtonLabelSingular);
            }
        }

        //adds one friend to the list
        function addFriendRow(oItem) {
            var sHtml = "<li class='fbFriendLi' data-fname=\"" + oItem.name + "\"><div class='fb-friends-list-item'>";
            sHtml += "<div class='fb-checkbox-container cell'><input type='checkbox' name='fbFriend' id='fbFriendCheckbox_" + oItem.uid + "' data-fbid='" + oItem.uid + "'></div>";
            //fb user image and name
            sHtml += "<div class='fb-user-img cell'>" + getPictureHTML(oItem) + "</div><div class='last-child cell'>" + oItem.name;
            sHtml +=  "</div></div></li>";
            jList.append(sHtml);
        }

        function checkPermissions(sScope, fCallback) {
            if (sAccessToken == null) {
                sAccessToken = FB.getAccessToken();
            }
            if (sUserId == null) {
                sUserId = FB.getUserID();
            }
            FB.api('/me/permissions?access_token=' + sAccessToken, function(oResponse) {
                if (typeof oResponse.data !== 'undefined' && oResponse.data.length > 0) {
                    var bCondition = true;

                    //check if every scope is included in the granted permissions
                    var aScopes = sScope.split(',');
                    for (var i = 0; i < aScopes.length; i++) {
                        bCondition = checkPermission(oResponse, aScopes[i]);
                        if (!bCondition) {
                            //console.log(oResponse);
                            console.log(aScopes[i]);
                            break;
                        }
                    }

                    //there's only a single permission required per share type,
                    //so no further analysis on this
                    return fCallback(bCondition);
                }
            });
        }

        function checkPermission(oResponse, sPermission){
            var bAcceptedPermission = false;
            if (!$.isEmptyObject(oResponse.data)) {
                oResponse.data.forEach(function(oPermission) {
                    if (isPermissionGranted(sPermission, oPermission)) {
                        bAcceptedPermission = true;
                    }
                })
            }
            return bAcceptedPermission;
        }

        function isPermissionGranted(sPermission, oPermission) {
            return oPermission.permission === sPermission && oPermission.status === 'granted';
        }

        function getScope() {
            return 'publish_actions,user_friends';
        }

        function requestPermissions(iTaggedCount, fCallback) {
            var sScope = getScope(iTaggedCount);

            FB.login(function() {
                return checkPermissions(sScope, fCallback);
            }, {scope: sScope});
        }

        function toggleError(sMsg) {
            if (!sMsg || $.trim(sMsg) === '') {
                $('#dialogTagFBErrorMessage')
                    .html(sMsg || '')
                    .slideUp();
            } else {
                if ($('#dialogTagFBErrorMessage').html().length > 0) {
                    $('#dialogTagFBErrorMessage').slideUp(function() {
                        $('#dialogTagFBErrorMessage')
                            .html(sMsg)
                            .slideDown();
                    });
                } else {
                    $('#dialogTagFBErrorMessage')
                        .html(sMsg)
                        .slideDown();
                }
            }
        }

        function hasExternalLink() {
            var sMessage = $('#dialogTagFBFriendsMessage').val(),
                aUrls = sMessage.match(/\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})\b/ig);
            
            if (aUrls === null) {
                return false;
            }
            
            var bExternalLink = false;
            for (var i=0, il=aUrls.length; i<il; i++) {
                if (!aUrls[i].match(/avaaz.org/)) {
                    bExternalLink = true;
                    break;
                }
            }
            return bExternalLink;
        }

        //shares the post on FB with tagging friends OR via DM (FB chat)
        function tagFriends() {
            var bPassed = true;
            var aTaggedFriends = [];

            $("input[name^='fbFriend']:checked").each(function() {
                aTaggedFriends.push($(this).data('fbid'));
            });

            if (aTaggedFriends.length === 0) {
                bPassed = false;
                toggleError(oFbMessageBlurbs.noFriendsSelected || 'Error: no friends selected');
                $.fn.send_ga_event_tagging(oOptions.sMethod, 'Error', 'No friends selected'); //GA tracking error showing
                bProcessingPost = false;
            } else if ($.trim($('#dialogTagFBFriendsMessage').val()) === '') {
                bPassed = false;
                toggleError(oFbMessageBlurbs.noMessageEntered || 'Error: no message entered');
                $.fn.send_ga_event_tagging(oOptions.sMethod, 'Error', 'No message entered'); //GA tracking error showing
                $.fn.sendOptimizelyEvent('do_dm_message_error');
                bProcessingPost = false;
            } else if (hasExternalLink()) {
                bPassed = false;
                bProcessingPost = false;
                toggleError(oFbMessageBlurbs.noAvaazLink || 'Error: no Avaaz link');
                $.fn.send_ga_event_tagging(oOptions.sMethod, 'Error', 'External link in the message'); //GA tracking error showing
            } else if (oOptions.iTaggingLimit > 0) {
                if ((oOptions.sMethod === 'tagging' && aTaggedFriends.length > oOptions.iTaggingLimit)) {
                    bPassed = false;
                    toggleError(oFbMessageBlurbs.maxFriendsExceeded || 'Error: maximum friends to tag exceeded');
                    $.fn.send_ga_event_tagging(oOptions.sMethod, 'Error', 'Too many friends selected'); //GA tracking error showing
                    bProcessingPost = false;
                }
            }

            if (bPassed) {
                //request extended permissions
                requestPermissions(aTaggedFriends.length, function(bHasPermissions) {
                    if (bHasPermissions) {
                        toggleError();
                        toggleSendingButton();
                        post_tags(aTaggedFriends, postCallback);
                    } else {
                        var sDefaultMessage = 'Avaaz needs permission to send this to your friends.';
                        msg = oFbMessageBlurbs.noTaggingDMPermissions || sDefaultMessage;
                        toggleError(msg);
                        $.fn.send_ga_event_tagging(oOptions.sMethod, 'Error', 'Needs permission'); //GA tracking error showing
                        bProcessingPost = false;
                    }
                });
            }
        }

        function get_mentions_string(friends) {
            var result = ''
            for (var i = 0; i < friends.length; i++) {
                result = result + ' @[' + friends[i] + ']';
            }
            return result;
        }

        function post_tags(friends, callback) {
            params = {
                message: jMessage.val() + get_mentions_string(friends),
                name: jTitle.html(),
                picture: $('meta[property="og:image"]').attr('content'),
                description: jDescription.html(),
                link: jLink.html(),
                campaign: $('meta[property="og:url"]').attr('content').replace(/https:\/\/(.+)\.avaaz\.org/, 'https://secure.avaaz.org') // for testing in branches
            };
            
            FB.api(
                'me/avaazorg:sign',
                'post',
                params,
                function(response) {
                    if (typeof response !== 'undefined' && response !== null && typeof response.id !== 'undefined' && response.id > 0) {
                        var user_hash = getUserHash(true);
                        // get hash from S&S form
                        if ($('#user_hash').length && $('#user_hash').val() !== '') {
                            user_hash = $('#user_hash').val();
                        }
                        $.ajax({
                            url: '/act/ajax_save_fb_share.php',
                            dataType: 'json',
                            type: 'POST',
                            data: {
                                user_hash: user_hash,
                                action_type: 'avaaz-org:sign',
                                action_id: response.id
                            }
                        });
                    }
                    callback(response);
            }); 
        }

        function prepareToSendMoreMessages() {
            //closing the popup on 2nd time messages was sent
            window.bMustClosePopupNextTime = true;

            //done sending link activation
            $('#dialogTagFBFriendsDoneSending').css('display', 'block');
            $.colorbox.resize();

            //send more messages title and text of popup
            $('#dialogTagFBFriendsHeaderTitle').html('<img src="/new/images/do_blue/green_check_med.png" alt="" />' + oFbMessageBlurbs.messageTitleSuccess);
            $('#dialogTagFBFriendsHeaderMessage').html(oFbMessageBlurbs.messageSendAnother);

            //flagging selected (messaged) users container as signed, unselected, not hoverable,
            //message sent, and placed in the bottom of the friends list - also removing checkbox itself
            $('.fb-friends-list input:checked').each(function (){
                $(this).parent().addClass('user-signed');
                $(this).parent().parent().removeClass('selected');
                $(this).parent().parent().removeClass('hoverable');
                $(this).parent().parent().children('div').children('em').html(oFbMessageBlurbs.messageSent);
                $(this).parent().parent().parent().data('order', '2');
                $(this).remove();
            });

            //cleaning search content
            jSearch.val('');
            jSearch.trigger('keyup');
        }

        function postCallback(oResponse) {
            toggleSendingButton();
            bFinishedSharing = true;
            if (oResponse && !oResponse.error) {
                $.fn.send_ga_event_tagging(oOptions.sMethod, 'Shared', 'Friends: ' + window.selectedFriendsCounter); //GA tracking successful shared

                if (!window.bMustClosePopupNextTime)  {
                    prepareToSendMoreMessages();
                } else {
                    self.close();
                }

            } else {
                toggleError(oResponse ? (oResponse.error.message || oResponse.error) : 'Error: no data');
                if (!oResponse) {
                    $.fn.send_ga_event_tagging(oOptions.sMethod, 'Error', oResponse ? (oResponse.error.message || oResponse.error) : 'No data in post callback'); //GA tracking error showing
                }
            }
            bProcessingPost = false;
        }

        function toggleSendingButton() {
            var currentButtonWidth = jButton.innerWidth();
            jButton.toggleClass('sending');
            if (jButton.hasClass('sending')) {
                jButton.find('.button_td1').html((oFbMessageBlurbs.sendingButtonText || 'Sending')+ '<b class="periods">...</b>');
                if (document.all && document.querySelector && !document.addEventListener) {   //recognition ie8
                    jButton.find('.button_td1').width(currentButtonWidth - 54 );
                } else {
                    jButton.width(currentButtonWidth - 40);
                }
                oRunPeriodsTimer = setInterval(animatePeriods, 800);

            } else {
                jButton.find('.button_td1').html(oFbMessageBlurbs.buttonContent);
                if (document.all && document.querySelector && !document.addEventListener) {   //recognition ie8
                    jButton.find('.button_td1').width('auto');
                } else {
                    jButton.width('auto');
                }

                clearInterval(oRunPeriodsTimer);
            }
        }

        function animatePeriods() {
            var jPeriods = jButton.find('.periods');
            var sText = jPeriods.html();
            jPeriods.html((sText !== null && sText.length < 3) ? sText + '.' : '');
        }

        function fill_contacts_callback(oResponse) {
            if (oResponse !== null && !oResponse.error) {
                if (oResponse.data !== null) {
                    for (var i = 0; i < oResponse.data.length; i++) {
                        var oItem = oResponse.data[i];
                        if (oItem && oItem.name && oItem.id && oItem.picture && oItem.picture.data && oItem.picture.data.url) {
                            oItem.uid = oItem.id;
                            oItem.pic_square = oItem.picture.data.url;
                            addFriendRow(oItem);
                            window.iLoadedFriends++;
                        }
                    }
                }

                //updating all counter
                $('#counter-all-friends').html(window.iLoadedFriends);

                var checkBoxChange = function(e) {
                    //main control for Google Analytics friends selection tracker
                    window.selectedFriendsCounter = $('.fb-friends-list input:checked', self).length;

                    if (window.selectedFriendsCounter > oOptions.iTaggingLimit) {
                        e.currentTarget.checked = false;
                        toggleError(oFbMessageBlurbs.tagFriendsMaxFriendsError || 'Error: You can only tag up to 10 friends in you Facebook post');
                        return false;
                    } else {
                        toggleError();
                    }
                    
                    if (e.currentTarget.checked) {
                        $(this).parent().parent().addClass('selected');
                    } else {
                        $(this).parent().parent().removeClass('selected');
                    }
                    
                    $.fn.selectFriendsCounter(oOptions.sMethod);

                    //updation button "Send X Messages"
                    if (window.selectedFriendsCounter != 0) {
                        var selectedFriendsCounterLength = (window.selectedFriendsCounter + ' ').length;
                        $('#counter-selected-friends').css({
                            width: selectedFriendsCounterLength * 10 + 'px'
                        });
                    } else {
                        $('#counter-selected-friends').css({
                            width: '0px'
                        });
                    }

                    //none selector coherence
                    if (window.selectedFriendsCounter == 0) {
                        $('#dialogTagFBSelectorNone').addClass('active');
                    } else {
                        $('#dialogTagFBSelectorNone').removeClass('active');
                    }

                    //all selector coherence
                    if (window.selectedFriendsCounter == window.iLoadedFriends) {
                        $('#dialogTagFBSelectorAll').addClass('active');
                    } else {
                        $('#dialogTagFBSelectorAll').removeClass('active');
                    }

                    $('#counter-selected-friends').html((window.selectedFriendsCounter != 0 ? window.selectedFriendsCounter + ' ' : ''));

                    checkSendButtonEnabling();
                    e.stopPropagation();
                };

                $("input[name='fbFriend']").click(checkBoxChange);
                $("input[name='fbFriend']").bind('checkBoxChange', checkBoxChange);

                //making li inner friend box clickable
                $("input[name='fbFriend']").closest('.fb-friends-list-item').bind('click', function() {
                    var oChildCheckbox = $(this).find(':checkbox');
                    oChildCheckbox.prop('checked', !oChildCheckbox.prop('checked')).trigger('checkBoxChange');
                });

                $('#' + sPopupId + 'Loading').hide();
            }
        }

        function dynamic_sort(property) {
            return function (a, b) {
                var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
                return result;
            }
        }

        function get_all_taggable_friends(callback, previous_response) {
            var params = {access_token: sAccessToken, limit: 5000};
            if (previous_response !== null) {
                params['after'] = previous_response.paging.cursors.after;
            }

            FB.api('/' + FACEBOOK_API_CURRENT + '/me/taggable_friends', 'get', params,
                function (response) {
                    if (!response.error && response.data) {

                        if (all_taggable_friends_response === null) {
                            all_taggable_friends_response = response;
                        } else {
                            all_taggable_friends_response.data = $.merge(all_taggable_friends_response.data, response.data);
                        }

                        if (response.paging && response.paging.cursors && response.paging.cursors.after) {
                            get_all_taggable_friends(callback, response)
                        } else {
                            all_taggable_friends_response.data.sort(dynamic_sort('name'));
                            callback(all_taggable_friends_response);
                        }
                    } else {
                        callback(response);
                    }
            });
        }

        $.fn.fill_contacts_table = function() {
            all_taggable_friends_response = null;
            get_all_taggable_friends(fill_contacts_callback, null);
        }

        //loads the user's contacts
        function loadContactsTable(bReloadContacts) {
            if (typeof(window.iLoadedFriends) == 'undefined' || window.iLoadedFriends == 0 || bReloadContacts) {
                jList.empty();
                $('#' + sPopupId + 'Loading').show();
                window.iLoadedFriends = 0;
                $.fn.fill_contacts_table();
            }
        }

        function getPictureHTML(oItem) {
            var sHtml = '<td class="fb-user-img">';
            if (oItem.pic_square) {
                sHtml += "<img id='pic_" + oItem.uid + "' src='" + oItem.pic_square + "' height='35' width='35' alt='" + oItem.name + "' />\n";
            } else {
                sHtml += "<span class='fbFriendBlock'></span>\n";
            }
            sHtml += "</td>";
            return sHtml;
        }

        function getPlaceHolderHTML() {
            return '<li class="friend-placeholder"></li>';
        }

        function registerGlobalCallbacks() {
            //register global fb callback handler
            if (!window.fbCallback) {
                window.fbCallback = function(oParams) {
                    for (var sCallbackName in window.aFbCallbackStack) {
                        window.aFbCallbackStack[sCallbackName](oParams);
                    }
                };
            }
            if (!window.aFbCallbackStack) {
                window.aFbCallbackStack = [];
            }
            if (!window.aFbCallbackStack.taggingCallback) {
                window.aFbCallbackStack.taggingCallback = function(oParams) {
                    if (oParams) {
                        sAccessToken = oParams.accessToken;
                        sUserId = oParams.userID;
                        bIsLoggedIn = true;
                        $.fn.send_ga_event_tagging(oOptions.sMethod, 'Load', tracking['lang']);

                        self.show();
                    }
                };
            }
            bInitialized = true;
        }

        return this;
    };

    $(document).facebookReady(function(){
        $(document).ready(function(){
            FB.getLoginStatus(function (response) {
                if (response.status == 'connected') {
                    FB.api('/me/permissions', function (response) {
                        if (typeof response.data !== 'undefined' && response.data.length > 0) {
                            response.data.forEach(function(oPermission) {
                                if (oPermission.permission === 'user_friends' && oPermission.status === 'granted') {
                                    window.bFbFriendsPermissionGranted = true;
                                    window.bTaggingToolFirstCall = true;
                                    if (!window.oFBTagWidget) {
                                        var options = {sMethod: sFbMethod};
                                        window.oFBTagWidget = $('div#dialogTagFBFriends').FBTagFriendsWidget(options);
                                    }
                                    window.oFBTagWidget.process();
                                }
                            })
                        }
                    });
                }
            });
        });
    });

})(jQuery);

if (!cid) {
    var cid = tracking.cid;
}

(function (d) {
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {
        return;
    }
    js = d.createElement('script');
    js.id = id;
    js.async = true;
    js.src = '//connect.facebook.net/en_US/sdk.js';
    ref.parentNode.insertBefore(js, ref);
}(document));

$(document).ready(function () {
    $('.message-bar .message-bar-column').eq(0).width(0);
    $('.message-bar .message-bar-column').eq(1).width('100%');
    $.colorbox.resize();
    
    $(window).resize(function() {
        var win_w = $(window).width();
        if ( $('#dialogTagFBFriends').is(':visible') ) {
            if( win_w < 480 ) {
                $.colorbox.resize({
                    width : '300px'
                });
            } else if ( win_w >= 480 && win_w < 768 ) {
                $.colorbox.resize({
                    width : '460px'
                });
            } else if ( win_w >= 768 && win_w < 1200 ) {
                $.colorbox.resize({
                    width : '660px'
                });
            } else {
                $.colorbox.resize({
                    width : '900px'
                });
            }
        }
    });
});
