﻿$(function () {
    AviaryJS.init();
});

var AviaryJS = AviaryJS || {};

AviaryJS.init = function () {
    AviaryJS.bindLoginForm();
    AviaryJS.bindForgotPasswordForm();
    AviaryJS.bindSidebar();
    AviaryJS.bindSdkDownloadLinks();
    AviaryJS.bindLightbox();
}

AviaryJS.showLightboxVideo = function (platform) {
    var el = $('#' + platform + '_video');
    el.show();

    el.html(el.html().replace('<!--', '').replace('-->', ''));
}

AviaryJS.bindLightbox = function () {
    $('.light_box').click(function () {
        $(this).hide();
    });
};

AviaryJS.bindSidebar = function () {
    var top = $('#page_content').offset().top; 
    $(window).scroll(function (event) {
        // what the y position of the scroll is
        var y = $(this).scrollTop();

        // whether that's below the form
        if (y >= top) {
            // if so, ad the fixed class
            $('#side_bar').addClass('fixed');
        } else {
            // otherwise remove it
            $('#side_bar').removeClass('fixed');
        }
    });
};

AviaryJS.addDefaultValue = function (domid, value) {
    var $el = $('#' + domid);
    if ($el.length > 0 && $el.attr('type') != 'hidden') {
        var el = document.getElementById(domid);
        var originalType = $el.attr('type');

        // special password code
        if (originalType == 'password') {
            el.setAttribute('type', 'text'); // note: doesn't work in ie < ie9
        }

        $el.focus(function () {
            el.setAttribute('type', originalType); // note: doesn't work in ie < ie9
            if (this.value == value) this.value = '';
        })
        .blur(function () {
            if (this.value == '') {
                this.value = value;
                el.setAttribute('type', 'text'); // note: doesn't work in ie < ie9
            }
        })
        .attr('defaultValue', value);
        
        //console.log($el);
        if ($el.val().length == 0) {
            $el.val(value);
        }
    }

};

AviaryJS.bindForgotPasswordForm = function () {
    var loginForm = $('.login_form');

    if ($('#txtCode').length > 0) {
        AviaryJS.addDefaultValue('txtNewPassword', 'New Password');
        AviaryJS.addDefaultValue('txtConfirmPassword', 'Confirm Password');

        $('#btnResetPassword', loginForm).click(function () {
            var email = $('#txtResetEmail').val();
            var newPassword = $('#txtNewPassword').val();
            var confirmPassword = $('#txtConfirmPassword').val();
            var code = $('#txtCode').val();
            var stuff = $('#txtStuff').val();

            $.ajax({
                url: "/handlers/ajax.ashx?method=changepassword&e=" + encodeURIComponent(email) + "&np=" + encodeURIComponent(newPassword) + "&cp=" + encodeURIComponent(confirmPassword) + "&c=" + encodeURIComponent(code) + "&s=" + encodeURIComponent(stuff),
                dataType: 'json',
                success: function (data) {
                    //console.log(data);
                    if (data.errors && data.errors.length > 0) {
                        AviaryJS.printLoginErrors(data.errors);
                    } else {
                        //console.log(email + " " + newPassword);
                        AviaryJS.login(email, newPassword, '/', stuff);
                    }
                }
            });
            return false;
        });

        // submit on enter
        $('input', loginForm).keypress(function (e) {
            if (e.which == 13) {
                e.preventDefault();
                $('#btnResetPassword').click();
            }
        });

        // show reset form on load
        AviaryJS.showLoginForm();
    }
};

AviaryJS.printLoginErrors = function (errors) {
    var errorString = errors.join();
    $('#login_errors').html(errorString);
};

AviaryJS.login = function (email, password, redirect, stuff) {
    $.ajax({
        url: "/handlers/ajax.ashx?method=login&u=" + encodeURIComponent(email) + "&pw=" + encodeURIComponent(password) + "&s=" + encodeURIComponent(stuff),
        dataType: 'json',
        success: function (data) {
            if (data.errors && data.errors.length > 0) {
                AviaryJS.printLoginErrors(data.errors);
            } else {
                if (redirect && redirect != '') {
                    window.location = redirect;
                } else {
                    window.location.reload();
                }
            }
        }
    });
};

AviaryJS.bindLoginForm = function () {
    var loginForm = $('.login_form');

    // clear fields
    $('#txtEmail, #txtPassword').each(function () {
        $(this).val('');
    });

    AviaryJS.addDefaultValue('txtEmail', 'Email');
    AviaryJS.addDefaultValue('txtPassword', 'Password');

    // login button
    $('#btnLogin', loginForm).click(function () {
        var email = $('#txtEmail').val();
        var password = $('#txtPassword').val();
        var redirect = $('#txtRedirect').val();

        // TODO: fix temp hack to prevent submitting with default password
        if ($('#txtPassword').attr('type') != 'password') {
            password = '';
        }

        var stuff = $('#txtStuff').val();

        AviaryJS.login(email, password, redirect, stuff);

        return false;
    });

    // forgot password
    $('#forgot_password a').click(function () {
        var $this = $(this);
        var email = $('#txtEmail').val();
        $.ajax({
            url: "/handlers/ajax.ashx?method=resetpassword&e=" + encodeURIComponent(email),
            dataType: 'json',
            success: function (data) {
                if (data.status == 'ok') {
                    AviaryJS.printLoginErrors(['Email sent! Check your inbox.']);
                } else { // error
                    AviaryJS.printLoginErrors(data.errors);
                }
            },
            error: function (data, error) {
                //console.log(data);
                //console.log(error);
            }
        });

        return false;
    });

    // logout button
    $('#log_out').click(function () {
        $.ajax({
            url: "/handlers/ajax.ashx?method=logout",
            dataType: 'json',
            success: function (data) {
                if (data.status == 'ok') {
                    window.location.reload();
                } else { // error
                    AviaryJS.printLoginErrors(data.errors);
                }
            }
        });
        return false;
    });

    // submit on enter
    $('input', loginForm).keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
            $('#btnLogin').click();
        }
    });
};

AviaryJS.bindSdkDownloadLinks = function () {
    var button = $('.download_doc');
    var sdk = button.attr('sdk');

    if (button) {
        if (AviaryJS.isLoggedIn) {
            if (sdk == 'web') {
                button.html("Get the widget");
            } else {
                button.html("Download the SDK");
                button.click(function () {
                    $.ajax({
                        url: "/handlers/ajax.ashx?method=sdkdownload&sdk=" + sdk,
                        dataType: 'json',
                        success: function (data) {
                            //console.log(data);
                        },
                        error: function (data, error) {
                            //console.log(data); console.log(error); 
                        }
                    });
                    return true;
                });
            }
        } else {
            button.attr('href', '#');
            if (sdk == 'web') {
                button.html("Log in to get the widget");
            } else {
                button.html("Log in to download SDK");
            }
            button.click(AviaryJS.showLoginForm);
        }

        button.show();
    }
}

AviaryJS.featherLoaded = false;
AviaryJS.featherReady = false;
AviaryJS.showFeatherDemo = function () {
    var launch = function () {
        if (AviaryJS.featherReady) {
            var imgSrc = $('#feather_demo').attr('src');
            AviaryJS.featherEditor.launch({
                image: 'feather_demo', 
                url: imgSrc
            });
        }
    }

    if (!AviaryJS.featherLoaded) {
        AviaryJS.featherLoaded = true;
        AviaryJS.loadScript('http://feather.aviary.com/js/feather.js', function () {
            var img = document.createElement("img");
            img.setAttribute("src", "http://images.aviary.com/imagesv5/feather_default.jpg");
            img.setAttribute("id", "feather_demo"); // style="display:;" /> $('<img />');
            img.setAttribute("style", "display:none");
            document.body.appendChild(img);

            AviaryJS.featherEditor = new Aviary.Feather({
                apiKey: '',
                apiVersion: 2,
                //maxSize: '400',
                onSaveButtonClicked: function () {
                    var html = '<div class="avpw_app_popup" id="avpw_aviary_savedisabled">' +
	                           '    <p class="avpw_message_text">Saving has been disabled for this demo.</p>' +
	                           '    <p class="avpw_message_text">To learn how saving works in the live version, follow the documentation link below:</p>' +
	                           '    <div class="avpw_message_buttons">' +
		                       '        <a href="/web" class="avpw_button">Documentation</a>' +
                               '        <a href="#Close" class="avpw_button" id="avpw_resume_ok">Okay</a>' +
	                           '    </div>' +
                               '</div>';
                    Aviary.controlsWidgetInstance.messager.addMessage(html);

                    $('#avpw_resume_ok').click(function () {
                        Aviary.controlsWidgetInstance.messager.hide();
                    });

                    Aviary.controlsWidgetInstance.messager.show('avpw_aviary_savedisabled', true);

                    return false;
                },
                onSave: function (imageID, newUrl) {
                    //console.log(newUrl);
                    //console.log(imageID);
                    //window.location = '/share?img=' + encodeURI(newUrl);
                },
                onLoad: function () {
                    AviaryJS.featherReady = true;
                    $('.avpw_close_button').click(function () {
                        AviaryJS.featherEditor.close();
                        return false;
                    });
                    launch();
                }
            });
        });
    } else {
        launch();
    }
}

AviaryJS.showLoginForm = function () {
    if (!$("div#panel").is(":visible")) {
        $("#open").click();
    } 
    return false;
}

AviaryJS.loadScript = function (url, callback) {
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script");
    script.src = url;

    /* Attach handlers for all browsers */
    var done = false;
    script.onload = script.onreadystatechange = function () {
        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
            done = true;

            /* Continue your code */
            if (callback != undefined) {
                callback();
            }

            /* Handle memory leak in IE */
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
    };

    head.appendChild(script);
}
