/*
	Alex Oleshkevich, 2008
*/

var Dialog = function (settings) {
	dialog = this;
	dialogBoxTitle = '';
	
	this.screen = {
		'width':screen.availWidth,
		'height':screen.availHeight
	}
	
	this.stack = new Array();
	
	if(typeof settings == 'undefined') {
		settings = new Object();
		settings.imagesPath = typeof settings.imagesPath == 'undefined' ? '../images' : settings.imagesPath;
		settings.drawShadows = typeof settings.drawShadows == 'undefined' ? true : settings.drawShadows;
		settings.forceExceptions = typeof settings.forceExceptions == 'undefined' ? false : settings.forceExceptions;
		settings.draggable = typeof settings.draggable == 'undefined' ? false : settings.draggable;
		settings.override = typeof settings.override == 'undefined' ? false : settings.override;

	}

	if(typeof settings.images == 'undefined')
		settings.images = new Object();
	
	settings.images.topLeft = typeof settings.images.topLeft == 'undefined' ? 'top_left_shadow.png' : settings.images.topLeft;
	settings.images.topRight = typeof settings.images.topRight == 'undefined' ? 'top_right_shadow.png' : settings.images.topRight;
	settings.images.bottomLeft = typeof settings.images.bottomLeft == 'undefined' ? 'bottom_left_shadow.png' : settings.images.bottomLeft;
	settings.images.bottomRight = typeof settings.images.bottomRight == 'undefined' ? 'bottom_right_shadow.png' : settings.images.bottomRight;
	
	this.createElement = function(element, params) {
		elem = document.createElement(element);
		
		for(i in params) {
			elem[i] = params[i];	
		}
		
		return elem;
	}
	
	this.getDialogBox = function() {
			
		dialogBox = this.createElement('div',{'className' : 'dialogBox'});
		
		title = this.createElement('div',{'className' : 'dialogTitle'});
		
		message = this.createElement('div',{'className' : 'dialogMessage'});
		
		toolbar = this.createElement('div',{'className' : 'dialogToolbar'});
	
		serviceBox = this.createElement('div',{'className' : 'dialogServiceBox'});
		
		this.dialogBoxId = this.makeId();
		dialogBox.setAttribute('id',this.dialogBoxId);
		dialogBox.dialogId = this.dialogBoxId;
		
		dialogBox.appendChild(title);
		dialogBox.appendChild(message);
		dialogBox.appendChild(serviceBox);
		dialogBox.appendChild(toolbar);
		
		dialogBox.dialogTitle = title;
		dialogBox.dialogMessage = message;
		dialogBox.dialogServiceBox = serviceBox;
		dialogBox.dialogToolbar = toolbar;
		
		dialogBox.addButton = function(button) {
			if(typeof button != 'object') 
				return alert('Not right kind of button!\n Misspelled?');

			this.dialogToolbar.appendChild(button);
		}
		
		dialogBox.append = function () {
			for(i=0;i<=args.length;i++) {
				alert(args[i]);
			}
		}	
		
		dialogBox.addTextField = function(value) {
			dialogTextarea = dialog.createElement('div',{'className' : 'dialogTextarea'});
			
			textarea = dialog.createElement('textarea',{'value' : value});
			dialogTextarea.appendChild(textarea);
			
			this.dialogServiceBox.dialogTextarea = textarea;
			
			this.dialogServiceBox.appendChild(dialogTextarea);
		}
		
		dialogBox.setTitle = function(title) {
			this.dialogTitle.innerHTML = title;
		}
		
		dialogBox.addClass = function(className) {
			this.className +=' '+className;
		}
		
		dialogBox.setMessage = function(msg) {
			this.dialogMessage.innerHTML = msg;
		}
		
		return dialogBox;
	}


// legacy code, will be removed in next releases
	this.addShadows = function(dialogBox) {
		topShadow = document.createElement('div');
		topShadow.className = 'shadow';
		
		topLeftImage = document.createElement('img');
		topRightImage = document.createElement('img');
		
		topLeftImage.src = settings.imagesPath + '/' + settings.images.topLeft;
		topRightImage.src = settings.imagesPath + '/' + settings.images.topRight ;
		topRightImage.className = 'dialogFloatRight';
		
		topShadow.appendChild(topLeftImage);
		topShadow.appendChild(topRightImage);
		
		bottomLeftImage = document.createElement('img');
		bottomLeftImage.src = settings.imagesPath + '/' + settings.images.bottomLeft ;
		
		bottomRightImage = document.createElement('img');
		bottomRightImage.src = settings.imagesPath + '/' + settings.images.bottomRight;
		bottomRightImage.className = 'dialogFloatRight';
		
		bottomShadow = document.createElement('div');
		bottomShadow.className = 'shadow';
		bottomShadow.appendChild(bottomLeftImage);
		bottomShadow.appendChild(bottomRightImage);
		
		wrapper = document.createElement('div');
		wrapper.className = 'wrapper';
		
		try {
			wrapper.appendChild(dialogBox.dialogTitle);
			wrapper.appendChild(dialogBox.dialogMessage);
			wrapper.appendChild(dialogBox.dialogServiceBox);
			wrapper.appendChild(dialogBox.dialogToolbar);
		} catch (e) {
			if(settings.forceExceptions) {
				alert('Add wrapper: '+e.message);
			}
		}
		
		dialogBox.appendChild(topShadow);
		dialogBox.appendChild(wrapper);
		dialogBox.appendChild(bottomShadow);
		
		return dialogBox;
	}

	this.addEvent = function(element,etype,fn,usecapture) {
		if(element.addEventListener){
			element.addEventListener(etype, fn, usecapture);
			
			return true;
		}else if(element.attachEvent){
			var r = element.attachEvent('on'+etype, fn);
			
			return r;
		}else{
			element['on'+etype]= fn;
		}
	}
	
	this.removeEvent = function(obj, etype, fn, usecapture){
		if (obj.removeEventListener){
			obj.removeEventListener(etype, fn, usecapture);
			return true;
		} else if (obj.detachEvent){
			var r = obj.detachEvent('on'+etype, fn);
			return r;
		} else {
			elt['on'+etype]= null;
		}
	}
	
	this.draggable = function(dialogBox) {
		this.addEvent(dialogBox.dialogTitle,'mousedown',function(event){
			
			dialog.current = {
				'left' : parseInt(dialogBox.style.left),
				'top' : parseInt(dialogBox.style.top),
				'x' : event.pageX || event.screenX,
				'y' : event.pageY || event.screenY
			}
			
			// kostyl' - prosto pizdec. na pervoe vremya
			dialogBox.drag = 1;
		},false);
		
		this.addEvent(dialogBox.dialogTitle,'mouseup',function(){
			dialogBox.drag = 0;
			dialogBox.dialogTitle.style.cursor = 'default';
		},false);
		
		this.addEvent(dialogBox.dialogTitle,'mouseout',function(){
			dialogBox.drag = 0;
			dialogBox.dialogTitle.style.cursor = 'default';
		},false);
		
		this.addEvent(dialogBox.dialogTitle,'mousemove',function(event){
			if(dialogBox.drag) {			
				left = dialog.current.left + (event.pageX || event.screenX) - dialog.current.x;
				top = dialog.current.top + (event.pageY || event.screenY) - dialog.current.y;
				//c.log(newLeft);
				
				dialogBox.dialogTitle.style.cursor = 'move';
				dialogBox.style.left = left+'px';
				dialogBox.style.top = top+'px';
				//c.log('New Left: '+newLeft);
			}
			
		},false);
		
	}
	
	this.createButton = function(caption, fn, mode) {
		button = document.createElement('a');
		button.href = mode ? 'javascript: dialog.removeDialogBox(' + this.dialogBoxId + ')' : 'javascript:void(0)';
		button.innerHTML = caption;
		button.id = caption + this.dialogBoxId;
		this.addEvent(button,'click',fn, false);
		
		return button;
	}
	
	this.inArray = function(needle,haystack) {
		for(i in haystack) {
			if(haystack[i] == needle) {
				return true;
			}
		}
		return false;
	}
	
	this.deleteFromArray = function(needle,haystack) {
		for(i in haystack) {
			if(haystack[i] == needle) {
				delete haystack[i];
			}
		}
	}
	
	this.removeDialogBox = function(id) {
		elm = document.getElementById(id);
		
		elm.parentNode.removeChild(elm);
		
		arr = dialog.stack.reverse();
		arr.shift();
		this.stack = arr.reverse();

		this.removeCarpet();
	}

	this.addCarpet = function () {
		try {

			document.getElementById('carpet');

			carpet = dialog.createElement('div', {
				'id' : 'carpet',
				'className' : 'carpet'
			})

			document.getElementsByTagName('body')[0].appendChild(carpet);

		} catch (e) {
			alert(e);
		}
		
	}

	this.removeCarpet = function () {
		try {
			carpet = document.getElementById('carpet');

			carpet.parentNode.removeChild(carpet);

			delete carpet;
		} catch (e) {
			alert(e);
		}
	}

// unstable
	this.fadeIn = function(id, interval, fn) {
		i = 0;
		elem = document.getElementById(id);

		timer = setInterval(function(){
			if (i >= 10) {
				clearInterval(timer);
			} else {
				elem.style.opacity = i/10;
				elem.style.filter = 'alpha(opacity=' + i + ')';
				i++;
			}

		}, interval);

		if (typeof fn == 'function')
			fn();
		
	}

// unstable
	this.fadeOut = function(id, interval, fn) {
		i = 10;
		elem = document.getElementById(id);

		timer = setInterval(function(){
			if (i <= 0) {
				clearInterval(timer);
			} else {
				elem.style.opacity = i/10;
				elem.style.filter = 'alpha(opacity=' + i + ')';
				i++;
			}

		}, interval);

		if (typeof fn == 'function')
			fn();

	}

	this.append = function(dialogBox) {
		this.addCarpet();

		obj = document.getElementsByTagName('body')[0];
				
		if(settings.drawShadows) 
			dialogBox = this.addShadows(dialogBox);
		
		this.stack.push(dialogBox.getAttribute('id'));
		
		obj.appendChild(dialogBox);
		
		boxWidth = dialogBox.offsetWidth;
		boxHeight = dialogBox.offsetHeight;
		
		dialogBox.style.left = ((this.screen.width - 200) / 2 - boxWidth / 2 + this.stack.length * 20) + 'px';
		dialogBox.style.top = ((this.screen.height - 300) / 2 - boxHeight / 2 + this.stack.length * 20) + 'px';
		
		if(settings.draggable) 
			this.draggable(dialogBox);
	}
	
	this.makeId = function() {
		return Math.floor(Math.random() * 100000);
	}
	
	this.getValue = function(id) {
		id = (!id?'dialogTextarea':id);
		return document.getElementById(id);
	}
	
	this.setTitle = function(title) {
		this.dialogBoxTitle = title;
	}
	
	this.getTitle = function() {
		return this.dialogBoxTitle;
	}
	
	this.registerPlugin = function(plugin) {
		for(i in plugin) {
			dialog[i] = plugin[i];
		}
	}
}

var error = function() {
	this.error = function(text,fn) {
		errorBox = this.getDialogBox();
		errorBox.setTitle( !dialog.getTitle() ? '' : dialog.getTitle() );
		errorBox.setMessage(text);
		errorBox.addClass('error');

		ok = this.createButton('OK',function(){
			if(typeof fn == 'function')
				fn();
		},true);
					
		errorBox.addButton(ok);
		
		this.append(errorBox);
	}
}
	

var message = function() {
	this.message = function(text,fn) {
		messageBox = this.getDialogBox();
		messageBox.setTitle('');
		messageBox.setMessage(text);
		
		ok = this.createButton('OK',function(){
			if(typeof fn == 'function') {
				fn();
			}
		},true);
		
		messageBox.addButton(ok);
		
		this.append(messageBox);
	}
}



var box = function () {
	this.box = function (title, text, fn) {
		box = this.getDialogBox();
		box.setTitle(title);
		box.setMessage(text);
		box.addClass('box');
		
		ok = this.createButton ('OK',function () {
			if (typeof fn == 'function') {
				fn();
			}
		}, true);
		
		box.addButton (ok);
		
		this.append (box);
	}
}
	
var _confirm = function() {
	this.confirm = function(text,fn,fn2) {
		confirmBox = this.getDialogBox();
		
		confirmBox.setMessage(text);
		confirmBox.addClass('confirm');
		
		ok = this.createButton('Yes',function(a) {
			if(typeof fn == 'function') {
				fn(a);
			}
		},true);
		
		cancel = this.createButton('No',function()  {
			if(typeof fn2 == 'function') {
				fn2();
			}
		},true);
		
		confirmBox.addButton(cancel);
		confirmBox.addButton(ok);
		
		this.append(confirmBox);
	}
}
	
var prompt = function() {
	this.prompt = function(text,defaultValue,fn) {
		promptBox = this.getDialogBox();
		promptBox.addTextField(defaultValue);
		promptBox.setMessage(text);
		promptBox.addClass('confirm prompt');

		ok = this.createButton('OK',function() {
			if(typeof fn == 'function') {
				fn(promptBox.dialogServiceBox.dialogTextarea.value);
			}
		},true);
		
		cancel = this.createButton('Cancel',function(){},true);
		
		promptBox.addButton(cancel);
		promptBox.addButton(ok);
		
		this.append(promptBox);
	}
}
	