// JQUERY
if (typeof jQuery != "undefined") {
	jQuery(document).ready(function() {
		
		// prepare loading image		
		loadingImage = new Image();
		loadingImage.src = '/images/ajax-loader.gif';
		
		fnEvents.init();
		fnRobotEditor.init();
		fnEventEditor.init();
	});
}

fnThickBox = {
	
	reinitializeThickBoxes:function() {
		tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	},
	
	showThickBox:function(src) {
		var t = src.title || src.name || null;
		var a = src.href || src.alt;
		var g = src.rel || false;
		tb_show(t,a,g);
		src.blur();
		return false;
	}
}

fnEvents = {
	
	init:function() {
	
		jQuery('#eventTools .linkExport').click(function(e) {
			e.preventDefault();			
			var link = jQuery('#exportForm .linkExport'); 
			link.href = fnEvents.fnExportURL();
			fnThickBox.showThickBox(link);			
		});
		
		jQuery('#eventTools .linkFilter').click(function(e) {
			e.preventDefault();
			fnEvents.filterEvents(jQuery(this), fnEvents.fnFilterURL());
		});
		
		fnEvents.addDescriptionDialogs();
		fnEvents.initializeAddButton();
		fnEvents.initializeEditButton();
		fnEvents.initializeDeleteButton();
		fnEvents.initializePublishButton();
		fnEvents.initializeUnpublishButton();
	},
	
	fnFilterQueryString : function() {
		var eventCategory = jQuery('#exportForm #eventCategory').val();
		var placeId = jQuery('#exportForm #eventPlace').val();
		var lastUpdated = jQuery('#exportForm #lastUpdated').val();
		var queryString = '';
		if (eventCategory != '') {
			queryString += '&eventCategory=' + eventCategory;
		}
		if (placeId != '') {
			queryString += '&eventPlace=' + placeId;
		}
		if (lastUpdated != '') {
			queryString += "&lastUpdated=" + lastUpdated;
		}
		if (queryString != '') {
			queryString = queryString.substring(1);
		}
		return queryString;
	},
	
	fnExportURL : function() {		
		return 'export_events.php?'+fnEvents.fnFilterQueryString()+'&KeepThis=true&TB_iframe=true&height=600&width=600';
	},
	
	fnFilterURL : function() {
		return 'events.php?' + fnEvents.fnFilterQueryString();
	},	
	
	filterEvents:function(src, url) {
		var loadingImageSrc = "<img id='loaderLinkFilter' height='10' width='10' src='"+loadingImage.src+"'/>";
		jQuery.ajax({
			type : "GET",
			url : url,
			dataType : "html",
			beforeSend: function() {
				jQuery(src).replaceWith(loadingImageSrc);
			},
			complete : function() {
				var loadingImage = jQuery('#loaderLinkFilter');
				jQuery(loadingImage).replaceWith(src);
				jQuery(src).click(function(e) {
					e.preventDefault();
					fnEvents.filterEvents(jQuery(this), fnEvents.fnFilterURL());
				});
			},
			success : function(data) {
				var newContent = jQuery('#events', data);
				if (newContent.length > 0) {		
					jQuery('#events').replaceWith(newContent);

					fnEvents.addDescriptionDialogs();
					fnEvents.initializeAddButton();			
					fnEvents.initializeEditButton();
					fnEvents.initializeDeleteButton();
					fnEvents.initializePublishButton();
					fnEvents.initializeUnpublishButton();				
					fnThickBox.reinitializeThickBoxes();
				}
			},
			error : function(data) {
				jQuery.jGrowl("Tuntematon virhe", {header: "Virhetilanne"});
			}
		});
	},
	
	addDescriptionDialogs:function() {
		jQuery('#eventTable .linkDescription').click(function(e) {
			e.preventDefault();
			var id = jQuery(jQuery(this).parent().parent()).attr('id').substring(5);
			var src = jQuery('#eventTable #description'+id);
			var target = jQuery('#descriptionDiv');
			target.html(src.html());
			target.dialog({
				autoOpen: false, 
				modal: true,
				closeText: 'sulje',
				draggable: false,
				resizable: false				
			});
			target.dialog('open');
		});
	},
	
	initializeAddButton:function() {
		jQuery("#events .linkAdd").click(function(e) {
			e.preventDefault();
			var link = jQuery(this);
			link.href = link.attr('href');
			fnThickBox.showThickBox(link);
		});
	},
	
	initializeEditButton:function() {
		jQuery("#eventTable .linkEdit").click(function(e) {
			e.preventDefault();
			var link = jQuery(this);
			link.href = link.attr('href');
			fnThickBox.showThickBox(link);
		});
	},
	
	initializeDeleteButton:function() {
		jQuery("#eventTable .linkDelete").click(function(e) {
			e.preventDefault();
			if (confirm('Haluatko varmasti poistaa tämän tapahtuman?')) {
				var id = jQuery(jQuery(this).parent().parent()).attr('id').substring(5);
				jQuery.ajax({
					type : "POST",
					url : "delete_event.php",
					data : "eventId=" + id,
					dataType : "json",
					success : function(data) {
						if ((data != null) && (data.success == true)) {
							jQuery.jGrowl("Tapahtuma poistettu.");
							jQuery('#eventTools .linkFilter').click();
						} else {
							jQuery.jGrowl("Tapahtuman poistaminen epäonnistui", {header: "Virhetilanne"});
						}
					},
					error : function(data) {
						jQuery.jGrowl("Tuntematon virhe", {header: "Virhetilanne"});
					}
				});
			} else {
				return false;
			}
		});
	},
	
	fnPublish : function(id, publish, msgSuccess, msgFailure) {
		var urlParams = "eventId=" + id;
		if (publish) {
			urlParams += "&action=publish";
		} else {
			urlParams += "&action=unpublish";
		}
		jQuery.ajax( {
			type : "POST",
			url : "publish_event.php",
			data: urlParams,
			dataType : "json",
			success : function(data) {
				if ((data != null) && (data.success == true)) {
					var id = data.publishedEvent.id;
					var name = data.publishedEvent.externalId;
					var row = jQuery('#eventTable tr#event'+id);
					var statusCol = jQuery('td:nth-child(1)', row);
					statusCol.toggleClass('published');
					jQuery('.linkPublish', row).toggleClass('none');
					jQuery('.linkUnpublish', row).toggleClass('none');
					jQuery.jGrowl(msgSuccess);						
				} else {
					jQuery.jGrowl(msgFailure, {header: "Virhetilanne"});
				}
			},
			error : function(data) {					
				jQuery.jGrowl("Tuntematon virhe", {header: "Virhetilanne"});
			}
		});
	},
	
	initializePublishButton:function() {
		jQuery("#eventTable .linkPublish").click(function(e) {
			e.preventDefault();
			var id = jQuery(jQuery(this).parent().parent()).attr('id').substring(5);
			fnEvents.fnPublish(id, true, "Tapahtuma julkaistu palveluun.", "Tapahtuman julkaiseminen epäonnistui");
		});
	},
	
	initializeUnpublishButton:function() {
		jQuery("#eventTable .linkUnpublish").click(function(e) {
			e.preventDefault();
			var id = jQuery(jQuery(this).parent().parent()).attr('id').substring(5);
			fnEvents.fnPublish(id, false, "Tapahtuma piilotettu palvelusta.", "Tapahtuman piilottaminen epäonnistui");
		});
	}
};

fnRobotEditor = {
		
	init : function() {
	
		jQuery('#robotTable .linkAdd').click(function(e) {
			e.preventDefault();
			fnRobotEditor.addRobot();
		});
	
		jQuery('#robotTable .linkEdit').click(function(e) {
			e.preventDefault();			
			var robotId = jQuery(this).parent().parent().attr('id').substring(5);			
			var robotName = jQuery(jQuery('#robotTable #robot'+robotId+' td')[1]).text();
			var robotScriptURL = jQuery(jQuery('#robotTable #robot'+robotId+' td')[2]).text();
			var robotBaseURL = jQuery(jQuery('#robotTable #robot'+robotId+' td')[3]).text();
			fnRobotEditor.openEditor(robotId, robotName, robotScriptURL, robotBaseURL);
		});

		jQuery('#robotTable .linkDelete').click(function(e) {
			e.preventDefault();			
			var robotId = jQuery(this).parent().parent().attr('id').substring(5);
			var robotName = jQuery(jQuery('#robotTable #robot'+robotId+' td')[1]).text();
			if (confirm('Haluatko varmasti poistaa robotin ' + robotName + '?')) {
				fnRobotEditor.deleteRobot(robotId);
			} else {
				return false;
			}
		});		
		
		jQuery('#editRobotDiv .linkAdd').click(function(e) {
			e.preventDefault();
			var robotId = jQuery('#editRobotDiv #robotId').val();
			fnRobotEditor.editItem(jQuery(this), robotId);
		});
		
		jQuery('#editRobotDiv .linkSave').click(function(e) {
			e.preventDefault();
			var robotId = jQuery('#editRobotDiv #robotId').val();
			var robotName = jQuery('#editRobotDiv #robotName').val();
			var robotScriptURL = jQuery('#editRobotDiv #robotScriptURL').val();
			var robotBaseURL = jQuery('#editRobotDiv #robotBaseURL').val();			
			fnRobotEditor.saveRobot(robotId, robotName, robotScriptURL, robotBaseURL);
		});
		
		jQuery('#editRobotDiv .linkCancel').click(function(e) {
			e.preventDefault();
			fnRobotEditor.closeEditor();
		});
	},

	addRobot:function() {
		var table = jQuery('#robotTable table');
		var newRow = "<tr>"+
			"<td>&nbsp;</td>"+
			"<td><input type='text' id='robotName'/></td>"+
			"<td><input type='text' id='robotScriptURL'/></td>"+
			"<td><input type='text' id='robotBaseURL'/></td>"+
			"<td colspan='2'><a class='linkCancel' href='#'>Peruuta</a>&nbsp;&nbsp;<a class='linkSave' href='#'>Tallenna</a></td>"+
			"</tr>";
		table.append(newRow);
		
		jQuery('#robotTable .linkCancel').click(function(e) {
			e.preventDefault();
			fnRobotEditor.cancelRobot();
		});
		
		jQuery('#robotTable .linkSave').click(function(e) {
			e.preventDefault();
			var robotName = jQuery("#robotTable #robotName").val();
			var robotScriptURL = jQuery("#robotTable #robotScriptURL").val();
			var robotBaseURL = jQuery("#robotTable #robotBaseURL").val();
			fnRobotEditor.saveRobot(null, robotName, robotScriptURL, robotBaseURL);
		});
	},
	
	saveRobot:function(robotId, robotName, robotScriptURL, robotBaseURL) {
		var urlParams = '';
		if (robotId != null) {
			urlParams = "id=" + robotId + "&";
		}
		urlParams += "robotName=" + robotName + "&robotScriptURL=" + robotScriptURL + "&robotBaseURL=" + robotBaseURL;
		jQuery.ajax( {
			type : "POST",
			url : "edit_robot.php",
			data: urlParams,
			dataType : "json",
			beforeSend : function(xhr) {
				xhr.overrideMimeType('text/html; charset=UTF-8');
			},
			success : function(data) {
				window.location.reload(true);
			},
			error : function(data) {					
				jQuery.jGrowl("Tuntematon virhe", {header: "Virhetilanne"});
			}
		});
	},
	
	cancelRobot:function() {
		jQuery('#robotTable table tr:last').remove();
	},
	
	deleteRobot:function(robotId) {
		jQuery.ajax( {
			type : "POST",
			url : "delete_robot.php",
			data: "id=" + robotId,
			dataType : "json",
			success : function(data) {
				window.location.reload(true);
			},
			error : function(data) {
				jQuery.jGrowl("Tuntematon virhe", {header: "Virhetilanne"});
			}
		});
	},
	
	openEditor : function(robotId, robotName, robotScriptURL, robotBaseURL) {

		jQuery('#editRobotDiv #robotId').val(robotId);
		jQuery('#editRobotDiv #robotName').val(robotName);
		jQuery('#editRobotDiv #robotScriptURL').val(robotScriptURL);
		jQuery('#editRobotDiv #robotBaseURL').val(robotBaseURL);
		fnRobotEditor.loadItemTable(robotId);
	},

	loadItemTable : function(id) {
		jQuery.get('robot_items.php', 'id=' + id, function(data) {

			// populate robot item table
			jQuery('#robotItemsDiv').html(data);

			// show robot edit table
			var editorDiv = jQuery('#editRobotDiv');
			if (editorDiv.hasClass('hidden')) {
				editorDiv.toggleClass("hidden");
			}
			
			// enable links
			jQuery('#robotItems .linkEdit').click(function(e) {
				e.preventDefault();
				var robotId = jQuery('#editRobotDiv #robotId').val();
				fnRobotEditor.editItem(jQuery(this), robotId);
			});			
			jQuery('#robotItems .linkDelete').click(function(e) {
				e.preventDefault();
				if (confirm('Haluatko varmasti poistaa tämän tapahtumapaikan?')) {
					var itemId = jQuery(jQuery(this).parent().parent()).attr('id').substring(4);
					fnRobotEditor.removeItem(itemId);
				} else {
					return false;
				}				
			});
			jQuery('#robotItems .linkCrawl').click(function(e) {
				e.preventDefault();
				var link = jQuery(this);				
				fnRobotEditor.startCrawling(link);
			});
			jQuery('#robotItems .linkCrawlAll').click(function(e) {
				e.preventDefault();
				var crawlLinks = jQuery('#robotItems .linkCrawl');
				jQuery.each(crawlLinks, function(e) {
					jQuery(this).click();
				});
			});
			
		}, 'html');
	},

	closeEditor : function() {
		jQuery('#robotItems tbody').empty();
		jQuery('#editRobotDiv').toggleClass("hidden");
	},

	editItem : function(src, robotId) {
		
		if (robotId == null) {
			return;
		}
		
		var itemId = null;
		if (src.hasClass('linkEdit')) {
			itemId = src.parent().parent().attr('id').substring(4);
		}	
		
		crawlerURL = null;
		placeId = null;
		categoryId = null;
		if (itemId == null) {
			jQuery('#robotItems tbody').append("<tr>"+fnRobotEditor.getItemEditor()+"</tr>");
		} else {
			crawlerURL = jQuery(jQuery('#robotItems tbody tr#item'+itemId).children()[0]).text();
			placeId = jQuery('#robotItems tbody tr#item'+itemId+' #placeId').val();
			categoryId = jQuery('#robotItems tbody tr#item'+itemId+' #categoryId').val();
			jQuery('#robotItems tbody tr#item'+itemId).html(fnRobotEditor.getItemEditor());			
		}
		
		fnRobotEditor.prepareItemEditorSelects();
		
		// if editing existing item, prepare existing values
		if (itemId != null) {
			jQuery('#robotItems tbody #crawlerURL').val(crawlerURL);
			jQuery('#robotItems tbody #placeId').val(placeId);
			jQuery('#robotItems tbody #categoryId').val(categoryId);
		}
		
		// add behaviour for save/cancel links
		jQuery('#robotItems tbody .linkSave').click(function(e) {
			e.preventDefault();
			var itemId = null;
			var tr = null;
			if (jQuery(jQuery(this).parent().parent()).attr('id')) {				
				itemId = jQuery(jQuery(this).parent().parent()).attr('id').substring(4);
				tr = 'tr#item'+itemId;
			} else {
				tr = 'tr:last';
			}
			var crawlerURL = jQuery('#robotItems tbody '+tr+' #crawlerURL').val();
			var placeId = jQuery('#robotItems tbody '+tr+' #placeId').val();
			var categoryId = jQuery('#robotItems tbody '+tr+' #categoryId').val();
			fnRobotEditor.saveItem(robotId, itemId, crawlerURL, placeId, categoryId);
		});		
		jQuery('#robotItems tbody .linkCancel').click(function(e) {
			e.preventDefault();
			var robotId = jQuery('#editRobotDiv #robotId').val();
			fnRobotEditor.loadItemTable(robotId);
		});
	},
	
	getItemEditor:function() {
		return "<td><input type='text' id='crawlerURL'/></td>"+
			"<td><select id='placeId'></select></td>"+
			"<td><select id='categoryId'></select></td>"+
			"<td colspan='2'><a class='linkCancel' href='#'>Peruuta</a>&nbsp;&nbsp;<a class='linkSave' href='#'>Tallenna</a></td>";
	},
	
	prepareItemEditorSelects:function() {
		
		// initiate place select
		var placeSelect = jQuery('#robotItems #placeId');
		var options = '';
		for (i = 0; i < placeArray.length; i++) {
			options += '<option value="'+placeArray[i].val+'">'+placeArray[i].text+'</option>';
		}
		placeSelect.html(options);
		
		// initiate category select
		var categorySelect = jQuery('#robotItems #categoryId');
		options = '';
		for (i = 0; i < categoryArray.length; i++) {
			options += '<option value="'+categoryArray[i].val+'">'+categoryArray[i].text+'</option>';
		}
		categorySelect.html(options);		
	},

	saveItem:function(robotId, itemId, url, placeId, categoryId) {
		var urlParams = '';
		if (itemId != null) {
			urlParams += "itemId=" + itemId + "&";
		}
		urlParams += "id="+ robotId + "&crawlerURL=" + url + "&placeId=" + placeId + "&categoryId=" + categoryId;
		jQuery.ajax( {
			type : "POST",
			url : "edit_robot_item.php",
			data: urlParams,
			dataType : "json",
			success : function(data) {
				if ((data != null) && (data.success == true)) {
					jQuery.jGrowl("Tapahtumapaikka tallennettu.");
					fnRobotEditor.loadItemTable(data.robotItem.robotId);
				} else {
					jQuery.jGrowl("Tapahtumapaikan tallentaminen epäonnistui", {header: "Virhetilanne"});
				}
			},
			error : function(data) {					
				jQuery.jGrowl("Tuntematon virhe", {header: "Virhetilanne"});
			}
		});
	},
	
	removeItem:function(id) {
		jQuery.ajax( {
			type : "POST",
			url : "delete_robot_item.php",
			data: "id=" + id,
			dataType : "json",
			success : function(data) {
				if ((data != null) && (data.success == true)) {
					jQuery.jGrowl("Tapahtumapaikka on poistettu");
					fnRobotEditor.loadItemTable(data.robotId);
				} else {
					jQuery.jGrowl("Tapahtumapaikan poistaminen epäonnistui", {header: "Virhetilanne"});
				}
			},
			error : function(data) {
				jQuery.jGrowl("Tuntematon virhe", {header: "Virhetilanne"});
			}
		});
	},
	
	startCrawling : function(src) {		
		var href = jQuery(src).attr('href');
		var id = href.substring(href.indexOf('=') + 1);
		var loadingImageSrc = "<img id='loader"+id+"' height='10' width='10' src='"+loadingImage.src+"'/>";
		jQuery.ajax( {
			type : "GET",
			url : href,
			dataType : "json",
			beforeSend: function() {
				jQuery(src).replaceWith(loadingImageSrc);
			},
			complete : function() {
				var loadingImage = jQuery('#loader'+id);
				jQuery(loadingImage).replaceWith(src);
				jQuery(src).click(function(e) {
					e.preventDefault();
					var link = jQuery(this);				
					fnRobotEditor.startCrawling(link);
				});
			},
			success : function(data) {
				if ((data != null) && (data.success == true)) {					
					jQuery.jGrowl("Lisättyjä tapahtumia: "+data.inserted+"<br/>Päivitettyjä tapahtumia: "+data.updated, {header: data.robotItem.place.name});
					jQuery('#robotItems #item'+data.robotItem.id+' td:nth-child(4)').text(data.robotItem.lastUpdated);
				} else {
					jQuery.jGrowl("Tapahtumatietojen hakeminen epäonnistui", {header: "Virhetilanne"});
				}
			},
			error : function(data) {
				jQuery.jGrowl("Tuntematon virhe", {header: "Virhetilanne"});
			}
		});
	}
};

fnEventEditor = {
	
	init : function() {
		jQuery('#eventEditDiv #btnCancel').click(function(e) {
			e.preventDefault();
			window.parent.tb_remove();
		});
		
		jQuery('#eventEditDiv #btnSubmit').click(function(e) {
			e.preventDefault();
			var form = jQuery('#eventForm');
			form.submit();
		});
		
		jQuery('#eventSavedDiv #btnClose').click(function(e) {
			e.preventDefault();
			window.parent.tb_remove();
		});
	},
	
	eventSaved : function() {
		window.parent.jQuery('#eventTools .linkFilter').click();
		setTimeout(function() { window.parent.tb_remove(); }, 4000);
	}
}

function cout(sMsg) {
	if (!!window.console)
		console.log(sMsg);

	if (!!window.log)
		log.info(sMsg);

	if (!!window.opera && !!window.opera.postError)
		opera.postError(sMsg);
}
