
/**
 * 메인화면(/bio/index.php)의 Contents View 의 메뉴 목록을 생성한다. 
 */
function makeStartMenuButtons ()
{
	var button = new Element( 'img', {
		id: 'start-memo', 
		src: skinFolder + 'btnStartMemo.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { openMemo(); $( 'startmenu' ).toggleClass( 'display-none' ); } },
		alt: 'Memo'
	});
	button.inject( 'startmenu' );

	button = new Element( 'img', {
		id: 'start-notice', 
		src: skinFolder + 'btnStartNotice.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { new OpenWindow({ windowName: 'notice' }); } },
		alt: '공지 사항'
	});
	button.inject( 'startmenu' );
	
	button = new Element( 'img', {
		id: 'start-graph', 
		src: skinFolder + 'btnStartBarcode.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { new OpenWindow({ windowName: 'barcode' }); } },
		alt: '바이오바코드 등록현황'
	});
	button.inject( 'startmenu' );
	
	button = new Element( 'img', {
		id: 'start-maps', 
		src: skinFolder + 'btnStartMaps.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { new OpenWindow({ windowName: 'maps' }); } },
		alt: '생물다양성 분포지도'
	});
	button.inject( 'startmenu' );
	
	button = new Element( 'img', {
		id: 'start-graph', 
		src: skinFolder + 'btnStartGraph.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { new OpenWindow({ windowName: 'graph' }); } },
		alt: '생물종 지역분포 그래프'
	});
	button.inject( 'startmenu' );
	
	button = new Element( 'img', {
		id: 'start-agency', 
		src: skinFolder + 'btnStartAgency.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { new OpenWindow({ windowName: 'agency' }); } },
		alt: '생명자원 기관별 등록현황'
	});
	button.inject( 'startmenu' );
	
	button = new Element( 'img', {
		id: 'start-status', 
		src: skinFolder + 'btnStartStatus.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { new OpenWindow({ windowName: 'status' }); } },
		alt: '국내 생명자원 보유 현황'
	});
	button.inject( 'startmenu' );
	
	button = new Element( 'img', {
		id: 'start-category', 
		src: skinFolder + 'btnStartCategory.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { new OpenWindow({ windowName: 'category' }); } },
		alt: '생물 다양성 대분류 검색'
	});
	button.inject( 'startmenu' );
	
	button = new Element( 'img', {
		id: 'start-index', 
		src: skinFolder + 'btnStartIndex.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { new OpenWindow({ windowName: 'index' }); } },
		alt: '생명자원 색인별 검색'
	});
	button.inject( 'startmenu' );
	
	button = new Element( 'img', {
		id: 'start-sites', 
		src: skinFolder + 'btnStartSites.png',
		styles: { 'display': 'block', 'cursor': 'pointer' }, 
		events: { 'click': function () { new OpenWindow({ windowName: 'sites' }); } },
		alt: '생명자원 정보 사이트'
	});
	button.inject( 'startmenu' );
    
    button = new Element( 'img', {
        id: 'start-step', 
        src: skinFolder + 'btnStartStep.png',
        styles: { 'display': 'block', 'cursor': 'pointer' }, 
        events: { 
            'click': function () {
                new OpenWindow({ windowName: 'step', onComplete: function () { treeTimer = loadTree.periodical( 50 ); } });
            }
        },
        alt: '생명자원 유형별 계층검색'
    });
    button.inject( 'startmenu' );
    
    button = new Element( 'img', {
        id: 'start-ebook', 
        src: skinFolder + 'btnStartEBook.png',
        styles: { 'display': 'block', 'cursor': 'pointer' }, 
//        events: { 'click': function () { new OpenWindow({ 'windowName': 'ebook', 'isFixed': true }); } },
        events: { 'click': function () { new OpenWindow({ 'windowName': 'ebook'}); } },
        alt: 'E-Book'
    });
    button.inject( 'startmenu' );
	
}


function resizeDesktopCustomized ()
{
	$( 'desktop-background-image' ).setStyles({ 'left': preference.container.styles.width - 130, 'top': preference.container.styles.height - 210 });
	$( 'desktop-tools' ).setStyles({ 'left': preference.container.styles.width / 2 - 350, 'top': preference.container.styles.height / 2 - 200	});
}

var treeTimer;
var isAddedEvent = false;
var loadTree = function () {
	
	if ( $( 'materials-tree' ) )
	{
		if ( isAddedEvent == false )
		{
			windows[ 'step' ].handler.addEvent( 'onInitiate', function () { treeTimer = loadTree.periodical( 50 ); } );
			isAddedEvent = true;
		}
		
		var config = {
			div: 'materials-tree',
			mode: 'files',
			grid: true,
			theme: '/images/mootree.gif',
			loader: { icon:  '/images/mootree_loader.gif', text: 'Loading...', color: '#a0a0a0' },
			onSelect: function( node, state ) {
				if ( state && node.data.data ) { windows[ 'step' ].handler.getContent( node.data.resource + '|' + node.data.data + '|1' ); }
			}
		};
		
		var options = {
			text: '생명자원 (1,700,927)',
			open: true
		};
		
		new MooTreeControl( config, options ).root.load( '/xml/tree.xml' );
		//new MooTreeControl( config, options ).adopt( 'materials-list' );
		$clear( treeTimer );
	}
	
};

function selectCategory ( kingdom )
{
	var species 		= ( $( 'category-species' ).getValue() ) ? '|' + $( 'category-species' ).getValue() : '';
	var family 			= ( $( 'category-family' ).getValue() ) ? '|' + $( 'category-family' ).getValue() : '';
	var scientificName	= ( $( 'category-scientific-name' ).getValue() ) ? '|' + $( 'category-scientific-name' ).getValue() : '';

	if ( scientificName )
	{
		windows[ 'category' ].handler.getContent( kingdom + species + family + scientificName );
	}
	else
	{
		windows[ 'category' ].handler.initiateContent( kingdom + species + family + scientificName );
	}
}


var temp = new Object;

/**
 * 인덱스 페이지가 로딩될 때 검색창등의 화면구성 이벤트 발생 
 * 
 */
/**
window.addEvent( 'domready', function () {

	var logo = new Element( 'div', {
		'id': 'desktop-tools',
		'styles': {
			'display': 'block',
			'position': 'absolute',
			'left': preference.container.styles.width / 2 - 350,
			'top': preference.container.styles.height / 2 - 200,
			'width': 700,
			'padding-top': 135,
			'text-align': 'center',
			'background': 'url( /images/bio/bgDesktop.jpg ) no-repeat top left'
		},
		'events': {
			'mouseenter': function () { this.setOpacity( 1 ); },
			'mouseleave': function () {
				if ( windowsIndex.length > 1 ) { this.setOpacity( 0.5 ); }
			}
		}
	});

	// 인덱스 페이지의 카테고리(1.Introduction, 2.biocafe, 3.depository, 4.biobarcode)를 Display. 
    var stylesDesktopButtons = { 'display': 'block', 'float': 'left', 'width': 94, 'height': 51, 'cursor': 'pointer' };
	var spanButtons = new Element( 'span', { 'styles': { 'display': 'block', 'padding-left': ( window.ie6 ? 50 : 100 ) }, 'class': 'clearfix' } ).inject( logo );
	var buttons = new Array;
	buttons.push( new Element( 'a', { 'id': 'button-introduction', 'class': 'desktop-button', 'title': 'Open Introduction Page..', 'styles': stylesDesktopButtons } ).inject( spanButtons ) );
	buttons.push( new Element( 'a', { 'id': 'button-cafe', 'class': 'desktop-button', 'title': 'Open Club..', 'styles': stylesDesktopButtons } ).inject( spanButtons ) );
	buttons.push( new Element( 'a', { 'id': 'button-depository', 'class': 'desktop-button', 'title': 'Open Depository Page..', 'styles': stylesDesktopButtons } ).inject( spanButtons ) );
	buttons.push( new Element( 'a', { 'id': 'button-Barcode', 'class': 'desktop-button', 'title': 'Open BioBarcode Page..', 'styles': stylesDesktopButtons } ).inject( spanButtons ) );
	
	buttons.each( function ( button ) {
		var imageName = button.getProperty( 'id' ).replace( 'button', 'btn' ).camelCase();
		var pageName  = button.getProperty( 'id' ).replace( 'button-', '' );
		
		var extension = ( imageName == 'btnIntroduction' || imageName =='btnBarcode') ? 'jpg' : 'gif';
		
		button.setStyles({ 'background': 'url( /images/bio/' + imageName + '.' + extension + ' ) no-repeat top center', 'margin-left': 30 });
		
		button.addEvent( 'mouseenter', function () { this.setStyle( 'background', 'url( /images/bio/' + imageName + '.' + extension + ' ) no-repeat bottom center' ); } );
		button.addEvent( 'mouseleave', function () { this.setStyle( 'background', 'url( /images/bio/' + imageName + '.' + extension + ' ) no-repeat top center' ); } );
		
		if ( imageName == 'btnCafe' )
		{
            button.addEvent( 'click', function () { location.href = '/cafe/'; } );
		}
		else
		{
		    button.addEvent( 'click', function () { location.href = '/bio/' + pageName; } );
		}
	}); 
	
	var pSearch 	 = new Element( 'p', { 'styles': { 'margin': 0, 'padding': 0 } } ).inject( logo );
	var selectSearch = new Element( 'select', { 'id': 'select-search', 'styles': { 'margin-right': 4 } } ).inject( pSearch );
	new Element( 'option', { 'value': 'all' } ).setHTML( '통합 검색' ).inject( selectSearch );
	new Element( 'option', { 'value': 'informations' } ).setHTML( '생명 정보' ).inject( selectSearch );
	new Element( 'option', { 'value': 'diversity' } ).setHTML( '생물 다양성' ).inject( selectSearch );
	new Element( 'option', { 'value': 'materials' } ).setHTML( '생물 자원' ).inject( selectSearch );
	new Element( 'input', {
		'type': 'text',
		'id': 'input-keyword',
		'styles': { 'width': 200, 'height': ( window.ie6 ? 22 : 14 ), 'margin-right': 4, 'padding': 3, 'border': '1px solid #aaa', 'font-size': '0.8em' },
		'events': {
			'keypress': function ( event ) {
				var event = new Event( event );
				if ( event.key == 'enter' ) { searchNow(); }
			}
		}
	}).inject( pSearch );
	
	// 검색, 상세검색 버튼 DOM요소 추가 
    new Element( 'img', {
        'id': 'button-search',
        'src': '/images/bio/btnSearch.gif',
        'alt': 'Search now..',
        'align': 'absmiddle',
        'styles': { 'cursor': 'pointer', 'margin': '0 3px' },
        'events': { 'click': function () { searchNow(); } }
    }).inject( pSearch );

    new Element( 'img', {
        'id': 'button-detail-search',
        'src': '/images/bio/hanaNew/s_btn_search.jpg',
        'alt': '상세 검색',
        'align': 'absmiddle',
        'styles': { 'cursor': 'pointer' },
        'events': { 'click': function () { location.href = '/bio/search/detail/true/'; } }
    }).inject( pSearch );

	logo.inject( 'layout-container' );
	
	var backgroundDesktop = new Element( 'div', {
		'id': 'desktop-background-image',
		'styles': {
			'display': 'block',
			'position': 'absolute',
			'left': preference.container.styles.width - 130,
			'top': preference.container.styles.height - 210,
			'width': 130,
			'height': 155,
			'background': 'url( /images/bio/hana/bgDesktop.gif ) no-repeat top left'
		}
	}).inject( 'layout-container' );
	
	if ( hasTree )
	{
		treeTimer = loadTree.periodical( 50 );
	}
	
	
	// 페이지가 로딩될 때 ebook(Bio-catalog 매뉴얼)과 공지사항 팝업창이 열리도록 설정. 
	// 그렇지 않은 경우 주석처리하도록 한다.
	if ( !$( 'window-ebook' ) )
    {
        var ebookLeft = ( window.ie6 ? document.body.clientWidth : window.getWidth() ) - 680; 
        new OpenWindow( { windowName: 'ebook', current: { left: ebookLeft, top: 15, width: 585, height: 668 } } );
    }
	
    if ( !$( 'window-notice' ) )
    {
        new OpenWindow( { windowName: 'notice', current: { left: 15, top: 15, width: 368, height: 250 } } );
    }
    
    // 페이지가 로딩되면 시작메뉴를 보이게 한다. 그렇지 않은 경우 주석처리.
    $( 'startmenu' ).toggleClass( 'display-none' );
    
    // 자동완성기능 추가 
    buildAutoComplete();
});
*/

function searchNow ()
{
	var keyword = $( 'input-keyword' ).getValue();
	if ( !keyword )
	{
		alert( '검색어를 입력하세요.' );
		$( 'input-keyword' ).focus();
		return;
	} 
	if ( keyword.length < 2 )
	{
		alert( '검색어를 2글자 이상 입력하세요.' );
		$( 'input-keyword' ).focus();
		return;
	} 
	
	var selectValue = $( 'select-search' ).getValue();
	
	if ( selectValue != 'all' )
	{
		location.href = '/bio/search/category/' + selectValue + '/keyword/' + keyword;
		return;
	}
	
	location.href = '/bio/search/keyword/' + keyword;
}

function getStatusInformations ( flag )
{
	var resourceType = 'diversity';
	if ( 1 <= flag && flag <= 18 ) { resourceType = 'informations'; }
	else if ( 19 <= flag && flag <= 36 ) { resourceType = 'materials'; }
	
	var district = flag % 3;
	district = ( district == 1 ) ? 'metropolitan' : ( district == 2 ? 'central' : 'southern' );
	
	var field = null;
	switch ( parseInt( ( flag - 1 ) / 3 ) )
	{
		case 0:		field = 'genome';				break;
		case 1:		field = 'est';					break;
		case 2:		field = 'marker_snp';			break;
		case 3:		field = 'expressed_protein';	break;
		case 4:		field = 'analysis_tool';		break;
		case 5:		field = 'textome';				break;
		case 6:		field = 'human';				break;
		case 7:		field = 'animal';				break;
		case 8:		field = 'plant';				break;
		case 9:		field = 'microbio';				break;
		case 10:	field = 'extract';				break;
		case 11:	field = 'sale';					break;
		case 12:	field = 'animal';				break;
		case 13:	field = 'plant';				break;
		case 14:	field = 'fungi';				break;
		case 15:	field = 'protists';				break;
		case 16:	field = 'bacteria';				break;
		case 17:	field = 'virus';				break;
		case 18:	field = 'other';				break;

	}
	
	var appendix = resourceType + '|' + district + '|' + field;
	windows[ 'status' ].handler.getContent( appendix );
}

var agencyOptions = { 'page': 1 };
function getStatusAgency ( flag )
{
	var appendix = null;
	switch ( flag )
	{
        case 1:     appendix = 'animalia|hgb';      break;
        case 2:     appendix = 'animalia|asjk';     break;
        case 3:     appendix = 'animalia|enhm';     break;
        case 4:     appendix = 'animalia|gnhm';     break;
        case 5:     appendix = 'animalia|hunm';     break;
        case 6:     appendix = 'animalia|jnhm';     break;
        case 7:     appendix = 'animalia|kiee';     break;
        case 8:     appendix = 'animalia|mnhm';     break;
        case 9:     appendix = 'animalia|nhmc';     break;
        case 10:    appendix = 'animalia|nhmk';     break;
        case 11:    appendix = 'animalia|smnh';     break;

        case 12:    appendix = 'plantae|asjk';      break;
        case 13:    appendix = 'plantae|gnhm';      break;
        case 14:    appendix = 'plantae|jnhm';      break;
        case 15:    appendix = 'plantae|mmnh';      break;
        case 16:    appendix = 'plantae|mnhm';      break;
        case 17:    appendix = 'plantae|nhmc';      break;
        case 18:    appendix = 'plantae|nhmk';      break;
        case 19:    appendix = 'plantae|smnh';      break;


		case 20: 	appendix = 'fungi|efcc';		break;
		case 21: 	appendix = 'fungi|scnu';		break;
        case 22:    appendix = 'fungi|kfri';        break;
        case 23:    appendix = 'fungi|brc';         break;
        
		case 24: 	appendix = 'protozoa|brc';		break;
		case 25: 	appendix = 'protozoa|kfri';		break;
		
		case 26: 	appendix = 'bacteria|brc';		break;
		case 27: 	appendix = 'bacteria|kfri';		break;
		

        case 28:    appendix = 'non-cell|gnhm';     break;
        case 29:    appendix = 'non-cell|jhnm';     break;
        case 30:    appendix = 'non-cell|mnhm';     break;
	}

	windows[ 'agency' ].handler.getContent( appendix + '|' + agencyOptions.page );
}

function getStatusMap ( diversityType, area )
{
	var appendix = diversityType + '|' + area;
	windows[ 'maps' ].handler.getContent( appendix );
}

var indexOptions = { 'resourceType': 'bi', 'page': 1 };
function getIndexList ( flag )
{
	var appendix = indexOptions.resourceType + '|' + flag + '|' + indexOptions.page;
	windows[ 'index' ].handler.getContent( appendix );
	
	indexOptions = { 'resourceType': 'bi', 'page': 1 };
}

function setIndexType ( flag )
{
	var resourceType = ( flag == 1 ) ? 'bi' : ( flag == 2 ? 'bd' : 'bm' ); 
	indexOptions.resourceType = resourceType;
}

function viewMetadata ( index )
{
	new OpenWindow({ 'windowName': 'viewer-' + index, 'key': index, 'isFixed': true });
}

function submitNotice ()
{
	new Element( 'iframe', {
		styles: {
			'display': 'none',
			'width': 0,
			'height': 0
		},
		id: 'hidden-frame',
		name: 'hidden-frame',
		frameborder: 'no',
		scrolling: 'no'
	}).inject( 'layout-container' );
	return true;
}

function goBackNotice ()
{
	windows[ 'notice' ].handler.getContent( $( 'current_notice_id' ).getValue() );
}

function deleteNotice ( id )
{
	if ( confirm( '삭제를 하면 복구할 수 없습니다.\n\n진행하려면 확인을 눌러주세요.' ) )
	{
		var request = new Json.Remote( '/bio/notice/mode/delete', {
			onComplete: function ( result ) {
				if ( result.isDeleted == true )
				{
					windows[ 'notice' ].handler.getContent( '|list||' );
				}
				else
				{
					alert( '삭제를 하는 과정에 오류가 발생하였습니다.\n\n관리자에게 문의하여 주세요.' );
				}
			}
		}).send({ 'id': id });
	}
}

/**
 * E-book 관련 함수
 */
function goBackEbookList() {
	windows['ebook'].handler.getContent();	
}

function submitEbook() {
	var form = document.getElementById('ebook-form');
	var title = form.title.value;
	var attachment = form.attachment.value;
	var userId = form.users_id.value;
	
	if(title == null || title == "") {
		alert("제목을 입력하지 않았습니다.");
		form.title.focus();
		return false;
	}
	
	if(attachment == null || attachment == "") {
		alert("첨부파일을 입력하지 등록하지 않았습니다.");
		form.attachment.focus();
		return false;
	}
	
	if((/.+\.zip/).test(attachment.toLowerCase()) == false) {
		alert("첨부파일은 압축 파일(.zip)만 가능합니다.");
		form.attachment.focus();
		return false;
	}
	
	new Element( 'iframe', {
		styles: {
			'display': 'none',
			'width': 0,
			'height': 0
		},
		id: 'ebook-hidden-frame',
		name: 'ebook-hidden-frame',
		frameborder: 'no',
		scrolling: 'no'
	}).inject( 'layout-container' );
	
	return true;
}

function deleteEbook(id) {
	if ( confirm( '삭제를 하면 복구할 수 없습니다.\n\n진행하려면 확인을 눌러주세요.' ) ) {
		var request = new Json.Remote( '/bio/ebook/mode/delete', {
			onComplete: function ( result ) {
				if ( result.isDeleted == true ) {
					goBackEbookList();
				} else {
					alert( '삭제를 하는 과정에 오류가 발생하였습니다.\n\n관리자에게 문의하여 주세요.' );
				}
			}
		}).send({ 'id': id });
	}
}



