﻿$(document).ready(function() {

    var options = {
        bookStatusField: $('#bookStatus'),
        publisherField: $('#publisher'),
        otherPublisherField: $('#otherPublisher'),
        emailField: $('#emailAddress'),
        cookie: 'ah_lead_email',
        validateTextField: "design_validate_re(/\\S+/,this,'Cannot be blank');",
        validateSelectField: "design_validate_select(1, this, 'First item is not a valid selection.')"
    };

    // Looks for ah_lead_email cookie
    // If exists, prepopulates email address field
    function getCookie(c_name) {
        if (c_name.length > 0) {
            c_start = document.cookie.indexOf(c_name + '=');
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(';', c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    }
    function checkForCookie() {
        emailAddress = getCookie(options.cookie);
        if (emailAddress != null && emailAddress != '') {
            options.emailField.val(emailAddress);
        }
    }
    function query(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else return results[1];
    }

    function refer() {
        document.getElementById('refurl').value = document.URL;
        document.getElementById('src').value = query('src');
        document.getElementById('kw').value = query('kw');
        document.getElementById('gclid').value = query('gclid');
        document.getElementById('gkw').value = query('gkw');
        document.getElementById('mt').value = query('mt');
        document.getElementById('cat').value = query('cat');
    }
    refer();
    checkForCookie();

    // Functions to hide/show correct fields
    options.publisherField.parent().hide();
    options.otherPublisherField.parent().hide();

    options.bookStatusField.blur(function(e) {
        currentSelection = e.currentTarget.selectedIndex;

        if (currentSelection == 1 || currentSelection == 2) {
            options.publisherField.parents('.row').show();
        } else {
            options.publisherField.parents('.row').hide();
        }
    });
    options.publisherField.blur(function(e) {
        otherOption = e.currentTarget.options.length - 1;


        if (otherOption == e.currentTarget.options.selectedIndex) {
        options.otherPublisherField.parents('.row').show();
        } else {
        options.otherPublisherField.parents('.row').hide();
        }
    });
});
