// 리모콘이 수정되었는 지를 확인한다
var remocon_modified = false;


/* 탭 변경 */
var clickRemoconTab = function(mode) {
	// 0 : 내 실타래, 1 : 나의실
	mode = (mode == 1) ? 1 : 0;
	var diff = (mode == 1) ? 0 : 1;
	var tab = [$('#remoconTab1'), $('#remoconTab2')];
	var container = [$('#loginInfo'), $('#remoteSealMain')];
	
	container[mode].css('display', 'block');
	container[diff].css('display', 'none');
	
	tab[mode].attr('src', '/images/common/remote_btn_'+(mode+1)+'_on.gif');
	tab[diff].attr('src', '/images/common/remote_btn_'+(diff+1)+'.gif');
	
	$.post('/ajax/clickRemoconTab.php', {mode: mode, ajax: true}, null, 'json');
};

/* 작은 탭 변경(실 달기) */
var clickRemoconSmallTab = function(mode) {
	// 0 : 나의실, 1 : 정보수정
	mode = (mode == 1) ? 1 : 0;
	var diff = (mode == 1) ? 0 : 1;
	var container = [$('#remoconMySeal'), $('#remoconMinusSeal')];
	
	if(remocon_modified && !mode) {
		if(!confirm('실타래의 변경 사항을 저장하지 않으면 변경 내역이 사라집니다. 계속하시겠습니까?'))
			return;
		$('#remoteSealMain').load('/ajax/loadRemoconSeal.php', {ajax: true, init: true});
		return;
	}
	
	
	container[mode].css('display', 'block');
	container[diff].css('display', 'none');
};

var clickRemoconSmallTab2 = function(mode) {
	// 0 : 나의실, 1 : 정보수정
	mode = (mode == 1) ? 1 : 0;
	var diff = (mode == 1) ? 0 : 1;
	var container = [$('#remoconMySeal'), $('#remoconMinusSeal')];
	
	if(remocon_modified && !mode) {
		if(!confirm('실타래의 변경 사항을 저장하지 않으면 변경 내역이 사라집니다. 계속하시겠습니까?'))
			return;
		$('#remoteSealMain').load('/ajax/loadRemoconSeal.php', {ajax: true, init: true});
		return;
	}
	
	
	container[mode].css('display', 'block');
	container[diff].css('display', 'none');
};


/* 실 추가 */
var addSealToRemocon = function(seal_idx) {
	//$.ajax({ type: 'POST', url: '/ajax/addSealToRemocon.php', data: {seal_idx: seal_idx, ajax: true}, complete: addSealToRemocon_exec, dataType: 'json' });
	$.post('/ajax/addSealToRemocon.php', {seal_idx: seal_idx, ajax: true}, addSealToRemocon_exec, 'json');
};

var addSealToRemocon2 = function(seal_idx) {
	//$.ajax({ type: 'POST', url: '/ajax/addSealToRemocon.php', data: {seal_idx: seal_idx, ajax: true}, complete: addSealToRemocon_exec, dataType: 'json' });

	$.get('/ajax/getSeal.php', {idx: seal_idx, ajax: true}, addSealToRemocon_exec2, 'json');

};
var addSealToRemocon_exec = function(res) {
	if(res.error) {
		alert(res.error);
		if(res.login == 1)
			showLoginPopup();
	}
	else {
		// 성공 시 리모컨 불러오기
		loadRemoconMinusSeal();
		clickRemoconTab(1);
		clickRemoconSmallTab(1);
		
		remocon_modified = true;
		
		alert('실타래가 리모콘에 추가되었습니다. 저장하기를 눌러주세요.');
	}
};

var deleteSeal = function(seal_idx) 
{

	$.get('/ajax/delSeal.php', { idx:seal_idx, ajax:true}, function(res){$('#'+seal_idx).remove();}); 

};
var addSealToRemocon_exec2 = function(res) {
	if(res.error) {
		alert(res.error);
		if(res.login == 1)
			showLoginPopup();
	}
	else {
		// 성공 시 리모컨 불러오기
		

		 if (document.getElementById(res.seal_idx))
		 {
			alert('이미 추가된 실입니다.');
			return; 
		 }

		 var html ='<li id="'+res.seal_idx+'"><div class="sealImage"><img id="remoconSealImg_'+res.seal_idx+'" src="/images/seal/'+res.path+'" alt="'+res.seal_idx+'" width="50" height="50" style="width:50px;height:50px"  class="seal_remocon_50"></div>';
		 html +='<div class="sealButton"><a href="#delSeal" onclick="deleteSeal('+res.seal_idx+')" ><img src="/images/common/icon_round_minus.png" class="minus" alt="실 빼기" width="24" height="24"></a></div></li>';

		 $('.remoteSealItems').append(html);

	}
};
/* 실 제거 */
var removeSealFromRemoconPopup = function(event, seal_idx) {
	// 실의 이름 구하기
	var seal_name = $('#remoconSealImg_' + seal_idx).attr('alt');
	
	showPopup(event, seal_name + ' 실타래를 빼려고 합니다', "실타래를 제거하면 해당 실타래의 실수다에 글 쓰기와<br>해당 실타래에 글 감기가 제한됩니다.<br><br>제거하시겠습니까? ", function() { removeSealFromRemocon(seal_idx); } );
	return false;
};
var removeSealFromRemocon = function(seal_idx) {
	//$.ajax({ type: 'POST', url: '/ajax/removeSealFromRemocon.php', data: {seal_idx: seal_idx, ajax: true}, complete: removeSealFromRemocon_exec, dataType: 'json' });
	$.post('/ajax/removeSealFromRemocon.php', {seal_idx: seal_idx, ajax: true}, removeSealFromRemocon_exec, 'json');
};
var removeSealFromRemocon_exec = function(res) {
	if(res.error) alert(res.error);
	else {
		// 성공 시 리모컨 불러오기
		loadRemoconMinusSeal();
		remocon_modified = true;
	}
};

/* 최종적으로 리모컨 반영 */
var applyRemoconToDb = function() {
	$.post('/ajax/applyRemoconToDb.php', {ajax: true}, applyRemoconToDb_exec, 'json');
};
var applyRemoconToDb_exec = function(res) {
	if(res.error) alert(res.error);
	else {
		// 성공 시 실 수정 닫기
		remocon_modified = false;
		loadRemoconSeal();
		//clickRemoconSmallTab(0);
		alert('실타래 목록이 저장되었습니다.');
		document.location.reload();
	}
};


// 리모컨의 실 부분을 전체 불러오기
var loadRemoconSeal = function() {
	$('#remoteSealMain').load('/ajax/loadRemoconSeal.php', {ajax: true});
};

// 실 수정 부분만 불러오기
var loadRemoconMinusSeal = function() {
	$('#remoconMinusSeal').load('/ajax/loadRemoconMinusSeal.php', {ajax: true});
};



// 실 변경 사항이 있을 때 로그아웃 시 메시지를 날리게 하는 녀석
var checkLogout = function() {
	if(remocon_modified)
		return confirm('로그아웃하시면 실타래 변경 내역이 사라집니다.\n저장 후 로그아웃을 해주시기 바랍니다.\n그래도 로그아웃 하시겠습니까?');
	else
		return true;
}









// 실 순서 변경
var _SealOrder = function(select, arr) {
	this.select = select;
	this.container = arr;
	this.now_index = -1;
};
_SealOrder.prototype.change = function() {
	var option = this.select.find('option');

	for(var i=0; i<option.length; ++i)
		if(option[i].selected) this.now_index = i;
};
_SealOrder.prototype.up = function() {
	if(this.now_index <= 0) return;
	
	var target = this.container[this.now_index - 1];
	this.container[this.now_index - 1] = this.container[this.now_index];
	this.container[this.now_index] = target;
	
	--this.now_index;
	
	this.render();
};
_SealOrder.prototype.down = function() {
	if(this.now_index < 0 || this.now_index + 1 >= this.container.length) return;
	
	var target = this.container[this.now_index + 1];
	this.container[this.now_index + 1] = this.container[this.now_index];
	this.container[this.now_index] = target;
	
	++this.now_index;
	
	this.render();
};
_SealOrder.prototype.render = function() {
	this.select.empty();
	for(var i=0; i<this.container.length; ++i) {
		this.select.append('<option value="'+this.container[i].idx+'" style="padding:3px 6px">'+(i+1)+'. '+this.container[i].name+'</option>');
	}
	
	if(this.now_index > -1)
		this.select.val(this.container[this.now_index].idx);
};
_SealOrder.prototype.apply = function() {
	var result = new Array(this.container.length);
	for(var i=0; i<this.container.length; ++i) {
		result[i] = this.container[i].idx;
	}

	$.post('/ajax/applySealOrder.php', {seal_order: result.join(',')}, completedSealOrder, 'json');	
};

// 귀찮아서 -_-
var completedSealOrder = function(res) {
	if(res.error) alert(res.error);
	else {
		alert('실 순서 변경이 완료되었습니다.\n메인페이지에서 저장하기 버튼을 눌러주시면 순서 변경이 완료됩니다.');
		window.opener.document.location.reload();
		window.close();
	}
};













var _remotePages = function() {
	this.prev = null;
	this.seals = null;
	this.next = null;
	this.page = null;
	this.max_page = null;
};
_remotePages.prototype.init = function(id) {
	if(!document.getElementById(id)) return;
	var self = this;

	this.prev = $($('#'+id+' .remoteSealNavi div')[0]).find('a');
	this.next = $($('#'+id+' .remoteSealNavi div')[1]).find('a');
	this.seals = $('#'+id+' .remoteSealItems');
	var length = this.seals.find('li').length;
	
	this.page = 1;
	this.max_page = Math.ceil(length / 9);
	
	this.seals.css('top', 0);
	
	this.prev.css('display', 'none');
	if(length <= 9)
		this.next.css('display', 'none');
	
	this.prev.click( function() { self.movePrev(); this.blur(); return false; } );
	this.next.click( function() { self.moveNext(); this.blur(); return false; } );
};
_remotePages.prototype.movePrev = function() {
	if(!this.seals) return;
	// 225px
	this.next.css('display', '');
	this.seals.css('top', (this.page-2) * -165);
	
	--this.page;
	if(this.page == 1)
		this.prev.css('display', 'none');
};
_remotePages.prototype.moveNext = function() {
	if(!this.seals) return;
	// 225px
	this.prev.css('display', '');
	this.seals.css('top', this.page * -165);
	
	++this.page;
	if(this.page == this.max_page)
		this.next.css('display', 'none');
};


