$(function() {
    var fields = $("#metaDescr, #city, #state");

    var updatePageTitleField = function() {
        var buf = [];
        buf.push($("#sitename").val());
        buf.push(" - ");
        buf.push($("#city").val());
        buf.push(", ");
        buf.push($("#state").val());

        var txt = buf.join("");
        var len = txt.length;

        $(".seo-preview .page-title").text(txt);
    };

    updateDescriptionField = function() {
        var description = $('#metaDescr').val();

        if (description.length > 160) {
            // Trim
            var maxLength = 160 // maximum number of characters to extract

            //trim the string to the maximum length
            var description = description.substr(0, maxLength);

            //re-trim if we are in the middle of a word
            description = description.substr(0, Math.min(description.length, description.lastIndexOf(" ")))

            description += ' ...';
        }

        $('.seo-preview .description').text(description);
    };

    fields.on("keyup keydown change paste", function(ev) {
        var target = $(this);

        if (!target.is("#metaDescr")) {
            updatePageTitleField();
        } else {
            updateDescriptionField();
        }
    });

    fields.change();
})