


/*** ASSET THUMB SELECT ***/


// pop up window to attach an asset
function assetAddPop(module,spec,attach_id,assetinuse_id,keywords) {

	// stop empty keywords being "underfined"
	if (!keywords) {
		keywords = '';
	}
	if (!assetinuse_id) {
		assetinuse_id = '';
	}
	
	var url = urlroot + '_code/lib_assets/_admin/_window_thumbs.php?args[module]=' + module + '&args[spec]=' + spec + '&args[attach_id]=' + attach_id + '&args[assetinuse_id]=' + assetinuse_id + '&search[keyword]=' + keywords;
	//alert(url);

	assetWin = new MochaUI.Window({
		id: 'assetWindow',
		type: 'modal',
		title: 'File Selector',
		loadMethod: 'xhr',
		contentURL: url,
		minimizable: false,
		width: 725,
		height: 475,
		onContentLoaded: function() {
			assetAddPopInit();
		}
	});
}

// 
function assetAddPopInit() {
	
	//alert('testb' + $$('#header_meta').length);
	//alert('testb' + $$('#assetWindow_content').length);
	
	/* change links to xhr */  
	$$('#assetWindow_content .xhrlinks a').addEvent('click', function(event) {  
		//prevent the page from changing  
		event.stop();  
		$('assetWindow_spinner').setStyle('visibility','visible'); 
		//make the ajax call, replace text  
		var req = new Request.HTML({  
			method: 'get',  
			url: this.get('href'),  
			onSuccess: function() {
				$('assetWindow_spinner').setStyle('visibility','hidden');
				// prep the dialog
				assetUploadPopInit();
			},
			onFailure: function() {
				$('assetWindow_spinner').setStyle('visibility','hidden'); 
				alert('need more cheese 2');
			},
			update: $('assetWindow_content')
		}).send();  
	});
	
	/* change form to xhr */  
	$$('#asset_search_button').addEvent('click', function(event) { 
		event.stop();  
		assetSubmitSearch();
	});
	$$('#asset_search').addEvent('submit', function(event) {  
		event.stop();  
		assetSubmitSearch(); 
	});
	function assetSubmitSearch() {
		//prevent the page from changing  
		$('assetWindow_spinner').setStyle('visibility','visible'); 
		//make the ajax call, replace text  
		var module = document.forms['asset_search'].elements['module'].value;
		var spec = document.forms['asset_search'].elements['spec'].value;
		var attach_id = document.forms['asset_search'].elements['attach_id'].value;
		var assetinuse_id = document.forms['asset_search'].elements['assetinuse_id'].value;
		var keyword = escape(document.forms['asset_search'].elements['search[keyword]'].value);
		var url = $('asset_search').get('action') + '?args[module]=' + module + '&args[spec]=' + spec + '&args[attach_id]=' + attach_id + '&args[assetinuse_id]=' + assetinuse_id + '&search[keyword]=' + keyword;
		//alert(url)
		var req = new Request.HTML({  
			method: 'get',  
			url: url,
			onSuccess: function() {
				$('assetWindow_spinner').setStyle('visibility','hidden'); 
				assetAddPopInit();
			},
			onFailure: function() {
				$('assetWindow_spinner').setStyle('visibility','hidden'); 
				alert('need more cheese 3');
			},
			update: $('assetWindow_content')
		}).send(); 
	}
	
	return true;

}











/*** ASSET UPLOAD ***/


function assetUploadPopInit() {
	
	/* change links to xhr */  
	$$('#assetWindow_content .xhrlinks a').addEvent('click', function(event) {  
		//prevent the page from changing  
		event.stop();  
		$('assetWindow_spinner').setStyle('visibility','visible'); 
		//make the ajax call, replace text  
		var req = new Request.HTML({  
			method: 'get',  
			url: this.get('href'),  
			onSuccess: function() {
				$('assetWindow_spinner').setStyle('visibility','hidden');
				// prep the dialog
				assetAddPopInit();
			},
			onFailure: function() {
				$('assetWindow_spinner').setStyle('visibility','hidden'); 
				alert('need more cheese 2');
			},
			update: $('assetWindow_content')
		}).send();  
	});

	if (document.forms['assetUploadForm'].elements['form[max_upload]']) {
		var maxUploadFiles = document.forms['assetUploadForm'].elements['form[max_upload]'].value;
	}
	
	// max upload is the maximum amount of files that can be uploaded at once.
	if (maxUploadFiles=='') {
		maxUploadFiles = 1;
	}
	uploadOK = false;
			
	session = document.forms['assetUploadForm'].elements['session'].value;
	token = document.forms['assetUploadForm'].elements['token'].value;
	module = document.forms['assetUploadForm'].elements['form[module]'].value;
	spec = document.forms['assetUploadForm'].elements['form[spec]'].value;
	attach_id = document.forms['assetUploadForm'].elements['form[attach_id]'].value;
	assetinuse_id = document.forms['assetUploadForm'].elements['form[assetinuse_id]'].value;
	
	slotsLeft = assetAddMoreTest (module,spec);
	if (slotsLeft<maxUploadFiles) {
		maxUploadFiles = slotsLeft;
	}
		
	var swiffy = new FancyUpload2($('asset-status'), $('asset-list'), {
	
		//url: '/work/_MINDTYPE6/_code/lib_assets/_admin/_window_upload3.php',
	
		// debug testing to console
		verbose: false,
		
		// path to the SWF file
		path: urlroot + '_code/lib_fancyupload/Swiff.Uploader.swf',
		
		// limits
		fileListSizeMax: maxUploadBytes,
		fileListMax: maxUploadFiles,
		multiple: true,
		
		// this is our browse button, *target* is overlayed with the Flash movie
		target: 'asset-browse-all',
		
		// graceful degradation, onLoad is only called if all went well with Flash
		onLoad: function() {
			$('asset-status').removeClass('hide');
			$('asset-fallback').destroy();
			
			// We relay the interactions with the overlayed flash to the link
			this.target.addEvents({
				click: function() {
					return false;
				},
				mouseenter: function() {
					this.addClass('hover');
				},
				mouseleave: function() {
					this.removeClass('hover');
					this.blur();
				},
				mousedown: function() {
					this.focus();
				}
			});
	
			$('asset-clear').addEvent('click', function() {
			
				$('asset-browse-all').removeClass('button_disabled');
				$('asset-clear').addClass('button_disabled');
				$('asset-upload').addClass('button_disabled');
				$$('.current-text').set('html','');
				$$('.progress-text').set('html','0%');
				$$('.overall-progress').set('style','background-position:-250px 0px');
				swiffy.remove(); // remove all files
				return false;
			});
			
			$('asset-browse-all').addEvent('click', function() {
				swiffy.browse();
				return false;
			});
			
			$('asset-upload').addEvent('click', function() {
				
					url = $('assetUploadForm').action + '?token=' + escape(token) + '&session=' + escape(session); 
					
					// ** PASS ON ALL FORM ELEMENTS THAT HAVE THE NAME name="form[blahblahblah]" ** //
					
					
					// loop through all the elements
					var lastName = false;
					var formEls = document.forms['assetUploadForm'].elements;
					var formElsSize = formEls.length;
					for(i=0;i<formElsSize;i++) {
					
						input = document.forms['assetUploadForm'].elements[i];
						inputAttr = input.attributes;
						// This stupid subroutine is just because IE fails on the input.getProperty('type') mootools method
						inputName = false;
						inputType = false;
						for(k = 0; k < inputAttr.length; k++) {
							if (inputAttr[k].name=='name') {
								inputName = inputAttr[k].value;
							} else if (inputAttr[k].name=='type') {
								inputType = inputAttr[k].value;
							}
						}

						// don't repeat inputs (especially multiple radio buttons)
						if (inputName!=lastName && inputName) {						
							// get the values of all the fields that are like "form["
							if (inputName.indexOf('form[')>-1) {
							
								// if the input is a radio button
								if (inputType=='radio') {
									var length = document.forms['assetUploadForm'].elements[inputName].length;
									for(k = 0; k < length; k++) {
										if(document.forms['assetUploadForm'].elements[inputName][k].checked) {
											var inputValue = document.forms['assetUploadForm'].elements[inputName][k].value;
										}
									}
								// if the input is any other type of input
								} else {
									inputValue = document.forms['assetUploadForm'].elements[inputName].value;
								}
								if (!inputValue) {
									url += '&' + inputName + '=';
								} else {
									url += '&' + inputName + '=' + escape(inputValue);
								}
								
							}
						}
						lastName = inputName;

					}
					
					swiffy.options.url = url;
					//alert(swiffy.options.url);
					swiffy.initializeSwiff();
					swiffy.start(); // start upload
				
				
				return false;
			});
	
	
		},
		onFileSuccess: function(file, response) {
			var json = new Hash(JSON.decode(response, true) || {});
			
			var module = json.get('module');
			var spec = json.get('spec');
			var attach_id = json.get('attach_id');
			var assetinuse_id_added = json.get('assetinuse_id_added');
			var assetbundle_id = json.get('assetbundle_id');
			//console.log('success: ' + response);
			if (json.get('result') == 'success') {
				//console.log('success: ' + response);
				if (uploadOK!='no') {
					uploadOK='yes';
				}
				var assetNo = assetInsert (module,spec,attach_id,'',assetbundle_id);
			} else {
				//console.log('error: ' + json.get('error'));
				uploadOK='no';
				alert('json error:' + response);
				//alert('json error:' + json.get('error'));
			}
		},
		onComplete:function (file,response) {
			insertTimer = function() {
				if (uploadOK!='no') {
					MochaUI.closeWindow($('assetWindow'));
				}
			}.delay(1500);
		},
		onSelect:function () {
			$('asset-clear').removeClass('button_disabled');
			$('asset-clear').addClass('button_off');
			$('asset-upload').removeClass('button_disabled');
		},
		onSelectFail: function(files) {
			files.each(function(file) {
				alert('You can not upload this file (you may be limited to uploading a certain amount of files in one go, or there may be a restriction on the type of file that can be uploaded)');
			}, this);
		},
		onFail: function(error) {
			switch (error) {
				case 'hidden': // works after enabling the movie and clicking refresh
					alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
					break;
				case 'blocked': // This no *full* fail, it works after the user clicks the button
					alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
					break;
				case 'empty': // Oh oh, wrong path
					alert('A required file was not found, please be patient and we fix this.');
					break;
				case 'flash': // no flash 9+ :(
					alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
			}
		}
	});
		 
	$('asset-nonflashsubmit').addEvent('click', function() {
		$('assetWindow_spinner').setStyle('visibility','visible'); 
		$('asset-fallback-progress').setStyle('visibility','visible'); 
	});
	
	
}











/*** FILE UPLOAD (NOT ATTACHING AN ASSET) ***/

// pop up window to upload a file
function fileUploadPop(type,redirect_url,maxWidth,maxHeight,method,adjust,bundle) {

	// adjust allows the user to set the width/height and resize method during resize
	

	// stop empty keywords being "underfined"
	if (!type) {
		type = '';
	}
	if (!maxWidth) {
		maxWidth = 9999;
	}
	if (!maxHeight) {
		maxHeight = 9999;
	}
	if (!method) {
		method = 'default';
	}
	
	var url = urlroot + '_code/lib_assets/_admin/_window_upload_file1.php?args[type]=' + type + '&args[width]=' + maxWidth + '&args[height]=' + maxHeight + '&args[method]=' + method + '&args[adjust]=' + adjust + '&args[redirect_url]=' + escape(redirect_url) + '&args[bundle]=' + bundle;
	//alert(url);

	assetWin = new MochaUI.Window({
		id: 'assetWindow',
		type: 'modal',
		title: 'File Selector',
		loadMethod: 'xhr',
		contentURL: url,
		minimizable: false,
		width: 725,
		height: 350,
		onContentLoaded: function() {
			fileUploadPopInit();
		}
	});
}

function fileUploadPopInit() {

	var maxUploadFiles = document.forms['assetUploadForm'].elements['form[max_upload]'].value;
	var maxUploadBytes = document.forms['assetUploadForm'].elements['form[max_bytes]'].value;
	
	// max upload is the maximum amount of files that can be uploaded at once.
	if (maxUploadFiles=='') {
		maxUploadFiles = 1;
	}
	uploadOK = false;
		
	var swiffy = new FancyUpload2($('asset-status'), $('asset-list'), {
	
		//url: '/work/_MINDTYPE6/_code/lib_assets/_admin/_window_upload3.php',
	
		// debug testing to console
		verbose: false,
		
		// path to the SWF file
		path: urlroot + '_code/lib_fancyupload/Swiff.Uploader.swf',
		
		// limits
		fileListSizeMax: maxUploadBytes,
		fileListMax: maxUploadFiles,
		multiple: true,
		
		// this is our browse button, *target* is overlayed with the Flash movie
		target: 'asset-browse-all',
		
		// graceful degradation, onLoad is only called if all went well with Flash
		onLoad: function() {
			$('asset-status').removeClass('hide');
			$('asset-fallback').destroy();
			
			// We relay the interactions with the overlayed flash to the link
			this.target.addEvents({
				click: function() {
					return false;
				},
				mouseenter: function() {
					this.addClass('hover');
				},
				mouseleave: function() {
					this.removeClass('hover');
					this.blur();
				},
				mousedown: function() {
					this.focus();
				}
			});
	
			$('asset-clear').addEvent('click', function() {
				$('asset-browse-all').removeClass('button_disabled');
				$('asset-clear').addClass('button_disabled');
				$('asset-upload').addClass('button_disabled');
				$$('.current-text').set('html','');
				$$('.progress-text').set('html','0%');
				$$('.overall-progress').set('style','background-position:-250px 0px');
				swiffy.remove(); // remove all files
				return false;
			});
 
			$('asset-browse-all').addEvent('click', function() {
				var type = document.forms['assetUploadForm'].elements['form[type]'].value;
				if (type=='pic') {
					swiffy.browse({'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'});
				} else if (type=='swf') {
					swiffy.browse({'Flash (*.swf)': '*.swf'});
				} else if (type=='mov') {
					swiffy.browse({'Movie (*.mov, *.wmv, *.flv, *.mp4, *.m4v, *.avi, *.mpg, *.mpeg)': '*.mov; *.wmv; *.flv; *.mp4; *.m4v; *.avi; *.mpg; *.mpeg'});
				} else {
					swiffy.browse();
				}
				return false;
			});
			
			$('asset-upload').addEvent('click', function() {
				// if validation is required...
				if (undefined!==window.validateMe) {
					validateMe.onSubmit()
					if (validateMe.form.isValid) {
						swiffyGO();
					}
				} else {
					swiffyGO();
				}
					
				function swiffyGO() {	
				
					var token = document.forms['assetUploadForm'].elements['token'].value;
					var session = document.forms['assetUploadForm'].elements['session'].value;
					
					url = $('assetUploadForm').action + '?token=' + escape(token) + '&session=' + escape(session); 
					
					// ** PASS ON ALL FORM ELEMENTS THAT HAVE THE NAME name="form[blahblahblah]" ** //
					
					
					// loop through all the elements
					var lastName = false;
					var formEls = document.forms['assetUploadForm'].elements;
					var formElsSize = formEls.length;
					for(i=0;i<formElsSize;i++) {
					
						input = document.forms['assetUploadForm'].elements[i];
						inputAttr = input.attributes;
						// This stupid subroutine is just because IE fails on the input.getProperty('type') mootools method
						inputName = false;
						inputType = false;
						for(k = 0; k < inputAttr.length; k++) {
							if (inputAttr[k].name=='name') {
								inputName = inputAttr[k].value;
							} else if (inputAttr[k].name=='type') {
								inputType = inputAttr[k].value;
							}
						}
							
						// don't repeat inputs (especially multiple radio buttons)
						if (inputName!=lastName && inputName) {						
							// get the values of all the fields that are like "form["
							if (inputName.indexOf('form[')>-1) {
							
								// if the input is a radio button
								if (inputType=='radio') {
									var length = document.forms['assetUploadForm'].elements[inputName].length;
									for(k = 0; k < length; k++) {
										if(document.forms['assetUploadForm'].elements[inputName][k].checked) {
											var inputValue = document.forms['assetUploadForm'].elements[inputName][k].value;
										}
									}
								// if the input is any other type of input
								} else {
									inputValue = document.forms['assetUploadForm'].elements[inputName].value;
								}
								if (!inputValue) {
									url += '&' + inputName + '=';
								} else {
									url += '&' + inputName + '=' + escape(inputValue);
								}
								
							}
						}
						lastName = inputName;
					
					}
					
					swiffy.options.url = url;
					//alert(swiffy.options.url);
					swiffy.initializeSwiff();
					swiffy.start(); // start upload
				}
				return false;
			});
		},
		onFileSuccess:function (file,response) {
			//alert(response);
			var json = new Hash(JSON.decode(response, true) || {});
			
			var filename = json.get('filename');
			if (json.get('result') == 'success') {
				//console.log('success: ' + response);
				if (uploadOK!='no') {
					uploadOK='yes';
				}
				//alert('upload success:' + json.get('module') + ' - ' + json.get('size'));
			} else {
				//console.log('error: ' + response);
				uploadOK='no';
				alert("ERROR\n\n" + json.get('error') + response);
			}
		},
		onComplete:function (file,response) {
			//alert(response);
			var redirect_url = document.forms['assetUploadForm'].elements['form[redirect_url]'].value;
			insertTimer = function() {
				if (uploadOK!='no') {
					if (typeof(MochaUI)!='undefined' && $('assetWindow')) {
						MochaUI.closeWindow($('assetWindow'));
					}
					//alert(redirect_url)
					self.location = redirect_url;
				}
			}.delay(1500);
		},
		onSelect:function () {
			$('asset-clear').removeClass('button_disabled');
			$('asset-clear').addClass('button_off');
			$('asset-upload').removeClass('button_disabled');
		},
		onSelectFail: function(files) {
			files.each(function(file) {
				alert('You can not upload this file (you may be limited to uploading a certain amount of files in one go, or there may be a restriction on the type of file that can be uploaded)');
			}, this);
		},
		onFail: function(error) {
			switch (error) {
				case 'hidden': // works after enabling the movie and clicking refresh
					alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
					break;
				case 'blocked': // This no *full* fail, it works after the user clicks the button
					alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
					break;
				case 'empty': // Oh oh, wrong path
					alert('A required file was not found, please be patient and we fix this.');
					break;
				case 'flash': // no flash 9+ :(
					alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
			}
		}
	});
 
	$('asset-nonflashsubmit').addEvent('click', function() {
		$('assetWindow_spinner').setStyle('visibility','visible'); 
		$('asset-fallback-progress').setStyle('visibility','visible'); 
	})
}











/*** ASSET/FILE UPLOAD - WHAT HAPPENS FOR NON-FLASH UPLOADS ***/

 
function nonFlashComplete(module,spec,attach_id,assetbundle_id) {
	
	assetInsert (module,spec,attach_id,'',assetbundle_id);
	assetAddMoreTest(module,spec);
	$('assetWindow_spinner').setStyle('visibility','hidden'); 
	MochaUI.notification('Asset added');
	insertTimer = function() {
		MochaUI.closeWindow($('assetWindow'));
	}.delay(1500);
};
 
function nonFlashFail() {
	$('assetWindow_spinner').setStyle('visibility','hidden'); 
};










/*** ASSET DELETE ***/


// pop up a window to delete an asset
function assetDelPop(module,spec,attach_id,assetinuse_id) {

	assetWin = new MochaUI.Window({
		id: 'assetWindow',
		type: 'modal',
		title: 'Remove a file',
		loadMethod: 'xhr',
		contentURL: urlroot + '_code/lib_assets/_admin/_window_delete1.php?args[module]=' + module + '&args[spec]=' + spec + '&args[attach_id]=' + attach_id + '&args[assetinuse_id]=' + assetinuse_id,
		minimizable: false,
		width: 250,
		height: 120
	});
}







/*** ASSET INFO ***/

// pop up a window to delete an asset
function assetInfoPop(module,spec,attach_id,assetinuse_id) {

	assetWin = new MochaUI.Window({
		id: 'assetWindow',
		type: 'modal',
		title: 'Asset Bundle Info',
		loadMethod: 'xhr',
		contentURL: urlroot + '_code/lib_assets/_admin/_window_info1.php?form[module]=' + module + '&form[spec]=' + spec + '&form[attach_id]=' + attach_id + '&form[assetinuse_id]=' + assetinuse_id,
		minimizable: false,
		width: 720,
		height: 455,
		onContentLoaded: function() {
			assetInfoPopInit(module,spec,attach_id,assetinuse_id)
		}
	});
}

function assetInfoPopInit(module,spec,attach_id,assetinuse_id) {

	ReMooz.assign('.bundle_thumb a', {
			origin: 'img'
		}
	);
	$('assetInfoForm').addEvent('submit', function(event) {
		
		event.stop();  
		
					url = $('assetInfoForm').action + '?function=complete'; 
					
					// ** PASS ON ALL FORM ELEMENTS THAT HAVE THE NAME name="form[blahblahblah]" ** //
					
					
					// loop through all the elements
					var lastName = false;
					var formEls = document.forms['assetInfoForm'].elements;
					var formElsSize = formEls.length;
					for(i=0;i<formElsSize;i++) {
					
						input = document.forms['assetInfoForm'].elements[i];
						inputAttr = input.attributes;
						// This stupid subroutine is just because IE fails on the input.getProperty('type') mootools method
						inputName = false;
						inputType = false;
						for(k = 0; k < inputAttr.length; k++) {
							if (inputAttr[k].name=='name') {
								inputName = inputAttr[k].value;
							} else if (inputAttr[k].name=='type') {
								inputType = inputAttr[k].value;
							}
						}

						// don't repeat inputs (especially multiple radio buttons)
						if (inputName!=lastName && inputName) {		
							//console.log(inputName);				
							// get the values of all the fields that are like "form["
							if (inputName.indexOf('form[')>-1) {
							
								// if the input is a radio button
								if (inputType=='radio') {
									var length = document.forms['assetInfoForm'].elements[inputName].length;
									for(k = 0; k < length; k++) {
										if(document.forms['assetInfoForm'].elements[inputName][k].checked) {
											var inputValue = document.forms['assetInfoForm'].elements[inputName][k].value;
										}
									}
								// if the input is any other type of input
								} else {
									inputValue = document.forms['assetInfoForm'].elements[inputName].value;
								}
								if (!inputValue) {
									url += '&' + inputName + '=';
								} else {
									url += '&' + inputName + '=' + escape(inputValue);
								}
								
							}
						}
						lastName = inputName;

					}
		
		//alert(url);
		
		$('assetWindow_spinner').setStyle('visibility','visible'); 
		
		var req = new Request.HTML({  
			method: 'get',  
			url: url,
			onSuccess: function() {
				$('assetWindow_spinner').setStyle('visibility','hidden'); 
				MochaUI.notification('Info updated');
				assetInfoPopInit();
			},
			onFailure: function() {
				alert('need more cheese 4');
			},
			update: $('assetWindow_content')
		}).send(); 
		return false;
	});
}









/*** ASSET - INSERT NEW ITEM INTO PAGE ***/

// attach a new asset to a spec
function assetInsert (module,spec,attach_id,assetinuse_id,bundle_id,keywords) {

	// module and spec allow you to find the table/primary key of the table to attach to. eg module='module_news' and spec='pic' lets you find table='news' and primary='news_id'
	// id is the id of the record to attach to, eg news_id='012345'
	// assetinuse_id allws you to replace an existing attachment instead of adding a new one.
	// bundle_id is the id of the asset bundle to attach
	// in the url that is sent form[level]=2 means to return just the attachment box, not the whole list of attachments, or just a certain list of attchments in a spec.

	var xhrUrl = urlroot + '_code/lib_assets/_admin/_attachment.php?args[level]=2&args[function]=add&args[module]=' + module + '&args[spec]=' + spec + '&args[assetinuse_id]=' + assetinuse_id + '&args[attach_id]=' + attach_id + '&args[bundle_id]=' + bundle_id + '&search[keyword]=' + keywords
	//alert(xhrUrl);
		
	$('assetWindow_spinner').setStyle('visibility','visible'); 
	
	var xhrAssetInsert = new Request.HTML({
		url:xhrUrl,
		method:'get',
		onSuccess: function(html) {
			if (!assetinuse_id) {
				var cssid = 'asset_spec_' + module + '_' + spec + '_' + attach_id + '_assets';
				//alert(cssid);
				$(cssid).adopt(html);
				// show/hide the "add more" button for this spec
				var showHide = assetAddMoreTest(module,spec);
				if (!showHide) {
					MochaUI.closeWindow($('assetWindow'));
				}
				return showHide;
			} else {
				var cssid = 'asset_inuse_' + assetinuse_id;
				// animate the delete
				var myFx = new Fx.Morph($(cssid));
				myFx.start({
					'opacity': [0.99, 0], //Morphs the 'height' style from 10px to 100px.
					'height': [224, 0]  //Morphs the 'width' style from 900px to 300px.
				});
				// clear the box
				myTimer = function() {
					var cssid = 'asset_inuse_' + assetinuse_id;
					$(cssid).destroy();					
					var cssid = 'asset_spec_' + spec + '_assets';
					$(cssid).adopt(html);
				}.delay(500);
				
			}
			// show/hide the "add more" button for this spec
			var showHide = assetAddMoreTest(module,spec);
			if (!showHide) {
				MochaUI.closeWindow($('assetWindow'));
			} else {
				$('assetWindow_spinner').setStyle('visibility','hidden'); 
			}
			MochaUI.notification('Asset added');
			return showHide;
		},
		onFailure: function() {
			alert('need more cheese 5');
			return false;
		}

	}).send();
	
}










/*** ASSET - DELETE ITEM FROM PAGE ***/

// attach a new asset to a spec
function assetDelete (module,spec,attach_id,assetinuse_id,unlink) {

	// module and spec allow you to find the table/primary key of the table to attach to. eg module='module_news' and spec='pic' lets you find table='news' and primary='news_id'
	// id is the id of the record to attach to, eg news_id='012345'
	// assetinuse_id is the assetinuse_id to delete.
	// in the url that is sent form[level]=2 means to return just the attachment box, not the whole list of attachments, or just a certain list of attchments in a spec.

	
	//alert(spec);
	var xhrAssetDelete = new Request.HTML().get(urlroot + '_code/lib_assets/_admin/_window_delete2.php?args[module]=' + module + '&args[spec]=' + spec + '&args[attach_id]=' + attach_id + '&args[assetinuse_id]=' + assetinuse_id + '&args[unlink]=' + unlink);
		
	$('assetWindow_spinner').setStyle('visibility','visible'); 
	
	if (xhrAssetDelete) {
		var cssid = 'asset_inuse_' + assetinuse_id;
		// animate the delete
		var myFx = new Fx.Morph($(cssid));
		myFx.start({
			'opacity': [0.99, 0],
			'height': [224,0] 
		});
		// clear the box
		myTimer = function() {
			$('asset_inuse_' + assetinuse_id).destroy();
			assetAddMoreTest(module,spec);
			MochaUI.notification('Asset deleted');
			MochaUI.closeWindow($('assetWindow'));
		}.delay(500);
		// show/hide the "add more" button for this spec
		assetAddMoreTest (module,spec);
	}
	

}









/*** ASSET - IS IT POSSIBLE TO ADD ANY MORE ASSETS? ***/

// hide/show the "Add more" button depending on how many are used compared to the max allowed.

function assetAddMoreTest (module,spec) {

	var thisClass = '.spec_'+module+'_'+spec;
	var thisClassBlocks = $$(thisClass);
	var max = eval('asset_max[\'' + module + ',' + spec + '\']');
	if (!max) {
		max = 99999;
	}
	//alert(thisClass + ': ' + thisClassBlocks.length);
	
	if (thisClassBlocks.length>0) {
	
		// for each block 
		for(i=0;i<thisClassBlocks.length;i++) {
		
			//how many blocks are there?
			if (thisClassBlocks[i].getChildren('.asset_spec_list').length>0) {
				var temp = thisClassBlocks[i].getChildren('div');
				var blocks = temp[1];
				var blocksNum = blocks.getChildren('div').length;
				// find the add button div
				var addDiv = thisClassBlocks[i].getLast();
				//alert(addDiv.getProperty('id') + '(' + blocksNum + '>=' + max + ')');
				// if the user shouldn't be able to add another item, hide the add button
				if (blocksNum>=max) {
					addDiv.setStyle('display','none');
					return false;
				// if the user should be able to add another item, show the add button
				} else {
					addDiv.setStyle('display','block');
					return max-blocksNum;
				}
			} else {
				var addDiv = thisClassBlocks[i].getLast();
				//alert(addDiv.getProperty('id') + '(0>=' + max + ')');
				addDiv.setStyle('display','block');
				return true;
			}
			
		}
	}

}








/*** REMOOZ IMAGE ENLARGEMENT OF IMAGES IN ASSET SIDEBAR ***/

// image enlargement script
window.addEvent('load', function() {
	
	// check all the specs and determine if the "add more" button should appear or not
	if (typeof(asset_max)!='undefined') {
		asset_max.each(function(value, key){ 
			temp = key.split(',');
			assetAddMoreTest (temp[0],temp[1]);
		});
	}
	
});