// Some functions [getPageSize] taken from
//
//	Lightbox v2.04
//	by Lokesh Dhakar - http://www.lokeshdhakar.com
//
//	For more information, visit:
//	http://lokeshdhakar.com/projects/lightbox2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//var ST = window.ST || {};

/**
 *@version 0.2
 *
 *changelog:
 *0.1 - initial version
 *0.2 - ST/SortTable changed for methodizing
 */
var ST = {};
/**** SorTable ****/

/**
* Creates sortable table
*/
ST.sortDirection = 'asc';
/**
 * Returns rendered row
 * @argument rowData {Array} Array filled with columns {content:,value:,options:}
 * @argument index {Number} Row index
 * @argument options {Object} Options object {altClass:,}
 */
ST.renderRow = function(rowData,options){
	if(typeof(rowData)==='undefined'){
		return false;
	}
	options = Object.clone(options) || {};
	var _options = {
		altClass:'alt',
		idPrefix:'',
		idSeparator:'_'
	};
	Object.extend(_options, options);
	var tableRow = new Element('tr');
	var rowId = null;
	if(typeof(rowData.id)!=='string'){
		if(options.idPrefix!=''){
			rowId = options.idPrefix+options.idSeparator+(this.rows.length+1);
		}		
	} else {
		if(rowData.id != ''){
			rowId = rowData.id;
		}
		
	}
	tableRow.id = rowId;
	if(this.options.altClass != ''){
		if((this.rows.length-1)%2==0){
			tableRow.addClassName(this.options.altClass);
		}
	}
	tableRow.columns = [];
	rowData.each(
		function(col,index){
			var tdElement;
			if(typeof(col)==='undefined' || col===null){
				col = '';
			}
			var column = this.columns[index];
			if(typeof(col.content)==='undefined'){
				col = {content:col};
			}
			col.options = Object.clone(col.options) || {};
			Object.extend(col.options, column.tdOptions);
			var tdElement = new Element('td',col.options);
			var columnData = {};
			var columnContent = '';
			columnContent = col.content;
			if(typeof(col.value)!=='undefined'){
				columnData.value = col.value;
			} else {
				columnData.value = col.content;
			}
			columnContent = col.content;
			switch (column.dataType){
				case "number":
					columnData.value = Number(columnData.value);
					break;
				case "image":
					var imagePath = column.imagePath+col.content;
					columnContent = new Element('img',{src:imagePath});
					break;
			}
			
			tdElement.update(columnContent);
			tableRow.id = "dupa";
			tableRow.columns.push(columnData);
			tableRow.appendChild(tdElement);
		}.bind(this)
	);
	this.rowElements.push(tableRow);
	this.appendChild(tableRow);
	return tableRow;
}
ST.SORT_ASC = 'sort_asc';
ST.SORT_DESC = 'sort_desc';
ST.createTable = function(columns,tableOptions){
	this.columns = [];
	this.rowElements = [];
	this.defaultSortColumn = null;
	this.options = {
		altClass:'alt',
		tableOptions:{
			id:'sortTable',
			className:'sortTable'
		},
		headerRowOptions:{
			className:''
		}
	};
	tableOptions = Object.clone(tableOptions) || {};
	Object.extend(this.options, tableOptions);
	var tableElement = new Element('table', this.options);
	tableElement.id = this.options.tableOptions.id;
	tableElement.addClassName(this.options.tableOptions.className);
	var headerRow = new Element('tr', this.options.headerRowOptions);
	headerRow.addClassName(this.options.headerRowOptions.className);
	columns.each(
		function(col,index){
			col.options = Object.clone(col.options) || {};
			var column = {
				dataType:'string',
				sortDirection:ST.SORT_ASC,
				imagePath:'img/',
				sortable:false,
				isDefault:false,
				label:'column '+index,
				tdOptions:{}
			};
			Object.extend(column, col);
			var tableHeaderCell = new Element('th', col.options);
			Object.extend(tableHeaderCell, column);
			tableHeaderCell.update(column.label);
			if(column.isDefault === true){
				this.defaultSortColumn = tableHeaderCell;
			}
			if(column.sortable === true){
				tableHeaderCell.setStyle({cursor:'pointer'});
				tableHeaderCell.observe('click', this.onSortableHeaderClickHandle.bind(tableElement));
			}
			this.columns.push(tableHeaderCell);
			headerRow.appendChild(tableHeaderCell);
		}.bind(this)
	)
	if(this.defaultSortColumn === null){
		this.defaultSortColumn = this.columns[0];
	}
	tableElement.appendChild(headerRow);
	Object.extend(tableElement, this);
	return tableElement;
}
ST.compare = function(aValue,bValue){
	if(aValue > bValue){
		if(this.options.sortDirection === ST.SORT_ASC){
			return 1;
		} else {
			return -1;
		}
	}
	if(aValue < bValue){
		if(this.options.sortDirection === ST.SORT_ASC){
			return -1;
		} else {
			return 1;
		}
	}
	if(aValue == bValue){
		return 0;
	}	
}
ST.sortRow = function(a,b){
	var columnIndex = this.sortColumnIndex;
	var compareFunction = ST.compare.bind(this);
	return compareFunction(
		a.columns[columnIndex].value,
		b.columns[columnIndex].value
	);
}
ST.onSortableHeaderClickHandle = function(e){
	var clickedHeaderCell = e.currentTarget;
	this.sortByColumn(clickedHeaderCell);
}
ST.sortByNamedColumn = function(columnName){
	var sortColumn = this.columns.find(
		function(headerCell){
			if(headerCell.label == columnName){
				return true;
			} else {
				return false;
			}
		}
	);
	if(sortColumn !== false){
		this.sortByColumn(sortColumn);
	}
}
ST.sortByDefault = function(){
	this.sortByColumn(this.defaultSortColumn);
}
ST.sortByColumn = function(headerElement){
	if(typeof(this.currentSortColumn)!=='undefined'){
		this.currentSortColumn.removeClassName('sortColumn');
		this.currentSortColumn.removeClassName('asc');
		this.currentSortColumn.removeClassName('desc');		
		if(this.currentSortColumn === headerElement){
			if(headerElement.sortDirection == ST.SORT_ASC){
				
				headerElement.sortDirection = ST.SORT_DESC;
			} else {
				headerElement.sortDirection = ST.SORT_ASC;
			}
		} else {
			this.currentSortColumn = headerElement;
		}
	} else {
		this.currentSortColumn = headerElement;
	}
	headerElement.addClassName('sortColumn');
	switch(headerElement.sortDirection){
		case ST.SORT_ASC:
			headerElement.addClassName('asc');
			break;
		case ST.SORT_DESC:
			headerElement.addClassName('desc');
			break;
	}
	this.options.sortDirection = headerElement.sortDirection;
	var columnIndex = this.columns.indexOf(headerElement);
	this.sortColumnIndex = columnIndex;
	this.rowElements.sort(ST.sortRow.bind(this));
	this.rowElements.each(function(row,iterator){
		row.removeClassName(this.options.altClass);
		if(iterator %2 == 0){
			row.addClassName(this.options.altClass);
		}
		this.appendChild(row);
	}.bind(this));
}
var mwwsDF = {}; // MWWS Dynamic Forms

mwwsDF.SELECT_UPGRADE_QUICKFIND_FIRST = 'qfBox first';
mwwsDF.SELECT_UPGRADE_QUICKFIND_ALL = 'qfBox all';
mwwsDF.quickFindSelect = {};
mwwsDF.quickFindSelect.onQuickFindFieldChangeHandle = function(e){
	var quickFindField = e.currentTarget;
	var selectField = quickFindField.selectField;
	var lastFound;
	selectField.getElementsBySelector('option').each(function(optionElement){
		if(optionElement.innerHTML.indexOf(quickFindField.value)===0){
			optionElement.show();
			if(!lastFound){
				lastFound = optionElement;
			}
		} else {
			optionElement.hide();
			optionElement.selected = false;
		}
	});
	if(!lastFound){
		if(typeof(selectField.lastFound)!=='undefined'){
			lastFound = selectField.lastFound;
		} else {
			lastFound = selectField.options[0];
		}		
	} else {
		selectField.lastFound = lastFound;
	}
	lastFound.show();
	lastFound.selected = true;
}
mwwsDF.upgradeSelectField = function(selectField, currentValue, selectOptionsArray, upgradeOptions){
	var upgradeType = mwwsDF.SELECT_UPGRADE_QUICKFIND_FIRST;
	if(typeof(upgradeOptions)!=='undefined'){
		if(typeof(upgradeOptions.upgradeType)!=='undefined'){
			upgradeType = upgradeOptions.upgradeType;
		}
	}
	selectField = $(selectField);
	selectOptionsArray.each(function(optionData){
		var optionElement = new Element('option',{value:optionData.value});
		optionElement.update(optionData.label);
		if(optionData.value == currentValue){
			optionElement.selected = true;
			hasSelected = true;
		}
		$H(optionData).each(function(oV){
			if(oV.key != 'label' && oV.key != 'value'){
				optionElement[oV.key] = oV.value;
			}
		});
		selectField.appendChild(optionElement);
	});
	//
	// TODO:
	// implement other upgrade types
	switch(upgradeType){
		case mwwsDF.SELECT_UPGRADE_QUICKFIND_FIRST:
			var selectWidth = selectField.getWidth();
			var quickFindBox = new Element('input',{type:'text'});
			if(String(selectWidth).indexOf('px')==-1){
				selectWidth = selectWidth+"px";
			}
			quickFindBox.setStyle({width:selectWidth});
			quickFindBox.selectField = selectField;
			quickFindBox.observe('keyup', mwwsDF.quickFindSelect.onQuickFindFieldChangeHandle);
			selectField.insert({'after':quickFindBox});
			quickFindBox.insert({'before':'<br/>'});
			break;
	}
}
//var MU = window.MU || {};
/*mwwsDF.gatherFormData = function(formElement){
	
mPE.gatherFormData = function() {
	var formInputFields = $$(':not[class*=dontsend]');
	var formData = new Object();
	formInputFields.inject(formData,
		function(formData, el, index){
			var inputName = el.name;
			var inputValue = el.value;
			if(el.type=='checkbox'){
				if(el.checked){
					formData[inputName] = 1;
				} else {
					formData[inputName] = 0;
				}
			} else {
				pD[inputName] = inputValue;
			}
			return pD;
		});
	return postData;
}

*/
var MU = {};
MU.onOverlayRemovedEvent = 'overlay_removed';
MU.onOverlayBoxRemovedEvent = 'overlay_box_removed';
MU.eventDispatcher = new Element('div');
MU.highlightAndClear = function (el, optionsObject){
	if(typeof(optionsObject.afterFinish)!=='function'){
		optionsObject.afterFinish = new Function();
	}
	optionsObject.afterFinish = optionsObject.afterFinish.wrap(
		function(proceed,fx){
			fx.element.setStyle({background:""});
			return proceed(fx);
		}
	);
	new Effect.Highlight(el, optionsObject);
}
MU.addEventListener = function(eventType, functionReference){
	MU.eventDispatcher.addEventListener(eventType, functionReference, false);
}
MU.removeEventListener = function (eventType, functionReference){
	MU.eventDispatcher.removeEventListener(eventType, functionReference, false);
}
MU.dispatchEvent = function(eventType, bubbles){
	if(typeof(bubbles) === 'undefined'){
		bubbles = true;
	}
	var eventObject = document.createEvent('HTMLEvents');
	eventObject.initEvent(eventType, bubbles, true);
	MU.eventDispatcher.dispatchEvent(eventObject);
}
MU.getElementOffset = function(element){
	var curleft = 0;
	var curtop = 0;
	if (element.offsetParent) {
		while (element = element.offsetParent) {
			curleft += element.offsetLeft;
			curtop += element.offsetTop;
		};
	}
	return [curleft,curtop];
}
MU.overlayBoxCount = 0;
MU.createOverlayBox = function (boxWidth, boxHeight, frameHeight){
	MU.overlayBoxCount++;
	var overlayBoxId = "overlayBox_"+MU.overlayBoxCount;
	if(typeof(boxWidth) === 'undefined' || boxWidth === null){
		boxWidth = 960;
	}
	if(typeof(boxHeight) === 'undefined' || boxHeight === null){
		boxHeight = 600;
	}
	if(typeof(frameHeight) === 'undefined' || frameHeight === null){
		frameHeight = 700;
	}
	var overlayElement = new Element('div');
	overlayElement.id = overlayBoxId;
	var windowSize = MU.getWindowSize();
	var leftOffset = (windowSize[0]-boxWidth)/2;
	var topOffset = (frameHeight-boxHeight)/2;
	overlayElement.addClassName('overlayBox');
	overlayElement.setStyle({
	    left:leftOffset+"px",
	    width:boxWidth+"px",
	    top:topOffset+"px",
	    height:boxHeight+"px"
	});
	return overlayElement;
}
MU.getPageSize = function(){
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	return [pageWidth,pageHeight];
}

MU.getWindowSize = function(){
	if(window.innerHeight){
		var cHeight = window.innerHeight;
	} else {
		var cHeight = document.documentElement.clientHeight;
	}
	if(window.innerWidth){
		var cWidth = window.innerWidth;
	} else {
		var cWidth = document.documentElement.clientWidth;
	}
	return [cWidth, cHeight];
}
MU.bgOverlayCount = 0;
MU.closeOverlayBox = function(overlayBoxId, afterFinishCallback){

	if(typeof(overlayBoxId) === 'undefined' || overlayBoxId === null){
		overlayBoxId = "overlayBox_"+MU.overlayBoxCount;
		MU.overlayBoxCount--;
	}
	var afterFinish = new Function();
	afterFinish = function(){
		this.ovBox.remove();
		MU.dispatchEvent(MU.onOverlayBoxRemovedEvent);
		if(this.userCallback != null){
			this.userCallback.call();
		}
	}	
	afterFinish.ovBox = $(overlayBoxId);
	if(!(typeof(afterFinishCallback) === 'undefined' || afterFinishCallback === null)){
		afterFinish.userCallback = afterFinishCallback;
	} else {
		afterFinish.userCallback = null;
	}

	new Effect.Opacity(overlayBoxId, {to:0, duration:0.3, afterFinish:afterFinish.bind(afterFinish)});
}
MU.removeOverlay = function(overlayId, afterFinishCallback){
	if(typeof(overlayId)==='undefined' || overlayId === null){
		overlayId = "bgOverlay"+MU.bgOverlayCount;
		MU.bgOverlayCount--;
	}
	var afterFinish = new Function();
	afterFinish = function(){
		this.overlay.remove();
		MU.dispatchEvent(MU.onOverlayRemovedEvent);
		if(this.userCallback != null){
			this.userCallback.call();
		}
	}	
	afterFinish.overlay = $(overlayId);
	if(!(typeof(afterFinishCallback) === 'undefined' || afterFinishCallback === null)){
		afterFinish.userCallback = afterFinishCallback;
	} else {
		afterFinish.userCallback = null;
	}	

	new Effect.Opacity(overlayId, {to:0, duration:0.3, afterFinish:afterFinish.bind(afterFinish)});
}
MU.createButton = function(label, clickAction){
	var returnButton = new Element('input');
	returnButton.type = 'button';
	returnButton.value = label;
	returnButton.observe('click', clickAction);
	return returnButton;
}
MU.createBgOverlay = function(){
	MU.bgOverlayCount++;
	var overlayId = "bgOverlay"+MU.bgOverlayCount;
	var pageSize = this.getPageSize();
	var screenSize = this.getWindowSize();
	var tempDiv = new Element('div');
	tempDiv.innerHTML = "<div style='display:none; background-color:#000; position:absolute; left:0px; top:0px' id='"+overlayId+"'>&nbsp;</div>";
	$$('body')[0].appendChild(tempDiv);
	var processingOverlayElement = $(overlayId);
	$$('body')[0].appendChild(processingOverlayElement);
	$$('body')[0].removeChild(tempDiv);
	processingOverlayElement.setStyle({width:pageSize[0]+"px", height:pageSize[1]+"px"});
	Effect.Appear(processingOverlayElement, {duration:0.1, to:0.7});
	return processingOverlayElement;
}
MU.getBrowser = function(){
	var browsers = new Array();
	var ieData = new Object({agentPreg:'MSIE', versionPreg: /MSIE ([0-9\.]+)/, fullString:'Internet Explorer', shortString:'IE'});
	browsers.push(ieData);
	for(var k=0;k<browsers.length;k++){
		browserData = browsers[k];
		if(navigator.userAgent.match(browserData.agentPreg)){
			var versionMatch = navigator.userAgent.match(browserData.versionPreg);
			var returnData = new Array();
			returnData['fullString'] = browserData.fullString;
			returnData['version'] = String(versionMatch[1]).split(".");
			returnData['id'] = browserData.shortString;
			return returnData;
		}
	};
	return false;
}
