
function api_tag_post(url, data, callback, type ) 
{
	if ( $.isFunction( data ) ) {
		callback = data;
		data = {};
	}

	return $.ajax({
		async: false,
		type: "POST",
		url: url,
		data: data,
		success: callback,
		dataType: type
	});
}

jQuery.fn.extend({	
	tagBox : function(options){
		return this.each(function(){
			var el=this, $el=$(this);
			el.opts = $.extend({}, {containment:'parent', editmode:false, editing:false, opurl:'/op/tag'}, options);
	        
           	$el.draggable({
					cursor: 'move',
					containment: el.opts.containment,
					drag : function(e, ui){
						$el.tagBoxMoveEditBox(el, $el);
						if(typeof(this.opts.updateevent) != 'undefined')
							el.opts.updateevent(el, e, ui);
					}
				})
            	.draggable("disable") 
            	.resizable({
	                containment: el.opts.containment,
    	            //proxy: 'proxy',
        	        //ghost: true,
            	    //animate:true,
	                handles: 'all',
    	            knobHandles: true,
        	        //aspectRatio: true,
            	    autohide: false,
                	minWidth: 60,
                	minHeight: 60,
					transparent:!el.opts.editmode,
					resize : function(e, ui){
						$el.tagBoxMoveEditBox(el, $el);
						if(typeof(el.opts.updateevent) != 'undefined')
							el.opts.updateevent(el, e, ui);
					}, 
					stop : function(e, ui){
						$el.tagBoxMoveEditBox(el, $el);
						if(typeof(el.opts.updateevent) != 'undefined')
							el.opts.updateevent(el, e, ui);
					}
				})
            	.resizable("disable")
            	.hover(
					function(){ 
						if(el.opts.editmode)
						{
            	    		$el.resizable("enable")
                			   .draggable("enable");
                		}
					}, 
		        	function(){
						if(el.opts.editmode)
						{
	            			$el.resizable("disable") 
            		       	   .draggable("disable"); 
            			}
                	}
            	)
            	.css({
            		cursor: 'move'
            	});
            	
            if(el.opts.editmode)
            {
            	if(typeof(el.opts.touchelement) != 'undefined')
            	{
            		el.opts.touchelement.click(function(e){
            			el.opts.editing = true;
		            	$el.tagBoxMoveTo(
		            		e.pageX, 
	    	        		e.pageY, 
	        	    		function(sender, newx, newy){
    		    	    		if(typeof(el.opts.touchfunc) != 'undefined')
	    	        				el.opts.touchfunc(sender, newx, newy);
	            			})
	            			.show()
							.tagBoxMoveEditBox(el, $el);
	    	        })
	            }
    	        if(typeof(el.opts.editelement) != 'undefined')
    	        {
   	        		el.opts.editelement.find(":button[@name='cancel']").each(function(){
 	        			$(this).click(function(e){
 	        				$el.tagBoxCancel();
   	        			});
   	        		});
    	        	el.opts.editelement.find('form').submit(function(a, b){
    	        		var datas = {};
    	        		var hasnullvalue = false;
    	        		el.opts.editelement.find(':input').each(function(){
    	        			var $input = $(this);
    	        			var name=$input.attr('name');
    	        			var value=$input.attr('value');
    	        			if(typeof(value) != 'undefined')
    	        			{
    	        				if(value == "")
    	        					hasnullvalue = true;
    	        				datas[name] = value;
    	        			}
    	        		});
    	        		if(hasnullvalue)
    	        		{
    	        			alert("不能有空值");
    	        			return false;
    	        		}
    	        		var tagdata = $el.data('tagdata');
    	        		if(typeof(tagdata) == 'undefined' || typeof(tagdata.tag_id) == 'undefined' || tagdata.tag_id == 0)
    	        		{
    	        			datas['mode'] = 'i';
							datas['tag_id'] = 0;
    	        		}
						else
						{
							datas['mode'] = 'u';
							datas['tag_id'] = tagdata.tag_id;
						}
						datas['img_uid'] = tagdata.img_uid;
    	        		datas['tag_type'] = 1;
    	        		datas['tag_x'] = parseInt($el.css("left")) || 0;
    	        		datas['tag_y'] = parseInt($el.css("top")) || 0;
    	        		datas['tag_width'] = $el.width();
    	        		datas['tag_height'] = $el.height();

    	        		$.post(el.opts.opurl, datas, function(xmlData, textStatus){
    	        			var xml;
						    if (jQuery.browser.msie) {
        						xml = new ActiveXObject( 'Microsoft.XMLDOM');
        						xml.async = false;
        						xml.loadXML(xmlData);
    						} else {
        						xml = xmlData;
    						} 
    	        			
    	        			if(textStatus == 'success')
    	        			{
	    	        			var $xml = $(xml);
    		        			$r = $xml.find('response');
    		        			var r = {
    	    	    				code: $r.attr('code'),
    	        					msg : $r.text()
    	        				};
    	        				if(r.code != 0)
    	        				{
    	        					alert('Error(' + r.code + ') : ' + r.msg);
    	        					return ;
    	        				}
    	        				
    	        				$tag = $xml.find('tag');
    	        				var tag = {
    	        					id: $tag.attr('tag_id'),
    	        					name: $tag.attr('tag_name')
    	        				};
    	        				
    	        				datas.tag_id = tag.id;
   	        					$el.data('tagdata', datas);
    	        				
   	        					if(typeof(el.opts.tageventupdate) != 'undefined')
   	        					{
   	        						if(datas['mode'] == 'i')
   	        						{
   	        							el.opts.tageventupdate("insert", datas);
   	        						}
   	        						else
   	        							el.opts.tageventupdate("update", datas);
   	        					}
    	        			}
    	        			else
    	        			{
    	        				alert(textStatus);
    	        			}
    	        			$el.tagBoxCancel();
    	        		});
    	        		return false;
    	        	});
    	        }
    	    }
		});		
	},
	tagBoxGetData : function() {
		var $el = $(this);
		var datas = $el.data('tagdata');
		return datas;
	},
	tagBoxSetData : function(img_uid, tag_id) {
		return this.each(function(){
			var el = this, $el = $(this);
			$el.data('loading', true);

        	if(typeof(el.opts.bindimageevent) != 'undefined')
				el.opts.bindimageevent(img_uid);
			
   			var	$taglist = el.opts.taglistelement;
			var datas = $el.data('tagdata');
			// 如果 datas 不存在或者 datas.img_uid 跟 img_uid 不同，表示是要重置
			if(typeof(datas) == 'undefined' || datas.img_uid != img_uid)
			{
   	        	if(typeof(el.opts.tageventupdate) != 'undefined')
					el.opts.tageventupdate("empty", null);
				
				// $taglist.empty(); 		// 清空所有 tag
				datas = {
					mode: 'l',			// list command
					img_uid: img_uid,
					tag_id: tag_id
				};
				$el.data('tagdata', datas);
				api_tag_post(el.opts.opurl, datas, function(xmlData, textStatus){
				// $.post(el.opts.opurl, datas, function(xmlData, textStatus){
    	        	var xml;
					if(jQuery.browser.msie) {
        				xml = new ActiveXObject( 'Microsoft.XMLDOM');
        				xml.async = false;
        				xml.loadXML(xmlData);
    				} else {
        				xml = xmlData;
    				}
					if(textStatus == 'success')
					{
    		        	$r = $('response', xml);
    		        	var r = {
    	    	    		code: $r.attr('code'),
    	        			msg : $r.text()
    	        		};
    	        		if(r.code != 0)
    	        		{
    	        			alert('Error(' + r.code + ') : ' + r.msg);
    	        			return ;
    	        		}

    	        		$('customer_permission', xml).each(function(index){
    	        			$self = $(this);
	    	        		var customer_permission = {
	    	        			'show_info': $self.attr('show_info')
    		        		};
			   	        	if(typeof(el.opts.tageventupdate) != 'undefined')
								el.opts.tageventupdate("permission", customer_permission);
    		       			$el.data('customerpermdata', customer_permission);
    	        		});

    	        		$('customer', xml).each(function(index){
    	        			$self = $(this);
	    	        		var customer = {
	    	        			'img_uid': img_uid,
    		        			'customer_id': $self.attr('customer_id'),
    		        			'account': $self.attr('account'),
    		        			'company': $self.attr('company'),
    		        			'owner': $self.attr('owner'),
    		        			'photo': $self.attr('photo'),
    		        			'moblie': $self.attr('moblie'),
    		        			'class': $self.attr('class'),
    		        			'area': $self.attr('area'),
    		        			'address': $self.attr('address'),
    		        			'tel': $self.attr('tel'),
    		        			'fax': $self.attr('fax'),
    		        			'email': $self.attr('email'),
    		        			'website': $self.attr('website'),
    		        			'blog': $self.attr('blog'),
    		        			'longitude': $self.attr('longitude'),
    		        			'latitude': $self.attr('latitude'),
    		        			'rank': $self.attr('rank'),
    		        			'intro': $self.attr('intro')
    		        		};
			   	        	if(typeof(el.opts.tageventupdate) != 'undefined')
								el.opts.tageventupdate("customer", customer);
    		       			$el.data('customerdata', customer);
    	        		});

    	        		$('case', xml).each(function(index){
    	        			$self = $(this);
	    	        		var caseinfo = {
	    	        			'img_uid': img_uid,
    		        			'case_id': $self.attr('case_id'),
    		        			'case': $self.attr('case_name'),
    		        			'style': $self.attr('case_style'),
    		        			'price': parseInt($self.attr('case_price')) || 0,
    		        			'dimension': parseInt($self.attr('case_dimension')) || 0,
    		        			'type': $self.attr('case_type'),
    		        			'status': $self.attr('case_status'),
    		        			'pattern': $self.attr('case_pattern'),
    		        			'desc': $self.attr('case_desc'),
    		        			'rank': $self.attr('case_rank')
    		        		};
			   	        	if(typeof(el.opts.tageventupdate) != 'undefined')
								el.opts.tageventupdate("case", caseinfo);
    		       			$el.data('casedata', caseinfo);
    	        		});


    	        		$('photo', xml).each(function(index){
    	        			$self = $(this);
	    	        		var photoinfo = {
	    	        			'img_uid': img_uid,
    		        			'space': $self.attr('space'),
    		        			'rank': $self.attr('rank')
    		        		};
			   	        	if(typeof(el.opts.tageventupdate) != 'undefined')
								el.opts.tageventupdate("space", photoinfo);
    		       			$el.data('space', photoinfo['space']);
    	        		});

						var casetag = {
	    	        		img_uid: img_uid,
    		        		tag_id: 0,
    		        		tag_name: '',
    		        		tag_type: 5,
    		        		tag_x: 0,
    		        		tag_y: 0,
    		        		tag_width: 0,
    		        		tag_height: 0
						};
    	        		$('tag', xml).each(function(index){
    	        			$self = $(this);
	    	        		var tag = {
	    	        			img_uid: img_uid,
    		        			tag_id: $self.attr('tag_id'),
    		        			tag_name: $self.attr('tag_name'),
    		        			tag_type: $self.attr('tag_type'),
    		        			tag_x: $self.attr('tag_x'),
    		        			tag_y: $self.attr('tag_y'),
    		        			tag_width: $self.attr('tag_width'),
    		        			tag_height: $self.attr('tag_height')
    		        		};
			   	        	if(typeof(el.opts.tageventupdate) != 'undefined')
			   	        	{
								el.opts.tageventupdate("insert", tag);
							}
    	        		});
					}
					else
        			{
        				alert(textStatus);
        			}
        			$el.data('loading', false);
				});
			} 
			else
			{
				$taglist.find('.image-tag-name[@id=' + tag_id + ']').each(function(){
					datas = $el.data('tagdata');
					datas['mode'] = 'u';
					$el.data('tagdata', datas);
/*						
						.css({
							left: datas['tag_x'],
							top: datas['tag_y'],
							width: datas['tag_width'],
							height: datas['tag_height']
						})
						.tagBoxMoveEditBox(el, $el);
							
	   	    		if(typeof(el.opts.touchfunc) != 'undefined')
		   				el.opts.touchfunc(sender, datas['tag_x'], datas['tag_y']);
*/				
				});
				$el.data('loading', false);
			}
		});
	},
	tagBoxCancel : function() {
		return this.each(function(){
			var el = this, $el = $(this);
			var tagdatas = $el.data('tagdata');
			datas = $.extend({}, tagdatas, {tag_id: 0});
			$el.data('tagdata', datas);
			
			$el.hide()
				.css({
					width: '90px',
					height: '90px'
				});
        	if(typeof(el.opts.editelement) != 'undefined')
        	{
	        	el.opts.editelement.hide();
    	        el.opts.editelement.find('form').each(function(){
    	        	this.reset();
    	        });
    	    }
    	    el.opts.editing = false;
    	});
	},
	isTagBoxEditing : function() {
		var el = this.get(0);
		return el.opts.editing;
	},
	tagBoxToEdit : function(tagdatas) {
		return this.each(function(){
			var el = this, $el = $(this);
			
   			el.opts.editing = true;
   			
           	$el.css({
           		left: tagdatas.tag_x + 'px',
           		top: tagdatas.tag_y + 'px',
           		width: tagdatas.tag_width + 'px',
           		height: tagdatas.tag_height + 'px'
           	});

    		if(typeof(el.opts.touchfunc) != 'undefined')
	   			el.opts.touchfunc(this, tagdatas['tag_x'], tagdatas['tag_y']);
	   		
       		el.opts.editelement.find(':input').each(function(){
       			var $input = $(this);
       			var name=$input.attr('name');
				$input.attr('value', tagdatas[name]);
      		});

			$el.data('tagdata', tagdatas)
			   .show()
			   .tagBoxMoveEditBox(el, $el);
		});
	},
	tagBoxShow : function(tagdatas) {
		return this.each(function(){
			var el = this, $el = $(this);
			if(el.opts.editing)
				return ;
			
           	$el.css({
           		left: tagdatas.tag_x + 'px',
           		top: tagdatas.tag_y + 'px',
           		width: tagdatas.tag_width + 'px',
           		height: tagdatas.tag_height + 'px'
           	});

    		if(typeof(el.opts.touchfunc) != 'undefined')
    		{
    			var tag_x = parseInt(tagdatas['tag_x']);
    			var tag_y = parseInt(tagdatas['tag_y']);
	   			el.opts.touchfunc(this, tag_x, tag_y);
	   		}
			$el.show();
    	});
	},
	tagBoxHide : function() {
		return this.each(function(){
			var el = this, $el = $(this);
			if(el.opts.editing)
				return ;
           	$el.css({
           		width: '90px',
           		height: '90px'
           	});
			$el.hide();
    	});
	},
	tagBoxRemoveTag : function(tagdatas) {
		return this.each(function(){
			var el = this, $el = $(this);
			if(el.opts.editing)
				return ;
			
			datas = {
				mode: 'd',			// delete command
				tag_id: tagdatas['tag_id']
			};
			
			$.post(el.opts.opurl, datas, function(xmlData, textStatus){
    	       	var xml;
				if(jQuery.browser.msie) {
        			xml = new ActiveXObject( 'Microsoft.XMLDOM');
        			xml.async = false;
        			xml.loadXML(xmlData);
    			} else {
        			xml = xmlData;
    			}
				if(textStatus == 'success')
				{
    		       	$r = $('response', xml);
    		       	var r = {
    	        		code: $r.attr('code'),
    	       			msg : $r.text()
    	       		};
    	       		if(r.code != 0)
    	       		{
    	       			alert('Error(' + r.code + ') : ' + r.msg);
    	       			return ;
    	       		}
    	       		tagdatas['tag_type'] = 1;
	   	        	if(typeof(el.opts.tageventupdate) != 'undefined')
						el.opts.tageventupdate("delete", tagdatas);
				}
				else
       			{
       				alert(textStatus);
       			}
			});
    	});
	},
	tagBoxMoveEditBox : function(el, $el) {
		return this.each(function(){
			if(typeof(el.opts.editelement) != 'undefined')
   	    	{
				var	elinfo = {
					left: parseInt($el.css("left")) || 0,
					top: parseInt($el.css("top")) || 0
				};
				// var elinfo = $el.offset();
				
				var newxy = {
					x: elinfo.left - el.opts.editelement.width() - 10,
					y: elinfo.top
				};
            	if(typeof(el.opts.touchelement) != 'undefined')
            	{
					$ct = el.opts.touchelement;
					var tinfo = {
						left: parseInt($ct.css("left")) || 0,
						top: parseInt($ct.css("top")) || 0
					};
            		// var tinfo = el.opts.touchelement.offset();
            		
            		var bottom = elinfo.top + el.opts.editelement.height();
            		if(bottom > tinfo.top + el.opts.touchelement.height())
            		{
            			newxy.y = tinfo.top + $ct.height() - el.opts.editelement.height() - 5;
            		}
            		
            		var right = elinfo.left + $el.width()/2;
            		if(right < tinfo.left + el.opts.touchelement.width()/2)
            		{
            			newxy.x = elinfo.left + $el.width() + 10;
            		}
				}
   	      		el.opts.editelement.css({
   	    			position: 'absolute',
   	    			zIndex: 100,
   	    			left: newxy.x + 'px',
   	    			top: newxy.y +'px'
   	    		});
   	    		var space = $el.data('space');
   	    		if(typeof(space) != 'undefined')
   	    		{
   	    			if(typeof(tag_name) != 'undefined')
   	    			{
   	    				if(typeof(tag_name[space]) != 'undefined')
   	    				{
	   	    				var html = "";
   		    				var space_names = tag_name[space];
   	    					for(var i=0; i<space_names.length; i++)
	   	    				{
   		    					html += "<li>" + space_names[i] + "</li>";
   	    					}
	   	    				var $tag_name_helper = $("#tag_name_helper");
   		    				$tag_name_helper.html(html);
   	    					$("#tag_name_helper > li")
	   	    					.click(function(){
   		    						var selectname = $(this).text();
   	    							el.opts.editelement.find(":input").each(function(){
   	    								var inputname = $(this).attr('name');
   	    								if(inputname == 'tag_name')
   	    								{
	   	    								$(this).attr('value', selectname);
   		    							}
	   	    						});
   		    					})
   	    						.hover(
   	    							function(){
   	    								$(this).css({
   	    									color: '#ffffff',
   	    									backgroundColor: '#8393AD'
   	    								});
	   	    						},
   		    						function(){
   	    								$(this).css({
   	    									color: '#444444',
   	    									backgroundColor: '#C3D3ED'
   	    								});
   	    							}
   	    						);
   	    				}
   	    				else
   	    				{
   	    					$("#tag_name_helper").html("空間[<font color='red'>" + space + "</font>]不是標準空間，<br>請先更改到標準空間再進行編輯。");
   	    				}
   	    			}
   	    			else
   	    			{
   	    				$("#tag_name_helper").html("tagname.js 不存在.");
   	    			}
   	    		}
   	    		el.opts.editelement.show();
   			}
   		});
	},
	tagBoxMoveTo : function(newx, newy, complateFunc){
		return this.each(function(){
  			var el=this, $el=$(this);
  			var $parent = $el.parent();
			var parentofs = $parent.offset();
			var parentsize = {
				width: $parent.width(),
				height: $parent.height()
			}
			var parent = {
				left: parentofs.left,
			    right: parentofs.left + parentsize.width,
				top: parentofs.top,
				bottom: parentofs.top + parentsize.height,
				width: parentsize.width,
				height: parentsize.height
			};
			var margin = {
				right: parseInt($el.css("marginRight")) || 0,
				left: parseInt($el.css("marginLeft")) || 0,
				top: parseInt($el.css("marginTop")) || 0,
				bottom: parseInt($el.css("marginBottom")) || 0
			};
			margin.width = margin.right-margin.left;
			margin.height = margin.top-margin.bottom;
			
			var tagbox = {
				width: $el.width() + margin.width,
				height: $el.height() + margin.height
			};
			var tx = newx-tagbox.width/2;
			var ty = newy-tagbox.height/2;
			if(tx<parent.left)
			{
				tx = parent.left;
			}
			else if(tx+tagbox.width >= parent.right)
			{
				tx = parent.right-tagbox.width-1;
			}
			if(ty < parent.top)
			{
				ty = parent.top;
			}
			else if(ty+tagbox.height >= parent.bottom)
			{
				ty = parent.bottom-tagbox.height-1;
			}
			tx -= parent.left;
			ty -= parent.top;
			$el.css({
				left: tx+'px',
				top: ty+'px'
			});
			if(typeof(complateFunc) != 'undefined')
				complateFunc(el, tx, ty);
		});
	}
});
