


var i, $img, imgWidth, imgHeight, measure, unit, posX, posY, filepath, $activeGridX, $activeGridY;
var phase = 0; //Izgara kontrol adımı (0: başlangıç noktası, 1: bitiş noktası, 2: düzenle)
var cnt = 0;
measure = 'drag';

rulerInit();

function rulerInit() {
	$('#workspace-ruler > div > div > div').remove(); 

	$img = $('#workspace-img-wrap');
	imgWidth = $img.width() + 1;
	imgHeight = $img.height() + 1;
	
	$('#workspace-ruler').css({ width: imgWidth, height: imgHeight }); 
	$('#gnb').css({ maxWidth: imgWidth + $('#workspace-ruler-y').width() }); 
	
	unit = 'px';
		
	for (i=0;i<imgWidth/10;i++)
		$('#workspace-ruler-x-1').append('<div class="workspace-ruler-x-1-el"></div>');	
	for (i=0;i<imgWidth/50;i++)
		$('#workspace-ruler-x-2').append('<div class="workspace-ruler-x-2-el">'+i*50+'px</div>');
	for (i=0;i<imgHeight/10;i++)
		$('#workspace-ruler-y-1').append('<div class="workspace-ruler-y-1-el"></div>');	
	for (i=0;i<imgHeight/50;i++)
		$('#workspace-ruler-y-2').append('<div class="workspace-ruler-y-2-el">'+i*50+'px</div>');
		
}

$(document).on('click', '.pop-btn-cancel, #dim', popClose).on('keydown', keyEvents); 

function generateCode() {
	popOpen($('#pop-code'));
	
	var imgsrc = ($('#workspace-img').attr('src').slice(0, 4) == 'blob') ? '<em>filepath</em>' : $('#workspace-img').attr('src'); // 이미지 소스
	var gcAloop = ''; // A 태그 마크업 루프
	var gcMloop = ''; // 이미지맵 마크업 루프
	var gcAlert = '<em class="pop-content-alert">&#9888; You have to replace each red text with a value.</em>';

	for (i=0;i<cnt;i++) {
		// A 태그 형태 좌표 및 크기
		var top = (unit == 'px') ? $('#grid-box-' + i).position().top + 1 : ($('#grid-box-' + i).position().top / (imgHeight - 2) * 100).toFixed(2);
		var left = (unit == 'px') ? $('#grid-box-' + i).position().left + 1 : ($('#grid-box-' + i).position().left / (imgWidth - 2) * 100).toFixed(2);
		var width = (unit == 'px') ? $('#grid-box-' + i).width() : ($('#grid-box-' + i).width() / imgWidth * 100).toFixed(2);
		var height = (unit == 'px') ? $('#grid-box-' + i).height() : ($('#grid-box-' + i).height() / imgHeight * 100).toFixed(2);
		
		// 이미지맵 형태 좌표 (px만 가능)
		var startCoordX = parseInt($('#grid-box-' + i).position().left + 1);
		var startCoordY = parseInt($('#grid-box-' + i).position().top + 1);
		var endCoordX = parseInt(startCoordX + $('#grid-box-' + i).width() + 1); // +1은 실보정 값
		var endCoordY = parseInt(startCoordY + $('#grid-box-' + i).height() + 1);
		
		var link = (mapEl[i][2]) ? mapEl[i][2] : '<em>link</em>';
		var target = (mapEl[i][3]) ? mapEl[i][3] : '<em>target</em>';
		
		gcAloop += '&nbsp;&nbsp;&nbsp;&nbsp;&lt;a href="' + link + '" style="position:absolute; top:' + top + unit + '; left:' + left + unit + '; width:' + width + unit + '; height:' + height + unit + '; display:block; background:url(about:blank);"&gt;&lt;a&gt;' + '<br>';
		gcMloop += '&nbsp;&nbsp;&nbsp;&nbsp;&lt;area shape="rect" coords="' + startCoordX + ', ' + startCoordY + ', ' + endCoordX + ', ' + endCoordY + '" href="' + link + '" target="' + target + '"&gt;' + '<br>';
	}
	
	var gcA = gcAlert + '&lt;div style="position:relative"&gt;' + '<br>' + '&nbsp;&nbsp;&nbsp;&nbsp;&lt;img src="' + imgsrc + '"&gt;' + '<br>' + gcAloop + '&lt;/div&gt;';
	$('#pop-codegen-a .pop-content p').html(gcA); // 생성된 마크업 출력
	
	var gcM = gcAlert + '&lt;img src="' + imgsrc + '" usemap="#<em>mapname</em>"&gt;' + '<br>' + '&lt;map name="<em>mapname</em>"&gt;' + '<br>' + gcMloop + '&lt;/map&gt;';
	$('#pop-codegen-im .pop-content p').html(gcM); // 생성된 마크업 출력
}

function popOpen($popup) {
	$('#dim').show().css({ opacity: 0.5 }); // 딤 스크린 표시
	
	$popup.show().css({ top: $(window).height() / 2 - $popup.height() / 2, left: $(window).width() / 2 - $popup.width() / 2 });	
	$popup.find('input').eq(0).focus(); // 첫 번째 인풋 자동 포커싱
}

function popClose() {
	$('#dim, .pop').hide();
	$('.pop-content').each(function() { $(this).find('input[type="text"], input[type="file"]').val(''); }); // 인풋 초기화
}



var pointStart = new Array();
var pointEnd = new Array();
var mapEl = new Array(); 

$(document).on('mousemove', '#workspace-img-wrap', drawGrid).on('mousedown mouseup', '#workspace-img-wrap', setGrid).on('mouseleave', '#workspace-img-wrap', resetGrid);
$(document).on('mouseenter mouseleave', '.grid-box', overMapElView).on('mouseup', '.grid-box', clickMapElView).on('click', '.grid-box-close', removeMapElView);
$(document).on('click', '.grid-box-link', addLinkToMapEl).on('click', '#pop-addlink .pop-btn-confirm', setLinkToMapEl);

$(document).on('mousedown', '#workspace-ruler', function() { return false; })

function drawGrid(e) {
    if (phase == 1) $img.addClass('_phase1');
    else {
        if ($img.hasClass('_phase1'))
        $img.removeClass('_phase1');
    }
	$activeGridX = (phase == 0) ? $('#grid-x1') : $('#grid-x2');
	$activeGridY = (phase == 0) ? $('#grid-y1') : $('#grid-y2');

	$activeGridX.css({ top: e.pageY - $('#gnb').height() - $('#workspace-ruler-x').height() - 1 });
	$activeGridY.css({ left: e.pageX - $('#workspace-ruler-y').width() - 1 });
	
	$('#grid-coords').css({
		top: (e.pageY < $('#gnb').height() + $('#workspace-ruler-x').height() + imgHeight - $('#grid-coords').outerHeight() - 5 ) ? e.pageY - $('#gnb').height() - $('#workspace-ruler-x').height() + 5 : e.pageY - $('#gnb').height() - $('#workspace-ruler-x').height() - $('#grid-coords').outerHeight() - 6,
		left: (e.pageX < $('#workspace-ruler-y').width() + imgWidth - $('#grid-coords').outerWidth() - 5) ? e.pageX - $('#workspace-ruler-y').width() + 5 : e.pageX - $('#workspace-ruler-y').width() - $('#grid-coords').outerWidth() - 6
	});
		
	posX = (unit == 'px') ? $activeGridY.position().left + 1 : (($activeGridY.position().left) / (imgWidth - 2) * 100).toFixed(2);
	posY = (unit == 'px') ? $activeGridX.position().top + 1 : (($activeGridX.position().top) / (imgHeight - 2) * 100).toFixed(2);

	$('#grid-coords').text(posX + unit + ', ' + posY + unit);
}

function setGrid(e) {
	if (!$img.hasClass('_overmap')) {
		$('.grid-box').removeClass('_active');
		
		if (e.type == 'mousedown') setGridPoint(pointStart);
		else if (phase == 0) return false;
		else setGridPoint(pointEnd);

		
		var limX = (unit == 'px') ? Math.abs(pointStart[0] - pointEnd[0]) : Math.abs(pixelize(pointStart[0], 'x') - pixelize(pointEnd[0], 'x'));
		var limY = (unit == 'px') ? Math.abs(pointStart[1] - pointEnd[1]) : Math.abs(pixelize(pointStart[1], 'y') - pixelize(pointEnd[1], 'y'));
		
		if (limX < 20 || limY < 20) return false; // 가로 또는 세로가 20px 미만일 때 맵 엘리먼트 생성 금지
		
		if (phase == 0) {
            cnt++;
            mapEl.push([pointStart.slice(0), pointEnd.slice(0)]); // 3차원 배열 저장 (Call by value)
            
			addMapElView(cnt - 1);
		}
        console.log(mapEl);
		event.preventDefault();
	} else return;
}

function pixelize(val, axis) {
	var valOut = (axis == 'x') ? imgWidth * val / 100 : imgHeight * val / 100;
	return valOut;
}

function setGridPoint(point) {
	point[0] = posX; // X축 좌표값 저장
	point[1] = posY; // Y축 좌표값 저장
	
	phase = (phase == 0) ? 1 : 0; // 단계 토글
}

function resetGrid() {
	phase = 0;
	$img.removeClass('_phase1');
	$('#grid-x1').css({ top: posY - 1 });
	$('#grid-y1').css({ left: posX - 1 });
}

function addMapElView(index) {
	$img.append('<div class="grid-box" data-id="0" id="grid-box-' + index + '"><span class="grid-box-cnt">' + (index + 1) + '</span><span class="grid-box-close">&times;</span><span class="grid-box-link">METİN EKLE</span></div>');
	
	$('#grid-box-' + index).css({
		width: (unit == 'px') ? Math.abs(mapEl[index][1][0] - mapEl[index][0][0]) : Math.abs(mapEl[index][1][0] - mapEl[index][0][0]) / 100 * imgWidth,
		height: (unit == 'px') ? Math.abs(mapEl[index][1][1] - mapEl[index][0][1]) : Math.abs(mapEl[index][1][1] - mapEl[index][0][1]) / 100 * imgHeight,
		top: (unit == 'px') ? Math.min(mapEl[index][0][1], mapEl[index][1][1]) : Math.min(mapEl[index][0][1], mapEl[index][1][1]) / 100 * imgHeight,
		left: (unit == 'px') ? Math.min(mapEl[index][0][0], mapEl[index][1][0]) : Math.min(mapEl[index][0][0], mapEl[index][1][0]) / 100 * imgWidth
	});
	
	if ($('#grid-box-' + index).width() < 50 || $('#grid-box-' + index).height() < 50) $('#grid-box-' + index).addClass('_errorhash');

    if (mapEl[index][2]) {
		$('#grid-box-' + index).addClass('_added');
		$('#grid-box-' + index).find('.grid-box-link').text('DÜZENLE');
	}
}

function overMapElView(e) {
	if (e.type == 'mouseenter' && phase == 0) $img.addClass('_overmap');
	else $img.removeClass('_overmap');
}

function clickMapElView() {
	if ($(this).hasClass('_moving')) {
		$('.grid-box').removeClass('_active');
		$(this).removeClass('_moving');
		$(this).addClass('_active');
		recalcElMap();
	}
}

function removeMapElView() {
	if ($('.grid-box._active').length > 0) {
		var delIndex = $('.grid-box._active').attr('id').split('-')[2];

		$('.grid-box._active').remove();
		$img.removeClass('_overmap');
		cnt--;
		mapEl.splice(delIndex, 1);
		$('.grid-box').remove();
			
		for (i=0;i<cnt;i++) {
			addMapElView(i);
		}
	}
}

function addLinkToMapEl() {
	popOpen($('#pop-addlink'));
	
    if ($('.grid-box._active').hasClass('_added')) {
        
		var targetIndex = $('.grid-box._active').attr('id').split('-')[2];
        var urlink = mapEl[targetIndex][2];

        $('#pop-addlink .pop-title').text('METİN DÜZENLE');
		$('#pop-addlink .pop-btn-confirm').text('GÜNCELLE');
		$('#pop-addlink-input').val(urlink);
	} else {
		$('#pop-addlink .pop-title').text('METİN EKLE');
		$('#pop-addlink .pop-btn-confirm').text('EKLE');
	}
    console.log(mapEl);
	return false;
}

function setLinkToMapEl() {
	var addIndex = $('.grid-box._active').attr('id').split('-')[2];
	
	if ($('#pop-addlink-input').val()) {		
		mapEl[addIndex][2] = $('#pop-addlink-input').val();
	}
	else {
		alert('Lütfen içerik girin');
		return false;
	}
	$('.grid-box._active').addClass('_added');
	$('.grid-box._active .grid-box-link').text('DÜZENLE');
	popClose();
}

function keyEvents(e) {
	switch (e.keyCode) {
		case 27: // ESC 키
			if ($('#dim').css('display') == 'block') popClose(); 
			else if (phase == 1) resetGrid(); 
			break;
		case 46: // DEL 키
			removeMapElView();
			break;
	}
}

$(document).on('click', '.pop-btn-copy', codeView).on('click', '.pop-btn-cancel._back', codeViewBack);

function codeView() {
	popClose();
	if ($(this).attr('id') == 'pop-btn-copy-a') popOpen($('#pop-codegen-a'));
	else popOpen($('#pop-codegen-im'));
}

function codeViewBack() {
	popOpen($('#pop-code'));
}

var beforePosX, beforePosY, beforeElPosX, beforeElPosY;

$(document).on('mousedown', '.grid-box', boxMoveStart).on('mousemove mouseleave', '.grid-box._moving', boxMove); // 맵 엘리먼트 이동

function boxMoveStart(e) {
	if ($(e.target)[0] != $(this).find('.grid-box-link')[0] && $(e.target)[0] != $(this).find('.grid-box-close')[0] && $(e.target)[0] != $(this).find('.grid-box-resize')[0]) {
		$('.grid-box').removeClass('_active');
		$(this).addClass('_moving');
		beforeElPosX = $(this).position().left;
		beforeElPosY = $(this).position().top;
		beforeClickPosX = e.pageX - $('#workspace-ruler-y').outerWidth() - $(this).position().left;
		beforeClickPosY = e.pageY - $('#workspace-ruler-x').outerHeight() - $('#gnb').outerHeight() - $(this).position().top;
	}	
}

function boxMove(e) {
	if (e.type == 'mousemove') {
		var mPosX = e.pageX - $('#workspace-ruler-y').outerWidth();
		var mPosY = e.pageY - $('#workspace-ruler-x').outerHeight() - $('#gnb').outerHeight();
		
		if (mPosX - beforeClickPosX < 0)
			$(this).css({ left: 0 });
		else if (mPosX + $(this).outerWidth() - beforeClickPosX + 1 > imgWidth)
			$(this).css({ left: imgWidth - $(this).outerWidth() - 1 });
		else
			$(this).css({ left: mPosX - beforeClickPosX });
		
		if (mPosY - beforeClickPosY < 0)
			$(this).css({ top: 0 });
		else if (mPosY + $(this).outerHeight() - beforeClickPosY + 1 > imgHeight)
			$(this).css({ top: imgHeight - $(this).outerHeight() - 1 });
		else
			$(this).css({ top: mPosY - beforeClickPosY });
	}
	else {
		$(this).removeClass('_moving');
		$(this).addClass('_active');
		recalcElMap();
	}
}

function recalcElMap() {
	var recalcIndex = $('.grid-box._active').attr('id').split('-')[2];
	
	mapEl[recalcIndex][0][0] = (unit == 'px') ? parseInt($('.grid-box._active').css('left')) : parseInt($('.grid-box._active').css('left')) / 10000 * imgWidth;
	mapEl[recalcIndex][0][1] = (unit == 'px') ? parseInt($('.grid-box._active').css('top')) : parseInt($('.grid-box._active').css('top')) / 10000 * imgWidth;
	mapEl[recalcIndex][1][0] = (unit == 'px') ? parseInt($('.grid-box._active').css('left')) + $('.grid-box._active').outerWidth() : (parseInt($('.grid-box._active').css('left')) + $('.grid-box._active').outerWidth()) / 10000 * imgWidth;
	mapEl[recalcIndex][1][1] = (unit == 'px') ? parseInt($('.grid-box._active').css('top')) + $('.grid-box._active').outerHeight() : (parseInt($('.grid-box._active').css('top')) + $('.grid-box._active').outerHeight()) / 10000* imgWidth;
}