/*
	Square Circle Triangle
	Author: 		Ben Schwarz / Anthony Kolber
	Description:	Anchor creator
	Desired usage:	new Anchors([ARRAY_OF_ELEMENTS], ANCHOR_LINK_PARENT_ELEMENT);
	Actual usage: 	new Anchors([ARRAY_OF_ELEMENTS], ANCHOR_LINK_PARENT_ELEMENT, ANCHOR_WRAPPING_NODES);


*/

var Anchors = function (elements, anchor_parent, anchor_wrapping_node, headers) {
	this.elements = elements;
	this.anchor_parent = anchor_parent;
	this.anchor_wrapping_node = anchor_wrapping_node;
	this.headers = headers;
	this.create();
};

Anchors.prototype = {
	// Create the anchors in this position
	create: function () {
		// Write the ID's onto an element
		if(this.writeIDs()) {
			// Write the named tags into the destination
			this.addNamedAnchors();
		} else {
			throw("An unexpected error occurred; Could not initialise the Anchor class");
		}
	},
	writeIDs: function () {
		for (var i = 0; i < this.elements.length; i++) {
			// Give the element an ID, if it already has one, grab the next child without one
			if(!this.elements[i].id) {
				this.elements[i].id = 'anchor_' + i;
			} else {
				this.elements[i].getElementsByTagName('div')[0].id = 'anchor_' + i;
			}
		}
		return true;
	},
	
	addNamedAnchors: function () {
		for (var i = 0; i < this.elements.length; i++) {
			// Create an element based on the first child node in with a text value larger than '' (simple yeah?)
			var wrapping_node = document.createElement(this.anchor_wrapping_node);
			var anchor = document.createElement('a');
			anchor.setAttribute('href', '#anchor_'+i);
			// add onclick event
			this.anchor_parent[0].appendChild(wrapping_node);
			wrapping_node.appendChild(anchor);
			anchor.innerHTML = $(this.headers[i]).text();
		}
	}
};
