var currentTag = '';
var currentSort = 'new';
var currentSortOrder = {'pop':'desc', 'new':'desc', 'name':'asc', 'runningTime':'asc', 'photoCount':'asc'};
var currentStyle = '';
var currentStyleMargin = 5;
var _arrayStyle = new Hash();
var isFirstCall = true;

function Style(seq, name, cgSeq, scaleWidth, scaleHeight, scalemode, 
						hitCount, usedCount, contentDescription, styleDescription, 
						configFile, price, styleSeq,
						stillcutFile, previewFile, photoCount, runningTime, 
						musicCount, movieCount) {
	this.seq 				= seq;
	this.name                  = name;
	this.cgSeq                 = cgSeq;
	this.scaleWidth           = scaleWidth;
	this.scaleHeight         = scaleHeight;
	this.scalemode           = scalemode;
	this.hitCount              = hitCount;
	this.usedCount           = usedCount;
	this.contentDescription= contentDescription.trim();
	this.styleDescription    = styleDescription.trim();
	this.configFile 		= configFile.trim();
	this.price 				= price;
	this.styleSeq 				= styleSeq;
	this.stillcutFile		= stillcutFile;
	this.previewFile		= previewFile;
	this.photoCount			= photoCount;
	this.runningTime		= runningTime;
	this.musicCount			= musicCount;
	this.movieCount			= movieCount;
}

var StyleControl = {
	loadingHtml : '<table height="400" width="200" align="center"><tr><td align="center" valign="middle"><img src="/image/common/loading_l.gif" /></td></tr></table>',
	noDataHtml : '<table height="200" width="200" align="center"><tr><td align="center" valign="middle"><img src="/image/style/img_notfind.gif"></td></tr></table>',
	sortImgSrcDesc : '/image/style/icon_arrow_down.gif',
	sortImgSrcAsc : '/image/style/icon_arrow_up.gif',
	
	resizeLayer: function() {
		
	},
	
	realignStyle: function() {

	},

	log: function (msg) {
		$('log').innerHTML = msg;
	},
	
	setCgSeq: function(cgSeq) {
		var oldCgSeq = currentCgSeq;
		var obj = $('cgSeq_' + cgSeq);
		obj.src = obj.src.replace("_off.", "_on.");
	},
	
	selCgSeq: function(cgSeq, searchVal) {
		if (searchVal == null) {
			searchVal = '';
		}
		
		var oldCgSeq = currentCgSeq;
		
		// 태그 리스트 해당 cgSeq 에 맞게 변경
		this.setTagState(cgSeq, '');
		
		// 정렬 기준값을 cgSeq에 맞게 설정
		if (cgSeq == '1') {
			$('sortingGroup2').style.display = 'block';
		} else {
			$('sortingGroup2').style.display = 'none';
		}
		if (oldCgSeq != cgSeq && (currentSort == 'runningTime' || currentSort == 'photoCount')) {
			this.selSort('pop');
		}
		
		$('tagList' + oldCgSeq).style.display = 'none';
		$('tagList' + cgSeq).style.display = 'block';
		
		currentCgSeq = cgSeq;
		cgSeqImgOut($('cgSeq_' + oldCgSeq), oldCgSeq);
		
		currentTag = '';
		$('searchVal').value = searchVal;
		
		this.getStyleList();
	},
	
	setTagState: function(newCgSeq, newTag) {
		var oldTag = $('tag_' + currentCgSeq + '_' + currentTag);
		oldTag.src = oldTag.src.replace("_on.", "_off.");
		
		var newTag = $('tag_' + newCgSeq + '_' + newTag);
		newTag.src = newTag.src.replace("_off.", "_on.");
		currentTag = newTag;
	},
	
	selTag: function(tag, searchVal) {
		if (searchVal == null) {
			searchVal = '';
		}
		
		this.setTagState(currentCgSeq, tag);
		
		currentTag = tag;
		$('searchVal').value = searchVal;
		this.getStyleList();
	},
	
	selSort: function(sort) {
		this.setSortState(sort);
		currentSort = sort;
		this.getStyleList();
	},
	
	setSortState: function(newSort) {
		if (currentSort == newSort) {
			if (currentSortOrder[currentSort] == 'asc') {
				currentSortOrder[currentSort] = 'desc';
				$('sortOrder_' + newSort).src = this.sortImgSrcDesc;
			} else {
				currentSortOrder[currentSort] = 'asc';
				$('sortOrder_' + newSort).src = this.sortImgSrcAsc;
			}
		} else {
			if (currentSortOrder[newSort] == 'asc') {
				$('sortOrder_' + newSort).src = this.sortImgSrcAsc;
			} else {
				$('sortOrder_' + newSort).src = this.sortImgSrcDesc;
			}
			
			$('sort_' + currentSort).className = 'styleSorting';
			$('sort_' + newSort).className = 'styleSortingSel';
			currentSort = newSort;
		}
	},
	
	goSearch: function(ff) {
		var searchVal = ff.searchVal.value;
		this.selTag('', searchVal);
		return false;
	},
	
	getStyleList: function() {
		// 뮤직스타일 서비스 중지 처리
		if (currentCgSeq == '3') {
			$('styleList').innerHTML = '<table width="90%"><tr><td width="100%" align="center"><img usemap="#musicNoservice" src="/image/style/img_break.gif"></td></tr></table>';
			return;
		} else {
			$('styleList').innerHTML = '';
		}
		
		// 기존 목록 초기화 
		this.loadingStyleList();
		
		var searchVal = $('searchVal').value;
		
		// Ajax Call
		var param = 'cgSeq=' + currentCgSeq
			+ '&tag=' + currentTag
			+ '&searchVal=' + searchVal
			+ '&sort=' + currentSort
			+ '&sortOrder=' + currentSortOrder[currentSort]
			+ '&_uid=' + (new Date()).getTime();
		
		var url = '/pepbox-cms/servlet/StyleInformation';

		new Ajax.Request(url, {
			method: 'get',
			parameters: param,
			onSuccess: function(xmlHttp) {
				StyleControl.printStyleList(xmlHttp);
			},
			onFailure: function(xmlHttp) {
				alert('에러');
			}
		});
	},
	
	getStyle: function(styleSeq) {
		
	},
	
	getTimeConvert: function(cgSeq, val, styleName, maxPhotoCount) {
		if (val == '0' || val == '') {
			return '-';
		}
		
		// 스타일명이 "팬시 or 사용자정의 " 가 아닐 경우 
		// 사진수 시간으로 변환
		if (cgSeq != '1' || (styleName.indexOf("팬시") == 0 || styleName.indexOf("사용자정의") == 0)) {
			var sec = val*1;
			var min = Math.floor(val/60);
			var sec = val%60;
			var result = '';
			
			if (min > 0) {
				result = min + '분 ';
			}
			if (sec > 0) {
				result = result + sec + '초';
			}
		} else { // 일반 스타일
			var timePerPhoto = Math.floor(val / maxPhotoCount*1);
			var result = timePerPhoto + '초*사진수';
		}
		
		return result;
	},
	
	getStyleXml: function(rows) {
		var scaleMode = GetValue(rows, "scale-mode");
		
		if ( scaleMode == '0' ) {
			scaleMode = "exactFit";
		} else if ( scaleMode == '1' ) {
			scaleMode = "showAll";
		} else if ( scaleMode == '2' ) {
			scaleMode = "noBorder";
		} else if ( scaleMode == '3' ) {
			scaleMode = "noScale";
		} else {
			scaleMode = "noScale";
		}
		
		var styleName = GetValue(rows, "name");
		
		var photoCount = GetValue(rows, "photo-min-count") + '-' + GetValue(rows, "photo-max-count") + '장';
		if (GetValue(rows, "photo-min-count") == GetValue(rows, "photo-max-count")) {
			photoCount = GetValue(rows, "photo-max-count") + '장';
		}
		
		var runningTime = this.getTimeConvert(GetValue(rows, "cg-seq"), GetValue(rows, "running-time"), styleName, GetValue(rows, "photo-max-count"));
		
		var musicCount = GetValue(rows, "music-min-count") + '-' + GetValue(rows, "music-max-count") + '곡';
		if (GetValue(rows, "music-min-count") == GetValue(rows, "music-max-count")) {
			musicCount = GetValue(rows, "music-max-count") + '곡';
		}
		
		var cgSeq = GetValue(rows, "cg-seq");
		if (cgSeq == 1) {
			musicCount = '최대 ' + GetValue(rows, "music-max-count") + '곡';
		}
		
		var movieCount = GetValue(rows, "movie-min-count") + '-' + GetValue(rows, "movie-max-count") + '개';
		if (GetValue(rows, "movie-min-count") == GetValue(rows, "movie-max-count")) {
			movieCount = GetValue(rows, "movie-max-count") + '개';
		}
		
		var style = new Style(
			GetValue(rows, "admin-album-seq")
			,styleName
			,GetValue(rows, "cg-seq")
			,GetValue(rows, "scale-width")
			,GetValue(rows, "scale-height")
			,scaleMode
			,GetValue(rows, "hit-count")
			,GetValue(rows, "used-count")
			,GetValue(rows, "content-description")
			,GetValue(rows, "style-description")
			,GetValue(rows, "config-file")
			,GetValue(rows, "price")
			,GetValue(rows, "style-seq")
			,GetValue(rows, "stillcut-file")
			,GetValue(rows, "preview-file")
			,photoCount
			,runningTime
			,musicCount
			,movieCount
		);
		return style;
	},
	
	printStyleList: function(xmlHttp) {
		var xml = xmlHttp.responseXML;
		var record_data = xml.getElementsByTagName("record");
		
		// 기존 목록 초기화 
		StyleControl.clearStyleList();
		
		var count = 0;
		if(record_data){
			for(var row=0;row<record_data.length;row++){
				
				if (record_data.item(row).hasChildNodes())
				{
					var rows = record_data.item(row);
					
					var style = this.getStyleXml(rows);
					
					_arrayStyle[style.styleSeq] = style;
					
					this.writeStyleList(style);
					count++;
				}
			}
		}
		
		if (count == 0) {
			this.noDataStyleList();
		} else {
			this.realignStyle();
		}
	},

	noDataStyleList: function() {
		$('styleList').innerHTML = StyleControl.noDataHtml;
	},
	
	loadingStyleList: function() {
		$('styleList').innerHTML = StyleControl.loadingHtml;
	},
	
	clearStyleList: function() {
		$('styleList').innerHTML = '';
		_arryStyle = new Hash();
	},
	
	writeStyleList: function(style) {
		var styleHtml = '';
		var className = 'listForOrder';
		
		var styleInfoText = '';

		if (style.cgSeq == '1') {
			styleInfoText = '  사진:'+style.photoCount+' / \n';
			
			if (style.runningTime != '-') {
				styleInfoText += '재생:'+style.runningTime+'\n';
			}
		} else if (style.cgSeq == '2') {
			styleInfoText = ''
				+ '재생:'+style.runningTime+' / \n'
				+ '무비:'+style.movieCount+'\n';
		}
			
		var styleHtml = '<table width="370"><tr>\n'
			+ '<td valign="top" width="120">\n'
			+ '<a href="javascript:StyleControl.previewAlbum('+style.styleSeq+');" title="' + style.name + '"><img src="'+style.previewFile+'" width="104px" height="74px" class="tabImg2 fl"" /></a>\n'
			+ '</td>\n'
			+ '<td valign="top" width="250">\n'
			+ '	<div style="width:230px; overflow:hidden; text-overflow:ellipsis;"><nobr>\n'
			+ '	<a href="javascript:StyleControl.previewAlbum('+style.styleSeq+');" class="Dot_b" title="' + style.name + '">' + style.name + '</a>\n'
			+ '	</nobr></div>\n'
			+ '	<span>' + styleInfoText + '</span><br>\n'
			+ '	<span>스타일 가격 : ' + Comma((style.price*1) + 0) + '원</span><br/>\n'
			+ '	<a href="javascript:CartControl.addItem('+style.styleSeq+',\''+style.name+'\', \''+style.previewFile+'\', '+ style.cgSeq +', 0, 0);"><img src="../../image/mypepbox/btn_basket.gif" align="absmiddle" border="0" vspace="5"></a><br/>\n'
			+ '</td>\n'
			+ '</tr></table>\n';
			
		var styleObj = document.createElement('DIV');
		
		styleObj.onclick = function(){StyleControl.getStyle(style.styleSeq);};
		styleObj.innerHTML = styleHtml;
		styleObj.className = className;
		styleObj.id = 'style_' + style.styleSeq;
		$('styleList').appendChild(styleObj);
	},
	
	loadingStyle: function() {
		var oldStyleSeq = currentStyleSeq;
		
		try {
			$('style_'+ oldStyleSeq).className = 'StyleList';
		} catch (e) {}
		
		$('stillCut').innerHTML = StyleControl.loadingHtml;
		currentStyleSeq = '';
	},
	
	clearStyle: function() {
		$('stillCut').innerHTML = '';
		currentStyleSeq = '';
	},
	
	writeStyle: function(style) {

	},
	
	printPrice: function(style) {
		
	},
	
	previewAlbum: function(styleSeq) {
		var style = _arrayStyle[styleSeq];
		if (style) {
			
		} else {
			alert('요청하신 스타일은 더이상 서비스 되지 않는 스타일 입니다. \n다른 스타일을 선택해주세요.');
		}
		
		var windowOtherWidth = 14;
		var windowOtherHeight = 28;
		var oBody = getBody();
		var oBodyInnerSize = getBodyInnerSize();
		var scaleWidth = style.scaleWidth;
		var scaleHeight = style.scaleHeight;

		if (layout == 'studio') {
			windowOtherHeight = 51;
		}
		
		var windowWidth = scaleWidth*1 + windowOtherWidth;
		var windowHeight = scaleHeight*1 + windowOtherHeight;

		// 미디어 크기가 window 영역보다 클 경우 작게 처리
		if (oBodyInnerSize.height < windowHeight)
		{
			var decreaseHeight = windowHeight - oBodyInnerSize.height;
			var ratio = scaleWidth/scaleHeight;

			scaleHeight = scaleHeight*1 - decreaseHeight;
			scaleWidth = Math.round(scaleHeight * ratio);
			
			// 
			windowWidth = scaleWidth*1 + windowOtherWidth;
			windowHeight = scaleHeight*1 + windowOtherHeight;
		}
		
		// 미디어 크기가 작을 경우 최소 크기 지정
		if (windowWidth < 400) windowWidth = 400;
		if (windowHeight < 300) windowHeight = 300;
		
		var objTag = "";
		objTag += "	 <embed src='" + pepboxUrl + "/main/base.swf?styleConfig="+ style.configFile 
			+"&service=1&userSeq=0&pepboxSeq="+ style.seq 
			+"&rootAccess=0&rootDomain="+ pepboxUrl +"&partnerId="+ partnerId +"' ";
		objTag += "	 quality='high' allowFullScreen='true' bgcolor='#ffffff' width='"+ scaleWidth +"' height='" + scaleHeight + "' name='pepbox' scale='"+ style.scalemode +"' align='LT' allowScriptAccess='always' ";
		objTag += "	 type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />";
		
		var quickViewHtml = '';
		quickViewHtml += '<table width="'+ windowWidth +'" height="'+ windowHeight +'" border="0" cellpadding="0" cellspacing="0">\n';
		quickViewHtml += '	<tr>\n';
		quickViewHtml += '		<td width="7" height="21" style="line-height:0px;">\n';
		quickViewHtml += '			<img src="../../image/view/quickview_01.gif" width="7" height="21" alt=""></td>\n';
		quickViewHtml += '		<td id="quickViewDivTitleBar" align="right" valign="middle" style="line-height:0px;" background="../../image/view/quickview_02.gif"><a href="javascript:GlobalPopup.closeQuickViewDiv();"><img src="../../image/view/quickview_close.gif" border="0" align="absmiddle"></a></td>\n';
		quickViewHtml += '<td width="7" height="21" style="line-height:0px;">\n';
		quickViewHtml += '			<img src="../../image/view/quickview_03.gif" width="7" height="21" alt=""></td>\n';
		quickViewHtml += '	</tr>\n';
		quickViewHtml += '	<tr>\n';
		quickViewHtml += '		<td width="7" background="../../image/view/quickview_04.gif"></td>\n';
		quickViewHtml += '  <td style="height:' + (windowHeight - windowOtherHeight) + 'px;line-height:0px;" bgcolor="#ffffff">' + objTag + '</td>\n';
		quickViewHtml += '		<td width="7" background="../../image/view/quickview_06.gif"></td>\n';
		quickViewHtml += '  </tr>\n';
		
		if (layout == 'studio') {
			quickViewHtml += '	<tr>\n';
			quickViewHtml += '		<td width="7" background="../../image/view/quickview_04.gif"></td>\n';
			quickViewHtml += '		<td bgcolor="#d3dfef" style="padding-top:5px;color:#000000;font-family:굴림;">현재 스타일로 만드시려면 <span style="font-weight:bold;color:blue">"파일선택"</span> 버튼을 클릭하세요.</td>\n';
			quickViewHtml += '		<td width="7" background="../../image/view/quickview_06.gif"></td>\n';
			quickViewHtml += '  </tr>\n';
		} else {
			quickViewHtml += '	<tr>\n';
			quickViewHtml += '		<td width="7" background="../../image/view/quickview_04.gif"></td>\n';
			quickViewHtml += '		<td bgcolor="#d3dfef" style="padding-top:8px;color:#000000;font-family:굴림;"> </td>\n';
			quickViewHtml += '		<td width="7" background="../../image/view/quickview_06.gif"></td>\n';
			quickViewHtml += '  </tr>\n';
		}
		
		quickViewHtml += '	<tr>\n';
		quickViewHtml += '		<td  width="7" height="7" style="line-height:0px;">\n';
		quickViewHtml += '			<img src="../../image/view/quickview_07.gif" width="7" height="7" alt=""></td>\n';
		quickViewHtml += '		<td height="7" background="../../image/view/quickview_08.gif"></td>\n';
		quickViewHtml += '  <td width="7" height="7" style="line-height:0px;">\n';
		quickViewHtml += '			<img src="../../image/view/quickview_09.gif" width="7" height="7" alt=""></td>\n';
		quickViewHtml += '	</tr>\n';
		quickViewHtml += '</table>\n';
		
		GlobalPopup.closeQuickViewDiv();

		GlobalPopup.makeGrayBackDiv();
							
		// left, top 계산 : 화면 중앙에 오도록
		var windowTop = Math.floor((oBodyInnerSize.height - windowHeight) / 2);
		if (windowTop <0)
		{
			windowTop = 0;
		}

		windowTop = oBody.top + windowTop;

		var windowLeft = Math.floor((oBodyInnerSize.width - windowWidth) / 2);
		if (windowLeft <0)
		{
			windowLeft = 0;
		}
		
		var quickViewDiv = document.createElement('div');
		quickViewDiv.innerHTML = quickViewHtml;
		quickViewDiv.id = 'quickViewDiv';
		quickViewDiv.style.position = 'absolute';
		quickViewDiv.style.top = windowTop + 'px';
		quickViewDiv.style.left = windowLeft + 'px';
		quickViewDiv.style.width = windowWidth + 'px';
		quickViewDiv.style.height = windowHeight + 'px';
		quickViewDiv.style.textAlign = 'center';
		quickViewDiv.style.zIndex = '500000';
		document.body.appendChild(quickViewDiv);
		quickViewDiv.style.display = 'block';
	},
	
	TagImgOver:function(tag) {
		if (tag.id != 'tag_' + currentCgSeq + '_' + currentTag) {
			tag.src = tag.src.replace("_off.", "_on.");
		}
	},
	
	TagImgOut:function(tag){
		if (tag.id != 'tag_' + currentCgSeq + '_' + currentTag) {
			tag.src = tag.src.replace("_on.", "_off.");
		}
	}
}

Event.observe(window, 'load', function() {
		StyleControl.setCgSeq(currentCgSeq);
		StyleControl.selCgSeq(currentCgSeq, '');
		
		// 화면 활성화 
		GlobalPopup.closeLoadingDiv();
	}
);

function cgSeqImgOver(param, id) {
	if (id != currentCgSeq) {
		param.src = param.src.replace("_off.", "_on.");
	}
}
function cgSeqImgOut(param, id){
	if (id != currentCgSeq) {
		param.src = param.src.replace("_on.", "_off.");
	}
}
