//
// util functions
//
function coverBox(pElem, buttonElem) 
{

	pElem = $(pElem);

	if (buttonElem) {
		buttonElem.disabled = true;
		buttonElem.value = "Please Wait...";
	}

	var cover = document.createElement('div');
	cover.id = pElem.id+"_cover";

	var waitImg = document.createElement('img');
	waitImg.src = "/images/ajax-loader-medium-trans.gif";
	waitImg.style.position = "absolute";
	waitImg.style.left = "50%";
	waitImg.style.marginLeft = "-16px";
	waitImg.style.top = "45%";

	cover.appendChild(waitImg);
	cover.style.display = 'none';
	pElem.appendChild(cover);
	cover = $(cover.id);

	if (cover) {

		cover.style.position = 'absolute';
		cover.style.margin = '0px';
		cover.style.padding = '0px';

		if (Prototype.Browser.IE) {
			if (cover.getOffsetParent().id == pElem.id) {
				cover.style.left = "0px";
				cover.style.top = "0px";
			} else {
				var offsets = pElem.cumulativeOffset();
				cover.style.left = offsets.left+"px";
				cover.style.top = offsets.top+"px";
			}
			cover.style.height = pElem.offsetHeight;
			cover.style.width = pElem.offsetWidth;
			cover.style.filter = 'alpha(opacity=80)';
		} else {
			cover.clonePosition(pElem);
			cover.style.opacity = '0.8';
		}

		cover.style.backgroundColor = '#fff';
		cover.style.zIndex = '100';
		cover.show();
	}
}


function coverScreen(toggle, zindex)
{
	var div;

	zindex = zindex ? zindex : 'auto';

	div = $('screen_cover');
	if (!div) {
		div = new Element('div', { id: 'screen_cover' }).setStyle({
			display:'none'
			});
		document.body.appendChild(div);
	}

	if (toggle) {
		div.setStyle({
			display: 'block',
			visibility: 'visible',
			position:'fixed',
			top:'0px',
			left:'0px',
			width:'100%',
			height:'100%',
			backgroundColor:'#ccc',
			opacity: 0.5,
			margin:'0px',
			padding:'0px',
			zIndex: zindex
			});
	} else {
		div.setStyle({
			display: 'none',
			visibility: 'hidden',
			position:'relative',
			width:'1px',
			height:'1px',
			margin:'0px',
			padding:'0px',
			zIndex: '-1'
			});
	}
}


function centerElement(elem, zindex)
{
	elem = $(elem);

	zindex = zindex ? zindex : 'auto';

	elem.style.position = 'fixed';
	elem.style.left = '50%';
	elem.style.top = '50%';
	elem.style.marginLeft = '-'+Math.floor(elem.offsetWidth / 2)+'px';
	elem.style.marginTop = '-'+Math.floor(elem.offsetHeight / 2)+'px';
	elem.style.zIndex = zindex;

}


function myGetComputedStyle(elem)
{
	if (window.getComputedStyle) {
		return window.getComputedStyle(elem, null);
	} else if(elem.currentStyle) {
		return elem.currentStyle;
	}

}

function parseIntZero(value)
{
	var int = parseInt(value);
	if (isNaN(int)) {
		return 0;
	} else {
		return int;
	}
}

function findPos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

var ErrorPopupsStatus = new Object();
var ErrorPopupFormElemFocused = "";

function showErrorPopup(formElem, popElem, withFocus)
{

	if (withFocus) {
		ErrorPopupFormElemFocused = formElem.id;
	}

	if (ErrorPopupsStatus[popElem.id]) { // we are already visible
		return false;
	}

	// get computed style info about our elements
	var pStyle = myGetComputedStyle(popElem, null);
	var fStyle = myGetComputedStyle(formElem, null);
	var pos = findPos(formElem);

	var startPosX = pos[1] + parseIntZero(fStyle.borderTopWidth);
	var startPosY = pos[0] + parseIntZero(fStyle.borderLeftWidth);

	popElem.style.position = 'absolute';
	popElem.style.top = startPosX+"px";
	popElem.style.left = startPosY+"px";
	popElem.style.opacity = 0.1;
	popElem.style.display = "block";

	// make the popup the same width as the form field
	// with a minimum of 150
	var pwidth = parseIntZero(formElem.offsetWidth) 
		- parseIntZero(pStyle.borderLeftWidth) - parseIntZero(pStyle.borderRightWidth) 
		- parseIntZero(pStyle.paddingLeft) - parseIntZero(pStyle.paddingRight);
	pwidth = pwidth > 150 ? pwidth : 150;
	popElem.style.width = pwidth+"px";

	// move the item up by its entire height
	var popElemHeight = parseInt(popElem.offsetHeight);
	var endPosX = startPosX - popElemHeight;

	options = {
		style: "opacity: 1.0; top:"+endPosX+"px;", // CSS Properties
		duration: 0.7, 
		transition: Effect.Transitions.spring
	}

	ErrorPopupsStatus[popElem.id] = true;

	new Effect.Morph(popElem.id, options);
}

function hideErrorPopup(formElem, popElem, withFocus)
{

	if (withFocus) {
		ErrorPopupFormElemFocused = "";
	}

	// don't hide if our form elem still has focus
	if (formElem.id == ErrorPopupFormElemFocused) {
		return false;
	}

	ErrorPopupsStatus[popElem.id] = false;
	popElem.hide();
}


function confirmLogout()
{
	var mssg = 'Are you sure you want to log out?';
	return confirm(mssg);
}

var FileUploadWindow = Class.create({

	initialize: function(element, options) {
		this.isEdit = false;
		this.element = $(element);

		this.closeButton = $(this.element.id+'_close');
		this.mainForm = $(this.element.id+'_form');
		this.mainFormSubmit = $(this.element.id+'_form_submit');
		this.uploadFrame = $(this.element.id+'_frame');

		this.options = {
		};
   	Object.extend( this.options, options ? options : {} );

		this.dbId = parseInt(this.options.dbId);

		if (this.options.progressElement) {
			this.progressElement = $(this.options.progressElement);
			this.progressBarElement = $(this.progressElement.id+'_bar');
			this.progressTextElement1 = $(this.progressElement.id+'_text1');
			this.progressTextElement2 = $(this.progressElement.id+'_text2');
			this.progressDebugElement = $(this.progressElement.id+'_debug');
		}

		// listen for close clicks
		Event.observe(this.closeButton, "click", this.hideWindow.bindAsEventListener(this));

		// listen for file uplaods
		//Event.observe(this.mainFormSubmit, "click", this.submitUpload.bindAsEventListener(this));
	},

	showFileUpload: function(fields, mediaType, container, listItemClass, editVals) {

		this.container = $(container);
		this.listItemClass = listItemClass;

		this.mediaType = mediaType;
		$(this.mainForm.id+'_mediaType').value = this.mediaType;
		if (this.mediaType === null) {
			return false;
		}

		// initialize all the form fields to blank
		var str = '';
		this.mainForm.getElements().each(function(el) {
			if (el.type == 'text' || el.type == 'file') {
				el.value = '';
			} else if (el.type == 'textarea') {
				el.value = '';
				el.innerHTML = '';
			}
		});

		var posFields = ['name','description', 'dimensions', 'edit', 'file']; //possible fields to display
		var shown = [];
		if (fields && typeof(fields) == 'object') {
			fields.each(function(f, i) {
				if (posFields.include(f)) {
					shown.push(f);
				}
			});
		} else {
			shown = posFields;
		}
	
		// hide all the optional fields
		posFields.each(function(field, i) {
			$(this.element.id+'_form_'+field).hide();
		}.bind(this));

		// show the ones we want
		var doEdit = false;
		shown.each(function(field, i) {
			$(this.element.id+'_form_'+field).show();
			if (field == 'edit') {
				doEdit = true;
			}
		}.bind(this));
	
		if (doEdit) {
			// listen for file edit submission
			Event.stopObserving(this.mainFormSubmit, 'click');
			Event.observe(this.mainFormSubmit, "click", this.submitEdit.bindAsEventListener(this));
			$(this.element.id+'_form_submit').value = "Submit";

			if (editVals) {
				this.fileEditId = editVals.id;
				if (editVals.name) {
					$(this.element.id+'_form_field_name').value = editVals.name;
				}
				if (editVals.description) {
					$(this.element.id+'_form_field_description').value = editVals.description;
				}
			}

		} else {
			// listen for file uploads
			Event.stopObserving(this.mainFormSubmit, 'click');
			Event.observe(this.mainFormSubmit, "click", this.submitUpload.bindAsEventListener(this));
			$(this.element.id+'_form_submit').value = "Upload File";
		}


		var scOffs = document.viewport.getScrollOffsets();
		var myTop = scOffs.top + 20;
		var style = {
			position: 'absolute',
			width: '300px',
			top: myTop+'px',
			left: '50%',
			marginLeft: '-150px',
			zIndex: 200
		};
		this.element.setStyle(style);
		coverScreen(1, 100);
	
		var welemDraggable = new Draggable(this.element, {
			handle: $(this.element.id+'_titleBar'),
			starteffect: null,
			endeffect: null
		});
	
		this.element.appear({ duration: 0.5 });
	},

	hideWindow: function() {
		//alert('hiding window');
		if (Prototype.Browser.IE) {
			this.element.hide();
		} else {
			this.element.fade({ duration: 0.5 });
		}
		coverScreen(0);
	},

	submitUpload: function() {

		if (!$(this.mainForm.id+'_file_field').value) {
			alert("Please select a file to upload.");
			return false;
		}

		coverBox(this.element);

		// find the upload tracking id	
		this.mainForm.getElements().each(function(felem, i) {
			if (felem.name == 'UPLOAD_IDENTIFIER') {
				this.uploadId = felem.value;
			}
		}.bind(this));

		// show the progress bar
		if (this.progressElement) {
			var style = {
				position: 'fixed',
				overflow:'auto',
				top:'150px', 
				width:'500px',
				left:'50%', 
				marginLeft: '-250px',
				background:'#fff',
				border:'2px solid black',
				zIndex:800
			};
			this.progressElement.setStyle(style);

			this.progressBarObj = new ProgressBar($(this.progressBarElement), {
				color: {r: 0, g: 0, b: 155},
				style: ProgressBar.INDETERMINATE | ProgressBar.TRANSPARENCY,
				IndeterminateIndicatorsSpeed: 12,
				noIndeterminateIndicators: 25
				});

			//this.progressElement.show();
			this.progressElement.appear({ duration: 0.5 });
		}

		// listen for the iframe to load
		Event.observe(this.uploadFrame, 'load', this.uploadDone.bindAsEventListener(this));

		// start the progress updator
		this.pe = new PeriodicalExecuter(this.pollUploadProgress.bind(this), 2);

		// submit the form only after the progressBar is done creating
		this.submitPe = new PeriodicalExecuter(this.verifyPBCreated.bind(this), 0.1);

	},

	verifyPBCreated: function(p) {
		if (this.progressBarObj) {
			p.stop();
			this.mainForm.submit();
		}
	},

	pollUploadProgress: function () {

			if (!this.options.progressURL || !this.progressElement) {
				return false;
			}

			new Ajax.Request(this.options.progressURL, {
				parameters: { progress_id: this.uploadId },
				onSuccess: function(transport) {

					//this.progressDebugElement.innerHTML = transport.responseText;

					var resp = eval("("+transport.responseText+")");

					if (resp && resp.time_start) {

						//update the progress bar
						this.updateProgressBar(resp);
						/*
						var str = 'time_start'+resp.time_start+"\n";
						str += 'time_last'+resp.time_last+"\n";
						str += 'speed_average'+resp.speed_average+"\n";
						str += 'speed_last'+resp.speed_last+"\n";
						str += 'bytes_uploaded'+resp.bytes_uploaded+"\n";
						str += 'bytes_total'+resp.bytes_total+"\n";
						str += 'files_uploaded'+resp.files_uploaded+"\n";
						str += 'est_sec'+resp.est_sec+"\n";
						this.progressDebugElement.innerHTML += str;
						*/
					}
  				}.bind(this)
			});

	},

	updateProgressBar: function(progress) {

		if (!this.progressBarObj) {
			return false;
		}

		if (!this.time_last || this.time_last < progress.time_last) {
			this.time_last = progress.time_last;

			if ((this.progressBarObj.options.style & ProgressBar.INDETERMINATE ) == ProgressBar.INDETERMINATE) {
				this.progressBarObj.setDeterminate();
			}

			// update the progress bar width
			this.progressBarObj.setSelection(((progress.bytes_uploaded / progress.bytes_total)*100) % this.progressBarObj.getMaximum());

			// udpate the progress text
			var str = ""+Math.round(progress.bytes_uploaded/1024)+" of "+Math.round(progress.bytes_total/1024)+"kB loaded";
			this.progressTextElement1.innerHTML = str;
			var str = ""+Math.round((progress.speed_average/1024)*10)/10+"kB/s - "+progress.est_sec+" seconds remaining";
			this.progressTextElement2.innerHTML = str;

		}
	},

	uploadDone: function(event) {

		var iframedoc = window.frames[event.element().id].document;
		var ret = iframedoc.body.innerHTML;

		if (ret.strip().substring(0,7) == 'success') {
			this.stopProgresBar();
		} else {
			this.stopProgresBar(ret.strip());
		}

		// remove the cover and hide the mainForm
		this.element.removeChild($(this.element.id+"_cover"));
		this.element.hide();
		coverScreen(0);

		if (this.mediaType == -1) {

			// reload the thumbnail
			new Ajax.Updater(this.container, '/AspeakerPacks/thumbnailimg/'+this.dbId, {
				method: 'post'
			});

		} else if (this.mediaType !== null && this.dbId) {
			// reload the media list
			new Ajax.Updater(this.container, '/AspeakerPacks/listfiles/'+this.dbId, {
				method: 'post',
				parameters: { type: this.mediaType },
				onComplete: function() {
					setSortableMedia(this.container, this.listItemClass, this.mediaType);
					lightwindowReInit();
				}.bind(this)
			});
		}

	},

	stopProgresBar: function (error) {

		// stop the ajax listener
		this.pe.stop();

		// stop listening for completion
		Event.stopObserving(this.uploadFrame, 'load');

		this.progressBarObj.dispose();
		this.progressBarObj = null;
		this.progressElement.fade({ duration: 0.5 });
		if (error) {
			alert(""+error);
		}
	},

	submitEdit: function(event)
	{
		var params = {
			do_edit: 1,
			type: this.mediaType,
			e_id: this.fileEditId,
			e_name: $(this.element.id+'_form_field_name').value,
			e_description: $(this.element.id+'_form_field_description').value
		};

		coverBox(this.element.id);

		new Ajax.Updater(this.container, '/AspeakerPacks/listfiles/'+this.dbId, {
			method: 'post',
			parameters: params,
			onComplete: function() {
				coverScreen(0);
				$(this.element.id+'_cover').remove();
				this.element.hide();
				setSortableMedia(this.container, this.listItemClass, this.mediaType);
				lightwindowReInit();
			}.bind(this)
		});
	}

});

function doMessagePopup(e)
{
	if (isShowingPopup) { 

		$(divPopup).remove();
		isShowingPopup = false;

	} else {

		divPopup = new Element('div', {

		});

		$(divPopup).setStyle({

			position: 'absolute',
			zIndex: 10,
			width: divPopupWidth,
			color: divPopupFontColor,
			backgroundColor: divPopupBackgroundColor,
			border: divPopupBorder,
			padding: divPopupPadding,
			fontSize: divPopupFontSize,
			textAlign: divPopupTextAlign,
			marginTop: divPopupMarginTop
			
		});

		$(divPopup).update(divPopupMssg);
		$(parentId).appendChild(divPopup);

		$(divPopup).observe('click', function(e) {

			$(divPopup).remove();

		});

		isShowingPopup = true;
	}
}


/**
*
* Replacements for basic javascript popup events alert, confim, prompt
* all of these are non-blocking and use callbacks rather than returning anything
*
*/
(function() {

	var instances = [];

	window.DomPopupCloseAll = function() {
		instances.each(function(ins) {
			ins.close();
		});
	}

	window.DomPopup = function(content, userConfig) {

		var defaultConfig = {
			containerClass: 'DomPopup',
			containerStyle: null,
			zindex: 1000,
			formId: null,
			position: [null,null],
			size: [null,null],
			showEffect: null,
			buttonSpacing: null,
			buttonClass: null,
			buttons: [{
				value: 'Cancel',
				onClick: function(e) { alert('Cancel clicked'); this.close(); }
			},{
				value: 'OK',
				onClick: function(e) { alert('OK clicked'); this.close(); }
			}],
			onSubmit: null,
			onLoad: null
		};
		userConfig = Object.extend(defaultConfig, userConfig);

		// set default style if there is none
		if (!userConfig.containerClass && !userConfig.containerStyle) {
			userConfig.containerStyle = { background:'#ccc', border:'1px solid black', padding:'10px' };
		}

		instances.push(new DomPopup(content, userConfig, instances.length));
	}


	function DomPopup(content, config, myId) {
	
		var self = this;
		self.mainId = 'DomPopup_'+myId;
		self.config = config;

		var div = document.createElement('div');
		self.element = div;

		div.id = self.mainId;
		Element.extend(div);
		div.addClassName(self.config.containerClass);
		div.setStyle({ position:'fixed', zindex:self.config.zindex, left:'0px', top:'0px' });
		if (self.config.containerStyle) {
			div.setStyle(self.config.containerStyle);
		}

		self.form = document.createElement('form');
		Element.extend(self.form);
		if (config.formId) {
			self.form.id = config.formId;
		}

		var contentDiv = document.createElement('div');
		contentDiv.innerHTML = content;
		self.form.appendChild(contentDiv);

		var buttonsDiv = document.createElement('div');
		Element.extend(buttonsDiv);
		buttonsDiv.setStyle({ textAlign:'center' });
		// add the buttons
		self.buttons = [];
		if (typeof self.config.buttons == 'object') {
			self.config.buttons.each(function(buttonConf, i) {
				var button = document.createElement('input');
				button.id = 'DomPopup_'+myId+'_button_'+i;
				button.type = 'button';
				button.value = buttonConf.value;
				Element.extend(button);
				buttonsDiv.appendChild(button);

				if (self.config.buttonClass) {
					button.addClassName(self.config.buttonClass);
				}

				if (self.config.buttonSpacing != null && i < (self.config.buttons.length - 1)) {
					button.setStyle({ marginRight: self.config.buttonSpacing+'px' });
				}

				if (typeof buttonConf.style == 'object') {
					button.setStyle(buttonConf.style);
				}

				if (typeof buttonConf.onClick == 'function') {
					button.observe('click', function(e) {
						buttonConf.onClick.call(self, e);
					});
				}

				self.buttons.push(button);
			});
		}
		self.form.appendChild(buttonsDiv);

		// form onSubmit listener
		if (typeof self.config.onSubmit == 'function') {
			self.form.onsubmit = function(e) {
				self.config.onSubmit.call(self, e);
				return false;
			};
		} else {
			self.form.onsubmit = function() { return false; };
		}

		div.appendChild(self.form);

		div.hide();
		document.body.appendChild(div);

		// position the element in the center as best we can
		var vp = document.viewport.getDimensions();
		var divDims = [], calcDims = [];
		if (self.config.size && self.config.size[0]) {
			divDims[0] = self.config.size[0];
		} else {
			calcDims = div.getDimensions();
			divDims[0] = calcDims.width;
		}
		if (self.config.size && self.config.size[1]) {
			divDims[0] = self.config.size[1];
		} else {
			calcDims = div.getDimensions();
			divDims[1] = calcDims.height;
		}

		var LT = [];
		LT[0] = Math.floor((vp.width - divDims[0]) / 2);
		LT[1] = Math.floor((vp.height - divDims[1]) / 2);
		div.setStyle({ left:LT[0]+'px', top:LT[1]+'px'});

		if (typeof self.config.showEffect == 'function') {
			self.config.showEffect.call(window, div);
		} else {
			div.show();
		}

		/* DomPopup methods */
		self.close = function() {
			// remove me from instances
			instances.splice(myId, 1);

			// remove me from the dom
			document.body.removeChild(div);
		}

		/* form helper methods */
		self.form.getElementByName = function(name) {
			var ret = null;
			self.form.getElements().each(function(el) {
				if (el.name == name) {
					ret = el;
					return;
				}
			});
			return ret;
		}

		// see if we need to run an onload event
		if (typeof self.config.onLoad == 'function') {
			self.config.onLoad.call(self);
		}

	};



	window.DomPopupAlert = function(mssg) {

		window.DomPopup(mssg, {
			containerClass: 'box1',
			containerStyle: { border:'2px solid black' },
			buttonSpacing: 0,
			buttons: [{
				value:' OK ',
				onClick: function(e) {
					this.close();
				}
			}]	
		}); 

	};


	window.DomPopupPrompt = function(mssg, defaultTxt, onSubmit) {

		var reg = /"/g;
		var content = '<div>'+mssg+'</div><div><input type="text" name="prompt" value="';
		content += defaultTxt.replace(reg, '&quot;')+'" /></div>';

		window.DomPopup(content, {
			containerClass: 'box1',
			containerStyle: { border:'2px solid black' },
			buttonSpacing: null,
			showEffect: null,
			buttons: [{
				value:'Cancel',
				style:{ display:'block', float:'left' },
				onClick: function(e) {
					this.close();
				}
			},{
				value:' OK ',
				style:{ display:'block', float:'right' },
				onClick: function(e) {
					this.form.getElements().each(function(elem) {
						if (elem.name == 'prompt' && typeof onSubmit == 'function') {
							onSubmit.call(this, elem.getValue());
						}
						return;
					});
					if (typeof onSubmit != 'function') {
						this.close();
					}
				}
			}],
			onLoad: function() {
				// focus the text input
				var elem = this.form.getElementByName('prompt');
				if (elem) { elem.focus(); }
			},
			onSubmit: function(e) {
				// form submit is same as OK button onclick
				this.config.buttons[1].onClick.call(this, e);
			}
		}); 

	};


	window.DomPopupConfirm = function(mssg, onSubmit) {

		window.DomPopup(mssg, {
			containerClass: 'box1',
			containerStyle: { border:'2px solid black' },
			buttonSpacing: null,
			buttons: [{
				value:'Cancel',
				style:{ display:'block', float:'left' },
				onClick: function(e) {
					this.close();
				}
			},{
				value:' OK ',
				style:{ display:'block', float:'right' },
				onClick: function(e) {
					if (typeof onSubmit == 'function') {
						if (onSubmit.call(this, e) !== false) {
							this.close();
						}
					} else {
						this.close();
					}
				}
			}]	
		}); 

	}


})();




