
/*  new/common/templates/widgets/widget_signshare/js/script.js  */
function SignShareWidget(options) {

    var self = this,
    facebook_enabled = false,
    fb_state = {user_details_loaded: false},
    settings = $.extend({}, options);

    function send_fbss_ga_event(type, action, label, callback) {
        if (_gaq && action) {
            _gaq.push(['_set', 'hitCallback', null]); //cleaning callback
            if (callback && typeof callback === 'function') {
                _gaq.push(['_set', 'hitCallback', callback]); //registering callback
            }
            _gaq.push(['_trackEvent', type + ':' + settings.cid, action, label || 'no data']); //registering event
        } else {
            if (callback && typeof callback === 'function') {
                callback(); //running callback anyway
            }
        }
    }

    function get_hash_from_url() {
        var url_params = window.location.search.replace('?', '').split('&');
        var entry = '';
        for (i in url_params) {
            entry = url_params[i];
            if (entry.indexOf('=') === -1 && !/^\d+$/.test(entry) && entry.length >= 6) {
                return entry.substring(1);
            }
        }
        return false;
    }


    function set_user_hash(hash) {
        if ($('#user_hash').length) {
            $('#user_hash').val(hash);
        } else {
            $('body').append('<input type="hidden" id="user_hash" value="' + hash + '"/>');
        }
    }

    function get_user_hash() {
        if ($('#user_hash').length) {
            return $('#user_hash').val();
        }

        return get_hash_from_url();
    }

    function facebook_ready_callback() {
        $(document).ready(function(){
            FB.getLoginStatus(function (response) {
                fb_state.status = response.status;
                $('#conditional-modal').hide();
                if (response.status === 'unknown') {
                    send_fbss_ga_event("FBSS", "NoFB");
                } else {
                    $("label.labeloverlay").inFieldLabels();

                    get_fb_permissions();
                    set_share_handlers();
                    facebook_enabled = true;

                    send_fbss_ga_event("FBSS", "FBFormLoad");
                }
            });
        });
    };

    $(document).facebookReady(facebook_ready_callback);


    function get_fb_permissions(callback) {
        FB.api('/me/permissions', function (oResponse) {
            fb_state.can_post = checkPermission(oResponse, 'publish_actions');
            fb_state.can_get_friends = checkPermission(oResponse, 'user_friends');

            if (!fb_state.user_details_loaded) {
                return get_user_details(callback);
            }
            if (callback && typeof callback === 'function') {
                return callback();
            }
            return;
        });
        return;
    }

    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 get_user_details(callback) {
        FB.api('/me', function(response) {
            if (response && !response.error) {
                //Enabling
                $('input[id^="fb_hidden_"]').removeProp('disabled');

                //Filling First and Last name fields with user data
                $('#fb_hidden_FirstName').val(response.first_name || '');
                $('#fb_hidden_LastName').val(response.last_name || '');

                //Updating or inserting DoB field
                if (response.birthday != null) { //separated tests to avoid error throwing "response.birthday is null"
                    if (response.birthday.match(/^(0\d|1[012])\/(0\d|1\d|2\d|3[01])\/(19|20)\d\d$/)) {
                        $('#fb_hidden_BirthDateDay').val(response.birthday.substr(3, 2) || '');
                        $('#fb_hidden_BirthDateMonth').val(response.birthday.substr(0, 2) || '');
                        $('#fb_hidden_BirthDateYear').val(response.birthday.substr(6, 4) || '');

                        //removing the additional field DoB if it's included
                        $("#additional_form_fields select[name*='DoB']").parent().hide();
                    }
                }

                fb_state.user_details_loaded = true;
            }

            if (callback && typeof callback === 'function') {
                return callback();
            }
        });
    }


    function set_share_handlers() {
        $('#sign-pettition-button').die('click').click(function() {
            if (settings.postaction_in_lightbox) {
                var hash = get_user_hash(),
                    share_data = {
                        display: 'popup',
                        method: 'share',
                        href: settings.link + (hash === '' ? '?fbss' : '?s' + hash)
                    };
                FB.ui(share_data, function() {
                    display_postaction_lightbox();
                });
                return false;
            } else {
                return true;
            }
        });
    }


    function post_to_facebook(message, submit_form) {
        var hash = get_user_hash(),
            post = {
                message: message,
                description: settings.fb_description,
                name: settings.fb_name,
                link: settings.link + (hash === '' ? '?fbss' : '?s' + hash),
                picture: $('meta[property="og:image"]').length > 0 ? $('meta[property="og:image"]').attr('content').replace(/https?:/, document.location.protocol) : ''
            };

        FB.api('/me/feed', 'post', post, function(response) {
            if (submit_form) {
                $.ajax({
                    url: '/act/facebook.php?action=save_share_counter&cid=' + settings.cid + '&lang=' + settings.lang + '&value=clicked',
                    success: function() {
                        $(window).off("unload", submit_form_in_background);
                        $('#petition-form').submit();
                    }
                });
            }
        });
    }


    function display_postaction_lightbox() {
        $.colorbox({
            inline: true,
            href: "#postaction-container-lightbox",
            onClosed: function() {
                $('#petition-form').submit();
            }
        });
    }


    function form_submit() {
        $(window).off("unload", submit_form_in_background);
        if (settings.postaction_in_lightbox) {
            display_postaction_lightbox();
        } else {
            $('#petition-form').submit();
        }
    }


    function submit_form_in_background() {
        $.ajax({
            type: 'POST',
            async: false,
            url: settings.ajax_submit_url,
            data: $('#petition-form').serialize(),
            dataType: 'json',
            success: function(response) {
                // replace url in suggested message and link field
                var url = settings.link + (response.userHash === '' ? '?fbdm' : '?d' + response.userHash);
                if ($('#suggestedMessageText').length > 0) {
                    var suggested_input = $('#suggestedMessageText');
                    suggested_input.data('text', suggested_input.data('text').split("\n")[0] + "\n" + url);
                    suggested_input.text(suggested_input.data('text'));
                }
                $('#dialogTagFBFriendsLink').html(url);

                set_user_hash(response.userHash);
            }
        });
    }
    
    function is_using_fb_tagging_tool() {
        return settings.fb_sharing_method === 'tagging';
    }

    // Init
    $(document).ready(function() {

        send_fbss_ga_event("FBSS", "PageLoad");

        $('#sign-pettition-button').click(function(event) {
            if (!$('#petition-form').valid()) {
                event.preventDefault();
                return false;
            }
        });

        $("#petition-form").submit(function() {
            send_fbss_ga_event("FBSS", "AjaxSign", null, function() {
                return false;
            });
        });


        $('#fbPseudoPopupButton').click(function() {
            post_to_facebook($('#fb_reason_popup').val(), true);
            $.colorbox.close();
        });


        $('#share_on_fb').click(function() {
            if (settings.postaction_in_lightbox) {
                $('#share_on_fb_signajax')[0].checked = $(this)[0].checked;
            }
            if ($('#share_on_fb').is(":checked")) {
                $(".selectwrapper2").hide();
            } else {
                $(".selectwrapper2").show();
            }
        });

        var callback_logged_facebook = function () {
            $(window).unload(submit_form_in_background);
            if (fb_state.can_post) {
                submit_form_in_background();
                if (can_use_tagging_tool()) {
                    if (is_using_fb_tagging_tool()) {
                        post_to_facebook($("#fb_reason").val(), false);
                    }
                    window.oFBTagWidget.process(true);
                } else {
                    var message = $("#fb_reason").val();
                    if ($.trim(message) !== '') {
                        send_fbss_ga_event("FBSS", "AddedDesc");
                        post_to_facebook(message, true);
                    } else {
                        $.colorbox({
                            href: '#fbPseudoPopup',
                            inline: true,
                            opacity: 0.6,
                            showClose: false,
                            onComplete: function () {
                                $.InFieldLabelsSetPosition();
                                $('#fb_reason_popup').focus();
                                $('#fbPseudoPopupImage').attr('src', $('meta[property="og:image"]').attr('content').replace(/https?:/, document.location.protocol));
                            },
                            onClosed: function () {
                                $('#petition-form').submit();
                            }
                        });
                    }
                }
            } else {
                form_submit();
            }
        }

        var can_use_tagging_tool = function () {
            return settings.integrate_dm_tag && window.oFBTagWidget && fb_state.can_get_friends === true;
        }

        $('#fb_sign_button').click(function() {

            //pattern taken from jQuery validator
            var pat = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,
                email = $('#petition-form-Email').val(),
                passed = true;

            $('#petition-form-Email').parent().removeClass('pinkwraper');
            if (email.length > 0 && pat.test(email)) {
                $('#fb_hidden_Email').val(email);
            } else {
                $('#petition-form-Email').parent().addClass('pinkwraper');
                passed = false;
            }

            if (!$('#petition-form').valid()) {
                passed = false;
            }

            if (passed) {

                var post_to_fb = $('#share_on_fb').prop('checked');

                if (post_to_fb) {
                    var sScope = get_facebook_scope();

                    FB.login(function(response) {
                        get_fb_permissions(callback_logged_facebook);
                    }, {
                        scope: sScope,
                        auth_type: 'rerequest'
                    });
                } else {
                    form_submit();
                }
            }
            return false;
        });

        var get_facebook_scope = function () {
            var sScope = 'publish_actions,user_birthday';
            if (is_set_tagging_widget()) {
                sScope += ',user_friends';
            }
            return sScope;
        }

        var is_set_tagging_widget = function () {
            return settings.integrate_dm_tag && window.oFBTagWidget;
        }

        // check for fbss hash to include the input hidden for conversions
        var url_params = window.location.search.replace('?', '').split('&');
        for (i in url_params) {
            if (url_params[i] === 'fbss') {
                $('form').each(function() {
                    if (!($(this).find('[name="hash"]')[0])) {
                        $(this).append('<input type="hidden" name="hash" value="fbss"/>');
                    }
                });
            }
        }

        // set global variable for FormSignAjax
        window.cbp = new CheckBoxProcessor('#petition-form');
        if (settings.check_isps) {
            window.cbp.setISPS(settings.isps);
        }


        (function() {

            var condition = is_using_fb_tagging_tool() && settings.integrate_dm_tag && (typeof($.fn.FBTagFriendsWidget) === 'function');
            
            if (condition) {
                var options = {
                    sMethod: settings.fb_sharing_method,
                    bIntegrateSignAndShare: true,
                    bForceFinishedCallback: settings.postaction_in_lightbox,
                    finishedCallback: function() {
                        form_submit();
                    }
                };
                if (!window.oFBTagWidget) {
                    window.oFBTagWidget = $('div#dialogTagFBFriends').FBTagFriendsWidget(options);
                }
            }
        })();


    });
}