﻿$(document).ready(function () {
    //the page for the ajax request.
    var arama_sayfasi= "arama_oneri.php";
    //the url for favicons
    var urlFavicon = "http://www.google.com/s2/favicons?domain=";
    // if setFocusOnIfFirst is true when reaching the top of suggestion it focuses on search box
    var setFocusOnIfFirst = true;
    // trigger suggestion after ms after key is pressed
    var search_m_after_keyup = 150;
    // characters minimum before the suggestion is triggered.
    var start_after_cnt = 2;
    // Text before keywords in Suggestion box
    var text_before_keywords = 'Search in '; 
    //Search box WARNING!!! searchBox HAS TO POINT TO 1 OBJECT
    var searchBox = $('#arama');
    // Suggestion box WARNING!!! autoSugg HAS TO POINT TO 1 OBJECT
    var autoSugg = $('#oneriler'); 
    //if focusOnSearchBox is true focus is given to the Search box after loading the page.
    var focusOnSearchBox = true;
    //the script from which the information for suggestion box will be loaded
    var arama_sayfasi= "arama_oneri.php";
    var t;
    var ok = 0; 
    searchBox.bind('keydown', type);
    searchBox.bind('keyup', keyup);
    //sizing suggestion box according to search box
    autoSugg.css('width', searchBox.width() - (
    parseInt(autoSugg.css('padding-left')) + parseInt(autoSugg.css('padding-right')) + parseInt(autoSugg.css('border-left-width')) + parseInt(autoSugg.css('border-right-width')) - (
    parseInt(searchBox.css('padding-left')) + parseInt(searchBox.css('padding-right')) + parseInt(searchBox.css('border-left-width')) + parseInt(searchBox.css('border-right-width')))));
    
    $(window).click(function () {
        if (autoSugg.is(':visible')) {
	  autoSugg.hide();
	}
    });
    //if focusOnSearchBox is true focus is given to the Search box after loading the page.
    if(focusOnSearchBox){
      searchBox.focus();
    }
    function type(e) {
	if(e.which == 13 && autoSugg.children('.div-results').length > 0){
	 entered();
	 if(autoSugg.is(':visible')) {
	   autoSugg.hide();
	 }
	  return false;
	}
        if (e.which == 38 || e.which == 40) {

            if (!autoSugg.is(':visible') && autoSugg.children('.div-results').length > 0  && searchBox.val().length > start_after_cnt && searchBox.val() != "&nbsp;") {
		autoSugg.show();
	    }

            if (autoSugg.children('.div-results').length > 0) {

                if (autoSugg.children('.selected').length > 0) {
                    var s = autoSugg.children('.selected');
                    s.toggleClass("selected");
                    if (e.which == 40) {
                        if (s.next().length == 0) {
                            autoSugg.children('.div-results:first').toggleClass('selected');
                        } else {
                            s.next().toggleClass("selected");
                        }
                    } else {
                        if (s.prev().length == 0) {
			  if(setFocusOnIfFirst==false){
                            autoSugg.children('.div-results:last').toggleClass('selected');
			  }else{
			    autoSugg.children('.div-results').removeClass('selected');
			    searchBox.focus();
			    searchBox.val(searchBox.val());
			  }
                        } else {
                            s.prev().toggleClass("selected");
                        }

                    }



                    s = autoSugg.children('.selected').children().children('.auto-keyword');
                 //   searchBox.val(s.text());
                }

                else {

                    autoSugg.children('.div-results:first').toggleClass("selected");
                    var s = autoSugg.children('.selected').children().children('.auto-keyword');
               //     searchBox.val(s.text());
                }
            }
        }

    }
function highlight (value, re){
  return value.replace(re, function(match){return '<strong>' + match + '<\/strong>'});
}

    function keyup(e)

    {
	if(e.which == 8)
	  $('#form-search').attr('action','search.php');
	//added the code above to return to the default URL search.php
      var searchText = searchBox.val();
        if (searchText.length <= start_after_cnt) {
            if (autoSugg.is(':visible')){
	      autoSugg.hide();
	    }
        }
	
        if (e.which != 0 && e.which != 38  && e.which != 37 && e.which != 39 && e.which != 13 && e.which != 40 && searchText.length > start_after_cnt && searchText != "&nbsp;") {
	    
            var f = function (e) {
               
		
                $.post(arama_sayfasi, {
                    keyword: encodeURI(searchText)
                }, function (data) {
               
		   data = unescape(decodeURI(data));
		   autoSugg.empty();
		   try{
		     if (data != null && data != ''){
		      data = $.parseJSON(data);
		      searchText = searchBox.val();
		      if (searchText.length < start_after_cnt || data == ''){
			autoSugg.empty();
			autoSugg.hide();
			return false;
		      }
		      var re = new RegExp('\\b' + searchText.match(/\w+/g).join('|\\b'), 'gi');
		      var addHtml='';
		   
		      $.each(data, function (key, value) {
			  addHtml = addHtml + ('<div class="div-results" k=' + key + '>' +
			    //'<img src = "http://www.getfavicon.org/?url=' + value.url + '"/>'
			    '<span style="background:url(' + urlFavicon + '' + value.url + ') no-repeat;background-position: 5px 2px;">'
			    + '<span class="text-before-keyword">'+text_before_keywords+'</span>'
			    + '<span class="auto-keyword">'
			    + value.keyword
			    + '<input type="hidden" value="'+value.rKeyword+'" class="rKeyword"/>'
			    + '</span></span><div class="rightdropdown">'+value.languages+' | <a href="http://www.gedoo.com/?prim='+value.id+'" title="Click here to make '+value.keyword+' your primary search engine">Makee primary</a>'
			    +'</div>'
			    + '<input type="hidden" class="search-id" value="'+value.id+'"/>'
			    +'</div>');
			  
		      });
		      autoSugg.append(addHtml);
		      if (!autoSugg.is(':visible')) {
                        autoSugg.css('top', searchBox.position().top + parseInt(searchBox.outerHeight(false)) + 'px');
			autoSugg.css('left', searchBox.position().left+'px');
                        autoSugg.show();
		      }
		      autoSugg.children('.div-results').bind('mouseover', mover).bind('click', entered);
		    }else{
		      autoSugg.hide();
		      
		    }
		    }catch(error){
		      autoSugg.hide();
		      
		    }
                });
		}
            
	    
            var check = function () {
                if (ok == 0) {
		  autoSugg.hide();
		}

            }
            if (t == null) t = setTimeout(f, search_m_after_keyup);
            else {
                clearTimeout(t);
                t = setTimeout(f, search_m_after_keyup);
                //setTimeout(check, 3000);
            }
        }

    }

    function mover() {
        autoSugg.children('.div-results').removeClass("selected");
        $(this).addClass("selected");
        var s = autoSugg.children('.selected').children().children('.auto-keyword');
	
    }

    function entered() {
      
      var selected;
      if(autoSugg.children('.selected').length == 0) {
      }else{
	selected = autoSugg.children('.selected');
      }
        var s = selected.children().children('.auto-keyword');
        searchBox.val(s.text() + ': ');

	var IDs = selected.children('.search-id').val();
	var form = $('#form-search');
	if(IDs != '')
	    form.attr('action','search.php?se='+IDs);
	searchBox.focus();
	autoSugg.hide();
	autoSugg.empty();
    }

});
