Element.extend({
	 amongTo:function(elp,opts){
		var el=this;
		var elSize=el.getSize(),
		elpSize=elp.getSize();
		
		var options={width:2,height:2};
		if(opts){options=$merge(options,opts);}
		el.setStyles({
		'position':'absolute',
		'opacity':1
		});
		var pos={
		'top':Math.abs(((elpSize.size.y/options.height).toInt())-((elSize.size.y/options.height).toInt())+elp.getPosition().y+elpSize.scroll.y),
		'left':Math.abs(((elpSize.size.x/options.width).toInt())-((elSize.size.x/options.width).toInt())+elp.getPosition().x+elpSize.scroll.x)
		}
		if(options.Fx){
		 new Fx.Styles(el).start(pos);
		}else{
		 el.setStyles(pos);
		}
		return this;	
	 },
	 zoomImg:function(maxwidth,maxheight,v){
	   if(this.getTag()!='img'||!this.width)return;
       var thisSize={'width':this.width,'height':this.height};
		   if (thisSize.width>maxwidth){
		      var overSize=thisSize.width-maxwidth;
			  var zoomSizeW=thisSize.width-overSize;
			  var zommC=(zoomSizeW/thisSize.width).toFloat();
			  var zoomSizeH=(thisSize.height*zommC).toInt();
			  $extend(thisSize,{'width':zoomSizeW,'height':zoomSizeH});
		   }
		   if (thisSize.height>maxheight){
		      var overSize=thisSize.height-maxheight;
			  var zoomSizeH=thisSize.height-overSize;
			  var zommC=(zoomSizeH/thisSize.height).toFloat();
			  var zoomSizeW=(thisSize.width*zommC).toInt();
			  $extend(thisSize,{'width':zoomSizeW,'height':zoomSizeH});
		   }
	   if(!v)return this.set(thisSize);
	   return thisSize;
	 },
	 subText:function(count){
	    var txt=this.get('text');
		if(!count||txt.length<=count)return txt;
		this.setText(txt.substring(0,count)+"...");
		if(!this.retrieve('tip:title'))
		this.set('title',txt);
		return txt;
	 },
	 getValues:function(){
		var values = {};
		this.getFormElements().each(function(el){
			var name = el.name;
			var value = el.getValue();
			if (value === false || !name || el.disabled) return;
			values[el.name] = value;
		});
		return values;
	 },
	 getAttrs:function(){
		var attrs = this.attributes;
		var ret={};
		for(var i=attrs.length-1;i>-1;i--){
			ret[attrs[i].nodeName] = attrs[i].nodeValue;
		}
		return ret;
	 },
	 getPositionAs:function(elp){
	 	return this.getPosition($(elp));
	 },
	 getPadding:function(){
	 	return {
			'x':this.getStyle('padding-left').toInt()||0+this.getStyle('padding-right').toInt()||0,
			'y':this.getStyle('padding-top').toInt()||0+this.getStyle('padding-bottom').toInt()||0
		}
	 },
	 getMargin:function(){
	 	return {
			'x':this.getStyle('margin-left').toInt()||0+this.getStyle('margin-right').toInt()||0,
			'y':this.getStyle('margin-top').toInt()||0+this.getStyle('margin-bottom').toInt()||0
		}
	 },
	 getBorderWidth:function(){
	 	return {
			'left':this.getStyle('border-left-width').toInt()||0,
			'right':this.getStyle('border-right-width').toInt()||0,
			'top':this.getStyle('border-top-width').toInt()||0,
			'bottom':this.getStyle('border-bottom-width').toInt()||0,
			'x':this.getStyle('border-left-width').toInt()||0+this.getStyle('border-right-width').toInt()||0,
			'y':this.getStyle('border-top-width').toInt()||0+this.getStyle('border-bottom-width').toInt()||0
		}
	 },
	 copyWidth:function(el){
	 	try{
	 	this.setStyle('width',
		el.getSize().size.x-(el.getPadding().x+el.getMargin().x)-(el.getBorderWidth().left+el.getBorderWidth().right)
		);
		}catch(e){this.setStyle('width',200)};
	 },
	 copyHeight:function(el){
	 	try{
	 	this.setStyle('height',
		el.getSize().size.y-(el.getPadding().y+el.getMargin().y)-(el.getBorderWidth().left+el.getBorderWidth().right)
		);
		}catch(e){
			this.setStyle('height',200);
		}
	 },
	 toggle:function(){
		this.setStyle('display',(this.style.display=='none'?'':'none'));
	 },
	 getTrueWidth:function(){
	 return this.getSize().size.x-(
	 this.getMargin().x+
	 this.getPadding().x+
	 this.getBorderWidth().left+
	 this.getBorderWidth().right
	 );
	 },
	 getTrueHeight:function(){
	  return this.getSize().size.y-(
	 this.getMargin().y+
	 this.getPadding().y+
	 this.getBorderWidth().top+
	 this.getBorderWidth().bottom
	 );
	 },
	 getCis:function(){
			return this.getCoordinates();
		},
	 getContainer:function(){
			try{
			  var el=$(this);
			  do{
			   el=el.getParent();
			  }while(!el.getProperty('container') && el)
			  return el;
			}catch(e){return false}
		},
	  bindValidator:function(vipt_className){
               vipt_className=vipt_className||'_x_ipt';
		       var status=true;
				var errorIndex=[];
				var f=this;
                elements=f.getElements('.'+vipt_className);
                if(!elements||!elements.length)return status;
				elements.each(function(el,idx){
						var vv=validator.test(f,el);
						if(!vv){
						  errorIndex.push(idx);
                          status=false;
						}
				});
				if(!status){
				     var el=elements[errorIndex[0]];
                      try{
                     if(el&&el.getStyle('display')!='none'&&el.getStyle('visibility')!='hidden')
                     el.focus();
                     }catch(e){}
				}
		        return status;
		},
	  show:function(){
	  this.fireEvent('onshow',this);
	  return 	$chk(this)?this.setStyle('display',''):this;
	  },
	  hide:function(){
	  this.fireEvent('onhide',this);
	   return 	$chk(this)?this.setStyle('display','none'):this;
	  },
      isDisplay:function(){
         if(this.getStyle('display')=='none'||(this.offsetWidth+this.offsetHeight)==0){
            return false;
         }
         return true;
      },
	  toggleDisplay:function(){
		 return 	$chk(this)&&this.getStyle('display')=='none'?this.setStyle('display',''):this.setStyle('display','none');
	  },
	  fixPNG:function(){
	     	if (window.ie6) {
				var el = $(this);
					var iconsrc = el.getStyle('backgroundImage').replace(/url\(|\)/g,'');
					 el.setStyle('background','none');
				     el.setStyle('filter',
		            "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" +iconsrc+ ", sizingMethod=scale)");
			}
			//console.info(iconsrc);
			return this;
	  },
	  getFormElementsPlus:function(ft){
	   var elements=[];
	   var nofilterEls=$$(this.getElements('input'), this.getElements('select'), this.getElements('textarea'));
       if(ft){
           nofilterEls=nofilterEls.filter(ft);
       }
	    nofilterEls.each(function(el){
		  var name = el.name;
		  var value = el.getValue();
		  if(!name||!value)return;
		  if(el.getProperty('type')=='checkbox'||el.getProperty('type')=='radio'){
                 if(el.getProperty('checked'))
				 return elements.include($(el).toHiddenInput());
                 return;
			 }
		  elements.include(el);
		});
		return $$(elements);
	  },
	  toHiddenInput:function(){
	  return  new Element('input',{'type':'hidden','name':this.name,'value':this.value});
	  },
	  getParentWithScroll:function(){
	     var e=this;
		 do{
		 e=e.getParent();
		 }
		 while((e.getSize().size.y>=e.getSize().scrollSize.y)&&e.id!='main')
		 return e;
	  },
	   getParentMatch:function(m){
	     if(!m)return this.getParent();
	     var e=this;
		 do{
		 e=e.getParent();
		 }
		 while(e.getTag()!='body'&&!!m(e))
		 return e;
	  }
	});
  String.extend({
	  format:function(){
        if(arguments.length == 0)
          return this;
         var reg = /{(\d+)?}/g;
         var args = arguments;
		 var string=this;
         var result = this.replace(reg,function($0, $1) {
           return  args[$1.toInt()]||"";
          }
     )
     return result;
  }
});

Window.implement({
         withUStatus:function(callback){
                 if(window.uStatus)
                 return  callback(window.uStatus);

                  window.addEvent('domready',function(){
                      if(!!(window.uStatus=new ViewState())){
                          callback(window.uStatus);
                       }else{
                          window.addEvent('load',function(){
                            callback(window.uStatus=new ViewState());
                          });
                       }
                  });
         }
     });


var ItemAgg=new Class({
  options:{
   onActive:Class.empty,
   onBackground:Class.empty,
   show:0,
   eventName:'click',
   activeName:'cur',
   firstShow:true
  },
  initialize:function(tabs,items,options){
     this.setOptions(options);
	 this.tabs=$$(tabs);
	
	 this.items=$$(items);
	 this.items.setStyle('display','none');
     this.tempCurIndex=this.options.show||0;
     
	 if(this.options.firstShow){
	    this.show(this.tempCurIndex);
     }
	 this.tabs.each(function(item,index){
	    item.addEvent(this.options.eventName,function(e){
		  e=new Event(e).stop();
		  this.tabs[index].blur();
		  if(this.tempCurIndex!=index){
              this.show(index);
              this.hide(this.tempCurIndex);
              this.tempCurIndex=index;
		  }
		}.bind(this));
	 },this);
  },
  show:function(index){
    this.items[index].show();
	this.tabs[index].addClass(this.options.activeName);
	this.fireEvent('onActive',[this.tabs[index],this.items[index]],this);
  },
  hide:function(index){
    this.items[index].hide();
	this.tabs[index].removeClass(this.options.activeName);
	this.fireEvent('onBackground',[this.tabs[index],this.items[index]],this);
  }
});

ItemAgg.implement(new Events, new Options);



/*finx IE6 SELECT*/
function $fixSelectOpacity(v,exclude){
    if(!window.ie6)return;
    exclude=$ES('select',exclude);
    $$('select').filter(function(sel){
	       return !exclude.contains(sel);
	}).setOpacity(v);
}

/* clean null Object*/
function $cleanNull(){
	var obj=arguments[0];
	for(p in obj){
	  if(!obj[p])
	  delete(obj[p]);
	}
	return obj;
};

/*viewIMG*/
function viewIMG(src,eventEl){
   var el=$(eventEl);
   el.addClass('viewIMG_Loading');
   var imgViewBox=($('imgViewBox')||new Element('div',{'id':'imgViewBox'}).setStyles({
    'border':'4px #000 solid',
	'padding':2,
	'background':'#ffffff',
	'position':'absolute',
	'zIndex':65535,
	'top':-2000
   }).inject(document.body))
   .empty().setHTML("<div style='padding:5px;'><span style='display:block;text-align:right;cursor:pointer;border-top:1px #ccc solid;' onclick='$(\"imgViewBox\").hide()'>关闭</span></div>");
    var _IMG= new Asset.image(src,{onload:function(){
				  var img=$(this);
				  if(img.$e)return;
			      img.injectTop(imgViewBox); 
				  imgViewBox.show().amongTo(window);
				  el.removeClass('viewIMG_Loading');
				  img.$e=true;
			},onerror:function(){alert("加载图片失败");el.removeClass('viewIMG_Loading');}});
}
function popPanel(url,options){
    var pp=$('popPanel')||new Element('div',{
	'id':'popPanel',
	'class':'popPanel',
	'styles':{
	'position':'absolute',
	'top':0,
	'left':0,
	'opacity':0,
	'zoom':1,
	'border':'8px #6b94ad solid',
	'display':'none',
	'zIndex':65000,
	'background':'#ffffff',
	'overflow':'hidden'
	}
	}).inject(document.body);
	window.MODALPANEL.show();
    $('loadMask').amongTo(window).show();
	var opt={
	  update:pp,
	  evalScripts:true,
	  onComplete:function(){
	    window.MODALPANEL.hide();
        $('loadMask').hide();
		$(pp).setStyles({
		  width:window.getSize().size.x-16,
		  height:window.getSize().size.y-16
		  }
		).setOpacity(1).show();
	  }
	};
	if(options)opt=$merge(opt,options);
	new Ajax(url,opt).request();
} 

function selectArea(sel,path,depth){		
    var sel=$(sel);
    if(!sel)return;	
	
    var sel_value=sel.value;
    var sel_panel=sel.getParent();
    var selNext=sel.getNext();
    var areaPanel= sel.getParentMatch(function(e){
           return !e.getAttribute('package');
        });
    var hid=areaPanel.getElement('input[type=hidden]');
    
    var setHidden=function(sel){
        var rst=[];
		var sel_break = true;
        var sels=$ES('select',areaPanel);
		sels.each(function(s){
		  if(s.getValue()!= '_NULL_' && sel_break){
			  rst.push($(s.options[s.selectedIndex]).get('text'));
		  }else{
		    sel_break = false;
		  }
		});		
		
        if(sel.value != '_NULL_'){			
			$E('input',areaPanel).value = areaPanel.get('package')+':'+rst.join('/')+':'+sel.value;				
		}else{			
		    $E('input',areaPanel).value =function(sel){
                          var s=sels.indexOf(sel)-1;
                          if(s>=0){
                             return areaPanel.get('package')+':'+rst.join('/')+':'+sels[s].value;
                          }
                          return '';
            }(sel);			
		}
     	hid.retrieve('onselect',$empty)(sel);
    };
	if(sel_value=='_NULL_'&&selNext&&(selNext.getTag()=='span' && selNext.hasClass('x-areaSelect'))){
		sel.getNext().empty();
        setHidden(sel);
	}else{
		/*nextDepth*/
		var curOption=$(sel.options[sel.selectedIndex]);
		if(curOption.get('has_c')){
		  new Request({
				onSuccess:function(response){					
					if(selNext && 
						(selNext.getTag()=='span'&& selNext.hasClass('x-region-child'))){
						var e = selNext;
					}else{
						var e = new Element('span',{'class':'x-region-child'}).inject(sel_panel);
					}
					function timeTag(){
						if($E('input',areaPanel)){
							$clear(timeobj);
							setHidden(sel);							
							if(response){
								e.set('html',response);
			                    if(hid){
		                           hid.retrieve('sel'+depth,$empty)();
		                           hid.retrieve('onsuc',$empty)();
		                        }
							}else{
								sel.getAllNext().remove();
								setHidden(sel);
								hid.retrieve('lastsel',$empty)(sel);
							}
						}else{
							$E('input',areaPanel);			
						}	  	
				   }
		 			var timeobj= timeTag.periodical(100);	
				}
			}).get('index.php?ctl=tools&act=sel_region&p[0]='+path+'&p[1]='+depth+'&t='+$time());
            
		}else{
		    sel.getAllNext().remove();
            setHidden(sel);
			
            if(!curOption.get('has_c')&&curOption.value!='_NULL_')
            hid.retrieve('lastsel',$empty)(sel);		
           
		}
	}
}

var loadingMask=new Abstract({
     show:function(caution){
        ($('loadingMask')||new Element('div',{styles:{
           position:'absolute',
           left:0,
           top:0,
           zIndex:65535,
           padding:2,
           background:'#ff3300',
           color:'#ffffff',
           opacity:.8
        },
        text:caution||'正在加载...',
        id:'loadingMask'
        }).inject(document.body)).setStyles({'display':'block','top':window.getScrollTop()});
     },
     hide:function(){
      if($('loadingMask'))$('loadingMask').setStyle('display','none');
     }
});


/*fix Image size*/
var fixProductImageSize=function(images,ptag){
        if(!images||!images.length)return;
         images.each(function(img){
             if(!img.src)return;
             new Asset.image(img.src,{
                  onload:function(){
                  var imgparent=img.getParent((ptag||'a'));
                  if(!this||!this.get('width'))return imgparent.adopt(img);
				  var imgpsize={x:imgparent.getTrueWidth(),y:imgparent.getTrueHeight()};
				  var nSize=this.zoomImg(imgpsize.x,imgpsize.y,true);
                  img.set(nSize);
                  var _style={'margin-top':0};
                  if(img&&img.get('height'))
                  if(img.get('height').toInt()<imgpsize.y){
    				     _style=$merge(_style,{'margin-top':(imgpsize.y-img.get('height').toInt())/2});
    				  }
                     img.setStyles(_style);
                     return true;
                  },onerror:function(){
                    
                  }
             });
         });
};