﻿/*
*  The SearchControl manages searchers and draws a UI for them.  However,
*  searchers can be used by themselves without the SearchControl.  This is
*  called using a "Raw Searcher".  When doing this, you must handle and draw
*  the search results manually.
*/

// ensure that the core google object has been loaded
google.load('search', '1');

/// <summary>executes and displays a google search</summary>
function googleSearch(userSearchType, query) {

    // private members
    var _googleSearchObject;
    var _pagingRequestComplete = false;
        
    // convention to allow private to access public
    var that = this;
   
    // public members
    this.userSearchType = userSearchType; // e.g. Web, News, Blogs, Images, Videos etc.
    this.query = query; // the actual query
    this.geoFilter = 'all'; // if not 'all', translates into an inurl: filter
    this.langFilter = '';
    this.fileTypeFilter = '';
    this.occFilter = '';
    this.siteFilter = ''; // translates into a site: filter
    this.recentFilter = ''; // filter by freshenss
    this.currentPage = 0;
    this.allowPaging = false;
    this.pageSize = 8;
    this.currentPage = 0;
    this.openResultsInNewWindow = true;
    this.searchSafety = google.search.Search.SAFESEARCH_STRICT;
    this.searchResultContainer = document.getElementById('newsTicker');
    //this.resultCountContainer = document.getElementById('newsTicker');
    this.hasResults = false;

    // public functions
    this.getGoogleSearchType = function() {
        var gSearchType = "WebSearch";
        if (this.userSearchType == 'Images') {
            gSearchType = "ImageSearch";
        } else if (this.userSearchType == 'Blogs') {
            gSearchType = 'BlogSearch';
        } else if (this.userSearchType == 'News') {
            gSearchType = 'NewsSearch';
        } else if (this.userSearchType == 'Video') {
            gSearchType = 'VideoSearch';
        }
        return gSearchType;
    }
    this.getGoogleSearchObject = function() {
        if (_googleSearchObject == null) {
            _googleSearchObject = eval('new google.search.' + this.getGoogleSearchType() + '();');
        }
        return _googleSearchObject;
    }
    /// executes the google search
    this.executeSearch = function() {

        var gSearchType = that.getGoogleSearchType();
        var objSearch = that.getGoogleSearchObject();
        var userSearchType = that.userSearchType;

        if (gSearchType == "WebSearch") {

            // add cse filter
            if (that.cseFilter != null && that.cseFilter != '') {
                objSearch.setSiteRestriction(that.cseFilter);
            }

            // add site filter
            if (that.siteFilter != null && that.siteFilter != '' && that.query.lastIndexOf('site:') < 0) {
                that.query = that.query + " site:" + that.siteFilter;
            }

            // add language filter
            if (that.langFilter != null && that.langFilter != '') {
                var extendedArgs = google.search.Search.RESTRICT_EXTENDED_ARGS;
                objSearch.setRestriction(extendedArgs, { lr: that.langFilter })
            }

            // add filetype filter
            if (that.fileTypeFilter != '' && that.query.lastIndexOf('filetype:') < 0) {
                that.query = that.query + " filetype:" + that.fileTypeFilter;
            }

            // add occurence filter
            if (that.occFilter != null && that.occFilter != '' && that.query.lastIndexOf(that.occFilter + ':') < 0) {
                that.query = that.occFilter + ": " + that.query;
            }

            if (userSearchType == "Presentations") {

                objSearch.setQueryAddition("filetype:ppt OR filetype:pptx OR filetype:key");
            }
            else if (userSearchType == "Documents") {
                objSearch.setQueryAddition("filetype:doc OR filetype:docx OR filetype:pdf OR filetype:txt OR filetype:rtf OR filetype:xls");
            }

        }

        // add geo filter
        if (that.geoFilter != null && that.geoFilter != ""
                && that.geoFilter != "all" && that.query.lastIndexOf('inurl:') < 0) {
            that.query = that.query + " inurl:." + that.geoFilter;
        }
        

        // preferences
        if (gSearchType != "BlogSearch" && gSearchType != "VideoSearch") {
            if (that.searchSafety != null) {
                if (that.searchSafety == "SAFESEARCH_STRICT")
                    objSearch.setRestriction(google.search.Search.RESTRICT_SAFESEARCH, google.search.Search.SAFESEARCH_STRICT)
                else if (that.searchSafety == "SAFESEARCH_MODERATE")
                    objSearch.setRestriction(google.search.Search.RESTRICT_SAFESEARCH, google.search.Search.SAFESEARCH_MODERATE)
            }
        }

        // set page size
        if (that.pageSize != null && that.pageSize == 4) {
            objSearch.setResultSetSize(google.search.Search.SMALL_RESULTSET)
        } else {
            that.pageSize = 8;
            objSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);
        }

        // set callback
        objSearch.setSearchCompleteCallback(this, searchComplete, null);

        // execute search
        objSearch.execute(that.query);
    }

    // private functions
    function addCommas(nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }

    function addPaginationLinks() {
        // The cursor object has all things to do with pagination
        var objSearch = that.getGoogleSearchObject();
        var cursor = objSearch.cursor;
        var curPage = cursor.currentPageIndex; // check what page the app is on
        var paginationContainer = document.createElement('p');


        for (var i = 0; i < cursor.pages.length; i++) {
            var page = cursor.pages[i];

            if (curPage == i) { // if we are on the curPage, then don't make a link
                paginationContainer.appendChild(buildPagingLink('span', i, page.label, false));

                var startPoint = (parseFloat(cursor.pages[i].start) + 1);
                var endPoint = ((that.pageSize * cursor.pages[i].label) > cursor.estimatedResultCount) ? cursor.estimatedResultCount : (that.pageSize * cursor.pages[i].label);
            } else {
                paginationContainer.appendChild(buildPagingLink('a', i, page.label));
            }
        }
    }

    // calls the gotoPage() method on the searcher.
    function goToPage(pageIndex) {
        var objSearch = that.getGoogleSearchObject();
        objSearch.gotoPage(pageIndex);
    }

    function buildPagingLink(element, id, label, isLink) {
        // If we aren't on the current page, then we want a link to this page.
        var link = document.createElement(element);
        link.innerHTML = label;
        if (!isLink) {
            var newQuery = $.query.REMOVE("page");
            link.href = newQuery + "&page=" + (id + 1);
        }
        return link;
    }
    
    function searchComplete() {
        // set page title
        //that.searchResultsPageTitle.innerHTML = that.userSearchType + ' Search for: ' + that.query
        // remove content areas
        that.searchResultContainer.innerHTML = '';
        //that.resultCountContainer.innerHTML = '';

        var gSearchType = that.getGoogleSearchType();
        var objSearch = that.getGoogleSearchObject();

        if (objSearch.results && objSearch.results.length > 0) {
            // Check that we got results

            // Loop through our results, printing them to the page.
            var results = objSearch.results;

            for (var i = 0; i < results.length; i++) {
                // For each result write it's title and image to the screen
                var result = results[i];
               // var imgContainer = document.createElement('div');

                var description = document.createElement('li');
                $(description).addClass("g-result-item");

                // We use titleNoFormatting so that no HTML tags are left in the title
                var linkTarget = '';
                if (that.openResultsInNewWindow == true) {
                    linkTarget = 'target="_blank"';
                }
                var descriptionString;
                var linkUrl = result.unescapedUrl;
                if (gSearchType == "BlogSearch") {
                    linkUrl = result.postUrl;
                }
                if (gSearchType == "VideoSearch") {
                    linkUrl = result.url;
                }                
                descriptionString = '<a href="' + linkUrl + '" ' + linkTarget + '>' + result.title +' [more]' + '</a>';     
                description.innerHTML += descriptionString;

                //imgContainer.appendChild(description);
                /*
                // attach the node into my dom
                var node = result.html.cloneNode(true);
                imgContainer.appendChild(node);
                */

                // Put our title + image in the content
                that.searchResultContainer.appendChild(description);
            }
			
			hi();
            
			if (that.allowPaging == true) {
                // Now add the paging links so the user can see more results.
                addPaginationLinks();
            }
        } else {        
            var imgContainer = document.createElement('div');
            var title = document.createElement('div');
            title.innerHTML = "No results.";
            that.searchResultContainer.appendChild(title);

            // hack!
            var videoResultsContainer = document.getElementById("googleYellowVideoSearchResults");
            if (videoResultsContainer)
                videoResultsContainer.innerHTML = "";
            
        }

        // apply paging if necessary
        if (!isNaN(that.currentPage) && that.currentPage > 0 && !_pagingRequestComplete) {
            goToPage(that.currentPage - 1);
            _pagingRequestComplete = true;
        }

    }
}

function hi() {
	$('#newsTicker').liScroll({ travelocity: 0.06 });
}
