﻿    //<![CDATA[
    google.load('search', '1.0');
    
    function OnLoad() {
      searchControl = new googleSearchControl();
      PerformSearches();
    }

    function PerformSearches() {
        if (document.getElementById("hSearchString") != null)
            searchString = document.getElementById("hSearchString").value;
        else
            searchString = "\"" + document.getElementById("hMixtapeTitle").value + "\"";
        firstSearch = true;
        setSearcher("blog");  //do initial google blog search
        setSearcher("web");   //do initial google web search
        //yahooSearch.init();
    }
    
    function ComputeStats() {
        var ourSiteDownloadsStart = Number(document.getElementById("hOurSiteDownloadsStart").value);
        var ourSiteDownloadsDaily = Number(document.getElementById("hOurSiteDownloadsDaily").value);
        var CTRBlasts = Number(document.getElementById("hCTRBlasts").value);
        var initialDownloadsPerSite = Number(document.getElementById("hInitialDownloadsPerSite").value);
        var initialDownloadsPerBlog  = Number(document.getElementById("hInitialDownloadsPerBlog").value);
        var daysFromRelease = Number(document.getElementById("hDaysFromRelease").value);
        var totalBlasts = Number(document.getElementById("hTotalBlasts").value);
        var totalViews = Number(document.getElementById("hTotalViews").value);
        var peakDownLoads = Number(document.getElementById("hPeakDownloads").value);
        var copiesDistributed = Number(document.getElementById("hCopiesDistributed").value);
        var mailingListSize = Number(document.getElementById("hMailingListSize").value);
        var websitesStocked = Number(document.getElementById("hWebsitesStocked").value);
        var reductionPercentWeb = Number(document.getElementById("hReductionPercentWeb").value);
        var reductionPercentBlog = Number(document.getElementById("hReductionPercentBlog").value);

        //in case we have very general search terms and results are ridiculous
        if (googleWebCount > 10000) googleWebCount = 10000;
        if (googleBlogCount > 10000) googleBlogCount = 10000;
        if (yahooCount > 10000) yahooCount = 10000;
         
        //if (daysFromRelease > 30) daysFromRelease = 30;
        //var totalDownloads = Number(ourSiteDownloadsStart) + Number(initialDownloadsPerSite) + Number(initialDownloadsPerBlog) + Number(copiesDistributed);
        var totalDownloads = Number(totalViews) + Number(initialDownloadsPerSite) + Number(initialDownloadsPerBlog) + Number(copiesDistributed);
        totalDownloads += ((totalBlasts + mailingListSize) * CTRBlasts);

        //var totalWebSites = Math.max(Number(googleWebCount), Number(yahooCount)) + websitesStocked;
        var totalWebSites = Number(googleWebCount) + websitesStocked;
        var dailyWebDownloads = (totalWebSites * initialDownloadsPerSite);
        var dailyBlogDownloads = (Number(googleBlogCount) * initialDownloadsPerBlog);
        for (var i = 1; i <= daysFromRelease; i++)
        {
            totalDownloads += (dailyWebDownloads + dailyBlogDownloads);
            dailyWebDownloads = ((100-reductionPercentWeb)/100.0) * dailyWebDownloads;
            dailyBlogDownloads = ((100-reductionPercentBlog)/100.0) * dailyBlogDownloads;
        }
        var totalElem = document.getElementById("summaryDownLoads");
        if (totalElem != null) {
            var newPeakDownLoads = Math.round(Math.max(totalDownloads, peakDownLoads));
            totalElem.innerHTML = addCommas(newPeakDownLoads);
        }
        
        var totalBlastSize = mailingListSize + Math.round(totalBlasts);
        var emailElem = document.getElementById("summaryEmailDownLoads");
        if (emailElem != null)
            emailElem.innerHTML = addCommas(Math.round(totalBlastSize * CTRBlasts));
        
        var emailBlastsElem = document.getElementById("summaryEmailBlasts");
        if (emailBlastsElem != null)
            emailBlastsElem.innerHTML = addCommas(totalBlastSize);

        var statID = document.getElementById("hStatID").value;
        var statUpdatePage = document.getElementById("hStatUpdatePage").value;

        //document.getElementById("UpdateStatsIFrame").src = "http://localhost:3190/artists/setsubmissionstats.aspx?submissionid=" + statID
        document.getElementById("UpdateStatsIFrame").src =
            statUpdatePage + statID 
                + "&totaldownloads=" + newPeakDownLoads
                + "&GoogleWebHits=" + googleWebCount
                + "&GoogleBlogHits=" + googleBlogCount
                + "&YahooWebHits=" + yahooCount;
        window.frames["UpdateStatsIFrame"].location.reload(true);

    }

    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 googleSearchControl() {
      this.results = document.getElementById("results");
      this.cursor = document.getElementById("cursor");
      this.webSearchDone = false;
      this.displayResults = true;
      
      this.searchers = new Array();

      GSearch.getBranding(document.getElementById("branding"));

      var searcher;
      searcher = new google.search.WebSearch();
      searcher.setNoHtmlGeneration();
      searcher.setResultSetSize(google.search.Search.LARGE_RESULTSET);
      searcher.setSearchCompleteCallback(this,
                                         googleSearchControl.prototype.webSearchComplete,
                                         [searcher]
                                         );
      this.searchers["web"] = searcher;

      searcher = new google.search.BlogSearch();
      searcher.setNoHtmlGeneration();
      searcher.setResultSetSize(google.search.Search.LARGE_RESULTSET);
      searcher.setSearchCompleteCallback(this,
                                         googleSearchControl.prototype.blogSearchComplete,
                                         [searcher]
                                         );
      this.searchers["blog"] = searcher;
}

    /**
     * searchComplete - called when a search completed. Note the searcher
     * that is completing is passes as an arg because thats what we arranged
     * when we called setSearchCompleteCallback
     */


googleSearchControl.prototype.webSearchComplete = function (searcher) {
    this.searchComplete(searcher);
}

googleSearchControl.prototype.blogSearchComplete = function (searcher) {
    this.searchComplete(searcher);
}

googleSearchControl.prototype.searchComplete = function (searcher) {
    // always clear old from the page
    this.clearResults();

    // if the searcher has results then process them
    if (searcher.results && searcher.results.length > 0) {

        // now manually generate the html that we disabled
        // initially and display it
        var countElem = document.getElementById('gCount');
        countElem.innerHTML = "(approx: " + searcher.cursor.estimatedResultCount + ")";

        var summaryCountElem;
        if (searcher == searchControl.searchers["web"]) {
            summaryCountElem = document.getElementById('summaryGWebCount');
            googleWebCount = searcher.cursor.estimatedResultCount;
        }
        else {
            summaryCountElem = document.getElementById('summaryGBlogCount');
            googleBlogCount = searcher.cursor.estimatedResultCount;
        }
        summaryCountElem.innerHTML = searcher.cursor.estimatedResultCount;

        if (!firstSearch || searcher == searchControl.searchers["web"]) {
            var div;
            for (var i = 0; i < searcher.results.length; i++) {
                var result = searcher.results[i];
                searcher.createResultHtml(result);
                if (result.html) {
                    div = result.html.cloneNode(true);
                } else {
                    div = createDiv("** failure to create html **");
                }
                this.results.appendChild(div);
            }

            // now, see if we have a cursor, and if so, create the 
            // cursor control
            if (searcher.cursor) {
                var cursorNode = createDiv(null, "gsc-cursor");
                for (var i = 0; i < searcher.cursor.pages.length; i++) {
                    var className = "gsc-cursor-page";
                    if (i == searcher.cursor.currentPageIndex) {
                        className = className + " gsc-cursor-current-page";
                    }
                    var pageNode = createDiv(searcher.cursor.pages[i].label, className);
                    pageNode.onclick = methodClosure(this, this.gotoPage,
                                             [searcher, i]);
                    cursorNode.appendChild(pageNode);
                }
                this.cursor.appendChild(cursorNode);
                var more = createLink(searcher.cursor.moreResultsUrl,
                                GSearch.strings["more-results"] + "&nbsp;&raquo;",
                                GSearch.LINK_TARGET_SELF,
                                "gsc-trailing-more-results");
                this.cursor.appendChild(more);
            }
            firstSearch = false;
        }
        if (firstSearch && searcher == searchControl.searchers["web"]) {
            ComputeStats();
        }
    }
}

    googleSearchControl.prototype.gotoPage = function(searcher, page) {
      searcher.gotoPage(page);
    }

    /**
     * clearResults - clear out any old search results
     */
    googleSearchControl.prototype.clearResults = function() {
      removeChildren(this.results);
      removeChildren(this.cursor);
    }

    function setSearcher(searchType)
    {
        //debugger;
        searchControl.searchers[searchType].execute(searchString.replace("%27", "'"));
    }
    
    /**
     * Static DOM Helper Functions
     */
    function removeChildren(parent) {
      while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
      }
    }
    function createDiv(opt_text, opt_className) {
      var el = document.createElement("div");
      if (opt_text) {
        el.innerHTML = opt_text;
      }
      if (opt_className) { el.className = opt_className; }
      return el;
    }

    function methodClosure(object, method, opt_argArray) {
      return function() {
        return method.apply(object, opt_argArray);
      }
    }

    function createLink(href, opt_text, opt_target, opt_className, opt_divwrap) {
      var el = document.createElement("a");
      el.href = href;
      if (opt_text) {
        el.innerHTML = opt_text;
      }
      if (opt_className) {
        el.className = opt_className;
      }
      if (opt_target) {
        el.target = opt_target;
      }
      if (opt_divwrap) {
        var div = this.createDiv(null, opt_className);
        div.appendChild(el);
        el = div;
      }
      return el;
    }

//Yahoo code
var yahooSearch =
{
  init : function()
  {
    yahooSearch.r = document.getElementById('yahooResults');
    yahooSearch.pingSearch();
  },
  pingSearch : function()
  {
    if (searchString)
    {
      yahooSearch.s = document.createElement('script');
      yahooSearch.s.type ='text/javascript';
      yahooSearch.s.charset = 'utf-8';
      yahooSearch.s.src = 'http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=gEWdXUXV34ENaZPc2_b_IX_ku5JO3gLZSDIG1Y3yzGWDrF1wM8VmiW7nHNrybHLLxxgn9p4-&results=8&type=phrase&output=json&callback=yahooSearch.pongSearch&query=' + searchString.replace(/&/, "%26");
      document.getElementsByTagName('head')[0].appendChild(yahooSearch.s);
    }
  },
  pongSearch : function(z)
  {
    var countElem = document.getElementById('yCount');
    countElem.innerHTML = "(approx: " + z.ResultSet.totalResultsAvailable + ")";
    var summaryCountElem = document.getElementById('summaryYCount');
    summaryCountElem.innerHTML = z.ResultSet.totalResultsAvailable;
    yahooCount = z.ResultSet.totalResultsAvailable;
    
    var br = document.createElement('br');
    
    yahooSearch.r.innerHTML = '';
    for (var i = 0; i < z.ResultSet.Result.length; i++)
    {
      var result = document.createElement('div');
      result.setAttribute("class", "gs-webResult gs-result");
      result.setAttribute("className", "gs-webResult gs-result");
      
      var title = document.createElement('div');
      title.setAttribute("class", "gs-title");
      title.setAttribute("className", "gs-title");
      var link = document.createElement('a');
      link.href = z.ResultSet.Result[i].Url;
      link.innerHTML = z.ResultSet.Result[i].Title;
      link.setAttribute("class", "gs-title");
      link.setAttribute("className", "gs-title");
      title.appendChild(link);

      var snippet = document.createElement('div');
      snippet.setAttribute("class", "gs-snippet");
      snippet.setAttribute("className", "gs-snippet");
      snippet.innerHTML = z.ResultSet.Result[i].Summary;

      var urlShort = document.createElement('div');
      urlShort.setAttribute("class", "gs-visibleUrl gs-visibleUrl-short");
      urlShort.setAttribute("className", "gs-visibleUrl gs-visibleUrl-short");
      var url = z.ResultSet.Result[i].Url;
      if (url.length > 40)
        url = url.substr(0,40) + "...";
      urlShort.innerHTML = url + "<br/><br/>";

      result.appendChild(title);
      result.appendChild(snippet);
      result.appendChild(urlShort);
      yahooSearch.r.appendChild(result);
    }
    var moreLink = document.createElement('a');
    moreLink.href = "http://search.yahoo.com/search?p=" + searchString.replace(/&/, "%26") + "&y=Search;";
    moreLink.innerHTML = "More results >>";
    moreLink.setAttribute("class", "gs-title");
    moreLink.setAttribute("className", "gs-title");
    yahooSearch.r.appendChild(moreLink);
    
    ComputeStats();
  }
};

