﻿/*
* Scandia Business Logic Library - Site Search
* ==========================================================
*
* Business logic library for extending Web applications
*
*
* Credits:
*   Martin Angelov (Based on: http://tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/)
*
* Dependecies:  
*   - jQuery (v 1.4.x)
*/

/* Global Vars */
var SITE_URL;



var escapeS = function(s){
	var escape_re = /[#;&,\.\+\*~':"!\^\$\[\]\(\)=><|\/\\]/;
	var left = s.split(escape_re, 1)[0];
	if (left == s) return s;
	return left + '\\' + s.substr(left.length, 1) + escapeS(s.substr(left.length+1));
};


$(document).ready(function () {

    // Site URL must be defined so that we can run a site search...
    if (!SITE_URL) {
        alert('Google Site Search will not work without a configured Web site URL. Please make sure to specify a URL.');
    }

    var config = {
        siteURL: SITE_URL, // Change this to your site
        searchSite: true,
        type: 'web',
        append: false,
        perPage: 8, 		// A maximum of 8 is allowed by Google
        page: 0				// The start page
    }

    // The small arrow that marks the active search icon:
    var arrow = $('<span>', { className: 'arrow' }).appendTo('ul.icons');

    $('ul.icons li').click(function () {
        var el = $(this);

        if (el.hasClass('active')) {
            // The icon is already active, exit
            return false;
        }

        el.siblings().removeClass('active');
        el.addClass('active');

        // Move the arrow below this icon
        arrow.stop().animate({
            left: el.position().left,
            marginLeft: (el.width() / 2) - 4
        });

        // Set the search type
        config.type = el.attr('data-searchType');
        $('#more').fadeOut();

        // if the keyword is filled in refresh the search with the new search type
        if ($('#txtSearch').val() != '') googleSearch();
    });

    // Adding the site domain as a label for the first radio button:
    $('#siteNameLabel').append(' ' + config.siteURL);

    // Marking the Search {sitename} radio as active:
    $('#searchSite').click();

    // Marking the web search icon as active:
    $('li.web').click();

    // Focusing the input text box:
    $('#txtSearch').focus();

    // execute the search using a click event (if you use the button; I've removed the form tag 
    // so that we don't have to worry about the nested table syndrome
    // for .Net apps...
    $('#submitButton').click(function () {
        var id = '#txtSearch';
            googleSearch(id);
        return false;
    });
	
	$('#submitButton1').click(function () {
        var id = '#txtSearch1';
            googleSearch(id);
        return false;
    });
	
    // execute search on enter key press too....
    $('#txtSearch').keydown(function (e) {
        if (e.keyCode == 13) {
			var id = '#txtSearch';
            googleSearch(id);
            return false;
        }
    });
	
	$('#txtSearch1').keydown(function (e) {
        if (e.keyCode == 13) {
			var id = '#txtSearch1';
            googleSearch(id);
            return false;
        }
    });

    $('#searchSite,#searchWeb').change(function () {
        // Listening for a click on one of the radio buttons.
        // config.searchSite is either true or false.

        config.searchSite = this.id == 'searchSite';

        // if the keyword is filled in refresh the search with the new search type
        if ($('#txtSearch').val() != '') googleSearch();
    });


    function googleSearch(id,settings) {

        // If no parameters are supplied to the function,
        // it takes its defaults from the config object above:

        settings = $.extend({}, config, settings);
        settings.term = settings.term || $(id).val();

        if (settings.searchSite) {
            // Using the Google site:example.com to limit the search to a
            // specific domain:
            settings.term = 'site:' + settings.siteURL + ' ' + settings.term;
        }

        // URL of Google's AJAX search API
        var apiURL = 'http://ajax.googleapis.com/ajax/services/search/' + settings.type + '?v=1.0&callback=?';
        var resultsDiv = $('#resultsDiv');

        $.getJSON(apiURL, { q: settings.term, rsz: settings.perPage, start: settings.page * settings.perPage }, function (r) {

            var results = r.responseData.results;
            $('#more').remove();

            if (results.length) {

                // If results were returned, add them to a pageContainer div,
                // after which append them to the #resultsDiv:

                var pageContainer = $('<div>', { 'class': 'lstResults' });

                for (var i = 0; i < results.length; i++) {
                    // Creating a new result object and firing its toString method:
                    pageContainer.append(new result(results[i]) + '');
                }

                if (!settings.append) {
                    // This is executed when running a new search, 
                    // instead of clicking on the More button:
                    resultsDiv.empty();
                }

                // pageContainer.append('<div class="clear"></div>')
							 // .hide().appendTo(resultsDiv)
							 // .fadeIn('slow');
				pageContainer.append('<div class="clear"></div>').appendTo(resultsDiv);
                var cursor = r.responseData.cursor;

                // Checking if there are more pages with results, 
                // and deciding whether to show the More button:

                if (+cursor.estimatedResultCount > (settings.page + 1) * settings.perPage) {
                    $('<div>', { id: 'more' }).appendTo(resultsDiv).click(function () {
                        googleSearch({ append: true, page: settings.page + 1 });
                        $(this).fadeOut();
                    });
                }
            }
            else {

                // No results were found for this search.

                resultsDiv.empty();
                $('<p>', { className: 'notFound', html: 'No Results Were Found!' }).hide().appendTo(resultsDiv).fadeIn();
            }			
			resultsDiv.hide();						

			$('#resultsDiv1')[0].value = resultsDiv.html();
			 //console.log(escapeS(resultsDiv.html()));
						
			$('#frmSearch').submit();			
        });
    }
	
	if(!window.googleSearch){
		window.googleSearch = googleSearch;
	}

    function result(r) {

        // This is class definition. Object of this class are created for
        // each result. The markup is generated by the .toString() method.

        var arr = [];

        // GsearchResultClass is passed by the google API
        switch (r.GsearchResultClass) {

            case 'GwebSearch':
                arr = [
					//'<div class="webResult">',
					//'<h2><a href="', r.unescapedUrl, '" target="_blank">', r.title, '</a></h2>',
					//'<p>', r.content, '</p>',
					//'<a href="', r.unescapedUrl, '" target="_blank">', r.visibleUrl, '</a>',
					//'</div>'
					'<dl>',
					'	<dt><a href="', r.unescapedUrl, '" target="_blank">', r.title, '</a></dt>',
					'<dd><p>', r.content, '</p>',
					'<p><a href="', r.unescapedUrl, '" target="_blank">', r.visibleUrl, '</a></p>',
					'</dd>',
					'</dl>'
				];
                break;
            case 'GimageSearch':
                arr = [
					'<div class="imageResult">',
					'<a target="_blank" href="', r.unescapedUrl, '" title="', r.titleNoFormatting, '" class="pic" style="width:', r.tbWidth, 'px;height:', r.tbHeight, 'px;">',
					'<img src="', r.tbUrl, '" width="', r.tbWidth, '" height="', r.tbHeight, '" /></a>',
					'<div class="clear"></div>', '<a href="', r.originalContextUrl, '" target="_blank">', r.visibleUrl, '</a>',
					'</div>'
				];
                break;
            case 'GvideoSearch':
                arr = [
					'<div class="imageResult">',
					'<a target="_blank" href="', r.url, '" title="', r.titleNoFormatting, '" class="pic" style="width:150px;height:auto;">',
					'<img src="', r.tbUrl, '" width="100%" /></a>',
					'<div class="clear"></div>', '<a href="', r.originalContextUrl, '" target="_blank">', r.publisher, '</a>',
					'</div>'
				];
                break;
            case 'GnewsSearch':
                arr = [
					//'<div class="webResult">',
					//'<h2><a href="', r.unescapedUrl, '" target="_blank">', r.title, '</a></h2>',
					//'<p>', r.content, '</p>',
					//'<a href="', r.unescapedUrl, '" target="_blank">', r.publisher, '</a>',
					//'</div>'
					'<dl>',
					'	<dt><a href="', r.unescapedUrl, '" target="_blank">', r.title, '</a></dt>',
					'<dd><p>', r.content, '</p>',
					'<p><a href="', r.unescapedUrl, '" target="_blank">', r.visibleUrl, '</a></p>',
					'</dd>',
					'</dl>'
				];
                break;
        }

        // The toString method.
        this.toString = function () {
            return arr.join('');
        }
    }


});

