// JavaScript Document 
// Bing API 2.0 code
// Web SourceType over the JSON Protocol.
// Bing.

var AppId = "F136BE16D32257AA91A8A359EB17F9EF0A70787A";
var siteFilter = "site:assetresearch.com ";    
	
	function searchBing()
    {
        var search_input = encodeURIComponent($.trim($('#searchTerm').val()));
		var qString = siteFilter + search_input;
		var requestStr = "http://api.bing.net/json.aspx?"
		//console.log(lang);
        
            // Common request fields (required)
            + "AppId=" + AppId
            + "&Query=" + qString
            + "&Sources=Web"
            
            // Common request fields (optional)
            + "&Version=2.0"
            + "&Market=en-us"
			+ "&Adult=Strict"
            + "&Options=EnableHighlighting"

            // Web-specific request fields (optional)
            + "&Web.Count=10"
            + "&Web.Offset=0"
            + "&Web.Options=DisableHostCollapsing+DisableQueryAlterations"

            // JSON-specific request fields (optional)
            + "&JsonType=callback"
            + "&JsonCallback=SearchCompleted";

         var script = document.createElement('script');
         script.src = requestStr;
         script.type = 'text/javascript';
         var head = document.getElementsByTagName('head').item(0);
         head.appendChild(script);

    }

    function SearchCompleted(response)
    {
        var errors = response.SearchResponse.Errors;
        if (errors != null)
        {
            // There are errors in the response. Display error details.
            DisplayErrors(errors);
        }
        else
        {
            // There were no errors in the response. Display the
            // Web results.
			$('#bingoutput').html('');
		    DisplayResults(response);
		 }
    }

    function DisplayResults(response)
    {
        var output = document.getElementById("bingoutput");
        var resultsHeader = document.createElement("h4");
        var resultsList = document.createElement("ul");
        output.appendChild(resultsHeader);
        output.appendChild(resultsList);
    				
		if(response.SearchResponse.Web.Results != undefined){
			var results = response.SearchResponse.Web.Results;
					
			// Display the results header.
			resultsHeader.innerHTML = "<a href='#' id='searchExit'></a>"
				+ "<br />Displaying "
				+ (response.SearchResponse.Web.Offset + 1)
				+ " to "
				+ (response.SearchResponse.Web.Offset + results.length)
				+ " of "
				+ response.SearchResponse.Web.Total
				+ " results<br />";
			
			// Display the Web results.
			var resultsListItem = null;
			var resultStr = "";
			for (var i = 0; i < results.length; ++i)
			{
				resultsListItem = document.createElement("li");
				resultsList.appendChild(resultsListItem);
				resultStr = "<a href=\""
					+ results[i].Url
					+ "\">"
					+ results[i].Title
					+ "</a><br />"
					+ results[i].Description
					+ "<br /><span class='resultDetails'>Last Crawled: "
					+ results[i].DateTime+"</span>"
					+ "<br /><br />";
				
				// Replace highlighting characters with strong tags.
				resultsListItem.innerHTML = ReplaceHighlightingCharacters(
					resultStr,
					"<strong>",
					"</strong>");
			}
			$('#searchExit').click(function(){
				$('#bingoutput').hide();							
			});
			$('#bingoutput').show();
		}else{
			$('#searchTerm').val('No Results...');
			$('#bingoutput').hide();
		}
    }
    
    function ReplaceHighlightingCharacters(text, beginStr, endStr)
    {
        // Replace all occurrences of U+E000 (begin highlighting) with
        // beginStr. Replace all occurrences of U+E001 (end highlighting)
        // with endStr.
        var regexBegin = new RegExp("\uE000", "g");
        var regexEnd = new RegExp("\uE001", "g");
              
        return text.replace(regexBegin, beginStr).replace(regexEnd, endStr);
    }

    function DisplayErrors(errors)
    {
        var output = document.getElementById("output");
        var errorsHeader = document.createElement("h4");
        var errorsList = document.createElement("ul");
        output.appendChild(errorsHeader);
        output.appendChild(errorsList);
        
        // Iterate over the list of errors and display error details.
        errorsHeader.innerHTML = "Errors:";
        var errorsListItem = null;
        for (var i = 0; i < errors.length; ++i)
        {
            errorsListItem = document.createElement("li");
            errorsList.appendChild(errorsListItem);
            errorsListItem.innerHTML = "";
            for (var errorDetail in errors[i])
            {
                errorsListItem.innerHTML += errorDetail
                    + ": "
                    + errors[i][errorDetail]
                    + "<br />";
            }
            
            errorsListItem.innerHTML += "<br />";
        }
    }
