/*function init() { 
  var widgets = YAHOO.util.Dom.getElementsByClassName("toggle");
  for(var i=0;i<widgets.length;i++){
    YAHOO.util.Event.addListener(widgets[i], "focus", TextWidget.removeDefault);
    YAHOO.util.Event.addListener(widgets[i], "blur", TextWidget.restoreDefault);
  }
  setMaxLength(); // http://www.quirksmode.org/dom/maxlength.html
} 
YAHOO.util.Event.onDOMReady(init);

var TextWidget = {
  // clears or resets the search term box
  removeDefault: function(e){
    var element = YAHOO.util.Event.getTarget(e);
    // if (element.value == element.title){
    if (element.value == "Enter Your Movie Title Here"){
      YAHOO.util.Dom.removeClass(element,'toggle');
      element.value='';
    }
  },
  restoreDefault: function(e){
    var element = YAHOO.util.Event.getTarget(e);
    if(element.value == ''){
      YAHOO.util.Dom.addClass(element,'toggle');
      YAHOO.util.Dom.removeClass(element,'black');
      // element.value = element.title;
      element.value = "Enter Your Movie Title Here";
    }
  }
}
*/
var Cookie = {
  create: function(name, value, days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
  },
  read: function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
  },
  erase: function(name){
    this.create(name,"",-1);
  }  
}

var sort_name = 'classical';
var movie_sort_name = 'title';
var showtime_direction = 'asc';
var showtime_sort_name = 'direction';


var Review ={
  getReviewSortField: function(attr){
    switch(attr){
      case 'classical':   return 'sort4'; break;
      case 'source':      return 'sort1'; break;
      case 'rating':      return 'sort2'; break;
      case 'popularity':  return 'sort3'; break;
    }
  },
  getMovieSortField: function(attr){
    switch(attr){
      case 'title':       return 'sort1'; break;
      case 'popularity':  return 'sort2'; break;
      case 'year':        return 'sort3'; break;
      case 'reviews':     return 'sort4'; break;
    }
  },
  zebraStripe: function(_parent){
    // add the zebra striping  
    var items = _parent.getElementsByTagName('LI');
    var add_alt = false;
    for(var i=0; i < items.length; i++) {
      var item = new YAHOO.util.Element(items[i]);
      if(add_alt){
        item.addClass('alt');
      }
      else{
        item.removeClass('alt');
      }    
      add_alt = !add_alt;
    }
  },
  doMovieSort: function(elem,q){
    // If elem is the active link, it will have a direction attribute
    // If elem is not the active link, the direction will be null, in which case we assume 'asc'
    // If it's *is* the active element, we reset the direction attribute to the opposite
    attr = elem.getAttribute('sort');
    direction = elem.getAttribute('direction');
    if(direction==null || direction=='') direction = 'asc';
    elem.setAttribute('direction',direction=='asc' ? 'desc' : 'asc');

    // Set the sort_name to stay current
    movie_sort_name = attr;

    // Sort the list
    // The title sort needs to be reversed
    _parent = new YAHOO.util.Element('result_list');
    myList = new Review.bubbleSort(_parent);
    var movie_sort_direction = movie_sort_name=='title' ? (direction == 'asc' ? 'desc' : 'asc') : direction
    myList.sort(Review.getMovieSortField(attr), movie_sort_direction);

    // add the zebra striping  
    Review.zebraStripe(_parent);

    // add the appropriate class names and html to the sidebar
    items = (new YAHOO.util.Element('sort_nav')).getElementsByTagName('A');
    for(var i=0; i < items.length; i++) {
      var item = new YAHOO.util.Element(items[i]);
      rel = item.get('element').getAttribute('sort');
      item.removeClass('desc');
      item.removeClass('asc');

      // construct the url and set the href
      var url = '/movies';
      url += '?q='+q
      url += '&sort='+rel
      if(rel==attr) url += '&direction='+direction
      item.get('element').setAttribute('href',url)

      if(rel==attr){
        item.addClass('active-tab');
        item.addClass(direction);
      }
      else{
        item.removeClass('active-tab');
        item.get('element').setAttribute('direction',null);
      }
    }

    // set the cookie
    Cookie.create('movies_sort',movie_sort_name);
    Cookie.create('movies_direction',direction);  
  },

  doSort: function(elem,uid){
    // If elem is the active link, it will have a direction attribute
    // If elem is not the active link, the direction will be null, in which case we assume 'asc'
    // If it's *is* the active element, we reset the direction attribute to the opposite
    attr = elem.getAttribute('sort');
    direction = elem.getAttribute('direction');
    if(direction==null || direction=='') direction = 'asc';
    elem.setAttribute('direction',direction=='asc' ? 'desc' : 'asc');

    // Set the sort_name to stay current
    sort_name = attr;

    // sort the list
    _parent = new YAHOO.util.Element('result_list');
    myList = new Review.bubbleSort(_parent);
    var review_sort_direction = sort_name=='rating' ? (direction == 'asc' ? 'desc' : 'asc') : direction
    myList.sort(Review.getReviewSortField(attr), review_sort_direction);

    // add the zebra striping  
    Review.zebraStripe(_parent);

    var outer_pane;

    // add the appropriate class names and html to the sidebar
    items = new YAHOO.util.Element('sort_nav').getElementsByTagName('A');
    var item;
    for(var i=0; i < items.length; i++) {
      var item = new YAHOO.util.Element(items[i]);
      rel = item.get('element').getAttribute('sort');
      pane = item.get('element').getAttribute('pane');
      outer_pane = pane;
      item.removeClass('desc');
      item.removeClass('asc');

      // construct the url and set the href
      var url = '/movies';
      url += '/'+uid
      if(pane!='reviews') url+='/'+pane;
      url += '?sort='+rel
      if(rel==attr) url += '&direction='+direction
      item.get('element').setAttribute('href',url)

      if(rel==attr){
        item.addClass('active-tab');
        item.addClass(direction);
      }
      else{
        item.removeClass('active-tab');
        item.get('element').setAttribute('direction',null);
      }
    }

    // set the cookie
    Cookie.create('reviews_sort',sort_name);
    Cookie.create('reviews_direction',direction);
  },

  doShowtimeSort: function(elem,attr,q){
    _parent = new YAHOO.util.Element('theaters');

    // only change the showtime_direction of the sort if it's the same link
    if(showtime_sort_name==attr){
      showtime_direction = showtime_direction == 'asc' ? 'desc' : 'asc';
    }
    showtime_sort_name = attr;

    // sort the list
    myList = new Review.bubbleSort(_parent);
    myList.sort(attr, showtime_direction);

    // add the appropriate class names and html to the sidebar
    items = new YAHOO.util.Element('sort_nav').getElementsByTagName('A');
    var item;
    for(var i=0; i < items.length; i++) {
      item = new YAHOO.util.Element(items[i]);
      rel = item.get('element').getAttribute('sort');
      item.removeClass('desc');
      item.removeClass('asc');

      // construct the url and set the href
      var url = '/showtimes';
      url += '?q='+q
      url += '&sort='+rel+'&showtime_direction='+showtime_direction
      item.get('element').setAttribute('href',url)

      if(rel==attr){
        item.addClass('active-tab');
        item.addClass(showtime_direction);
      }
      else{
        item.removeClass('active-tab');
      }
    }

    // set the cookie
    Cookie.create('showtimes_sort',showtime_sort_name);
    Cookie.create('showtimes_showtime_direction',showtime_direction);  
  },

  bubbleSort: function(_parent){
    // Original JavaScript code by Chirp Internet: www.chirp.com.au
    // Please acknowledge use of this code by including this header.
    var _parent = _parent;

    // build array of 'child' nodes
    var items = _parent.getElementsByTagName('LI');
    var N = items.length;

    // define private methods
    var get = function(i,attr){
      var retval = items[i].getAttribute(attr);
      return parseFloat(retval) == retval ? parseFloat(retval) : -1;
    }

    var compare = function(val1, val2, dir){
      if(val1 == -1) return false;
      else if(val2 == -1) return true;
      else return (dir=='desc') ? val1 > val2 : val1 < val2;
    }

    var exchange = function(i, j){
      _parent.insertBefore(items[i], items[j]);
    }

    // define public method
    this.sort = function(attr, dir){
      for(var j=N-1; j > 0; j--) {
        for(var i=0; i < j; i++) {
          if(compare(get(i+1,attr), get(i,attr), dir)) {
            exchange(i+1, i);
          }
        }
      }
    }
  }
}


/* Registration */
showOther = function(){
  if(document.getElementById('user_hear_about')=='other'){
    (new YAHOO.util.Element('user_hear_about_other')).setStyle('display','block');
    document.getElementById('user_hear_about_other').value='Please tell us how';
  }
  else{
    (new YAHOO.util.Element('user_hear_about_other')).setStyle('display','none');
    document.getElementById('user_hear_about_other').value='';
  }
}

/* Forums */
var TopicForm = {
  editNewTitle: function(txtField) {
    document.getElementById('new_topic').innerHTML = (txtField.value.length > 5) ? txtField.value : 'New Topic';
  }
}

var EditForm = {
  // show the form
  init: function(postId) {
    (new YAHOO.util.Element('edit-post-' + postId + '_spinner')).setStyle('display','block');
    this.clearReplyId();
  },

  // sets the current post id we're editing
  setReplyId: function(postId) {
    document.getElementById('edit').setAttribute('post_id', postId.toString());
    new(YAHOO.util.Element('posts-' + postId + '-row')).addClass('editing');
    if(document.getElementById('reply')){
      (new YAHOO.util.Element('reply')).setStyle('display','none');
    }
  },

  // clears the current post id
  clearReplyId: function() {
    var currentId = this.currentReplyId()
    if(!currentId || currentId == '') return;

    var row = new YAHOO.util.Element('post_' + currentId + '-row');
    if(row) row.removeClassName('editing');
    document.getElementById('edit').setAttribute('post_id', '');
  },

  // gets the current post id we're editing
  currentReplyId: function() {
    return document.getElementById('edit').getAttribute('post_id');
  },

  // checks whether we're editing this post already
  isEditing: function(postId) {
    if (this.currentReplyId() == postId.toString())
    {
      (new YAHOO.util.Element('edit')).setStyle('display','block');
      document.getElementById('edit_post_body').focus();
      return true;
    }
    return false;
  },

  // close reply, clear current reply id
  cancel: function() {
    this.clearReplyId();
    (new YAHOO.util.Element('edit')).setStyle('display','none');
  }
}

clearText = function(element){
  element.value = '';
}

function setMaxLength() {
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength')) {
			var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = '<span>0</span>/'+x[i].getAttribute('maxlength');
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = x[i].onchange = checkMaxLength;
			x[i].onkeyup();
		}
	}
}

function checkMaxLength() {
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (currentLength > maxLength)
		this.relatedElement.className = 'toomuch';
	else
		this.relatedElement.className = '';
	this.relatedElement.firstChild.nodeValue = currentLength;
	// not innerHTML
}

function scrollToElementAndFocus(elementToScroll, elementToFocusOn){
  elementToFocusOn.focus();
  var region = YAHOO.util.Dom.getRegion(elementToScroll);
  window.scrollTo(region[0],region[1]);
}

/*
	Toggles toggles the display of the short/full descriptive text in reviews list
*/

function toggleText(id)
{
	if (id == 'more')
	{
		document.getElementById('long').style.display = 'block';
		document.getElementById('more').style.display = 'none';
	}
	else
	{
		document.getElementById('long').style.display = 'none';
		document.getElementById('more').style.display = 'inline';
	}
}