if (console == undefined) {
  var console = {};
  console.log = function() {};
}

var trace = console.log;

function findRevision(v)
{
  var regex = new RegExp('Revision ' + v + ':');
  var ptags = document.getElementsByTagName('p');
  for (var i = 0; i < ptags.length; i++) {
    if (ptags[i].firstChild.nodeName == 'STRONG') {
      var strong = ptags[i].firstChild;
      if (strong.innerHTML.match(regex))
	return ptags[i];
    }
  }
  return false;
}

var Comments =
{
  url: APP_ROOT + '/comments.php',
  form: null,
  formHeight: 0,
  exthelp: null,
  genhelp: null,
  spinner: APP_ROOT + '/inc/gfx/spinner-ffffff.gif',
  validXML: false,

  Load: function(path)
  {
    this.form = new Fx.Slide('comments-form', {
      transition: Fx.Transitions.Quad.easeInOut,
      duration: 300
    }).chain(function() {
      document.location.href = '#comments-form';
    });

    this.spinner = new Asset.image(this.spinner, { width: 17, height: 17 });

    var ct = $('comments-display');
    var cf = $('comments-form');

    this.spinner.injectInside(ct);

    //! Comments
    new Ajax(this.url, {
      data: { path: path },
      onSuccess: function(data)
      {
	ct.setHTML(data);
	if (document.location.hash.length > 0) {
	  document.location.href = document.location.hash;
	  try {
	    $(document.location.hash.substring(1))
	      .setStyle('outline', '1px solid #6DA4ED');
	  }
	  catch (e) {}
	}
      }
    }).request();

    //! Form
    new Ajax(this.url, {
      data: {
	path: path,
	action: 'form'
      },
      onSuccess: function(data)
      {
	cf.setHTML(data);
	Comments.form.hide();
	var cb = $('cremember');

	$('cform').addEvent('submit', function(e) {
	  new Event(e).stop();
	  Comments.Send();
	});

	cb.addEvent('focus', function() {
	  this.getParent().addClass('cb-focus');
	});

	cb.addEvent('blur', function() {
	  this.getParent().removeClass('cb-focus');
	});

	cb.addEvent('click', function() {
	  var c = this.parentNode.hasClass('cb-on');
	  this.getParent().removeClass((c ? 'cb-on' : 'cb-off'));
	  this.getParent().addClass((c ? 'cb-off' : 'cb-on'));
	});

	var l = cb.getParent();
	cb.setStyle('visibility', 'hidden');
	l.addClass(cb.checked ? 'cb-on' : 'cb-off');

	$('caction').value = 'add';
	$('csecret').value = $('sessholder').className;

	Comments.exthelp = new Fx.Slide('extended-help', {
	  transition: Fx.Transitions.Quad.easeInOut,
	  duration: 300
	}).hide();
	Comments.genhelp = new Fx.Slide('general-help', {
	  transition: Fx.Transitions.Quad.easeInOut,
	  duration: 300
	});
      }
    }).request();
  },

  ToggleForm: function()
  {
    this.form.slideIn();
  },

  Preview: function()
  {
    $('caction').value = 'preview';
    this.Send();
  },

  Send: function()
  {
    var name    = $('cname');
    var www     = $('cwww');
    var comment = $('ccomment');

    if (www.value.length > 0 && www.value.substr(0, 7) != 'http://')
      www.value = 'http://' + www.value;

    var errors = [];

    if (name.value.length < 2)
      errors.push("Please fill in your name!");

    if (comment.value.length < 5)
      errors.push("Please give me at least five characters of comment!");

    if (errors.length > 0) {
      var str = "THERE'S SOME ERRORS:\n";
      str += errors.join("\n");
      alert(str);
      return false;
    }

    var sp = Comments.spinner.clone();

    sp.addClass('fs-absolute');
    sp.injectInside($('form-spinner'));

    Comments.validateAndSubmit($('ccomment').value);

    return false;
  },

  validateAndSubmit: function(text)
  {
    new Ajax(Comments.url, {
      async: false,
      data: {
	path: 'temp',
	action: 'validate',
	comment: text
      },

      onSuccess: function(res)
      {
	res = Json.evaluate(res);
	if (res.code == 0) {
	  alert("YOU HAVE AN ERROR IN YOUR COMMENT:\n" + res.value);
	  $('form-spinner').empty();
	  return false;
	}
	//! Send the form
	else {
	  $('cform').send({
	    update: 'comments-display',
	    onComplete: function(result)
	    {
	      Comments.toggleFields();
	      $('form-spinner').empty();
	      if ($('caction').value == 'add')
		$('ccomment').value = '';
	      $('caction').value = 'add';
	    }
	  }).chain(function() {
	    Comments.toggleFields();
	  });
	}
      }
    }).request();
  },

  toggleFields: function()
  {
    var inps = $('cform').getElements('input[type!=hidden]');
    inps.each(function(inp) {
      inp.disabled = !inp.disabled;
    });
  },

  ExtendedHelp: function(caller)
  {
    if (caller.state == undefined)
      caller.state = 0;

    caller.state = !caller.state;

    var form = $('comments-form');

    if (!Comments.formHeight)
      Comments.formHeight = form.getSize().size.y;

    if (caller.state)
      form.setStyle('overflow', 'auto');
    else
      form.setStyle('overflow', 'hide');

    caller.setText(caller.state ? 'Less help' : 'More help');
    Comments.exthelp.toggle();
    Comments.genhelp.toggle();
  }
};

window.addEvent('domready', function() {
  if (document.location.pathname.indexOf('/changelog/') > -1) {
    var qs = document.location.search;
    if (qs) {
      var parts = qs.substring(1).split('&');
      var part = null;
      while (part = parts.shift()) {
	var pair = part.split('=');
	var k = pair[0];
	var v = pair[1];

	if (k == 'rev') {
	  var rev = findRevision(v);
	  if (rev) {
	    rev.className          = 'highlighted';
	    rev.id                 = 'highlighted-changelog';
	    document.location.href = '#highlighted-changelog';
	    break;
	  }
	}
      }
    }
  }

  // Documentation site
  if (document.location.pathname.indexOf('/doc/') > -1 && $('todo')) {
    var todo = new Fx.Slide('todo', {
      transition: Fx.Transitions.Quad.easeInOut
    });
    todo.hide();
    $('toggle-todo').addEvent('click', function(e) {
      e = new Event(e);
      if (this.getText() == 'Show')
	this.setText('Hide');
      else
	this.setText('Show');
      todo.toggle();
      e.stop();
    });
  }
});

var News =
{
  current: null,
  List: function(extended)
  {
    extended = extended == undefined ? '' : 'yes';
    var target = $('news-wrapper');
    new Ajax(APP_ROOT + '/news.php', {
      data: { extended: extended },
      onSuccess: function(data) {
	target.setHTML(data);
	var as = target.getElements('a');
	as.each(function(a) {
	  var href = a.href;
	  var id = href.substring(href.indexOf('=')+1);
	  a.addEvent('click', function(e) {
	    new Event(e).stop();
	    if (News.current) {
	      News.current.setStyle('font-weight', 'normal');
	    }
	    this.setStyle('font-weight', 'bold');
	    this.getParent().toggleClass('spinner');
	    News.current = this;
	    News.LoadItem(id, this);
	    return false;
	  });
	});
      }
    }).request();
  },

  LoadItem: function(id, caller)
  {
    new Ajax(APP_ROOT + '/news.php', {
      data: {
	action: 'view',
	id: id
      },

      onSuccess: function(data) {
	caller.getParent().toggleClass('spinner');
	var e = $('news-display');
	var runfx1 = true;
	if (!e) {
	  var e = new Element('div', { id: 'news-display' });
	  var h1 = $('inner-content').getElements('h1');
	  if (h1.length > 0) {
	    e.injectAfter(h1[0]);
	  }
	  else {
	    trace("NO H1");
	    e.injectTop($('inner-content'));
	    e.setStyle('margin-top', 20);
	    document.location.href = '#stripe';
	  }
	  
	  e.setStyle('opacity', 0);
	  runfx1 = false;
	}

	var fx = new Fx.Styles(e, { 
	  duration: 200, 
	  wait: false,
	  transition: Fx.Transitions.Quad.easeIn
	});
	
	if (runfx1)  {
	  fx.start({ opacity: 0 }).chain(function() {
	    e.empty();
	    e.setHTML(data);
	    fx.start({ opacity: 1 });
	  });
	}
	else {
	  e.setHTML(data);
	  fx.start({ opacity: 1 });
	}
      }
    }).request();
  },
  
  RemoveDisplay: function() 
  {
    var fx = new Fx.Styles($('news-display'), { 
      duration: 200, 
      wait: false,
      transition: Fx.Transitions.Quad.easeIn
    });

    fx.start({ opacity: 0 }).chain(function() {
      $('news-display').remove();
      if (News.current) 
	News.current.setStyle('font-weight', 'normal');
    });
    
    return false;
  }
};

function relay(message)
{
  if (window.confirm(message))
    return true;

  return false;
}
