/**
 *   Quick Designer for QHM Professional Edition
 *   -------------------------------------------
 *   qdsgn.swfu.js
 *   
 *   Copyright (c) 2009 hokuken
 *   http://hokuken.com/
 *  
 *   created  : 2009-06-15
 *   modified : 
 *     
 *   Open Image Dialog and be able to upload image files.
 *     
 *   Usage :
 *     
 */
$(document).ready(function() {

	var swfupath = '../commu/js/hkswfu/';
	var image_dir = 'img/icons/';

	$('div.imagesetButton')
		.click(function(){
			$('#imageManager_dialog').dialog({
				autoOpen: false,
				modal: true,
				width: '80%',
				buttons: {
					"閉じる": function() {
						$(this).dialog("destroy");
					}
				}
			});
			$('#imageManager_dialog').dialog('open');
		});

	$('div.imageBox')
		.click(
			$.data(document, "imgBoxFuncClick",
			function(){
				$('div.imageBox').css('border-color','#333');
				$('#selectImageFile').empty();
				$(this).css('border-color','#f90');
				var imgobj = $(this).children('.image').children('img');
				var	src = imgobj.attr('src');
				var	wsize = 0, hsize = 0;
				var	style = '';
				if (imgobj.css('width') == 'auto') {
					hsize  = (imgobj.css('height') < 40) ? imgobj.css('height') : 40;
					style = 'height:'+hsize+'px';
				}
				else if (imgobj.css('height') == 'auto') {
					wsize  = (imgobj.css('width') < 70) ? imgobj.css('width') : 70;
					style = 'width:'+wsize+'px';
				}
				else if (imgobj.width() > imgobj.height()) {
					wsize  = (imgobj.width() < 70) ? imgobj.width() : 70;
					style = 'width:'+wsize+'px';
				}
				else {
					hsize  = (imgobj.height() < 40) ? imgobj.height() : 40;
					style = 'height:'+hsize+'px';
				}
				var basename = src.slice(src.lastIndexOf("/")+1);
				$('#selectImageFile')
					.append('<p style="margin:0 0 5px;">'+basename+'</p>')
					.append('<table class="selectedImage"><tr><td valign="middle"><img id="background-image" src="'+src+'" title="'+basename+'" style="'+style+'" /></td></tr></table>');
			}));

	$('div.image')
		.each(
			$.data(document, "imgFuncMK",
			function(i,ob) {
				var boxobj = $(this).parent();
				var imagepath = $(this).children('img').attr('src');
				$(this).css('cursol','pointer');
				$('<div class="operator" style="display:none"></div>')
					.append('<div class="expand"><img src="'+swfupath+'expand.gif" /></div>')
					.append('<div class="delete"><img src="'+swfupath+'delete.gif" /></div>')
					.appendTo(this)
					.children('.expand')
						.hover(
							function(e){
								$(this).append('<div class="expand_image"><img src="'+imagepath+'" /></div>')
								$('div.expand_image',this).css({left:e.pageX-$(window).scrollLeft(),top:e.pageY-$(window).scrollTop(), position:'fixed'});
							},
							function(){
								$('div.expand_image').remove();
							})
						.click(function(e){
							e.stopPropagation();
						})
					.parent().children('.delete')
						.click(function(e){
							e.stopPropagation();
							var basename = imagepath.slice(imagepath.lastIndexOf("/")+1);
							// msgboxの表示
							if ($('#delete_confirm').length) {
								$('#delete_confirm span').text(basename);
								$('#delete_confirm').dialog('option','buttons',
									{
										'削除する': function(ev){
											$.post('delete_image.php', {'delfile':imagepath}, function(ev){delete_file(ev,boxobj)});
											$(this).dialog("close");
										},
										'キャンセル': function(ev){
											$(this).dialog("close");
										}
									});
							}
							else {
								$(this).append('<div id="delete_confirm" title="ファイルの削除"><p>ファイルを削除してもよろしいですか？</p><p>削除するファイル名：<span>'+basename+'</span></p></div>');
							}
							$('#delete_confirm').dialog({
								autoOpen: false,
								modal:true,
								width: 350,
								height: 200,
								resizeable: false,
								buttons: {
									'削除する': function(ev){
										$.post('delete_image.php', {'delfile':imagepath}, function(ev){delete_file(ev,boxobj)});
										$(this).dialog("close");
									},
									'キャンセル': function(ev){
										$(this).dialog("close");
									}
								}
							});
							$('#delete_confirm').dialog('open');
			});
		}))
		.hover(
			$.data(document, "imgFuncME",
			function(){
				$(this).children('.operator').show();
			}),
			$.data(document, "imgFuncML", 
			function(){
				$('div.operator').hide();
			})
		);

	$('#swfupload-control').swfupload({
		upload_url: "upload_icons.php",
		file_size_limit : "10240",
		file_types : "*.gif;*.jpg;*.jpeg;*.png;*.GIF;*.JPG;*.JPEG;*.PNG;",
		file_types_description : "Icons",
		file_upload_limit : "0",
		flash_url : swfupath+"swfupload/swfupload.swf",
		button_image_url : swfupath+"swfupload/uploadButton_61x22.gif",
		button_width : 61,
		button_height : 22,
		button_placeholder : $('#upbutton')[0],
		debug: false,
		custom_settings : {something : "here"}
	})
		.bind('fileQueued', function(event, file){
			$(this).swfupload('startUpload');
		})
		.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
			$.data(document,'filecount',numFilesSelected);
		})
		.bind('uploadSuccess', function(event, file, serverData){
//			console.log(arguments);
			$.get('upload_icons.php', {'upfile':file.name, 'filecnt':$.data(document,'filecount')}, dispImage);
			$(this).blur();
		})
		.bind('uploadComplete', function(event, file){
			// upload has completed, lets try the next one in the queue
			$(this).swfupload('startUpload');
		})
		.bind('uploadError', function(event, file, errorCode, message){
			console.log(arguments);
			if (message == "302") {
				$.get('upload_icons.php', {'upfile':file.name, 'filecnt':$.data(document,'filecount')}, dispImage);
				$(this).blur();
			}
		});

	function dispImage(res)
	{
		var d = JSON.parse(res);
		if (d == null || d == '') {
			return;
		}
		var fname    = d['name'];
		var width    = d['width'];
		var height   = d['height'];
		var sbwidth  = d['sbwidth'];
		var sbheight = d['sbheight'];
		var style = (d['width'] > d['height']) ? 'width:'+d['sbwidth'] : 'height:'+d['sbheight'];

		$('<div class="imageBox"></div>')
			.prepend('<p align="center" style="margin-top:2px;">'+fname+'<br />('+width+'×'+height+')</p>')
			.prepend('<div class="image"><img src="'+image_dir+fname+'" alt="'+fname+'" style="'+style+'px;" /></div>')
			.prependTo('div.imagelist')
			.children('.image').each($.data(document,'imgFuncMK'))
			.hover($.data(document,'imgFuncME'),$.data(document,'imgFuncML'))
			.parent().click($.data(document,'imgBoxFuncClick'))
			.trigger('click');
    }


	// イメージファイルの削除
	function delete_file(pstr, obj) {
		var arr = JSON.parse(pstr);
		var filename = arr['file'];
		var src = obj.children('.image').find('img').attr('src');
	
		if (filename == src) {
			obj.remove();
		}
	}

});

