
/*
*	this code generates an XML block from the fields on the page, we key into the GravityForms via class names prefixed w/ xfld-
*	the code is dependent upon Michal Korecki's json2xml jQuery plugin, www.michalkorecki.com
*
*	this code populates a select list from the server so that we can reload the form and make updates to a given business
*
*	allen @joslin .net -- 10/2010
*/

function dbg (msg) { if (false) { if (console && console.log) { console.log(msg); } } };

$(document).ready(function(){

	$('.xhdr-listing').before('<div><select id="xmls"><option disabled="disabled" value="0">These are the businesses already saved to the server</option></select></div>');
	$.get('/xml-data/xml-listing.php', function(data){ $('#xmls').addOption(JSON.parse(data)).selectOptions('0',true); });

	$('#gform_submit_button_1').click(function(event) {

		try {

			var entityType = 'Business';
			var nodeList = []; var entityData = {};
			$('.gfield').map(function( ndx, domE ){

				try {

					var classes = $(this).attr('class').split(/ +/);
					for (var ndx in classes) {
						if (classes[ndx].split(/-/)[0] == 'xfld') {

							try {

								var name = classes[ndx].split(/-/)[1];
								var value = $(this).find('input').val();

								if ($(this).find('input:checkbox').length) { value = []; $(this).find('input:checkbox:checked').each(function(){ value.push($(this).val()); }); value = value.join(','); }
								if ($(this).find('[type="file"]').length) { value = $(this).find('[type="file"]:prev("label")').attr('name'); }
								if ($(this).find('input:radio').length) { value = $(this).find('input:radio:checked').val(); }
								if ($(this).find('textarea').length) { value = $(this).find('textarea').val(); }
								if ($(this).find('select').length) { value = $(this).find('select').val(); }

								if ($(this).css('display') != 'none') {
									entityData[name] = value.replace('&','&amp;');
									nodeList.push(entityType+'.'+name);
								}

							}
							catch (ex) { dbg('inner exception: '+ex); }
						}
					}
				}
				catch (ex) { dbg('outer exception: '+ex); }
			});

			if (! entityData.location)         { throw 'You must choose a location';          }
			if (! entityData.name)             { throw 'You must choose a name';              }
			if (! entityData.subtitle)         { throw 'You must choose a subtitle';          }
			if (! entityData.desc)             { throw 'You must choose a desc';              }
			if (! entityData.address1)         { throw 'You must choose an address1';         }
			if (! entityData.city)             { throw 'You must choose a city';              }
			if (! entityData.state)            { throw 'You must choose a state';             }
			if (! entityData.zipcode)          { throw 'You must choose a zipcode';           }
			if (! entityData.phoneNumber)      { throw 'You must choose a phoneNumber';       }
			if (! entityData.price)            { throw 'You must choose a price';             }
			if (! entityData.Text_Color)       { throw 'You must choose a Text_Color';        }
			if (! entityData.advertisingLevel) { throw 'You must choose an advertisingLevel'; }

			if (entityData.businessType_1 == "Select PRIMARY Business Type") { throw 'You must choose a Primary Business Type'; }

			if (entityData.latitude && isNaN(entityData.latitude)) { throw 'Latitude must be a number'; }
			if (entityData.longitude && isNaN(entityData.longitude)) { throw 'Longitude must be a number'; }

			var data = {}; 
			data['version'] = '1.0';

			businessType1 = entityData.businessType_1;

			nodeList.push('business_id'); // add a key to the Business node			
			entityData.business_id = entityData.name;

			// workaround Gravity Forms inability to handle Values in Conditional Logic
			var rightFields = [ 'KidStuff', 'HealthSpa', 'RentalRepair', 'TheArts' ];
			var wrongFields = [ 'Kid Stuff', 'Health/Spa', 'Rental Repair', 'The Arts' ];
			for (var x in wrongFields) { if (entityData.businessType_1 == wrongFields[x]) { entityData.businessType_1 = rightFields[x]; } }
			for (var x in wrongFields) { if (entityData.businessType_2 == wrongFields[x]) { entityData.businessType_2 = rightFields[x]; } }
			for (var x in wrongFields) { if (entityData.businessType_3 == wrongFields[x]) { entityData.businessType_3 = rightFields[x]; } }

			entityData.categories = []; var cat_0 = '<categories/>'; // make a replaceable item, store things to replace into it
			var cat_1 = (entityData[entityData.businessType_1] == undefined)?'': (entityData.businessType_1)? '<categories businessType="'+entityData.businessType_1+'">'+entityData[entityData.businessType_1]+'</categories>': '';
			var cat_2 = (entityData[entityData.businessType_2] == undefined)?'': (entityData.businessType_2)? '<categories businessType="'+entityData.businessType_2+'">'+entityData[entityData.businessType_2]+'</categories>': '';
			var cat_3 = (entityData[entityData.businessType_3] == undefined)?'': (entityData.businessType_3)? '<categories businessType="'+entityData.businessType_3+'">'+entityData[entityData.businessType_3]+'</categories>': '';

			// remove all the businessType and related entities
			delete entityData.businessType_1; delete entityData.businessType_2; delete entityData.businessType_3; 
			$('.xfld-businessType_1 select option').each(function(){ delete entityData[$(this).val()]; });

			// push custom colors into parent fields
			if (entityData['Custom_Color']) { entityData['Text_Color'] = entityData['Custom_Color']; delete entityData['Custom_Color']; }
			if (entityData['Custom_BKG_Color']) { entityData['BKG_Color'] = entityData['Custom_BKG_Color']; delete entityData['Custom_BKG_Color']; }

			// these are workarounds for GF's inability to handle values
			delete entityData.RentalRepair; delete entityData.TheArts;
			delete entityData.KidStuff; delete entityData.HealthSpa; 

			data[entityType] = entityData; // final assembly and running json2xml plugin -- there is still some cleaup required after that
			var xmlText = $.json2xml( data, { formatOutput: true, formatTextNodes: false, indentString: '  ', rootTagName: 'xml', ignore: [], replace: [], nodes: nodeList } );

			// swap in the categories & category labels
			cat_1 = (cat_1)? cat_1+'\n    ': ''; cat_2 = (cat_2)? cat_2+'\n    ': '';
			xmlText = xmlText.replace(cat_0,cat_1+cat_2+cat_3);
			$('.xfld-businessType_1 select option').each(function(){ xmlText.replace($(this).val(),$(this).text()); });

			// these are workarounds for GF's inability to handle values
			xmlText = xmlText.replace(/KidStuff/g,'Kid Stuff');
			xmlText = xmlText.replace(/HealthSpa/g,'Health/Spa');
			xmlText = xmlText.replace(/RentalRepair/g,'Rental Repair');
			xmlText = xmlText.replace(/TheArts/g,'The Arts');

			// fuk the xml -- it's what they want
			xmlText = xmlText.replace('<xml version="1.0">','<?xml version="1.0"?>');
			xmlText = xmlText.replace('</xml>','');			

			var callOpts = { url: 'http://www.richlaur.com/xml-data/xml-upload.php', type: 'POST', data: { bid: entityData.business_id, xml: xmlText, lid: entityData.location, pid: businessType1 } };
			dbg('callOpts: '+JSON.stringify(callOpts));

			$.ajax(callOpts);
			dbg(xmlText);

			alert('enrolled');

		}
		catch (ex) { alert(ex); }
		return false; // do not propogate the submit button click
	});

});


// done

