﻿/**
 * lottaservices : Ajax extension for eZ Publish 4.x
 * Created on	 : <01-Apr-2010 00:00:00 jk>
 * 
 * This piece of code depends on YUI 3.0 and eZJSCore ( Y.io.ez() plugin ).
 *
 * @copyright Copyright (c) 2010, lemonjuice
 * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2.0
 * @package eZ Starating extension for eZ Publish
 *
 */
 // http://share.ez.no/articles/ez-publish/ezjscore-ez-publish-javascript-and-ajax-framework/(page)/7
 
 
//alert ('lottaservices yui3 is here. 25.4.2010 14:05.'); 
// Create new YUI instance, and populate it with the required modules
// http://developer.yahoo.com/yui/3/node/
YUI( YUI3_config ).use('node', 'event', 'io-ez', 'io-form', function( Y )
{
	Y.on( "domready", function( e )
	{
	   //alert ('lottaservices domready yui3'); 
	   
	   Y.all('form.lottaservices-create-form-input-ajax-form').each( function( node ){
			//alert ('found form yui3 form.lottaservices-create-form-input-ajax-form');
		} );
	   Y.all('form.lottaservices-create-form-input-ajax-form').on( 'submit', _create_form_input_submit_form );
	   
	   /*
	   //Y.all('a.lotta_deletecomment_link').each( function( node ){
	   //	 alert ('found a.lotta_deletecomment_link yui3');
	   // } );
	   Y.all('a.lotta_editcomment_link').on( 'click', _edit_comment_show_form );
	   
	   //Y.all('a.lotta_deletecomment_link').each( function( node ){
	   //	 alert ('found a.lotta_deletecomment_link yui3');
	   // } );
	   Y.all('a.lotta_deletecomment_link').on( 'click', _delete_comment_submit );
	   
	   //Y.all('a.lotta_createcomment_link').each( function( node ){
	   //	 alert ('found a.lotta_createcomment_link yui3');
	   // } );
	   Y.all('a.lotta_createcomment_link').on( 'click', _create_comment_show_form );
	   
	   //Y.all('form.lottaservices-create-comment-ajax-form').each( function( node ){
	   //	 alert ('found form yui3');
	   // } );
	   Y.all('form.lottaservices-create-comment-ajax-form').on( 'submit', _create_comment_submit_form );
		*/
	   

	});
	
	
	/**
	 * @method _parseFields
	 * @private
	 * @param {Y.Node} contentBox
	 * @description Sets the 'fields' attribute based on parsed HTML
	 */
	function _parseFields  (contentBox) {
		var children = contentBox.all('*'),
			labels = contentBox.all('label'),
			fields = [];
		
		children.each(function(node, index, nodeList) {
			var nodeName = node.get('nodeName'), 
				nodeId = node.get('id'),
				o, c = [];
			if (nodeName == 'INPUT') {
				o = {
					type: node.get('type'),
					name : node.get('name'),
					value : node.get('value'),
					disabled : node.get('disabled'),
					checked  : node.get('checked')
				};
				
				if (o.type == 'submit' || o.type == 'reset' || o.type == 'button') {
					o.label = node.get('value');
				}
			} else if (nodeName == 'BUTTON') {
				o = {
					type : 'button',
					name : node.get('name'),
					label : node.get('innerHTML'),
					disabled : node.get('disabled')
				};
			} else if (nodeName == 'SELECT') {
				node.all('option').each(function (optNode, optNodeIndex, optNodeList) {
					c.push({
						label : optNode.get('innerHTML'),
						value : optNode.get('value'),
						disabled : node.get('disabled')
					});
				});
				o = {
					type : 'select',
					name : node.get('name'),
					disabled : node.get('disabled'),
					value : node.get('value'),
					choices : c
				};
			} else if (nodeName == 'TEXTAREA') {
				o = {
					type: 'textarea',
					name : node.get('name'),
					//value : node.get('innerHTML'),
					value : node.get('value'),
					disabled : node.get('disabled')
				};
			}		
			// probably radionbox is missing here
			
			if (o) {
				if (nodeId) {
					o.id = nodeId;
					labels.some(function(labelNode, labelNodeIndex, labelNodeList) {
						if (labelNode.get('htmlFor') == nodeId) {
							o.label = labelNode.get('innerHTML');
						}
					});
				}
				fields.push(o);
			}
			//node.remove();
		});

		return fields;
	}
	
	
	function _create_form_input_submit_form(e)
	{
		try
		{
			//lottaHideDiv('lotta_create_formular_eingang');
			lottaShowDiv('lotta_create_formular_eingang_response');
			lottaShowDiv('lotta_create_formular_eingang_response_ajax_waiting');
			/*
			lottaShowDiv('lotta_create_formular_eingang_response');
			lottaShowDiv('lotta_create_formular_eingang_response_ajax_waiting');
			lottaHideDiv('lotta_create_formular_eingang_response_ajax_success');
			lottaHideDiv('lotta_create_formular_eingang_response_ajax_failure');
			*/
			
			//alert ('_create_form_input_submit_form yui3 12:50 ');
			e.preventDefault();
			var f = e.currentTarget._node;
			var useDf = false;
			
			var data = [];
			var el = 0;
			var s = {};
			
			// jok. 24.4.2010 changed from buggy original ez-sarrating example to a mor Yui3 conform query.
			/*
			for (i = 0, il = f.childNodes.length; i < il; ++i) 
			{
				var e = f.childNodes[i];
				var d = e.disabled;
				var n = e.name;
				allNames += i + n + "/";

				if ((useDf) ? n : (n && !d)) 
			*/
			//alert (" f.childNodes.length " + f.childNodes.length);
			var allNames = "";
			//var nodes = e.currentTarget.all('input, select, button, textarea'); // uses css-selector
			var yuiNode = e.currentTarget;
			var nodes = _parseFields (yuiNode); // this is better for us.

			
			for (i = 0, il = nodes.length; i < il; ++i) 
			{
				var e = nodes[i];
				var d = e.disabled;
				var n = e.name;
				var v = e.value;
				allNames += i + n + "/";

				if ((useDf) ? n : (n && !d)) 
				{
					
					n = encodeURIComponent(n) + '=';
					v = encodeURIComponent(e.value);
					switch (e.type) {
						// Safari, Opera, FF all default options.value from .text if
						// value attribute not specified in markup
						case 'select-one':
							if (e.selectedIndex > -1) {
								o = e.options[e.selectedIndex];
								data[el++] = n + eUC((o.attributes.value && o.attributes.value.specified) ? o.value : o.text);
							}
							break;
						case 'select-multiple':
							if (e.selectedIndex > -1) {
								for (j = e.selectedIndex, jl = e.options.length; j < jl; ++j) {
									o = e.options[j];
									if (o.selected) {
									  data[el++] = n + eUC((o.attributes.value && o.attributes.value.specified) ? o.value : o.text);
									}
								}
							}
							break;
						case 'radio':
						case 'checkbox':
							if(e.checked){
								data[el++] = n + v;
							}
							break;
						case 'file':
							// stub case as XMLHttpRequest will only send the file path as a string.
						case undefined:
							// stub case for fieldset element which returns undefined.
						case 'reset':
							// stub case for input type reset button.
						case 'button':
							// stub case for input type button elements.
							break;
						case 'submit':
						default:
							data[el++] = n + v;
					}
				}
			}
			//alert (allNames);
			var datastring = data.join('&');
			// alert ("call  lottaservices::lottaservices_create_formular_input  with data: \n" + datastring);
			// ezjscore.ini FunctionList[];
			Y.io.ez( 'lottaservices::lottaservices_create_formular_input', { on : { success: _create_form_input_submit_callback }, data: datastring } );
			
		}
		catch (e)
		{
			alert (e);
		}		
	}
	function _create_form_input_submit_callback( id, o )
	{
		try
		{
			//alert ("_create_form_input_submit_callback " + id + " " + o);
			if ( o.responseJSON && o.responseJSON.content !== '' )
			{
				var data = o.responseJSON.content;
				//alert ("response: " + data  + ' message: ' + data.message + ' version: ' + data.version);
				//alert (" success: " + data.success);
				lottaHideDiv('lotta_create_formular_eingang_response_ajax_waiting');
				lottaHideDiv('lotta_create_formular_eingang_response_ajax_failure');
				lottaHideDiv('lotta_create_formular_eingang_response_ajax_success');
				lottaShowDiv('lotta_create_formular_eingang_response');
				
				var ajaxSuccess = ((data.success == 'true') || (data.success == '1')); 
				if (ajaxSuccess)
				{
					//alert ("Ok!");
					//var insertedID = data.insertedID;
					//var insertedObject = data.object;
					//var insertedSubject = insertedObject.subject;
					//var insertedPublished = insertedObject.published;
					//var insertedAuthorName = insertedObject.authorName;
					//var insertedAuthorLogin = insertedObject.authorLogin;  not yet implemented in service
					//var insertedAuthorEmail = insertedObject.authorEmail;
					//var insertedMessage = insertedObject.message;
					//alert ("insertedSubject: " + insertedSubject);
	
					//alert ("try to show lotta_createcomment_response_ajax_success");
					lottaShowDiv('lotta_create_formular_eingang_response_ajax_success');
					Y.get('#lotta_create_formular_eingang_response_ajax_success').setContent( data.message );
				}
				else
				{
					//alert ("Es ist ein Fehler aufgetreten!");
					//alert ("try to show lotta_create_formular_eingang_response_ajax_failure");
					lottaShowDiv('lotta_create_formular_eingang_response_ajax_failure');
					var htmlMessage = data.message.replace(/\n/g, "<br/>")
					Y.get('#lotta_create_formular_eingang_response_ajax_failure').setContent( htmlMessage );
				}
			}
			else
			{
				lottaHideDiv('lotta_create_formular_eingang_response_ajax_waiting');
				lottaHideDiv('lotta_create_formular_eingang_response_ajax_success');
				
				lottaShowDiv('lotta_create_formular_eingang_response');
				lottaShowDiv('lotta_create_formular_eingang_response_ajax_failure');
				
				// This shouldn't happen as we have already checked access in the template..
				// Unless this is inside a aggressive cache-block of course.
				alert( o.responseJSON.error_text );
				Y.all('#lotta_create_formular_eingang_response_ajax_failure').setContent( 'Http-Error: ' + o.responseJSON.error_text );
			}
		}
		catch (e)
		{
			alert (e);
		}
	}
	
});

