﻿function Search() {
    var SearchObj = {};
    
    var rootURL = "";
    var headID = 0;
    var docTitle = "";
    var yAppId = "ipw5f5zV34ETt7hO4m4eMiwd7ZX50UDmokAIMVervGOJ7qoamdHg4s_EisRTIrOnSQ--";
    var searchRetries = 0;
    var rootUrl = "www.agrisurf.com";
    
    //************** Start Callback Functions **************************
    //**
    function AddJSONScriptTag(codeRequest) {

        var fullUrl = rootURL + codeRequest;
        try {
             // Create a new script object
             aObj = new JSONscriptRequest(fullUrl);
             // Build the script tag
             aObj.buildScriptTag();
             // Execute (add) the script tag
             aObj.addScriptTag();               
        }
        catch (err) {
            alert(err);
        }
    }
    function JSONscriptRequest(fullUrl) {
        // REST request path
        this.fullUrl = fullUrl; 
        // Get the DOM location to put the script tag
        this.headLoc = document.getElementsByTagName("head").item(0);
        // Generate a unique script tag id
        this.scriptId = 'fpHead_Id' + headID;
        
        var scriptTag = returnObjById('fpHead_Id' + headID);
        if(scriptTag){
          this.headLoc.removeChild(scriptTag);
        }
        headID++;
    }
    // buildScriptTag method
    JSONscriptRequest.prototype.buildScriptTag = function () {
        // Create the script tag
        this.scriptObj = document.createElement("script");

        // Add script object attributes
        this.scriptObj.setAttribute("type", "text/javascript");
        this.scriptObj.setAttribute("src", this.fullUrl);
        this.scriptObj.setAttribute("id", this.scriptId);
    };
    // removeScriptTag method
    JSONscriptRequest.prototype.removeScriptTag = function () {
        // Destroy the script tag
        this.headLoc.removeChild(this.scriptObj);  
    };
    // addScriptTag method
    JSONscriptRequest.prototype.addScriptTag = function () {
           
        //alert("this.scriptObj");
        // Create the script tag
        this.headLoc.appendChild(this.scriptObj);
    };
    //**
    //************** End Callback Functions **************************
    
    
    //************** Start Yahoo Functions **************************
    //**
    SearchObj.ExtractTerms = function(q,txt) {        
        //rsc.actionsStatus("Extracting Terms",true);
        var codeRequest = "http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction?appid=" + yAppId + "&query=" + q + "&output=json&callback=Search.displaySimTerms&context=" + txt ;
        if (codeRequest.length > 2000) {
            codeRequest = codeRequest.substring(0,1999);
        }
        AddJSONScriptTag(codeRequest);
    };
    SearchObj.displaySimTerms = function(jsonData) {
        var t = eval(jsonData); 
        var r = t.ResultSet.Result;
        
        if (r && r.length > 0) {
            html = YWSAttrib() + "<b>More possibilities: </b>";
            for (i = 0; i < r.length; i++) {
                html+= "<a class=\"srchSuggest\" href=\"?q=" + escape(r[i]) + "\">" + r[i] + "</a> ";
                if (i>=9) { break; };
            }
            var srchsuggest = returnObjById("srchsuggest");
            if (srchsuggest) {
                srchsuggest.style.border = "solid 1px Green";
                //srchsuggest.style.margin = "0 50px 10px 50px";
                srchsuggest.style.padding = "5px 5px";
                srchsuggest.innerHTML = html;
            }
        }
    };    
    SearchObj.RelatedQ = function(q) {        
        var codeRequest = "http://search.yahooapis.com/WebSearchService/V1/relatedSuggestion?appid=" + yAppId + "&query=" + q + "&output=json&callback=Search.displayRelTerms";
        if (codeRequest.length > 2000) {
            codeRequest = codeRequest.substring(0,1999);
        }
        AddJSONScriptTag(codeRequest);
    };
    SearchObj.displayRelTerms = function(jsonData) {
        var t = eval(jsonData); 
        var r = t.ResultSet.Result;
        
        if (r && r.length > 0) {
            html = YWSAttrib() + "<b>Try also: </b>";
            for (i = 0; i < r.length; i++) {
                html+= "<a class=\"srchSuggest\" href=\"?q=" + escape(r[i]) + "\">" + r[i] + "</a> ";
                if (i>=9) { break; };
            }
            var srchsuggest = returnObjById("querysuggest");
            if (srchsuggest) {
                srchsuggest.style.border = "solid 1px Green";
                //srchsuggest.style.margin = "0 50px 10px 50px";
                srchsuggest.style.padding = "5px 5px";
                srchsuggest.innerHTML = html;
            }
        }
    };
    
    SearchObj.SpellCheckQ = function(q) {
        
        var codeRequest = "http://search.yahooapis.com/WebSearchService/V1/spellingSuggestion?appid=" + yAppId + "&query=" + q + "&output=json&callback=Search.displaySpell";
        if (codeRequest.length > 2000) {
            codeRequest = codeRequest.substring(0,1999);
        }
        AddJSONScriptTag(codeRequest);    
    };
    SearchObj.displaySpell = function(jsonData) {
        var t = eval(jsonData); 
        var r = t.ResultSet.Result;
        
        if (r && r.length > 0) {
            html = YWSAttrib() + "<b>Did you mean:<a class=\"srchSuggest\" href=\"?q=" + escape(r) + "\">" + r + "</a>?</b>";
            var srchsuggest = returnObjById("queryspell");
            if (srchsuggest) {
                srchsuggest.style.border = "solid 1px Green";
                //srchsuggest.style.margin = "0 50px 10px 50px";
                srchsuggest.style.padding = "5px 5px";
                srchsuggest.innerHTML = html;
            }
        }
    };
    function YWSAttrib() {
        return "<a style=\"float:right\" href=\"http://developer.yahoo.com/about\"><img src=\"http://us.dev1.yimg.com/us.yimg.com/i/us/nt/bdg/websrv_120_1.gif\" border=\"0\"></a>";
    }
    //**
    //************** End Yahoo Functions **************************
    
    SearchObj.search = function() {
        var searchBox = returnObjById("searchBox");
        var searchRestrict = returnObjById("chkSearchRestrict");
        var loc = "search.aspx?q=" +  escape(searchBox.value);
        if (searchRestrict && searchRestrict.checked) {
            var catId = returnObjById("catId");
            if (catId) {loc += "&catId=" + catId.innerHTML ; }
            var catName = returnObjById("catName");
            if (catName) {loc += "&catName=" + catName.innerHTML ; }
            var tagName = returnObjById("tagName");
            if (tagName) {loc += "&tagName=" + tagName.innerHTML ; }
                 
        }
        window.location.href = loc;    
    };
    SearchObj.keypress = function(e) {
        var keycode;
        if (window.event) {
            keycode = window.event.keyCode;
        }
        else if (e) {
            keycode = e.which;
        }
        if (keycode === 13) {
            Search.search();
        }
    };
    //faviconLoadError
    SearchObj.faviconLoadError = function(obj){
        obj.onload=null;
        obj.src='img/pixel.gif';
    };
    SearchObj.faviconLoad = function(obj,src){
        obj.onload=null;
        obj.src="http://" + src + "/favicon.ico";
    };
    
    //************** Start Search Control Functions **************************
    //**
    SearchObj.RawSearchControl = function() {
        
        docTitle = document.title;
        this.resultsSection = returnObjById("defaultSearchTarget");
        this.srchResultCount = returnObjById("srchResultCount");
         
        this.resultsStore = [];
        this.actionsArray = []; //a state tracking array that gets added to as actions occur and removed from as they finish
        this.resultStoreObj = {};
        
        // Search for URL Only
        this.searcher = new GwebSearch();                                                                                    
        this.searcher.setNoHtmlGeneration();
        this.searcher.setSearchCompleteCallback(this, Search.RawSearchControl.prototype.searchComplete, [this.searcher]);
        this.searcher.setResultSetSize(GSearch.LARGE_RESULTSET);        
        
        var crefUrl = "http://" + rootUrl + "/tagGA.aspx?t=-1";
        var searchRestrict = returnObjById("chkSearchRestrict");
        if (searchRestrict && searchRestrict.checked === true) {
            var res;
            var catId = getURLparam("catId");
            var catName = getURLparam("catName");
            if (catId  && catName) {res = "http://" + rootUrl + "/catRSS.aspx?i=" +  catId;
                    crefUrl = "http://" + rootUrl + "/catGA.aspx?i=" +  catId;
            } else {
                var tagName = getURLparam("tagName");
                if (tagName) {
                    crefUrl = "http://" + rootUrl + "/tagGA.aspx?t=" + escape(tagName.replace(/ /g,"+"));
                }
            }            
        }
        this.searcher.setSiteRestriction({crefUrl : crefUrl});
        
        GSearch.getBranding(document.getElementById("GBrand"));
        
        //get any search term present
        //check to see if a certain page of the thread has been requested
        this.q = getURLparam("q");
        
        this.executeSearch(this.q);      
    };
    
    SearchObj.RawSearchControl.prototype.executeSearch = function(query){
        
        this.q = query.replace(/^\s+|\s+$/g, '') ;
        if (this.q.length > 0) { 
        
            // always clear old from the page
            this.resultsStore = [];
            this.actionsArray = [];
            
            //main search
            returnObjById("searchBox").value = this.q;
            this.actionsStatus("Searching Web",true);
            this.searcher.execute(this.q);            
            
            Search.RelatedQ(escape(this.q));
            Search.SpellCheckQ(escape(this.q));    
        }            
    };
    SearchObj.RawSearchControl.prototype.searchComplete = function(searcher) {

        if (searcher.cursor) {
            this.resultsStore[searcher.cursor.currentPageIndex] = cloneObject(searcher);
            if (searcher.cursor.currentPageIndex === searcher.cursor.pages.length-1) {
                this.processAllResults(this.resultsStore);
            } else {
                this.gotoPage(searcher, searcher.cursor.currentPageIndex+1);
            }
        } else {
            if (this.resultsStore.length === 0 && searchRetries < 3) {
                searchRetries++;
                this.executeSearch(this.q); 
                return;
            }
            this.processAllResults(this.resultsStore);
        }
    };    
    SearchObj.RawSearchControl.prototype.processAllResults = function(resultsStore) {

        var html = "";
        var resultObjectArray = [];
        var urlArray = [];
        
        this.actionsStatus("Processing Results",true);
        this.actionsStatus("Searching Web",false);
        
        if (resultsStore.length > 0) {
            var alltxt = "";
            for (var i=0;i<resultsStore.length;i++)
            {            
                if (i === resultsStore.length-1) {
//                    this.srchResultCount.innerHTML = "Your search returned " + resultsStore[i].cursor.estimatedResultCount + " results";
                    this.srchResultCount.appendChild(createDiv("Your search returned approx. " + resultsStore[i].cursor.estimatedResultCount + " results", "searchCount"));
                    if (resultsStore[i].cursor.estimatedResultCount > 32) {
                        this.srchResultCount.appendChild(createDiv("You should add keywords to narrow the result.", "searchCountSub"));
                    }
                }
                //get array of unique URLs returned by this search
                for (var j=0; j<resultsStore[i].results.length; j++) {  
                    var result = resultsStore[i].results[j];
                    resultObjectArray.push(result);
                    var siteUrl = cleanedSiteURL(result.visibleUrl);
                    if (!ArrayContains(urlArray,siteUrl)) {
                        var k = urlArray.push(siteUrl);
                    }
                }
            }     
            alltxt = SiteListingTXT(resultObjectArray, true);
            Search.ExtractTerms(escape(this.q),escape(alltxt));
            
            html += this.showResults(resultObjectArray);
            
        } else {
//            this.srchResultCount.innerHTML = "Your search returned 0 results";
            this.srchResultCount.appendChild(createDiv("Your search did not return any results.", "header"));
            this.srchResultCount.appendChild(createDiv("Please try some other keywords", "subheader"));
        }
        
        
//        if (resultsStore.length === 0)) {
//            this.srchResultCount.appendChild(createDiv("Your search did not return any results.", "header"));
//            this.srchResultCount.appendChild(createDiv("Please try some other keywords", "subheader"));
//        }
//        else {        
//            this.srchResultCount.appendChild(createDiv("Your search returned approx. " + resultsStore[resultsStore.length-1].cursor.estimatedResultCount + " results", "header"));
//            if (resultsStore[resultsStore.length-1].cursor.estimatedResultCount > 32) {
//                this.srchResultCount.appendChild(createDiv("You should add keywords to narrow the result.", "subheader"));
//            }
//        }
        
        removeChildren(this.resultsSection);
        this.resultsSection.appendChild(createDiv(html));
        
        this.actionsStatus("Processing Results",false);
//        if (urlArray.length > 0) {
//            Search.CheckFoundLinks(urlArray);
//        }
    };
    SearchObj.RawSearchControl.prototype.showResults = function(resultObjectArray) {
        //removeChildren(this.resultsSection);
        
        var html = "<table>";
        var col;
        
        for (var i=0;i<resultObjectArray.length;i++) {
            var resultObject = resultObjectArray[i];
            col = "white";
            if (resultObject.unescapedUrl.replace(/http:\/\//i,"").split("/")[0] + "/" === resultObject.unescapedUrl.replace(/http:\/\//i,"")) {
                col = "LightYellow";
            }
            html += "<tr id=\"result_" + i + "\" name=\"result_" + cleanedSiteURL(resultObject.visibleUrl) + "\">";
            html += "<td style=\"width:20px;vertical-align:top;\">" + (i + 1) + "</td>";
            html += "<td style=\"width:20px;vertical-align:top;\"><img width=\"16\" height=\"16\" onload=\"Search.faviconLoad(this,'" + cleanedSiteURL(resultObject.visibleUrl) + "');\" onerror=\"Search.faviconLoadError(this);\" src=\"img/icon_busy.gif\"'/></td><td>";
            
            
            
            html += "<div name=\"result_HideShow\" style=\"background-color:" + col + "\">";
            html += "<div style=\"float:right;cursor:pointer;\" title=\"Hide this result\" onclick=\"Search.ClearResult(" + i + ")\"><img src=\"img/close_button.gif\"></div>";
            html += "<a href=\"" + resultObject.unescapedUrl + "\">" + resultObject.title + "</a>"; 
            //html += UrlControls(id,i,cleanedSiteURL(resultObject.visibleUrl));
            if (resultObject.content.length > 0) {
                html += "<br/><span>" + resultObject.content + "</span>";
            }
            html += "<br/>";
            html += "<span title=\"" + resultObject.unescapedUrl + "\" style=\"color:green;\">" + shortenString(resultObject.unescapedUrl.replace(/http:\/\//i,""),50) + "</span>";
            html += "<span class=\"xtra\">";
            html += " - <a href=\"?q=related:" + resultObject.unescapedUrl.replace(/http:\/\//i,"") + "\">Similar pages</a>";
            html += " - <a href=\"?q=link:" + resultObject.unescapedUrl.replace(/http:\/\//i,"") + "\">Pages that link</a>";
            if (this.q.toLowerCase().indexOf(" site:")===-1) {
                html += " - <a href=\"?q=" + this.q + " site:" + resultObject.visibleUrl.replace(/www./i,"") + "\">More from this site</a>";
            }
            if (this.q.toLowerCase().indexOf(" site:" + resultObject.visibleUrl.replace(/www./i,""))===-1) {
                html += " - <a href=\"?q=" + this.q + " -site:" + resultObject.visibleUrl.replace(/www./i,"") + "\">Ignore this site</a>";
            }
            html += "</span>";
            html += "</div>";    
            html += "</td></tr>";            
        }
        html += "</table>"; 
        return html;
        
    };
    SearchObj.RawSearchControl.prototype.gotoPage = function(searcher, page) {
      searcher.gotoPage(page);
    };
    SearchObj.RawSearchControl.prototype.actionsStatus = function(action, status) {
        if (status) {
            document.title = docTitle + " - " + action;
            //this.searchStatus.innerHTML = document.title;
            var cnt = this.actionsArray.push(action);
        } else {
            var newArr = this.actionsArray.splice(this.actionsArray.indexOf(action),1);
            if (this.actionsArray.length == 0) {
                document.title = docTitle + " - Finished";
                //SNAP_COM.shot.Rescan();
            }
        }
    };
    SearchObj.ClearResult = function(i) {
        var killEl = returnObjById("result_" + i );
        killEl.parentNode.removeChild(killEl);        
    };
    //**
    //************** End Search Control Functions **************************
    
    
    //************** Start Helper Functions **************************
    //**
    function returnObjById( id ) {
        var returnVar;
        if (document.getElementById) {
            returnVar = document.getElementById(id); }
        else if (document.all) {
            returnVar = document.all[id]; }
        else if (document.layers) {
            returnVar = document.layers[id]; }
        return returnVar;
    }
    function removeChildren(parent) {
      while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
      }
    }
    function createDiv(opt_text, opt_className, opt_id) {
      var el = document.createElement("DIV");
      if (opt_text) {
        el.innerHTML = opt_text;
      }
      if (opt_className) { el.className = opt_className; }
      if (opt_id) { el.id = opt_id; }
      return el;
    }
    function cloneObject(obj) {
        if (typeof obj !== 'object' || obj == null) {
            return obj;
        }
        var c = obj instanceof Array ? [] : {};
        for (var i in obj) {
            var prop = obj[i];
            if (typeof prop == 'object') {
               if (prop instanceof Array) {
                   c[i] = [];
                   for (var j = 0; j < prop.length; j++) {
                       if (typeof prop[j] != 'object') {
                           c[i].push(prop[j]);
                       } else {
                           c[i].push(cloneObject(prop[j]));
                       }
                   }
               } else {
                   c[i] = cloneObject(prop);
               }
            } else {
               c[i] = prop;
            }
        }
        return c;
    }
    function cleanedSiteURL(url) {
        var site = url.toLowerCase().replace(/http:\/\//i,"").split("/")[0];
        
        if (site.indexOf("www.") !== 0) {
        
            var siteArray = site.split(".");
            
            if (siteArray.length === 2) {
                siteArray.unshift("www");        
            } else if (siteArray.length === 3 && siteArray[siteArray.length-1].length === 2) {            
                siteArray.unshift("www");  
            }
            
            site = siteArray.join(".");
        }
        return site;
    }
    function SiteListingTXT(resultObjectArray,opt_IncludeTitle) {
        
        var alltxt = "";
        
        for (var i=0; i<resultObjectArray.length; i++) {
            var result = resultObjectArray[i];
            alltxt += result.content + " ";
            if (opt_IncludeTitle) {
                alltxt += result.titleNoFormatting + " ";
            }
        }
        return CleanSiteListingTXT(alltxt);
    }
    function CleanSiteListingTXT(txt) {
        
        txt = txt.replace(/<b>/ig, '').replace(/<\/b>/ig, '').replace(/\./ig, '').replace(/\&(\w+)\;/ig, '');
        var alltxtArr = txt.split(" ");
        var alltxtClean = "";
        for (var j=0; j<alltxtArr.length; j++) {
            if (alltxtArr[j].length > 1) {
                alltxtClean += alltxtArr[j] + "+";
            }
        }
        return txt;
    }
    function shortenString(stringToShorten, maxLength) {
      if (stringToShorten !== undefined && stringToShorten.length > maxLength) {
          stringToShorten = stringToShorten.substring(0, maxLength-3) + "...";
        }
      return stringToShorten;
    }  
    function ArrayContains(arr,element) 
    {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] === element) {
                return true;
            }
        }
        return false;
    }      
    //returns a url parameter value when passed the parameter name. Will return "" if the param does not exist.
    function getURLparam(name){
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results === null ) {
            return "";
        }
        else {
            return unescape(results[1]);
        }
    }
    if(Array.indexOf = 'undefined' || !Array.indexOf) {
        Array.prototype.indexOf = function(obj) {
            for(var i=0; i<this.length; i++) {
                if(this[i]==obj){
                    return i;
                }
            }
            return -1;
        }
    }
    //**
    //************** End Helper Functions **************************
    return SearchObj;
}
Search = new Search();