// JavaScript Document
// UPLOADER FUNCTION SET

// beginNewUploader(pri_id, pri_type, pri_action, up_code, pri_max, pri_inc, end_func);
// beginNewUploader("COMMANDING ID", "SINGLE or MULTI", "FORM ACTION", "EXISTING FILES", "MAXIMUM UPLOADABLE", "CURRENT UPLOADED", "FUNCTION INITIATED AT END");

// SINGLE UPLOADER SETTINGS
// Example: beginNewUploader('frm_upload', 'single', 'index.php?show=eIndex&show_filter=create&type=agent&step=step_2&request=rules&live=true', false, 1, 0, 'alert(\'YEY\');');
// frm_upload[forms] 	= Upload form location

// MULTIPLE UPLOADER SETTINGS
// Example: beginNewUploader('frm_upload', 'multi', 'index.php?show=eIndex&show_filter=create&type=agent&step=step_2&request=rules&live=true', {blah:'one.jpg',rah:'two.jpg'}, 5, 0, null);
// frm_upload[forms] 	= Upload form location
// frm_upload[list]	= Upload list location (table tags empty)

window.uploaderSettings = new Array();

// CONTROLLER FUNCTIONS //

	// SETUP form uploader
	function beginNewUploader(pri_id, pri_type, pri_action, up_code, pri_max, pri_inc, end_func)
	{ 
		if	(pri_id && !window.uploaderSettings[pri_id])
		{
			window.uploaderSettings[pri_id] = new Array();
			window.uploaderSettings[pri_id]['max'] 		= pri_max;
			window.uploaderSettings[pri_id]['inc'] 		= pri_inc; 
			window.uploaderSettings[pri_id]['action'] 	= pri_action;
			window.uploaderSettings[pri_id]['type'] 	= pri_type;
			window.uploaderSettings[pri_id]['current']	= 1;
			window.uploaderSettings[pri_id]['end_func']	= end_func;
			window.uploaderSettings[pri_id]['iframe_queue'] 	= new Array();
			window.uploaderSettings[pri_id]['iframe_current'] 	= false; 
		}
		
		// SETUP and initiate file field environment
		if		(pri_type == 'multi')
		{
			// Add existing files to the upload list
			if	(up_code)
			{
				for (var i in up_code) 
				{ finishFileEntry(pri_id, 'Uploaded!', up_code[i], up_code[i], window.uploaderSettings[pri_id]['inc']); window.uploaderSettings[pri_id]['inc'] = (window.uploaderSettings[pri_id]['inc']+1);  }
			}
			// End of the above
			
			// Add new upload file field
			addFileForm(pri_id, false, up_code);
			// End of the above
		}
		else if (pri_type == 'single')
		{ addFileForm(pri_id, up_code, up_code); }
		// End of the above
	}
	// End of the above
	
	function replaceFileForm(pri_id, pri_cur, up_code)
	{
		var current_frm = document.getElementById('upload_div['+pri_cur+']');
		
		document.getElementById('upload_div['+pri_cur+']').setAttribute("class", "");
		document.getElementById('upload_div['+pri_cur+']').setAttribute("className", "");
		document.getElementById('upload_div['+pri_cur+']').style.position = 'absolute';
		document.getElementById('upload_div['+pri_cur+']').style.left = '-10000px';
		
		var element_tab  = document.getElementById('file_upload_'+pri_cur).value.split("\\");
		var nbr_elements = element_tab.length;
		
		// Generate pending list entry
		pendingFileEntry(pri_id, pri_cur, element_tab[nbr_elements-1]);
		// End of the above
	}
	
	// Add new file entry to display and upload queue
	function addFileForm(pri_id, up_code, upload)
	{
		var pri_current = window.uploaderSettings[pri_id]['current'];
		var pri_new 	= (window.uploaderSettings[pri_id]['current']+1);
		
		if	(document.getElementById(pri_id+'[forms]'))
		{	
			// Relocate old upload form
			if	(upload == 'true' && document.getElementById('upload_div['+pri_current+']'))
			{
				var current_frm = document.getElementById('upload_div['+pri_current+']');
				
				document.getElementById('upload_div['+pri_current+']').setAttribute("class", "");
				document.getElementById('upload_div['+pri_current+']').setAttribute("className", "");
				document.getElementById('upload_div['+pri_current+']').style.position = 'absolute';
				document.getElementById('upload_div['+pri_current+']').style.left = '-10000px';
				
				var element_tab  = document.getElementById('file_upload_'+pri_current).value.split("\\");
				var nbr_elements = element_tab.length;
				
				// Generate pending list entry
				pendingFileEntry(pri_id, pri_current, element_tab[nbr_elements-1]);
				// End of the above
			}
			// End of the above
			
			// Generate new form tag conditions pending
			if	(window.uploaderSettings[pri_id]['type'] == 'multi')
			{
				if	(!window.uploaderSettings[pri_id]['max'] || window.uploaderSettings[pri_id]['max'] && window.uploaderSettings[pri_id]['max'] > window.uploaderSettings[pri_id]['inc'])
				{ addFileEntry('forms', pri_id, pri_new, up_code, false); }
				else if	(window.uploaderSettings[pri_id]['max'] < window.uploaderSettings[pri_id]['inc'])
				{ alert('You have uploaded your allowed total'); }
			}
			else if	(!window.uploaderSettings[pri_id]['iframe_current'])
			{ addFileEntry('forms', pri_id, pri_new, up_code, false); }
			// End of the above
			
			window.uploaderSettings[pri_id]['current'] = pri_new;
		}
	}
	// End of the above
	
	// iFRAME upload controller function
	function autoToggleiFrame(pri_id)
	{
		if	(window.uploaderSettings && window.uploaderSettings[pri_id] && window.uploaderSettings[pri_id]['iframe_current'])
		{		
			// Extract server response from iframe
			if	(document.getElementById(pri_id+'[iFrame]'))
			{ var return_content = document.getElementById(pri_id+'[iFrame]').contentWindow.document.body.innerHTML; }
			// End of the above
			
			// Collect server response XML sheet
			if	(return_content)
			{ var JSONDoc = eval('('+return_content+')'); }
			// End of the above

			// Process upload status
			if	(JSONDoc.TRANS_STATUS == 'successful')
			{ 
				// Execute successful upload function
				if	(window.uploaderSettings[pri_id]['end_func'])
				{ eval(window.uploaderSettings[pri_id]['end_func']); }
				// End of the above
				
				// Update the file display code
				finishFileEntry(pri_id, JSONDoc.UPLOAD_MSG, JSONDoc.CODE, JSONDoc.NAME, window.uploaderSettings[pri_id]['iframe_current']);
				// End of the above
			}
			else if	(JSONDoc.TRANS_STATUS == 'failed')
			{ errorFileEntry(pri_id, window.uploaderSettings[pri_id]['iframe_current'], JSONDoc.ERROR_MSG, JSONDoc.NAME); }
			// End of the above
		}
	}
	// End of the above

	// Transfers all pending form uploads to a master form
	function checkPendingForms(tgt_form)
	{
		
	}
	// End of the above

// END OF CONTROLLER FUNCTIONS //

// DISPLAY FUNCTIONS //

	function addFileEntry(tgt, pri_id, pri_cur, file_code, entry_val)
	{ 
		// Generate new form tag conditions pending	
		if	(!tgt || tgt == 'forms')
		{
			if	(!file_code)
			{	
				graft(document.getElementById(pri_id+'[forms]'), 
				['div', {id:'upload_div['+pri_cur+']',name:'upload_div['+pri_cur+']',style:'position:relative;'},
					['form', { id:'upload_form['+pri_id+']['+pri_cur+']', name:'upload_form['+pri_id+']['+pri_cur+']', method:'post', action:window.uploaderSettings[pri_id]['action'], enctype:'multipart/form-data', encoding:'multipart/form-data', target:pri_id+'[iFrame]'}, 
						['input', { type:'file', name:'file_upload_'+pri_cur+'', id:'file_upload_'+pri_cur+'', className:'fileInput_small', onchange: function() { addFileForm(pri_id, false, 'true'); } } ], 
						['input', { type:'hidden', name:'hash', id:'hash', value:rand(122356,4433234)} ],
						['input', { type:'hidden', name:'limit', id:'limit', value:window.uploaderSettings[pri_id]['max']} ]
					]
				]);
			}
			else
			{
				graft(document.getElementById(pri_id+'[forms]'), 
				['div', {id:'upload_div['+pri_cur+']',name:'upload_div['+pri_cur+']',style:'position:relative;'},
					['form', { id:'upload_form['+pri_id+']['+pri_cur+']', name:'upload_form['+pri_id+']['+pri_cur+']', method:'post', action:window.uploaderSettings[pri_id]['action'], enctype:'multipart/form-data', encoding:'multipart/form-data', target:pri_id+'[iFrame]'}, 
						['input', { type:'file', name:'file_upload_'+pri_cur+'', id:'file_upload_'+pri_cur+'', className:'fileInput_small', onchange: function() { addFileForm(pri_id, file_code, 'true'); } } ], 
						['input', { type:'hidden', name:'hash', id:'hash', value:rand(122356,4433234)} ],
						['input', { type:'hidden', name:'file_code[file_upload_'+pri_cur+']', id:'file_code[file_upload_'+pri_cur+']', value:file_code} ],
						['input', { type:'hidden', name:'limit', id:'limit', value:window.uploaderSettings[pri_id]['max']} ]
					]
				]);
			}
		}
		else if	(tgt == 'row' && file_code)
		{
			removeContents('upload_row['+pri_cur+']');
			
			graft(document.getElementById('upload_row['+pri_cur+']'), 
			['tbody',
				['td', {id:'upload_row['+pri_cur+'][row]', valign:'bottom', colSpan:'3'}, 									
					['div', {id:'upload_div['+pri_cur+']',name:'upload_div['+pri_cur+']',style:'position:relative;'},
						['form', { id:'upload_form['+pri_id+']['+pri_cur+']', name:'upload_form['+pri_id+']['+pri_cur+']', method:'post', action:window.uploaderSettings[pri_id]['action'], enctype:'multipart/form-data', encoding:'multipart/form-data', target:pri_id+'[iFrame]'}, 
							['input', { type:'file', name:'file_upload_'+pri_cur+'', id:'file_upload_'+pri_cur+'', className:'fileInput_small', onchange: function() { replaceFileForm(pri_id, pri_cur, file_code); } } ], 
							['input', { type:'hidden', name:'hash', id:'hash', value:rand(122356,4433234)} ],
							['input', { type:'hidden', name:'file_code[file_upload_'+pri_cur+']', id:'file_code[file_upload_'+pri_cur+']', value:file_code} ],
							['input', { type:'hidden', name:'limit', id:'limit', value:window.uploaderSettings[pri_id]['max']} ]
						]
					]
				]
			]
			);
		}
		// End of the above
	}

	// Pending file entry
	function pendingFileEntry(pri_id, pri_cur, entry_val)
	{
		if	(window.uploaderSettings[pri_id]['type'] == 'multi' && document.getElementById(pri_id+'[list]'))
		{
			// Set the selected file in the upload queue
			window.uploaderSettings[pri_id]['iframe_queue'][pri_cur] = pri_cur;
			// End of the above
			
			// Set the auto iFrame function
			if	(!window.uploaderSettings[pri_id]['iframe_current'])
			{ autoToggleiFrame(pri_id); }
			// End of the above
			
			// Update internal ticker
			window.uploaderSettings[pri_id]['inc'] = (window.uploaderSettings[pri_id]['inc']+1);
			// End of the above
			
			if	(document.getElementById('upload_row['+pri_cur+']'))
			{ 
				moveEntity('upload_div['+pri_cur+']', pri_id+'[forms]'); 
				removeContents('upload_row['+pri_cur+']'); 
				
				graft(document.getElementById('upload_row['+pri_cur+']'), 
				['tbody',
					['td', {id:'upload_row['+pri_cur+'][text]', valign:'bottom',width:'40%'}, entry_val],
					['td', {id:'upload_row['+pri_cur+'][status]', width:'40%'}, "In queue, waiting.." ],
					['td', {id:'upload_row['+pri_cur+'][link]', width:'20%'}, ["a", {id:'blah', href:'javascript:cancelFileEntry(\''+pri_id+'\', \''+pri_cur+'\')'}, "cancel" ]]
				]
				);
			}
			else
			{			
				graft(document.getElementById(pri_id+'[list]'), 
				['tbody',
					['tr', {id:'upload_row['+pri_cur+']', className:'black_text_normal'},
						['td', {id:'upload_row['+pri_cur+'][text]', valign:'bottom',width:'40%'}, entry_val],
						['td', {id:'upload_row['+pri_cur+'][status]', width:'40%'}, "In queue, waiting.." ],
						['td', {id:'upload_row['+pri_cur+'][link]', width:'20%'}, ["a", {id:'blah', href:'javascript:cancelFileEntry(\''+pri_id+'\', \''+pri_cur+'\')'}, "cancel" ]]
					]
				]
				);
			}
			
			if	(window.uploaderSettings[pri_id]['iframe_queue'])
			{
			for (var i in window.uploaderSettings[pri_id]['iframe_queue'])
			{
				if	(!window.uploaderSettings[pri_id]['iframe_current'])
				{ window.uploaderSettings[pri_id]['iframe_current'] = i; }
			} 
			}
			
			if	(window.uploaderSettings[pri_id]['iframe_current'] && document.getElementById('upload_form['+pri_id+']['+window.uploaderSettings[pri_id]['iframe_current']+']'))
			{ uploadingFileEntry(pri_id, window.uploaderSettings[pri_id]['iframe_current'], entry_val); document.getElementById('upload_form['+pri_id+']['+window.uploaderSettings[pri_id]['iframe_current']+']').submit(); }
		}
		else if (window.uploaderSettings[pri_id]['type'] == 'single')
		{
			// Set the auto iFrame function
			if	(!window.uploaderSettings[pri_id]['iframe_current'])
			{ window.uploaderSettings[pri_id]['iframe_current'] = pri_cur; }
			// End of the above
			
			graft(document.getElementById(pri_id+'[forms]'), 
			['table', {id:'upload_table['+pri_cur+']',width:"100%",border:"0",cellspacing:"0",cellpadding:"0"},
			['tbody',
				['tr', {className:'black_text_normal'},
					['td', {valign:'bottom',width:'50%'}, entry_val],
					['td', {width:'30%'}, "In queue, waiting.." ]
				]
			]
			]
			);
			
			if	(document.getElementById('upload_form['+pri_id+']['+window.uploaderSettings[pri_id]['current']+']'))
			{ uploadingFileEntry(pri_id, window.uploaderSettings[pri_id]['current'], entry_val); document.getElementById('upload_form['+pri_id+']['+window.uploaderSettings[pri_id]['current']+']').submit(); }
		}
	}
	// End of the above

	function uploadingFileEntry(pri_id, pri_cur, up_code)
	{	
		if	(document.getElementById('upload_row['+pri_cur+']'))
		{ 
			removeContents('upload_row['+pri_cur+']');
				
			graft(document.getElementById('upload_row['+pri_cur+']'), 
			['tbody',
				['td', {id:'upload_row['+pri_cur+'][text]', valign:'bottom',width:'40%'}, up_code],
				['td', {id:'upload_row['+pri_cur+'][status]', width:'40%'}, 'Uploading...'],
				['td', {id:'upload_row['+pri_cur+'][link]', width:'20%'}, ["a", {href:'javascript:addFileEntry(\'row\', \''+pri_id+'\', \''+pri_cur+'\', \''+up_code+'\', false);'}, "Replace" ]]
			]
			);
		}
		else if	(document.getElementById('upload_table['+pri_cur+']'))
		{
			removeEntity('upload_table['+pri_cur+']'); 
			
			graft(document.getElementById(pri_id+'[forms]'), 
			['table', {id:'upload_table['+pri_cur+']',width:"100%",border:"0",cellspacing:"0",cellpadding:"0"},
			['tbody',
				['tr', {className:'black_text_normal'},
					['td', {valign:'bottom',width:'50%'}, up_code],
					['td', {width:'50%'}, 'Uploading...']
				]
			]
			]
			);
		}
	}

	// Complete file Entry
	function finishFileEntry(pri_id, responseTEXT, up_code, up_name, pri_cur)
	{	
		// Delete file from the file queue
		if	(window.uploaderSettings[pri_id]['iframe_queue'][window.uploaderSettings[pri_id]['iframe_current']])
		{ delete window.uploaderSettings[pri_id]['iframe_queue'][window.uploaderSettings[pri_id]['iframe_current']]; }
		
		if	(window.uploaderSettings[pri_id]['iframe_current'])
		{ delete window.uploaderSettings[pri_id]['iframe_current']; }
		// End of the above
		
		if	(window.uploaderSettings[pri_id]['type'] == 'multi' && document.getElementById(pri_id+'[list]'))
		{	
			if	(!document.getElementById('upload_row['+pri_cur+']'))
			{
				removeContents('upload_row['+pri_cur+']');
				
				graft(document.getElementById(pri_id+'[list]'), 
				['tbody',
					['tr', {id:'upload_row['+pri_cur+']', className:'black_text_normal'},
						['td', {id:'upload_row['+pri_cur+'][text]', valign:'bottom',width:'40%'}, up_name],
						['td', {id:'upload_row['+pri_cur+'][status]', width:'40%'}, responseTEXT+', '+up_name],
						['td', {id:'upload_row['+pri_cur+'][link]', width:'20%'}, ["a", {href:'javascript:addFileEntry(\'row\', \''+pri_id+'\', \''+pri_cur+'\', \''+up_code+'\', false);'}, "Replace" ]]
					]
				]
				);
			}
			else
			{
				removeContents('upload_row['+pri_cur+']');
				
				graft(document.getElementById('upload_row['+pri_cur+']'), 
				['tbody',
					['td', {id:'upload_row['+pri_cur+'][text]', valign:'bottom',width:'40%'}, up_name],
					['td', {id:'upload_row['+pri_cur+'][status]', width:'40%'}, responseTEXT+', '+up_name],
					['td', {id:'upload_row['+pri_cur+'][link]', width:'20%'}, ["a", {href:'javascript:addFileEntry(\'row\', \''+pri_id+'\', \''+pri_cur+'\', \''+up_code+'\', false);'}, "Replace" ]]
				]
				);
			}
			
			if	(document.getElementById('upload_div['+pri_cur+']'))
			{ removeEntity('upload_div['+pri_cur+']'); }
		
		}
		else if	(window.uploaderSettings[pri_id]['type'] == 'single' && document.getElementById(pri_id+'[forms]') && document.getElementById('upload_div['+pri_cur+']'))
		{
			removeEntity('upload_div['+pri_cur+']'); 
			removeEntity('upload_table['+pri_cur+']');
			
			addFileForm(pri_id, up_code, false);	
		}
		
	} 
	// End of the above
	
	// Error file Entry
	function errorFileEntry(pri_id, pri_cur, responseTEXT, up_code)
	{
		if		(responseTEXT == 'OVER_LIMIT')
		{ var errorText = 'File too large'; }
		else if	(responseTEXT == 'INCORRECT_FILE_TYPE')
		{ var errorText = 'Wrong file type'; }
		else if	(responseTEXT == 'FILE_EXISTS')
		{ var errorText = 'File already exists'; }
		
		if	(document.getElementById('upload_row['+pri_cur+']'))
		{ 
			removeContents('upload_row['+pri_cur+']');
				
			graft(document.getElementById('upload_row['+pri_cur+']'), 
			['tbody',
				['td', {id:'upload_row['+pri_cur+'][text]', valign:'bottom',width:'40%'}, up_code],
				['td', {id:'upload_row['+pri_cur+'][status]', width:'40%'}, errorText],
				['td', {id:'upload_row['+pri_cur+'][link]', width:'20%'}, ["a", {href:'javascript:addFileEntry(\'row\', \''+pri_id+'\', \''+pri_cur+'\', \''+up_code+'\', false);'}, "Change" ]]
			]
			);
		}
		else if	(document.getElementById('upload_table['+pri_cur+']'))
		{ 
			removeEntity('upload_table['+pri_cur+']'); 
			
			graft(document.getElementById(pri_id+'[forms]'), 
			['table', {id:'upload_table['+pri_cur+']',width:"100%",border:"0",cellspacing:"0",cellpadding:"0"},
			['tbody',
				['tr', {className:'black_text_normal'},
					['td', {id:'upload_row['+pri_cur+'][text]', valign:'bottom',width:'40%'}, up_code],
					['td', {id:'upload_row['+pri_cur+'][status]', width:'40%'}, errorText],
					['td', {id:'upload_row['+pri_cur+'][link]', width:'20%'}, ["a", {href:'javascript:addFileEntry(\'row\', \''+pri_id+'\', \''+pri_cur+'\', \''+up_code+'\', false);'}, "Change" ]]
				]
			]
			]
			);
		}
	}
	// End of the above

	// Cancel pending file entry
	function cancelFileEntry(pri_id, pri_cur)
	{
		if	(window.uploaderSettings[pri_id]['type'] == 'multi')
		{
			// Remove file ENTRY row from display table
			if	(document.getElementById('upload_row['+pri_cur+']'))
			{ removeEntity('upload_row['+pri_cur+']'); }
			// End of the above
			
			// Remove file tag div from the upload queue
			if	(document.getElementById('upload_div['+pri_cur+']'))
			{ removeEntity('upload_div['+pri_cur+']'); }
			// End of the above
			
			// Remove 1 entry from internal ticker
			if	(!window.uploaderSettings[pri_id]['max'] || window.uploaderSettings[pri_id]['max'] && window.uploaderSettings[pri_id]['max'] >= window.uploaderSettings[pri_id]['inc'])
			{ window.uploaderSettings[pri_id]['inc'] = (window.uploaderSettings[pri_id]['inc']-1); addFileForm(pri_id, false, upload); }
			else
			{ window.uploaderSettings[pri_id]['inc'] = (window.uploaderSettings[pri_id]['inc']-1); }
			// End of the above
		}
		
		// Remove file entry from file upload queue
		if	(window.uploaderSettings[pri_id]['iframe_queue'][pri_cur])
		{ delete window.uploaderSettings[pri_id]['iframe_queue'][pri_cur]; }
		// End of the above
	}
	// End of the above

// END OF DISPLAY FUCNTIONS