/* Use semicolons at the end of lines so this can be minified */

/* run "rake javascript:combine" to add this file to combined_min.js */

var COOKIE_DOMAIN = ".chow." + window.TLD;


document.observe("dom:loaded", function() {

// main nav event listener
  var main_nav = $$('a.menu_link_text');
	var sub_nav = $$('.nav_tier2');
	var nav_timeout;
	
	// move subnavs from footer to header
	sub_nav.each(function(div) {
		var parent = 'main_' + div.id;
		$(parent).insert(div);
	});
	
  main_nav.each(function(a) {
    a.observe('mouseover', function(e) {
			if (!e) var e = window.event;
			var relTarg = e.fromElement || e.relatedTarget;

			sub_id = a.id.split("_link")[0]; 
			if (relTarg.id != sub_id){
				nav_timeout = setTimeout("show_nav(sub_id)",200);
			} else {
				show_nav(sub_id);
			}
 
    });
    a.observe('mouseout', function(e) {
			if (nav_timeout) clearTimeout(nav_timeout);

      var sub_id = a.id.split("_link")[0];
			if ( $(sub_id) && sub_id.length != 0 ){
			 $(sub_id).style.display = "none";
			 }
    });
  });
	
	sub_nav.each(function(div) {
    div.observe('mouseover', function(e) {
      div.style.display = "block";
    });
    div.observe('mouseout', function(e) {
			div.style.display = "none";
    });
  });



// popup opener and closer
// assumes <a href="#id_of_popup" class="open_popup">text</a>
// assumes <a href="#id_of_popup" class="close_popup">text</a>
	var open_popup = $$('a.open_popup');
	var close_popup = $$('a.close_popup');

	open_popup.each(function(a) {
		a.observe('click', function(e) {
			e.stop();
			var popupId = this.href.split('#')[1]; 
			$(popupId).addClassName('active');
			
			//places list specific
			//if ($('searchbar_entry')) { 
				//$('searchbar_entry').value = '';
				//$('location').value = '';
				//$('place_description').value = '';
				//$('places_list').update("");
			//}
		});
	});
	
	close_popup.each(function(a) {
		a.observe('click', function(e) {
			e.stop();
			var popupId = this.href.split('#')[1]; 
			$(popupId).removeClassName('active');
		});
	});

	// restaurant rating on CH posts
	if($('restaurant_review_checkbox')) {
		($('restaurant_review_checkbox').checked) ? showRestaurantInputs(0) : '';
	}



}); // dom:loaded

function show_nav(id){
	if ( $(id) && id.length != 0 )
	$(id).style.display="block";
}


var Timezone = { 
  set: function() { 
    var d = new Date(); 
    createCookie("timezone", -d.getTimezoneOffset() * 60, 1000);
  } 
}

//

var Proteus = {
  update_counter: function() {
    var c = readCookie("proteus_counter");
    var n = c ? (parseInt(c) + 1) : 0;
    createCookie("proteus_counter", n);
    return n;
  }
}

//

// TODO add to elements as a method
function removeChildren(parent) {
  while (parent.firstChild) {
    parent.removeChild(parent.firstChild);
  }
}

// Designed for non-terminating tag pairs, like p, div, etc.
function elem(name, contents) { // , options) {
  // XXX if we don't $() it IE will silently die
  var e = $(document.createElement(name));
  
  if (contents) {
    if (typeof(contents) == 'string') {
      // e.appendChild(document.createTextNode(contents))
      // XXX need to refactor how Places search results are populated before using proper dom building
      e.update(contents);
    } else {
      e.appendChild(contents);
    }
  }
  
  // if (options) options.each(function(k,v) { e[k] = v })
  
  return e;
}

// XXX prototype has a facility for this, i think..
function getElementsByClass(searchClass, node, tag) {
  var classElements = [];
  
  if (!node) node = document;
  if (!tag)  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;
}

// XXX don't need this.. should refactor it out and use Event.observe instead
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

// Used for counting characters in email redbox
function textCounter(elementId, counterId, maxlimit) {
    var field = document.getElementById(elementId);
    if (field.value.length > maxlimit) {
        // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
    } else {
        // otherwise, update 'characters left' counter
        var tag = document.getElementById(counterId);
        tag.firstChild.data = maxlimit - field.value.length;
    }
}

String.prototype.blank = function() { return this == '' || this == null }

/*
  Google Maps API helper functions
*/

function centerAndZoom(map, bounds) {
  var sw = bounds.getSouthWest();
  var ne = bounds.getNorthEast();
  var center = new GLatLng(
    (sw.lat() + ne.lat()) / 2,
    (sw.lng() + ne.lng()) / 2
  );
  map.setCenter(center, map.getBoundsZoomLevel(bounds));
}

/*
  Google AJAX Search - http://code.google.com/apis/ajaxsearch/documentation/reference.html
*/
var glocal_ctl, glocal_searcher;

function GoogleSearchCtl() {
  this.results = $('places_search_results');
  
  glocal_searcher = new GlocalSearch(); 
  glocal_searcher.setNoHtmlGeneration();
  glocal_searcher.setCenterPoint('94105'); // San Francisco
  // glocal_searcher.setAddressLookupMode(GlocalSearch.ADDRESS_LOOKUP_DISABLED)
  glocal_searcher.setSearchCompleteCallback(this, GoogleSearchCtl.prototype.searchComplete, [glocal_searcher]);
}

GoogleSearchCtl.prototype.formSubmit = function() {  
  if (Restaurant.validate_search()) {
    $('spinner').show();
    glocal_searcher.execute($F('name') + ' in ' + $F('location'));
  } else {
    $('spinner').hide();
  }
}

// This callback is fired after a Searcher completes its execute() call.
GoogleSearchCtl.prototype.searchComplete = function(searcher) {
  removeChildren(this.results);
  
  var post = 'name=' + escape($F('name')) + '&location=' + escape($F('location'));

  if ($F('board_id')) post += '&board_id=' + escape($F('board_id'));
  
  var params = {
    postBody: post,
    onComplete: function(t) { glocal_ctl.populateResults(eval(t.responseText), searcher.results) }
  }
  
  new Ajax.Request('/restaurants/search', params);
  
  $('restaurant_name').value     = $F('name');
  $('restaurant_location').value = $F('location');
  $('restaurant_board_id').value = $F('board_id');
}

// This fires during searchComplete to show the results to the user.
// Results container is currently hardcoded to #places_search_results for all instances of the SearchControl.
// 
// XXX needs refactoring
GoogleSearchCtl.prototype.populateResults = function(chow_places, google_places) {
  // alert(chow_places.inspect() + '\n\n\n' + google_places.inspect())
  
  $('spinner').hide();
  
  this.results.style.display = 'block';
  
  var chow_div = Restaurant.search_results_container('CHOW Places');
  this.results.appendChild(chow_div);
  
  // Chow  
  if (chow_places.length > 0) {    
    chow_places.each(function(cp, i){
      var div =  elem('div', cp.name + '<br>' + cp.location);
      div.addClassName('chow');
      div.addClassName('result');
      div.onclick = function() { Restaurant.select(escape(cp.name), escape(cp.location), escape(cp.phone)) }
    
      chow_div.appendChild(div);
    })
  } else {
    chow_div.appendChild(
      elem('p', 'Sorry, no CHOW Places found for that region.')
    )
  }
  
  // Google
  if (google_places.length > 0) {    
    var google_div = Restaurant.search_results_container('Other results by name and location');
    this.results.appendChild(google_div);
    
    // XXX has to be a for loop to use +continue+
    for (var j = 0; j < google_places.length; j++) {
      var gp = google_places[j];
      
      if (gp.phoneNumbers == null) {
        // alert('skipping: ' + gp.inspect() + '; no phone numbers')
        continue; // ignore junk
      }
      
      // skip google results that we think we already have in our db
      var dup = false;
      chow_places.each(function(cp){ dup = Restaurant.check_for_dup(cp, gp) })
      
      if (dup) {
        // alert('skipping: ' + gp.inspect() + '\n\n\n' + 'believed to be: ' + cp.inspect())
        continue;
        
      } else {
        var number = '';
        
        if (gp.phoneNumbers.length > 0) {
          gp.phoneNumbers.each(function(n) {
            // label certain valid types accordingly: http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GlocalResult
            if (n.type == 'fax' || n.type == 'mobile' || n.type == 'data') {
              number += n.type + ':&nbsp;';
            }
            number += n.number + '\n';
          })
        }
        
        var div = elem('div', gp.titleNoFormatting + '<br />' + gp.streetAddress + ', ' + gp.city + ', ' + gp.region);
        div.addClassName('result');
      /* prevaluate the parameters to avoid closing over gp, which preserves only its last value */
        div.onclick = new Function(
          "Restaurant.select(\"" + 
            escape(gp.titleNoFormatting) + "\",\"" + 
            escape(gp.streetAddress) + " " + escape(gp.city) + " " + escape(gp.region) + "\",\"" +
            escape(number) +
          "\")"
        )
        
        google_div.appendChild(div);    
      }
    }
  }
  
 /* var none_found = elem('p',
    'Not in list? <input type="button" onclick="$(\'places_add\').show(); $(\'places_search_results\').hide(); $(\'places_search_instructions\').hide()" value="Add a Place" />'
  )*/
  var none_found = ('p'," ");
  this.results.appendChild(none_found);
}


/*
  Main nav
*/
var UserNav = {
  init: function() {
    if (window.user_id != null) {
      // logged in
      $('logout_link').href += '?return_to=' + window.location.pathname;
    } else {
      // logged out
      $('login_link').href += '?return_to=' + window.location.pathname;
      $('signup_link').href += '?return_to=' + window.location.pathname;
    }
  }
}

/*
  The Boards: Topics and posts
*/
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:'parent_id=' + new_id + '&topic_id=' + topic_id + '&level=' + level, evalScripts:true})
    }

    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).update('');
    }
    
    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';
    }
  }
} // end Topic

var Post = {
  // TODO refactor out in favor of a scaleable 3rd party tab-UI library
  advancedToggle : function(id, which) {
    /*var other;
    
    if (which == 'place') { 
      other = 'photo';
      glocal_ctl = new GoogleSearchCtl();
    } else {
      other = 'place';
    }

    if ($(other + '_button_' + id) != null) {
      $(other + '_form_' + id).hide();
      $(other + '_button_' + id).removeClassName('button_active').addClassName('button');
    }     
    */
    var button = $(which + '_button_' + id);
    var form   = $(which + '_form_' + id);
    
    if (button.className.match(/button_active/)) {
      button.removeClassName('button_active');
      form.style.display = 'none';
    } else {
      button.addClassName('button_active');
      form.style.display = 'block';
    }
    
    // if ($('name')) $('name').focus()
  },
  
  editMode : function(id) {
    $('post_content_' + id + '_in_place_editor').hide();
    if ($('post_' + id + '_places')) {
      $('post_' + id + '_places').hide();
    }
    if($('post_' + id + '_reviewed_restaurant')){
      $('post_' + id + '_reviewed_restaurant').hide();
    }

    editors[id].enterEditMode('click');

    for (var index = 0; index < 4; index++) {
      try {
        $('inplace_photo_edit_' + id + '_index_' + index).show();
      } 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) {}
      }
    }
    var showPlacesList = function(){
      if ($('post_' + id + '_places')) {
        $('post_' + id + '_places').show();
      }
      if($('post_' + id + '_reviewed_restaurant')){
        $('post_' + id + '_reviewed_restaurant').show();
      }

    }
    var insertRatingAndPlaceModule = function(ipe, ipeForm){
      var divTag = document.createElement("div");
      ipeForm.insertBefore(divTag,ipeForm.firstChild);
      new Ajax.Request('/posts/rating_module?id='+id, {
        method: 'get',
        onSuccess: function(transport) {
          divTag.innerHTML = transport.responseText;
					// call restaurant rating and AC functions if restaurant id is set
					if ($('restaurant_id_edit_post_' + id) && $('restaurant_id_edit_post_' + id).value != '' ) {
						$('restaurant_review_checkbox_edit_post_' + id).checked = 'true';
						var checkBoxValue = $('restaurant_review_checkbox_edit_post_' + id).value;
						var ACBoardId = $('restaurant_board_edit_post_' + id).value;
						restaurant_rating('rating_edit_post_' + id);
						setRestaurantName('restaurant_id_edit_post_' + id,'restaurant_edit_post_' + id); 
						restaurant_auto_complete('restaurant_edit_post_' + id,'rest_autoCompleteContainer_edit_post_' + id, ACBoardId, 'restaurant_id_edit_post_' + id);
						showRestaurantInputs('rest_rating_module_edit_post_' + id, 'restaurant_name_edit_post_' + id, 'restaurant_review_checkbox_edit_post_' + id, checkBoxValue);
					}
       }
     });

     var placesUlTag =  document.createElement("div");
     ipeForm.insertBefore(placesUlTag, ipeForm.lastChild);
     new Ajax.Request('/posts/edit_linked_restaurant_module?id='+id, {
        method: 'get',
        onSuccess: function(transport) {
          placesUlTag.innerHTML = transport.responseText;
       }
     });
    
    }

    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,onFormCustomization: insertRatingAndPlaceModule,onLeaveEditMode: showPlacesList, htmlResponse:false})
    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) {
    var highlight_id = 'highlight-' + id;
    var post = $('post-content-' + id);
    
    if (!post.visible()) {
      post.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});
  }
} // end Post


/*
  Places
*/
var Restaurant = {
  // Are we adding a place from outside a thread or not? True if so, false if not i.e. in a topic.
  new_path: function() {
    return window.location.href.match(/places\/new#?$/);
  },
  
  validate_search: function(name, location) {
    if (!name) name = $F('name');
    if (!location) location = $F('location');
    
    if (name.blank()) {
      alert('Name is required!');
      $('name').focus();
      return false;
    } else if (location.blank()) {
      alert('Location is required!');
      $('location').focus();
      return false;
    }
    return true;
  },
  
  select : function(name, location, phone) {    
    var params = { postBody: 'restaurant[name]=' + name + '&restaurant[location]=' + location + '&restaurant[phone]=' + phone + '&restaurant[board_id]=' + $F('board_id') };
    new Ajax.Request('/restaurants/create', params);


    // Just redirect to edit the new place if coming from the detached form
    if (Restaurant.new_path()) return;
    
    glocal_ctl.results.hide();
    $('places_search_instructions').hide();
    $('places_add').hide();
    
    $('confirmation_name').update(unescape(name));
    $('places_search_confirmation').style.display = 'block';
    
    $('places_list').show();   
    
    // $('name').value = ''
    // $('location').value = ''
    
    $('restaurant_name').value = '';
    $('restaurant_location').value = '';
  },
  
  another : function() {
    $('places_search_confirmation').hide();
    $('places_search_results').hide();
    $('places_add').hide();
    
    $('places_search_instructions').show();
  },
  
  cancel_another: function() {
    $('places_add').hide();
    
    $('places_search_instructions').show();   
  },
  
  remove : function(place_id) {
    //var place  = $(place_id);
    //var places = $('places');
    //place.parentNode.removeChild(place);
    //if (places) $('fake_places').update(places.innerHTML);
	$(place_id).remove();
	Restaurant.addRemoveClass();
  },
  
  search_results_container: function(heading) {
    return elem('div', elem('p', heading).addClassName('topic_header_underline'));
  },
  
  check_for_dup: function(chow_place, google_place) {
    return google_place.titleNoFormatting == chow_place.name &&
    google_place.streetAddress == chow_place.street &&
    google_place.city == chow_place.city
  },
  
  add_restaurant: function(link) {
    if($('restaurant-list')){
		$('restaurant-list').insert(link,'bottom');
	} else {
		$('fake_places').insert(link,'bottom');
	}
  },
  
  addRemoveClass: function(){
		
	// remove class 'first' from all li tags in the manage links list and then add the class to the first li tag
	if($('restaurant-list')){
		var restaurant_list_li =  $$('#restaurant-list li');
		restaurant_list_li.each(function(li){
			li.removeClassName('first');							 							 
		});
		
		if(restaurant_list_li.length > 0){
			restaurant_list_li[0].addClassName('first');
		}
		
	}  
	  
  },
  
  addRestaurantLink: function(){
	  	  

    // continue if there's an id value and if that value is not already in the ids field
	if($("restaurant_link_id").value != '' && $("restaurant_link_ids").value.match($("restaurant_link_id").value) == null ){
		
  		var link = '<li id=\"restaurant_' + $("restaurant_link_id").value + '\">' + '<a href="#" class="remove" ' +
			'onclick="Restaurant.remove(\'restaurant_'+ $("restaurant_link_id").value + '\');' +
			'Restaurant.removeRestaurantLinkId(\''+ $("restaurant_link_id").value + '\'); return false">Remove</a>' + 
		    '<a href="/restaurants/'+ $("restaurant_link_id").value + '" class=\"r_name\" target=\"_blank\">' + 
			$("restaurant_link_name").value + '</a> - <span class=\"r_address\">' + 
			$("restaurant_link_address").value + '</span>';
        
		if($('manage_links_instructions')) $('manage_links_instructions').style.display='block';
        
		if($('restaurant-list')) $('restaurant-list').style.display='block';
  	    
		Restaurant.add_restaurant(link);
		
		Restaurant.addRemoveClass();
	
        
		$("restaurant_link_ids").value += $("restaurant_link_id").value + ',';
	  }
	},

	removeRestaurantLinkId: function(id){
		$("restaurant_link_ids").value = $("restaurant_link_ids").value.replace(id + ',', '');
	}
   
 
} // end Restaurant

function voteCountAdjust() {
  var field = document.getElementById('contest_entries_overview');
  var strongs = field.getElementsByTagName('strong');
  var voteWidths = new Array();
  for(var i=0; i<strongs.length; i++) {
    if(strongs[i].getAttribute('class') == 'vote_count') {
      var mom = strongs[i].parentNode;
      var newH = mom.offsetHeight;
      strongs[i].style.height = newH + 3 + "px";
      voteWidths[i] = strongs[i].offsetWidth;     
    }
  }
  voteWidths.sort(function(a,b){return (b - a)})
  for(var j=0; j<strongs.length; j++) {
    if(strongs[j].getAttribute('class') == 'vote_count') {
      if(strongs[j].offsetWidth < voteWidths[0]) {
        strongs[j].style.width = voteWidths[0] + "px";
      }
    }
  }
}

function voteCountAdjustIE() {
  var field = document.getElementById('contest_entries_overview');
  var strongs = field.getElementsByTagName('strong');
  var voteWidths = new Array();
  for(var i=0; i<strongs.length; i++) {
    if(strongs[i].className == 'vote_count') {
      var mom = strongs[i].parentNode;
      var newH = mom.offsetHeight;
      strongs[i].style.height = newH + 3 + "px";
      voteWidths[i] = strongs[i].offsetWidth;     
    }
  }
  voteWidths.sort(function(a,b){return (b - a)})
  for(var j=0; j<strongs.length; j++) {
    if(strongs[j].className == 'vote_count') {
      if(strongs[j].offsetWidth < voteWidths[0]) {
        strongs[j].style.width = voteWidths[0] + "px";
      }
    }
  }
}

function showMenu(menu, tog) {
  if(tog == 1) {
    $('menu_' + menu).style.display = "block";
    $('menu_' + menu + '_link').style.backgroundImage="url(/images/nav-bg-active.gif)";
    $('menu_' + menu + '_link').style.backgroundRepeat = "repeat-x";
    $('menu_' + menu + '_link').style.color = "#fff";
    $('menu_' + menu + '_link').style.textDecoration = "none";
  }else{
    $('menu_' + menu).style.display = "none";
    $('menu_' + menu + '_link').style.backgroundImage = "url(/images/nav-bg.gif)";
    $('menu_' + menu + '_link').style.backgroundRepeat = "repeat-x";
    $('menu_' + menu + '_link').style.backgroundColor = "#d7d7d7";
    $('menu_' + menu + '_link').style.color = "#bd0e13";
    $('menu_' + menu + '_link').style.height="22px";
    $('menu_' + menu + '_link').style.textDecoration = "none";
  }
}

function showActionMenu(menu, tog) {
  if(tog == 1) {
    $('menu_' + menu).style.display = "block";
  }else{
    $('menu_' + menu).style.display = "none";
  }
}


/* restaurant rating on topic pages */
function restaurant_rating(rating_field){
var rating_modules = YAHOO.util.Dom.getElementsByClassName('rating_module');

for (var i = 0; i < rating_modules.length; i++) {
  var ul = rating_modules[i];
  var li = YAHOO.util.Dom.getChildren(rating_modules[i]);
  for (var j = 0; j < li.length; j++) {
    YAHOO.util.Event.on(li[j], 'click', function(e){
      YAHOO.util.Event.preventDefault(e);
      for(x=1; x <=5; x++){
        YAHOO.util.Dom.removeClass(ul, 'stars' +x );
      }
      YAHOO.util.Dom.addClass(ul, this.className);
      var rating_value = this.className.split('stars')[1];
      YAHOO.util.Dom.get(rating_field).value = rating_value;
    });
  }

}


}
/* restaurant auto complete for boards, link to place, and places lists */
function restaurant_auto_complete(rest_input_field, AC_field, restaurant_board_id, restaurant_id_field, restaurant_name_field, restaurant_address_field){
	// rest_input_field is the id of the input that the user types the restaurant name into
	// AC_field is the id of the autocomplete container
	// restaurant_board_id is the board id
	// restaurant_id_field is the id of the input field that will hold the restaurant id once it's returned
	
	// the next two are optional and are used on 'link to a place' in topics
	// restaurant_name_field is the id of the input field that will hold the restaurant name once it's returned
	// restaurant_address_field is the id of the input field that will hold the restaurant address once it's returned
	
	
	if(restaurant_board_id == null && $('new_board_id') && $('new_board_id').value != 0) { // places list
		restaurant_board_id = $('new_board_id').value;	 
	} else if (restaurant_board_id == null) {
		restaurant_board_id = "";
	}
	
	var oDS = new YAHOO.util.XHRDataSource('/xhr/restaurant/autocomplete?board_ids=' + restaurant_board_id);

	// Set the responseType
	oDS.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
	oDS.responseSchema = {
	  resultsList : "response.docs",
	  fields : ["restaurant_name", "id", "address", "city", "country_state"]
	};
	
	
	// Instantiate the AutoComplete
	var oAC = new YAHOO.widget.AutoComplete(rest_input_field, AC_field, oDS);
	
	oAC.forceSelection = true;
	oAC.useIFrame = true;
	
	oAC.generateRequest = function(sQuery) {
	  return "&prefix=" + sQuery ;	  
	};
	
	// flatten results into an array
	oAC.resultTypeList = true;
	
	oAC.formatResult = function(oResultData, sQuery, sResultMatch) {
		var acAdress = (oResultData[2] != null) ? oResultData[2] : '';
		var acCity = (oResultData[3] != null) ? oResultData[3] : '';
		return '<span class="fr">' + acAdress + ', ' + acCity + '</span><span class="bold">' + oResultData[0] + '</span>';
	};
	
	oAC.itemSelectEvent.subscribe(function(oSelf, elItem , oData) {
		document.getElementById(restaurant_id_field).value = elItem[2][1];
		
		// the next two are used for link to a place
		if (restaurant_name_field !=''){
			document.getElementById(restaurant_name_field).value = elItem[2][0];
		}
		if (restaurant_address_field !=''){
			document.getElementById(restaurant_address_field).value = elItem[2][2] + ' ' + elItem[2][3] + ', ' + elItem[2][4];
		}
		
		// add name and address to input field unless we're in the manage links module
		if(rest_input_field == "link_to_restaurant_field") {
			$(rest_input_field).value = "";
		} else {
			$(rest_input_field).value = elItem[2][0] + ' ' + elItem[2][2] + ' ' + elItem[2][3] + ', ' + elItem[2][4];
		}
		
		// write html
		Restaurant.addRestaurantLink();
		
	});
	

  return {
      oDS: oDS,
      oAC: oAC
  };
}

function showRestaurantInputs(rest_rating_module, restaurant_name, restaurant_review_checkbox, checkbox_value) {

		if(checkbox_value == "0") {
				//show
				$(rest_rating_module).style.display ='block';
				$(restaurant_name).style.display ='block';
				$(restaurant_review_checkbox).value ='1';

		} else {
				//hide
				$(rest_rating_module).style.display ='none';
				$(restaurant_name).style.display ='none';
				$(restaurant_review_checkbox).value ='0';
		}

}

// write restaurant name to page if user is editing a previous post
function setRestaurantName(id_field, nameField){
	var idValue = document.getElementById(id_field).value;
	if(idValue=="") return;
	var sUrl = '/xhr/restaurant/get?id='+ idValue;	
	
	var restNameSuccess = function(o){
		if(o.responseText !== undefined){
			var restaurantResult = eval('(' + o.responseText + ')');
			//var restaurantResult = JSON.parse(o.responseText); // doesn't work in IE6
			document.getElementById(nameField).value= restaurantResult.response.docs[0].restaurant_name;	
		}
	};
	
	var restNameFailure = function(o){
		if(o.responseText !== undefined){
			document.getElementById(nameField).value= "Couldn't find Restaurant name";
		}
	};
	
	var callback =
	{
		success:restNameSuccess,
		failure:restNameFailure
	};

	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);

}


// autocomplete for sidebar and topics search bar
// takes the id of the input field and the autocomplete container
function chowAutoSuggest(input_id, AC_id) {
	
	var oDS = new YAHOO.util.XHRDataSource('/xhr/tags/autocomplete');

	// Set the responseType
	oDS.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
	oDS.responseSchema = { 
		 resultsList : "response.docs", 
		 fields : ["tag_name"]
	};

	// Instantiate the AutoComplete
	var oAC = new YAHOO.widget.AutoComplete(input_id, AC_id, oDS);
	oAC.generateRequest = function(sQuery) { 
			return "?prefix=" + sQuery ; 
	};
	
	oAC.autoHighlight = false;
	oAC.allowBrowserAutocomplete = false;
	oAC.animVert = false;
	oAC.useIFrame = true;

	return {
			oDS: oDS,
			oAC: oAC
	};
}

var goRecipePrint = {

	printNow : function() {	
		var isCtrl = false;
		var isP = false;
		if (document.getElementById( "printID" )) {
			document.getElementById( "printID" ).onclick = this.doPopup;
		}
		document.onkeydown = this.KeyDownCheck;
		document.onkeyup = this.KeyUpCheck; 			  
	},
	
	KeyUpCheck : function(e) {		
		var KeyID = (window.event) ? event.keyCode : e.keyCode;	 		 
		switch(KeyID){

	 		case 17:
	 		isCtrl = false;
	 		break;
		  
	 		case 224:
	 		isCtrl = false;
	 		break;
	  
	 		case 91://for safari
	 		isCtrl = false;
	 		break;	 
		}
	},  
	
	KeyDownCheck : function(e){
		var KeyID = (window.event) ? event.keyCode : e.keyCode;
		switch(KeyID){

			case 17:
			isCtrl = true;			
			break;
			  
			case 224:
			isCtrl = true;
			break;
		  
			case 91://for safari
			isCtrl = true;
			break;	 
		}
	  
		if (isCtrl && KeyID == 80){	
			var theURL = document.location.href; 
			recipeNumber = theURL.substring(theURL.length-5, theURL.length);
			printURL = "/print/recipe/" + recipeNumber;
			if (document.all){ window.parent; }//for IE6 because it losses focus
			document.location = printURL; 
			return false;  		  	  
		}		
	},
		
	doPopup : function() {
		var theURL = document.location.href; 
		recipeNumber = theURL.substring(theURL.length-5, theURL.length);
		printURL = "/print/recipe/" + recipeNumber;
		document.location = printURL;
		return false;
	}
}// end goRecipePrint object

// Manage Links in Post - Auto-linking restaurants

function sendPostContent(restaurant_link_id, restaurant_link_name, restaurant_link_address, restaurant_link_ids, open_manage_links, restaurant_list, manage_links){
	var board_id = $('board_id').value;
	var postContent = document.topic.elements['post_content'].value;
		
	
	// append title field to postContent if it exists
	if($('topic_title')) postContent += ' ' + $('topic_title').value;
	
	// if coming from a restaurant page and creating a new post, get restaurnat id from url and append it to xhr call
	if(document.location.toString().match('restaurant_id')){
		postContent += '&restaurantID=' + document.location.toString().split('restaurant_id=')[1].split('&')[0];
	}
	
	
	autoLinkRestaurantsUrl = '/xhr/linkPost?boardID=' + board_id;
	
	
	if($('open_manage_links')) $('open_manage_links').value = 1;
		
	YAHOO.util.Connect.asyncRequest('POST', autoLinkRestaurantsUrl, {
		
		success: function(e) {
			
			var restaurantResultsObj = YAHOO.lang.JSON.parse(e.responseText);
			
			// if results exist, carry on, otherwise exit
			if (restaurantResultsObj.restaurantsInfoResult) {
				var O = restaurantResultsObj.restaurantsInfoResult;
				if($('manage_links_instructions')) $('manage_links_instructions').style.display = 'block';
				if($('restaurant-list')) $('restaurant-list').style.display = 'block';
			} else { return }
				
				
			for (i=0; i < O.length; i++) {
				  
					$(restaurant_link_id).value = O[i].id;
					

					// the next two are used for link to a place
					if (restaurant_link_name !=''){
						$(restaurant_link_name).value = O[i].name;
					}
					if (restaurant_link_address !=''){
						$(restaurant_link_address).value = O[i].address.address[0] + ' ' + O[i].address.city + ', ' +  O[i].address.state;
					}
					Restaurant.addRestaurantLink();
														
			} // end for loop																	
			
			
		} // end success
	}, 'postContent=' + encodeURIComponent(postContent)); //end ajax request
	
} // end Auto-linking restaurants

// Don't submit form when enter key is pressed
function disableEnterKey(e,inputFieldId) {
     var key=e.keyCode || e.which; // IE / firefox     
     return (key != 13);
     if ($(inputFieldId)) {
	    $(inputFieldId).value = '';
	   }  
} // end disableEnter Key


// js for photo uploads
var uploadPhoto = {

	filebrowsers: 0,

	addNewFileBrowser: function(){

		//detect change event on file selector
		YAHOO.util.Event.addListener( document.getElementById('add-photo-filebrowse-'+uploadPhoto.filebrowsers), 'change', function(){

			if( this.value != '' ){
				//add filename to input
				document.getElementById('add-photo-filetext-'+uploadPhoto.filebrowsers).value = this.value;
				
			}

		});
		
	},
	
	init: function(){

        //register events
        uploadPhoto.addNewFileBrowser();
	}
}

// initialize fake photo input
function createFileInput() {
		uploadPhoto.init();
		
	}
