
/*
	[DUCEDIS] (C)2007-2008 Ducedis.com
    This is a freeware, use is subject to license terms
    Script filename：global.js

    Support: www.ducedis.com

*/

/*
查询字符串中是否存在某字符 
fore = 1 表示字符串开头
*/
var $_find = function ( needle, str, fore ){
	var pos=needle?(str+'').indexOf(needle):-1;
	if (pos!=-1) {
		if(fore==1)
			return pos===0?true:false;

		return true
	}
	return false
}

/*
获取字符串中某字符最后出现处起的字符串, 
length = -1 表示前面到某字符最后出现处的字符串
length > 0 表示某字符最后出现处起的字符串截取 length 个字符
length = undefined||0 表示某字符最后出现处起的字符串
*/
var $_findend = function ( needle, str, length ) {
	var pos=$_find(needle,str)?(str+'').lastIndexOf(needle):-1;
	if ( pos != -1 ) {
		if ( length > 0 )
			return str.substr( pos + needle.length, length );

		if ( length == -1 )
			return str.substr( 0, pos );

		return str.substr( pos + needle.length )
	}
	return str
}

/*截获商店URL地址最后出现"/"起的字符串*/
var $_findext = function ( src ) {
	if(!src) return '';
	return $_findend('/', src).replace(/^(index\.php)?(\?)?/i, '').replace(/%2C/ig, ',')
}

var $_IMGDIR = $_findend('/', $('ducedis_r').src, -1); /*模板图片URL目录*/
var $_INADMIN = parent.SHOPADMINDIR ? true : false;
var $_SHOPBASE = $_IMGDIR.replace(/\/themes\/[a-z0-9_\-]+\/images([\/]+)?$/, '/');
var $_LOCAL = location.href.replace(/%2C/ig, ',');

var $_DUCEDIS = {

	showLogin:function(){
		var logout = register = login = lost = '';
		var uname = Cookie.get('S[UNAME]');
			uname = uname ? '<cite>' + uname + '</cite>' : '';
		if(!Cookie.get('S[MEMBER]')){
			var s = $_CONFIG['lang']['logon'];
			login='<a class="login" href="' + $_SHOPBASE + 'passport-login.html">' + $_CONFIG['lang']['login'] + '</a>';
			register = '<a class="signup" href="' + $_SHOPBASE + 'passport-signup.html">' + $_CONFIG['lang']['signup'] + '</a>';
			lost = '<a href="' + $_SHOPBASE + 'passport-lost.html">' + $_CONFIG['lang']['lost'] + '</a>';
		}else{
			var s = $_CONFIG['lang']['logged'] + '<a href="'+$_SHOPBASE+'member.html">会员中心</a>';
			logout = '<a href="'+$_SHOPBASE+'passport-logout.html">' + $_CONFIG['lang']['logout'] + '</a>';
		}
		s = s.replace(/\{username\}/, uname)
			.replace(/\{register\}/, register)
			.replace(/\{login\}/, login)
			.replace(/\{lost\}/, lost)
			.replace(/\{logout\}/, logout);

		document.write('<ul><li class="smember">'+s+'</li></ul>')
	},
	
	goSearch: function(f){
		f.action = this.searchurl ? this.searchurl : ($_SHOPBASE+'search-result.html')
	},

	initHead: function () {

		this.showItemSet = false;
		this.showItemChild('.navbar .GoodsDropNavs .n-cat-depth-1');

		window.addEvent('domready', function(){
			var hotcat = $E('.hotcatsWrap');
			if ( hotcat ) {
			hotcat.getElements('ul').each(function(ul){
				ul.addEvents({
					'mouseenter': function(){this.addClass('current');},
					'mouseleave': function(){this.removeClass('current');}
				})
			});
			}
		});

		/*初始化搜索框*/
		var f = $E('#search .SearchBar');
		if ( f ) {
			var k = $E('.keywords', f);
			var w = $_CONFIG['lang']['keywords'];
			if(!k.value.trim()) k.value = w;
			k.onfocus = function(){
				if(this.value == w)	this.value = '';
				this.setStyle('borderColor', '#C00');
			};
			k.onblur = function(){
				this.setStyle('borderColor', '');
			};
			f.onsubmit = function(){
				if(k.value == w){ MessageBox.error(w + '!!!'); return false;}
			};
			this.searchurl = f.action;
		}

		if(!$E('.header_bannerad').getHTML()){
			$E('.header_bannerad').setStyle('display','none');
		}

	},
	
	gallery: function(){
		this.showItemChild()
	},

	furl: function(url){		
		var pros = $_findext(url).replace(/_ANY_/ig, '').split('-');
		if(pros[2]){
			if(/t,\d+/.test(pros[2])){
				pros[1] += '-' + pros[2].match(/^(.+)?(t,\d+)(.+)?$/)[2];
			}else if(/^p,\d+/.test(pros[2])) {
				pros[1] += '-' + pros[2].match(/^(p(,\d+)+)(.+)?$/)[1];
			}
		}
		return pros[1]
	},

	/* 初始化左边栏商品分类列表 */
	showItemChild: function(spec){
		if(this.showItemSet&&!spec){
			return;
		}
		
		var cats = $ES(spec?spec:'.border_item .dm0-depth-1');
		if(!cats[0]) return;

		var _this=this,
			u=this.furl($_LOCAL),
			n,
			all=false;

		if(!spec){
			this.showItemSet = true;
			all=$E('.border_item li.current')?false:true;
		}

		var reid = 0;
		var config = $_CONFIG['cats']||{};

		cats.each(function(cat){
			var a = $ES('a', cat);
			var show = all||false;
			if(reid || !cat.hasClass('cat-custom')) {
				show = show||$_find(config[reid], $_LOCAL)||u==_this.furl(a[0].href);
				if( config[reid]){a[0].href = ($_find('http://',config[reid],1)?'':$_SHOPBASE) + config[reid];}
				reid++;
			}
			if(spec){return;}
			if(show){
				if(a[1]) cat.addClass('current');
			}
			if(a[1]){
				new Element('cite', {
					'events': {
						'click': function(){
							if( this.getParent().hasClass('current') ) {
								this.getParent().removeClass('current');
							}else{
								this.getParent().addClass('current');
							}
						}
					}
				}).injectBefore(a[0]);
				if ( window.ie6 )
					cat.setStyle('padding-top', '1px');
			}
		});

	},

	//修正tools.js中的getTrueWidth和getTrueHeight错误
	getPadding: function(c){
		return {
			x:(c.getStyle("padding-left").toInt()||0)+(c.getStyle("padding-right").toInt()||0),
			y:(c.getStyle("padding-top").toInt()||0)+(c.getStyle("padding-bottom").toInt()||0)
		}
	},

	getMargin: function(c){
		return {
			x:(c.getStyle("margin-left").toInt()||0)+(c.getStyle("margin-right").toInt()||0),
			y:(c.getStyle("margin-top").toInt()||0)+(c.getStyle("margin-bottom").toInt()||0)
		}
	},
	
	getBorderWidth: function(c){
		return{
			left:c.getStyle('border-left-style')=='none'?0:c.getBorderWidth().left,
			right:c.getStyle('border-right-style')=='none'?0:c.getBorderWidth().right,
			top:c.getStyle('border-top-style')=='none'?0:c.getBorderWidth().top,
			bottom:c.getStyle('border-bottom-style')=='none'?0:c.getBorderWidth().bottom
		}
	},
	
	getBorder: function(c){
		var b=this.getBorderWidth(c);
		return{x:b.left+b.right,y:b.top+b.bottom}
	},

	getTrueSize: function(c,i){
		var n=!i?{x:0,y:0}:this.getImgWard(i,c);
		var p=this.getPadding(c);
		//var m=this.getMargin(c);
		var b=this.getBorder(c);
		return{x:c.getSize().size.x-(p.x+b.x)-n.x,y:c.getSize().size.y-(p.y+b.y)-n.y}
	},
	
	getImgWard: function(p,c){
		var g=p.getParent();
		var k=$(g)==$(c)?{x:0,y:0}:{x:this.getPadding(g).x+this.getMargin(g).x+this.getBorder(g).x,y:this.getPadding(g).y+this.getMargin(g).y+this.getBorder(g).y};
		return{
			x:this.getPadding(p).x+this.getMargin(p).x+this.getBorder(p).x+k.x,
			y:this.getPadding(p).y+this.getMargin(p).y+this.getBorder(p).x+k.y
		}
	},

	zoomImg: function(p,b,c,o){
		var f=this.getTrueSize(c,p);
		if(f.y<p.getSize().y&&!c.getStyle('height').toInt()){
			f.y = p.getSize().y;
		}
		if(f.x<1||f.y<1) return;

		p.store('resized',true);
		var m={x:b.get("width"),y:b.get("height")};

		var s = {'width':m.x-1,'height':m.y};
		if(m.x>f.x){
			m.y=(f.x*m.y/m.x).toInt();
			s['width']=m.x=f.x;
			s['height']=window.ie6?m.y:'auto';
		}else{
			s['width']='auto';
		}
		if(m.y>f.y){
			m.x=(f.y*m.x/m.y).toInt();
			s['width']=window.ie6?m.x:'auto';
			s['height']=m.y=f.y;
		}else{
			s['height']='auto';
		}
		if(m.y<f.y&&o!='middle'){
			s['margin-top']=((f.y-m.y)/2).toInt();
		}
		p.setStyles(s);
	},

	fixGoodsImgSize: function(ss,o){
		//return;
		var _this = this;
		ss.each(function(box,i){
			var img, src;
			if(!(img = box.getElement('img')) || img.retrieve('resized') || !(src = (img.get("init_src") || img.get("src")))) return;
			new Asset.image(src, {
				onload:function(){
					if(!this || !this.width){
						return img.getParent().adopt(img);
					}
					_this.zoomImg(img,this,box,o);
				}
			})
		});
	},

	setLayout: function(){
		var pagelist;
		if((pagelist = $E('.pagelist'))){
			var localurl = $_findext($_LOCAL);
			var isfaq=$E('.pagelist.faq');
			$ES('a', pagelist).each(function(a){
				if(isfaq && a.getParent().hasClass('cat1')){
					a.getParent().addEvent('click',function(e){e.stop();});
				}
				if(!pagelist.retrieve('current')){
					pagelist.store('current', $_findext(a.href)==localurl ? a.addClass('current') : '');
				}
			});
		}
	},
	
	extend: function(){
		var target = arguments[0] || {}, i = 1, length = arguments.length, options;
		if(typeof target != "object" && typeof target != "function")
			target = {};
		if(length == i){
			target = this;
			--i;
		}
		for ( ; i < length; i++ )
			if ( (options = arguments[i]) != null )
				for ( var name in options ) {
					var src = target[name], copy = options[name];
					if ( target === copy )
						continue;
					if ( copy !== undefined )
						target[ name ] = copy;
				}
		return target;
	}

};

