

// receives some javascript object and outputs a string of its contents								  
var enumerator = function( obj ){
	
	var val = "",
		counter = 0,
		formattedVal = val;

	if (typeof obj === "undefined") {
		val = "undefined";
		formattedVal = val;
	}
	else if (obj === null) {
		val = "null";
		formattedVal = val;
	}
	else if (typeof obj === "string") {
		val = obj;
		formattedVal = '"' + val + '"'
	}
	else if (typeof obj.call !== "undefined") {
		val = (counter++?", ":"") + String(obj.valueOf()).replace(/[\r\n\s]/g, "").replace(/function/,"function ");
		formattedVal = val;
	}
	else {
		var isArray = (typeof obj.join !== "undefined");
		for(sub in obj ) {
			val += (counter++?", ":"") +  (isArray?"": sub + ": " ) + enumerator(obj[sub])
		}
		if (isArray) {
			formattedVal = '[ '+val+' ]';
		}
		// is object
		else {
			formattedVal = '{ '+val+' }'
		}
		
	}

	return val?formattedVal:obj;
};

/*
 
 -----------------------------------------
   ajax-forms.js
 -----------------------------------------

 * @version 0.2.1
 * @author LBi - http://www.lbi.com/en
 * @requires jQuery Core 1.3.2 - http://www.jquery.com/
 * @requires jQuery Form plugin - http://malsup.com/jquery/form/

*/

/*jslint eqeqeq: true, undef: true */
/*global $, jQuery, BTT, window, document, swfobject, confirm, prompt  */

/**
 * AJAXy stuff.
 * @namespace AJAXy stuff.
 * @member BTT
 */
BTT.AJAX = {
	defaultElementToReplace : 'body',
	isInLightbox : false,
	classNames : {
		lightboxActiveClass : 'contentAreaHighlight'
	},
	/**
	* AJAX.Forms is an object that enables forms to be submitted asynchronously
	**/
	Forms : {
		submitButtonsArray : [],
		defaultFormElement : $('form'),
		lightboxToDestroy : null,
		nameSpace : 'form-plugin',
		classNames : {
			submitButtonsClass : 'JS_ajaxSubmit',
			fileUploadClass : 'JS_uploadFile',
			MEForm : 'JS_MEForm'
		},
		options : { 
			beforeSubmit:	null,	// pre-submit callback 
			success:		null, 	// post-submit callback
			//target:	 id			// target element(s) to be updated with server response 
			//url:		 url		// override for form's 'action' attribute 
			//type:		 type		// 'get' or 'post', override for form's 'method' attribute 
			//dataType:	 null		// 'xml', 'script', or 'json' (expected server response type) 
			//clearForm: true		// clear all form fields after successful submit 
			//resetForm: true		// reset the form after successful submit 
			// $.ajax options can be used here too, for example: 
			//timeout:	 3000
			cache: false
		},
		
		/**
		* createSubmitButtonsArray is a function that creates an array of submit buttons
		* each trigger has a class starting with 'JS_ajaxSubmit'
		*/
		createSubmitButtonsArray : function(className){
			// get all the triggers on the page
			var submitButtonsTriggers = $('*[class*="'+ className +'"]'),
				tempInput = '',
				tempArray = [],
				regExp = BTT.AJAX.Forms.classNames.submitButtonsClass+'\\(([^\\)]*)\\)',
				i = 0,
				tempGetId = '',
				tempPlaceId = '',
				regExp = new RegExp(regExp);
			// loop through all the triggers in the page and assign them into array based upon what is within the class attribute
			for(i = 0; i < submitButtonsTriggers.length; i=i+1){
				tempInput = submitButtonsTriggers[i].className;
				// tempGetId & tempPlaceID is the bit of the classname between the parentheses
				tempInput = tempInput.match(regExp);
				tempArray = tempInput[1].split(',');
				tempGetId = tempArray[0];
				if (tempArray.length > 1) {
					tempPlaceId = tempArray[1];
				}
				//push parsed string into the array
				BTT.AJAX.Forms.submitButtonsArray.push({
					submitButtonsTrigger: submitButtonsTriggers[i],
					getId: tempGetId,
					placeId: tempPlaceId
				});	
			}
			//console.log("Array", submitButtonsTriggers);
		},
		activateButtons : function(getId,placeId,buttonTrigger) {
			
			//console.log("ActivateButtonsVars GetID:", getId + " PlaceID: " + placeId + " ButtonTrigger: " + buttonTrigger);
			/**
			 * This function activates buttons for submit via AJAX
			 */
			var handler = function(triggerEvent) {

				// Parameters
				var lightbox = placeId,
					contentWrap = null,
					button = null,
					formOptions = {},
					fileUploadId = 'uploadId',
					fileUploadProgressInterval = null,
					
					//function which creates and change the progress bar content
					fileUploadProgressUpdate = function(container, currentSize, totalSize) {
						
						var progressBarClassName = 'fileUploadProgress',
							currentPercent = 0,
							currentContainer = null,
							stringToChange = '',
							progressBarContainer = $('.' + progressBarClassName, container);
						
						// Create the progress bar if it doesn't already exist
						if ((container.hasClass(BTT.Lightboxes.classNames.contentLoaderClass)) && (progressBarContainer.length === 0)) {
							progressBarContainer = $('<div />')
								.addClass('fileUploadProgress')
								.append(
									$('<h1 />').html(BTT.Messages.Lightboxes.uploadFileHeader)
								)
								.append(
									$('<p />').html(BTT.Messages.Lightboxes.uploadFileText)
								)
								.append(
									$('<p />').html(BTT.Messages.Lightboxes.uploadFileTip)
								)
								.append(
									$('<div />').addClass('contentArea spacingBottomOne spacingTopTwo')
									.append(
										$('<div />').addClass('progressBar')
										.append(
											$('<span />').addClass('bar incomplete').css('width','0')
											.append(
												$('<span />').addClass('value').html('0')
											)
											.html('/')
											.append(
												$('<span />').addClass('best').html('100')
											)
										)
									)
								)
								.append(
									$('<div />').addClass('contentArea contentAreaAlignRight')
									.append(
										$('<p />')
											.addClass('status')
									)
								);
							container
								.css('background-image','none')
								.append(progressBarContainer);
						}
						
						if ((typeof currentSize !== "undefined") && (typeof totalSize !== "undefined")) {
							
							currentPercent = Math.round(currentSize*100/totalSize);
							currentContainer = progressBarContainer.find('.bar');
							
							if (currentPercent > parseInt(currentContainer.css('width'),10)) {
								currentContainer
									.animate( { width: currentPercent + '%'}, 'normal', 'linear', function() {
										if (currentSize === totalSize) {
											$(this).removeClass('incomplete');
										}
									})
									.children('.value').html(currentPercent);
								currentContainer = progressBarContainer.find('.status');
								
								var currentSizeKB = Math.round(currentSize/1024),
									totalSizeKB = Math.round(totalSize/1024),
									lightboxMessages = BTT.Messages.Lightboxes,
									stringToChange = "";
								
								if ( totalSizeKB <= 0 ) {
									stringToChange = lightboxMessages.uploadFileDetermining;
								} else {
									stringToChange = lightboxMessages.uploadFileStatus
														.replace(/\{0\}/, currentSizeKB)
														.replace(/\{1\}/, totalSizeKB);
								}

								currentContainer.html(stringToChange);
							}
							
						}
					};
				
				// If we have either a get ID or place ID, then
				if (!(((getId) === '') && (placeId === ''))) {
					if (lightbox > '') {
						lightbox = $('#'+lightbox);
					} else {
						lightbox = $('.'+BTT.Lightboxes.classNames.lightboxActiveClass);
					}
					$('.'+BTT.Lightboxes.classNames.closeButtonClass, lightbox).siblings().css('display','none');
					contentWrap = $('.'+BTT.Lightboxes.classNames.contentWrapClass+':first', lightbox);
					contentWrap.addClass(BTT.Lightboxes.classNames.contentLoaderClass);						
					
					// Set before submit function
					BTT.AJAX.Forms.options.beforeSubmit = BTT.AJAX.Forms.showRequest;
					
					// Set success function, sending the getID, placeID and form action
					BTT.AJAX.Forms.options.success = BTT.AJAX.Forms.showResponse(triggerEvent.data.getId, triggerEvent.data.placeId, $(this).closest('form').attr('action'));
					BTT.AJAX.Forms.options.complete = function(a, b, c){
					}
					
					// Update the data that gets sent with the AJAX request
					BTT.AJAX.Forms.options.data = [];
					
					// If the triggered button was a submit button, reset the AJAX form
					if ($(this).is(':submit')) {
						BTT.AJAX.Forms.options.data[$(this).attr('name')] = $(this).attr('value');
						$(this).closest('form')
							.ajaxFormUnbind()
							.ajaxForm(BTT.AJAX.Forms.options);
					}
					
					// If the triggered button was a file upload button, do the following
					else if ($(this).hasClass(BTT.AJAX.Forms.classNames.fileUploadClass)) {
						var tries = totalTries = 10, // Number of attempts at ajax request
							retryTime = 500;
							
						// Progress bar functionality
						fileUploadId = fileUploadId + '=' + BTT.Utilities.urlParamParser($(this).closest('form').attr('action'), fileUploadId);
						fileUploadProgressUpdate(contentWrap);
						fileUploadProgressInterval = window.setInterval(function(){
							var jsonUrl = (BTT.ctx ? BTT.ctx : '/ts') + '/media-editor/uploadUpdate?' + fileUploadId;
							
							$.ajax({
								url: jsonUrl,
								cache: false,
								dataType: "json",
								success: function(data, textStatus) {
									var currentSize = data.progress.bytesRead,
										totalSize = data.progress.contentLength;
									if(textStatus === 'success') {
	
										var paramsAreDefined = typeof currentSize !== "undefined" && typeof totalSize !== "undefined",
											noTriesLeft = tries < 1;
									
										if(paramsAreDefined || noTriesLeft) {
											if (paramsAreDefined) {
												fileUploadProgressUpdate(contentWrap, currentSize, totalSize);
											} else {
												fileUploadProgressUpdate(contentWrap, 80, 100);
											}
											if ((currentSize === totalSize) || tries < 1) {
												window.clearInterval(fileUploadProgressInterval);
											} 
										}else {
											tries--;
											
											fileUploadProgressUpdate(contentWrap, 100*((totalTries-tries)/(totalTries*2)), 100);
										}
									}
								},
								error: function(XMLHttpRequest, textStatus, errorThrown){
								},
								complete: function(xmlHttp) {
								}
							});
							
						}, retryTime);
						
						// Look for the first submit button within the container of the upload element,
						// We are going to assume this is the button that needs to be clicked
						button = $(this).closest('.contentArea').find(':submit:first');
						
						BTT.AJAX.Forms.options.data[button.attr('name')] = button.attr('value');
						
						$(this).closest('form')
							.ajaxFormUnbind()
							.ajaxForm(BTT.AJAX.Forms.options)
							.submit();
					}
				}
			};
			BTT.AJAX.Forms.defaultFormElement = $(buttonTrigger).closest('form');
			
			// Attach callback function 'handler' to change event of file upload button
			// and to the click event of all other buttons with AJAX submit
			if ($(buttonTrigger).hasClass(BTT.AJAX.Forms.classNames.fileUploadClass)) {
				$(buttonTrigger).bind('change', { getId : getId, placeId : placeId }, handler );
			} else {
				$(buttonTrigger).bind('click', { getId : getId, placeId : placeId }, handler );
			}
		},
		
		// pre-submit callback
		showRequest: function(formData, jqForm, options){

			// Work around to ensure file_decoy (see main.js) not sent to server
			$('[name=file_decoy]:gt(0)').each(function(){
				$(this).remove();
			});

			// formData is an array; here we use $.param to convert it to a string to display it 
			// but the form plugin does this for you automatically when it submits the data 
			var queryString = $.param(formData); 
		 
			// here we could return false to prevent the form from being submitted; 
			return true;
		},
	
	
		// post-submit callback 
		showResponse: function(getId, placeId, getUrl){

			var result = function(responseText, statusText){

				var loadNewContent = function(){
					if (BTT.AJAX.Forms.lightboxToDestroy === null) {
						var content = responseText,
							lightbox = placeId;
						// for normal html responses, the first argument to the success callback 
						// is the XMLHttpRequest object's responseText property
						if (lightbox > '') {
							lightbox = $('#'+lightbox);
						}
						if (getId > '') {
							if ($(content).find('#'+getId).length > 0) {
								if (typeof BTT.Omniture !== "undefined") {
									BTT.Omniture.omnitureInLightbox(content);
								}
								content = $(content).find('#'+getId);
							} else {
								content = $('<h1/>')
									.text(BTT.Messages.Lightboxes.ajaxWrongId);
								//.text("ERROR!")
							}
						} else {
							content = $(content);
							if ((getUrl !== undefined) && (getUrl !== '')) {
								window.location.replace(getUrl);
							} else {
								window.location.reload();
							}
						}
						$(content).find('img.JS_noCache').attr("src", function() { 
							return BTT.Utilities.noCache(this.src); 
						});
						$('.'+BTT.Lightboxes.classNames.closeButtonClass, lightbox).siblings().remove();
						$('.'+BTT.Lightboxes.classNames.contentWrapClass+':first', lightbox).css('background-image','');
						
						BTT.Lightboxes.changeLightboxContent(content,lightbox,false);
						BTT.Lightboxes.enableClose(lightbox,$(BTT.Lightboxes.lightboxParams.defaultTrigger),true);
					}
				}
				
				var retryTimer,
					attempts = 11,
					timeBetweenRetries = 500,
					timeOnSuccessState = 500;
					fileLoadedMsg = BTT.Messages.Lightboxes.uploadFileComplete;
				
				var attemptGetPage = function() {
					
					var bar = $('.bar')		// Assumes one bar on page
						barWidth = bar.width(),
						barParentWidth = bar.parent().width(),	
						isReady = attempts !== 11 && ((barWidth / barParentWidth) === 1)? true : false;

					if (barWidth === null) {
						loadNewContent();
					}
					else if (isReady || attempts-- <= 0) {
						
						bar.stop("true")
						bar.animate({width:"100%"}, "normal", "linear")
						
						$('.status').text( fileLoadedMsg )
						var timer = setTimeout(loadNewContent, timeOnSuccessState);
					}
					else {
						retryTimer = setTimeout(attemptGetPage, timeBetweenRetries);
					}
				}
				attemptGetPage();
			};
			return result;
		}
	},
	init: function(lightboxCall) {
		var MEForm = $('.'+BTT.AJAX.Forms.classNames.MEForm);
		BTT.AJAX.Forms.createSubmitButtonsArray(BTT.AJAX.Forms.classNames.submitButtonsClass);
		$(BTT.AJAX.Forms.submitButtonsArray).each(function(i){
			BTT.AJAX.Forms.activateButtons($(this)[0].getId,$(this)[0].placeId,$(this)[0].submitButtonsTrigger);
		});
		$(':input:not(:submit, :file)', MEForm).bind('focus.ME blur.ME', function(e){
			if (e.type === 'focus') {
				$(document).bind('keypress.ME', function(event){
					if (event.keyCode === 13){
						//$(e.target).closest('form')
						//return false;
					}
				});
			} else {
				$(document).unbind('.ME');
			}
		});
		$('input.'+BTT.AJAX.Forms.classNames.fileUploadClass).each(function() {
			var getId = 'mediaManager',
				placeId = '';
			BTT.AJAX.Forms.activateButtons(getId,placeId,$(this));
		});
	}
};

/* Initialise page when the DOM is ready
-------------------------------- */
$(document).ready(function(){	
	if ((typeof BTT.IE === "undefined") || (typeof BTT.IE.runAjaxAndLightboxes !== "undefined") && BTT.IE.runAjaxAndLightboxes !== false) {
		BTT.AJAX.init(false);
	}
});

