/*

Ajax Functions for dynamically generated content
Updated 1007-01-12 Microsoft IE does not like to compare the result of start_http_request with false.

*/

// Note Generic Functions
// function genericStartRequest(targetUrlString, postVarsString, targetDivObject)
// function genericFulfilRequest(httpRequest, targetDivObject)
// function isInArray(myArray, searchValString)

// set up the row count, used in automatically generating the form!
var row_count = 0;

// get the PHP Session ID for use later
var phpSessionId = "";
var allCookies = document.cookie;
var pos = allCookies.indexOf("PHPSESSID=");

if (pos != -1) {

	var start = pos + 10;
	var end = allCookies.indexOf(";");
	
	if (end == -1) { end = allCookies.length }
	phpSessionId = allCookies.substring(start, end);
	
}

var scriptPhotoId = false;
var scriptDivId = false;
var scriptSelectedIds = [];
var pageVarPreviewDiv;
var pageVarImgsSelectedDiv;
var pageVarMetaTagsDiv;


function show_advanced_search_form(club_id) {
	
	// initiate an http request for the form
	var blankDisplay  = document.createElement("div");
	var myHttpRequest = start_http_request();
	
	if (myHttpRequest) { 

		myHttpRequest.onreadystatechange = function() { generateAdvancedSearchForm(myHttpRequest); };
		myHttpRequest.open('POST', "meta_search.php", true);
		myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		myHttpRequest.send('club_id=' + club_id);

		blankDisplay.className = "background_blank";
		blankDisplay.id = "background_blanker";
		document.body.appendChild(blankDisplay);
	
	}

}


function generateAdvancedSearchForm(httpRequest) {	

	// generate the form contents
	var content;
	var tableElement = document.createElement("div");
	var x_center;
	var y_center;

	content = get_http_response(httpRequest);
	if (content == false) { return false; }
				
	tableElement.id = "meta_data_form";
	tableElement.className = "meta_data_table";	

	tableElement.innerHTML = "<div><h3>Advanced Search</h3>"
	+ "<a href=# onclick=\"createNewRow();\">"
	+ "<img src=\"images/button_add_meta_tag.gif\" alt=\"Add a Meta Tag\" title=\"Add a Meta Tag\"></a>"
	+ " <a href=# onclick=\"close_meta_form();\">"
	+ "<img src=images/button_cancel_blue.gif alt=\"Close This Window\" title=\"Close This Window\"></a>"
	+ "<form name=some id=formy method=post action=photogallery.php>"

	+ "<div id=meta_area>"
	+ content
	+ "</div>"

	+ "<input type=submit value=\"Search\">"
	+ "</form>"
	+ "</div>";

	document.body.appendChild(tableElement);
			
	y_center = (document.body.clientWidth - 400) / 2;
	x_center = (document.body.clientHeight - 400) / 2;

	if (x_center > 200) { x_center = 200; }

	tableElement.style.position = "absolute";	
	tableElement.style.display = "block";
	tableElement.style.left = y_center + "px";
	tableElement.style.top = x_center + "px";

}

function processFormInPlace(formObj, dispDivObj) {

	// call all the parts of a form and submit, but display result in place
	var postString = "";
	var scriptAction = formObj.action;
		
	// loop through all the form objects in form id given
	
	for (var i = 0; i < formObj.length; i ++) {
	
		postString += formObj.elements[i].name + "=" + formObj.elements[i].value + "&";
	
	}

	genericStartRequest(scriptAction, postString, dispDivObj);
	dispDivObj.innerHTML = "Posting to Server ";

}

function processSendLink(formObj, dispDivObj) {

	// process a gallery add comment form
	// processes an photo comment request from photogallery_comments.php
	// dispDivObj is div to display result in
	// closDivObj is form div that is finished with so close

	var postString = "";
	var giveUp = false;
	
	// loop through all the form objects in form id given
	
	for (var i = 0; i < formObj.length; i ++) {
	
		// is it the submit button?
		if (formObj.elements[i].name == "name" && formObj.elements[i].value == "") {
		
			giveUp = true;
			dispDivObj.innerHTML += "<div class='alerter'>You must enter your name</div>";
		
		}
		
		if (formObj.elements[i].name == "capcha" && formObj.elements[i].value == "") {
		
			giveUp = true;
			dispDivObj.innerHTML += "<div class='alerter'>You must enter a CAPCHa! value</div>";
		
		}
				
		postString += formObj.elements[i].name + "=" + formObj.elements[i].value + "&";
	
	}

	// now post to the server

	if (giveUp == false) {
	
		genericStartRequest("cms_sendlink.php", postString, dispDivObj);
		dispDivObj.innerHTML = "Posting to Server ";

	}
	
}

function destroyGenericForm() {

	// destroy a generic form
	var genericFormObj = document.getElementById("generic_form");
	var genericBlankObj = document.getElementById("blanker");

	document.body.removeChild(genericFormObj);
	document.body.removeChild(genericBlankObj);	
	
}

function showGenericForm(formType, contextId) {

	// get a generic form from the server and display!

	// blanker
	var htmlBlnkElement = document.createElement("div");
	var htmlFormElement = document.createElement("div");
	var htmlMenuElement = document.createElement("div");
	var htmlInnerElement = document.createElement("div");

	htmlBlnkElement.id = "blanker";
	htmlFormElement.id = "generic_form";
	htmlMenuElement.id = "generic_form_menu";
	htmlInnerElement.id = "generic_form_inner";

	document.body.appendChild(htmlBlnkElement);
	document.body.appendChild(htmlFormElement);

	htmlFormElement.appendChild(htmlMenuElement);
	htmlFormElement.appendChild(htmlInnerElement);
	
	htmlMenuElement.innerHTML = "<button onclick=\"destroyGenericForm(); return false;\">Close</button>";
	htmlInnerElement.innerHTML = "loading form";

	centerElement(htmlFormElement);
	genericStartRequest("cms_forms.php", "form_type="+formType+"&context_id="+contextId, htmlInnerElement);


}

function commentDelete(commentId, divObj) {

	// delete a comment
	if (confirm("Do you really wish to delete the comment?")) {
	
		genericStartRequest("photogallery_comments.php", "method=delete_comment&comment_id="+commentId, divObj);
		divObj.innerHTML = "Deleting from Server ";
	
	}

}

function processGalleryComment(formObj, dispDivObj, closeDivObj) {

	// process a gallery add comment form
	// processes an photo comment request from photogallery_comments.php
	// dispDivObj is div to display result in
	// closDivObj is form div that is finished with so close

	var postString = "";
	var giveUp = false;
	
	// loop through all the form objects in form id given
	
	for (var i = 0; i < formObj.length; i ++) {
	
		// is it the submit button?
		if (formObj.elements[i].name == "name" && formObj.elements[i].value == "") {
		
			giveUp = true;
			closeDivObj.innerHTML += "<div class='alerter'>You must enter your name</div>";
		
		}
		
		if (formObj.elements[i].name == "capcha" && formObj.elements[i].value == "") {
		
			giveUp = true;
			closeDivObj.innerHTML += "<div class='alerter'>You must enter a CAPCHa! value</div>";
		
		}
				
		postString += formObj.elements[i].name + "=" + formObj.elements[i].value + "&";
	
	}

	// now post to the server

	if (giveUp == false) {
	
		genericStartRequest("photogallery_comments.php", postString, dispDivObj);
		dispDivObj.innerHTML = "Posting to Server ";
		closeDivObj.style.display = "none";

	}
	
}

function photoAddComment(photoId, divObj) {

	// show the add comment form for a photo!

	// if form display:none, load form
	if (divObj.style.display == "block") {
	
		divObj.style.display = "none";
	
	} else {
		
		divObj.style.display = "block";
		divObj.innerHTML = "Loading...";
		genericStartRequest('photogallery_comments.php', 'method=comment_form&photo_id='+photoId, divObj);
	
	}
	
}

function inlineEditTitle(galleryId, displayDiv) {

	displayDivObj = document.getElementById(displayDiv);
	// edit the title and photo gallery descriptions etc...

	displayDivObj.innerHTML = "Loading...";
	genericStartRequest('photogallery_meta_2.php', 'method=gallery_title_form&gallery_id='+galleryId, displayDivObj);
	
}

function processGalleryEntryForm(divObj) {

	// process a gallery edit form
	
	// processes an add/edit meta tags request from photogallery_add_tags.inc.php

	var postString = "";
	var formObj = document.getElementById('gallery_data_entry');
	var myHttpRequest = start_http_request();
	
	// loop through all the form objects in form id given
	
	for (var i = 0; i < formObj.length; i ++) {
	
		// is it the submit button?
		if (formObj.elements[i].name != "submit_butt" && formObj.elements[i].name != "cancel_butt") {

			postString += formObj.elements[i].name + "=" + formObj.elements[i].value + "&";
			
		}
	
	}

	postString += "method=do_gallery_title";
	
	// now post to the server
	genericStartRequest("photogallery_meta_2.php", postString, divObj);
	divObj.innerHTML = "Posting to Server";

}


function clearGalleryEntryForm(divObj, galleryId) {

	// reset the gallery entry form div and refill with gallery info
	genericStartRequest("photogallery_meta_2.php", "method=show_gallery_title&gallery_id="+galleryId, divObj);

}

function select_photo(photoId) {

	// photo has been selected
	// if a member of the array, remove and reset class
	// if not a member of the array, add and set class

	var photoObj;
	var previewPaneObj = document.getElementById(pageVarPreviewDiv);
	var imgsSelectedObj = document.getElementById(pageVarImgsSelectedDiv);
	
	// this is a bodge to make the older ajax windows work
	scriptPhotoId = photoId;
	
	if (document.add_meta.multiple_sel.checked) {
	
		// multiple selections are enabled.
	
		photoObj = document.getElementById("photo_" + photoId.valueOf());
		
		if (isInArray(scriptSelectedIds, photoId.valueOf()) == -1) {

			// select
					
			scriptSelectedIds[scriptSelectedIds.length] = photoId.valueOf();
			photoObj.className = "photo_cell_selected";
			
			previewPaneObj.innerHTML = "<img src=/cms/photogallery_preview_image.php?image_id="
			+ photoId.valueOf() + "&full=true>";
					
		} else {
		
			// deselect
			
			scriptSelectedIds.splice(isInArray(scriptSelectedIds, photoId.valueOf()), 1);
			photoObj.className = "photo_cell";
			
			if (scriptSelectedIds.length > 0) {
				previewPaneObj.innerHTML = "<img src=/cms/photogallery_preview_image.php?image_id="
				+ scriptSelectedIds[scriptSelectedIds.length-1].valueOf() + "&full=true>";
			}
	
		}
			
		document.add_meta.selected_ids.value = scriptSelectedIds.toString();


	} else {
	
		// multiple selections disabled
		
		if (isInArray(scriptSelectedIds, photoId.valueOf()) == -1) {
		
			// select
			// clear array and reset all element styles
			for(i=0; i<scriptSelectedIds.length; i++) {
			 
   				photoObj = document.getElementById("photo_" + scriptSelectedIds[i]);
   				photoObj.className = "photo_cell";		 
			
			}

			scriptSelectedIds = [];
			photoObj = document.getElementById("photo_" + photoId.valueOf());
			photoObj.className = "photo_cell_selected";			
			scriptSelectedIds[0] = photoId.valueOf();

			// update the preview image
			previewPaneObj.innerHTML = "<img src=/cms/photogallery_preview_image.php?image_id="
			+ photoId.valueOf() + "&full=true>";

		} else {
			
			// deselect
			
			// clear the array and clear the object style	
			for(i=0; i<scriptSelectedIds.length; i++) {
			 
   				photoObj = document.getElementById("photo_" + scriptSelectedIds[i]);
   				photoObj.className = "photo_cell";		 
			
			}
				
			scriptSelectedIds = [];
			photoObj = document.getElementById("photo_" + photoId.valueOf());
			photoObj.className = "photo_cell";
	
		}
			
		document.add_meta.selected_ids.value = scriptSelectedIds.toString();
	
	}
	
	// update the number of images selected.
	updateImgsSelected();
	
	// show the meta form for the last image selected
	if (scriptSelectedIds.length > 1) {
	
		// do a multiple form
		single_meta_form(scriptSelectedIds[scriptSelectedIds.length - 1]);
	
	} else if (scriptSelectedIds.length > 0) {
	
		// do a single form
		single_meta_form(scriptSelectedIds[0]);		
	
	}

	
}


function checkbox_check_status(htmlElement) {

	if (!htmlElement.checked) {
	
		// clear all the selections apart from the last one
		for(i=0; i<scriptSelectedIds.length-1; i++) {
			 
   				photoObj = document.getElementById("photo_" + scriptSelectedIds[i]);
   				photoObj.className = "photo_cell";		 
			
		}
		
		scriptSelectedIds.splice(0, scriptSelectedIds.length - 1);
		document.add_meta.selected_ids.value = scriptSelectedIds.toString();

	}
	
	// update the number of images selected.
	
	updateImgsSelected();
	
}


function addToSetCheckStatus(checkObj) {

	// check the status of the add to set checkbox
	// if it is now selected then clear all the value boxes to prevent overwriting any valuable data
	// if it is now unselected then reload the dialog box with the prefill data
	var formObj = document.getElementById("meta_data_entry");
	
	if (checkObj.checked) {
	
		// clear all the form objects
		for (var i = 0; i < formObj.length; i ++) {
	
			if (formObj.elements[i].name.indexOf("meta_tag") !== -1) { formObj.elements[i].value = ""; }
			if (formObj.elements[i].name == "description") { formObj.elements[i].value = ""; }

		}
	
	} else {
	
		// show the meta form for the currently selected image
		single_meta_form(scriptSelectedIds[scriptSelectedIds.length - 1]);	
	
	}

}

function clearTagsObj() {

	// clears out the meta data object window
	var previewPaneObj = document.getElementById(pageVarPreviewDiv);
	var tagsPaneObj = document.getElementById(pageVarMetaTagsDiv);

	previewPaneObj.innerHTML = "";
	tagsPaneObj.innerHTML = "";
	
}

function updateImgsSelected() {

	// update the images selected display
	
	var imgsSelectedObj = document.getElementById(pageVarImgsSelectedDiv);	
	imgsSelectedObj.innerHTML = scriptSelectedIds.length + " images selected";
	
	if (scriptSelectedIds.length == 0) { clearTagsObj(); }

}


function clearImgsSelected() {

	// clear all the images selected
	for(i=0; i<scriptSelectedIds.length; i++) {
	 
		photoObj = document.getElementById("photo_" + scriptSelectedIds[i]);
		photoObj.className = "photo_cell";		 
		
	}
		
	scriptSelectedIds.splice(0, scriptSelectedIds.length);
	document.add_meta.selected_ids.value = scriptSelectedIds.toString();
	updateImgsSelected();
	clearTagsObj();
	
}

var scriptAllIds = new Array();

function selectAllImgs() {

	// select all the images
	// must use array.slice to make a new copy
	scriptSelectedIds = scriptAllIds.slice();
	
	for(i=0; i<scriptSelectedIds.length; i++) {
	 
		photoObj = document.getElementById("photo_" + scriptSelectedIds[i]);
		photoObj.className = "photo_cell_selected";		 
		
	}
		
	document.add_meta.selected_ids.value = scriptSelectedIds.toString();
	document.add_meta.multiple_sel.checked = true;
	updateImgsSelected();
	
	// display a meta edit form
	single_meta_form(scriptSelectedIds[scriptSelectedIds.length - 1]);	

}


function single_meta_form(photoId) {
	
	// load a meta form
	var metaPaneObj = document.getElementById(pageVarMetaTagsDiv);
	var postUrl = 'photo_id=' + photoId.valueOf() + '&method=single_form';
	
	// start a generic request
	genericStartRequest("photogallery_meta_2.php", postUrl, metaPaneObj);
	scriptPhotoId = photoId;
	
}

function processMetaEntryForm(formObj) {

	// processes an add/edit meta tags request from photogallery_add_tags.inc.php

	var postString = "";
	var myHttpRequest = start_http_request();
	var tagDivObj = document.getElementById(pageVarMetaTagsDiv);
	var addToSetObj = document.getElementById("add_to_set_checkbox");
	
	// loop through all the form objects in form id given
	
	for (var i = 0; i < formObj.length; i ++) {
	
		// is it the submit button?
		if (formObj.elements[i].name != "submit_butt" && formObj.elements[i].name != "ignore_checkbox") {

			if (formObj.elements[i].value.length > 0) {
			
				postString += formObj.elements[i].name + "=" + formObj.elements[i].value + "&";
	
			}
			
		}
	
	}


	if (document.forms["add_meta"]) {
	// check that form add_meta exists - if not, then probably editing metadata for a single image in the gallery
	
		if (document.add_meta.multiple_sel.checked){
	
			// is a multiple request
			postString += "method=do_multiple_form&multiple_images=" + scriptSelectedIds.toString();
			
			// check if add to set checkbox is checked
			// if yes, then add do_not_delete_first=true
	
			if (addToSetObj.checked) { postString += "&do_not_delete_first=true"; }
	
		} else {
		
			// is a single request
			postString += "method=do_single_form";
	
			// check if add to set checkbox is checked
			// if yes, then add do_not_delete_first=true
	
			if (addToSetObj.checked) { postString += "&do_not_delete_first=true"; }
	
		}

		clearImgsSelected();

	} else {

		// being called from a single photo view context	
		// is a single request
		postString += "method=do_single_form";

		// check if add to set checkbox is checked
		// if yes, then add do_not_delete_first=true

		if (addToSetObj.checked) { postString += "&do_not_delete_first=true"; }
	
	}
	// now post to the server
	genericStartRequest("photogallery_meta_2.php", postString, tagDivObj);
	tagDivObj.innerHTML = "Posting to Server ";
	
}


function show_gallery_meta_form(galleryId) {
	
	// initiate an http request for the form
	var blankDisplay  = document.createElement("div");
	var myHttpRequest = start_http_request();
	
	if (myHttpRequest) { 

	    	myHttpRequest.onreadystatechange = function() { generateGalleryMetaForm(myHttpRequest); };
    		myHttpRequest.open('POST', "photogallery_meta.php", true);
    		myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    		myHttpRequest.send('gallery=true&gallery_id=' + galleryId);

		blankDisplay.className = "background_blank";
		blankDisplay.id = "background_blanker";
		document.body.appendChild(blankDisplay);
	
	}

}

function generateGalleryMetaForm(httpRequest) {	

	// generate the form contents
	var content;
	var tableElement = document.createElement("div");
	var x_center;
	var y_center;

	content = get_http_response(httpRequest);
	if (content == false) { return false; }
				
	tableElement.id = "meta_data_form";
	tableElement.className = "meta_data_table";	

	tableElement.innerHTML = "<a href=# onclick=\"createNewRow();\">"
	+ "<h3>Add Photo Metadata</h3>"
	+ "<img src=\"images/button_add_meta_tag.gif\" alt=\"Add a Meta Tag\" title=\"Add a Meta Tag\"></a>"
	+ " <a href=# onclick=\"close_meta_form();\">"
	+ "<img src=images/button_cancel_blue.gif alt=\"Close This Window\" title=\"Close This Window\"></a>"
	+ "<form name=some id=formy method=post action=photogallery_meta.php>"
	+ "<div id=meta_area>"
	+ content
	+ "</div>"
	+ "<input type=submit value=\"Store Meta Data\">"

	+ "<div class=photo_gall_photo_meta style=\"margin: 10px;\">"
	+ "<div class=meta_dropdown_menu>Meta Data Types Administration</div class=meta_data_row>"
	
	+ "<div class=photo_gall_meta_data>"
	+ "  <div><a href=\"javascript:toggle('create_new_type_div');\">Create New Type</a></div>"
	+ "  <div id=create_new_type_div style=\"display: none;\">"
	+ "    <input type=text id=add_type_text>"
	+ "    <select id=add_type_select><option value='F'>Free Text Field</option><option value='E'>Enumerated</option></select>" 
	+ "    <button onclick=\"addTypeToDB();\" type=button name=b_button>Add</button>"	
	+ "  </div>"
	+ "</div>"

	+ "<div class=photo_gall_meta_data>"
	+ "<div><a href=\"javascript:addMetaTypeValue();\">Create Type Values</a></div>"
	+ "<span id=meta_type_add_value_span></span>"
	+ "</div>"

	+ "</form>"
	+ "</div>";

	document.body.appendChild(tableElement);
			
	y_center = (document.body.clientWidth - 400) / 2;
	x_center = (document.body.clientHeight - 400) / 2;

	if (x_center > 200) { x_center = 200; }

	tableElement.style.position = "absolute";	
	tableElement.style.display = "block";
	tableElement.style.left = y_center;
	tableElement.style.top = x_center;

}


function show_meta_form(photoId, galleryId, skipOver) {
	
	// initiate an http request for the form
	var blankDisplay  = document.createElement("div");
	var myHttpRequest = start_http_request();
	
	if (myHttpRequest) { 

	    	myHttpRequest.onreadystatechange = function() { generateMetaForm(myHttpRequest); };
    		myHttpRequest.open('POST', "photogallery_meta.php", true);
    		myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    		myHttpRequest.send('photo_id=' + photoId + '&gallery_id=' + galleryId + '&skipover=' + skipOver);

		blankDisplay.className = "background_blank";
		blankDisplay.id = "background_blanker";
		document.body.appendChild(blankDisplay);
	
	}

	scriptPhotoId = photoId;

}

function generateMetaForm(httpRequest) {	

	// generate the form contents
	var content;
	var tableElement = document.createElement("div");
	var x_center;
	var y_center;

	content = get_http_response(httpRequest);
	if (content == false) { return false; alert("here"); }
				
	tableElement.id = "meta_data_form";
	tableElement.className = "meta_data_table";	

	tableElement.innerHTML = "<a href=# onclick=\"createNewRow();\">"
	+ "<h3>Add Photo Metadata</h3>"
	+ "<img src=\"images/button_add_meta_tag.gif\" alt=\"Add a Meta Tag\" title=\"Add a Meta Tag\"></a>"
	+ " <a href=# onclick=\"close_meta_form();\">"
	+ "<img src=images/button_cancel_blue.gif alt=\"Close This Window\" title=\"Close This Window\"></a>"
	+ "<form name=some id=formy method=post action=photogallery_meta.php>"
	+ "<div id=meta_area>"
	+ content
	+ "</div>"
	+ "<input type=submit value=\"Store Meta Data\">"

	+ "<div class=photo_gall_photo_meta style=\"margin: 10px;\">"
	+ "<div class=meta_dropdown_menu>Meta Data Types Administration</div class=meta_data_row>"
	
	+ "<div class=photo_gall_meta_data>"
	+ "  <div><a href=\"javascript:toggle('create_new_type_div');\">Create New Type</a></div>"
	+ "  <div id=create_new_type_div style=\"display: none;\">"
	+ "    <input type=text id=add_type_text>"
	+ "    <select id=add_type_select><option value='F'>Free Text Field</option><option value='E'>Enumerated</option></select>" 
	+ "    <button onclick=\"addTypeToDB();\" type=button name=b_button>Add</button>"	
	+ "  </div>"
	+ "</div>"

	+ "<div class=photo_gall_meta_data>"
	+ "<div><a href=\"javascript:addMetaTypeValue();\">Create Type Values</a></div>"
	+ "<span id=meta_type_add_value_span></span>"
	+ "</div>"

	+ "</form>"
	+ "</div>";

	document.body.appendChild(tableElement);
			
	y_center = (document.body.clientWidth - 400) / 2;
	x_center = (document.body.clientHeight - 400) / 2;

	if (x_center > 200) { x_center = 200; }

	tableElement.style.position = "absolute";	
	tableElement.style.display = "block";
	tableElement.style.left = y_center;
	tableElement.style.top = x_center;

}

function addMetaTypeValue() {

	var myHttpRequest = start_http_request();
	if (myHttpRequest) {

    		myHttpRequest.onreadystatechange = function() { getTypeSelectValues(myHttpRequest, 'meta_type_add_value_span'); };
    		myHttpRequest.open('POST', "meta_get_types.php", true);
    		myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    		myHttpRequest.send('enum_only=true');

	}

}

function getTypeSelectValues(httpRequest, div_id) {	

	// Create the types field
	var content;
	var htmlElement = document.getElementById(div_id);
	
	content = get_http_response(httpRequest);
	if (content == false) { return false; }
			
	htmlElement.innerHTML = "<select id=add_type_enum_value_select>" + content + "</select>"
	+ "<input type=text id=add_type_enum_value_text>" 
	+ "<button onclick=\"addTypeValueToDB();\" type=button name=a_button>Add</button>";
			
}

function addTypeValueToDB() {

	var selectField = document.getElementById('add_type_enum_value_select');
	var textField = document.getElementById('add_type_enum_value_text');
	
	if (selectField.value != "" && textField.value != "") {
	
		var myHttpRequest = start_http_request();
		if (myHttpRequest) { 

		    myHttpRequest.onreadystatechange = function() { deleteDivAfterRequest(myHttpRequest, 'meta_type_add_value_span'); };
		    myHttpRequest.open('POST', "meta_create_types.php", true);
		    myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    		myHttpRequest.send('type_id=' + selectField.value + "&value_text=" + encodeURI( textField.value ) + "&method=add_type_value"
    		+ "&PHPSESSID=" + phpSessionId + "&photo_id=" + scriptPhotoId);	

		}
	}
}

function addTypeToDB() {

	var selectField = document.getElementById('add_type_select');
	var textField = document.getElementById('add_type_text');
	
	if (selectField.value != "" && textField.value != "") {
	
		var myHttpRequest = start_http_request();
		if (myHttpRequest) {
	
	    		myHttpRequest.onreadystatechange = function() { hideDivAfterRequest(myHttpRequest, 'create_new_type_div'); };
	    		myHttpRequest.open('POST', "meta_create_types.php", true);
    			myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    			myHttpRequest.send('type=' + selectField.value + "&description=" + encodeURI( textField.value ) + "&method=add_type"
    			+ "&PHPSESSID=" + phpSessionId + "&photo_id=" + scriptPhotoId);	

		}
	
		textField.value = "";
	}
}


function hideDivAfterRequest(httpRequest, div_id) {	

	// Create the types field
	var content = get_http_response(httpRequest);
	var htmlElement = document.getElementById(div_id);

	if (content.indexOf("OK") == -1) {
	
		alert(content);
		
	} else {
	
		htmlElement.style.display = "none";
		alert("Meta Tag type value was added, you will need to re-select the the type from the drop-down box to see any changes");
		
	}
	
}


function deleteDivAfterRequest(httpRequest, div_id) {	

	// Create the types field
	var content = get_http_response(httpRequest);
	var htmlElement = document.getElementById(div_id);

	if (content.indexOf("OK") == -1) {
	
		alert(content);
		
	} else {
	
		htmlElement.innerHTML = "";
		alert("Meta Tag type value was added, you will need to re-select the the type from the drop-down box to see any changes");
		
	}
	
}


function get_value_from_div(divId) {

	var htmlElement = document.getElementById(divId);
	var inputElements = htmlElement.getElementsByTagName('input');
	var selectElements = htmlElement.getElementsByTagName('select');
		
	var myValue
	var myType
	
	for (i = 0; i < inputElements.length; i++) {
//		alert(inputElements[i].value);
		myValue = inputElements[i].value;	
	}
	
	for (i = 0; i < selectElements.length; i++) {
//		alert(selectElements[i].name + selectElements[i].value);
		myType = selectElements[i].value;
	}

	getExistData(myType, myValue);

}

function createNewRow() {
	
	// generate a new row and the type select field
	var meta_type_div  = document.createElement("span");
	var meta_value_div = document.createElement("span");
	var delete_row_div = document.createElement("span");
	var htmlElement    = document.createElement("div");
	var htmlForm       = document.getElementById("meta_area");

	meta_type_div.id = "meta_type_div_" + row_count;
	meta_value_div.id = "meta_value_div_" + row_count;	
	delete_row_div.innerHTML = " <a href=\"javascript:remove_meta_tag('meta_data_row_" + row_count + "');\">[delete]</a>";
	delete_row_div.innerHTML = delete_row_div.innerHTML + " <a href=\"javascript:get_value_from_div('meta_data_row_" + row_count + "');\">[copy]</a>";
				
	htmlElement.className = "meta_data_row"
	htmlElement.id = "meta_data_row_" + row_count;
	
	htmlElement.appendChild(meta_type_div);
	htmlElement.appendChild(meta_value_div);
	htmlElement.appendChild(delete_row_div);
			
	htmlForm.appendChild(htmlElement);

	row_count ++;
	


	var myHttpRequest = start_http_request();
	if (myHttpRequest) {

	    myHttpRequest.onreadystatechange = function() { generateTypeObject(myHttpRequest, row_count - 1); };
	    myHttpRequest.open('POST', "meta_get_types.php", true);
	    myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    myHttpRequest.send('form_type=test');
	
	}
}


function getExistData(type, value) {
	
	// generate a new row and the type select field
	var prefill_div  = document.createElement("div");
	var htmlForm       = document.getElementById("meta_area");

	prefill_div.id = "prefill_content";
	prefill_div.innerHTML = "Searched Content - delete as needed<br>";

	htmlForm.appendChild(prefill_div);	
	
	
	var myHttpRequest = start_http_request();
	if (myHttpRequest) {

	    myHttpRequest.onreadystatechange = function() { generatePrefillObject(myHttpRequest); };
	    myHttpRequest.open('POST', "photogallery_meta.php", true);
	    myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    myHttpRequest.send('get_for_type=' + type + "&value=" + value);
	
	}
}


function generatePrefillObject(httpRequest) {	

	// Create the types field
	var content;
	var htmlElement = document.getElementById('prefill_content');

	content = get_http_response(httpRequest);
	if (content == false) { return false; }

	htmlElement.innerHTML = htmlElement.innerHTML + content;		
	createValueField(row, 0);
			
}


function generateTypeObject(httpRequest, row) {	

	// Create the types field
	var content;
	var htmlElement = document.getElementById('meta_type_div_' + row);
	
	content = get_http_response(httpRequest);
	if (content == false) { return false; }
			
	htmlElement.innerHTML = "<select name=meta_type[] onchange=\"createValueField('" + row + "', this);\">" + content + "</select>";		
	createValueField(row, 0);
			
}


function createValueField(row, selectElement) {
	
	// start a httpRequest for the value field
	var type_id       = selectElement.value;
	var myHttpRequest = start_http_request();
	
	if (myHttpRequest) {
	
	    myHttpRequest.onreadystatechange = function() { generateValueObject(myHttpRequest, row); };
	    myHttpRequest.open('POST', "meta_get_values.php", true);
	    myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    myHttpRequest.send('type_id=' + type_id);

	}
}


function generateValueObject(httpRequest, row) {	

	// Create the value select field
	var content;
	var htmlElement = document.getElementById('meta_value_div_' + row);;
	
	content = get_http_response(httpRequest);
	if (content == false) { return false; }
	htmlElement.innerHTML = content;

}



/* 

	Generic support modules for AJAX

*/

function start_http_request() {

	// start an http request
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...

    	httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) { httpRequest.overrideMimeType('text/xml'); }
        
    } else if (window.ActiveXObject) { // IE
        
        try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } 
        catch (e) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } 
        catch (e) {} }
        
    }

	if (!httpRequest) {
        alert('Your browser does not appear to support AJAX forms. Sorry!');
        return false;
    }

	// return the httpRequest object to the caller
	return httpRequest;

}

function get_http_response(httpRequest) {
	
	// get the http response and return the content
 	if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {

			// read the response
			return httpRequest.responseText;
			
        } else {

            alert('There was a problem with the request.');
			
        }

    }

	return false;

}

function close_meta_form() {

	// closes the meta form down
	// kill the <div id=meta_data_form> and <div id=background_blanker>
	document.body.removeChild(document.getElementById('meta_data_form'));
	document.body.removeChild(document.getElementById('background_blanker'));
	
}

function remove_meta_tag(tagId) {

	// remove a meta tag from the form
	// remove the content from the DIV and then make it invisible
	// removeChild doesn't seem to work for this one for some reason
	var metaFormElement = document.getElementById(tagId);
	metaFormElement.innerHTML = "";
	metaFormElement.style.display = 'none';

}

function genericStartRequest(targetUrl, postVars, targetDiv) {
	
	// a generic ajax routine
	// initiate an http request for the form
	var myHttpRequest = start_http_request();
	if (myHttpRequest) { 
		
	    	myHttpRequest.onreadystatechange = function() { genericFulfilRequest(myHttpRequest, targetDiv); };
    		myHttpRequest.open('POST', targetUrl, true);
    		myHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    		myHttpRequest.send(encodeURI(postVars));

	}

}

function genericFulfilRequest(httpRequest, targetDiv) {
	
	// generate the form contents
	var content;
	content = get_http_response(httpRequest);
	if (content == false) { return false; }
	targetDiv.innerHTML = content;
		
}

function isInArray(myArray, searchVal) {

	// check for a value in an array
	// workaround for msie
	
	for(i=0; i<myArray.length; i++) {
	 
		if (myArray[i] == searchVal) {
		
			return i;
			
		} 
	
	}
	
	return -1;

}

function getViewportDimensions() {

	// thanks to
	// http://blog.josh420.com/archives/2007/10/centering-an-element-on-the-page-with-javascript-cross-browser.aspx
    var intH = 0, intW = 0;
    
    if(self.innerHeight) {
       intH = window.innerHeight;
       intW = window.innerWidth;
    } 
    else {
        if(document.documentElement && document.documentElement.clientHeight) {
            intH = document.documentElement.clientHeight;
            intW = document.documentElement.clientWidth;
        }
        else {
            if(document.body) {
                intH = document.body.clientHeight;
                intW = document.body.clientWidth;
            }
        }
    }

    return {
        height: parseInt(intH, 10),
        width: parseInt(intW, 10)
    };
}

function centerElement(elem) {
    var viewport = getViewportDimensions();
    var left = (viewport.width == 0) ? 50 : parseInt((viewport.width - elem.offsetWidth) / 2, 10);
    var top = (viewport.height == 0) ? 50 : parseInt((viewport.height - elem.offsetHeight) / 2, 10);

    elem.style.left = left + 'px';
    elem.style.top = top + 'px';

    viewport, left, top, elem = null;    
}


