/***********************************************
 * tradeKorea JavaScript Core
 */
if(window.TK == null){	
	window.TK = {
		__seq : 0,
		webPath : null, // web resource root url
		createUID : function(){
			this.__seq++;
			return this.__seq;
		}
	};
	
	TK.Ajax = {
			/**
			 * formName : form name string
			 * options
			 * {
			 * 	beforeSubmit : before submit function,
			 *  success : success function,
			 *  error : error function
			 * }
			 */
		submitForm : function(formName, option){
			if(option != null){
				if(typeof(option) == "function"){
					var successFn = option;
					option = {
						success : successFn
					};
				}
			}
			
			var formObj;

			if( formName instanceof jQuery){
				formObj = formName;
			} else if(typeof(formName) == "string") {
				var form = document.forms[formName];
				formObj = $(form);
			} else if( formName.tagName == "FORM") {
				formObj = $(formName);
			} else {
				alert("Unsupportable FORM type.");
				return;
			}

			if(formObj != null){
				formObj.ajaxSubmit(option);
			}
			else {
				alert("Unsupportable FORM type.");
				return;
			}
/*
			var form = document.forms[formName];
			formObj = $(form);

			formObj.ajaxSubmit(option);
*/
		} ,
		/**
		 * options
		 * {
		 * 	url : url,
		 *  type : "get|post",
		 *  data : dataObject,
		 *  async : true|false,
		 *  success : success function,
		 *  error : error function
		 * }
		 */
		send : function(options){
			$.ajax(options);
		} ,
		
		parseJson : function(data){
			var obj = window.eval("("+data+")");
			return obj;
		}
	};
	
	TK.Dialog = {
		_modalStack : [],
			
		/**
		 * options
		 * {
		 * 	url : url,
		 *  data : dataObject,
		 *  formName : form name // url혹은 formName 둘중에 하나만 세팅
		 *  type : "get|post",
		 *  async : true|false
		 * }
		 */
		showModal : function (options){
			var dialog = new TK.Dialog.Dlg(options);
			dialog.init(options);
			
			if(options.contents != null){
				dialog.open();
				dialog.setContents(options.contents);
			} else {
				if(options.formName != null){
					TK.Ajax.submitForm(options.formName, function(data){
						dialog.setContents(data);
					});
				} else {
					TK.Ajax.send({
						url : options.url,
						type : options.type,
						data : options.data,
						async : options.async,
						type : "post",
						success : function(data){
							dialog.setContents(data);
						}
					});
				}
				dialog.open();
			}
			
			this.pushModal(dialog);
			return dialog;
		} ,
		
		pushModal : function(dialog){
			this._modalStack.push(dialog);
		} ,
		
		popModal : function(){
			return this._modalStack.pop();
		} ,
		
		lastModal : function(){
			return this._modalStack[this._modalStack.length-1];
		} ,
		
		closeModal : function(){			
			this.popModal();			
			$.unblockUI();			
		} ,
		
		invoke : function(eventId, parameters){
			this.lastModal().invoke(eventId, parameters);
		}
	};
	
	
	/**
	 * options {
	 * 	width : "width",
	 * 	height : "height",
	 * 	left : "left",
	 * 	top : "top",
	 * 	title : "title",
	 * 	handlers : {
	 * 		"event name" : function,
	 * 		"event name2" : function2
	 * 	}
	 * }
	 * @param options
	 */
	TK.Dialog.Dlg = function(options){
		this.width = ( options.width != null ) ? options.width : 400;
		this.height = ( options.height != null ) ? options.height : 300;
		this.left = options.left;
		this.top = options.top;
		this.title = options.title;
		this.printable = options.printable;
		this._eventHandlers = options.handlers;
		this.dlgHeight = this.height + 30;
		this.zIndex = options.zIndex;
		
		if(this.zIndex == null){
			this.zIndex = "3000";
		}
		
		if(this._eventHandlers == null){
			this._eventHandlers = {};
		}
	};
	
	TK.Dialog.Dlg.prototype = {
		init : function(options){
			this.dlgId = "__dlg_" + TK.createUID();			
			this.contentsId = this.dlgId + "_conts";			
			TK.webPath = (TK.webPath == null) ? "http://web.tradekorea.com" : TK.webPath;
			
			var dlgSrc = "<div id='" + this.dlgId + "'>" 
					+ "<p class='close'><img src='" + TK.webPath + "/images/btn/close_04.gif' class='cursor'/></p>"
					+ "<h1 style='font-size:14px;color:#343434;margin-bottom:10px;margin-top:10px;'>" + this.title + "</h1>";
			
			if(this.printable){
				dlgSrc += "<p align='right' style='padding-bottom:6px'>"
					 + "<img id='__dlg_print_btn' src='" + TK.webPath + "/images/btn/btn_print_01.gif' class='cursor'/></p>" ;
				this.dlgHeight += 26;
			}
			
			// 로딩 이미지 가운데 정렬을 위한 탑 패딩값 설정
			var waitTopPad = ( options.height / 2 ) - 62;
			
			dlgSrc += "<div id='" + this.contentsId + "' style='width:" + options.width + "px;height:" + options.height + "px;'>"
					+ "<h1 style='padding-top:" + waitTopPad + "px;'><img src='" + TK.webPath + "/images/common/loading.gif' alt='loading' /></h1></div>"
					+ "</div>" ;
			
			
			this.dlgFrame = $(dlgSrc);
			
			var closePara = $(".close",this.dlgFrame).css({
				position:"relative",
				marginBottom:"-20px",
				textAlign:"right"
			});
			
			var dlg = this;
			
			$("img",closePara).click(function(){				
				TK.Dialog.closeModal();
			});
			
			if(this.printable){
				var contentsId = this.contentsId;
				$("#__dlg_print_btn",this.dlgFrame).click(function(){
					TK.Printer.print($("#" + contentsId));
				});
			}
		},
		
		invoke : function(eventId, parameters){
			var handler = this._eventHandlers[eventId];
			if(handler != null){
				handler(parameters);
			}
		},
		
		dispose : function(){
			this._eventHandlers = null;
		},
		
		open : function(){
			var dlg = this;
			$.blockUI({
				message : this.dlgFrame,
				css : { width:this.width, 
					height:this.dlgHeight, 
					top:  ($(window).height() - this.height) /2 + 'px',                 
					left: ($(window).width() - this.width) /2 + 'px',
					padding:"6px",
					border:"4px solid #77a8db",
					cursor:"default" ,
					"z-index":this.zIndex
					},
				overlayCSS : {opacity:"0.2"},
				fadeIn:200,
				centerY : true,
				centerX : true,
				onUnblock : function(){
					dlg.dispose();
				}
			});
		},
		
		// 내용 박스 아이디 정보 반환
		getContentPane : function(){
			return $("#"+ this.contentsId);
		},
		
		// 진행중 이미지 출력 (지정된 박스내에 출력)
		showProgressBox : function( boxId ) {
			$( boxId ).html(
				"<p style='margin-top:" + ( $(boxId).height() / 2 - 31) + ";margin-left:" + ( $(boxId).width() / 2 - 31) + ";'>"
				+ "<img src='" + TK.webPath + "/images/common/loading.gif' alt='loading' />"
				+ "</p>"
			);
		},
		
		// 내용 출력
		setContents : function(data){
			var contsPane = $("#"+ this.contentsId);
			contsPane.css({overflow:"auto", 
				width:this.width, 
				height:this.height,
				position:"static",
				textAlign:"left"
				});
			
			if(typeof(data) == "string"){
				contsPane.html(data);
			} else if(data instanceof jQuery){
				contsPane.html("");
				contsPane.append(data.html());
			} else {
				contsPane.append($(data));
			}
		}
	};
	
	TK.Printer = {
		print : function (contents){
			var win = window.open();
			var doc = win.document;
			
			var htmlSrc = "<html><head>";
			
			for(var i = document.styleSheets.length-1; i>=0; i--){ 
				var style = document.styleSheets[i];
				htmlSrc += "<link rel='stylesheet' type='text/css' href='" 
						+ style.href
						+ "'/>";
			}
			
			htmlSrc += "</head><body>";
			htmlSrc += contents.html();
			htmlSrc += "</body></html>";
			
			doc.write(htmlSrc);
			
			win.focus();
			win.print();
		}
	};
	
	TK.Image = {
		seeInModal : function (contents) {					
			var newImg=new Image();
			var imgUrl = contents;
			newImg.src = imgUrl;
			var modalWidth;
			var modalHeight;
			var imageLayerHtml;
			var baseWidth = $( window ).width() - 200;
			var baseHeight = $( window ).height() - 200;
			if(newImg.width > 0 && newImg.height > 0) {
				modalWidth = ( newImg.width < baseWidth ) ? newImg.width : baseWidth;
				modalHeight = ( newImg.height < baseHeight ) ? newImg.height : baseHeight; 
				
				if(modalWidth < 200) {
					modalWidth = 200;
					modalHeight = 200 * newImg.height / newImg.width;
					topMargin = modalHeight / 4 + 5; 
				} else {
					topMargin = 5; 
				}
				
				modalWidth = modalWidth + 10; 
				modalHeight = modalHeight + 10; 
		
				imageLayerHtml = '<div style="text-align:center;vertical-align:middle;margin-top:' + topMargin + 'px;">'
								+ '<a href="javascript:TK.Dialog.closeModal();">'
								+ '<img src="' + newImg.src + '" style="border:1px #ccc solid;" alt=""/>'
								+ '</a>'
								+ '</div>';
		
				var dlg = TK.Dialog.showModal({
					contents : imageLayerHtml,
					title : "See Original Image",
					width: modalWidth,
					height: modalHeight
				});			
			} else {
				alert("Not Enough Image Info.");				
			}
		},
		
		//======================================================================================
		//DESCRIPTION	:	이미지를 지정된 폭과 높이의 배율에 맞게 리사이즈한다..
		// - imageObj	:	이미지 객체
		// - width		:	최대폭 
		// - height		:	최대높이 
		//Return Value	: none
		//======================================================================================
		setImageSize : function( imageObj, maxWidth, maxHeight ) {
			var topMargin = 0;
			maxWidth = (isNaN(maxWidth)) ? maxWidth : parseInt(maxWidth, 10);
			maxHeight = (isNaN(maxHeight)) ? maxHeight : parseInt(maxHeight, 10);
			
			var newImg = new Image();
			newImg.src = $( imageObj ).attr("src");

			// 원본 이미지 사이즈 저장
			var width = $( newImg ).attr("width");
			var height = $( newImg ).attr("height");
			
			// 가로 길이가 최대 가로 사이즈보다 큰경우  
			if( width > maxWidth ||  height > maxHeight ) {
				resizeWidth = maxWidth;
				resizeHeight = Math.round((height * resizeWidth) / width);
				topMargin = Math.round((maxHeight - resizeHeight) / 2);
				
				// 재조정된 높이가 제한 높이보다 큰경우.
				if( resizeHeight > maxHeight ) {
					resizeWidth = Math.round( width * ( maxHeight / height ));
					resizeHeight = maxHeight;
					topMargin = 0;
				}
			} else {	// 최대사이즈보다 작으면 원본 그대로
				resizeWidth = width;
				resizeHeight = height;
				topMargin = Math.round((maxHeight - resizeHeight) / 2);
			}
			
			$( imageObj ).attr("width", resizeWidth );
			$( imageObj ).attr("height", resizeHeight);
			$( imageObj ).css("margin-top", topMargin);
		},
		
		setNoImage : function( imageObj, width, height ) {
			$( imageObj ).attr( "src", TK.webPath + "/images/no_image/" + width + "_" + height + ".gif" );
		},
		
		imageDetail : function( obj ) {
			TK.Image.seeInModal( $( "img", obj).attr( "src" ) );
		}
	};
	
	TK.EditToolTip = {
		setTip : function( frm, element, type, comment, div ) {
			var form = $("form[name=" + frm + "]");
			var tipSpace = (div == null) ? "#wrapper" : div;
			
			// focus event bind
			$( type + "[name=" + element + "]", $(frm) ).bind(
					"focus",
					function(){
						var $this = $(this);
						TK.EditToolTip.showToolTipBox( $this, comment, tipSpace );
					}
			);
			
			// blur event bind
			$( type + "[name=" + element + "]", $(frm) ).bind(
					"blur",
					function(){
						var $this = $(this);
						TK.EditToolTip.hideToolTipBox( $this );
					}
			);
		},
		
		// toolTip display
		showToolTipBox : function( obj, comment, div ) {
			var $obj = $(obj);
			var html = "";
			var div_id = "tooptip_" + $obj.attr("name");

			$( "#" + div_id ).remove();			
			
			html += '<div id="' + div_id + '" class="des_foot">';
			html += '	<div class="des_top">';
			html += '		<div class="des_cont">' + comment + '</div>';
			html += '	</div>';
			html += '</div>';
			
			$(html).appendTo( $( div ) );
			
			var position = $obj.position();
			var top = position.top - $( "#" + div_id ).height() - 2;
			var left = position.left;

			$( "#" + div_id ).css("z-index", "105");
			$( "#" + div_id ).css("position", "absolute");
			$( "#" + div_id ).css("top", top);
			$( "#" + div_id ).css("left", left);

			$( "#" + div_id ).show(200);			
		},
		
		// toolTip hidden
		hideToolTipBox : function( obj ) {
			var $obj = $(obj);
			var div_id = "tooptip_" + $obj.attr("name");
			
			$( "#" + div_id ).hide();
			$( "#" + div_id ).remove();			
		}
	};
	
	TK.Timer = {
		startTime : new Date().getTime(),
		interval : 10 * 60 * 1000, 
		call : function(){
			var timer = this;
			$.ajax({
				url : timer.contextPath + "/session.jsp" ,
				success : function(data){
					window.status = new Date().getTime() - timer.startTime;
					timer.setTimeout();
				}
			});
		} ,
		start : function(contextPath){
			this.contextPath = contextPath;
			this.setTimeout();
		}  ,
		setTimeout : function(){
			var timer = this;
			window.setTimeout(function(){ timer.call(); } , timer.interval );
		} 
	}

	TK.Notice = {
		show : function(imgUrl){
			$.blockUI({
				message : "<img src='" + imgUrl + "' onclick='TK.Notice.close();'>",
				css : {
					padding:"0px",
					border:"0px",
					cursor:"hand",
					backgroundColor :"#76A8DB" 
					},
				overlayCSS : {opacity:"0.2" },
				fadeIn:200,
				fadeOut:200,
				centerY : true,
				centerX : true
			});
		} ,
		close : function(){
			$.unblockUI();
		}
	}
	
	TK.HtmlEditor = {

		init : function(contentsId) {
			this.initFull(contentsId);
		} ,
		
		initSimple : function(contentsId) {
			this.initImpl(contentsId, "simple");
		} ,

		initFull : function(contentsId) {
			this.initImpl(
					contentsId
					, "advanced"
					, "code,|,undo,redo,|,fontselect,fontsizeselect,|,bold,italic,underline,|,bullist,numlist,|,forecolor,backcolor"
					, "justifyleft,justifycenter,justifyright,justifyfull,|,tablecontrols,|,image"
			);
		} ,
		
		initImpl : function(contentsId , theme, buttonSet1, buttonSet2 ) {
			if(tinyMCE == null){
				alert("Html Editor is not set.");
				return;
			}
			tinyMCE.init({
				mode : "exact",
				elements : contentsId,
				/*
				 * 이하는 테마 설정 및 플러그인에 대한 설정임.
				 * 모든 설정을 다 포함하고 있어서 복잡함.
				 */
				theme : theme,
				forced_root_block : false ,
				// Plugins
				plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
				// Theme options
				theme_advanced_buttons1 : buttonSet1,
				theme_advanced_buttons2 : buttonSet2,
				theme_advanced_buttons3 : "",
				theme_advanced_buttons4 : "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_resizing : true,
				init_instance_callback : "TK.HtmlEditor.setTabIndex"
			});
		} ,
		
		setTabIndex : function () {
			$(".mceToolbarContainer > *").attr("tabIndex", "-1");
		} ,
		
		showPhotoBox : function(formObj) {
			// Modal window 출력요청
			TK.Dialog.showModal({ 
				url : "/mytradekorea/myTrade/myPhoto/myPhotoAjax.mvc",
				data : {
					viewName	: "src",
					insertName	: "src",
					idx			: 0,
					page		: 1,
					monthYear	: ""
				},
				title : "My Photo List",
				width:765,
				height:375,
				zIndex : 5000000,
				handlers : {
					"viewPhotoListPageMove" : function(params){	// 이미지 리스트 페이지 이동
						// 페이지 정보가 없는 경우 1로 설정
						page = (!params.page) ? 1 : parseInt(params.page, 10);
		
						// Ajax 요청
						TK.Ajax.send({ 
							url : "/mytradekorea/myTrade/myPhoto/myPhotoListAjax.mvc",
							type : "post",
							data : {
								monthYear	: params.monthYear,
								viewName	: params.viewName,
								insertName	: params.insertName,
								idx			: params.idx,
								page		: params.page
							},
							success : function(data, respText){
								// 이미지 박스내 html Code 삽입
								$( "#myPhotoList" ).html(data);
							} , 
							error : function(data,respText){
								alert("TK.Ajax.send error :: " + data);
							}
						});
					},
					"setMyPhotoInfo" : function(params){	// 해당 이미지 정보 삽입
						formObj.src.value = TK.webPath + params.fileSysNm;
						// 정보 삽입후 해당 Model Window close
						TK.Dialog.closeModal();
					}
				}
			});			
		} ,
		
		checkInsert : function( id, lang, message, form_name ) {
			tinyMCE.triggerSave();
			
			var obj = (form_name != null) ? $( "#" + id, "form[name=" + form_name + "]" ) : $( "#" + id );
			var value = $(obj).val();
			message = (lang == "en") ? "Please Enter the " + message : message;

			if( $.trim( value ).length < 1) {
				alert( message );
				$( obj ).focus();
				return false;
			} else {
				return true;
			}
		}
	}
};



