var KNOWN_VISITER = false;
var form_edited = false;

function on_form_edit() {
    if (this.value) {
        form_edited = true;
    };
}

$(document).ready(function() {

$("#id_new_name").change(on_form_edit);
$("#id_company").change(on_form_edit);
$("#id_new_email").change(on_form_edit);
$("#id_phone").change(on_form_edit);
$("#id_skype").change(on_form_edit);
$("#id_budget").change(on_form_edit);
$("#id_start").change(on_form_edit);
$("#id_subject").change(on_form_edit);
$("#id_message").change(on_form_edit);

$(window).unload(function() {
    if (form_edited) {
        data = $('#mad-form').serialize();
        if (data) {
            $.post('/talk_form_edited/', data);
        }
        else {
            data = $('#contact-form').serialize();
            $.post('/talk_form_edited/', data);
        }
    };
});

$( "#dialog" ).dialog({
    hide: 'slow',
    show: 'slow',
    autoOpen: false,
    resizable: false,
    draggable: true,
    height: 'auto',
    width: '500',
    position:  [100, 300],
    modal: false,
    zIndex: 2000
});

$('#stayInTouchForm').submit(function() {
    $.post('/stay/', $('#stayInTouchForm').serialize(), function(response) {
        var incorrect = response[0],
            created = response[1],
            blank = response[2];
            ER_MESSAGE = $('#formErrorMessage')
            SUCCESS_MESSAGE = $('#formSuccessMessage')
        ER_MESSAGE.empty();
        SUCCESS_MESSAGE.empty();
        if (incorrect) {
            ER_MESSAGE.append('You entered a non-valid e-mail address!');
        } else if (created) {
            SUCCESS_MESSAGE.append('Your e-mail is already in our mailing list!');
            KNOWN_VISITER = true;
        } else if (blank) {
            ER_MESSAGE.append('Enter your e-mail addres before submiting!'); 
        } else {
            SUCCESS_MESSAGE.append('Thank you!');
            KNOWN_VISITER = true
        }
    }, "json");
    $.idleTimer('destroy');
    $( "#dialog" ).dialog("close");
    return false;
});

// idleTimer() takes an optional argument that defines the idle timeout
// timeout is in milliseconds; defaults to 30000
$.idleTimer(15000);
 
function getCurrentButtonStyle() {
    form = document.getElementsByTagName("form")[0]
    if (form.id == 'mad-form') {
        return 'mad-button'
    } else if (form.id == 'contact-form') {
        return 'contact-button'
    } else {
        return ''
    }
}
 
$(document).bind("idle.idleTimer", function() {
// function you want to fire when the user goes idle
    if (!KNOWN_VISITER) {
        $( "#dialog" ).dialog("open");
        $("#stayInTouchButton").removeClass().addClass(getCurrentButtonStyle());
        $('div.ui-dialog-titlebar').removeClass('ui-widget-header');
    } else {
        // pass the string 'destroy' to stop the timer
        $.idleTimer('destroy');
    }
});

});

