jQuery(function ($) {

    var $container = $('#YWSFD_wrapper'),
        queryString = '';

    $(document).on('woocommerce_variation_has_changed', function () {

        var params = [];

        if (ywsfd.onsale_variations.length > 0) {

            var active_variation = parseInt($('.single_variation_wrap .variation_id, .single_variation_wrap input[name="variation_id"]').val());

            if ($.inArray(active_variation, ywsfd.onsale_variations) === -1) {
                $('.ywsfd-wrapper').show();
            } else {
                $('.ywsfd-wrapper').hide();
            }

        }

        if (ywsfd.custom_url === 'no') {

            $('.variations select').each(function () {
                if ($('option:selected', this).val()) {
                    params.push('attribute_' + $(this).attr('id') + '=' + $('option:selected', this).val());
                }
            });

            queryString = params.join('&');

            if (ywsfd.facebook === 'yes') {
                $('body').trigger('facebook_button').trigger('facebook_share');
            }

            if (ywsfd.twitter === 'yes') {
                $('body').trigger('twitter_button');
            }

            if (ywsfd.linkedin === 'yes') {
                $('body').trigger('linkedin_button');
            }

            if (ywsfd.email === 'yes') {
                if (queryString !== '') {
                    var email = $('#ywsfd_sharing_url');
                    email.val(ywsfd.sharing.url + '?' + queryString);
                }
            }

        }

    });

    $(document).ready(function () {
        load_share_bar();
    });

    /** Load Share Bar*/
    function load_share_bar() {

        if (container_processing()) {
            return false;
        }

        if (!$container.length) {
            return false;
        }

        $.ajax({
            type    : 'POST',
            url     : ywsfd.ajax_load_url,
            data    : {
                post_id: ywsfd.post_id
            },
            success : function (response) {
                $container.html(response);
                /**
                 * If Facebook active
                 */
                if (ywsfd.facebook === 'yes') {
                    $("a.ywsfd-facebook-share").click(facebook_share);
                }

                /**
                 * If Twitter active
                 */
                if (ywsfd.twitter === 'yes') {

                    var tweet_textarea = $('.ywsfd-twitter-form-wrapper .input-textarea');

                    twitter_length(tweet_textarea);
                    tweet_textarea.on('change keyup input', function () {
                        twitter_length($(this));
                    });
                    tweet_textarea.on('blur input change', function () {

                        var $this = $(this),
                            $parent = $this.closest('.form-row'),
                            validated = true;

                        if ($parent.is('.ywsfd-validate-required')) {
                            if ($this.val() === '') {
                                $parent.removeClass('ywsfd-validated').addClass('ywsfd-invalid');
                                validated = false;
                            }
                        }

                        if (validated) {
                            $parent.removeClass('ywsfd-invalid').addClass('ywsfd-validated');
                        }

                    });

                    $('.ywsfd-tweet-button').unbind().bind('click', function (e) {
                        e.preventDefault();
                        $.when(twitter_auth()).then(function (response) {
                            twitter_show_form(response.oauth_token, response.oauth_verifier)
                        })
                    });

                    $('body').trigger('twitter_button');

                }

                /**
                 * If Linkedin active
                 */
                if (ywsfd.linkedin === 'yes') {

                    $('.ywsfd-linkedin-button').unbind().bind('click', function (e) {

                        e.preventDefault();

                        $.when(linkedin_auth()).then(function (response) {
                            linkedin_show_form(response.code, response.state)
                        })

                    });

                    $('body').trigger('linkedin_button');

                }

                /**
                 * If Email active
                 */
                if (ywsfd.email === 'yes') {

                    var ywsfd_mail_form = {
                        body          : $('body'),
                        email_form    : $('.ywsfd-email-form-wrapper'),
                        email_submit  : $('#ywsfd_email'),
                        init          : function () {
                            // Form submission
                            this.email_submit.on('click', this.submit);
                            // Inline validation
                            this.email_form.on('blur input change', '.input-text', this.validate_field);

                        },
                        validate_field: function () {
                            var $this = $(this),
                                $parent = $this.closest('.form-row'),
                                validated = true;

                            if ($parent.is('.ywsfd-validate-required')) {
                                if ($this.val() === '') {
                                    $parent.removeClass('ywsfd-validated').addClass('ywsfd-invalid');
                                    validated = false;
                                }
                            }

                            if ($parent.is('.ywsfd-validate-email')) {
                                if ($this.val()) {

                                    /* https://stackoverflow.com/questions/2855865/jquery-validate-e-mail-address-regex */
                                    var pattern = new RegExp(/^((([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);

                                    if (!pattern.test($this.val())) {
                                        $parent.removeClass('ywsfd-validated').addClass('ywsfd-invalid');
                                        validated = false;
                                    }
                                }
                            }

                            if (validated) {
                                $parent.removeClass('ywsfd-invalid').addClass('ywsfd-validated');
                            }
                        },
                        submit        : function (e) {
                            var $form = $('.ywsfd-email-form-wrapper');
                            $form.addClass('opened');

                            if ($('#ywsfd_friend_email').val() == $('#ywsfd_user_email').val()) {

                                $('#ywsfd_friend_email').parent().addClass('ywsfd-invalid');
                                $('#ywsfd_user_email').parent().addClass('ywsfd-invalid');

                                return false;
                            }


                            if (container_processing()) {
                                return false;
                            }

                            $.ajax({
                                type    : 'POST',
                                url     : ywsfd.ajax_email_url,
                                data    : {
                                    ywsfd_wpnonce     : $('#ywsfd_wpnonce').val(),
                                    ywsfd_friend_email: $('#ywsfd_friend_email').val(),
                                    ywsfd_user_email  : $('#ywsfd_user_email').val(),
                                    ywsfd_message     : $('#ywsfd_message').val(),
                                    ywsfd_sharing_url : $('#ywsfd_sharing_url').val(),
                                    ywsfd_post_id     : $('#ywsfd_post_id').val()
                                },
                                success : function (code) {

                                    var result = parse_response(code);

                                    try {

                                        if (result.status === 'success') {
                                            after_share_redirect(result.redirect);
                                        } else if (result.status === 'failure') {
                                            print_error_messages(result, code)
                                        }

                                    } catch (err) {
                                        print_error_messages(result, code);
                                    }
                                },
                                dataType: 'html'
                            });

                            return false;
                        }
                    };

                    ywsfd_mail_form.init();

                    $('.ywsfd-email').click(function () {
                        $('.ywsfd-email-form-wrapper').toggleClass('opened')
                    });

                }

                if (ywsfd.custom_url === 'no') {

                    $(document).ready(function () {

                        $('body').bind('twitter_button', alter_twitter_button).bind('linkedin_button', alter_linkedin_button).bind('facebook_button', alter_facebook_button).bind('facebook_share', alter_facebook_share);
                    });

                }

                if (ywsfd.onsale_variations.length > 0) {

                    var active_variation = parseInt($('.single_variation_wrap .variation_id, .single_variation_wrap input[name="variation_id"]').val());

                    if ($.inArray(active_variation, ywsfd.onsale_variations) !== -1) {

                        $('.ywsfd-wrapper').hide();

                    }

                }

                $container.removeClass('processing').unblock();

            },
            complete: function () {
                if (ywsfd.facebook === 'yes') {
                    loadScript("//connect.facebook.net/" + ywsfd.locale + "/all.js",
                        function () {
                            FB.init({
                                appId  : ywsfd.fb_app_id,
                                xfbml  : true,
                                version: 'v2.12'
                            });
                            FB.XFBML.parse();
                            FB.Event.subscribe("edge.create", function () {
                                get_coupon('fblike');
                            });
                            $('body').trigger('facebook_button').trigger('facebook_share');
                        });
                }
            },
            dataType: 'json'
        });

        return false;

    }

    /** Container processing handler*/
    function container_processing() {

        if ($container.is('.processing')) {
            return true;
        }

        $container.addClass('processing');
        $container.block({
            message   : null,
            overlayCSS: {
                background: '#fff',
                opacity   : 0.6
            }
        });

        return false;
    }

    /** Get the coupon and add it to cart */
    function get_coupon(social) {

        if (social !== 'twitter' && social !== 'linkedin') {
            if (container_processing()) {
                return false;
            }
        }

        $.ajax({
            type    : 'POST',
            url     : ywsfd.ajax_social_url,
            data    : {
                post_id: ywsfd.post_id
            },
            success : function (code) {

                var result = parse_response(code);

                try {
                    if (result.status === 'success') {
                        after_share_redirect(result.redirect);
                    } else if (result.status === 'failure') {
                        print_error_messages(result, code);
                    }
                } catch (err) {
                    print_error_messages(result, code);
                }
            },
            dataType: 'html'
        });

        return false;

    }

    /** Share Button Function */
    function facebook_share(e) {

        e.preventDefault();

        var url = $(this).data('href');

        FB.ui({
            method : 'feed',
            link   : url,
            caption: '',
            display: 'popup'
        }, function (response) {
            if (typeof response !== 'undefined') {
                get_coupon('fbshare');
            }
        });

    }

    /** Twitter Button Functions */
    function twitter_auth() {

        var dfd = $.Deferred(),
            popup = window.open(ywsfd.twitter_login, "", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=450");

        window.twitter_callback = function (oauth_token, oauth_verifier) {
            popup.close();
            dfd.resolve({
                oauth_token   : oauth_token || null,
                oauth_verifier: oauth_verifier || null
            });
        };

        return dfd.promise();

    }

    function twitter_show_form(oauth_token, oauth_verifier) {

        $('.ywsfd-twitter-form-wrapper').addClass('opened');
        $('.ywsfd-send-tweet').unbind().bind('click', function () {

            if (container_processing()) {
                return false;
            }

            $.ajax({
                type    : 'POST',
                url     : ywsfd.twitter_send_ajax,
                data    : {
                    oauth_token   : oauth_token || null,
                    oauth_verifier: oauth_verifier || null,
                    tweet         : $('#ywsfd_tweet_text').val(),
                    sharing_url   : $('.ywsfd-tweet-button').data('href')
                },
                success : function (code) {
                    var result = parse_response(code);

                    try {
                        if (result.status === 'success') {
                            get_coupon('twitter');
                        } else if (result.status === 'failure') {
                            print_error_messages(result, code);
                        }
                    } catch (err) {
                        print_error_messages(result, code);
                    }
                },
                dataType: 'html'
            });

        });
        $('.ywsfd-cancel-tweet').unbind().bind('click', function () {
            $('.ywsfd-twitter-form-wrapper').removeClass('opened');
        });

    }

    function twitter_length(textarea) {

        if (textarea.val() === undefined) {
            return;
        }

        var length = textarea.val().length,
            chars = 280 - length,
            char_count = $('.ywsfd-char-count');

        char_count.find('span').text(chars);

        if (chars < 0) {
            char_count.addClass('maxed-out');
        } else {
            char_count.removeClass('maxed-out');
        }

    }

    /** LinkedIn Button Functions */
    function linkedin_auth() {

        var dfd = $.Deferred(),
            popup = window.open(ywsfd.linkedin_login, "", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=450");

        window.linkedin_callback = function (code, state) {
            popup.close();
            dfd.resolve({
                code : code || null,
                state: state || null
            });
        };

        return dfd.promise();

    }

    function linkedin_show_form(code, state) {

        $('.ywsfd-linkedin-form-wrapper').addClass('opened');
        $('.ywsfd-send-linkedin').unbind().bind('click', function () {

            if (container_processing()) {
                return false;
            }

            $.ajax({
                type    : 'POST',
                url     : ywsfd.linkedin_send_ajax,
                data    : {
                    code       : code || null,
                    state      : state || null,
                    message    : $('#ywsfd_linkedin_text').val(),
                    sharing_url: $('.ywsfd-linkedin-button').data('href')
                },
                success : function (code) {

                    var result = parse_response(code);

                    try {
                        if (result.status === 'success') {
                            get_coupon('linkedin');
                        } else if (result.status === 'failure') {
                            print_error_messages(result, code);
                        }
                    } catch (err) {
                        print_error_messages(result, code);
                    }

                },
                dataType: 'html'
            });

        });

        $('.ywsfd-cancel-linkedin').unbind().bind('click', function () {
            $('.ywsfd-linkedin-form-wrapper').removeClass('opened');
        });

    }

    /** Querystring Functions*/
    function alter_twitter_button() {
        if (queryString !== '') {
            $('.ywsfd-social-button .ywsfd-tweet-button').data('href', ywsfd.sharing.url + "?" + queryString);
            $('#ywsfd_tweet_text').val(ywsfd.sharing.message + ' - ' + ywsfd.sharing.url + "?" + queryString + ywsfd.sharing.twitter_username);
        }
    }

    function alter_linkedin_button() {
        if (queryString !== '') {
            $('.ywsfd-social-button .ywsfd-linkedin-button').data('href', ywsfd.sharing.url + "?" + queryString);
            $('#ywsfd_linkedin_text').val(ywsfd.sharing.message + ' - ' + ywsfd.sharing.url + "?" + queryString);
        }
    }

    function alter_facebook_button() {
        if (queryString !== '') {
            $('.ywsfd-social-button.fb-like-btn').html('<div class="fb-like" data-layout="button" data-action="like" data-show-faces="false" data-share="false" data-href="' + ywsfd.sharing.url + '?' + queryString + '"></div>');
            FB.XFBML.parse()
        }
    }

    function alter_facebook_share() {
        if (queryString !== '') {
            $('.ywsfd-social-button .ywsfd-facebook-share').data('href', ywsfd.sharing.url + "?" + queryString);
        }
    }

    /** Parse AJAX response */
    function parse_response(response) {
        // Get the valid JSON only from the returned string
        if (response.indexOf('<!--WC_START-->') >= 0) {
            response = response.split('<!--WC_START-->')[1]; // Strip off before after WC_START
        }

        if (response.indexOf('<!--WC_END-->') >= 0) {
            response = response.split('<!--WC_END-->')[0]; // Strip off anything after WC_END
        }

        // Parse
        return $.parseJSON(response);
    }

    /** Manage error message*/
    function print_error_messages(result, code) {

        // Remove old errors
        $('.woocommerce-error, .woocommerce-message').remove();

        // Add new errors
        if (result.messages) {
            $('.ywsfd-errors').append(result.messages);
        } else {
            $('.ywsfd-errors').append(code);
        }

        // Cancel processing
        $container.removeClass('processing').unblock();

        // Scroll to top
        $('html, body').animate({
            scrollTop: ($container.offset().top - 100)
        }, 1000);

    }

    /** Redirection after sharing*/
    function after_share_redirect(redirect) {
        setTimeout(function () {
            if (redirect.indexOf("https://") !== -1 || redirect.indexOf("http://") !== -1) {
                window.location = redirect;
            } else {
                window.location = decodeURI(redirect);
            }
        }, 10000);
    }

    function loadScript(stUrl, fnCallback) {
        var script = document.createElement("script");
        script.type = "text/javascript";

        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState === "loaded"
                    || script.readyState === "complete") {
                    script.onreadystatechange = null;
                    fnCallback();
                }
            };
        }
        else {
            script.onload = function () {
                fnCallback();
            };
        }

        script.src = stUrl;
        script.id = 'facebook-jssdk';
        script.async = true;
        document.getElementsByTagName('head')[0].appendChild(script);
    }

});


