﻿
    // GLOBAL VARIABLES FOR SEARCH RESULTS
    
    var searchStore = new Ext.data.Store({
                // load using HTTP
                //proxy: new Ext.data.MemoryProxy(jsonData),
                // the return will be XML, so lets set up a reader
                reader: new Ext.data.JsonReader({
                       // records will have an "Item" tag
                       root: 'GetSearchResultsResult.SearchResults',
                       id: 'SimpleAssetId'}, 
                       [
                       {name: 'SimpleAssetId', mapping: 'SimpleAssetId'},
                       {name: 'Description', mapping: 'Description'},
                       {name: 'MyvideorightsGuid', mapping: 'MyvideorightsGuid'},
                       {name: 'Title', mapping: 'Title'},
                       {name: 'Duration', mapping: 'Duration'},
                       {name: 'FriendlyDuration', mapping: 'FriendlyDuration'},
                       {name: 'AssetRef', mapping: 'AssetRef'},
                       {name: 'Thumbnail', mapping: 'Thumbnail'}
                   ])
            });
    
        function submitenter(myfield,e)
        {
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e) keycode = e.which;
        else return true;

        if (keycode == 13)
           {
           GetSearchResults();
           return false;
           }
        else
           return true;
        }


    function makeSearchRequest(operation, params)
    {
        Ext.lib.Ajax.defaultPostHeader = 'application/json';

        var onFailure = function(r, opts) {
            
            gracefulError();
            return false;
            //Ext.MessageBox.alert('ERROR 43', 'There was an error updating your lightbox. Please try again.');
        };
           
        Ext.Ajax.request({
        url: 'Services/AnonSearchService.svc/ajaxEndpoint/' + operation,
        method: 'POST',
        params: params,
        success: function(response, options) {
            RenderSearchResults(response, options, operation);
        },
        failure: onFailure
        });        
 
    }  

    function SetUpPage(isDataRequest, searchTerms)
    {
        try
        {

            // switch off the animiation
            //var elAnimation = document.getElementById("mvrLoadMask");
                    
            if(isDataRequest)
            {
                
                var centerPanel = Ext.getCmp('center-panel');

                document.getElementById('centerPanel').innerHTML = '';
                centerPanel.setTitle("Search results for '" + searchTerms + "'");
                
                //elAnimation.style.display = 'block';

            }
            else
            {
                //elAnimation.style.display = 'none';

            }            
                
        }
        catch(e)
        {
            //alert(e);
        }    
    }
    
    

    // This function creates an asynchronous call to the service
    function GetSearchResults(){

        var elInput = Ext.get("inpSearchTerms");
        var searchTerms = elInput.getValue().trim();
                
        if(searchTerms.length > 0)
        {
            // Build the body of the JSON message
            searchTerms = Ext.util.Format.htmlEncode(searchTerms);

            var params = '{"SearchTerms": "';
            params = params + searchTerms + '"}';
            
            searchStore.fireEvent('beforeload');
            SetUpPage(true, searchTerms);
            makeSearchRequest("GetSearchResults", params);
            return false;
        }
        else
        {
            Ext.MessageBox.alert('Input Error', 'Please enter a search term.');        
        }

    }

   
 
    
    function RenderSearchResults(xmlHttp)
    {
        
        if(xmlHttp.status == 200)
        {
            SetUpPage(false, '');  
                
            var jsonString = xmlHttp.responseText;
            
            try {
	            var jsonData = Ext.util.JSON.decode(jsonString);
	            //Ext.MessageBox.alert('Success', 'Decode of stringData OK<br />jsonData.date = ' + jsonData.CurrentLightboxResult.CreatedDate);
	            // You can do anything with jsonData if you want.
            }
            catch (err) {
                gracefulError();
                return false;
	            //Ext.MessageBox.alert('ERROR', 'Could not decode Server response.');
            }
            

            
            searchStore.loadData(jsonData);
            
            var tpl = new Ext.XTemplate(
             "<p class='LargeGreen' style='text-align:center;clear:both;padding-top:10px;'>The first 10 results from your search...<p>",
                "<p class='LargeGreen' style='text-align:center'>To see unlimited results, preview our catalogue and license videos, <a id='A1' href='register/register.aspx' title='register' >register</a> or <a id='A2' href='SignIn.aspx' title='sign in' >sign in</a> now!</p>",
                "<ul id='AnonSearch' class='AssetList'>",
                    '<tpl for=".">',
                    
                        "<li class='asset'>",
                        
                            "<img class='thumbnail' src='Images/Thumbnails/{Thumbnail}' />",

                        "<h5>{Title:ellipsis(50)}&nbsp;</h5>",
                        '<p>Duration: {FriendlyDuration}&nbsp;</p>',
                        "<p><strong>REF: </strong>{AssetRef}&nbsp;</p>",
                        '</li>',
                    '</tpl>',
                "</ul>"
                
               
            );

            var dv = new Ext.DataView({
                    store: searchStore,
                    tpl: tpl,
                    autoHeight:true,
                    multiSelect: true,
                    loadingText: 'Loading Search...',
                    itemSelector:'li.asset',
                    emptyText: 'No videos to display'
                });
                
                document.getElementById('centerPanel').innerHTML = '';
                dv.render('centerPanel', 1);

        }
        else
        {
            // notify error loading lightbox.
            // alert('error');
        }
    }
    

    function gracefulError()
    {
    
        document.getElementById('centerPanel').innerHTML = "<p class='copy'>We are very sorry, but our web server could not action your request. Our technical team have been informed of the problem and will be investigating in due course.</p><p>Please continue to use the rest of myvideorights.com or contact us if your require urgent assistance.</p>";
        return false;
    }