var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + ';path=/' + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') = '1');
  },

  remove: function(name, value) {
	  var c = Cookie.get(name);
	  c = c.split('|').without(value);
	  return Cookie.set(name, c);
  },

  push: function(name, value) {
	  var c = Cookie.get(name);
	  if (c == null || c == '') {
		  c = [value];
	  } else {
	    c = c.split('|');
  	  c.push(value);
	  } // end if
	
	  c = c.compact();
	  return Cookie.set(name, c.join('|'));
  }
};

////////////////////////////////////////////////////////////

function sorttable_callback(th) {
	var table = th.sorttable_tbody;
	//console.log(table);
	var odd = false;
	$A(table.childNodes).each(function(row) {
		odd ? row.addClassName('odd') : row.removeClassName('odd');
		odd = !odd;
	});
}

function initSearchResults() {
  var rows = $$('#sr tr');
  rows.each(function(row) {
	  if (row.id.match(/_/)) {
      row.onclick = viewUser;
    } // end if id != null
  });
}

function viewUser() {
  // alert(this.id);
  var user_id = this.id.split(/_/)[1];
  window.location.href = '/users/edit/' + user_id;
}


function toggleBranch(dom_id) {
	var ul = $(dom_id);
	var handle = dom_id.split('-')[1];
	console.log(ul.hasClassName('loaded'));
	if (ul.hasClassName('loaded')) {
	  //ul.toggle();	
	  if (ul.style.display == 'none') {
		  ul.show();
		  Cookie.remove('hidden_branches', handle);
	  } else {
		  ul.hide();
		  Cookie.push('hidden_branches', handle);
	  } // end
	}	else {
  	new Ajax.Updater(dom_id, '/admin/show_branch/' + handle, {
	    onSuccess: function(r) { 
		    ul.addClassName('loaded'); 
		    ul.show(); 
		  } // end onSuccess
    });
  } // end if
} // end toggleBranch


function doProgress(show) {
	show ? Element.show('progress') : Element.hide('progress');
}

// global AJAX handlers
var myGlobalHandlers = {
  onCreate: function() {
    if (Ajax.activeRequestCount>0) {
      doProgress(true);
    } // end if
  },

  onComplete: function(request) {
    var status = request.transport.status;

    if (Ajax.activeRequestCount==0) {
      doProgress(false)
    } // end if
  }
};

Ajax.Responders.register(myGlobalHandlers);