// --- Search Bar Start
function _srchBar() {
  var color_grey_text = '#c3beb5';
  var color_black = '#000';
  var srchBarFld = 'srchfld';
  // default prompts
  var blurFontSize = '15px';
  var focusFontSize = '14px';
  var blurMarginTop = '18px';
  var focusMarginTop = '20px';
  // user text
  
  var aSB = {     // array search bar
    'srchfld': {
      'first': true,
      'other': 'askfld',
      'wd_focus': 217,
      'wd_blur': 60,
      'prompt': ' Search',
      'cntnr': '#searchBar_3_field1_1',
      'cntnr_wd_focus': 300,
      'cntnr_wd_blur': 110,
      'btn': '#btn_search',
      'blur_icon': '#srch_blur_icon'
    },
    'askfld': {
      'first': true,
      'other': 'srchfld',
      'wd_focus': 250,
      'wd_blur': 84,
      'prompt': 'Ask',
      'cntnr': '#searchBar_5_field2_1',
      'cntnr_wd_focus': 300,
      'cntnr_wd_blur': 110,
      'btn': '#btn_ask',
      'blur_icon': '#ask_blur_icon'
    }
  };
  
  this.resizeFld = function(currFld) {
    if (this.srchBarFld != currFld) {
      var othrFld = aSB[currFld]['other'];
      var _$currFld = $('#' + currFld);
      var _$othrFld = $('#' + othrFld);
      var currText = _$currFld.val();
      var othrText = _$othrFld.val();
      $(aSB[othrFld]['btn']).fadeOut('fast', function() {
          $(aSB[othrFld]['blur_icon']).fadeIn('slow');
      });
      // _$othrFld.css({width: aSB[othrFld]['wd_blur']});
      if (othrText == '' || (aSB[othrFld]['first'] && othrText == aSB[othrFld]['prompt'])) {
        _$othrFld
          .css({color: color_grey_text, 
            'font-weight': 'bold', 
            'margin-top': blurMarginTop,
            'font-size': blurFontSize})
          .val(aSB[othrFld]['prompt']);
          aSB[othrFld]['first'] = false;
      }
      // $(aSB[othrFld]['cntnr']).animate({width: aSB[othrFld]['cntnr_wd_blur'] + 'px'}, 'slow');
      // $(aSB[currFld]['cntnr']).animate({width: aSB[currFld]['cntnr_wd_focus'] + 'px'}, 'slow');
      $(aSB[currFld]['blur_icon']).fadeOut('fast', function() {
        $(aSB[currFld]['btn']).fadeIn('slow');
      });
      _$currFld.animate({width: aSB[currFld]['wd_focus'] + 'px'}, 'slow');
      if (_$currFld.val() == aSB[currFld]['prompt'] || _$currFld.val().match(/type terms/i ) ) {
        _$currFld.val('').css({color: color_black, 'font-weight': 'normal', 'font-size': focusFontSize});
      }
      this.srchBarFld = currFld;
    }
  }
}

var oSrchBar = new _srchBar();
var askshown = false;
function resizeSearchAsk() {
  oSrchBar.resizeFld('srchfld');  
  HideAskSuggest();
}
function resizeAskSearch() {
  oSrchBar.resizeFld('askfld');
  if ( $('#askfld').val() != '' && !askshown ) {
    showAskSuggest();
  }
}

/*********** SUGGESTED SEARCH ****************/

function submitQuestion() {
  document.location = "/ask.html?q=" + $('#askfld').val();
}

function ClearSuggest() {
  $('#suggested-questions').empty();
}

// Where results are cached
var askData = new Object();
var curKey = new String();
var selectedQ = '';

function ClearSuggest() {
  $('#suggested-questions').empty();
}
function makeSuggestedQuestions() {

  // here we need to determine if we have cached data already of if we need to fetch anew
  curKey = $('#askfld').val();
 
  // canonicalize
  curKey = curKey.replace( /\s\s+/, ' ');
  curKey = curKey.replace( /^\s+|\s+$/g, '');

  // cached?
  if ( curKey ) {
    if ( !askData[curKey] ) {
      $.get( "/includes/ajax/search-suggest.php", "q=" + curKey, function(data) { askData[curKey]=data; }, "json" );
      $('#suggested-questions').ajaxComplete(displaySuggestedQuestions);
    }
    else {
      displaySuggestedQuestions();
    }
  }
}
function displaySuggestedQuestions() {

  if ( askData[curKey] ) {
    // start fresh
    $(this).empty();

    // display new results
    var items = askData[curKey].items;
    for ( i=0; i<items.length; i++ ) {
      var node = document.createElement("a");
          node.href = items[i].url;
      var sugitem = document.createElement("div");
          sugitem.className ="asksugitem";
      var img = document.createElement("img");
          img.src = items[i].avatar;
          img.className = 'commentimg';
      var title = document.createElement("div");
          title.className = "question";
          title.innerHTML = items[i].question;
      var author = document.createElement("div");
          author.className = 'item-author';
          author.innerHTML = 'By <em>' + items[i].author + '</em> ' +
                             items[i].updated + ' | <em>' + items[i].comments + '</em>';
      var clear = document.createElement("div");
          clear.className = "Clear";
      sugitem.appendChild(img);
      sugitem.appendChild(title);
      sugitem.appendChild(author);
      sugitem.appendChild(clear);
      node.appendChild(sugitem);
      $(this).append(node);
      $('#suggested-questions a').hover( cbkHighlightResult, cbkUnhighlightResult );
    }
    // Now update totals
    $('#num-suggested-questions').html('<a href="/search.html?q=' + askData[curKey].search_str + '">' +
                                       (askData[curKey].total - items.length) +
                                       ' More >> View All</a>');
  }
}

function cbkHighlightResult(event) {
  highlightResult(event.target);
}
function highlightResult(target) {
  // Make sure nothing is highlighted
  $('#suggested-questions').children().children().removeClass('asksugitem-highlighted');
  target.className += " asksugitem-highlighted";
}
function cbkUnhighlightResult(event) {
  unhighlightResult(event.target);
}
function unhighlightResult(target) {
  var reg = new RegExp('(\\s|^)asksugitem-highlighted(\\s|$)');
  target.className=target.className.replace(reg,' ');
}

function HideAskSuggest() {
  if ( askshown ) {
    $('#searchBar_asksug').hide();
    askshown = false;
  }
}

function showAskSuggest(event) { 

  // If askfld is empty, make sure it is hidden
  if ( $('#askfld').val() == '' ) {
    HideAskSuggest();
  }
  else {

    if ( !askshown ) {
 
      // Request and show suggestions if we have at least one word
      if ( $('#askfld').val().length > 2 && event.keyCode == 32 ) {
        makeSuggestedQuestions();
        $('#searchBar_asksug').fadeIn('slow'); 
        askshown = true; 
      }
    }
    else if ( event.keyCode == 32 || event.keyCode == 191 ) {
      // hit a space or a ?
      makeSuggestedQuestions();
    }
    else {

      // already shown.  If up/down arrow pressed, highlight the appropriate element
      var reg = new RegExp('(\\s|^)asksugitem-highlighted(\\s|$)');
      var kids = $('#suggested-questions').children().children();
      var found = false;
      if ( event.keyCode == 38 ) {
        // up pressed
        for ( i=0; i<kids.length; i++ ) {
          if ( kids[i].className.match(reg) ) {
            found = true;
            if ( i == 0 ) {
              highlightResult(kids[kids.length-1]);
              break;
            }
            else {
              highlightResult(kids[i-1]);
              break;
            }
          }
        }
        if ( !found ) {
          highlightResult(kids[kids.length-1]);
        }
      }
      else if ( event.keyCode == 40 ) {
        // down pressed
        for ( i=0; i<kids.length; i++ ) {
          if ( kids[i].className.match(reg) ) {
            found = true;
            if ( i == (kids.length-1) ) {
              highlightResult(kids[0]);
              break;
            }
            else {
              highlightResult(kids[i+1]);
              break;
            }
          }
        }
        if ( !found ) {
          highlightResult(kids[0]);
        }
      }
    }
  }
}

$().ready(function() {
  $('#srchfld').focus(resizeSearchAsk);
  // $('#askfld').focus(resizeAskSearch);
  // $('#askfld').keyup(showAskSuggest);
});
// --- Search Bar End

