﻿/* 	For easier recognition of functions, all methods and global vars 
	specific for Adding an Unort should start with AU_
*/

// ========================= Add unort variables ========================= //

// General

var AU_stored_step = "";
var AU_type_categories = "";
var AU_targetDragmarker;
var AU_lat = "";
var AU_lng = "";

// form 1 - info
var AU_type = 1;
var AU_title = "";
var AU_date_noticed = "";
var AU_description = "";

// form 2 - categories

var AU_static_categories = "";
var AU_user_categories = "";
var AU_user_categories_str = "";

// ========================= Init Form code below ========================= //

function AU_initAndOpenNewUnortWindow( dragmarker, lat, lng ) {
	
	globalStatus.open_window = true;
	
	// Save all these vars in here
	AU_targetDragmarker = dragmarker;
	AU_lat = lat;
	AU_lng = lng;
	
	// Reset any stored data from a previous new Add Unort
	AU_type = 1;
	AU_title = IN_defText('nu1');
	AU_description = IN_defText('nu2');
	var now = new Date();
	AU_date_noticed = now.getDate() + '.' + (1+ now.getMonth()) + '.' + now.getFullYear();
	
	AU_category = "Kategorie 1, Kategorie 2";
	
	AU_media_title = "Title";
	AU_media_description = "Kurzbeschreibung";
	AU_media_filename = "";
	
	// Force the latest used step to step 1
	AU_stored_step = 1;
	
	// Open the first window
	AU_step1();
}

function AU_restoreDraggedMarker(dragmarker,lat,lng){
	// Save all these vars in here
	AU_targetDragmarker = dragmarker;
	AU_lat = lat;
	AU_lng = lng;
	AU_restoreAddUnortStep();
}

// ========================= Form code below ========================= //

function AU_composeNewUnort1Window() {
	var form1 = 
		'<div class="ewin new_unort" id="new_unort_1" onMouseOver="disableDragging()" onMouseOut="enableDragging()">' +
				'<form name="new_unort_form1" method="post" action="" accept-charset="utf-8">' + 
		'<div class="topbox">' + 
		'	<div class="title">Neuen Unort anlegen 1/2</div>' + 
		'	<div class="closer"><a href="javascript:AU_abortNewUnort();"><img src="img/win/win_x.gif" /></a></div>' + 
		'</div>' + 
		'<div class="bodybox">' + 
		
		'<div class="column bullet w_shl">Unort entdeckt am</div>'+
		'<div class="column">'+
		'	<input onclick="focus()" name="date_noticed" id="date_noticed" value="' + AU_date_noticed + '" type="text" disabled="disabled" />'+
		'	<a href="javascript:calendarShow(2);"><img src="img/win/btn_cal.gif" class="calbtn" title="Kalender &#246;ffnen" /></a>'+
		'</div>'+
		'<div class="dot_line"></div>'+
		'	<div class="column bullet w_shl">Unort Typ w&auml;hlen</div>' + 
		'	<div id="new_unort_type_select" class="column">' + 
		'		<select name="type" id="type" size="1" onChange="AU_form1_updateTypeIcon()">' +
		//'			<option value="0" selected="selected">bitte Typ ausw&auml;hlen</option>' +
		'			<option value="1" >'+ unort_types[1]+'</option>' +
		'			<option value="2" >'+ unort_types[2]+'</option>' +
		'			<option value="3" >'+ unort_types[3]+'</option>' +
		'			<option value="4" >'+ unort_types[4]+'</option>' +
		'		</select>' +
		'	</div>' +
		//'	<div id="new_unort_icon_text_0" class="icon_text">' +
		//'		<img class="icon" src="' + unort_types_img[0] + '" />' +
		//'		<div class="icon_txt">'+ unort_types[0]+ '</div>' +
		//'	</div>' +
		'	<div id="new_unort_icon_text_1" class="icon_text">' +
		'		<img class="icon" src="' + unort_types_img[1]+ '" title="Unorttyp" />' +
		'		<div class="icon_txt">'+ unort_types[1]+ '</div>' +
		'	</div>' +
		'	<div id="new_unort_icon_text_2" class="icon_text">' +
		'		<img class="icon" src="' + unort_types_img[2]+ '" title="Unorttyp" />' +
		'		<div class="icon_txt">'+ unort_types[2]+ '</div>' +
		'	</div>' +
		'	<div id="new_unort_icon_text_3" class="icon_text">' +
		'		<img class="icon" src="' + unort_types_img[3]+ '" title="Unorttyp" />' +
		'		<div class="icon_txt">'+ unort_types[3]+ '</div>' +
		'	</div>' +
		'	<div id="new_unort_icon_text_4" class="icon_text">' +
		'		<img class="icon" src="' + unort_types_img[4]+ '" title="Unorttyp" />' +
		'		<div class="icon_txt">'+ unort_types[4]+ '</div>' +
		'	</div>' +
		'	<div class="b10"> &nbsp;</div>' +
		'	<div class="dot_line"></div>' +
		'	<div class="column bullet w_shl">Titel und Kurzbeschreibung</div>' +
		/*
		'	<div class="column"><input type="text" onclick="IN_click(' + "'nu1'" + ')" onfocus="IN_focus(' + "'nu1'" + ')" onblur="IN_blur(' + "'nu1'" + ')" name="title" id="title" class="full deftext" value="' + AU_title + '" maxlength="40" /></div>' +
		'	<div class="column"><textarea onclick="IN_click(' + "'nu2'" + ')" onfocus="IN_focus(' + "'nu2'" + ')" onblur="IN_blur(' + "'nu2'" + ')" name="description" id="body" class="full deftext" onclick="focus()">' + AU_description + '</textarea></div>' +
		*/
		'	<div class="column">' +
		'		<iframe src="sys/edit2.iframe.php?type=new" name="editframe" id="editframe" class="if_addunort"></iframe>'+
		'	</div>' +
		'	<div class="h10"></div>' +
		'	<div class="btn_area">' +
		'		<div class="left"><a href="javascript:AU_abortNewUnort();"><img src="img/btn/btn_abbrechen.gif" /></a></div>' +
		'		<div class="right"><a href="javascript:AU_form1_submit();"><img src="img/btn/btn_next_to_step_2.gif" /></a></div>' +
		'	</div>' +
		'</div>' +
		'<div class="footerbox">' +
		'	<img src="img/win/win_point.gif" />' +
		'</div>' +
		'</form>' +
		'</div>';
	return form1;
}		

function AU_composeNewUnort2Window() {
	var form2 =
		'<div class="ewin new_unort" id="new_unort_2" onMouseOver="disableDragging()" onMouseOut="enableDragging()">' + 
		'<form name="new_unort_form2" id="unort" method="post" action="" accept-charset="utf-8">' + 
		'	<div class="topbox">' + 
		'		<div class="title">Neuen Unort anlegen 2/2</div>' + 
		'		<div class="closer"><a href="javascript:AU_abortNewUnort();"><img src="img/win/win_x.gif" /></a></div>' + 
		'	</div>' + 
		'	<div class="bodybox">' + 
		'		<div class="column bullet w_shl">Kategorien hinzufügen</div>' + 
		'		<div class="window">' +
		'			<table>' + AU_showCategoriesForType() + '</table>' +
		'		</div>' + 
		'		<div class="column w_shl">Eigene Kategorien <span class="t_tiny">(mehrere durch Komma trennen)</span></div>' + 
		//'		<div class="column"><input type="text" onclick="focus()" onfocus="IN_focus('+"'nu3'"+')" onblur="IN_blur('+"'nu3'"+')"  name="extra_cats" id="extra_cats" class="full" value="" /></div>' + 
		'	<div class="column">' +
		'		<iframe src="sys/edit2.iframe.php?type=cat" name="editframe" id="editframe" class="if_addcat"></iframe>'+
		'	</div>' +
		'		<div class="h10"></div>' +
		'		<div class="btn_area">' + 
		// '			<div class="left"><img src="img/btn/btn_back.gif" onClick="AU_storeDataFromStep2();AU_step1()"/></div>' + 
		'			<div class="left"><a href="javascript:AU_abortNewUnort();"><img src="img/btn/btn_abbrechen.gif" /></a></div>' +
		'			<div class="right"><a href="javascript:AU_form2_submit();"><img src="img/btn/btn_unort_save.gif" /></a></div>' +
		'		</div>' + 
		'	</div>' + 
		'	<div class="footerbox">' +
		'		<img src="img/win/win_point.gif" />' +
		'	</div>' +
		'</form>' + 
		'</div>';
	return form2;
}


// ========================= Form loading and data storage for each form ========================= //

function AU_saveState(){
	if (AU_stored_step == 1)
		AU_storeDataFromStep1();
	else if (AU_stored_step == 2)
		AU_storeDataFromStep2();
	else if (AU_stored_step == 3)
		AU_storeDataFromStep3();
}

function AU_step1() {
	AU_stored_step = 1;
	overlayWindow.openOnMarker( AU_targetDragmarker, AU_composeNewUnort1Window() );
	// Reset the values of the fields
	document.forms['new_unort_form1'].date_noticed.value = AU_date_noticed;
	document.forms['new_unort_form1'].type.value = AU_type;
	//document.forms['new_unort_form1'].title.value = AU_title;
	//document.forms['new_unort_form1'].description.value = AU_description;
	AU_form1_restoreTypeIcon();
}

function AU_storeDataFromStep1() {
	AU_date_noticed = document.forms['new_unort_form1'].date_noticed.value;
	AU_type = document.forms['new_unort_form1'].type.value;
	//AU_title = document.forms['new_unort_form1'].title.value;
	//AU_description = document.forms['new_unort_form1'].description.value;
	//AU_title = editframe.getValue( "title" );
	//AU_description = editframe.getValue( "text" );
}

function AU_init_step2() {
	AU_getCategoriesForUser( globalStatus.user_id );
}

function AU_step2() {
	AU_stored_step = 2;
	overlayWindow.openOnMarker( AU_targetDragmarker, AU_composeNewUnort2Window() );
	
	// If any stored categories are available, show them
	if (AU_static_categories.length > 0) {
		for (i=0; i < document.forms['new_unort_form2'].elements.length; i++) {
   			var element = document.forms['new_unort_form2'].elements[i];
   			for (j = 0; j < AU_static_categories.length; j++){
			   	if (element.value == AU_static_categories[j])
			   		element.checked = true;
			}
		}
	}	
	
	// Fill in any previously entered user defined categories
	var user_cats = "";
	for (i = 0; i < AU_user_categories.length-1; i++){
		user_cats += AU_user_categories[i] + ',';
	}
	// Prevent the , behind the last item
	if (AU_user_categories.length > 0)
		user_cats += AU_user_categories[AU_user_categories.length-1];
		
	// document.forms['new_unort_form2'].extra_cats.value = user_cats;
}

function AU_storeDataFromStep2(){
	// Clear the saved state
	AU_user_categories = new Array();
	AU_static_categories = new Array();
	
	// Save the current state
	// For the static categories, save the selections
	for (i = 0; i < (AU_type_categories.length/2); i++){
		if (document.forms['new_unort_form2'].elements['category' + i].checked){
			AU_static_categories.push(document.forms['new_unort_form2'].elements['category' + i].value);
		}
	}
	// Get the user added categories
	/*
	if (document.forms['new_unort_form2'].extra_cats.value != ""){
		var pieces = document.forms['new_unort_form2'].extra_cats.value.split(',');
		for (i = 0; i < pieces.length; i++){
			AU_user_categories.push(pieces[i]);
		}
	}
	*/
	if (AU_user_categories_str != ""){
		var pieces = AU_user_categories_str.split(',');
		for (i = 0; i < pieces.length; i++){
			AU_user_categories.push(pieces[i]);
		}
	}
}

function AU_step3(){
	AU_stored_step = 3;
	overlayWindow.openOnMarker(AU_targetDragmarker,AU_composeNewUnort3Window());
	//document.forms['new_unort_form3'].file.value = AU_media_filename;
	//document.forms['new_unort_form3'].title.value = AU_media_title;
	//document.forms['new_unort_form3'].description.value = AU_media_description;	
}

function AU_storeDataFromStep3(){
	//AU_media_filename = document.forms['new_unort_form3'].file.value;
	//AU_media_title = document.forms['new_unort_form3'].title.value;
	//AU_media_description = document.forms['new_unort_form3'].description.value;
}

function AU_form1_submit() {
	if (!checkLoggedIn( true ))
		return;
	
	AU_title = frames[0].document.form.title.value;
	AU_description = frames[0].document.form.text.value;
	if (AU_title == '' || AU_title == IN_input_defaults['nu1'][1] ||
			AU_description == '' || AU_description == IN_input_defaults['nu2'][1]) {
		displayMessage( 'Sie müssen einen Titel und eine Beschreibung eingeben' );
	} else {
		AU_saveState();
		AU_init_step2();
	}
}

function AU_form2_submit() {
	if (!checkLoggedIn( true ))
		return;
	
	AU_user_categories_str = frames[0].document.form.title.value;
	if (AU_user_categories_str == IN_input_defaults["nu3"][1]) {
		AU_user_categories_str = '';
	}
	
	AU_saveState();
	AU_addNewUnort();
}

// ========================= Helper methods ========================= //

// Clears the marker and the overlaywindow
function AU_abortNewUnort(){
	AU_saveState();
	AU_targetDragmarker.hide();
	AU_targetDragmarker = null;
	if (overlayWindow != null) {
		//overlayWindow.remove();
		map.removeOverlay( overlayWindow );
		overlayWindow = null;
	}
	// map.removeOverlay( overlayWindow );
	globalStatus.open_window = false;
}

function AU_form1_updateTypeIcon(){
	var localValue = document.forms['new_unort_form1'].type.value;
	for (i = 1; i < 5; i++){
		document.getElementById("new_unort_icon_text_"+i).style.visibility = "hidden";
	}
	document.getElementById("new_unort_icon_text_"+localValue).style.visibility = "visible";
}

function AU_form1_restoreTypeIcon(){
	for (i = 1; i < 5; i++){
		document.getElementById("new_unort_icon_text_"+i).style.visibility = "hidden";
	}
	document.getElementById("new_unort_icon_text_"+AU_type).style.visibility = "visible";
}

function AU_restoreAddUnortStep() {
	if (AU_stored_step == 1)
		AU_step1();
	else if (AU_stored_step == 2)
		AU_step2();
	else if (AU_stored_step == 3)
		AU_step3();
}

// ============= AJAX code (add new unort) below - works =============== //

function AU_addNewUnort(){
	// only continue if xmlHttp isn't void
	if (xmlHttp) {
		// try to connect to the server
		try {
			var catList = AU_static_categories.join( "," );
			var user_cats= AU_user_categories.join( "," );
			var query = "sys/addunort.php?type_id=" + AU_type +
				"&categories="+ catList +
				"&user_cats="+ encodeURIComponent( user_cats ) +
				"&lat="+ AU_lat +
				"&lng="+ AU_lng +
				"&date="+ AU_date_noticed +
				"&title="+ encodeURIComponent( AU_title ) +
				"&text="+ encodeURIComponent( AU_description );
			
			// make asynchronous HTTP request to retrieve new message
			xmlHttp.open( "GET", query , true );
			xmlHttp.onreadystatechange = function() {
					var xmlResponse = xmlHttp.responseXML;
					if (xmlResponse != null){
						var response = xmlResponse.getElementsByTagName( 'unortinfo' );
						var place_id = response[0].getAttribute( "id" );
						window.location = "index.php?unort_id=" + place_id + "&new_unort=1";
						
					}
				};
			xmlHttp.send(null);
		} catch(e) {
			displayError( e );
		}
	}
	// See method AU_abortNewUnort for documentation
	AU_abortNewUnort();
	// Refresh the GUI
	initGui();
}

// ============= AJAX code below (get categories) - works =============== //

function AU_getCategoriesForUser( user_id ) {
	// only continue if xmlHttp isn't void
	if (xmlHttp) {
		// try to connect to the server
		try {
			// make asynchronous HTTP request to retrieve new message
			var query = "sys/categories.php?action=add&user_id=" + user_id;
			xmlHttp.open("GET", query , true);
			xmlHttp.onreadystatechange = AU_handleGetCategoriesForUser;
			xmlHttp.send(null);
		} catch(e) {
			displayError( e );
		}
	}
}

// function called when the state of the HTTP request changes
function AU_handleGetCategoriesForUser() {
	// when readyState is 4, we are ready to read the server response
	if (xmlHttp.readyState == 4) {
		// continue only if HTTP status is "OK"
		if (xmlHttp.status == 200) {
			try {
				// do something with the response from the server
				AU_prepareCategoriesForUser();
			} catch(e) {
				// display error message
				displayError( e.toString() );
			}
		} else {
			// display error message
			displayError(xmlHttp.statusText);   
		}
	}
}

// handles the response received from the server
function AU_prepareCategoriesForUser()
{
  // We need to clear the saved selected categories also as they now change
  AU_static_categories = new Array();
  AU_type_categories = new Array();
  // read the message from the server
  var xmlResponse = xmlHttp.responseXML; 
  // obtain the XML's document element
  xmlRoot = xmlResponse.documentElement;  
  // obtain arrays with categories 
  categories = xmlRoot.getElementsByTagName("category");
  
  // iterate through the arrays and push the info into an array
  for (var i = 0; i < categories.length; i++) {
  	AU_type_categories.push(categories[i].getAttribute("id"));
  	AU_type_categories.push(categories[i].getAttribute("name"));
  }
  
  AU_step2();
}

function AU_showCategoriesForType(){
	var html = "";
	if (AU_type_categories.length == 0)
		html = "No categories found.";
	else{
		for (var i = 0; i < AU_type_categories.length; i = i+2){
			html += 
				'<tr>' + 
					'<td class="check"><input type="checkbox" name="category'+(i/2)+'" value="' + AU_type_categories[i]+ '" /></td>' + 
					'<td class="name txt">' + AU_type_categories[i+1] + '</td>' +
				'</tr>';
		}
	}
	return html;	
}
