/* Application-wide javascript methods for PointCarbon web app */

function updatePhoneCountryCode(countryCode) {
    var codes = document.getElementById("userInfoForm:userPhoneCountryCodeSelect");
    var i;
    var found = false;
    for (i = 0; i <codes.options.length; i++) {
        if (codes.options[i].value == countryCode) {
            document.getElementById("userInfoForm:userWorkPhoneCountryCode").value = codes.options[i].text;
            document.getElementById("userInfoForm:userWorkPhoneCountryCodeText").value = codes.options[i].text;
            document.getElementById("userInfoForm:userMobilePhoneCountryCode").value = codes.options[i].text;
            document.getElementById("userInfoForm:userMobilePhoneCountryCodeText").value = codes.options[i].text;
            found = true;
            return;
        }
    }
    if (found == false) {
        document.getElementById("userInfoForm:userWorkPhoneCountryCode").value = "";
        document.getElementById("userInfoForm:userWorkPhoneCountryCodeText").value = "";
        document.getElementById("userInfoForm:userMobilePhoneCountryCode").value = "";
        document.getElementById("userInfoForm:userMobilePhoneCountryCodeText").value = "";
    }

}

function updateInvoicePhoneCountryCode(countryCode) {
    var codes = document.getElementById("invoiceInfoForm:invoicePhoneCountryCodeSelect");
    var i;
    var found = false;
    for (i = 0; i <codes.options.length; i++) {
        if (codes.options[i].value == countryCode) {
            document.getElementById("invoiceInfoForm:invoicePhoneCountryCode").value = codes.options[i].text;
            document.getElementById("invoiceInfoForm:invoicePhoneCountryCodeText").value = codes.options[i].text;
            found = true;
            return;
        }
    }
    if (!found) {
        document.getElementById("invoiceInfoForm:invoicePhoneCountryCode").value = "";
        document.getElementById("invoiceInfoForm:invoicePhoneCountryCodeText").value = "";
    }

}

/*
 * The goal of this hack is to support Tomahawk dataScroller
 * component in FireFox. See PC-1462
 */
function a4jDataScrollerSyncFormSubmitHack (form) {
    if (form.isSubmittingByA4J) {
        return true; // allow A4J to send form
    }

    var idclDetected = false;
    var scrollDetected = false;

    for (var i = 0; i < form.elements.length; i++) {
        var name = form.elements[i].name;
        if (name == form.name + ":_idcl") {
            idclDetected = true;
        } else if (name == form.name + ":scroll_1") {
            scrollDetected = true;
        }
    }

    // if it looks like data scroller form submit
    if (idclDetected && scrollDetected && form.action && form.action.indexOf("javascript:") == 0) {
        var params = {};
        params[form.id] = form.id;

        form.isSubmittingByA4J = true;
        A4J.AJAX.SubmitForm('_viewRoot', form.id, {'parameters': params, 'actionUrl': location.pathname } );
        form.isSubmittingByA4J = false;

        return false; // we already sent form
    }

    // allow form submission for non- data scroller requests
    return true;
}

/*
 * Use new SingleSubmitSupport.apply("#myForm", 30000) to allow the "myForm" form to be submitted only once per 30 sec
 */
SingleSubmitSupport = function (jqueryExpression, unlockTimeout) {
    this.submitLocked = false;

    var form = jQuery(jqueryExpression);
    var that = this;

    form.submit(function() {
        if (that.submitLocked) {
            return false; // prevent submitting
        }

        that.submitLocked = true;
        form.fadeTo(500, 0.5);

        if (unlockTimeout) {
            setTimeout(function() {
                that.submitLocked = false;
                form.fadeTo(500, 1.0);
            }, unlockTimeout);
        }

        return true;
    });
};

SingleSubmitSupport.apply = function (jqueryExpression, unlockTimeout) {
    return new SingleSubmitSupport(jqueryExpression, unlockTimeout);
};

LoginFormSupport = {
    apply : function () {
        var singleSubmitSupport = SingleSubmitSupport.apply("#loginForm", 30000);

        var usernameField = jQuery('#username');
        var passwordField = jQuery('#password');

        var usernameText = jQuery('#username_backgroundtext');
        var passwordText = jQuery('#password_backgroundtext');

        usernameField.data("fgDiv", usernameText);
        passwordField.data("fgDiv", passwordText);

        usernameText.data("inputField", usernameField);
        passwordText.data("inputField", passwordField);

        jQuery("#username, #password").focusin(function() {
            jQuery(this).data("fgDiv").fadeOut(500);
        }).focusout(function () {
            if (!jQuery(this).val()) {
                jQuery(this).data("fgDiv").fadeIn(500);
            }
        }).bind('mousemove mouseover keydown keyup', function() {
            if (jQuery("#password").val().length > 0) {
                passwordText.hide();
            }
        });

        jQuery("#username_backgroundtext, #password_backgroundtext").click(function() {
            jQuery(this).fadeOut(500);
            jQuery(this).data("inputField").focus();
        });

        if (readCookie("rmc") == "1") {
            jQuery('input#rememberMe').attr('checked', true);
        }

        jQuery("#loginForm").submit(function() {
            createCookie("rmc", jQuery("input#rememberMe").attr("checked") ? 1 : 0, 90);
        });

        jQuery('#login_button').click(function() {
            jQuery(".login_box").slideToggle(250);
        });

        jQuery("#loginForm input[value=cancel]").click(function() {
            if (!singleSubmitSupport.submitLocked) {
                jQuery(".login_box").slideUp(250);
            }
        });

        // need to wait a bit because browser does login/password autofill with unknows timeout and without firing onchange() event
        setTimeout(function() {
            jQuery("#username, #password").each(function() {
                if (jQuery(this).val()) {
                    jQuery(this).data("fgDiv").fadeOut(500);
                } else {
                    jQuery(this).data("fgDiv").fadeIn(500);
                }
            });
        }, 1000);

        // show form if login failed
        jQuery(".login_box .errorMessage").each(function() {
            jQuery(".login_box").slideDown(250);
        });

        SingleSubmitSupport.apply("#logoutForm", 30*1000);
    }
};

jQuery(function() {
    LoginFormSupport.apply();
});

CollapsibleDigest = {
    apply: function(listSeq, digestCharacters) {
        jQuery(listSeq +' .article_abstract').each(function(k,v) {
            var elem = jQuery(v);
            if(elem.html().length > digestCharacters) {
                var elemExpand = jQuery(document.createElement('span')).text('+').attr('title', 'Show full digest').addClass('more');
                var elemCollapse = jQuery(document.createElement('span')).text('-').attr('title', 'Hide digest').addClass('less');

                elemExpand.click(function() {
                    CollapsibleDigest.expand(elem);
                });

                elemCollapse.click(function() {
                    CollapsibleDigest.collapse(elem, digestCharacters);
                });

                elem.attr('fulltext', elem.html())
                        .html((elem.html().substr(0, digestCharacters) + '...'))
                        .after(elemExpand.css('display', 'inline'))
                        .after(elemCollapse.css('display', 'none'));
            }
        });
    },
    expand : function (elem) {
        elem.html(elem.attr('fulltext'));
        elem.siblings('.more').css('display', 'none');
        elem.siblings('.less').css('display', 'inline');
    },

    collapse : function (elem, digestCharacters) {
        elem.html(elem.html().substr(0, digestCharacters) + '...');
        elem.siblings('.less').css('display', 'none');
        elem.siblings('.more').css('display', 'inline');
    }

};

(pc = window.pc || {}).time = {
    /**
     * Wrapper around window.setTimeout() function.
     * Provides delayed function execution with arguments(!).
     */
    setTimeout : function (timeout, func, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) {
        var f = function () {
            func(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
        };
        return setTimeout(f, timeout);
    }
};

String.prototype.padLeft = function (length, padChar) {
    if (typeof padChar == undefined) {
        padChar = " ";
    }

    var s = this;

    while (s.length < length) {
        s = padChar + s;
    }

    return s;
}

