function openPopup(url, width, height)
{
    if (width == null) {
        width = 500;
    }
    
    if (height == null) {
        height = 400
    }

    var props =
        "width=" + width + ",height=" + height + "," +
        "location=no,toolbar=no,menubar=no,scrollbars=yes," +
        "resizable=yes";

    window.open(url, "popup", props);
}

function editDog(id)
{
    if (id != 0) {
        location.href='index.php?action=pg_edit_dog&dog_id=' + id;
    }
}

function editUser(id)
{
    if (id != 0) {
        location.href='index.php?action=pg_edit_user&user_id=' + id;
    }
}

function viewDeletion(id)
{
    if (id != 0) {
        location.href='index.php?action=pg_view_deleted&dog_id=' + id;
    }
}

function confirmSave(form)
{
    var name = form.dog_name.value;
    var photo1 = form.photo1.value;
    var photo2 = form.photo2.value;

    photo1 = photo1 == '' ? '(not changed)' : photo1;
    photo2 = photo2 == '' ? '(not changed)' : photo2;

    return confirm(
        'Are you sure to save the dog record with the following data?\n' +
        'Name: ' + name + '\n' +
        'Photo1: ' + photo1 + '\n' +
        'Photo2: ' + photo2
    );
}

function handleReturned(returned)
{
    if (Number(returned) == 1) {
        openPopup('?action=pg_edit_adopter');
    }
}

function init()
{
    if (document.dog) {
        switchOtherDispositions();
        document.dog.dog_status.onchange = switchOtherDispositions;
    }
    /*if (focusInfo != null) {
        focusElement(focusInfo[0], focusInfo[1]);
    }*/
}

function switchOtherDispositions()
{
    var form = document.dog;
    var selectValue = form.dog_status.value;
    var disabled = true;
    if (selectValue == 'other disposition') {
        disabled = false;
    }
    var controls =
        ['euthanized', 'returned_to_shelter', 'returned_to_owner'];
    for (var i = 0; i < controls.length; i++) {
        var control = eval('form.dog_' + controls[i]);
        control.disabled = disabled;
    }
}

/**
 * Validates form defined by form name.
 *
 * @access public
 * @param  string
 */
function validate(formName)
{
    switch (formName) {
    case 'login':
        conditions = [
            ['user_login', 'not_empty', 'Please input your user name.'],
            ['user_password', 'not_empty', 'Please input your password.']
        ];
        break;
    case 'dog':
        conditions = [
            ['dog_name', 'not_empty', 'Please input dog name.'],
            ['dog_gender', 'not_empty', 'Please choose dog gender.'],
            ['dog_age', 'not_empty', 'Please input dog age.'],
            ['dog_age', 'positive', 'Dog age incorrect.'],
            ['dog_status', 'not_empty', 'Please choose dog status.'],
            ['dog_intake_date', 'date', 'Intake date is incorrect.']
        ];
        break;
    case 'user':
        conditions = [
            ['user_login', 'not_empty', 'Please input user login.'],
            ['user_password', 'not_empty', 'Please input password.'],
            ['user_name', 'not_empty', 'User name cannot be empyt.'],
            ['user_email', 'not_empty', 'Please fill in e-mail address.'],
            ['user_email', 'email', 'Please input correct e-mail address.']
        ];
        break;
    case 'referral':
        conditions = [
            ['listing_dog_name', 'not_empty', 'Please input dog\'s name.'],
            ['listing_owner_name', 'not_empty', 'Please input your full name.'],
            ['listing_home_phone', 'not_empty', 'Please specify your home phone.'],
            ['listing_email', 'not_empty', 'Please fill in e-mail address.'],
            ['listing_email', 'email', 'Please input correct e-mail address.'],
            ['file', 'not_empty', 'Please choose dog photo file.'],
            ['listing_bio', 'not_empty', 'Please fill in dog\'s bio.']
        ];
        break;
    default:
        alert('Error! Incorrect form name');
        return false;
    }

    return check(conditions, formName);
}

/**
 * Checks form using given conditions.
 *
 * @access public
 * @param  string
 */
function check(conditions, formName)
{
    form = document.forms[formName];
    elems = form.elements;

    for (i = 0; i<conditions.length; i++) {
        field = conditions[i][0];
        type = conditions[i][1];
        message = conditions[i][2];

        for (j = 0; j < elems.length; j++) {
            if (elems[j].name == field) {
                elem = elems[j];
                value = elem.value;
                switch (type) {
                case 'not_empty':
                    if (value == '') {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'email':
                    if (!value.match(/.+@.+\..+/)) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'url':
                    if (!(
                        value == 'http://www.' ||
                        value == '' ||
                        value.match(/^https?:\/\/([\w-]+\.)+[\w-]+(\/.*|)$/)
                    )) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'positive':
                    value = Number(value);
                    if (isNaN(value) || value <= 0) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'regexp':
                    param = conditions[i][3];
                    if (!value.match(param)) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'not_equal':
                    param = conditions[i][3];
                    if (value == param) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'exp':
                    parts = value.split('/');
                    if (!(
                        parts.length == 2 &&
                        parts[0] > 0 &&
                        parts[0] <= 12 &&
                        parts[1] >= 2000
                    )) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'integer':
                    if (!value.match(/^\d+$/)) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'date':
                    if (value != '' && !isCorrectDate(value)) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'currency':
                    if (value != '' && !isCorrectCurrency(value)) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'currency/date':
                    if (value != '') {
                        parts = value.split('/');
                        if (parts.length != 4) {
                            fail(message, formName, elem);
                            return false;
                        }
                        price = parts[0];
                        date = parts[1] + '/' + parts[2] + '/' + parts[3];

                        if (!(
                            isCorrectCurrency(price) &&
                            isCorrectDate(date)
                        )) {
                            fail(message, formName, elem);
                            return false;
                        }
                    }
                    break;
                case 'zip':
                    if (value != '' && !value.match(/^\d{5,}$/)) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                case 'phone':
                    if (value != '' && !value.match(/^[0-9 \+\-\(\)]+$/)) {
                        fail(message, formName, elem);
                        return false;
                    }
                    break;
                }
            }
        }
    }

    return true;
}

/**
 * Checks if given string is a correct date in format mm/dd/yyyy.
 *
 * @param  string
 * @return bool
 */
function isCorrectDate(str)
{
    parts = str.split('/');
    if (parts.length != 3) {
        return false;
    }
    date = new Date(parts[2], parts[0] - 1, parts[1]);

    if(
        (Number(date.getDate()) == Number(parts[1])) &&
        (Number(date.getMonth()) + 1 == Number(parts[0])) &&
        (Number(date.getFullYear()) == Number(parts[2]))
    ) {
        return true;
    } else {
        return false;
    }
}

/**
 * Checks if given string is a correct currency with thouthands and decimals separators.
 *
 * @param  string
 * @return bool
 */
function isCorrectCurrency(value)
{
    return value.match(/^\d+(,\d{3})*(\.\d+)?$/);
}

/**
 * Fails form field one condition check.
 *
 * @param string
 * @param string
 * @param object element
 */
function fail(message, formName, field)
{
    alert(message);
    focus(field);
}

/**
 * Sets focus to given element.
 *
 * @access public
 * @param  object element
 */
function focus(element)
{
    element.focus();
}

/**
 * Sets focus to given element of given form.
 *
 * @access public
 * @param  string
 * @param  string
 */
function focusElement(formName, elementName)
{
    focus(document.forms[formName].elements[elementName]);
}

function go_if_confirmed(message, url)
{
    if (confirm(message)) {
        location.href = url;
    }
}
