﻿/* Register the AtlasEndeca namespace */
Type.registerNamespace("AtlasEndeca");


/****************************************************************************************
EndecaService object	
*****************************************************************************************/
AtlasEndeca.EndecaService = function() {
    // Add the OnEndecaServiceComplete function (see below) as event handler. This function displays the
    // web service results.
    this.add_endecaServiceCompleteEvent(window.OnEndecaServiceComplete);

    // Uncomment the following line if you want to see an alert of any exceptions raised in a webservice.
    //	this.add_endecaServiceExceptionEvent(window.OnEndecaServiceException);	
    // Uncomment the following line if you want to see an alert of any exceptions raised when trying to call a webservice.
    //	this.add_endecaServiceCallExceptionEvent(window.OnEndecaServiceCallException);	
}

// Raises the event specified by 'eventName'.
AtlasEndeca.EndecaService.prototype._raiseEvent = function(eventName, eventArgs) {
    var handler = this.get_events().getHandler(eventName);
    if (handler) {
        if (!eventArgs) {
            eventArgs = Sys.EventArgs.Empty;
        }
        handler(this, eventArgs);
    }
}

// Gets all events registered with this object.
AtlasEndeca.EndecaService.prototype.get_events = function() {
    if (!this._events) {
        this._events = new Sys.EventHandlerList();
    }
    return this._events;
}

/* Adding/removing event handlers */
AtlasEndeca.EndecaService.prototype.add_endecaServiceStartEvent = function(handler) {
    this.get_events().addHandler('endecaServiceStartEvent', handler);
}

AtlasEndeca.EndecaService.prototype.remove_endecaServiceStartEvent = function(handler) {
    this.get_events().removeHandler('endecaServiceStartEvent', handler);
}

AtlasEndeca.EndecaService.prototype.add_endecaServiceCompleteEvent = function(handler) {
    this.get_events().addHandler('endecaServiceCompleteEvent', handler);
}

AtlasEndeca.EndecaService.prototype.remove_endecaServiceCompleteEvent = function(handler) {
    this.get_events().removeHandler('endecaServiceCompleteEvent', handler);
}

// Exception event which is invoked when an exception occurs inside a web service
AtlasEndeca.EndecaService.prototype.add_endecaServiceExceptionEvent = function(handler) {
    this.get_events().addHandler('endecaServiceExceptionEvent', handler);
}

AtlasEndeca.EndecaService.prototype.remove_endecaServiceExceptionEvent = function(handler) {
    this.get_events().removeHandler('endecaServiceExceptionEvent', handler);
}

// Exception event which is invoked when calling a webservice has failed
AtlasEndeca.EndecaService.prototype.add_endecaServiceCallExceptionEvent = function(handler) {
    this.get_events().addHandler('endecaServiceCallExceptionEvent', handler);
}

AtlasEndeca.EndecaService.prototype.remove_endecaServiceCallExceptionEvent = function(handler) {
    this.get_events().removeHandler('endecaServiceCallExceptionEvent', handler);
}


/* Raising events */
AtlasEndeca.EndecaService.prototype.OnEndecaServiceStart = function() {
    AtlasEndeca.EndecaService.getInstance()._raiseEvent('endecaServiceStartEvent');
}

AtlasEndeca.EndecaService.prototype.OnEndecaServiceComplete = function(result) {
    AtlasEndeca.EndecaService.getInstance()._raiseEvent('endecaServiceCompleteEvent', result);
}

AtlasEndeca.EndecaService.prototype.OnEndecaServiceException = function(result) {
    AtlasEndeca.EndecaService.getInstance()._raiseEvent('endecaServiceExceptionEvent', result);
}

AtlasEndeca.EndecaService.prototype.OnEndecaServiceCallException = function(result) {
    AtlasEndeca.EndecaService.getInstance()._raiseEvent('endecaServiceCallExceptionEvent', result);
}

/*
Implementation of a 'Singleton' pattern
*/

AtlasEndeca.EndecaService._Instance = null;
AtlasEndeca.EndecaService.getInstance = function() {
    if (AtlasEndeca.EndecaService._Instance == null) {
        AtlasEndeca.EndecaService._Instance = new AtlasEndeca.EndecaService();
    }
    return AtlasEndeca.EndecaService._Instance;
}


/*
This function executes an Endeca navigation query against the entities navigation engine.
The request is made using Atlas, through the NetMatch.Zoover.Web.Services.Endeca.EntityQueryService
webservice. When the request is completed, results are passed to the OnEndecaServiceComplete function.
Remark: the placeHolderIdList parameter is optional
*/
AtlasEndeca.EndecaService.prototype.EntityQuery = function(queryString, placeHolderIdList) {
    // variables
    var ServiceRequest;
    var ZooverPageContext;
    var lPlaceHolderIdList;

    // Call the OnRequestStart so that the page can show some message or cool effect...
    this.OnEndecaServiceStart();

    // Check if the Atlas framework has been loaded. We do this by checking if the webservice proxy is available.
    // Also check if the PlaceHolderIdList array is available. If not, the page hasn't loaded completely 
    // (the array is registered at the bottom of the page using ScriptManager.RegisterArrayDeclaration(..)).
    if ((typeof (NetMatch) == 'undefined') || (typeof (PlaceHolderIdList) == 'undefined')) {
        // Atlas has not been loaded. Attach this function to the load event and let it execute again..
        Sys.Application.add_load(function() { EntityQuery(queryString, placeHolderIdList) });
        return;
    }

    // Set up the request object
    ServiceRequest = new NetMatch.Zoover.Endeca.Web.EndecaQueryServiceRequest();
    ServiceRequest.QueryString = queryString;

    //The 'OriginalQueryString' variable is initialized by the endeca controller
    if (typeof (EndecaContext) != 'undefined' && EndecaContext != null) {
        EndecaContext.CurrentQueryString = queryString;
    }

    // If the place holder ids list is not given we use the one registered by the place holder controls	
    if (typeof placeHolderIdList == 'undefined') {
        // The PlaceHolderIdList variable is registered by the placeholder controls
        lPlaceHolderIdList = PlaceHolderIdList;
    }
    else {
        lPlaceHolderIdList = placeHolderIdList;
    }
    ServiceRequest.PlaceHolderIdList = lPlaceHolderIdList;

    try {
        // The GetPageContext() function is registered by the EndecaQueryServiceController
        ZooverPageContext = GetPageContext();

        // Call the webservice asynchronously and pass the request and the event handlers
        // Query:function(request,pageContext,succeededCallback, failedCallback, userContext) 
        NetMatch.Zoover.Web.Services.Endeca.EndecaQueryService.Query(ServiceRequest, ZooverPageContext,
			this.OnEndecaServiceComplete, this.OnEndecaServiceException, null);
    }
    catch (e) {
        // Most likely the webservice is not available
        this.OnEndecaServiceCallException(e);
    }
    return false;
}

/// Sends a request to the entity service with the original query string so that all the filtering/sorting is removed
AtlasEndeca.EndecaService.prototype.ResetEntityQuery = function() {
    ///The 'OriginalQueryString' variable is initialized by the endeca controller
    if (typeof (EndecaContext) != 'undefined' && EndecaContext != null) {
        AtlasEndeca.EndecaService.getInstance().EntityQuery(EndecaContext.OriginalQueryString);
    }
}

/*
This function executes an Endeca navigation query against the testimonials navigation engine.
The request is made using Atlas, through the NetMatch.Zoover.Web.Services.Endeca.TestimonialQueryService
webservice. When the request is completed, results are passed to the OnEndecaServiceComplete function.
*/
AtlasEndeca.EndecaService.prototype.TestimonialQuery = function(queryString) {
    // variables
    var ServiceRequest;
    var ZooverPageContext;

    // Call the OnRequestStart so that the page can show some message or cool effect...
    this.OnEndecaServiceStart();

    // Check if the Atlas framework has been loaded. We do this by checking if the webservice proxy is available.
    // Also check if the PlaceHolderIdList array is available. If not, the page hasn't loaded completely 
    // (the array is registered at the bottom of the page using ScriptManager.RegisterArrayDeclaration(..)).
    if ((typeof (NetMatch) == 'undefined') || (typeof (PlaceHolderIdList) == 'undefined')) {
        // Atlas has not been loaded. Attach this function to the load event and let it execute again..
        Sys.Application.add_load(function() { TestimonialQuery(queryString) });
        return;
    }

    // Set up the request object
    ServiceRequest = new NetMatch.Zoover.Endeca.Web.EndecaQueryServiceRequest();
    ServiceRequest.QueryString = queryString;

    ///The 'OriginalQueryString' variable is initialized by the endeca controller
    if (typeof (EndecaContext) != 'undefined' && EndecaContext != null) {
        EndecaContext.CurrentQueryString = queryString;
    }

    // The PlaceHolderIdList variable is registered by the placeholder controls
    ServiceRequest.PlaceHolderIdList = PlaceHolderIdList;

    try {
        // The GetPageContext() function is registered by the EndecaQueryServiceController
        ZooverPageContext = GetPageContext();

        // Call the webservice asynchronously and pass the request and the event handlers		
        NetMatch.Zoover.Web.Services.Endeca.TestimonialQueryService.Query(ServiceRequest, ZooverPageContext,
			this.OnEndecaServiceComplete, this.OnEndecaServiceException, null);
    }
    catch (e) {
        // Most likely the webservice is not available
        this.OnEndecaServiceCallException(e);
    }
}

/// Sends a request to the testimonial service with the original query string so that all the filtering/sorting is removed
AtlasEndeca.EndecaService.prototype.ResetTestimonialQuery = function() {
    ///The 'OriginalQueryString' variable is initialized by the endeca controller
    if (typeof (EndecaContext) != 'undefined' && EndecaContext != null) {
        EndecaService.getInstance().TestimonialQuery(EndecaContext.OriginalQueryString);
    }
}


// Register the AtlasEndeca.EndecaService class
AtlasEndeca.EndecaService.registerClass('AtlasEndeca.EndecaService', null, Sys.IDisposable);

/****************************************************************************************
END - EndecaService object - END
*****************************************************************************************/

/****************************************************************************************
ResponseType object
*****************************************************************************************/

function ReponseType() { }
ReponseType.ATLAS_ENDECA = 'AtlasEndeca';
ReponseType.GOOGLE_MAP = 'GoogleMap';

/****************************************************************************************
END - ResponseType object - END
*****************************************************************************************/



/*
This function executes an Endeca navigation query against the entities navigation engine.
The request is made using Atlas, through the NetMatch.Zoover.Web.Services.Endeca.EntityQueryService
webservice. When the request is completed, results are passed to the OnEndecaServiceComplete function.
*/
function EntityQuery(queryString) {
    AtlasEndeca.EndecaService.getInstance().EntityQuery(queryString);
}

function ResetEntityQuery() {
    AtlasEndeca.EndecaService.getInstance().ResetEntityQuery();
}

/*
This function executes an Endeca navigation query against the testimonials navigation engine.
The request is made using Atlas, through the NetMatch.Zoover.Web.Services.Endeca.TestimonialQueryService
webservice. When the request is completed, results are passed to the OnEndecaServiceComplete function.
*/
function TestimonialQuery(queryString) {
    AtlasEndeca.EndecaService.getInstance().TestimonialQuery(queryString);
}

function ResetTestimonialQuery() {
    AtlasEndeca.EndecaService.getInstance().ResetTestimonialQuery();
}

/*
This function is called when a request to the webservice completes succesfully.
The result will contain an array of EndecaQueryServiceResponseItem objects.
Each object contains the new inner html for a particular EndecaQueryResultsPlaceHolder 
control on the page.
*/
function OnEndecaServiceComplete(sender, result) {
    var lCurrentPlaceHolder;
    var lCurrentItem;

    /* Iterate over the result items and set the inner html of each related placeholder */
    for (i = 0; i < result.Items.length; i++) {
        // Each item contains an EndecaQueryServiceResponseItem object
        lCurrentItem = result.Items[i];

        if (lCurrentItem.ResponseType == ReponseType.ATLAS_ENDECA) {
            lCurrentPlaceHolder = document.getElementById(lCurrentItem.PlaceHolderId);
            if (lCurrentPlaceHolder != null) {
                lCurrentPlaceHolder.innerHTML = lCurrentItem.InnerHtml;
                // evaluate any script that was inserted into the place holder
                for (var j = 0, e = lCurrentPlaceHolder.getElementsByTagName("script"); j < e.length; j++) {
                    eval(e[j].innerHTML);
                }
            }
            else {
                alert('Could not find an EndecaQueryResultsPlaceHolder with placeholder id \"' +
					lCurrentItem.PlaceHolderId + '\".');
            }
        }
    }

    // Call the OnAfterEndecaServiceComplete so that the page can do any additional processing required
    if (window.OnAfterEndecaServiceComplete)
        OnAfterEndecaServiceComplete();
}

function OnEndecaServiceCallException(sender, exception) {
    alert('Calling webservice failed: ' + exception.message);
}

function OnEndecaServiceException(sender, exception) {
    alert('The webservice returned an exception: ' + exception.get_message());
}

/*
Gets the query string of the last query executed against the Endeca navigation engine.
*/
function GetCurrentENEQueryString() {
    if (typeof (EndecaContext) != 'undefined' && EndecaContext != null) {
        return EndecaContext.CurrentQueryString;
    }
    else return null;
}

/*
Gets the query string of the query which was executed agains the Endeca Navigation Engine when the
page was originally loaded.
*/
function GetOriginalENEQueryString() {
    if (typeof (EndecaContext) != 'undefined' && EndecaContext != null) {
        return EndecaContext.OriginalQueryString;
    }
    else return null;
}

/*
Sets the sorting in the provided query string to the specified sort key.
*/
function SetSortKey(queryString, sortKey, sortAscending) {
    // variables
    var NewQueryString;
    var SortOrderValue;

    // Determine the value of the sort order parameter
    SortOrderValue = sortAscending ? "0" : "1";

    // Does the query string contain a sort key?
    if (queryString.indexOf("&Ns=") > 0) {
        // Replace the current sort key with the specified one
        NewQueryString = queryString.replace(/Ns=[^&]*/, "Ns=" + sortKey);
    }
    else {
        // Add the sort key to the query
        NewQueryString = queryString + "&Ns=" + sortKey;
    }
    // Does the query string contain a sort order?
    if (queryString.indexOf("&Nso=") > 0) {
        // Replace the current sort order with the specified one
        NewQueryString = NewQueryString.replace(/Nso=[^&]*/, "Nso=" + SortOrderValue);
    }
    else {
        // Add the sort order to the query
        NewQueryString = NewQueryString + "&Nso=" + SortOrderValue;
    }

    return NewQueryString;
}