jQuery.noConflict();

jQuery(document).ready(function() {
    var HasGsaButton = function() {
        if (jQuery("#GSASubmitButton").length == 0)
            return false;
        else
            return true;
    };

    var PostSearch = function() {
        var params = '{itemID: "' + jQuery('#GSACurrentPageID').val() + '"';
        if (HasGsaButton())
            params += ', searchText: "' + jQuery("#GSASearchTextBox").val() + '"';
        else
            params += ', searchText: ""';
        
        params += '}';

        jQuery.ajax({
            type: 'POST',
            url: '/Services/Search.asmx/RelatedPages',
            data: params,
            beforeSend: function(xhr) {
                xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
                xhr.setRequestHeader('Content-length', params.length);
            },
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(msgData, status) {
                jQuery('#GSARelatedPages').html(msgData.d); 
            },
            error: function(xhr, msg, e) {
                jQuery('#GSARelatedPages').html("<p>Unable to load any related pages</p>");
            }
        });
    };

    jQuery('#GSASearchTextBox').keypress(function(e) {
        if (e.keyCode == 13) { // enter
            PostSearch();

            //e.cancelBubble is supported by IE - this will kill the bubbling process.
            if (e.cancelBubble) e.cancelBubble = true;
            if (e.returnValue) e.returnValue = false;

            //e.stopPropagation works only in Firefox.
            if (e.stopPropagation) e.stopPropagation();
            if (e.preventDefault) e.preventDefault();

	return false;
        }
    });

    if (HasGsaButton()) // wait to post on submit
        jQuery('#GSASubmitButton').click(function() {
            PostSearch();
        });
    else
        PostSearch();
});

