var lastSection = 0;

function addSection(){
	var button = document.getElementById('add-section-button');
	var template = document.getElementById('master-section');

	var range = document.createRange()
	range.selectNodeContents(template);

	var fragment = range.cloneContents();
	recurseAndModifySection(fragment);

	button.parentNode.insertBefore(createTitleField(), button);
	button.parentNode.insertBefore(fragment, button);

	lastSection++;
}

function recurseAndModifySection(fragment){
	for(var i = 0; i < fragment.childNodes.length; i++){
		var node = fragment.childNodes[i];
		if(node.nodeName == 'DIV' && node.getAttribute('class') == 'article-image'){
			node.parentNode.removeChild(node);
			i--;
			continue;
		}
		if(node.nodeName == 'FIELDSET'){
			node.parentNode.removeChild(node);
			i--;
			continue;
		}
		if(node.nodeName == 'LABEL'){
			if(node.getAttribute('class') == 'option'){
				node.parentNode.removeChild(node);
				i--;
				continue;
			}
			node.innerHTML = node.innerHTML.replace('Primary Image', 'Section Image');
		}
		if(node.nodeName == 'INPUT' || node.nodeName == 'TEXTAREA'){
			var fieldName = node.getAttribute('name');			
			node.value = '';
			
			if(fieldName.substr(0, 5) == 'edit['){
				var newName;
				var lastNum = fieldName.substr(-2, 1);
				if(isNaN(parseInt(lastNum))){
					newName = fieldName.substr(0, fieldName.length - 1) + '_' + lastSection + ']';
				}
				else{
					newName = fieldName.substr(0, fieldName.length - 2) + lastSection + ']';
				}
				node.setAttribute('name', newName);
			}
		}
		if(node.hasChildNodes()){
			recurseAndModifySection(node);
		}
	}
}

function createTitleField(){
	var form_item = document.createElement('div');
	form_item.setAttribute('class', 'form-item');
	form_item.innerHTML = '<label for="edit-subtitle-' + lastSection + '">Section Title:</label><input type="text" maxlength="128" name="edit[subtitle_' + 
							lastSection + ']" id="edit-subtitle-' + lastSection + '"  size="60" class="form-text"/>';
	return form_item;
}

function showDetailedImage(path, width, height){
	window.open(path, 'image_detail', 'screenX=30,left=30,screenY=30,top=30,scrollbars=no,width=' + width + ',height=' + height + ',toolbar=no,location=no,directories=no,status=no', true)
}

function showVideo(url, width, height){
newwindow=window.open(url,'name','height=450,width=450');
	if (window.focus) {newwindow.focus()}
	return false;
	
}


