
// generic enumeration
Function.prototype.forEach = function(object, block, context) {
    for (var key in object) {
        if (typeof this.prototype[key] == "undefined") {
            block.call(context, object[key], key, object);
        }
    }
};

var forEach = function(object, block, context) {
    if (object) {
        var resolve = Object; // default
        if (object instanceof Function) {
            // functions have a "length" property
            resolve = Function;
        } else if (object.forEach instanceof Function) {
            // the object implements a custom forEach method so use that
            object.forEach(block, context);
            return;
        } else if (typeof object.length == "number") {
            // the object is array-like
            resolve = Array;
        }
        resolve.forEach(object, block, context);
    }
};


function processModalForm(target, context) {
	log('processing modal forms...');
	if(context === null) context = 'document';
	log(target);
	log(context);
	
	$(target, context).submit(function(e) { 
		log('#promt form.submit');
		log('this:');
	
		log(this); 
	
		// discover our action by asking the form for the url
		var action = $(this).attr('action');
	
		// discover the button that opened the overlay.
		// then close the overlay associated with it
		//
		// The button targets this form's parent by id
	
		// Find the id
		var id = $(this).parent().attr('id');
	
		// Look for the button via the 'rel' attribute
		var button = $( '.modalInput[rel=#' + id + ']' );
		
		log('found ' + button.length + ' buttons');
		
		// close the overlay
		
		// This old way only allowed for 1 button...
		//button.overlay().close();
		
		// This new way allows for multiple buttons to open the same overlay.
		button.each( function() {
			$(this).overlay().close();
		});
		
	
		// Create the parameter string to send to the ajax script
		var params = $(this).serialize();
		params += '&rel=#' + $(this).parent().attr('id'); // this is the admin modal window form
		params += '&target=' + $(this).attr('rel'); // This is the related item in the dom that we are editing
	
		log('params:');
		log(params);
	
		$.post('?ajax=TRUE&url=' + action,
			params,
			onAjaxResponse,
			'json');
	
	    // do not submit the form 
	    return e.preventDefault(); 
	}).
	find('button.close').click( function(e) {
		// Grab the id of the parent element
		var id = $(this).parent().attr('id');
	
		// Look for the button via the 'rel' attribute
		var button = $( '.modalInput[rel=#' + id + ']' );
	
		// close the overlay
		button.overlay().close();
	});
	
	// log('processing form file "' + target + '", "' + context + '"');
	// 
	// log($(context));
	// log($(target + ' > input'));
	// log($(target + ' > input[type=file]'));
	// log($(target + ' > input[type=file]', context));
	
	var form = $(target, context);
	var action = form.attr('action');
	
	log('action = ' + action);
	
	$(target + ' > input[type=file]', context).makeAsyncUploader({
		upload_url: action, // Important! This isn't a directory, it's a HANDLER such as an ASP.NET MVC action method, or a PHP file, or a Classic ASP file, or an ASP.NET .ASHX handler. The handler should save the file to disk (or database).
		flash_url: '/delicious_cms/library/js/jquery.plugins/jquery-asyncUpload-0.1/swfupload.swf',
		button_image_url: '/delicious_cms/library/js/jquery.plugins/jquery-asyncUpload-0.1/blankButton.png'
	});
	
	$(target, context).removeClass('unprocessed');
}

function initializeModalForm(target, context) {
	
	if(context === null) context = 'document';
		
	/**
	 * For each modal form this will find any linked elements in the dom
	 * and place their values into the form elements, thus setting the default value
	 * of each input to the current value of the linked element.
	 */
	$(target, context).each( function() {
		log(this);
		
		// Find the related item
		// This provides the link to the target element
		
		var rel_target = $(this).attr('rel');
		
		log('rel_target = ' + rel_target);
		
		var target = $(rel_target);
		
		$('input', this).each( function() {
			
			log('BEGIN setting default value of form input...');
			
			log(this);
			
			var rel_item = $(this).attr('rel');
			
			log('rel_item = ' + rel_item);
		
			// If there was a related attribute 'rel', then there is a related dom item
			// 
			// First we look for a rel of 'this' which means we want to set
			// an attribute of the current target
		
			if(rel_item == 'this') {
				log('	setting "this" to default...');
				rel_item = '[id=' + target.attr('id') + ']';
				log('rel_item = ' + rel_item);
				var name = $(this).attr('name');
				log('		name = ' + name);
				var value = $(rel_item).attr( name );
				log('		value = ' + value);
				$(this).val(value);
			}
		
			// Otherwise we want to set the html of the current target
		
			else if(rel_item) {
				log('	setting ' + rel_item + ' to default value...');
				var value = $(rel_item, target).html();
				$(this).val(value);
			}
			
			log('END setting default value of form input...');
		});
		
	});
}

function onAjaxResponse(data, textStatus) {
	log("onAjaxResponse...");
	log("	textStatus = " + textStatus);
	log("	success = " + data.success);
	if(data.error != '') {
		log("	error = " + data.error);
	}
	
	var form = $(data.rel + ' form');
	var target = $(data.target);
	
	/*log('form:');
	log(form);
	log(form.html());*/
	/*log('target:');
	log(target.html());*/
	
	// If we are told to redirect to a new page, do that here
	
	if(data.redirect != null && data.redirect != '' && data.redirect != undefined) {
		log('data.redirect = ' + data.redirect);
		if(data.redirect == 'CURRENT') {
			window.location = window.location;
		}
		else {
			window.location = data.redirect;
		}
	}
	
	// Otherwise try to update the dom based on the json instructions
	
	else {
		forEach( data, function(element, index, array) {
		
			log('trying to set "' + index + '" to "' + element + '"');
		
			// Get the related item id from the attributes of this form element
			var rel = $('[name=' + index + ']', form).attr('rel');
		
			log('rel:"' + rel + '"');
		
			// If there was a related attribute 'rel', then there is a related dom item
			// 
			// First we look for a rel of 'this' which means we want to set
			// an attribute of the current target
		
			if(rel == 'this') {
				rel = '[id=' + target.attr('id') + ']';
				$(rel).attr(index, element);
			}
		
			// Otherwise we want to set the html of the current target
		
			else if(rel) {
				log('setting...');
				log($(rel, target));
				$(rel, target).html(element);
			}
		});
	}
}

$(document).ready( function() {
	
	// log('will process .modal form.unprocessed...');
	
	if($(".modal form.unprocessed").length > 0) {
		processModalForm(".modal form.unprocessed");
	}
	
	if($(".modalInput.unprocessed").length > 0) {
		/**
		 * This will turn all .modalInput elements into an overlay that opens when
		 * its target element is pressed.
		 */
		$(".modalInput.unprocessed").overlay({ 
		
			closeOnClick: false,
		
			// some expose tweaks suitable for modal dialogs 
			expose: { 
				color: '#fff', 
				loadSpeed: 200, 
				opacity: 0.7,
				closeOnClick: false,
				onLoad: function(event) {
					// Try to focus the first input element of the form
					var exposed = $('input', this.getExposed());
					if(exposed.length > 0) {
						exposed[0].focus();
					}
					//$('input', this.getExposed())[0].focus();
				}
			},
		
			/**
			 * If the target item has an 'external_url' attribute then that url will be used
			 * to load the contents via ajax. This is used to grab dynamic forms as requested.
			 */
			onBeforeLoad: function(event) { 
			
				if(this.getTrigger().attr("external_url")) {
				
					// grab wrapper element inside content 
					var wrap = this.getContent(); 
			
					// Build the data variablet to pass into the load command
				
					var data = 'target_id=' + escape(this.getTrigger().attr("rel").replace('#', '').replace('_admin', ''));
					data+= '&location=' + escape(this.getTrigger().attr("location"));
				
					// Insert the preloader so the user knows that something is going on
			
					wrap.html('<div class="preloader"><h1 class="center">loading...</h1><img src="delicious_cms/library/img/ajax-loader_bar.gif" /></div>');
				
					// load the page specified in the trigger 
					wrap.load(this.getTrigger().attr("external_url"), data, function(data) {
					
						// This function is called after the content is fully loaded
					
						log('wrap.load complete');
						log('data:');
						log(data);
					
						// @work
						// This is a hack cause the script needs to return
						// html to fill this wrapper if SUCCESSFUL
						// otherwise we need some note that it failed, which
						// is supplied via json.
					
						var useJSON = false;
						try {
							jsondata = eval("(" + data + ")");
							// log(jsondata);
							useJSON = true;
						}
						catch(e) {
							//nothing here
						}
					
						// If we find json data AND it tells us the results are
						// false then close this modal dialog
					
						if(useJSON && jsondata.success === false) {
						
							// Find the id
							var id = $(this).attr('id');
						
							log('id=' + id);
						
							// Look for the button via the 'rel' attribute
							var button = $( '.modalInput[rel=#' + id + ']' );
		
							log('button:');
							log(button);
						
							// close the overlay
							button.overlay().close();
						}
					
						// We have successfully retrieved the form content for this
						// modal dialog...process it and exit.
						else {
							processModalForm("form.unprocessed", this);
							//initializeModalForm('form', this);
						}
					
					}); 
				}
				else {
					// processModalForm("form.unprocessed", this);
				}
			} 
		}).removeClass('unprocessed'); 
	}
	
});

