function getfileextension(inputId) 
{ 
 //var fileinput = document.getElementById("foo"); 
 //if(!fileinput ) return ""; 
 var filename = inputId; 
 if( filename.length == 0 ) return ""; 
 var dot = filename.lastIndexOf("."); 
 if( dot == -1 ) return ""; 
 var extension = filename.substr(dot+1,filename.length); 
 return extension.toLowerCase(); 
} 

function getfileicon(fileExtension){
	if(fileExtension == 'jpg' || fileExtension == 'jpeg' || fileExtension == 'png' || fileExtension == 'gif'){
	fileIcon = 'images/icons/picture.png';
	fileIconTip = 'Image File';
	fileIconRef = 'jpg';
	} else
	if(fileExtension == 'doc' || fileExtension == 'docx'){
	fileIcon = 'images/icons/page_white_word.png';
	fileIconTip = 'Word Document';
	fileIconRef = 'doc';
	} else
	if(fileExtension == 'pdf'){
	fileIcon = 'images/icons/page_white_acrobat.png';
	fileIconTip = 'PDF Document';
	fileIconRef = 'pdf';
	} else 
	if(fileExtension == 'txt' || fileExtension == 'rtf'){
	fileIcon = 'images/icons/page_white_text.png';
	fileIconTip = 'Text Document';
	fileIconRef = 'doc';
	} else 
	if(fileExtension == 'ppt' || fileExtension == 'pptx' || fileExtension == 'pps' || fileExtension == 'ppsx'){
	fileIcon = 'images/icons/page_white_powerpoint.png';
	fileIconTip = 'Presentation';
	fileIconRef = 'ppt';
	} else 
	if(fileExtension == 'avi' || fileExtension == 'mpg' || fileExtension == 'mp4' || fileExtension == 'mp4'){
	fileIcon = 'images/icons/film.png';
	fileIconTip = 'Video File';
	fileIconRef = 'avi';
	} else
	if(fileExtension == 'mp3' || fileExtension == 'wav'){
	fileIcon = 'images/icons/sound.png';
	fileIconTip = 'Audio File';
	fileIconRef = 'mp3';
	} else
	if(fileExtension == 'htm' || fileExtension == 'html'){
	fileIcon = 'images/icons/link.png';
	fileIconTip = 'Web Link';
	fileIconRef = 'html';
	} else
	if(fileExtension == 'xls' || fileExtension == 'xlsx'){
	fileIcon = 'images/icons/page_white_excel.png';
	fileIconTip = 'Spreadsheet';
	fileIconRef = 'xls';
	} else
	{
	fileIcon = 'images/icons/link.png';
	fileIconTip = 'Web Link (Unknown Filetype)';
	fileIconRef = 'html';
	}
	
	return fileIcon+','+fileIconTip+','+fileIconRef;
}

function setAttachFile(){
	//Set File Name
	//alert(attachmentFile)
	urlfilename = unescape(document.getElementById('attachFile').value.substring(document.getElementById('attachFile').value.lastIndexOf('/')+1));
	urlfilename = urlfilename.replace(/["']{1}/gi,"");
	filename = unescape(document.getElementById('attachFile').value);
	filename = filename.replace(/["']{1}/gi,"");
	
	if(urlfilename != ''){
	
		attachmentFileName = document.getElementById('attachFileName').value;
		if (attachmentFileName == ''){
			document.getElementById('attachFile').value=filename;
			document.getElementById('attachFileName').value=urlfilename.replace("."+getfileextension(urlfilename),'');		
		}
		fileExtension = getfileextension(urlfilename); 
		fileType = getfileicon(fileExtension);
		fileTypeInfo = fileType.split(',');
		fileIcon = fileTypeInfo[0];
		fileIconTip = fileTypeInfo[1];
		fileIconRef = fileTypeInfo[2];
				//alert(fileIconRef)
		document.getElementById('attachmentTypeSelect').value=fileIconRef;
		attachFileNameBox =	document.getElementById('attachFileName');
		//attachFileNameBox.focus();
		
		//Show File Notes
		InsertContent('attachFileNotes_box');
		$.colorbox.resize();
	
	}
}
	
		
function removeAttachmentFromList(id,edit){
	filesArray = document.getElementById('attachedFiles').value;
	files = filesArray.split(',');
	//alert(files.length)
	NewfileList = '';
	
	for (i=0;i<files.length;i++){
		fileInfoArray = files[i];
		fileInfo = fileInfoArray.split('|');
		
		if(i != id){
			if(NewfileList!=''){NewfileList += ',';}
			NewfileList += fileInfo[0]+'|'+fileInfo[1]+'|'+fileInfo[2]+'|'+fileInfo[3];
			//if(fileInfo[2]){
			//	NewfileList += '|'+fileInfo[2];
			//}
		} else {
			if(edit == 1){
				RemoveContent('attachCancelButton');
				document.getElementById('attachFile').value=decodeURIComponent(fileInfo[0]);
				document.getElementById('attachFileName').value=unescape(fileInfo[1]);
				if(fileInfo[2]){
				document.getElementById('attachFileNotes').value=unescape(fileInfo[2]);
				}
				InsertContent('attachFileNotes_box');
				document.getElementById('attachFileName').focus();
				
				fileExtension = getfileextension(fileInfo[0]); 
				fileType = getfileicon(fileExtension);
				fileTypeInfo = fileType.split(',');
				fileIconRef = fileTypeInfo[2];
				
				if(fileInfo[3]!=''){
				fileIconRef = fileInfo[3];
				}
			//alert(fileIconRef)
				document.getElementById('attachmentTypeSelect').value=fileIconRef;
				
				attachPopUp();
				
			}
		}
		
	}
	
	document.getElementById('attachedFiles').value=NewfileList;
	makeAttachmentsList();
}
function makeAttachmentsList(){
	
	filesArray = document.getElementById('attachedFiles').value;
	//alert(filesArray)
	files = filesArray.split(',');
	//alert(files.length)
	fileLinks = '';
	
	for (i=0;i<files.length;i++){
	
		fileInfoArray = files[i];
		fileInfo = fileInfoArray.split('|');
		
		if (fileInfo[0] != ''){
				
			if(fileLinks==''){fileLinks += '<ul class="list" style="font-size:1em;" >';}
			
			selectedFileType = fileInfo[0];
			fileExtension = getfileextension(selectedFileType);
			//alert(fileInfo[3])
			if (fileInfo[3] != 'undefined'){
				fileExtension = fileInfo[3];
				//alert(selectedFileType);
			}
			//alert(getfileextension(fileInfo[0]))
			
			//alert(fileExtension)
			fileType = getfileicon(fileExtension);
			fileTypeInfo = fileType.split(',');
			fileIcon = fileTypeInfo[0];
			fileIconTip = fileTypeInfo[1];
			
			var filenotes = '';
			//Set Tooltip
			var filetooltip = '<strong>Click To Preview</strong> - '+fileIconTip+'<br />Name: '+unescape(fileInfo[1]);
			if(fileInfo[2]){
				filetooltip += '<br />Notes: '+unescape(fileInfo[2]).replace(/\n/g,'<br />');
				filenotes = '<br /><span style="font-size:1.2em;">'+unescape(fileInfo[2])+'</span>';
			}
			//filetooltip += '<br />Link: '+decodeURIComponent(fileInfo[0]);
		
		//fileLinks += '<span onmouseover="InsertContent(\'removeLink'+i+'\');RemoveContent(\'icon'+i+'\');" onmouseout="RemoveContent(\'removeLink'+i+'\');InsertContent(\'icon'+i+'\');" style="white-space:nowrap;"><img id="icon'+i+'" src="'+fileIcon+'" style="margin-bottom:-2px;" border="0" width="12" onmouseover="ToolTip(\''+fileIconTip+'\');" onmouseout="UnTip();" /> <span id="removeLink'+i+'" style="display:none;"><a href="javascript:;" onclick="removeAttachmentFromList('+i+');UnTip();"><img src="images/icons/cross_sml.png" border="0" width="8" onmouseover="ToolTip(\'Click Here To Remove '+unescape(fileInfo[1])+'\');" onmouseout="UnTip();" /></a> <a href="javascript:;" onclick="removeAttachmentFromList('+i+',1);UnTip();"><img src="images/icons/pencil_sml.png" border="0" width="8" onmouseover="ToolTip(\'Click Here To Edit '+unescape(fileInfo[1])+'\');" onmouseout="UnTip();" /></a></span> <a target="_blank" href="'+decodeURIComponent(fileInfo[0])+'" onmouseover="ToolTip(\''+filetooltip+'\');" onmouseout="UnTip();">'+unescape(fileInfo[1])+'</a></span>';
		fileLinks += '<li onmouseover="InsertContent(\'removeLink'+i+'X\');" onmouseout="RemoveContent(\'removeLink'+i+'X\');">';
		if (edit_access){
		fileLinks += '<span id="removeLink'+i+'X" style="display:none; float:right;"><a href="javascript:;" onclick="removeAttachmentFromList('+i+');changeField(\'event\');UnTip();"><img src="images/icons/cross.png" style="" border="0" width="16" onmouseover="ToolTip(\'Click Here To Remove '+unescape(fileInfo[1])+'\');" onmouseout="UnTip();" /></a> <a href="javascript:;" onclick="removeAttachmentFromList('+i+',1);UnTip();" class=""><img src="images/icons/pencil.png" style="" border="0" width="16" onmouseover="ToolTip(\'Click Here To Edit '+unescape(fileInfo[1])+'\');" onmouseout="UnTip();" /></a> </span>';
		}
		fileLinks += '<span style="white-space:nowrap; font-size:1.4em;"><img id="icon'+i+'" src="'+fileIcon+'" style="margin-bottom:-4px;" border="0" width="16" onmouseover="ToolTip(\''+fileIconTip+'\');" onmouseout="UnTip();" /> ';
		fileLinks += '<a target="_blank" href="'+decodeURIComponent(fileInfo[0])+'" onmouseover="ToolTipBox(\''+filetooltip+'\',250);" onmouseout="UnTip();"><strong>'+unescape(fileInfo[1])+'</strong></a></span>'+filenotes+'</li>';
	}
	
	}
	
	if (fileLinks != ''){
		fileLinks += '</ul>';
		InsertContent('attachedBox');
		
	} else {
		RemoveContent('attachedBox');
	}
	document.getElementById('attachedFileList').innerHTML=fileLinks;
	return fileLinks;
}

function getAttachmentsMsg(){
	
	filesArray = document.getElementById('attachedFiles').value;
	files = filesArray.split(',');
	
	var attachmentMsg = '';
	
	if (files.length == 1 && files[0]){
		attachmentMsg = '<a href="#attachments" style="text-decoration:none;"><img src="../images/icons/attach.png" style="margin-bottom:-2px; " border="0" width="16" /> <strong>THERE IS 1 FILE ATTACHED TO THIS MESSAGE</strong></a><br /><span style="font-size:10px;">Please scroll to the bottom of this email to download the attachment</span><br />';
	} else 
	if (files.length > 1 && files[0]){
		attachmentMsg = '<a href="#attachments" style="text-decoration:none;"><img src="../images/icons/attach.png" style="margin-bottom:-2px; " border="0" width="16" /> <strong>THERE ARE '+files.length+' FILES ATTACHED TO THIS MESSAGE</strong></a><br /><span style="font-size:10px;">Please scroll to the bottom of this email to download the attachments</span><br />';
	}
	
	return attachmentMsg;
	
}

function makeAttachmentsTable(){
	
	filesArray = document.getElementById('attachedFiles').value;
	
	files = filesArray.split(',');
	
	var fileTable = '<a name="attachments"></a>';
	if (files.length > 0 && files[0]){
	fileTable += '<table align="left" style="border:2px solid #F4F4F4; margin-bottom:10px; margin-top:15px; background-color:#FFF;" cellspacing="0" cellpadding="3">';
	fileTable += '<tr><td  style="background-color:#DEE7EB; color:#7A9BAD; border-bottom:2px solid #CCC;" align="left"><strong>Attached Files</strong> (Click file to view / download)</td></tr>';
	for (i=0;i<files.length;i++){
					
		fileInfoArray = files[i];
		fileInfo = fileInfoArray.split('|');
		
		if (fileInfo[0]){
			fileTable += '<tr>';	
			
			//if(fileLinks!=''){fileLinks += ', ';}
			fileExtension = getfileextension(fileInfo[0]);
			//alert(fileExtension)
			fileType = getfileicon(fileExtension);
			fileTypeInfo = fileType.split(',');
			fileIcon = fileTypeInfo[0];
			fileIconTip = fileTypeInfo[1];
			//Set Tooltip
			filetooltip = unescape(fileInfo[1])+' - '+fileIconTip;
			
			filenotes = '<em>No File Notes</em>';
			if(fileInfo[2]){
				filenotes = unescape(fileInfo[2]);	
				filetooltip = unescape(fileInfo[1])+' - '+unescape(fileInfo[2]).replace(/\n/g,'<br />');
			}
		
		
		
			fileTable += '<td style="border-bottom:1px solid #CCC;">';
			fileTable += '<a target="_blank" href="'+decodeURIComponent(fileInfo[0])+'" title="'+filetooltip+'" style="text-decoration:none;" ><img id="icon'+i+'" src="'+fileIcon+'" style="margin-bottom:-2px; " border="0" width="12" title="'+filetooltip+'" /> '+unescape(fileInfo[1])+'</a>';
			fileTable += '';
			fileTable += '<br /><div style="margin-left: 17px; color: #999999; font-size:10px">';
			fileTable += filenotes;
			fileTable += '</div>';
			fileTable += '</td>';
			fileTable += '</tr>';
		}
	
		
	}
	fileTable += '</table>';
	fileTable += '<div style="clear:both"></div>';
	
	
	} 
	return fileTable;
}

function clearAttachForm(){
	input = document.getElementById('attachFile');
	inputName = document.getElementById('attachFileName');
	inputNotes = document.getElementById('attachFileNotes');
	inputType = document.getElementById('attachmentTypeSelect');
	InsertContent('attachCancelButton');
	RemoveContent('attachFileNotes_box');
	input.value = '';
	inputName.value = '';	
	inputNotes.value = '';
	inputType.value = '';
}

function attachFile(){
	input = document.getElementById('attachFile');
	inputName = document.getElementById('attachFileName');
	inputNotes = document.getElementById('attachFileNotes');
	inputType = document.getElementById('attachmentTypeSelect');
	list = document.getElementById('attachedFiles');
	//textlist = document.getElementById('attachedFileList');
	if(list){
	attachedfiles = list.value;
	//attachedFilesText = textlist.innerHTML;
	}
	name = inputName.value;
	notes = inputNotes.value;
	urlfilename = input.value.substring(input.value.lastIndexOf('/')+1);
	urlfilename = urlfilename.replace(/["']{1}/gi,"");
	if (name == ''){
		if(urlfilename!=''){
			name=urlfilename;
		} else {
			name=input.value;
		}
	}

	filenotes = '';
	filenotes = '|'+escape(inputNotes.value.replace(/["']{1}/gi,""));
	
	
	selectedtype = '';
	selectedtype = '|'+inputType.value;
	
	if(input.value){
		if (attachedfiles != ''){
		attachedfiles += ',';
		//attachedFilesText += ', '; 
		}
	attachedfiles += encodeURIComponent(input.value)+'|'+escape(inputName.value.replace(/["']{1}/gi,""))+filenotes+selectedtype;
	}
	//attachedFilesText += '<a target="_blank" href="'+input.value+'" onmouseover="ToolTip(\'<strong>Click To Preview</strong><br />Name: '+inputName.value+'<br />Link: '+input.value+'\');" onmouseout="UnTip();">'+inputName.value+'</a>';
	//textlist.innerHTML=attachedFilesText;
	list.value=attachedfiles;
	makeAttachmentsList();
	clearAttachForm();
	$.colorbox.close();
}

function cancelAddAttachment(){
	clearAttachForm();
	makeAttachmentsList();
	$.colorbox.close();
	//RemoveContent('actions_edit');
}

////////////////////


$(document).ready(function(){
						   

$(".attachButton").live('click',function(){attachPopUp()});						   
						   
						   						   
var attachmentFormOptions = { 
        //target:        '#output2',   // target element(s) to be updated with server response 
       // beforeSubmit:  showRequest,  // pre-submit callback 
        //// post-submit callback 
		
		
		//Set 'ajax' variable as form being processed with ajax form query
		//IE doesn't work with live.submit, so this will redirect on save
		data: { ajax: '1' },
		
 		beforeSubmit: function() {
			savingDialog(); 
			
			clearAttachForm();
			$.colorbox.close();
           // $.blockUI({ message: '<h1><img src="images/active_bar_trans.gif" /><br /> Saving Changes...</h1>' });
        },
		success:       attachmentFormResponse  
		
        // other available options: 
        //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 
    }; 
 
    // bind to the form's submit event 
	
    $('.attachmentForm').live('submit',function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $(this).ajaxSubmit(attachmentFormOptions); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    }); 
	
	
	


}); 
 
// pre-submit callback 
function attachmentFormRequest(formData, jqForm, options) { 
    // 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); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
    alert('About to submit: \n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 
 
// post-submit callback 
function attachmentFormResponse(responseText, statusText, xhr, $form)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
   //alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.'); 
	
	if (responseText === 'OK'){
		$.blockUI({ 
			css: { 
				border: 'none', 
				padding: '15px', 
				backgroundColor: '#000', 
				'-webkit-border-radius': '10px', 
				'-moz-border-radius': '10px', 
				opacity: .3, 
				color: '#fff',
				fontSize: '2em'
				},
			message: '<img src="images/icons/tick_lrg.png"  /> Saved'	
		}); 
		//setTimeout('window.location.reload();', 1000); 
		//restoreEventsBanner()
		setTimeout('$.unblockUI();',1500); 
		
		
		var content = $("#attachments_box");
		//window.scrollTo(0,0);
		content.fadeOut('slow');
		var value = $('#eventID').val(); 
//alert('The event is: ' + value); 
		content.load("attachments_panel.php?eventID="+value+"&page="+page+"&pageNumber="+pageNumber, content.fadeIn('slow'));
	    content.fadeIn('slow');
		//Reset the form for an insert
		var content = $("#attachmentPopup_content");
		content.load("control_panel/attachment_popup.php?eventID="+value+"&pageNumber="+pageNumber+ " #attachmentPopup_content");
		
		//$.colorbox.close()
	} else {
		$.blockUI({ 
			css: { 
				border: 'none', 
				padding: '15px', 
				backgroundColor: '#000', 
				'-webkit-border-radius': '10px', 
				'-moz-border-radius': '10px', 
				opacity: .5, 
				color: '#fff',
				fontSize: '2em'
				},
			message: '<img src="images/icons/cross.png"  /> Save Failed'	
		}); 
		//setTimeout('window.location.reload();', 2000); 
		setTimeout('$.unblockUI();', 3000); 
		setTimeout('attachPopUp();', 3000); 
	}
} 

	
function editAttachment(id){
	
		var content = $("#attachmentPopup_content");
		//window.scrollTo(0,0);
		//alert('The event is: ' + value); 
		InsertContent('attachFileNotes_box');
		attachPopUp();
		content.load("control_panel/attachment_popup.php?attachID="+id+ " #attachmentPopup_content");
		
	   // content.fadeIn('slow');
	   
}


//Delete A Room
function deleteAttached(uid,id,name){
	var r=confirm("Are You Sure You Want To Delete '"+name+"'?");
	if (r==true)
	  {
	  //alert("You pressed OK!");
	  savingDialog();
	  url = 'scripts/php/attachments.php';
		type = 'DeleteAttached';
		params = 'uid='+uid+'&';
		params += 'id='+id+'&';
		params += ''+type+'=type&';
		
		httpRequestPOST(url,params,type);
		$.colorbox.close();
	  }
	else
	  {
	  //alert("Cancelled Delete!");
	  }
}		
		
function attachPopUp(){ 
$.colorbox({width:"550px", opacity:0.1, inline:true, href:"#attachmentPopUp", overlayClose: false, onComplete: $.colorbox.resize()});
$('#cboxClose').css('display','none'); 
}		


function closeAttachPopup(){
	clearAttachForm();
	$.colorbox.close();
	//Reset the form for an insert
	id = document.getElementById('eventID').value;
	  var content = $("#attachmentPopup_content");
	  content.load("control_panel/attachment_popup.php?eventID="+id+"&pageNumber="+pageNumber+" #attachmentPopup_content");
}
