/**
 * 투어오피스 스크립트
 *
 * 작성자 : 정 혁 (jjjhyeok@naver.com)
 * 작성일 : 2009.08.24
 * 수정일 : 2010.04.28 (할인항공 상세정보 팝업 추가 : pop_air_info())
 */

/* prototype.js를 사용하므로 prototype.js 를 기반으로 작성하면 좋음 */
/* 표준스크립트를 사용하여 크로스 브라우저(최소 IE, FF)로 작성함 */

// TourOffice_JS
if (typeof(TourOffice_JS) == 'undefined') {
	var TourOffice_JS = true;

	// 이미지 전환 함수 (20090909 정 혁)
	// 수정 : 이미지 메모 객체 추가 (20100203 정 혁)
	function image_blend(obj, img, memo, obj_memo, duration) {
		obj = (typeof(obj) == 'string') ? document.getElementById(obj) : obj;
		if (!obj || !img) return;
		if (duration == undefined) duration = '0.5';
		if (obj.filters) {
			obj.style.filter = 'blendTrans(duration=' + duration + ')';
			obj.filters.blendTrans.Stop();
			obj.filters.blendTrans.Apply();
			obj.src = img;
			obj.filters.blendTrans.Play();
		}
		else {
			obj.src = img;
		}

		// 이미지 메모 추가 (20091016 정 혁)
		obj_memo = (typeof(obj_memo) == 'string') ? document.getElementById(obj_memo) : obj_memo;
		if (!obj_memo) obj_memo = document.getElementById('gallery_memo');
		if (obj_memo) {
			obj_memo.innerHTML = memo || '';
		}
	}

	// ajax 로딩 HTML (20090910 정 혁)
	function ajax_load_html(id, html) {
		if ($(id)) {
			if (html == undefined) {
				var h = ($(id).getHeight()) ? $(id).getHeight() : 32;
				// indicator_01(small), indicator_02(big), indicator_03(snake)
				//var load_html = '<div style="text-align:center; padding:15px; height:' + h + 'px;"><img src="/image/indicator_01.gif" /></div>';
				var load_html = '<div style="text-align:center; height:' + h + 'px;"><img src="/image/indicator_01.gif" style="margin:15px 0;" /></div>';
			}
			else {
				var load_html = html;
			}

			$(id).innerHTML = load_html; 
		}
	}

	// ajax 페이지 업데이트 함수 (20090910 정 혁)
	function ajax_updater(url, id, param, async, loading) {
		if (!url) return;

		// 로딩 HTML 설정 (20100127 정 혁)
		loading = (loading == undefined) ? true : loading;

		// id 가 없을 경우
		if (!id) id = 'ajax_list';
		if (!$(id)) id = 'ajax_Proc';

		// ajax 로딩 HTML
		if (loading) ajax_load_html(id);

		// 파라메터 설정
		if (param == undefined) param = '';
		param = ($(param)) ? $(param).serialize() : param;

		// 동기화방식 설정 (true:비동기, false:동기)
		async = (async != undefined && async == false) ? false : true;

		// ajax 페이지 업데이트
		var TO_Ajax = new Ajax.Updater(id, url, {
			parameters: param,
			asynchronous: async,
			onFailure: function() { alert('데이터 로딩에 실패하였습니다.'); ajax_load_html(id, ''); },
			evalScripts: true
		});
	}

	// ajax 페이지 호출 함수 (20090910 정 혁)
	function ajax_request(url, callback, param, async) {
		if (!url) return;
	
		// id 가 없을 경우
		var id = '';

		// ajax 로딩 HTML
		ajax_load_html(id);

		// 파라메터 설정
		if (param == undefined) param = '';
		param = ($(param)) ? $(param).serialize() : ((param) ? param : {});

		// 동기화방식 설정 (true:비동기, false:동기)
		async = (async != undefined && async == false) ? false : true;

		// 콜백함수 설정
		if (typeof(callback) == 'string' && /(text|xml|json)/i.test(callback)) {
			var type = callback;
			callback = function(transport) { ajax_request_data(transport, type); }
		}

		// ajax 페이지 호출
		var TO_Ajax = new Ajax.Request(url, {
			parameters: param,
			asynchronous: async,
			onLoading: function() { ajax_load_html(id, ''); },
			onComplete: callback,
			onFailure: function() { alert('데이터 로딩에 실패하였습니다.'); ajax_load_html(id, ''); }
		});
	}

	// ajax 페이지 결과 데이터 반환 함수 (20090923 정 혁)
	function ajax_request_data(req, type) {
		if (!req) return '';

		ajax_request.data = '';
		switch (type.toLowerCase()) {
			case 'text': ajax_request.data = req.responseText; break;
			case 'xml' : ajax_request.data = req.responseXML; break;
			case 'json': ajax_request.data = req.responseJSON; break;
		}
	}

	// 월별 탭 변경 함수 (20090910 정 혁)
	function date_tab(id, d_day, sel_class, save_class) {
		// 클래스 설정
		if (!sel_class) sel_class = 'on'; // 선택 탭
		if (!save_class) save_class = ''; // 선택 되었던 탭
		
		// 객체가 있을 경우 실행
		if ($(id)) {
			// 선택탭 클래스 변경
			$(id).className = sel_class;

			// 선택탭 안의 이미지 변경
			var day_tmp = d_day.split("-");
			$$('#' + id + ' img').each(function(s, index) {
				// index = 0:년, 1:월 
				var day_str = (index == 0) ? 'year' : 'month';
				// 이미지 경로 변경시 여기 수정
				s.src = '../image/product/' + day_str + '_' + day_tmp[index] + '_on.gif';
			});

			// 저장된 아이디가 있을 경우 (=선택된 탭이 있을 경우)
			var s_id = date_tab.save_id;
			if (s_id && s_id != id) {
				// 선택탭 클래스 변경
				$(s_id).className = save_class;

				// 선택탭 안의 이미지 변경
				day_tmp = d_day.split("-");
				$$('#' + s_id + ' img').each(function(s, index) {
					s.src = s.src.replace(/_on/, '');
				});
			}

			// 선택탭 아이디 저장
			date_tab.save_id = id;
		}
	}

	// 상품정보 탭 변경 함수 (20090911 정 혁)
	function info_tab(no, g_uid, d_uid, param) {
		if (!no || !g_uid) return;
		if (!d_uid) d_uid = '';
		if (!param) param = '';

		// 탭 아이디 설정 (아이디명 변경시 여기 수정해야함)
		var id = 'tab_' + no;

		// 넘어온 no 별로 ajax 페이지 설정
		var page;
		switch (no) {
			case 1: page = "info_schedule.ajax.html";	break;	// 일정표
			case 2: page = "info_hotel.ajax.html";		break;	// 호텔정보
			case 3: page = "info_select.ajax.html";		break;	// 선택관광
			case 4: page = "info_place.ajax.html";		break;	// 관광명소
		}

		// 객체가 있을 경우 실행
		if ($(id)) {
			// 선택탭 클래스 변경
			$(id).className = 'on';

			// 선택탭 이미지 변경
			$(id).src = $(id).src.replace(/\_on/i, ''); // 초기화
			$(id).src = $(id).src.replace(/\.gif/i, '_on.gif'); // on 이미지 변경

			// 저장된 아이디가 있을 경우 (=선택된 탭이 있을 경우)
			var s_id = info_tab.save_id;
			if (s_id && s_id != id) {
				// 선택탭 클래스 변경
				$(s_id).className = '';

				// 선택탭 이미지 변경
				$(s_id).src = $(s_id).src.replace(/\_on/i, '');
			}

			// 선택탭 아이디 저장
			info_tab.save_id = id;

			// 선택된 ajax 페이지 업데이트 실행
			var url = page + '?g_uid=' + g_uid + '&d_uid=' + d_uid;
			ajax_updater(url, 'Info_Div');
		}
	}

	// 갤러리 보기 팝업 (20090917 정 혁)
	// @param type : good(상품), hotel(호텔), info(지역(관광지))
	// @param ImgType : 갤러리 이미지 타입 추가 (20091111 정혁)
	// @param Gidx : 지역정보(호텔) 코드 추가 (20091111 정혁)
	function pop_info_gallery(g_uid, type, w, h, ImgType, Gidx) {
		if (!g_uid || !type) {
			alert('갤러리가 존재하지 않습니다.');
			return;
		}

		// SLB 호출
		w = (w) ? parseInt(w) : 630;
		h = (h) ? parseInt(h) : 535;
		var url = '/product/pop_gallery.html?g_uid=' + g_uid + '&type=' + type;
		// ImgType(갤러리 이미지 타입) 추가 (20091111 정혁)
		url += '&ImgType=' + ((ImgType) ? ImgType : '');
		// Gidx(지역정보(호텔) 코드) 추가 (20091111 정혁)
		url += '&Gidx=' + ((Gidx) ? Gidx : '');
		SLB(url, 'iframe', w, h, false, false);
	}

	// 상품 일정표 인쇄하기/메일보내기 팝업 (20090918 정 혁)
	// @param type : print(인쇄하기), email(메일보내기)
	function pop_info_print(type, g_uid, d_uid, w, h) {
		if (!g_uid || !type) {
			alert('일정이 존재하지 않습니다.');
			return;
		}

		// 일정표 탭으로 무조건 변경하려면 주석 제거
		info_tab(1, g_uid, d_uid);

		// SLB 호출
		w = (w) ? parseInt(w) : 710;
		h = (h) ? parseInt(h) : 800;
		var url = '/product/pop_print.html?type=' + type + '&g_uid=' + g_uid;
		if (d_uid) url += '&d_uid=' + d_uid;
		SLB(url, 'iframe', w, h, false, true);
	}

	function pop_info_print2(type, g_uid, d_uid, w, h) {
		if (!g_uid || !type) {
			alert('일정이 존재하지 않습니다.');
			return;
		}

		// 일정표 탭으로 무조건 변경하려면 주석 제거
		info_tab(1, g_uid, d_uid);

		// SLB 호출
		w = (w) ? parseInt(w) : 710;
		h = (h) ? parseInt(h) : 800;
		var url = '/product/pop_print2.html?type=' + type + '&g_uid=' + g_uid;
		if (d_uid) url += '&d_uid=' + d_uid;
		SLB(url, 'iframe', w, h, false, true);
	}


	// 예약확인 팝업 (20100405 정 혁)
	function pop_reserv_view(res_no, w, h) {
		if (!res_no) {
			alert('예약정보가 존재하지 않습니다.');
			return;
		}

		// SLB 호출
		w = (w) ? parseInt(w) : 710;
		h = (h) ? parseInt(h) : 600;
		var url = '/mypage/pop_reserv_view.html?Res_No=' + res_no;
		SLB(url, 'iframe', w, h, false, true);
	}

	// 우편번호검색 팝업 (20090923 정 혁)
	function pop_zipcode(f, zip1, zip2, addr1, addr2, w, h) {
		if (!f || !zip1) {
			alert('우편번호 폼값이 설정되지 않았습니다.');
			return;
		}

		// SLB 호출
		w = (w) ? parseInt(w) : 420;
		h = (h) ? parseInt(h) : 200;
		var url = '/member/pop_zipcode.html?f_name=' + f;
		url += '&f_zip1=' + ((zip1) ? zip1 : '');
		url += '&f_zip2=' + ((zip2) ? zip2 : '');
		url += '&f_addr1=' + ((addr1) ? addr1 : '');
		url += '&f_addr2=' + ((addr2) ? addr2 : '');
		SLB(url, 'iframe', w, h, false, true);
	}

	// SLB iframe 띄운 상태에서 이미지 레이어로 띄우는 함수 (20090918 정 혁)
	function SLB_parent(url, type) {
		// 부모창 레이어
		var obj = parent.document.getElementById('SLB_content_parent');

		// style 설정
		var SLB_style = 'cursor:pointer; visibility:hidden; border: solid 5px #000; background-color: #FFF;';

		if (type == 'image') {
			obj.innerHTML = "<img src=" + url + " style='" + SLB_style + "' onload='layer_center(this);' />";
		}
	}

	// 여행자추가 함수 (20090921 정 혁)
	// AddPerson('product','예약가능좌석(d_seat)',document.getElementById('res_type').value);SumPrice();
	function AddPerson(obj, num, res_type) {
		var re_person1 = document.getElementById('re_person1'); // 성인
		var re_person2 = document.getElementById('re_person2'); // 소아
		var re_person3 = document.getElementById('re_person3'); // 유아
		var re_person1_num = parseInt(re_person1.value, 10); // 성인(인원)
		var re_person2_num = parseInt(re_person2.value, 10); // 소아(인원)
		var re_person3_num = parseInt(re_person3.value, 10); // 유아(인원)

		var t_person = document.getElementById('t_person'); // 총 예약인원

		// 총 예약인원
		t_person.value = re_person1_num + re_person2_num + re_person3_num;
		var len = parseInt(t_person.value, 10);

		// 호텔일 경우
		if (obj == 'hotel') {
			var chklen = re_person1_num + re_person2_num;
			firNum = 1;
		}
		// 호텔이 아닐 경우
		else {
			var chklen = re_person1_num + re_person2_num + re_person3_num;
			firNum = 0;
		}

		// 예약가능인원 체크
		if (res_type == 'A' && parseInt(len) > parseInt(num)) {
			if (confirm('예약가능인원(' + num + '명)을 초과하였습니다. 대기예약으로 진행하시겠습니까?')) {		
				document.getElementById('res_type').value = 'B';
				//document.getElementById('Res_Img').src = '/image/btn/icorn_reservation04.gif';
				AddPersonProc(len, obj);
			}
			else {
				// 초기화
				re_person1.value = 0;
				re_person2.value = 0;
				re_person3.value = 0;
				t_person.value = 0;
				document.getElementById('res_type').value = 'A';
				//document.getElementById('Res_Img').src = '/image/btn/icorn_reservation01.gif';
				AddPersonProc(firNum, obj);
			}
		}
		else {
			//document.getElementById('res_type').value=  'A';
			AddPersonProc(len, obj);
		}
	}

	// 여행자추가 페이지 업데이트 (ajax)
	function AddPersonProc(len, obj) {
		var url = '/product/AddPerson.php?len=' + len + '&type=' + obj;

		// 동기화 방식으로 업데이트 (비동기화로 업데이트하면 객체를 인식할 수 없음)
		ajax_updater(url, 'AddPersonDiv', '', false);

		// 예약자 동행 체크 함수 (해당 페이지에 해당함수 추가해서 체크함)
		if (typeof(check_same) == 'function') check_same();
	}

	// 찜하기 함수
	function wish_add(g_uid, d_uid, tar) {
		if (!tar) tar = 'hidden_frame';
		$(tar).src = '/mypage/wish_add.html?g_uid=' + g_uid + '&d_uid=' + d_uid;
	}

	// 찜하기 함수 (로그인 체크)
	function wish_add_no(url) {
		if (confirm('로그인을 하셔야 합니다.\n\n로그인 하시겠습니까?')) {
			location.href = url;
		}
	}

	// 게시판 비밀번호 체크 팝업 (20090929 정 혁)
	function pop_password(url, w, h) {
		if (!url) return;
		
		// SLB 호출
		w = (w) ? parseInt(w) : 300;
		h = (h) ? parseInt(h) : 150;
		SLB(url, 'iframe', w, h, false, false);
	}

	// 할인항공 상세정보 팝업 (20100428 정 혁)
	function pop_air_info(ti_uid, w, h) {
		if (!ti_uid) {
			alert('할인항공권 정보가 존재하지 않습니다.');
			return;
		}

		// SLB 호출
		w = (w) ? parseInt(w) : 710;
		h = (h) ? parseInt(h) : 300;
		var url = '/air/pop_air_info.html?ti_uid=' + ti_uid;
		SLB(url, 'iframe', w, h, false, true);
	}

	// 할인항공 나라변경시 도시 <option> 변경 함수 (ajax) (20100511 정 혁)
	function change_air_city(sel, tar, val) {
		if (!$(sel) || !$(tar)) {
			alert('나라 selectbox 또는 도시 selectbox 가 존재하지 않습니다.');
			return;
		}

		// 변수 설정
		sel = $(sel).value;
		tar = $(tar).id;
		if (!val) val = '';
		var url = '/air/air_city.ajax.html?sel=' + sel + '&tar=' + tar + '&val=' + val;

		// ajax 페이지 업데이트
		ajax_updater(url, '');
	}

	// 팝업 레이어 생성 함수 (20091019 정 혁)
	var popup_layer_index = 9000;
	function popup_layer(id, pidx, option) {
		if (!pidx) return
		if (!option) option = {};

		// 옵션 설정
		var t = (option.top != undefined) ? parseInt(option.top, 10) : 10;
		var l = (option.left != undefined) ? parseInt(option.left, 10) : 10;
		var center = (option.center == '1') ? true : false;

		// 팝업 레이어 생성(설정)
		//var layer = document.createElement('div');
		var layer = $(id);
		if (!layer) return;
		with (layer.style) {
			display = 'none';
			position = 'absolute';
			margin = '0px';
			top = t + 'px';
			left = l + 'px';
			textAlign = 'left';
			zIndex = popup_layer_index;
		}
		Event.observe(window, 'load', function() {
			document.body.appendChild(layer)
		});;

		// 팝업 레이어 데이터 업데이트 (ajax)
		ajax_updater('/popup/popup_layer.ajax.php?PIdx=' + pidx, id);

		// 레이어 출력
		if (center == true) layer_center(layer); // 센터
		else layer.show();

		// popup_layer_index 증가
		popup_layer_index++;
	}

	// 팝업 레이어 숨김 (20091021 정 혁)
	function close_popup(id, PIdx, expire) {
		if ($('popupCheck' + PIdx).checked == true) {
			if (expire == undefined) expire = 1
			set_cookie(id, "done", 24 * expire); // 쿠키생성(시간)
		}

		$(id).hide();
	}

	// CKEditor에 데이터를 설정 (20091007 정 혁)
	function ckeditor_setData(data, id) {
		// 에디터 instance 생성
		var editor = CKEDITOR.instances[id];

		// 에디터에 데이터 설정
		editor.setData(data);
	}

	// CKEditor의 데이터를 반환 (20091007 정 혁)
	function ckeditor_getData(id) {
		// 에디터 instance 생성
		var editor = CKEDITOR.instances[id];

		// 에디터의 데이터를 반환
		return editor.getData();
	}

	// CKEditor의 데이터를 textarea 에 설정 (ajax 사용시 필요) (20100421 정 혁)
	function ckeditor_setText(id) {
		if ($(id)) {
			$(id).value = ckeditor_getData(id);
		}
	}

	// CKEditor에 데이터를 삽입 (20091007 정 혁)
	function ckeditor_addData(data, id) {
		// 에디터 instance 생성
		var editor = CKEDITOR.instances[id];

		// 모드 체크후 데이터를 삽입
		if (editor.mode != 'wysiwyg') {
			alert('에디터 모드에서만 사용하실 수 있습니다.');
			return;
		}
		editor.insertHtml(data);
	}

	// CKEditor instance 삭제 (20100421 정 혁)
	function ckeditor_destory(editor, id) {
		if (id) {
			// 에디터 instance 생성
			editor = CKEDITOR.instances[id];
		}

		if (editor && editor != null) {
			editor.destroy();
			editor = null;
		}
	}

	// CKEditor 에 포커스 주기 (20100504 정 혁)
	function ckeditor_setFocus(id) {
		// 에디터 instance 생성
		var editor = CKEDITOR.instances[id];

		// 에디터에 포커스
		editor.focus();
	}

	// 공통 Validator 함수 (폼체크 함수)
	// @f : 폼객체(필수)
	// @lang : 언어(KO(default), EN(영어))
	function TO_Validator(f, lang) {
		// /js/Validator.js 파일에 있는 함수
		return jh_Validator(f, lang);
	}

} // TourOffice_JS 닫기
