/******************************************************************************
 * File: search_bar.js
 *
 * Creation Date: 28/03/2011
 *
 * Description: This file contains ze necessary functions that handles ze
 *              interaction made with the 'Powered by Google' search bar. This
 *              file is included in the s_header scriptlet alongside
 *              the search bar.
 ******************************************************************************/

//
// Should be const. IE doesn't like const.
//
var XPRIMA_CSE_EN_ID = '007925917890866431643:q9uvhbrva8g';
var XPRIMA_CSE_FR_ID = '007925917890866431643:rjl8nw5lrsa';

var TRIM_SORT_STR = 6;
var WAIT_TIME = 250;  // milliseconds
var INT_BASE = 10; // Numeral system to be used by the parseInt method

//
// Global variable (intended to be singular)
// Do not add more - For every global added, god kills a kitten.
// Kitty count = 1
//
var modificationCount = 0;

/**
 * Event Handler - On DOM Ready
 */
jQuery(document).ready(function()
{
  // NOT A CLEAN HACK
  //
  // Let's bind on our div the DOMSubtreeModified event.
  // Each time the div's DOMSubtree gets modified, a counter is incremented
  // and passed to a function. Each 250 millisecond the function verifies
  // if her current count is the same as the global modification count and if
  // both are the same(meaning that the DOM is no longer modified), then
  // the click can be done on the proper tab.
  //
  // This is done to handle a parametrized URL and needs to be on the
  // proper tab once the DOM is ready.
  jQuery("#search-results").bind('DOMSubtreeModified', function()
  {
    $('.gsc-webResult.gsc-result:first').css('border-top','none');
    $('a.gs-title').attr('target','_self');
    modificationCount = modificationCount + 1;

    var functionCall = "verifyCompleted(" + modificationCount +  ")"
    setTimeout(functionCall, WAIT_TIME);
  });

  // For each div contained in the tab area, a listener on the click action
  // is added
  jQuery(".gsc-tabsArea div").live("click" , function()
  {
    // Add the proper hashtag to the URL
    window.location.hash = "#" + jQuery("div.gsc-tabhActive").text();
    return false;
  });

  // back/forward button management
  jQuery(window).bind('hashchange', function()
  {
    handleHash();
  });
  
  	//get all instance of searchWidget and assign them language, focus, keyup, blur and submit evt
 $('.google-search-box').each(function(){
 	var searchLg = $(this).find(".input-lg").attr("value");
  	
  	//focus event
  	$(this).find('.google-query-input').focus(function(){
  	 	$(this).css("borderColor","#000").prev('span').css("color","#000");
  	 	$(this).css("background-image","url(/site/vrJinja/css/images/loupe_over.png)");
  	 });
  	 //key up event
  	 $(this).find('.google-query-input').keydown(function(evt){
  	 	
  	 	var code = (evt.keyCode ? evt.keyCode : evt.which);
  	 	if (evt.keyCode != 32) {
  	
  	 		if($(this).prev('span').is(":visible"))
  	 		{
 		     	$(this).prev('span').css("display","none");
 		     	$(this).val($.trim($(this).val()));
  	 		}
    	}
  	 });
  	 //blur event
  	 $(this).find('.google-query-input').blur(function(){
  	 	var queryInput = $(this).attr("value");
  	 	$(this).css("borderColor","#E6E6E6");
  	 	$(this).css("background-image","url(/site/vrJinja/css/images/loupe.png)");
  	 	queryInput = $.trim(queryInput);
	
  	 	if (queryInput =="")
		  {
		  	$(this).prev('span').css("color","#999");
		  	$(this).prev('span').css("display","block");
		  }
  	 });
  	 //submit event
  	 $(this).submit(function(){
		  	 	/**
		 * Calls the page that will contain the google results with the
		 * appropriate parameters concatenated in the url.
		 *
		 * @param - The page language (en/fr)
		 */
  	 	// Get the criteria entered in the upper right input box
  			var query = $(this).find('.google-query-input').val();
  			query = $.trim(query);
  			query = encodeURIComponent(query);
  		// Look at the page language and default a refinement
  			var default_refinement = (searchLg == 'en') ? '#All' : '#Tout';
  		 // If the user entered something in the input
			  if(query.length > 0)
			  {
			    // Add the query criteria to the URL
			  
			    window.location = '/' + searchLg +  '/sitesearch.spy?q=' + query + default_refinement;
			  }
			  else // The user didn't specify
			  {
			    // Default to auto123.com
			    window.location = '/' + searchLg +  '/sitesearch.spy?q=auto123.com' + default_refinement;
			  }
			 // Prevent the default link click behavior by returning false
  	 		return false;
  	 });
  	 
  });	

  $("#footer .google-query-input").prev().text($("#footer-search-msg").text());
  $("#div-wrapper .google-query-input").prev().text($("#header-search-msg").text());

	
});



/**
 * Verifies that the event DOMSubtreeModified is done. This is useful
 * since we can't properly hook-up after google's code injection and prevents
 * from executing code on elements that aren't loaded in the page.
 */
function verifyCompleted(verificationCount)
{
  if(verificationCount == modificationCount)
  {
    handleHash();
  }
}

/**
 * Detect the hashtag in the URL and click on the proper tab
 */
function handleHash()
{
  // Get the hash (fragment) as a string, with any leading # removed.
  var refinement = getRefinementFromURL();

  // Replace the %20 (if found) by a proper space or else, we won't be able to
  // map to the tab properly.
  //
  // i.e: Essais%20Routier(in url) vs Essais Routier(tab text)
  if(refinement.indexOf("%20") > 0)
  {
    refinement = refinement.replace('%20', ' ');
  }

  // Get the google tabs
  var tabs = jQuery(".gsc-tabsArea div");
  // For each tab
  tabs.each(function()
  {
    // If the tab's HTML(in our case its label) is the same as
    // the refinement in the URL
    if(jQuery(this).html() == refinement)
    {
      // Execute click on the element
      jQuery(this).click();
    }
  });
}

/**
 * Calls the page that will contain the google results with the
 * appropriate parameters concatenated in the url.
 *
 * @param - The page language (en/fr)
 */

/**
* Extracts the users query from the URL and sets it
* to the google search engine. It is used to execute
* the desired query on a seperate page.
*/
function getQuery()
{
  var url = '' + window.location;
  var queryStart = url.indexOf('?') + 1;
  var query = '';

  if (queryStart > 0)
  {
    var parts = url.substr(queryStart).split('&');
    for (var i = 0; i < parts.length; i++)
    {
      // Let's look for the part of the URL containing the q= param.
      if (parts[i].length > 2 && parts[i].substr(0, 2) == 'q=')
      {
        query = decodeURIComponent(parts[i].split('=')[1].replace(/\+/g, ' '));

        // If a refinement is present but no sort option
        var atPos = query.indexOf('#');
        if(atPos > -1)
        {
          // strip the refinement
          query = query.substring(0, atPos);
        }
        return query;
      }
    }
  }
  return '';
}

/**
 * Sorts the google results based on a dropdown list. The sort type is user-defined.
 * On page load, if a parameter is defined in the URL, the results are sorted
 * accordingly. If a new sort type is chosen, the url will be replaced.
 *
 * @param - User defined sort type. (Relevance, date, etc...)
 */
function sortResults(sortType)
{
  var url = '' + window.location;
  var original = "";
  var replacement = "";

  alert("sort");
  // No sort defined
  if(!isSortOptionDefined())
  {
    // No refinement defined
    if(!isRefinementDefined())
    {
      // Add the sort option straight to the URL
      window.location = window.location + '&sort=' + sortType;
    }
    else // append the sort option before the hash tag (refinement)
    {
      // Fetching the refinement
      original = url.substring(url.indexOf("#"));
      // Building the sort param
      replacement = "&sort=" + sortType;
      // Adding the sort type before the refinement
      replacement = replacement.concat(original);
      // Replace the refinement with the concat of refinement and sort option
      window.location = url.replace(original, replacement);
    }
  }
  else // Sort option already defined
  {
    original = '&sort=' + getSortTypeFromURL();
    replacement = '&sort=' + sortType;
    // Replace the old sort option with the new one
    window.location = url.replace(original, replacement);
  }
}

/**
 * Parses the URL and get the defined sort option.
 *
 * @return (string) the sort option selected.
 */
function getSortTypeFromURL()
{
  var url = '' + window.location;
  var sort_start = url.indexOf('&');
  var sort_end = url.indexOf('#');

  if(sort_end < 0) // No refinement defined
  {
    return url.substring(sort_start + TRIM_SORT_STR);
  }
  else // refinement in URL
  {
    return url.substring(sort_start + TRIM_SORT_STR, sort_end);
  }
}

/**
 * Retrieves the refinement(if it exists) from the URL and
 * strip its '#' caracter.
 */
function getRefinementFromURL()
{
  var url = '' + window.location;
  return url.substring(url.indexOf('#')); // strip the #
}

/**
 * Parses the URL and tries to find if a sort parameter is defined.
 *
 * @return TRUE - the parameter is defined in the URL (indexOf returns a value > 0)
 *         FALSE -  the parameter is not defined in the URL (indexOf returns -1)
 */
function isSortOptionDefined()
{
  var url = '' + window.location;
  return(url.indexOf('&sort') > 0);
}

/**
 * Parses the URL and tries to find if a refinement is defined.
 *
 * @return TRUE - the refinement is defined in the URL (indexOf returns a value > 0)
 *         FALSE - the refinement is not defined in the URL (indexOf returns -1)
 */
function isRefinementDefined()
{
  var url = '' + window.location;
  return(url.indexOf('#') > 0);
}

/**
 * Add the next and previous button the the navigation at the bottom of the
 * result page. It is called once the google API has finished it's search.
 *
 * @param customSearchControl - Google object which is used to execute
 *                              Custom Search queries and display results
 *
 * @param language - The page language
 *
 * @WATCHOUT - currentPageIndex: To prevent from having the same tab index for
 *                               all refinements, the current page index of the
 *                               current tab is put in a variable. Keep in mind
 *                               that the google index starts at 0.
 */
function searchCompleteCallback(customSearchControl, language)
{
  var btn_previous = '';
  var btn_next = '';
  var all_refinement = '';
  var reviews_refinement = '';
  var news_refinement = '';

  // Bi-lingual caption and refinement management
  switch(language)
  {
    case 'en':
      btn_previous = 'Previous';
      btn_next = 'Next';
      all_refinement = 'All';
      reviews_refinement = 'Reviews';
      news_refinement = 'News';
      break;
    case 'fr':
      btn_previous = 'Précédent';
      btn_next = 'Suivant';
      all_refinement = 'Tout';
      reviews_refinement = 'Essais Routiers';
      news_refinement = 'Nouvelles';
      break;
    default:
      break;
  }

  jQuery('div.google-next.'+jQuery('.gsc-tabHeader.gsc-tabhActive').html()).remove();
  jQuery('div.google-previous.'+jQuery('.gsc-tabHeader.gsc-tabhActive').html()).remove();

  // Let's retrieve the current page index
  // WARNING! don't change the h for a g  ;)
  var currentPageIndex = parseInt(jQuery('.gsc-tabdActive .gsc-cursor-current-page').html(), INT_BASE);

  // Back to the top ouh yeah!
  window.scrollTo(0, 0);
}
