if (!w3d) var w3d = {};
if (!w3d.viewer) w3d.viewer = {};
var wv = w3d.viewer;

/* basic setting function
=============================*/
// 전역 변수 및 기본/편집 메뉴 설정
wv.editing = {};
wv.globalCategory = 0;
wv.productCategory = 0;
wv.fabricCategoryId = 0;
wv.layerObject = {};

wv.setLayers = function(id) {
	$('#innerBelongings').empty();
	//wv.slist = [];
	var layerPlace = $('#layers');
	layerPlace.empty();
	var start;
	$.ajax({
		url: '/manager/product/layer/getlist',
		type: 'POST',
		cache: false,
		data: {id:id},
		dataType: 'json',
		async: false,
		success: function(response) {
			var list = response['layerList'],
				slist = response['slist'];
			//alert(list.length);s
            for (li in list) {
                var button = $("<div class='layers "+li+"'>" + list[li] + "</div>").appendTo(layerPlace);
                button.data({'layerName':list[li], 'index':li});
                wv.addBelongingList(button, id);
                $('.layers.'+li).click( function(){
                    wv.setTargets(this, id);
                });
            }
            var layersTotal = list.length;
            if (layersTotal > 2) {
                var pagesTotal = Math.ceil(layersTotal/2);                
                for (var page = 1; page <= pagesTotal; page++) {
                    var currentPage = $('<div class="layerPage '+page+'"></div>').hide().appendTo(layerPlace);
                    indexMax = 2 * page - 1,
                    indexMin = indexMax - 1;
                    for (i = indexMin; i <= indexMax; i++) {
                    //for (var i = 0; i <= 11; i++) {
                        $(".layers."+i, layerPlace).appendTo(currentPage);
                        //alert('fertig');
                    }
                }
                $(".layerPage:first", layerPlace).show();
                var currentPage = 1,
                    nextPage = $('<div class="nextPage">></div>').appendTo(layerPlace),
                    frontPage = $('<div class="frontPage"><</div>').appendTo(layerPlace);
                $('.nextPage', layerPlace)
                    .hover(function(){$(this).css('cursor', 'pointer')})
                    .click(function(){
                        $(this).hide();
                        currentPage++;
                        $('.layerPage', layerPlace).hide();
                        $('.layerPage.'+currentPage, layerPlace).show();
                        $('.frontPage', layerPlace).prependTo(layerPlace).show();
                         /*   .hover(function(){$(this).css('cursor', 'pointer')})
                            .click(function(){
                                $(this).hide();
                                currentPage--;
                                $('.layerPage', layerPlace).hide();
                                $('.layerPage.'+currentPage, layerPlace).show();
                                nextPage.appendTo(layerPlace);
                                if( currentPage > 1 ) $(this).prependTo(layerPlace);
                            });*/
                        if( currentPage < pagesTotal ) $(this).appendTo(layerPlace).show();
                    });
                $('.frontPage', layerPlace)
                    .hover(function(){$(this).css('cursor', 'pointer')})
                    .click(function(){
                        $(this).hide();
                        currentPage--;
                        $('.layerPage', layerPlace).hide();
                        $('.layerPage.'+currentPage, layerPlace).show();
                        $('.nextPage', layerPlace).appendTo(layerPlace).show();
                          /*  .hover(function(){$(this).css('cursor', 'pointer')})
                            .click(function(){
                                $(this).hide();
                                currentPage++;
                                $('.layerPage', layerPlace).hide();
                                $('.layerPage.'+currentPage, layerPlace).show();
                                frontPage.prependTo(layerPlace);   
                                if( currentPage < pagesTotal ) $(this).appendTo(layerPlace);
                            });*/
                        if( currentPage > 1 ) $(this).prependTo(layerPlace).show();
                    });
                //$('.frontPage', layerPlace)

            }
            wv.setTargets($('.layers:first'), id, 0);
		},
		error: function() {
			
		}
	});
};

wv.addBelongingList = function(button, pid){
	var button = $(button);
	var layerName = button.data('layerName'); 
	$.ajax({
		url: '/fabric/belonging/getlist',
		type: 'POST',
		cache: false,
		data: {layerName:layerName, pid:pid, type:'json'},
		dataType: 'json',
		async: false,
		success: function(response) {
			var idList = response['idList'];
			button.data('idList', idList);
		},
		error: function() {
		
		}
	});		
};

wv.setTargets = function(button, pid) {
	var button = $(button),
        layerName = button.data('layerName'),
        index = button.data('index'),
        targetSize;
	$('.layers').removeClass('selected'); 
	$('#targetPages', '#belongings').empty();
    button.addClass('selected');
	$('.targetPage', '#belongings').hide();
    //$('#innerBelongings').empty();
	$('.productTarget').hide();
	if (button.data('done')) {
        targetSize = $(".productTarget."+index+"index").size();
        if (targetSize > 2) {     
            var currentPage = $('.targetPage:first', belongings).show();
            $(".productTarget."+index+"index").show();
        } else {
            $(".productTarget."+index+"index").show();
        }
	} else {	
		var idList = button.data('idList');
		for (id in idList) {
			wv.parseTargets(idList[id], index, pid, id);
		}
        button.data('done', true);
        targetSize = $(".productTarget."+index+"index").size();
        if ( targetSize > 2 ) {
            wv.setTargetPages(targetSize, index);
            //var currentPage = 
            $('.targetPage:first', belongings).show();
            //$(".productTarget."+index+"index", currentPage).show();
        } else {
            $(".productTarget."+index+"index").show();
        }
	}
    wv.setTargetPagesBtn(targetSize, index);
};

wv.setTargetPages = function(targetSize, index) {
    var pagesTotal = Math.ceil(targetSize/2),
        belongings = $('#innerBelongings');
    for (var page = 1; page <= pagesTotal; page++) {
        var currentPage = $('<div class="targetPage '+index+'index '+page+'"></div>').hide().appendTo(belongings);
        indexMax = 2 * page - 1,
        indexMin = indexMax - 1;
        for (i = indexMin; i <= indexMax; i++) {
        //for (var i = 0; i <= 11; i++) {
            $(".productTarget."+index+"index."+i, belongings).show().appendTo(currentPage);
            //alert('fertig');
        }
    }
};

wv.setTargetPagesBtn = function(targetSize, index) {
    var currentPage = 1,
        pagesTotal = Math.ceil(targetSize/2);
    if (pagesTotal < 1) pagesTotal = 1;
    $('#targetPages','#belongings')
        .append(
            '<div class="wrapTop">'+
                '<div class="changePage currentPage">'+currentPage+'</div>'+
                '<div class="changePage maxPage">/ '+pagesTotal+'</div>'+
            '</div>'+
            '<div class="wrapBottom">'+            
                '<div class="changePage frontPageBtn"><img style="widh:100%; height:100%" src="/media/image/Viewer/left1.bmp"></div>'+
                '<div class="changePage nextPageBtn"><img style="widh:100%; height:100%" src="/media/image/Viewer/right1.bmp"></div>'+
            '</div>'
        );
    $('.changePage.nextPageBtn','.wrapBottom')
        .hover(function(){$(this).css('cursor', 'pointer')})
        .click(function(){
            if (pagesTotal <= 1) return false;
            if (currentPage == pagesTotal) {
                currentPage = 1;
            } else {
                currentPage++
            }
            $('.changePage.currentPage', '.wrapTop').text(currentPage);
            $('.targetPage', '#belongings').hide();
            $('.targetPage.'+index+'index.'+currentPage, '#belongings').show();
        });
    
    $('.changePage.frontPageBtn','.wrapBottom')
        .hover(function(){$(this).css('cursor', 'pointer')})
        .click(function(){
            if (pagesTotal <= 1) return false;
            if (currentPage == 1) {
                currentPage = pagesTotal;
            } else {
                currentPage--
            }
            $('.changePage.currentPage', '.wrapTop').text(currentPage);
            $('.targetPage', '#belongings').hide();
            $('.targetPage.'+index+'index.'+currentPage, '#belongings').show();
        });
};

wv.parseTargets = function(fid, index, pid, belongIndex) {
	
	var belongings = $('#innerBelongings');
	
	$.ajax({
		url: '/fabric/target',
		type: 'POST',
		cache: false,
		data: {fid:fid},
		dataType: 'json',
		async: false,
		success: function(response) {

			var name = response['name'],
				path = response['path'],
				thum_url = response['thum_url'],
				width = response['width'],
				height = response['height'],
				mask = response['mask'],
				id = response['id'],
				element = $("<div class='productTarget "+index+"index "+belongIndex+"'></div>").hide().appendTo(belongings);
		
			element.append("<div class='fabricItem_image'></div><div class='fabricItem_name'>"+name+"</div>");
			$('.fabricItem_image', element).css('background-image', 'url(' + thum_url + ')');
			if (mask){ element.data('mask', mask) }
			element
				.data({'name':name,'id':id, 'path':path, 'belongIndex':belongIndex, 'width':width, 'height':height, 'thum_url':thum_url})
				.drop("start",function(){
					$( this ).addClass("active");
				})
				.drop(function( ev, dd ){
					var old_id = $(this).data('id');
					
					$('.fabricItem_image',this).empty();
					$('.fabricItem_name, .fabricItem_size',this).remove();

					var name = $(dd.drag).data('name'),
						path = $(dd.drag).data('path'),
						thum_url = $(dd.drag).data('thum_url'),
						new_id = $(dd.drag).data('id');
					
					//change Target
					$('.fabricItem_image',this).css('background-image', 'url(' + thum_url + ')');
					$("<div class='fabricItem_name'>"+name+"</div>").appendTo(element);
					$(this).data({'path':path, 'pid':pid, 'id':new_id, 'thum_url':thum_url});
					
					//change the global list
					var idList = $('.layers.selected').data('idList');
                    //alert($('.layers.selected').data('idList'));
					idList[belongIndex] = new_id;
					//alert($('.layers.selected').data('idList'));
                    wv.runSimulation(pid);		
				})
				.drop("end",function( ev, dd ){
					$( this ).removeClass("active");
				});
			element.hover(function(){
				var offset = $('#bigImage').offset(),
					top = offset.top,
					left = offset.left,
					width = $('#bigImage').width(),
					height = $('#bigImage').height(),
					mask = $(this).data('mask'),
					bigMask = $("<img id='bigMask' src='"+mask+"' style='position:absolute;'/>").appendTo($('#mainImage'));
				bigMask.width(width).height(height).offset({top:top, left:left});
				
				var soffset = $('#smallImage').offset(),
					stop = soffset.top,
					sleft = soffset.left,
					swidth = $('#smallImage').width(),
					sheight = $('#smallImage').height(),
					smallMask = $("<img id='smallMask' src='"+mask+"' style='position:absolute;'/>").appendTo($('#upperSelectorDivLeft'));
				smallMask.width(swidth).height(sheight).offset({top:stop, left:sleft});

			}, 
			function(){
				$('#bigMask, #smallMask').remove();
			});
			
		},
		error: function() {
		
		}
	});
};


wv.runSimulation = function(pid){
	var fids = [];
	$('.layers').each(function(){
		idList = $(this).data('idList');
		fids = fids.concat(idList);
	});
	fids = fids.join();
	
	$("<div id='loading_mask'></div>")
		.css('opacity', 0.5)
		.appendTo($('body'));
	
	$.ajax({
		url: '/simulation',
		type: 'POST',
		cache: false,
		data: {FIDS:fids, PID:pid},
		dataType: 'json',
		async: true,
		success: function(response) {
			var url = response['url'];
			//alert(url);
			$('#mainImage, #upperSelectorDivLeft').empty();
			$('#mainImage').append("<img id='bigImage' src='"+url+"' style='width:100%; height:100%'/>");
			$('#upperSelectorDivLeft').append("<img id='smallImage' src='"+url+"' style='width:100%; height:100%'/>");
			
			$('#loading_mask').remove();
		},
		error: function() {
			alert('시뮬레이션 실패');
			$('#loading_mask').remove();
		}
	});
};

wv.warePicImage = function(type) {
	$('#theSelectorBottom').empty();
    $('.wrap','#selectorPages').empty();
	var cid = wv.categoryId,
		idList = [],
		selector = $('#theSelectorTop'),
		finalProductCategory = $("<div id='finalProductCategory' class='finalProductCategory'></div>").appendTo(selector);
	$.ajax({
		url: '/manager/product/category/getlist',
		type: 'POST',
		cache: false,
		data: {CID:cid, TYPE:type},
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var categoryList = $('Records', $(xml));
			$('Record', categoryList).each(function(i) {
				var categoryId = $(this).attr('ID');
				idList.push(categoryId);
				var categoryName = $(this).attr('Name'),
					orderValue = $(this).attr('OrderValue'),
					button = $("<div id='etc' class='choiceProductSelector'>" + categoryName + "</div>").appendTo(finalProductCategory);
				$("<div style='font-size:15; color:black; float: left; padding: 5px 0px 0px 5px;'>|</div>").appendTo(finalProductCategory);
				button.click(function(){
					wv.productCategory = categoryId;
					$('.choiceProductSelector').removeClass('selected');
					$(this).addClass('selected');
					wv.parseProducts(categoryId, type);
				});
			});
			if(wv.globalCategory == 1) {
				wv.parseProducts(idList[0], type);
				$('.choiceProductSelector:first').addClass('selected');
			}
			else {	
				wv.parseProducts(wv.productCategory, type);
			}
		},
		error: function() {
	
		}
	});
	
};

wv.parseProducts = function(cid, type){
	wv.productCategory = cid;
	//alert(cid);
	$('#theSelectorBottom').empty();
    $('.wrap','#selectorPages').empty();
	$.ajax({
		url: '/manager/product/getlistViewer',
		type: 'POST',
		cache: false,
		data: { cid:cid, Type:type },
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var productList = $('Records', $(xml)),
                first = $('Record:first', productList),
                totalProductSize = $('Record', productList).size(),
                tempProducts = $('<div class="tempProducts"></div>').hide().appendTo($('#theSelectorBottom')),
                pagesTotal = Math.ceil(totalProductSize/12), 
                i;
            if (pagesTotal == 0) pagesTotal = 1; 
			$('Record', productList).each(function(i) {
				var name = $(this).attr('Name'),
				path = $(this).attr('path'),
				thumb_url = $(this).attr('thumb_url'),
				layerCount = $(this).attr('LyerCount'),
				//var width = $(this).attr('width');
				//var height = $(this).attr('height');
				id = $(this).attr('ID'),
                element = $("<div class='productItem "+i+"'></div>");
				
                element.append("<img src='"+thumb_url+"' style='width:115px; height:115px; border:1px solid black; display:block;'/>");
				
                var element_name = $("<div class='productItem_name'>"+name+"</div>").appendTo(element);
				element.data('name', name);
				element.data('id', id);
				element.data('path', path);
				element.data('layerCount', layerCount);
				element.appendTo(tempProducts);
				element
					.drag("start",function( ev, dd ){
						$( dd.available ).addClass("available");
						return $( this ).clone()
							.css("opacity", .5 )
							.addClass('clone')
							.appendTo( document.body );
					})
					.drag("end",function( ev, dd ){
						$( dd.available ).removeClass("available");
						$( dd.proxy ).remove();
					})		
					.drag(function( ev, dd ){
						$( dd.proxy ).css({
							top: dd.offsetY,
							left: dd.offsetX
						});
					}, { drop:'#mainImage, #upperSelectorDivLeft' });
				$.drop({ mode:"intersect" });
			});
            
            for (var page = 1; page <= pagesTotal; page++) {
                var currentPage = $('<div class="productPage '+page+'"></div>').hide().appendTo($('#theSelectorBottom')),
                    indexMax = 12 * page - 1,
                    indexMin = indexMax - 11;
                
                for (i = indexMin; i <= indexMax; i++) {
                    $('.productItem.'+i, tempProducts).appendTo(currentPage);
                }
            }
            
			if (wv.globalCategory == 1) {
				var path = $(first).attr('path');
				var id = $(first).attr('ID');
				$('#mainImage').empty();
				$('#upperSelectorDivLeft').empty();
				$('#mainImage').append("<img id='bigImage' src='"+path+"' style='width:100%; height:100%'/>");
				$('#upperSelectorDivLeft').append("<img id='smallImage' src='"+path+"' style='width:100%; height:100%'/>");
				$('#mainImage').data('id', id);
				$('#upperSelectorDivLeft').data('id', id);
				wv.setLayers(id);
			}
            
            $('.productPage:first', '#theSelectorBottom').show();
            var currentPage = 1;
            
            var wrap = $('.wrap','#selectorPages')
                .append(
                    '<div class="changePage currentPage">'+currentPage+'</div>'+
                    '<div class="changePage maxPage">/ '+pagesTotal+'</div>'+
                    '<div class="changePage frontPageBtn"><img style="widh:100%; height:100%" src="/media/image/Viewer/left1.bmp"></div>'+
                    '<div class="changePage nextPageBtn"><img style="widh:100%; height:100%" src="/media/image/Viewer/right1.bmp"></div>'
                );

            $('.changePage.nextPageBtn', wrap)
                .hover(function(){$(this).css('cursor', 'pointer')})
                .click(function(){
                    if (pagesTotal <= 1) return false;
                    if (currentPage == pagesTotal) {
                        currentPage = 1;
                    } else {
                        currentPage++;
                    }
                    $('.changePage.currentPage', wrap).text(currentPage);
                    $('.productPage', '#theSelectorBottom').hide();
                    $('.productPage.'+currentPage, '#theSelectorBottom').show();
                });
            
            $('.changePage.frontPageBtn', wrap)
                .hover(function(){$(this).css('cursor', 'pointer')})
                .click(function(){
                    if (pagesTotal <= 1) return false;
                    if (currentPage == 1) {
                        currentPage = pagesTotal;
                    } else {
                        currentPage--;
                    }
                    $('.changePage.currentPage', wrap).text(currentPage);
                    $('.productPage', '#theSelectorBottom').hide();
                    $('.productPage.'+currentPage, '#theSelectorBottom').show();
                });
		},
		error: function() {

		}
	});
};

wv.supermaterial = function(arg) {
	$('#finalProductCategory').hide();
	var idList = [];
	var selector = $('#theSelectorTop');
	var finalFabricSuperCategory = $("<div class='finalFabricSuperCategory "+arg.attr("id")+"'></div>").appendTo(selector);
	$.ajax({
		url: '/manager/fabric/category/getlist',
		type: 'POST',
		cache: false,
		data: {level: 2, supercid: arg.attr("id")},
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var categoryList = $('Records', $(xml));
			/*
			$("<div id='00' class='choiceFabricSelector'>ALL</div>")
				.data("categoryId", "00")
				.data("level1id", arg.attr("id"))
				.appendTo(finalFabricSuperCategory)
				.click(function(){
					$('.choiceFabricSelector', finalFabricSuperCategory).removeClass('selected');
					$(this).addClass('selected');
					$('.finalFabricCategory', '#theSelectorTop').remove();
					wv.material("00", $(this).data("level1id"));
				});
			$("<div style='font-size:15; color:black; float: left; padding: 5px 0px 0px 5px;'>|</div>").appendTo(finalFabricSuperCategory);
			*/
			$('Record', categoryList).each(function(i) {
				var categoryId = $(this).attr('ID');
				idList.push(categoryId);
				var categoryName = $(this).attr('Name');
				var orderValue = $(this).attr('OrderValue');
				var button = $("<div id='"+categoryId+"' class='choiceFabricSelector'>" + categoryName + "</div>")
					.data("categoryId", categoryId)
					.data("level1id", arg.attr("id"))
					.appendTo(finalFabricSuperCategory);
				$("<div style='font-size:15; color:black; float: left; padding: 5px 0px 0px 5px;'>|</div>").appendTo(finalFabricSuperCategory);
				button.click(function(){
					$('.finalFabricCategory', '#theSelectorTop').remove();
					$('.choiceFabricSelector', finalFabricSuperCategory).removeClass('selected');
					$(this).addClass('selected', arg.attr("id"));
					wv.material(categoryId, $(this).data("level1id"));
				});
			});
			$('.choiceFabricSelector:first', finalFabricSuperCategory).addClass('selected');
			wv.material($('.choiceFabricSelector:first', finalFabricSuperCategory).data("categoryId"), arg.attr("id"));
			
		},
		error: function() {
		
		}
	});
};

wv.material = function(level2id) {
	var idList = [];
	var selector = $('#theSelectorTop');
	var finalFabricCategory = $("<div class='finalFabricCategory'></div>").appendTo(selector);

	$.ajax({
		url: '/manager/fabric/category/getlist',
		type: 'POST',
		cache: false,
		data: {level: 3, supercid:level2id},
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var categoryList = $('Records', $(xml));
			/*
			$("<div id='00' class='choiceFabricSelector'>ALL</div>")
				.data("categoryId", "00")
				.data("level2id", level2id)
				.data("level1id", level1id)
				.appendTo(finalFabricCategory)
				.click(function(){
					$('.choiceFabricSelector', finalFabricCategory).removeClass('selected');
					$(this).addClass('selected');
					wv.parseFabrics("00", $(this).data("level2id"), $(this).data("level1id"));
				});
			$("<div style='font-size:15; color:black; float: left; padding: 5px 0px 0px 5px;'>|</div>").appendTo(finalFabricCategory);
			*/
			$('Record', categoryList).each(function(i) {
				var categoryId = $(this).attr('ID');
				idList.push(categoryId);
				var categoryName = $(this).attr('Name');
				var orderValue = $(this).attr('OrderValue');
				var button = $("<div id='"+categoryId+"' class='choiceFabricSelector'>" + categoryName + "</div>")
					.data("categoryId", categoryId)
					.data("level2id", level2id)
					.appendTo(finalFabricCategory);
				$("<div style='font-size:15; color:black; float: left; padding: 5px 0px 0px 5px;'>|</div>").appendTo(finalFabricCategory);
				button.click(function(){
					wv.parseFabrics(categoryId);
					$('.choiceFabricSelector', finalFabricCategory).removeClass('selected');
					$(this).addClass('selected');
				});
			});
			$('.choiceFabricSelector:first', finalFabricCategory).addClass('selected');
			wv.parseFabrics($('.choiceFabricSelector:first', finalFabricCategory).data("categoryId"));
			//wmf.selectCategory(form, selectedId);
		},
		error: function() {
		
		}
	});
};

wv.parseFabrics = function(categoryId){
	wv.fabricCategoryId = categoryId;
	wv.setUploader($('#Upload'));
	$('#theSelectorBottom').empty();
    $('.wrap','#selectorPages').empty();


	$.ajax({
		url: '/manager/fabric/getlist',
		type: 'POST',
		cache: false,
		data: { cid:categoryId},
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var fabricList = $('Records', $(xml)),
                userFabricSize = $('Record', fabricList).size(),
                managerFabricList = $('ManagerRecords', $(xml)),
                managerFabricSize = $('ManagerRecord', managerFabricList).size(),
                totalFabricSize = userFabricSize + managerFabricSize,
                tempFabrics = $('<div class="tempFabrics"></div>').hide().appendTo($('#theSelectorBottom')),
                pagesTotal = Math.ceil(totalFabricSize/12), 
                i;
            if (pagesTotal == 0) pagesTotal = 1; 
            $('Record', fabricList).each(function(i) {
				var name = $(this).attr('Name'),
                    path = $(this).attr('path'),
                    thum_url = $(this).attr('thum_url'),
                    width = $(this).attr('width'),
                    height = $(this).attr('height'),
                    id = $(this).attr('id'),
                    element = $("<div class='fabricItem user "+i+"'></div>"),
                    element_image = $("<div class='fabricItem_image'></div>").appendTo(element),
                    viewerBtn = $("<div class='viewerBtn' title='織物の情報を見る'></div>").css('opacity', 0.85).hide().appendTo(element_image),
                    element_name = $("<div class='fabricItem_name'>"+name+"</div>").appendTo(element);
				element_image.css('background-image', 'url(' + thum_url + ')');
				//element.append("<img src='"+thum_url+"'/>");
				element.data({'name': name, 'id': id, 'path': path, 'width': width, 'height': height, 'thum_url': thum_url});
				element.appendTo(tempFabrics);
				element.hover(function(){
					element.append($("<div class='eraser'></div>"));
					$('.eraser').click(function(e){
						wv.deleteItem(id, categoryId);
						e.stopPropagation();
					});
					viewerBtn.show();
					$('.fabricItem_name',element).hide();
					element.append($("<div class='fabricItem_size'>"+width+"x"+height+"</div>"))
				},
				function(){
					$('.eraser').remove();
					viewerBtn.hide();
					$('.fabricItem_name',element).show();
					$('.fabricItem_size',element).remove();
				});
			});
			
			$('ManagerRecord', managerFabricList).each(function(i) {
				i = i+userFabricSize;
                var name = $(this).attr('Name'),
                    path = $(this).attr('path'),
                    thum_url = $(this).attr('thum_url'),
                    width = $(this).attr('width'),
                    height = $(this).attr('height'),
                    id = $(this).attr('id'),
                    element = $("<div class='fabricItem manager "+i+"'></div>"),
                    element_image = $("<div class='fabricItem_image'></div>").appendTo(element),
                    viewerBtn = $("<div class='viewerBtn'  title='織物の情報を見る'></div>").css('opacity', 0.85).hide().appendTo(element_image),
                    element_name = $("<div class='fabricItem_name'>"+name+"</div>").appendTo(element);
				element_image.css('background-image', 'url(' + thum_url + ')');
				element.data({'name': name, 'id': id, 'path': path, 'width': width, 'height': height, 'thum_url': thum_url});
				element.appendTo(tempFabrics);
				element.hover(function(){
					viewerBtn.show();
					$('.fabricItem_name',element).hide();
					element.append($("<div class='fabricItem_size'>"+width+"x"+height+"</div>"))
				},
				function(){
					viewerBtn.hide();
					$('.fabricItem_name',element).show();
					$('.fabricItem_size',element).remove();
				});
			});
            for (var page = 1; page <= pagesTotal; page++) {
                var currentPage = $('<div class="fabricPage '+page+'"></div>').hide().appendTo($('#theSelectorBottom')),
                    indexMax = 12 * page - 1,
                    indexMin = indexMax - 11;
                
                for (i = indexMin; i <= indexMax; i++) {
                    $('.fabricItem.'+i, tempFabrics).appendTo(currentPage);
                }
            }
            
            $('.fabricItem')
                .drag("start",function( ev, dd ){
                    $( dd.available ).addClass("available");
                    return $( this ).clone()
                        .css("opacity", .5 )
                        .addClass('clone')
                        .appendTo( document.body );
                })
                .drag("end",function( ev, dd ){
                    $( dd.available ).removeClass("available");
                    $( dd.proxy ).remove();
                })		
                .drag(function( ev, dd ){
                    $( dd.proxy ).css({
                        top: dd.offsetY,
                        left: dd.offsetX
                    });
                }, { drop:'.productTarget', not:'.viewerBtn, .eraser' });
            $.drop({ mode:"intersect" });
            
            $('.fabricPage:first', '#theSelectorBottom').show();
            var currentPage = 1;
            var wrap = $('.wrap','#selectorPages')
                .append(
                    '<div class="changePage currentPage">'+currentPage+'</div>'+
                    '<div class="changePage maxPage">/ '+pagesTotal+'</div>'+
                    '<div class="changePage frontPageBtn"><img style="widh:100%; height:100%" src="/media/image/Viewer/left1.bmp"></div>'+
                    '<div class="changePage nextPageBtn"><img style="widh:100%; height:100%" src="/media/image/Viewer/right1.bmp"></div>'
                );
            $('.changePage.nextPageBtn', wrap)
                .hover(function(){$(this).css('cursor', 'pointer')})
                .click(function(){
                    if (pagesTotal <= 1) return false;
                    if (currentPage == pagesTotal) {
                        currentPage = 1;
                    } else {
                        currentPage++;
                    }
                    $('.changePage.currentPage', wrap).text(currentPage);
                    $('.fabricPage', '#theSelectorBottom').hide();
                    $('.fabricPage.'+currentPage, '#theSelectorBottom').show();
                });
            
            $('.changePage.frontPageBtn', wrap)
                .hover(function(){$(this).css('cursor', 'pointer')})
                .click(function(){
                    if (pagesTotal <= 1) return false;
                    if (currentPage == 1) {
                        currentPage = pagesTotal;
                    } else {
                        currentPage--;
                    }
                    $('.changePage.currentPage', wrap).text(currentPage);
                    $('.fabricPage', '#theSelectorBottom').hide();
                    $('.fabricPage.'+currentPage, '#theSelectorBottom').show();
                });
            
            
		},
		error: function() {
			
		}
	});
};

wv.showMaterial = function(id, path, width, height){
	var detailImage = [];
	$.ajax({
		url: '/manager/fabric/getinfo',
		type: 'POST',
		cache: false,
		data: {
			fid: id
		},
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var FabricInfoXML = $('fabricinformation', $(xml));
			var onerepeatImg = $('onerepeatimage', FabricInfoXML);
			
			$("<div id='imageViewer_mask'></div>")
				.css('opacity', 0.5)
				.click(removeViewer)
				.appendTo('body');
			
			var viewer = $("<div id='imageViewer'></div>")
				.click(removeViewer)
				.appendTo('body');
						
			function removeViewer() {
			 $('#imageViewer_mask').remove();
			 $('#imageViewer').remove();
			}
			
			var outer_box = $("<div class='outer_box'></div>").appendTo(viewer);
			outer_box.click(function(e) { e.stopPropagation(); });
			var title = $("<div class='imageViewer_title'></div>").appendTo(outer_box);
			$("<div class='imageViewer_title_text'>Fabric information</div>").appendTo(title);
			var closeBtn = $("<div class='closeBtn'></div>").appendTo(title);
			closeBtn.click(function(e) { removeViewer(); });
			var content = $("<div class='content'></div>").appendTo(outer_box);
			var pointerLeft = $("<div class='pointer left'></div>").appendTo(content);
			var box = $("<div class='contentImageBox'></div>").appendTo(content);
			var pointerRight = $("<div class='pointer right'></div>").appendTo(content);
			//$("<div class='contentImage'></div>").appendTo(box);
			var mainImage_element = $("<div class='contentImage'></div>")
				.data('index', 0)
				.data('src', $('image_url', onerepeatImg).text())
				.appendTo(box);
/*
			var imageLabel = $("<div class='imageLabel'>One repeat image</div>").appendTo(box);
			var mainImage = $('image_url', onerepeatImg).text()
			detailImage.push(mainImage);
			var mainImage_element_img = $("<img class='mainImage_element_img' src='" + mainImage + "' />").hide().appendTo(mainImage_element);
			w3d.fn.fitImageIntoParent(mainImage_element_img);
*/
			$('detailimage', FabricInfoXML).each(function() {
				var detailImg = $(this);
				var src = $('image_url', detailImg).text();
				detailImage.push(src);
			});
			
			var imageLabel = $("<div class='imageLabel'></div>").appendTo(box);
			if (detailImage.length == 0)
				imageLabel.text('Detail image ( ' + 0 + ' / ' + 0 + ' )');
			else
				imageLabel.text('Detail image ( ' + 1 + ' / ' + detailImage.length + ' )');			
			var mainImage_element_img = $("<img class='mainImage_element_img' src='" + detailImage[0] + "' />").hide().appendTo(mainImage_element);
			w3d.fn.fitImageIntoParent(mainImage_element_img);
			
			pointerLeft.click(function(){
				var mainImage_element = $('.contentImage');
				var mainImage_element_img = $('.mainImage_element_img');
				var index = mainImage_element.data('index');
				mainImage_element.empty();
				if (detailImage.length > 0) {
					if (index == 0) {index = detailImage.length-1;} else {index--;}
					var mainImage_element_img = $("<img src='" + detailImage[index] + "' />").hide().appendTo(mainImage_element);
					w3d.fn.fitImageIntoParent(mainImage_element_img);
					mainImage_element.data('index', index);
					/*
					if (index == 0) {
						imageLabel.text('One repeat image');
					}
					else {
						imageLabel.text('Detail image (' + index + '/' + (detailImage.length - 1) + ')');
					}
					*/
					imageLabel.text('Detail image ( ' + (index+1) + ' / ' + detailImage.length + ' )');
				}
			});
			
			pointerRight.click(function(){
				var mainImage_element = $('.contentImage');
				var mainImage_element_img = $('.mainImage_element_img');
				var index = mainImage_element.data('index');
				mainImage_element.empty();
				if (detailImage.length > 0) {
					if (index < detailImage.length-1) {index++;} else {index = 0}
					var mainImage_element_img = $("<img src='" + detailImage[index] + "' />").hide().appendTo(mainImage_element);
					w3d.fn.fitImageIntoParent(mainImage_element_img);
					mainImage_element.data('index', index);
					/*
					if (index == 0) {
						imageLabel.text('One repeat image');
					}
					else {
						imageLabel.text('Detail image ( ' + index + ' / ' + (detailImage.length - 1) + ' )');
					}
					*/
					imageLabel.text('Detail image ( ' + (index+1) + ' / ' + detailImage.length + ' )');
				}
			});
			var detailInfo = $('detailinfo', FabricInfoXML);
			var name = $('name', detailInfo).text();
			var code = $('code', detailInfo).text();
			var weight = $('weight', detailInfo).text();
			var width = $('width', detailInfo).text();
			var composition = $('composition', detailInfo).text();
			var price = $('price', detailInfo).text();
			var size = $('size', detailInfo).text();
			var text = $('text', detailInfo).text().replace(/\n/g, '<br/>');//.split('\n').join('<br/>');
			
			var information = $("<div class='information'></div>").appendTo(outer_box);
			var informationTitle = $("<div class='informationTitle'></div>").appendTo(information);
			$("<div class='informationTitle_name'>品番: "+name+" / *シリーズ [ "+code+" ]</div>").appendTo(informationTitle);
			var informationContent = $("<div class='informationContent'></div>").appendTo(information);
			var infoConLeft = $("<div class='infoCon bleft'></div>").appendTo(informationContent);
			$("<div class='infoConTitle'>生地情報</div>").appendTo(infoConLeft);
			$("<div class='infoConTable'><table><tr><td class='index'>o シリーズ </td><td class='contents'>"+code+"</td></tr><tr><td class='index'>o 生地巾 </td><td class='contents'>"+weight+"</td></tr><tr><td class='index'>o 組成 </td><td class='contents'>"+width+"</td></tr><tr><td class='index'>o 柄リピート </td><td class='contents'>"+composition+"</td></tr><tr><td class='index'>o 裾仕様 </td><td class='contents'>"+price+"</td></tr><tr><td class='index'>o 形状記憶加工 </td><td class='contents'>"+size+"</td></tr></table></div>").appendTo(infoConLeft);
			var infoConMid = $("<div class='infoCon bmid'></div>").appendTo(informationContent);
			$("<div class='infoConTitle'>洗濯表示</div>").appendTo(infoConMid);
			var laundryBox = $("<div class='infoConMid'></div>").appendTo(infoConMid);
			var infoConRight = $("<div class='infoCon bright'></div>").appendTo(informationContent);
			$("<div class='infoConTitle'>MEMO</div>").appendTo(infoConRight);
			$("<div class='infoConRight'>"+text+"</div>").appendTo(infoConRight);
			var laundryTags = $('landrytags', FabricInfoXML).text();
			
			//var tag_name = ['Single', 'Dry', 'Shade', 'Water', 'Hand', 'Iron', 'Twist']
			for (var tag = 0; tag < laundryTags.length -1; tag++){			//tag in laundryTags) {
				var num = parseInt(tag, 10)+1;
				var tag_div = $("<div class='tagDiv'></div>").appendTo(laundryBox);
				$("<img src='/media/image/manager/tag"+num+".png' class='tagImage'/>").appendTo(tag_div);
				//$("<div class='tagName'>" + tag_name[tag] + "</div>").appendTo(tag_div);
				if (laundryTags[tag] != '1') {
					tag_div.css('opacity', 0.2);
				}
			}
		},
		error: function() {
			alert('faild to load fabric information');
		}
	});
};

wv.showMyFabric = function(path, width, height){
	$("<div id='imageViewer_mask'></div>")
		.css('opacity', 0.5)
		.click(removeViewer)
		.appendTo('body');
	
	var viewer = $("<div id='imageViewer'></div>")
		.click(removeViewer)
		.appendTo('body');
	
	var innerViewer = $("<div id='imageInnerViewer'></div>")
		.click(removeViewer)
		.appendTo(viewer);
	
	var contentImg = $("<img src='"+path+"' />")
		.css('border', '2px solid white')
		.hide()
		.appendTo(innerViewer);
	w3d.fn.fitImageIntoParent(contentImg);
	
	function removeViewer() {
	 $('#imageViewer_mask').remove();
	 $('#imageViewer').remove();
	}
};

wv.setUploader = function(uploadButton) {	
	var cid;
	if($('#warePic').hasClass('selected')){
		cid = 0;
	} else {
		cid = wv.fabricCategoryId;
	}
	var uploader = new qq.FileUploader({
		params: {
			Type: '0',
			Visible: 'true',
			CID:cid
		},
		allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'tif', 'tiff'],
		element: uploadButton[0],
		text: '',
		action: '/manager/fabric/create',
		onComplete: function(id, filename, response) {
			if(response['success']) {
				wv.parseFabrics(cid);
			}
			else {
				switch(response['reason']){
					case 'Anonymous':
						alert('please login first');
						break;
					case 'NoCategory':
						alert('none of categories selected.');
						break;
					default:
						alert('please login or select a fabric category.');
						return false;
						break;
				}	
			}
		}
	});
};

wv.deleteItem = function(id, categoryId) {
	$.ajax({
		url: '/manager/fabric/delete',
		type: 'POST',
		cache: false,
		data: {
			fid: id
		},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				
			}
			else {
				switch (response['reason']) {
					case 'DoesNotExist':
						alert('a fabric to delete is not exist');
						break;
					default:
						alert('faild to delete the fabric : ' + response['reason']);
				}
			}
		},
		error: function() {
			alert('faild to delete the fabric');
		}
		
	});
	wv.parseFabrics(categoryId);
};

wv.setKeydownHandler = function() {
	$('body').keydown(function(evt) {
		var key = evt.which;
		
		switch(key) {
			case 27:	// escape
				$('#imageViewer_mask').remove();
				$('#imageViewer').remove();
				break;
			default:
				break;
		}
	});
};


	
function setCookie(name, value, expiredays) {
    var todayDate = new Date();
    todayDate.setDate(todayDate.getDate() + expiredays);
    document.cookie = name + "=" + escape(value) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}
function getCookie(name) {
    var nameOfCookie = name + "=";
    var x = 0;
    while (x <= document.cookie.length)
    {
        var y = (x + nameOfCookie.length);
        if (document.cookie.substring(x, y) == nameOfCookie)
        { 
            if ((endOfCookie=document.cookie.indexOf(";", y)) == -1)
                endOfCookie = document.cookie.length;
                return unescape(document.cookie.substring(y, endOfCookie));
        }
        x = document.cookie.indexOf(" ", x) + 1;
        if (x == 0)
        break;
    }
    return "";
}
            
function checkFunc() {
    if ($('input[id="popupCheck"]').is(":checked"))
        $('input[id="popupCheck"]').attr('checked',false);
    else
        $('input[id="popupCheck"]').attr('checked',true);
}
function closePopup(num) {
    if ($('input[id="popupCheck"]').is(":checked"))
        setCookie("event20141004", "done", 3);
    
    $(function(){
        $("#helperLayer_"+num).hide();
    }); 
}

if (getCookie("event20141004") == "done") {
    $(function(){
        $(".helperLayer").hide();
    });
}
else {
    $(function(){
        $("#helperLayer_2").hide();
    });
}


jQuery(function($) {
    $( document )
    .on("click",".sendmailBtn", function() {
        
        var content = "<html> <head> <xmeta http-equiv='Content-Type' content='text/html; charset=utf-8'> </head> <body> <div class='title_image'> <a href='http://www.keyuca.com/'><img src='http://www.keyuca.com/wp-content/themes/KEYUCA/images/logo.gif' width='106' height='19' alt='KEYUCA -インテリアショップ ケユカ-'></a> </div> <div class='mailContent' style=' font-family: ' メイリオ',Meiryo,Osaka,' ヒラギノ角ゴ ProW3','Hiragino Kaku Gothic Pro',' ＭＳ Ｐゴシック','MSPGothic',sans-serif; text-align: center;'> <div class='bigImage'> <img src='http://211.238.177.155/media/data/tex3d_images/0/184.jpg'> </div> <div class='informationTitle' style='width:885px; height: 27px; background-color: #4F4A46; color: white; overflow: hidden;'> <div class='informationTitle_name' style='color: white; font-weight:bold; font-size:13px; text-align:left; float:left; margin-left:40px; line-height: 27px;'>生地名: mint / *品番 [ ] </div> </div> <div class='informationContent' style='height:200px;'> <table> <tbody> <tr> <td width='110px'> <img src='http://54.64.166.93/media/data/fabric_thumbs/0/1015.jpg'> </td> <td width='230px'> <div style='float:left; margin: 10px 0 0 15px;'> <div style='height:20px; font-size:13px; text-align:left; font-weight:bold; margin-left:15px;'>生地情報</div> <div style='width:220px; height:160px; border:2px solid grey;'> <table style='margin-left:10px; width: 230px; table-layout: fixed; border-spacing: 8px; line-height:15px;'> <tbody> <tr> <td style='padding: 0px; font-size:12px; text-align:left; width:75px; font-weight:bold; border-right: 1px solid;'>o No. </td><td style='padding: 0px; font-size:12px; text-align:left; width:130px; color:#4F4A46; font-weight:bold; padding-left:5px;'></td></tr><tr><td style='padding: 0px; font-size:12px; text-align:left; width:75px; font-weight:bold; border-right: 1px solid;'>o Weight </td><td style='padding: 0px; font-size:12px; text-align:left; width:130px; color:#4F4A46; font-weight:bold; padding-left:5px;'></td></tr><tr><td style='padding: 0px; font-size:12px; text-align:left; width:75px; font-weight:bold; border-right: 1px solid;'>o Width </td><td style='padding: 0px; font-size:12px; text-align:left; width:130px; color:#4F4A46; font-weight:bold; padding-left:5px;'>8x8</td></tr><tr><td style='padding: 0px; font-size:12px; text-align:left; width:75px; font-weight:bold; border-right: 1px solid;'>o Compos. </td><td style='padding: 0px; font-size:12px; text-align:left; width:130px; color:#4F4A46; font-weight:bold; padding-left:5px;'></td></tr><tr><td style='padding: 0px; font-size:12px; text-align:left; width:75px; font-weight:bold; border-right: 1px solid;'>o Price </td><td style='padding: 0px; font-size:12px; text-align:left; width:130px; color:#4F4A46; font-weight:bold; padding-left:5px;'>320</td></tr><tr><td style='padding: 0px; font-size:12px; text-align:left; width:75px; font-weight:bold; border-right: 1px solid;'>o Size </td><td style='padding: 0px; font-size:12px; text-align:left; width:130px; color:#4F4A46; font-weight:bold; padding-left:5px;'></td></tr></tbody></table> </div> </div> </td> <td width='230px'> <div style='float:left; margin: 10px 0 0 15px;'> <div style='height:20px; font-size:13px; text-align:left; font-weight:bold; margin-left:15px;'>洗濯表示</div> <div style='width:245px; height:154px; border:2px solid grey; padding-top:6px; text-align:center;'> <table> <tbody><tr> <td> <div style='opacity: 0.2; width:48px; margin:5px; display:inline-block;'> <img src='/media/image/manager/tag1.png' style='width:40px; height:40px; display:block; margin:auto;'> </div> </td> <td> <div style='opacity: 0.2; width:48px; margin:5px; display:inline-block;'> <img src='/media/image/manager/tag2.png' style='width:40px; height:40px; display:block; margin:auto;'> </div> </td> <td> <div style='opacity: 0.2; width:48px; margin:5px; display:inline-block;'> <img src='/media/image/manager/tag3.png' style='width:40px; height:40px; display:block; margin:auto;'> </div> </td> <td> <div style=' width:48px; margin:5px; display:inline-block;'> <img src='/media/image/manager/tag4.png' style='width:40px; height:40px; display:block; margin:auto;'> </div> </td> </tr><tr> <td></td> <td> <div style=' width:48px; margin:5px; display:inline-block;'> <img src='/media/image/manager/tag5.png' style='width:40px; height:40px; display:block; margin:auto;'> </div> </td> <td> <div style='opacity: 0.2; width:48px; margin:5px; display:inline-block;'> <img src='/media/image/manager/tag6.png' style='width:40px; height:40px; display:block; margin:auto;'></div> </td> </tr> </tbody></table> </div> </div> </td> <td width='230px'> <div style='float:left; margin: 10px 0 0 15px;'> <div style='height:20px; font-size:13px; text-align:left; font-weight:bold; margin-left:15px;'>MEMO</div> <div style='width:220px; height:154px; border:2px solid grey; padding:5px; font-size:12px; text-align:left; color:black; background-color: rgba(255, 255, 255, 0.3); -ms-filter: '> </div> </div> </td> </tr> </tbody></table> </div> </div> </xmeta> </body> </html>"
        $.ajax({
            url: '/sendmail',
            type: 'POST',
            cache: false,
            data: {
                content: content
            },
            dataType: 'json',
            async: false,
            success: function(response) {
                if (response['success']) {
                    alert("success");
                }
                else {
                    alert("fail");
                }
            },
            error:
                function() {
                    alert("fail2");
                }
        });
    });
});