// IE6 Flickering bug fixing
try { doument.execCommand("BackgroundImageCache", false, true); } catch(ignored) {}

Prototype.Browser.IE6 = ( window.XMLHttpRequest ? false : true );

// auto complete input expand class
Ajax.AutocompleterTo = Class.create( Ajax.Autocompleter , {
	'onObserverEvent' : function( $super ) {
		this.changed = false;   
		this.tokenBounds = null;
		if(this.getToken().length>=this.options.minChars && !this.disabled ) {
		  this.getUpdatedChoices();
		} else {
		  this.active = false;
		  this.hide();
		}
		this.oldElementValue = this.element.value;
	}
	, 'disable' : function() { this.disabled = true; }
	, 'enable' : function() { this.disabled = false; }
} );

// multi langueage function
var trans = function() {
	var args = $A( arguments );
	var msgCategory = args.shift();
	var msgID = args.shift();
	if( !msgCategory || !msgID ) return '';

	var msgDic = _LANG_MESSAGE_FRONT[ msgCategory ];
	if( !msgDic ) return '';

	var msg = msgDic[ msgID ] || '';
	if( msg.indexOf( '#{' ) == -1 ) return msg;

	for( var i = 0 , len = args.size() , eData = {} ; i < len ; i++ ) eData[ 'ARG_' + ( i +1 ) ] = args[ i ];

	return ( new Template( msg ).evaluate( eData ) );
};
var getSetting = function( settingID ) {
	return _LANG_SETTINGS[ settingID ] || null;
}

// API request wrapper
var API = Class.create( {
	'apiFrom' : '/api/webmail/0.2/'
	, 'initialize' : function( methodName , vars , callback , options ) {
		this.options = options;
		this.callback = callback;
		if( !methodName ) {
			throw 'API Error : No Method Name';
			return;
		}
		var params = '';
		if( vars ) {
			var params = ( typeof( vars ) == 'object' ) ? $H( vars ).toQueryString() : vars
		}

		try {
			this.options = Object.extend( {
				postBody : params
				, evalJSON : false
				, onSuccess : function( transport ) {
					if( !this.callback ) return;

					try {
						var jsonData = transport.responseText.evalJSON();
					} catch( jerr ) {
						throw 'JSON error : ' + transport.responseText;
						return;
					}
					if( !jsonData.code ) {
						throw 'Response error : ' + transport.responseText;
						return;
					}
					if( !this.result ) this.response = {};
					Object.extend( this.response , jsonData );

					switch( this.code ) {
						case '9999' : location.replace( '/intro.php' ); return; break;
						case '2001' : throw 'Missing Essentials : ' + transport.responseText; return; break;
						case '2002' : throw 'Processing Error : ' + transport.responseText; return; break;
						default : this.callback( this.response ); break;
					}
				}.bind( this )
			} , ( options || {} ) );

			new Ajax.Request( this.apiFrom + methodName + '.php' + '?tId=' + ( new Date ).getTime() , this.options );

			return this;
		} catch( e ) {
			throw e;
			return;
		}
	}
} );


// UI class name space
// --------------------------------------

var UTIL = {};

UTIL.getByteStr = function( val ) {
	if( typeof( val ) == 'string' ) val = parseInt( val );

	var global = { 'comparator' : 1 , 'rule' : 1000 };
	[ '' , 'K' , 'M' , 'G' , 'T' ].each( function( prefix , i ) {
		if( i == 0 && ( val < ( this.comparator * this.rule ) ) ) {
			this.result = val + 'B';
			throw $break;
		}
		if( val < ( this.comparator * this.rule ) ) {
			this.result = ( ( ( val / this.comparator ) * 100 ).ceil() / 100 )  + prefix + 'B';
			throw $break;
		}
		this.comparator = this.comparator * this.rule;
	} , global );

	return global.result;
}
UTIL.getBoxLocalTitle = function( realName , title ) {
	return $A( [ 'INBOX' , 'Me' , 'nSent' , 'Drafts' , 'Spam' , 'Trash' ] )
		.indexOf( realName ) === -1 ? title : trans( 'mbox' , realName );
}
// --------------------------------------


// Webmail Control modules class name space
// --------------------------------------
var WCM = {};

// expand toggler : change src element status and target elements visibility
WCM.expandToggler = Class.create( {
	'initialize' : function( id , targetObj , options ) {
		this.options = Object.extend( ( this.options || {} ) , options );

		this.element = $( id );

		this.initialized = true;
		this.keyWord = null;

		if( this.element.tagName == 'IMG' ) {
			this.keyWordTarget = 'src';
		}
		else {
			this.keyWordTarget = 'className';
		}

		try {
			if( this.element[ this.keyWordTarget ].indexOf( 'plus' ) != -1 ) this.keyWord = [ 'plus' , 'minus' ];
			else if( this.element[ this.keyWordTarget ].indexOf( 'minus' ) != -1 ) this.keyWord = [ 'plus' , 'minus' ];
			else if( this.element[ this.keyWordTarget ].indexOf( 'open' ) != -1 ) this.keyWord = [ 'open' , 'close' ];
			else if( this.element[ this.keyWordTarget ].indexOf( 'close' ) != -1 ) this.keyWord = [ 'open' , 'close' ];
		} catch( err ) {
			throw 'expandToggler Control keyWord Error';
			return;
		}

		if( !this.keyWord ) {
			this.initialized = false;
			throw 'expandToggler Control initialize Error';
			return;
		}

		if( typeof( targetObj ) == 'object' ) {
			this.targetObjs = Object.isArray( targetObj ) ? targetObj : [ targetObj ];
		}
		else {
			this.targetObjs = [ $( targetObj ) ];
		}
		this.targetObjs.each( function( TO ) {
			$( TO ).writeAttribute( 'ctlId' , ( typeof( id ) == 'object' ? id.id : id ) );
		} );

		Event.observe( this.element , 'click' , this.toggle.bind( this ) );

		this.expanded = ( this.element[ this.keyWordTarget ].indexOf( this.keyWord[ 0 ] ) == -1 );

		return this;
	}
	, 'toggle' : function() {
		if( !this.initialized ) return;

		this[ ( this.expanded ? 'collapse' : 'expand' ) ]();

		return this;
	}
	, 'expand' : function() {
		if( !this.initialized ) return true;
		if( this.ing ) return true;
		if( this.expanded ) return true;

		this.targetCnt = 0;
		this.ing = true;
		this.targetObjs.each( function( TO ) {
			var src = this;
			src.targetCnt += 1;
			// when event end , control status change and rise event
			new Effect.BlindDown( TO , { 'duration' : 0.4 , 'afterFinish' : function( obj ) {
				src.targetCnt -= 1;
				if( src.targetCnt == 0 ) {
					var elmt = $( src.element );
					src.ing = false;
					elmt[ src.keyWordTarget ] = elmt[ src.keyWordTarget ].gsub( src.keyWord[ 0 ] , src.keyWord[ 1 ] );
					elmt.alt = '-';
					elmt.fire( elmt.id + ':expanded' );
					if( this.options.toggled ) {
						this.options.toggled( this.element , this.targetObjs );
					}
					else if( this.options.expanded ) {
						this.options.expanded( this.element , this.targetObjs );
					}
				}
			}.bind( this ) } );
		} , this );

		if( this.options.expanded ) this.options.expanded( this.element , this.targetObjs );

		this.expanded = true;

		return this;
	}
	, 'collapse' : function() {
		if( !this.initialized ) return true;
		if( this.ing ) return true;
		if( !this.expanded ) return true;

		this.targetCnt = 0;
		this.ing = true;
		this.targetObjs.each( function( TO ) {
			var src = this;
			src.targetCnt += 1;
			new Effect.BlindUp( TO , { 'duration' : 0.4 , 'afterFinish' : function( obj ) {
				src.targetCnt -= 1;
				if( src.targetCnt == 0 ) {
					var elmt = $( src.element );
					src.ing = false;
					elmt[ src.keyWordTarget ] = elmt[ src.keyWordTarget ].gsub( src.keyWord[ 1 ] , src.keyWord[ 0 ] );
					elmt.alt = '-';
					elmt.fire( elmt.id + ':collapsed' );
					if( this.options.toggled ) {
						this.options.toggled( this.element , this.targetObjs );
					}
					else if( this.options.collapsed ) {
						this.options.collapsed( this.element , this.targetObjs );
					}
				}
			}.bind( this ) } );
		} , this );

		if( this.options.collapsed ) this.options.collapsed( this.element , this.targetObjs );

		this.expanded = false;

		return this;
	}
} );

// auto resizable textarea
WCM.smartTextarea = Class.create( {
	'initialize' : function( id , limit ) {
		this.element = $( id );
		this.prevHeight = null;
		this.limit = limit;
		if( !this.element ) return;

		this.element.observe( 'propertychange' , this.checkIt.bindAsEventListener( this ) );
		this.element.observe( 'input' , this.checkIt.bindAsEventListener( this ) );
		this.element.observe( 'paste' , this.checkIt.bindAsEventListener( this ) );
		this.element.observe( 'keyup' , this.checkIt.bindAsEventListener( this ) );
		this.checkIt();

		return this.element;
	}
	, 'checkIt' : function( ev ) {
		if( ev && this.eventCaptured ) {
			Event.stop( ev );
			return;
		}
		this.eventCaptured = true

		var scrH = this.element.scrollHeight;

		if( !this.prevHeight ) this.prevHeight = scrH;
		if( !this.lineHeight ) this.lineHeight = scrH || this.element.offsetHeight;
		if( !this.lineHeight ) {
			this.eventCaptured = false;
			return;
		}

		if( scrH > ( this.lineHeight * this.limit ) ) {
			this.element.style.overflowY = 'auto';
			this.eventCaptured = false;
			return;
		}
		else {
			this.element.style.height = null;
			scrH = this.element.scrollHeight;
			this.element.style.height = scrH + 'px';
			this.element.style.overflowY = 'hidden';
		}
		if( this.prevHeight == scrH ) {
			this.eventCaptured = false;
			return;
		}

		this.element.style.height = ( scrH || this.lineHeight ) + 'px';
		this.prevHeight = scrH;

		this.eventCaptured = false;
		return;
	}
} );
WCM.blocker = Class.create( {
	'options' : {
		'blocked' : false
		, 'backgroundColor' : '#CCCCCC'
		, 'opacity' : 0.5
		, 'zIndex' : 1000
	}
	, 'initialize' : function( options ) {
		this.options = Object.extend( ( this.options || {} ) , options );
		this.id = '_BLOCK_' + ( ( new Date ).getTime() + '' + Math.random().toString().gsub( '.' , '' ) );
		this.blocked = this.options.blocked;
		if( this.blocked ) this.block();
	}
	, 'unblock' : function() {
		if( this.element ) {
			this.element.remove();
			this.element = null;
		}

		this.blocked = false;
		return true;
	}
	, 'block' : function() {
		if( !this.element ) {
			var viewPort = document.viewport.getDimensions();
			this.element = new Element( 'div' , { 'id' : this.id } )
				.setOpacity( this.options.opacity )
				.setStyle( {
					'position' : 'absolute'
					, 'backgroundColor' : this.options.backgroundColor || 'transparent'
					, 'width' : viewPort.width + 'px'
					, 'height' : viewPort.height + 'px'
					, 'zIndex' : this.zIndex
					, 'top' : 0
					, 'left' : 0
				} )
				.observe( window , 'scroll' , this.onScroll.bindAsEventListener( this ) );

			Element.insert( document.body , { 'top' : this.element } );
		}

		this.blocked = true;
		return true;
	}
	, 'onScroll' : function( ev ) {
		if( !this.blocked ) return false;

		var scrolls = document.viewport.getScrollOffsets();
		this.element.setStyle( { 'top' : scrolls.top + 'px' , 'left' : scrolls.left + 'px' } );

		return true;
	}
	, 'onResize' : function( ev ) {
		if( !this.blocked ) return false;

		var viewPort = document.viewport.getDimensions();
		this.element.setStyle( { 'width' : viewPort.width + 'px' , 'height' : viewPort.height + 'px' } )
	}
} );
WCM.frame = Class.create( {
	'frameOptions' : { 'opened' : false , 'destroy' : true , 'center' : false }
	, 'initialize' : function( options ) {
		this.options = Object.extend( this.frameOptions , options );

		this.frameId = '_FRAME_' + ( ( new Date ).getTime() + '' + Math.random().toString().gsub( '.' , '' ) );

		this.width = parseInt( ( this.options.width || 0 ).toString().gsub( /px|cm|pt|em/ , '' ) );
		this.height = parseInt( ( this.options.height || 0 ).toString().gsub( /px|cm|pt|em/ , '' ) );
		this.left = parseInt( ( this.options.left || 0 ).toString().gsub( /px|cm|pt|em/ , '' ) );
		this.top = parseInt( ( this.options.top || 0 ).toString().gsub( /px|cm|pt|em/ , '' ) );

		this.opened = this.options.opended;
		if( this.opened ) {
			this.open();
		}

		return true;
	}
	, 'isOpen' : function() {
		return this.opened;
	}
	, 'toggle' : function( ev ) {
		this[ ( this.isOpen() ? 'close' : 'open' ) ]( ev );
		return true;
	}
	, 'open' : function( ev ) {
		if( ev ) Event.stop( ev );

		if( !this.element ) {
			this.createFrame();
			this.getContent();
		}

		this.setSize();
		this.setPosition();

		if( !this.element ) return false;

		this.element.show();

		this.opened = true;
		return true;
	}
	, 'close' : function( ev ) {
		if( ev ) Event.stop( ev );

		if( this.options.destroy ) {
			this.destroyFrame();
		}
		else {
			this.element.hide();
		}
		
		this.opened = false;
		return true;
	}
	, 'getContent' : function() {
		this.setContent();
		return true;
	}
	, 'setContent' : function() {
		if( !this.element ) return false;

		this.element.update( this.content );
		this.setSize();
		this.setPosition();
		return true;
	}
	, 'setSize' : function() {
		if( !this.element ) return false;

		var info = this.element.getDimensions();

		if( ( this.width ) && ( info.width < this.width ) ) info.width = this.width;
		if( ( this.height ) && ( info.height < this.height ) ) info.height = this.height;

		this.width = info.width;
		this.height = info.height;

		this.element.setStyle( { 'width' : info.width + 'px' , 'height' : info.height + 'px' } );
	}
	, 'setPosition' : function() {
		if( !this.element ) return false;

		var info = this.element.cumulativeOffset();

		if( this.options.center ) {
		}
		else {
			if( this.left ) info.left = this.left;
			if( this.top ) info.top = this.top;
		}

		this.left = info.left;
		this.top = info.top;

		this.element.setStyle( { 'left' : info.left + 'px' , 'top' : info.top + 'px' } );
	}
	, 'createFrame' : function() {
		this.element = new Element( 'div' , { 'id' : this.frameId } );
		this.element.setStyle( { 'position' : 'absolute' , 'float' : 'left' } );
		Element.insert( document.body , { 'top' : this.element } );
		return true;
	}
	, 'destroyFrame' : function() {
		this.element.remove();
		this.element = null;
		return true;
	}
} );
WCM.select = Class.create( WCM.frame , {
	'selectOptions' : {
		'relativePosition' : 'BC'
		, 'innerClickHide' : true
		, 'opener' : null
		, 'onMouseClass' : null
	}
	, 'initialize' : function( $super , options ) {
		if( !$super( Object.extend( this.selectOptions , options ) ) ) return false;
		this.selectId = '_SELECT_' + this.frameId;
		if( this.options.opener ) {
			this.opener = $( this.options.opener );
			this.opener.writeAttribute( 'selectId' , this.selectId );
		}
	}
	, 'getContent' : function( $super ) {
		var cont = new Element( 'div' , { 'class' : 'selectContain' } );
		this.content = cont.insert( this.content );

		return $super();
	}
	, 'setContent' : function( $super ) {
		if( !$super() ) return false;

		if( this.options.onMouseClass ) {
			var mouseEventSet = function( obj ) {
				$( obj ).writeAttribute( {
					'outclass' : this.options.onMouseClass.out
					, 'overclass' :  this.options.onMouseClass.over
				} )
				.observe( 'mouseover' , function( evt ){
					var src = Event.element( evt );
					src.removeClassName( src.readAttribute( 'outclass' ) ).addClassName( src.readAttribute( 'overclass' ) )
				} )
				.observe( 'mouseout' , function( evt ){
					var src = Event.element( evt );
					src.removeClassName( src.readAttribute( 'overclass' ) ).addClassName( src.readAttribute( 'outclass' ) );
				} );
			};

			$$( '#' + this.frameId + ' .' + this.options.onMouseClass.out ).each( mouseEventSet , this );
			$$( '#' + this.frameId + ' .' + this.options.onMouseClass.over ).each( mouseEventSet , this );
		}
		return true;
	}
	, 'setPosition' : function() {
		if( !this.opener ) return false;
		if( !this.element ) return false;

		if( this.options.relativePosition ) {
			var wDim = this.element.getDimensions();

			var position = this.opener.cumulativeOffset();
			var dimension = this.opener.getDimensions();

			switch( this.options.relativePosition.substr( 0 , 1 ) ) {
				default:
				case 'B' : this.top = ( position[ 1 ] + dimension.height + 1 ).ceil(); break;
				case 'T' : this.top = ( position[ 1 ] - wDim.height - 1 ).ceil(); break;
			}
			switch( this.options.relativePosition.substr( 1 , 1 ) ) {
				default :
				case 'C' : this.left = ( ( position[ 0 ] + ( dimension.width /2 ) ) - ( wDim.width /2 ) ).ceil(); break;
				case 'L' : this.left = position[ 0 ]; break;
				case 'R' : this.left = position[ 0 ] - ( wDim.width - dimension.width ); break;
			}

			this.element.setStyle( { 'left' : this.left + 'px' , 'top' : this.top + 'px' } );
		}
		return true;
	}
	, 'createFrame' : function( $super ) {
		if( !$super() ) return false;

		this.element.setStyle( { 'zIndex' : 1000 } );
		this.element.writeAttribute( 'selectId' , this.selectId );

		this.resizeHandler = this.setPosition.bindAsEventListener( this );
		Event.observe( window , 'resize' , this.resizeHandler );

		if( Prototype.Browser.IE6 ) {
			this.elementHidingHandler = function( evt ) {
				if( !evt ) return false;
				Event.stop( evt );

				if(
					( evt.pageX >= this.left )
					&& ( evt.pageX <= ( this.left + this.width ) )
					&& ( evt.pageY >= this.top )
					&& ( evt.pageY <= ( this.top + this.element.offsetHeight ) )
				) return true;
				this.close();
			}.bindAsEventListener( this );

			Event.observe( this.element , 'blur' , this.elementHidingHandler );
		}
		else {
			this.hidingHandler = function( evt ) {
				if( !evt ) return false;

				if( this.options.innerClickHide ) {
					this.close();
					return true;
				}

				var src = Event.element( evt );
				var ancestors = src.ancestors();
				var srcSelectId = src.readAttribute( 'selectId' );
				if( srcSelectId == this.selectId ) return true;

				if( ancestors.find( function( AE ) {
					return ( AE.readAttribute( 'selectId' ) == this.selectId );
				}.bind( this ) ) ) return true;

				if(
					( evt.pageX >= this.left )
					&& ( evt.pageX <= ( this.left + this.width ) )
					&& ( evt.pageY >= this.top )
					&& ( evt.pageY <= ( this.top + this.height ) )
				) {
					return true;
				}

				this.close();
				return true;
			}.bindAsEventListener( this );
		}

		if( this.hidingHandler ) {
			Event.observe( document.body , 'click' , this.hidingHandler );
		}

		return true;
	}
	, 'destroyFrame' : function( $super ) {
		if( this.elementHidingHandler ) {
			Event.stopObserving( this.element , 'resize' , this.elementHidingHandler );
			this.elementHidingHandler = null;
		}
		if( this.resizeHandler ) {
			Event.stopObserving( window , 'resize' , this.resizeHandler );
			this.resizeHandler = null;
		}
		if( this.hidingHandler ) {
			Event.stopObserving( document.body , 'click' , this.hidingHandler );
			this.hidingHandler = null;
		}
		return $super();
	}
	, 'open' : function( $super , ev ) {
		if( !this.opener && ev ) {
			this.opener = Event.element( ev );
			this.opener.writeAttribute( 'selectId' , this.selectId );
		}

		var result = $super( ev );

		if( Prototype.Browser.IE ) {
			this.element.focus();
		}

		return result;
	}
	, 'close' : function( $super , ev ) {
		return $super( ev );
	}
} );
WCM.alert = function( txt ) {
	return alert( txt );
}
WCM.confirm = function( txt ) {
	return confirm( txt );
}

// --------------------------------------



// webmail components namespace
// --------------------------------------

// controling window resize event and global functions, abstract class
var Webmail = Class.create( {
	'WebmailOptions' : { 'fixedLayout' : true , 'logo' : true }
	, 'initialize' : function( options ) {
		this.options = Object.extend( this.WebmailOptions , options );
		this.appId = '_APPLICATION_' + ( ( new Date ).getTime() + '' + Math.random().toString().gsub( '.' , '' ) );

		document.observe( 'dom:loaded' , this.onDomLoaded.bind( this ) );

		return true;
	}
	, 'languageSet' : function( ev ) {	// application language change
		var lang = Event.element( ev ).readAttribute( 'lang' );
		if( _LANG == lang ) return;

		new API( 'FrontSetUserinfo' , { 'language_set' : lang } , function( result ){
			if( !result || !result.data || !result.data.result ) return;
			document.location.reload();
		} );
	}
	, 'onDomLoaded' : function() {	// when dom loaded not window loaded
		this.bodyArea = $( 'bodyArea' );
		this.contContain = $( 'contContain' );
		this.content = $( 'content' );
		this.footerArea = $( 'footerArea' );

		this.bodyArea.observe(
			'leftMenu:resized'
			, ( this.onResize || Prototype.emptyFunction ).bindAsEventListener( this )
		);
		this.bodyArea.observe(
			'leftMenu:updated'
			, ( this.onLeftMenuUpdate || Prototype.emptyFunction ).bindAsEventListener( this )
		);

		this.leftMenu = new Webmail.LeftMenu( { 'mboxData' : this.options.leftMenuData , 'fixedLayout' : this.options.fixedLayout } ).hide();

		if( this.options.fixedLayout ) {
			var html = document.getElementsByTagName( 'html' )[ 0 ];
			if( html ) html.style.overflowY = 'hidden';
			if( document.body ) document.body.style.overflowY = 'hidden';

			this.footerArea.style.position = 'absolute';
			this.contContain.style.height = '100%';
			// main doc resize
		}
		else {
			document.getElementsByTagName( 'html' )[ 0 ].style.overflowY = 'auto';
		}

		var logoCont = $( 'logoCont' );
		if( this.options.logo && logoCont ) {
			try {
			this.loadLogo();
			} catch( err ) {}
		}
		else if( logoCont ) {
			logoCont.update();
		}

		Event.observe( window , 'resize' , this.onResize.bind( this ) );
		Event.observe( window , 'load' , this.onResize.bind( this ) );

		$$( '#topAreaContent img.langChangeButton' ).each( function( Btn ) {
			Btn.observe( 'click' , this.languageSet.bindAsEventListener( this ) );
		} , this );

		this.leftMenu.show();
		this.onResize();

		return true;
	}
	, 'loadLogo' : function( ev ) {
		var logoCont = $( 'logoCont' );
		if( !logoCont ) return;

		var alturl = logoCont.readAttribute( 'alturl' );

		new API( 'WebmailGetLogoInfo' , {} , function( result ) {
			if( !result || !result.data ) return;

			var type = ( result.data.type.toLowerCase() || 'image' );
			var outerlink = false;
			var link = '/intro.php';
			if( result.data.link ) {
				outerlink = true;
				link = result.data.link;
			}

			try {
				switch( type ) {
					case 'image' :
						if( Prototype.Browser.IE ) {
							var logoImage = new Image();
							logoImage.onload = function() {
								if( logoImage.width > 185 ) {
									var nY = parseInt( Math.floor( ( 185 * logoImage.height ) / logoImage.width ) );
									logoImage.width = 185;
									logoImage.height = nY;
								}
								var cont = document.getElementById( 'logoCont' );
								cont.innerHTML = '';

								var anchor = document.createElement( 'a' );
								if( outerlink ) anchor.target = '_blank';
								anchor.href = link;
								anchor.appendChild( logoImage );
								cont.appendChild( anchor );
							};
							logoImage.id = 'logoImage';
							logoImage.src = ( alturl ? alturl : '/images/?type=logo' );
						}
						else {
							var logoImage = new Element( 'img' , { 'id' : 'logoImage' , 'src' : ( alturl ? alturl : '/images/?type=logo' ) , 'alt' : 'Logo Image' } )
								.observe( 'load' , function( ev ) {
									var img = Event.element( ev );
									if( img.width > 185 ) {
										var nY = parseInt( Math.floor( ( 185 * img.height ) / img.width ) );
										img.writeAttribute( { 'width' : 185 , 'height' : nY } );
									}
									$( 'logoCont' )
										.update( new Element( 'a' , { 'href' : link , 'target' : ( outerlink ? '_blank' : '_self' ) } )
											.update( img ) );
								} );
						}
						break;
					case 'flash' :
						if( Prototype.Browser.IE ) {
							logoCont.update( '<object'
								+ ' classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="185" height="60">'
								+ '<param name="movie" value="/images/?type=logo">'
								+ '</object>' );
						}
						else {
							logoCont
								.update( new Element( 'embed'
									, { 'id' : 'logoMovie' , 'src' : ( alturl ? alturl : '/images/?type=logo' ) , 'width' : '185px' , 'height' : '60px'  } ) );
						}
						break;
				}
			} catch( err ) {
				throw 'Logo Image Loading Error';
			}
		} );
	}
	, 'onResize' : function( ev ) {
		if( !this.footerArea ) return false;
		if( !this.bodyArea ) return false;

		try {
			if( this.options.fixedLayout ) {
				this.fixedResize( ev );
				if( this.bodyHeight + ( Prototype.Browser.IE ? 34 : 0 ) < this.leftMenu.getHeight() ) {
					this.leftMenu.overHeightHandler();
				}
			}
			else {
				this.flexableResize( ev );
			}
			this.bodyArea.fire( 'body:resize' );
		} catch( err ) {
			throw 'Resize Error';
			return false;
		}
		return true;
	}
	, 'fixedResize' : function( ev ) {
		this.bodyHeight = this.footerArea.offsetTop - this.bodyArea.offsetTop - ( Prototype.Browser.IE6 ? 34 : 0 );
		this.contentHeight = this.bodyHeight - this.content.offsetTop;

		this.bodyArea.style.height = this.bodyHeight + 'px';
		this.content.style.height = this.contentHeight + 'px';
	}
	, 'flexableResize' : function( ev ) {
		var leftMenuHeight = this.leftMenu.getHeight();

		this.contentHeight = this.content.offsetTop + this.content.scrollHeight;
		this.bodyArea.style.height = (
			( this.contentHeight < leftMenuHeight )
				? leftMenuHeight
				: this.contentHeight
		) + 'px';
	}
} );

// list control object
Webmail.List = Class.create ( {
	'initialize' : function( options ) {
		this.options = new Hash( {
			'display' : null	 // list display element

			, 'chkCtlId' : null	// list toggle control id
			, 'releaseText' : 'Release All'	// chkCtlId text in selected status
			, 'selectText' : 'Select All'	// chkCtlId text in deselected status
			, 'selectorName' : 'idxs'	// list checkbox name

			, 'deleteCtlId' : null
			, 'selectWarnText' : 'Select at least one'
			, 'deleteConfirmText' : 'Are you sure?'
			, 'listEmptyText' : 'No Search Result'
		} ).merge( options || {} ).toObject();

		this.listId = '_LIST_' + ( ( new Date ).getTime() + '' + Math.random().toString().gsub( '.' , '' ) );

		if( this.options.display ) {
			this.display = $( this.options.display );

			this.loadingImg = new Element( 'div' , { 'id' : 'loadingImage' + this.listId , 'class' : 'listLoadingImage' } )
				.setStyle( { 'height' : '66px' } )
				.update( '<br / >' );
		}

		if( typeof( this.options.onUpdated ) == 'function' ) {
			this.updateCallback = this.options.onUpdated;
		}

		this.selectorName = this.options.selectorName;
		if( this.selectorName && this.options.chkCtlId ) {
			this.chkCtl = $( this.options.chkCtlId );
			this.chkCtl.observe( 'click' , this.toggle.bindAsEventListener( this ) );
		}

		if( this.selectorName && this.options.deleteCtlId ) {
			this.deleteCtl = $( this.options.deleteCtlId );
			this.deleteCtl.observe( 'click' , this.deleteSelected.bindAsEventListener( this ) );
		}

		if( this.options.startGet ) {
			this.getData();
		}

		return true;
	}
	, 'onUpdated' : function() {
		if( this.updateCallback ) this.updateCallback( this );
		return true;
	}
	, 'getSelected' : function() {
		return $A( document.getElementsByName( this.selectorName ) )
			.findAll( function( C ) {
				return C[ ( C.type == 'checkbox' ? 'checked' : 'selected' ) ];
			} , this );
	}
	, 'deleteSelected' : function( ev ) {
		Event.stop( ev );
		var targets = this.getSelected();
		if( targets.length < 1 ) return WCM.alert( this.options.selectWarnText );
		if( !WCM.confirm( this.options.deleteConfirmText ) ) return false;

		this.deletes( targets.collect( function( C ) { return $( C ).readAttribute( 'chkKey' ) || C.value; } , this ) );

		return true;
	}
	, 'deletes' : function( ids ) {
		return true;
	}
	, 'toggle' : function( ev , status ) { // for chkbox or radio toggling
		Event.stop( ev );
		if( !this.selectorName ) return false;

		this.selected = ( status || !this.selected );
		this.selected = this.selected ? true : false;

		$A( document.getElementsByName( this.selectorName ) ).each( function( C ) {
			C[ ( C.type == 'checkbox' ? 'checked' : 'selected' ) ] = this.selected;
		} , this );
		if( this.chkCtl ) {
			this.chkCtl[ ( this.chkCtl.tagName == 'input' ? 'value' : 'innerHTML' ) ] = ( this.selected ? this.options.releaseText : this.options.selectText );
			if( this.chkCtl.href ) this.chkCtl.href = ( this.selected ? '#releaseAll' : '#selectAll' );
		}

		return true;
	}
	, 'setLoader' : function() {
		this.loadingImg = new Element( 'div' , { 'id' : 'loadingImage' + this.listId , 'class' : 'listLoadingImage' } )
			.setStyle( { 'height' : '66px' } )
			.update( '<br / >' );
		this.loaderCallId = function() {
			if( this.loaderCallId ) this.loaderCallId = null;
			if( this.dataReceived ) return;
			if( this.display ) {
				this.display.insert( { 'before' : this.loadingImg } );
			}
		}.bind( this ).delay( 1 );
	}
	, 'clearLoader' : function() {
		if( this.loaderCallId ) {
			window.clearTimeout( this.loaderCallId );
			this.loaderCallId = null;
		}
		if( this.loadingImg.parentNode ) {
			this.loadingImg.remove();
			this.loadingImg = null;
		}
	}
	, 'getData' : function() {
		if( this.display ) {
			this.display.hide();
			this.display.update();
		}

		this.dataReceived = false;
		this.setLoader();
		new API( this.method , ( this.requestParams || {} ) , this.get.bind( this ) , {
			'onException' : this.clearLoader.bind( this )
			, 'onFail' : this.clearLoader.bind( this )
		} );
        return true;
	}
	, 'get' : function( result ) {
		this.dataReceived = true;

		this.setData( result.data || [] );
		return true;
	}
	, 'setData' : function( data ) {
		this.clearLoader();
		if( this.display ) {
			this.display.show();
		}
		this.set();
		return true;
	}
	, 'set' : function() {
		this.onUpdated();
		return true;
	}
} );

Webmail.LeftMenu = Class.create( {
	'leftMenuOptions' : { 'mode' : 'mail' , 'fixedLayout' : false }
	, 'initialize' : function( options ) {
		this.options = Object.extend( this.leftMenuOptions , options );

		this.element = $( 'leftMenu' );
		this.top = $( 'leftMenuTop' );
		this.bottom = $( 'leftMenuBottom' );
		this.content = $( 'leftMenuContent' );

		this.visible = true;

		if( this.options.mboxData ) {
			this.mboxData = this.options.mboxData.data;
			this.prcMboxData();
			this.setMboxData();
		}
		else {
			this.refresh();
		}

		if( this.options.mode == 'mail' ) {
			if( !this.options.fixedLayout ) {
				var toggled = function() { this.element.fire( 'leftMenu:resized' ); }.bind( this );
			}
			else {
				var toggled = function() {};
				//this.element.observe( 'leftMenu:fixedLayoutOverHeigh' , this.overHeightHandler.bind( this ) );
			}
			this.separatedTrash = true;
			if( $( 'myBoxExpand' ) ) {
				this.myBoxExpander = new WCM.expandToggler( 'myBoxExpand' , 'leftMenuMyBoxListContain' , { 'toggled' : toggled } );
				this.separatedTrash = false;
			}
			this.addMyBoxButton = $( 'myBoxAdd' ).observe( 'click' , this.toggleAddMbox.bindAsEventListener( this ) );
			this.addMyBoxInput = false;
		}
	}
	, 'hide' : function() {
		this.visible = false;
		this.element.hide();
		return this;
	}
	, 'show' : function() {
		this.visible = true;
		this.element.show();
		return this;
	}
	, 'getHeight' : function() {
		return this.element.offsetHeight;
	}
	, 'getLong' : function() {
		return this.element.offsetTop + this.element.offsetHeight;
	}
	, 'fireOverHeight' : function() {
		this.element.fire( 'leftMenu:fixedLayoutOverHeigh' );
		return true;
	}
	, 'overHeightHandler' : function() {
		if( this.myBoxExpander ) this.myBoxExpander.collapse();
		return true;
	}
	, 'refresh' : function() {
		switch( this.options.mode ) {
			default :
			case 'mail' :
				this.getMboxData();
				break;
		}

		return true;
	}
	, 'getMboxData' : function() {
		new API( 'FrontGetEmailInfo' , {} , function( result ) {
			if( !result.data ) {
				throw 'Left Menu Refreshing Error : API';
				return;
			}
			this.mboxData = result.data;
			this.prcMboxData();
			this.setMboxData();
		}.bind( this ) );

		return true;
	}
	, 'prcMboxData' : function() {
		if( !this.mboxData ) return false;
		if( !this.mboxData.rgTotalCount || !this.mboxData.rgTotalUsage ) return false;

		var data = {
			'totalCount' : this.mboxData[ 'rgTotalCount' ][ 'nAllCnt' ]
			, 'totalNewCount' : this.mboxData[ 'rgTotalCount' ][ 'nAllNewCnt' ]
			, 'totalPercent' : this.mboxData[ 'rgTotalUsage' ][ 'nPercent' ]
			, 'totalSize' : this.mboxData[ 'rgTotalUsage' ][ 'nTotal' ]
			, 'totalUsed' : this.mboxData[ 'rgTotalUsage' ][ 'nUsed' ]
		};

		$H( { 'WMMT1001' : 'defaultMbox' , 'WMMT1002' : 'myMbox' } ).each( function( Set ) {
			var type = Set.key;
			var name = Set.value;

			data[ name + 'Index' ] = [];
			data[ name ] = {};

			$A( this.mboxData[ 'rgMailInfo' ][ type ] ).each( function( D ) {
				data[ name + 'Index' ].push( D[ 'nIdx' ] );
				data[ name ][ D[ 'nIdx' ] ] = D;
			} );
		} , this );

		this.mboxData = data;

		return true;
	}
	, 'setMboxData' : function() {
		var data = this.mboxData;
		if( !data ) return;

		var linkPage = '/user/mail/main.php';
		var settingPage = '/user/setting/setting_mbox.php';

		$H( { 'default' : 'leftMenuMbox' , 'my' : 'leftMenuMyBoxList' } ).each( function( Set ) {
			var boxType = Set.key;
			var contain = $( Set.value );
			if( !contain ) return;

			contain.update();

			var loopLen = data[ boxType + 'MboxIndex' ].size() -1;
			$R( 0 , loopLen ).each( function( i ) {
				var idx = data[ boxType + 'MboxIndex' ][ i ];
				var d = data[ boxType + 'Mbox' ][ idx ];
				var link = linkPage + '?page=list&mbox=' + d[ 'strRealName' ];

				var pos = '';
				if( boxType == 'my' ) {
					pos = ' first';
					if( i > 0 ) pos = ' middle';
					if( i == loopLen ) pos = ' last';
				}

				if( this.separatedTrash && ( [ 'Spam' ].indexOf( d[ 'strRealName' ] ) !== -1 ) ) {
					pos = pos + ' row underline';
				}

				var li;
				var sep = false;
				if( this.separatedTrash && ( [ 'Trash' ].indexOf( d[ 'strRealName' ] ) !== -1 ) ) {
					sep = true;
					li = $( 'leftMenuTrash' );
					li.childElements().each( function( obj ) {
						obj.remove();
					} );
					li.insert( new Element( 'span' , { 'class' : 'main' } ).insert( new Element( 'a', { 'href' : link } ).update( trans( 'left' , 'Trash' ) ) ) );
				}
				else {
					li = new Element( 'li' , { 'class' : pos } )
						.insert( new Element( 'span' , { 'class' : ( this.separatedTrash ? 'default' : boxType ) } )
							.insert(
								new Element( 'span' , { 'class' : 'boxName' } )
									.insert( new Element( 'a' , { 'href' : link , 'class' : 'link' } ).update( UTIL.getBoxLocalTitle( d[ 'strRealName' ] , d[ 'strNickName' ] ) ) )
							)
							.insert(
								new Element( 'span' , { 'class' : 'count' } )
									.insert( '(' )
									.insert( new Element( 'a' , { 'href' : link + '&new=new' } ).update( d[ 'nNewCnt' ] ) )
									.insert( ')' )[ ( parseInt( d[ 'nNewCnt' ] ) > 0 ? 'show' : 'hide' ) ]()
							)
						);
				}
				if( ( boxType == 'default' ) && ( i == 0 ) ) {
					li.insert(
						new Element( 'span' , { 'class' : 'mgmt' } ).insert(
							new Element( 'a' , { 'href' : settingPage } ).update( trans( 'setting_main' , 'manage' ) )
					) );
				}
				else if( [ 'Spam' , 'Trash' ].indexOf( d[ 'strRealName' ] ) !== -1 ) {
					li.insert(
						new Element( 'span' , { 'class' : 'button style4' } ).insert(
								new Element( 'a' , { 'href' : '#emptyBox' , 'idx' : idx , 'boxName' : UTIL.getBoxLocalTitle( d[ 'strRealName' ] , d[ 'strNickName' ] ) } )
									.observe( 'click' , this.emptyBox.bind( this ) )
									.update( trans( 'left' , 'emptyBox' ) )
					) );
				}
				if( !sep ) contain.insert( li );
			} , this );
		} , this );

		//$( 'leftMenuMyBoxList' ).insert( new Element( 'li' , { 'class' : 'clear' } ) );

		this.element.fire( 'leftMenu:updated' , this.mboxData );

		return true;
	}
	, 'emptyBox' : function( ev ) {
		var src = Event.element( ev );
		var mboxIdx = src.readAttribute( 'idx' );
		var mboxName = src.readAttribute( 'boxName' );

		Event.stop( ev );

		if( !WCM.confirm( trans( 'left' , 'askEmptyBox' , mboxName  ) ) ) return false;

		new API( 'FrontEmptyMbox' , { 'mbox_idx' : mboxIdx } , function( result ) {
			if( !result.data ) return WCM.alert( 'setting_js' , 'noneEmpty' );
			if( !result.data.result ) return WCM.alert( 'setting_js' , 'noneEmpty' );
			this.refresh();
		}.bind( this ) );

		return true;
	}
	, 'toggleAddMbox' : function( ev ) {
		if( this.addMyBoxInput ) {
			this.hideAddMbox( ev );
		}
		else {
			this.showAddMbox( ev );
			if( this.myBoxExpander && !this.myBoxExpander.expanded ) {
				this.myBoxExpander.expand();
			}
		}
		return true;
	}
	, 'showAddMbox' : function( ev ) {
		if( ev ) {
			Event.stop( ev );
		}
		if( this.addMyBoxButton ) {
			this.addMyBoxButton.update( trans( 'left' , 'cancelAddMbox' ) );
		}

		var cont = $( 'leftMenuMyBoxList' );
		var last = cont.down( '.last' );
		if( last ) {
			last.removeClassName( 'last' ).addClassName( 'middle' );
		}

		var input = new Element( 'input' , { 'type' : 'text' , 'id' : 'newMboxName' , 'size' : 12 , 'maxlength' : 16 } );
		var li = new Element( 'li' , { 'id' : 'boxAddRow'  } )
			.addClassName( ( last ? 'last' : 'solo' ) )
			.insert(
				new Element( 'span' , { 'class' : 'my' } )
					.insert(
						new Element( 'span' , { 'class' : 'boxName' , 'id' : 'addMboxText' } )
						.insert( input ) )
						.insert(
							new Element( 'span' , { 'class' : 'button style4' , 'id' : 'addMboxButton' } ).insert(
									new Element( 'a' , { 'href' : '#addMyBox' } ).observe( 'click' , this.addMbox.bindAsEventListener( this ) ).update( trans( 'left' , 'addMbox' ) ) )
						)
			);
		if( last ) {
			last.insert ( { 'after' : li } );
		}
		else {
			cont.insert( li );
		}
		input.focus();
		//input.observe( 'blur' , this.hideAddMbox.bindAsEventListener( this ) );
		input.observe( 'keypress' , function( ev ) { if( ev.keyCode == 13 ) this.addMbox( ev ); }.bind( this ) );
		this.addMyBoxInput = true;
		return true;
	}
	, 'hideAddMbox' : function( ev ) {
		if( ev ) {
			Event.stop( ev );
		}
		if( this.addMyBoxButton ) {
			this.addMyBoxButton.update( trans( 'left' , 'addMbox' ) );
		}

		var row = $( 'boxAddRow' );
		if( !row ) return false;

		var prev = row.previous();
		if( prev ) prev.removeClassName( 'middle' ).addClassName( 'last' );

		row.remove();
		this.addMyBoxInput = false;
		return true;
	}
	, 'addMbox' : function( ev ) {
		Event.stop( ev );

		var boxName = $( 'newMboxName' ).value;
		if( !boxName ) return WCM.alert( trans( 'error' , 'NO_BOX_NAME' ) );

		new API( 'FrontAddMbox' , { 'mbox_name' : boxName } , function( result ) {
			if( result.code == '2101' ) {
				return WCM.alert( trans( 'error' , 'BOX_NAME_EXIST' ) );
			}
			if( result.code == '2102' ) {
				return WCM.alert( trans( 'error' , 'BOX_NAME_TOO_LONG' ) );
			}
			this.hideAddMbox();
			this.refresh();
		}.bind( this ) );
	}
} );

// --------------------------------------

function installUploaderBeta() {
	var dummy = document.getElementById( 'tempActiveXObject' );
	if( dummy ) {
		dummy.outerHTML = '<object id="upObj" classid="clsid:55399877-B7F0-4a0f-BDEE-6FD1982EAB20"'
			+ ' codebase="/images/activex/WebMailFileUpDown.cab#version=1,0,0,73"'
			+ ' width="100%" height="106" onError=""></object>';
	}
}