﻿$(function() {

    /* Initialize autocomplete for Author */
    function authorAutoComplete() {
        $('#authorSearch, .authorSearchInput').autocomplete({
            source: "components/author.cfc?method=search",
            minLength: 1,
            focus: function(event, ui) {
                return false;
            },
            select: function(event, ui) {
                $(this).attr('value', ui.item.value);
                $(this).siblings('.authorSearchID').attr('value', ui.item.id);
                return false;
            }
        });
    }
    /* Initialize autocomplete for Books */
    $('#bookSearchInput').autocomplete({
        source: "components/book.cfc?method=search",
        minLength: 1,
        focus: function(event, ui) {
            return false;
        },
        select: function(event, ui) {
            $(this).attr('value', ui.item.value);
            $(this).siblings('.bookSearchID').attr('value', ui.item.id);
            $(this).siblings('#searchSubmit').removeAttr('disabled');

            $('#searchSubmit').click();
        }
    });

    /* Initialize autocomplete for Publisher */
    $('#publisherSearchInput').autocomplete({
        source: "components/publisher.cfc?method=search",
        minLength: 1,
        focus: function(event, ui) {
            return false
        },
        select: function(event, ui) {
            $(this).attr('value', ui.item.value);
            $(this).siblings('#publisherSearchID').attr('value', ui.item.id);
            return false;
        }
    });

    /* Disable the Search Button unless value has changed */
    $('#searchSubmit').click(function() {
        if ($('.authorSearchID, .publisherSearchID, .bookSearchID').val() > 0) {
            return true;
        } else {
            return false;
        }
    });


    /* On bookedit.cfm - add author functionality */
    $('form table').delegate("#authoradd a", "click", function(event) {
        event.preventDefault();
        var numAuthors = $('#addauthors').val(),
            numAuthors = parseInt(numAuthors, 10),
            numPrevAuthors = numAuthors - 1,
            numNextAuthors = numAuthors + 1,
            authoradd, authorRem, html;

        /* build a new table row */
        html = '<tr><th><label for="author' + numNextAuthors + '">Author:</label></th>' +
               '<td colspan="6"><input type="text" name="author' + numNextAuthors + '" class="wide authorSearchInput" />' +
               '<input type="hidden" name="authorID' + numNextAuthors + '" class="authorSearchID" />';
        html += '<br />';
        if (numAuthors < 4) {
            html += '<span id="authoradd"> <a href="#">Add Author</a></span>';
        }
        if (numAuthors > 0) {
            html += '<span id="authorrem"> <a href="#">Remove Author</a></span>';
        }
        html += '</td></tr>';

        /*append new row to parent */
        $(this).parents('tr').after(html);

        /* remove current add/remove author links */
        $(this).parent().siblings('#authorrem').remove();
        $(this).parent().remove();

        /* update hidden field */
        $('#addauthors').val(numNextAuthors);

        /* re-initialize the autocomplete for all of the author inputs */
        authorAutoComplete();
        zebraStripes();
    });

    /* On bookedit.cfm - remove author functionality */
    $('form table').delegate("#authorrem a", "click", function(event) {
        event.preventDefault();
        var numAuthors = $('#addauthors').val(),
            numAuthors = parseInt(numAuthors, 10),
            numPrevAuthors = numAuthors - 1,
            numNextAuthors = numAuthors + 1,
            authoradd, authorRem, html;

        /* build the html for add/remove links */
        html = '';
        if (numAuthors < 6) {
            html += '<span id="authoradd"> <a href="#">Add Author</a></span>';
        }
        if (numAuthors > 2) {
            html += '<span id="authorrem"> <a href="#">Remove Author</a></span>';
        }

        /* append html to previous row */
        $(this).parents('tr').prev().children('td:first').append(html);

        /* remove current row */
        $(this).parents('tr').remove();

        /* update hidden field */
        $('#addauthors').val(numPrevAuthors);

        /* re-initialize the autocomplete for all of the author inputs */
        authorAutoComplete();
        zebraStripes();
    });

    /* on bookedit.cfm show fields for hardback, paperback, or dustjacket */
    function showBookFields() {
        if (jQuery.support.leadingWhitespace === true) {
            var cell = "table-cell";
        } else {
            var cell = "block";
        }
        /* Show hbonly if Hardback is selected */
        if ($('#hardback').is(':checked')) {
            $('.hbonly').css('display', 'inline');
            $('.hbonlyrow').show(0);
            $('.hbonlycell').css('display', cell);
            $('.pbonly').hide(0);
            $('.pbonlyrow').hide(0);
            $('.pbonly input, .pbonlyrow input').removeAttr("checked");
        }
        /* Show djonly if DustJacket is selected */
        if ($('#dustjacket').is(':checked')) {
            $('.djonly').css("display", "inline");
            $('.djonlyrow').show(0);
            $('.djonlycell').css("display", cell);
        }
        /* Show djonly if DustJacket is selected */
        if ($('#dustjacketno').is(':checked')) {
            $('.djonly').hide(0);
            $('.djonlyrow').hide(0);
            $('.djonlycell').hide(0);
            $('.djonly input, .djonlyrow input, .djonlycell input').removeAttr("checked");
        }
        /* Show pbonly if Paperback is selected */
        if ($('#paperback').is(':checked')) {
            $('.hbonly').hide(0);
            $('.hbonlyrow').hide(0);
            $('.hbonlycell').hide(0);
            $('.djonly').hide(0);
            $('.djonlyrow').hide(0);
            $('.djonlycell').hide(0);
            $('.pbonly').css("display", "inline");
            $('.pbonlyrow').show(0);
            $('.pbonlycell').css("display", cell);
            $('.djonly input, .djonlyrow input, .hbonly input, .hbonlyrow input, .djonlycell input, .hbonlycell input')
                .removeAttr("checked");
        }
        if ($('#bookloanedto').is(':checked')) {
            $('.loanonlyrow').show(0);
        } else {
            $('.loanonlyrow').hide(0);
            $('.loanonlyrow input').val('');
        }


        // For report.cfm show/hide priceclipped option
        if ($('#hardback_report').is(':checked')) {
            $('.hbonly').show(0);
            $('.pbonly').show(0);
        } else if ($('#hardback_report').is(':not(:checked)')) {
            $('.hbonly').hide(0);
            $('.pbonly').hide(0);
            $('.pbonly input, .hbonly input').removeAttr('checked');
        }


        zebraStripes();
    }

    //binds showBookFields to clicks
    $('#hardback, #paperback, #dustjacket, #dustjacketno, #hbpb, td input[name=status]').live("click", function() {
        showBookFields();
    });

    //Only display Awards if Topic == Science Fiction
    function displayAwards() {
        if ($('#topicID option:selected').text() == "Science Fiction") {
            $('#scifionlyrow').css('display', '');
        } else {
            $('#scifionlyrow').hide(0);
            $('input[name=hugo], input[name=nebula]').removeAttr('checked');
        }
    }

    $('#topicID').change(function() {
        displayAwards();
    });

    //adds classes for background colors
    function zebraStripes() {
        var $item = $('table.zebra tr:visible');
        $item.filter(':even').addClass('treven').removeClass('trodd');
        $item.filter(':odd').addClass('trodd').removeClass('treven');
        if (!$('table').is('.nolast')) {
            $item.filter(':last').removeClass('trodd treven');
        }
    }

    /* Create buttons for adding tags */
    $('#addLinkNewBook, #addTagNewBook, #addLinkEditBook, #addTagEditBook, #topicAddButton').button({
        icons: {
            primary: 'ui-icon-plus'
        }
    }).css("font-size", ".8em");

    /* On click "Add New Topic", create new topic, append to select box  */
    $('#topicrow').delegate('#topicAddButton', 'click', function(e) {
        e.preventDefault();
        var topicName = $('#topicAdd').val();
        $.ajax({
            type: "POST",
            url: 'components/topic.cfc?method=addtopic',
            data: ({ topicname: topicName }),
            dataType: 'json',
            success: function(data) {
                if (data.exists == false) {
                    $('#topicID').append('<option value="' + data.topicID + '">' + data.topicName + '</option>');
                    $('#topicID').val(data.topicID);
                    $('#topicAdd').val("");
                } else if (data.exists == true) {
                    $('#topicID').val(data.topicID);
                    $('#topicAdd').val("");
                }
            }
        });
    });

    /* On click "Create Tag", create new tag, append to select box */
    $('#tagrow').delegate('#addTagNewBook, #addTagEditBook', 'click', function(e) {
        e.preventDefault();
        var tagName = $('#addTagInput').val();
        $.ajax({
            type: "POST",
            url: 'components/tag.cfc?method=addtag',
            data: ({ tagname: tagName }),
            dataType: 'json',
            success: function(data) {
                if (data.exists == false) {
                    $('#selectTag').append('<option value="' + data.tagID + '">' + data.tagName + '</option>');
                    $('#selectTag').val(data.tagID);
                    $('#addTagInput').val("");
                } else if (data.exists == true) {
                    $('#selectTag').val(data.tagID);
                    $('#addTagInput').val("");
                }
            }
        });
    });

    /* On click "Create Tag", create new tag, append to select box */
    $('#tagrow').delegate('#addLinkEditBook', 'click', function(e) {
        e.preventDefault();
        var tagID = $('#selectTag').val(),
            bookID = $('#bookID').val();
        $.ajax({
            type: "POST",
            url: 'components/tag.cfc?method=addlinktag',
            data: ({ bookID: bookID, tagID: tagID }),
            dataType: 'json',
            success: function(data) {
                if (data.exists == false) {
                    $('#taglist').append('<li id="tag' + data.tagID + '"><a href="#">' + data.tagName + '</a></li>');
                    $('#selectTag').val("0");
                    $('#addTagInput').val("");
                } else {
                    $('#selectTag').val("0");
                    $('#addTagInput').val("");
                }
            }
        });
    });

    /* On click "Add To Book", post tag by ajax. Append new tag to list  */
    $('#tagrow').delegate('#addLinkNewBook', 'click', function(e) {
        e.preventDefault();
        if ($('#selectTag').val() != '0') {
            var tagIDList = $('#tagIDHidden').val(),
            tagID = $('#selectTag').val(),
            bookID = $('#bookID').val(),
            tagIDArray = new Array(),
            exists = false,
            tagName;

            tagIDArray = tagIDList.split(",");

            for (i = 0; i < tagIDArray.length; i++) {
                if (tagID == tagIDArray[i]) {
                    exists = true;
                }
            }

            if (exists == false) {
                tagIDArray.push(tagID);
                tagIDList = tagIDArray.toString();
                tagName = $('#selectTag option:selected').text();
                $('#tagIDHidden').val(tagIDList);
                $('#taglistnew').append('<li id="tag' + tagID + '"><a href="#">' + tagName + '</a></li>');
                $('#selectTag').val("0");
                $('#addTagInput').val("");
            }
        }

    });

    /* On click, delete tag by ajax. */
    $('#taglist').delegate('a', 'click', function(e) {
        var $thiscache = $(this).parent(),
            linkTagID = $thiscache.attr("id");

        linkTagID = linkTagID.substr(3);
        $.ajax({
            type: "POST",
            url: 'components/tag.cfc?method=deletetag',
            data: ({ linkTagID: linkTagID }),
            success: function() {
                $thiscache.hide('drop', 200, function() { $thiscache.remove() });
            }
        });
    });

    /* On click, delete tag by ajax. */
    $('#taglistnew').delegate('a', 'click', function(e) {
        var $thiscache = $(this).parent(),
            tagIDArray = new Array(),
            tagIDList = $('#tagIDHidden').val(),
            newTagIDArray = new Array();

        tagIDArray = tagIDList.split(",");

        var linkTagID = $thiscache.attr("id");
        linkTagID = linkTagID.substr(3);
        $.ajax({
            type: "POST",
            url: 'components/tag.cfc?method=deletetag',
            data: ({ linkTagID: linkTagID }),
            success: function() {
                $thiscache.hide('drop', 200, function() { $thiscache.remove() });

                //generate new list
                for (i = 0; i < tagIDArray.length; i++) {
                    if (linkTagID != tagIDArray[i]) {
                        newTagIDArray.push(tagIDArray[i]);
                    }
                }

                //Hidden field = newTagArray
                tagIDList = newTagIDArray.toString();
                $('#tagIDHidden').val(tagIDList);
            }
        });
    });

    //------Validation for year
    $('#validatePublished').focusout(function() {
        var year = $(this).val(),
            year = parseInt(year, 10),
            date = new Date(),
            errmsg;

        date = date.getFullYear();
        date++;


        if (year >= 1800 && year <= date) {
            if ($('#publishedError').length > 0) {
                $('#publishedError').remove(0);
            }
            if (!($('.ui-state-error').length > 0)) {
                $('#bookSubmit').removeAttr("disabled");
            }
        } else {
            errmsg = "Must be 1800-" + date;
            if ($('#publishedError').length > 0) {
                $('#publishedError').html(errmsg);
                $('#bookSubmit').attr("disabled", "disabled");
            } else {
                $('#validatePublished').after('  <span id="publishedError" class="ui-state-error">' + errmsg + '</span>');
                $('#bookSubmit').attr("disabled", "disabled");
            }
        }

    });

    // Cancel button to go back to book.cfm
    $('#bookCancel').click(function() {
        window.location = "book.cfm";
    });
    /*----------------------------- End Book Edit Page ---------------------- */
    /*----------------------------- Report Page ----------------------------- */

    $('#reportSubmit').click(function(e) {
        e.preventDefault();
        $('#accordion').accordion("activate", 1);
    });

    /* Accordion for report page */
    var icons = {
        header: "ui-icon-circle-arrow-e",
        headerSelected: "ui-icon-circle-arrow-s"
    },
        xhrSame;
    $('#accordion').accordion({
        collapsible: true,
        icons: icons,
        autoHeight: false,
        changestart: function(event, ui) {
            if (ui.newHeader.text() == "Report") {
                var bookType = $('#filter input[name=cover]:checked').val(),
                    reporttype = $('#filter input[name=reporttype]:checked').val(),
                    first = $('#filter input[name=first]:checked').val(),
                    award = $('#filter input[name=award]:checked').val(),
                    signed = $('#filter input[name=signed]:checked').val(),
                    unread = $('#filter input[name=unread]:checked').val(),
                    priceclipped = $('#filter input[name=priceclipped]:checked').val(),
                    topic = $('#filter select[name=selectTopic]').val(),
                    status = $('#filter input[name=status]:checked').val(),
                    author = $('#filter #authorSearchID').val();


                var selectTag;
                $('#filter select[name=selectTag] option:selected').each(function(index) {
                    if (index === 0) {
                        selectTag = $(this).val();
                    } else {
                        selectTag += "," + $(this).val();
                    }
                });

                $.ajax({
                    type: "POST",
                    url: 'reportinfo.cfm',
                    data: ({ cover: bookType, reporttype: reporttype, first: first, award: award, signed: signed,
                        unread: unread, selectTopic: topic, selectTag: selectTag, authorID: author, priceclipped: priceclipped,
                        status: status
                    }),
                    beforeSend: function() {
                        $('#report').html("");
                    },
                    success: function(data) {
                        $('#report').html(data);
                        var contentHeight = parseInt(($('#content').css("height") + 200), 10),
                            reportHeight = parseInt(($('#report').css("height")), 10);
                        if (reportHeight > contentHeight) {
                            contentHeight = reportHeight + 200;
                            $('#content').css("height", contentHeight);
                        }
                        Paginate();
                    },
                    error: function() {
                        $('#report').html("An error has occured.");
                    }
                });
            };
        }
    });
    //Clear AuthorID field if you do not want to filter the report for an author.
    $('#clearAuthor').button();
    $('#clearAuthor').live("click", function() {
        $('#authorSearchID').val("0");
        $('#authorSearch').val("");
    });
    // Pagination
    function Paginate() {
        $('#nextPage').button({
            icons: { secondary: 'ui-icon-arrowthick-1-e' }
        });

        $('#prevPage').button({
            icons: { primary: 'ui-icon-arrowthick-1-w' }
        });
    }
    // Get next/prev page by ajax.
    $('#report').delegate('#nextPage, #prevPage', "click", function(e) {
        e.preventDefault();
        var authorIDReport = $('#authorIDReport').val(),
            awardReport = $('#awardReport').val(),
            coverReport = $('#coverReport').val(),
            firstReport = $('#firstReport').val(),
            signedReport = $('#signedReport').val(),
            selectTagReport = $('#selectTagReport').val(),
            selectTopicReport = $('#selectTopicReport').val(),
            unreadReport = $('#unreadReport').val(),
            reporttypeReport = $('#reporttypeReport').val(),
            startReport = $('#startReport').val(),
            perpageReport = $('#perPageReport').val(),
            priceclippedReport = $('#priceclippedReport').val(),
            status = $('#statusReport').val();

        startReport = parseInt(startReport, 10);
        perpageReport = parseInt(perpageReport, 10);
        if ($(this).attr("name") == "nextPage") {
            startReport = startReport + perpageReport;
        }

        if ($(this).attr("name") == "prevPage") {
            startReport = startReport - perpageReport;
        }

        $.ajax({
            type: "POST",
            url: 'reportinfo.cfm',
            data: ({ authorID: authorIDReport, award: awardReport, cover: coverReport, first: firstReport,
                signed: signedReport, selectTag: selectTagReport, selectTopic: selectTopicReport,
                unread: unreadReport, reporttype: reporttypeReport, start: startReport, perpage: perpageReport,
                priceclipped: priceclippedReport, status: status
            }),
            beforeSend: function() {
                $('#report').html("");
            },
            success: function(data) {
                $('#report').html(data);
                var contentHeight = parseInt(($('#content').css("height") + 200), 10),
                        reportHeight = parseInt(($('#report').css("height")), 10);
                if (reportHeight > contentHeight) {
                    contentHeight = reportHeight + 200;
                    $('#content').css("height", contentHeight);
                }
                Paginate();
            },
            error: function() {
                $('#report').html("An error has occured.");
            }
        });
    });


    /*----------------------------- End Report Page ----------------------------- */

    $('#regSubmit').attr("disabled", "disabled");

    //if pw isn't long enough
    $('#regpassword').keyup(function() {
        var errmsg = "Password must be longer than 5 characters";

        if ($('#regpassword').val().length >= 5) {
            if ($('#regpasserror').length > 0) {
                $('#regpasserror').remove(0);
            }
        } else {
            if ($('#regpasserror').length > 0) {
                $('#regpasserror').html(errmsg);
            } else {
                $('#regpassword').after('   <span id="regpasserror" class="ui-state-error">' + errmsg + '</span>');

            }
        }
    });

    //if pw doesn't match    
    $('#regconfirm').keyup(function() {
        var errmsg = "Passwords do not match";

        if ($('#regpassword').val() == $('#regconfirm').val()) {
            if ($('#regconfirmerror').length > 0) {
                $('#regconfirmerror').remove(0);
            }
        } else {
            if ($('#regconfirmerror').length > 0) {
                $('#regconfirmerror').html(errmsg);
            } else {
                $('#regconfirm').after('   <span id="regconfirmerror" class="ui-state-error">' + errmsg + '</span>');
            }
        }
    });

    $('#regemail, #regusername, #regpassword, #regconfirm').keyup(function() {
        if ($('#regemail').val().length > 0 &&
            $('#regusername').val().length > 0 &&
            $('#regpassword').val().length > 0 &&
            $('#regconfirm').val().length > 0 &&
            !($('.ui-state-error').length > 0)) {
            $('#regSubmit').removeAttr('disabled');
        } else {
            $('#regSubmit').attr('disabled', 'disabled');
        }
    });


    //if email is invalid
    $('#regemail').keyup(function() {
        var errmsg = "Email is not valid",
            regex = new RegExp("^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$");


        if (regex.test($('#regemail').val())) {
            if ($('#regemailerror').length > 0) {
                $('#regemailerror').remove(0);
            }
        } else {
            if ($('#regemailerror').length > 0) {
                $('#regemailerror').html(errmsg);
            } else {
                $('#regemail').after('   <span id="regemailerror" class="ui-state-error">' + errmsg + '</span>');
            }
        }
    });

    authorAutoComplete();
    showBookFields();
    //zebraStripes();
    displayAwards();

});
