﻿//////////////////////////////////////////////////////////////////////////////////////
/// Literature library pages (browse, search and order). Comments will be stripped out
/// on minify, so please leave.
//////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////
/// some general set up
$.fn.emptySelect = function() {
    return this.each(function() {
        if (this.tagName == 'SELECT') this.options.length = 0;
    });
}

$.ajaxSetup({
  cache: false
});

//$.SWUtil.modalBox.bindtoAJAX = true;
//$.SWUtil.modalBox.isOn = true;
//$.SWUtil.modalBox.message = "Please wait...";
////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////
/// stuff for searching
$(document).ready(function() {
    // removes the "Keyword" when clicking on the input field
    if ($('#searchkeyword').val() == "Keyword") {
        $('#searchkeyword').overLabel();
    }

    // when an item is selected from the category dropdown, trigger ajax call to populate sub-categories
    // and fire a change event straight away to prime the dropdown on initial load
    $('#searchcategory').change(function() {
        getSubCategories($(":selected", this).val())
    }).change();

    // add click event to post a search
    $('#literaturesearchbutton').click(function() {
        $("#literaturesearchform").submit();
        return false;
    }
    );
    // wire up the enter key to the search input fields
    $('#searchcategory, #searchsubcategory, #searchkeyword').trapEnter('#literaturesearchbutton');
});

function getSubCategories(category) {
    var subCategoriesDropdown = $('#searchsubcategory');
    if (category.length == 0) {
        // if no category option is selected from category dropdown, prevent selection from subcategory dropdown
        subCategoriesDropdown.attr('disabled', true);
        subCategoriesDropdown.emptySelect();
        subCategoriesDropdown.append('<option value="0">Select sub category...</option>');
    }
    else {
        subCategoriesDropdown.emptySelect();
        subCategoriesDropdown.append('<option value="0">Loading, please wait...</option>');
        subCategoriesDropdown.attr('disabled', false);

        // suppress Ajax modal pop-up as this call is usually too quick to matter
        $.SWUtil.modalBox.suppressAJAXBox = true;

        $.get(
            "/" + $.SWUtil.serverInfo.applicationPath + 'LiteratureActions/SubCategories/' + category,
            function(data) {
                updateSubCategories(subCategoriesDropdown, data);
            }
        );

        // switch Ajax modal pop-up back on
        $.SWUtil.modalBox.suppressAJAXBox = false;
    }
}

function updateSubCategories(subCategoriesDropdown, data) {
    subCategoriesDropdown.emptySelect();

    // if a category/sub-category has been selected in a search, it will be saved in this hidden field
    // and we need to preselect it on the search results page
    var selectedSubcategory = $("#selectedSubcategory").val();
    if ((selectedSubcategory == null) || (selectedSubcategory == "0")) {
        subCategoriesDropdown.append('<option value="0">Select sub category...</option>');
    }
    $.each(
        data,
        function(index, optionData) {
        if ((selectedSubcategory != null) && (selectedSubcategory != "0") && (selectedSubcategory == optionData.Category)) {
                subCategoriesDropdown.append('<option value="' + optionData.Category + '" selected="selected">' + optionData.CategoryName + '</option>');
            }
            else {
                subCategoriesDropdown.append('<option value="' + optionData.Category + '">' + optionData.CategoryName + '</option>');
            }
        }
    );
    // once a new category has been selected, blank out the category selected on the initial search results display
    $("#selectedSubcategory").val("0"); 
}
////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////
/// Stuff for category and document lists (browse or search results)
$(function() {
    // add divider line above rows except first; see http://css-tricks.com/how-nth-child-works/
    $('#categoryLinks div:nth-child(3n+1)').addClass('first');


    // trigger order update when document item selected from list of documents
    // note that the id of the element is set to the doc ref. This is a "live" event as the
    // search page dynamically updates the document list via an ajax call that gets some new html
    $('.JQ_documentTable input:checkbox').live('click', function(e) {
        updateOrder(this.id, $(this).is(':checked'));
        return true;
    });
});

function updateOrder(EDocRefNo, isChecked) {
    // stop other checkboxes being clicked
    $('.JQ_documentTable input:checkbox').attr("disabled", true);

    // update the list of ordered documents
    //alert(EDocRefNo + ", add:" + isChecked);
    
    // suppress Ajax modal pop-up as this call is usually too quick to matter
    $.SWUtil.modalBox.suppressAJAXBox = true;
    
    $.get(
        "/" + $.SWUtil.serverInfo.applicationPath + "LiteratureActions/UpdateOrder/" + EDocRefNo + "/" + isChecked,
        function(data) {
            if (data.NoOfOrderItems == 0) {
                $('#literatureyourorderlink').text('View your order');
                $('#literatureorderbtn').text('Your order');
            }
            else {
                $('#literatureyourorderlink').text('View your order (' + data.NoOfOrderItems + ')');
                $('#literatureorderbtn').text('Your order (' + data.NoOfOrderItems + ')');
            }
            // re-enable all the checkboxes
            $('.JQ_documentTable input:checkbox').attr("disabled", false);
        });

    // switch Ajax modal pop-up back on
    $.SWUtil.modalBox.suppressAJAXBox = false;
}

function getNextSearchPage() {
    $.get(
        "/" + $.SWUtil.serverInfo.applicationPath + "Literature/SearchResultsPage/" + pagestate.currentPage,
        function(data) {
            //alert(data);
            $('#searchResultsList').html(data);
            // Update pagers
            searchPager.renderPager(pagerTotalPages, pagerTotalItems);
        });
}

////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////
/// Stuff for document order
$(document).ready(function() {

    // override click event to remove a document (the anchor id should be the doc ref)
    $(".JQ_literatureorder_remove").click(function(e) {

        // suppress Ajax modal pop-up as this call is usually too quick to matter
        $.SWUtil.modalBox.suppressAJAXBox = true;

        // update the order list
        updateOrder(this.id, false);
        $("#literatureOrderRow_" + this.id).remove();
        var tBody = $("#literatureOrderTableBody");
        if ($("tr", tBody).length == 0) {
            tBody.append('<tr><td colspan="4">No documents have been ordered.</td></tr>');
        }

        // see http: //blog.stevensanderson.com/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/
        Sys.Mvc.clearFieldValidationForDeletedElements();
        
        // switch Ajax modal pop-up back on
        $.SWUtil.modalBox.suppressAJAXBox = false;

        return false;
    });

    // add click event to submit an order form (thought about using .one, but need to retain the click
    // event if client side validation errors, so event unbound if no errors)
    $('#literaturesubmitorderbtn').bind('click', function(e) {
    if (Sys.Mvc.validateForm($('#literatureorderform')[0])) {
            $(this).unbind(e);
            $.SWUtil.modalBox.message.dialog('open');
            $("#literatureorderform").submit();
        }
        return false;
    }
    );
    // wire up the enter key to the search input fields
    $('#ordercompanyname, #orderaddressee, #OrderForm_Address_AddressHouseNumber, #OrderForm_Address_AddressLine1, #OrderForm_Address_AddressLine2, #OrderForm_Address_AddressLine3, #OrderForm_Address_AddressLine4, #OrderForm_Address_AddressLine5, #OrderForm_Address_AddressLine6, #OrderForm_Address_AddressLine7, #OrderForm_Address_AddressPostalTown, #OrderForm_Address_AddressPostcode, #orderemail').trapEnter('#literaturesubmitorderbtn');
    $('#OrderForm_Address_AddressSearchPostcode').trapEnter('#aFindAddress');
});

//function validForm(form) {   
//    var errs = Sys.Mvc.FormContext.getValidationForForm(form).validate('submit');   
//    return (!(errs && errs.length));
//}



////////////////////////////////////////////////////////////////////////////////////

