
var PageImage = Class.create({
	initialize: function(imageId, caption, credit) {
		this.imageId = imageId;
		this.caption = caption;
		this.credit = credit;
	},
	
	getSrc: function() {
		return "/image/" + this.imageId;
	}
});

var ArticleForm = Class.create({
  initialize: function(containerId, bodyFieldId) {
	this.containerId = containerId;
    this.bodyFieldId = bodyFieldId;
    this.pageImages = [];
  },

  setPageImages: function(images) {
	this.pageImages = images;
  },
	
  numPages: function() {
    var n = 1;
	var index = 0;
	var text = $(this.bodyFieldId).value;
	while (true) {
      text = text.substring(index + ArticleForm.PAGE_BREAK.length);
	  index = text.indexOf(ArticleForm.PAGE_BREAK);
      if (index == -1) break;
	  n++;
    }
    return n;
  },

  appendElements: function(pageNum) {
	var pageImage = this.pageImages[pageNum-1];
	var tbody = Builder.node('tbody');
	var divider = Builder.node('tr', Builder.node('td', {colspan:2, className:"divideStyle"}) );
    //var divider = Builder.node('tr', [ Builder.node('td', {className:'type'}), Builder.node('td', {className:'type'}) ]);
    tbody.appendChild(divider);

    if (pageImage) {
        //changed 'name' to 'id'
        var hiddenImgValue = Builder.node('input', {name:'image-id-'+pageNum, id:'image-id-'+pageNum, type:'hidden', value:pageImage.imageId});
        tbody.appendChild(hiddenImgValue);
	}
	
	var src = pageImage ? pageImage.getSrc() : "/images/no-image.png";
	var image = Builder.node('tr', [Builder.node('td', "Page " + pageNum + " Image"), Builder.node('td', {colspan:2}, Builder.node('img', {src:src}))]);
	tbody.appendChild(image);

    //remove image button
    if (pageImage) {
        var imageBut = Builder.node('tr', [Builder.node('td', "Remove Page " + pageNum + " Image"), Builder.node('td', {colspan:2}, Builder.node('input', {id:'reset-id-'+pageNum, type:'button', value:'Remove Image'}))]);
        imageBut.onclick = function() {
            document.getElementById('image-id-'+pageNum).value = '';
            document.getElementById('reset-id-'+pageNum).value = 'Image Removed';
            tbody.removeChild(hiddenImgValue);
            tbody.removeChild(image);
        };
        tbody.appendChild(imageBut);
	}
    //end remove image button
		
	var fields = ["image-file", "caption" , "credit"];
    var types  = ["file" ,      "textarea", "textarea"  ];
    var labels = ["File" ,      "Caption" , "Credit"];

    for (var i = 0; i < fields.length; i++) {
	    var field = fields[i];
	    var type = types[i];
	    var label = "Page " + pageNum + " " + labels[i];
	
	    var name = field + "-" + pageNum;
	    var value = "";
        if (type == "textarea" && pageImage) {
	        value = pageImage[field];
        }

        var tr = Builder.node('tr', { className: "prop" });
        var td = Builder.node('td', { className: "name" });

        //td.appendChild(Builder.node('label', { for:name }, label));
        td.appendChild(Builder.node('label', { htmlFor:name }, label));
        tr.appendChild(td);

        td = Builder.node('td', { className: "value" });
        
        var input = null;
        if (type == 'file') {
	      input = Builder.node('input', { name:name, type:'file' });
	    } else if (type == 'textarea') {
		  input = Builder.node('textarea', {name:name}, value);
	    }
	    input.width = 400;
        td.appendChild(input);
        tr.appendChild(td);
        tbody.appendChild(tr);

        $(this.containerId).appendChild(tbody);
    }
  },
    
  renderImageInputs: function() {
    var n = this.numPages();
    for (var i = 1; i <= n; i++) {
	  this.appendElements(i);
    }
  }
    
});
ArticleForm.PAGE_BREAK = "---";

var ContentAutoCompleter = Class.create({
	
  initialize: function(callback) {
	new Form.Element.Observer($(ContentAutoCompleter.SEARCH_INPUT_ID), 0.2, this.query.bind(this));
	var self = this;
	$(ContentAutoCompleter.SEARCH_INPUT_ID).onblur = function() { setTimeout(self.clearResults, 2000) }
	this._callback = callback;
  },

  showMode: function() {
	$(ContentAutoCompleter.SEARCH_CONTAINER).hide();
	$(ContentAutoCompleter.SEARCH_INPUT_ID).clear();
	$(ContentAutoCompleter.SHOW_CONTAINER_ID).appear();
  },

  searchMode: function() {
	$(ContentAutoCompleter.SHOW_CONTAINER_ID).hide();
	
	$(ContentAutoCompleter.SEARCH_CONTAINER).appear();
	$(ContentAutoCompleter.SEARCH_CANCEL_ID).appear();
  },

  callback: function(content) {
	
	this.content = content;
	$(ContentAutoCompleter.SHOW_TITLE_ID).update(this.content.title);
    this.showMode();
    if (this._callback) this._callback(content);
  },

  clearResults: function() {
	$(ContentAutoCompleter.RESULTS_CONTAINER_ID).update('');
  },

  query: function(el, value) {
	if (value == '') return this.clearResults();
	
	var callback = this.callback.bind(this); // needed to bind below
	
	new Ajax.Request('/admin/content/searchAJAX?q='+value, { 
	  method: 'get', 
	  onSuccess: function(transport) {
		var json = eval('(' + transport.responseText +')');
		var results = json[ContentAutoCompleter.JSON_KEY];
		
		var table = Builder.node('table', { cellpadding:0, cellspacing:0 });
        var tbody = Builder.node('tbody');
	    for (var i = 0; i < results.length; i++) {
		  var content = results[i];
		  var type = ContentAutoCompleter.LABELS_FOR_TYPES[content.type];
          var tr = Builder.node('tr', [ Builder.node('td', content.title), Builder.node('td', {className:'type'}, type) ]);
          tr.style.cursor = 'pointer';
	      tr.content = content;
	      tr.onclick = function() { callback(this.content) };
          tbody.appendChild(tr);
	      table.appendChild(tbody);
	    }
	
		$(ContentAutoCompleter.RESULTS_CONTAINER_ID).update(table);
		
	  }
	});
  }

});

ContentAutoCompleter.JSON_KEY = 'results'; // FIXME: not needed if grails json builder can return a top-level array
ContentAutoCompleter.SEARCH_CONTAINER = 'ac-c';
ContentAutoCompleter.SEARCH_INPUT_ID = 'ac-title';
ContentAutoCompleter.SHOW_CONTAINER_ID = 'selected-content';
ContentAutoCompleter.SHOW_TITLE_ID = 'selected-title';
ContentAutoCompleter.SEARCH_CANCEL_ID = 'search-cancel';
ContentAutoCompleter.RESULTS_CONTAINER_ID = 'ac-results';
ContentAutoCompleter.LABELS_FOR_TYPES = {"content.ArticleRevision":"article"};

var EditorPickForm = Class.create({
	
  selectContent: function(content) {
    $('content-id').value = content.id;	
    $('content-title').update(content.title);
    $('content-dek').update(content.dek);

	// these are not displayed for a new editor's pick (id == 0)
	$('title-row').appear();
	$('dek-row').appear();
  },
	
  showTitleOverride: function() {
    $('content-title-c').hide();
	$('title-override-c').appear();
	$('titleOverride').value = $('content-title').innerHTML;
  },

  hideTitleOverride: function() {
    $('content-title-c').appear();
	$('title-override-c').hide();
	$('titleOverride').value = '';
  },

  showDekOverride: function() {
    $('dek-c').hide();
	$('dek-override-c').appear();
	$('dekOverride').innerHTML = $('content-dek').innerHTML;
  },
	
  hideDekOverride: function() {
    $('dek-c').appear();
	$('dek-override-c').hide();
	$('dekOverride').innerHTML = '';
  }

});

var RelatedContentForm = {

  selectContent: function(content) { 
	var parentId = $('related-content-parent-id').value;
    new Ajax.Request('/admin/relatedContent/save', {
	  method: 'post',
	  postBody: 'parent.id='+parentId+'&child.id='+content.id,
	  onSuccess: RelatedContentForm.handleSuccess
	});
  },


  handleSuccess: function(transport) { 
	$('related-content').update(transport.responseText);
  
    $(ContentAutoCompleter.SHOW_CONTAINER_ID).hide();
	$(ContentAutoCompleter.SEARCH_CONTAINER).appear();
	$(ContentAutoCompleter.SEARCH_CANCEL_ID).hide();
  },

  'delete': function(id) {
	new Ajax.Request('/admin/relatedContent/delete', {
	  method: 'post',
	  postBody: 'id='+id,
	  onSuccess: RelatedContentForm.handleSuccess
    });
  }
      
};

var WebinarForm = {
	showOrHideScheduledTime: function(show) {
		$('scheduled-time-row').style.display = show ? 'table-row' : 'none';
	} 
}

var Tag = Class.create({
	
  initialize: function(json) {
	this.id = json['id'];
    this.name = json['name'];
  }

});

var TagSearch = Class.create({
	
  initialize: function(input, resultsContainer, url) {
	this.input = input;
	var self = this;
	$(input).onblur = function() { setTimeout(function() { $(resultsContainer).update(''); }, 1000) };
	this.resultsContainer = resultsContainer;
	this.url = url;
	with(this) { new Form.Element.Observer(input, 0.2, search.bind(this)); }
  },

  parseValue: function(value) {
	return value.split(',').last().replace(' ', '');
  },

  remainderForTag: function(tag, partial) {
	return tag.substring(partial.length);
  },

  search: function(input, value) {
	var query = this.parseValue(value);
	
	if (query == '') { 
		this.updateResults('');
		return;
	}
	with(this) {
	  new Ajax.Request(this.url+query, { 
	    method: 'get', 
	    onSuccess: handleSuccess.bind(this)
	  });
	}
  },

  handleSuccess: function(transport) {
    var json = this.parseResponse(transport.responseText);
    var html = this.jsonToList(json);
	this.updateResults(html);
  },

  select: function(tag) {
	if (this.tagList().indexOf(tag) >= 0) return; 
	var partial = this.parseValue($(this.input).value);
	var remainder = this.remainderForTag(tag, partial);
	$(this.input).value += remainder + ', ';
    this.updateResults('');
    $(this.input).focus();
  },

  tagList: function() {
	return $(this.input).value.split(', ');
  },

  jsonToList: function(json) {
	var ul = Builder.node('ul', {className:'ajax-search-results'});
	for (var i = 0; i < json.length; i++) {
	  var tag = new Tag(json[i]);
	  var li = Builder.node('li', tag.name)
	  with(this) { li.onclick = select.bind(this, tag.name) };
	  ul.appendChild(li);
    }
    return ul;
  },

  updateResults: function(html) {
	$(this.resultsContainer).update(html);
  },

  parseResponse: function(responseText) {
	var json = eval('(' + responseText +')');
	return json['tags'];
  }

});

// FIXME: share base class with Contributor
var ExternalBlog = {

  add: function() {
	$('external-blog-error').hide();
    var blogId = $('external-blog-blog-id').value;
    var title = $('external-blog-title').value;
    var url = $('external-blog-url').value;
    new Ajax.Request('/admin/externalBlog/save', {
      postBody:"blog.id="+blogId+"&title="+title+"&url="+url, 
	  method:'post', 
	  onSuccess: ExternalBlog.handleAddSuccess,
	  onFailure: ExternalBlog.handleAddFailure
    });
  },

  handleAddFailure: function(transport) {
    $('external-blog-error').update(transport.responseText);
    $('external-blog-error').appear();
  },

  handleAddSuccess: function(transport) {
    $('external-blogs').update(transport.responseText);
    $('external-blogs').highlight();
    $('external-blog-title').value = '';
    $('external-blog-url').value = '';
  },

  'delete': function(id) {
	new Ajax.Request('/admin/externalBlog/delete', {
      postBody:"id="+id, 
	  method:'post', 
	  onSuccess: ExternalBlog.handleDeleteSuccess
    });
  },

  handleDeleteSuccess: function(transport) {
	$('external-blogs').update(transport.responseText);
    $('external-blogs').highlight();
  }

}

// FIXME: share base class with ExternalBlog
var Contributor = {

  add: function() {
	$('contributor-error').hide();
    var blogId = $('contributor-blog-id').value;
    var name = $('contributor-name').value;
    var location = $('contributor-location').value;
    new Ajax.Request('/admin/contributor/save', {
      postBody:"blog.id="+blogId+"&name="+name+"&location="+location, 
	  method:'post', 
	  onSuccess: Contributor.handleAddSuccess,
	  onFailure: Contributor.handleAddFailure
    });
  },

  handleAddFailure: function(transport) {
    $('contributor-error').update(transport.responseText);
    $('contributor-error').appear();
  },

  handleAddSuccess: function(transport) {
    $('contributors').update(transport.responseText);
    $('contributors').highlight();
    $('contributor-name').value = '';
    $('contributor-location').value = '';
  },

  'delete': function(id) {
	new Ajax.Request('/admin/contributor/delete', {
      postBody:"id="+id, 
	  method:'post', 
	  onSuccess: Contributor.handleDeleteSuccess
    });
  },

  handleDeleteSuccess: function(transport) {
	$('contributors').update(transport.responseText);
    $('contributors').highlight();
  }

}

var MediaLink = {
	
  'delete': function(id) {
	new Ajax.Request('/admin/mediaLink/delete', {
      postBody:"id="+id, 
	  method:'post', 
	  onSuccess: function() { $('medialink-'+id).hide(); } 
    });
  }

};

