var searchControl;

var Nav = {
  toggle : function(clicked){
    nav_elements = getElementsByClass('nav_tier2');
    for(var i = 0; i < nav_elements.length; i++){
      if(nav_elements[i] != $('menu_' + clicked)) Element.hide(nav_elements[i])
      $(nav_elements[i].id + '_toggle').className = 'toggle_button';
      $(nav_elements[i].id + '_link').removeClassName('toggled');
    }
    
    if(!$('menu_' + clicked).visible()){
      $('menu_' + clicked + '_toggle').className = 'toggle_button_toggled';
      $('menu_' + clicked + '_link').addClassName('toggled');
    }
    $('menu_' + clicked).toggle();
  }
}

var Post = {
  advancedToggle : function(id, which) {
    if(which == 'restaurant'){
      other = 'photo';
      searchControl = new RawSearchControl();
    }else{
      other = 'restaurant';
    }

    if($(other + '_button_' + id) != null){
      $(other + '_form_' + id).hide();
      $(other + '_button_' + id).removeClassName('button_active').addClassName('button');
    }
     
    button = $(which + '_button_' + id);
    if(button.className.match(/button_active/)){
      button.removeClassName('button_active');
    }else{
      button.addClassName('button_active');
    }
    $(which + '_form_' + id).toggle()
  },
  
  editMode : function(id) {
    $('post_content_' + id + '_in_place_editor').hide();
    editors[id].enterEditMode('click');
    for (var index = 0; index < 4; index++) {
      try {
        $('inplace_photo_edit_' + id + '_index_' + index).show();
      } catch(e) {}
    }
  },
  
  /*
  hideCallback: function() {
    for (var index = 0; index < 4; index++) {
      try {
        $('inplace_photo_edit_' + id + '_index_' + index).hide();
      } catch(e) {}
    }
  },
  */
  
  setupEditing : function(id, rows) {
    /* ugh.. my js is bad */
    var hideCallback = function() {
      for (var index = 0; index < 4; index++) {
        try {
          $('inplace_photo_edit_' + id + '_index_' + index).hide();
        } catch(e) {}
      }
    }
   
    editors[id] = new Ajax.InPlaceEditor('post_content_' + id + '_in_place_editor', '/posts/set_post_content/' + id, {clickToEditText: null, loadTextURL:'/posts/get_post_content/' + id, okText: 'Save', rows:rows, hideCallback: hideCallback });
    editors[id].dispose();
  },
  
  visibilityToggle : function(id) {
    el = $('post-content-' + id);
    if(el.style.display != 'none'){
      el.hide();
      Element.removeClassName('highlight-' + id, 'post_collapsed');
      $('truncated-content-' + id).show();
    }else{
      el.show();
      Element.removeClassName('highlight-' + id, 'post_collapsed');
      $('truncated-content-' + id).hide();
    }
  },
  
  repliedTo : function(id) {
    el = $('post-content-' + id);
    if(el.style.display == 'none'){
      el.show();
      Element.removeClassName('highlight-' + id, 'post_collapsed');
      $('truncated-content-' + id).hide();
    }
    new Effect.Highlight('highlight-' + id, {duration: 5});
    new Effect.ScrollTo('highlight-' + id, {offset: -200});
  }
}

var Topic = {
  current : null,
  currentType : null,
  
  switcher : function() {
    var node = $('comments');
    var posts = getElementsByClass('post', node);
    if($('switcher').innerHTML == 'Expand All'){
      for(var i = 0; i < posts.length; i++){
        var id = posts[i].id.replace('highlight-', '');
        Element.removeClassName(posts[i], 'post_collapsed');
        $('truncated-content-' + id).hide();
        $('post-content-' + id).show();
      }
      $('switcher').innerHTML = 'Only Show New Posts';
    }else{
      for(var i = 0; i < posts.length; i++){
        if(!posts[i].className.match(/new_post/)){
          var id = posts[i].id.replace('highlight-', '');
          Element.addClassName(posts[i], 'post_collapsed');
          $('truncated-content-' + id).show();
          $('post-content-' + id).hide();
        }
      }
      $('switcher').innerHTML = 'Expand All';
    }
  },
  
  changeResponseArea : function(new_id, topic_id, level) {
    if(this.current != null && (this.current != new_id || this.current_type != 'comment')){ $('comment-' + this.current).hide(); }
    
    if((this.current != new_id) || (this.current_type != 'comment')){
      $('comment-' + new_id).innerHTML = '<div style="text-align:center"><img src="/images/spinner.gif" /></div>';
      new Ajax.Updater($('comment-' + new_id), '/posts/reply', {postBody:'id=' + new_id + '&topic_id=' + topic_id + '&level=' + level});
    }

    this.finishChange(new_id, 'comment');
  },
  
  changeFeedbackArea : function(new_id) {   
    if(this.current != null && (this.current != new_id || this.current_type != 'feedbk')){ $('comment-' + this.current).hide(); }
    
    if((this.current != new_id) || this.current_type != 'feedbk'){
      $('comment-' + new_id).innerHTML = '<div style="text-align:center"><img src="/images/spinner.gif" /></div>';
      new Ajax.Updater($('comment-' + new_id), '/posts/feedback_panel/' + new_id);
    }
    
    this.finishChange(new_id, 'feedbk');
  },
  
  changeModArea : function(new_id) {
    if(this.current != null && (this.current != new_id || this.current_type != 'mod')){ $('comment-' + this.current).hide(); }
    
    if((this.current != new_id) || (this.current_type != 'mod')){
      $('comment-' + new_id).innerHTML = '<div style="text-align:center"><img src="/images/spinner.gif" /></div>';
      new Ajax.Updater($('comment-' + new_id), '/posts/mod_panel/' + new_id);
    }
        
    this.finishChange(new_id, 'mod');
  },
  
  finishChange : function(new_id, type) {
    //new Effect.toggle(location.getElementById('comment-' + new_id), 'blind', {duration: .3, fps: 50});
    $('comment-' + new_id).toggle();
        
    // Blow out previous response area
    if(this.current != null && this.current != new_id){ $('comment-' + this.current).innerHTML = ''; }
    
    this.current = new_id;
    this.current_type = type;
  },
  
  changeSelection : function(selected_value, new_title, input, new_board) {
    if(selected_value == 'POST_SPLIT' || selected_value == 'POST_SPLIT_REPLIES'){
      var title = prompt('Please enter in a topic title for the new thread:');
      if(title != null || title != ''){
        $(input).value = title;
        $(new_title).show();
        $(new_board).show();
      }
    }else if(selected_value == 'TOPIC_MOVE'){
      $(new_title).hide();
      $(new_board).show();
    }else{
      $(new_title).hide();
      $(new_board).hide();
    }
  },
  
  toggleDropdown : function(){
    $('dropdown').toggle();
    if($('options_toggle').className == 'toggle_button'){
      $('options_toggle').className = 'toggle_button_toggled';
    }else{
      $('options_toggle').className = 'toggle_button';
    }
  }
}

var Timezone = {
  set : function() {
    var date = new Date();
    var timezone = "timezone=" + -date.getTimezoneOffset() * 60;
    date.setTime(date.getTime() + (1000*24*60*60*1000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = timezone + expires + "; path=/";
  }
}

// Generic methods
function getElementsByClass(searchClass,node,tag) {
  var classElements = new Array();
  if ( node == null )
    node = document;
  if ( tag == null )
    tag = '*';
  var els = node.getElementsByTagName(tag);
  var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
  for (i = 0, j = 0; i < els.length; i++) {
    if ( pattern.test(els[i].className) ) {
      classElements[j] = els[i];
      j++;
    }
  }
  return classElements;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if(typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function isEmpty(string){
  return string == '' || string == null
}

function embed(string) {
  document.write(string);
}

function inspect(obj) {
    var str = '';
    for (var k in obj){
        str += 'obj.' + k + ' = ' + obj[k] + ' ';
    }
    alert(str);
}


// Local Search
var searcher;

function RawSearchControl() {
  this.results = $("results");
  searcher = new GlocalSearch();
  searcher.setNoHtmlGeneration();
  searcher.setCenterPoint("94105");
  searcher.setSearchCompleteCallback(this, RawSearchControl.prototype.searchComplete, [searcher]);
}

RawSearchControl.prototype.formSubmit = function(name, location) {
  name = name.value;
  location = location.value;
  if(name == '' || name == null){
    alert('Please enter in a name');
  }else if(location == '' || location == null){
    alert('Please enter in a location');
  }else{
    searcher.execute(name + " in " + location);
  }
}

RawSearchControl.prototype.searchComplete = function(searcher) {
  removeChildren(this.results);
  var params = { postBody:'name=' + escape($('name').value) + '&location=' + escape($('location').value), onComplete:function(t){ searchControl.populateResults(eval(t.responseText), searcher) } };
  new Ajax.Request('/restaurants/search', params);  
  $('restaurant_name').value = $('name').value;
  $('restaurant_location').value = $('location').value;
}

RawSearchControl.prototype.populateResults = function(places, searcher) {
  // Chow
  for(i = 0; i < places.length; i++){
    div = createDiv(Restaurant.buildChowRow(places[i]));
    this.results.appendChild(div);
  }
  // Google
  if(searcher.results && searcher.results.length > 0){
    for(i = 0; i < searcher.results.length; i++){
      // gets rid of junk
      if(searcher.results[i].phoneNumbers == null) continue;
      // remove duplicates
      found = false;
      for(j = 0; j < places.length; j++){        
        if(searcher.results[i].titleNoFormatting == places[j].name && 
           searcher.results[i].streetAddress == places[j].street &&
           searcher.results[i].city == places[j].city) {
          found = true;
          break;
        }
      }
      if(!found){
        div = createDiv(Restaurant.buildRow(searcher.results[i]));
        this.results.appendChild(div);
      }  
    } 
  }
  this.results.appendChild(createDiv(noneFound()));
}

var Restaurant = {
  select : function(name, location, phone) {
    $('results').innerHTML = ''
    $('results').hide()
    $('search_instructions').hide()
    $('confirmation_name').innerHTML = unescape(name)
    $('confirmation').show()
    $('restaurant_list').show()
    $('name').value = ''
    $('location').value = ''
    if (location != null && location != '') {
      var params = { postBody:'restaurant[name]=' + name + '&restaurant[location]=' + location + '&restaurant[phone]=' + phone }
      new Ajax.Request('/restaurants/create', params)
    }
    $('restaurant_add').hide()
    $('restaurant_name').value = ''
    $('restaurant_location').value = ''
  },
  
  buildRow : function(result) {
    $('results').show();
	  number = '';
    if (result.phoneNumbers[0] != null) {
		  for(j = 0; j < result.phoneNumbers.length; j++){
		    n = result.phoneNumbers[j];
		    if (n.type == 'main') {
		      number += n.number + '\n';
		    } else {
			    number += n.type + ': ' + n.number + '\n';
			  }
      }
    }
    select = "Restaurant.select('" + escape(result.titleNoFormatting) + "','" + escape(result.streetAddress + ",") + " " + escape(result.city + ",") + " " + escape(result.region) + "','" + escape(number) + "')";
    place  = '<div class="mb10"><input type="radio" onclick="' + select + '" /> ';
    place += result.titleNoFormatting + '<div style="margin-left:16px">';
    place += result.streetAddress + ', ' + result.city + ', ' + result.region + '</div></div>';
    return place;
  },
  
  buildChowRow : function(result) {
    select = "Restaurant.select('" + escape(result.name) + "','" + escape(result.location) + "','" + escape(result.phone) + "')";
    place  = '<div class="mb10"><input type="radio" onclick="' + select + '" /> ';
    place += result.name + '<div style="margin-left:16px">';
    place += result.location + '</div></div>';
    return place;
  },
  
  another : function() {
    $('confirmation').hide();
    $('search_instructions').show();
    $('results').hide();
  },
  
  remove : function(restaurant_id) {
    restaurant = $(restaurant_id)
    restaurant.parentNode.removeChild(restaurant)
    $('fake_restaurants').innerHTML = $('restaurants').innerHTML
  }
}

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 noneFound(){
  return 'Not in list? <input type="button" onclick="$(\'restaurant_add\').show(); $(\'results\').hide(); $(\'search_instructions\').hide();" value="Add a Place" />';
}
    

