﻿/// <reference path="jquery-1.3-vsdoc.js" />
//  jQuery page load function
//  Used to set up view page event handlers
$().ready(function() {
    dhtmlHistory.initialize();
    dhtmlHistory.addListener(historyListener);

    //  Display # of records marked from the current search
    if($("#mCount").val().length > 0)
        $("#markedCount").html($("#mCount").val());
        
    $("a[title = 'MarkRecord']").click(function() {
        individualRecord_Click(this);
        return false;
    });

    //  Advanced search client-side field validation
    $(".frmSearch").submit(FormValidation);

    //  Advanced search date fields preset styling
    $("a[sd][ed]").click(CheckDateRangeMatch);
    $("#dateStart").add("#dateEnd").keyup(CheckDateRangeMatch);
    CheckDateRangeMatch();
    
    //  Advanced search clear created dates link
    $("a#clearCreatedDates").click(function() {
        $("input#createdDateStart").val("");
        $("input#createdDateEnd").val("");
        return false;
    });
    
    //  Deny non-numeric input on date fields
    $("input#dateStart").add("input#dateEnd").add("input#createdDateStart").add("input#createdDateEnd").keypress(function(e) {
        if(!e) var e = window.event;
        if(e.keyCode) code = e.keyCode;
        else if(e.which) code = e.which;

        if(code == 8 || code == 13)  //  allow backspace/enter
            return true;
        else if((code < 48) || (code > 57))
            return false;  //  deny non-numeric input
    });
    
    HighlightSearchKeywords("div#publicationView");
});

function historyListener(newLocation, historyData) {
}

//  Handles individual result checkbox clicks
function individualRecord_Click(oElem) {
    if(oElem.id == null)
        oElem = this;

    var resultID = QueryString('id');
    var myregexp = new RegExp('(?:-)?' + resultID + '\\|');
    var mymatch = myregexp.exec($("#cm").val());

    if($(oElem).text() == "Mark this Record") {
        if(mymatch != null && mymatch.length > 0) {
            if(mymatch[0].substring(0, 1) == '-') { //  if a -id was found, remove it and add +
                $("#cm").val($("#cm").val().replace(myregexp, ''));
                $("#cm").val($("#cm").val() + resultID + '|');
                $("#mCount").val(parseInt($("#mCount").val()) + 1);
                $("#markedCount").html($("#mCount").val());
            }
        }
        else { //add to marked
            $("#cm").val($("#cm").val() + resultID + '|');
            $("#mCount").val(parseInt($("#mCount").val()) + 1);
            $("#markedCount").html($("#mCount").val());
        }
    }
    else { //we unmarked the record
        if(mymatch != null && mymatch.length > 0) { //delete from marked
            if(mymatch[0].substring(0, 1) != '-') { //  if a +id was found, remove it and add -
                $("#cm").val($("#cm").val().replace(myregexp, '-' + resultID + '|'));
                $("#mCount").val(parseInt($("#mCount").val()) - 1);
                $("#markedCount").html($("#mCount").val());
            }
        }
        else { //delete from marked
            $("#cm").val($("#cm").val() + '-' + resultID + '|');
            $("#mCount").val(parseInt($("#mCount").val()) - 1);
            $("#markedCount").html($("#mCount").val());
        }
    }

    //  Persists client marked records on result check
    $.post("/includes/session_callback.aspx", 'h=' + $("#searchHash").val() + '&cm=' + $("#cm").val());

    //  Show that we added/removed the record
    if($(oElem).text() == "Mark this Record") {
        AddClientMessage('message', 'This record has been added to your marked records collection.', 'Record Marked');
        $(oElem).text("Unmark this Record");
    }
    else {
        AddClientMessage('message', 'This record has been removed from your marked records collection.', 'Record Unmarked');
        $(oElem).text("Mark this Record");
    }
}

function FormValidation() {
    if($("#dateStart").size() == 1) { //make sure we're on the advanced search form
        var dateErrors = 0;

        $("input#dateStart").add("input#dateEnd").add("input#createdDateStart").add("input#createdDateEnd").each(function() {
            var dateLen = $(this).val().length;

            if(dateLen > 0) {
                if(dateLen != 8 && dateLen != 6 && dateLen != 4) {
                    AddClientMessage("error", "Date fields must be in YYYYMMDD format.", "Invalid date");
                    $(this).get(0).select();
                    $(this).get(0).focus();
                    dateErrors++;
                }
                else if(($(this).attr("id") == 'dateStart') && (parseInt($(this).val().substring(0, 4)) < 1850)) {
                    AddClientMessage("error", "Start date must be more recent than 1850.", "Invalid date");
                    $(this).get(0).select();
                    $(this).get(0).focus();
                    dateErrors++;
                }
            }
        });
        
        if(dateErrors > 0)
            return false;
    }
    else if($("#txtKeywords").size() == 1) { //check for the simple search field
        if($("#txtKeywords").val().length < 2) {
            AddClientMessage("error", "Please enter one or more keywords to limit your search.", "No keywords");
            $("#txtKeywords").get(0).select();
            $("#txtKeywords").get(0).focus();
            return false;
        }
    }
    
    return true;
}

//  Determines if the date fields currently match any of the link presets,
//  and changes the class to reflect that.
function CheckDateRangeMatch() {
    $("a[sd][ed]").each(function() {
        $(this).removeClass();
    });

    var oElem = $("a[sd='" + $("#dateStart").val() + "'][ed='" + $("#dateEnd").val() + "']").get(0);
    if(oElem != null)
        $(oElem).addClass("activeLink");
}