
/*
	[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 login_s = register_s = logout_s = lost_s = logout = register = login = lost = '';
		var uname = Cookie.get('S[UNAME]');
			uname = uname ? '<em>' + uname + '</em>' : '';
		var s = $_CONFIG['lang']['welcome'].replace(/\{username\}/, uname);

		if(!Cookie.get('S[MEMBER]')){
			login='<a href="' + $_SHOPBASE + 'passport-login.html">' + $_CONFIG['lang']['login'] + '</a> | ';
			register = '<a href="' + $_SHOPBASE + 'passport-signup.html">' + $_CONFIG['lang']['signup'] + '</a> | ';
			lost = '<a href="' + $_SHOPBASE + 'passport-lost.html">' + $_CONFIG['lang']['lost'] + '</a> | ';
			login_s = $_CONFIG['lang']['login_s'].replace(/\{login\}/, login);
			register_s = $_CONFIG['lang']['signup_s'].replace(/\{register\}/, register);
			lost_s = $_CONFIG['lang']['lost_s'].replace(/\{lost\}/, lost);
		}else{
			logout = '<a href="'+$_SHOPBASE+'passport-logout.html">' + $_CONFIG['lang']['logout'] + '</a> | ';
			logout_s = $_CONFIG['lang']['logout_s'].replace(/\{logout\}/, logout);
		}
		s = s.replace(/\{register\}/, register)
			.replace(/\{login\}/, login)
			.replace(/\{lost\}/, lost)
			.replace(/\{logout\}/, logout)
			.replace(/\{login_s\}/, login_s)
			.replace(/\{register_s\}/, register_s)
			.replace(/\{lost_s\}/, lost_s)
			.replace(/\{logout_s\}/, logout_s);

		document.write('<ul class="ducenavs">'+s+'</ul>')
	},

	goSearch: function(f){
		f.action = this.searchurl ? this.searchurl : ($_SHOPBASE+'search-result.html')
	},

	initHead: function () {

		this.showItemSet = false;
		var _this = this;
		window.addEvent('domready',function(){
			_this.fixGoodsImgSize($$('.goodpic','.goodsImg','.dComment .pic','.goods-detail-pic-thumbnail a'));
			_this.fixGoodsImgSize($$('.goods-detail-pic'),'middle');
		});

		/*初始化搜索框*/
		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($_find($_CONFIG['lang']['defaultkeywords'],this.value))	this.value = '';
				this.setStyle('borderColor', '#C00');
			};
			k.onblur = function(){
				this.setStyle('borderColor', '');
			};
			f.onsubmit = function(){
				if($_find($_CONFIG['lang']['defaultkeywords'],this.value)){ 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(all){
		if(this.showItemSet){
			return;
		}
		var _this = this;
		this.showItemSet = true;
		
		var cats = $ES('.border_item .c-cat-depth-1');
		if(!cats[0]) return;

		if( !all ) {
			var u = $_LOCAL, n;
			if($_find('product', u)){
				u = ( n = $ES('.Navigation a') ) && n.length ? $_findext(n[n.length-1].href) : u;
			}
			var u = this.furl(u);
			all = !u ? true : all;
		}

		var config = $_CONFIG['cats']||{};
		var pcats = $$('.priceItem .c-cat-depth-1 a[href]');

		cats.each(function(cat, i){
			var a = $ES('a', cat);
			if($_CONFIG['cats_bg']&&!pcats.contains(a[0])) {
				a[0].className = 'toggle-cat d-cat-' + i;
			}
			var show = all||false;
			if( config[i] ) {
				show = show||$_find(config[i], $_LOCAL)||u==_this.furl(a[0].href);
				a[0].href = $_SHOPBASE + config[i];
			}

			if ( show ){
				if ( a[1] )	cat.addClass('cat_current');
			}
			else{
				for ( var ii = 0; ii < a.length; ii++ ) {
					if( $_LOCAL == a[ii].href || u == _this.furl(a[ii].href) ){
						a[ii].addClass('now');
						if ( a[1] )	cat.addClass('cat_current');
						break;
					}
				}
			}
			if ( a[1] ) {
				new Element('cite', {
					'title': $_CONFIG['lang'][cat.hasClass('cat_current')?'to_close':'to_open'],
					'events': {
						'click': function(){
							if( this.getParent().hasClass('cat_current') ) {
								this.title = $_CONFIG['lang']['to_open'];
								this.getParent().removeClass('cat_current');
							}else{
								this.title = $_CONFIG['lang']['to_close'];
								this.getParent().addClass('cat_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 z=o&&o!='middle'?true:false;
		if(z&&o.retrieve('size')){
			var f=o.retrieve('size');
		}else{
			var f=this.getTrueSize(c,p);
			if(z){o.store('size',f);}
			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,'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';
		}
		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;
		}
		if(m.y<f.y&&o!='middle'){
			s['margin-top']=((f.y-m.y)/2).toInt();
		}
		/*if(img.getParent('.ducerank-hot')) {
			alert(f.x+'-'+f.y);
			//alert(this.getImgWard(img).x+'-'+this.getImgWard(img).y);
		}*/
		p.setStyles(s);
	},

	fixGoodsImgSize: function(ss,o){
		//return;
		var _this=this;
		ss.each(function(c,i){
			var p=c.getElement('img');
			var u=p.get("init_src")||p.get("src");
			if(!u||p.retrieve('resized')){return}
			new Asset.image(u, {
				onload:function(){
					//var g=p.getParent();
					if(!this||!this.width){
						return //g.adopt(p)
					}
					//if(!i) alert(this.get("height"));
					_this.zoomImg(p,this,c,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') : '');
				}
			});
		}
	},
	
	fmtUrl: function(u) {
		if ( $_find( '.', u, 1 ) ){
			var href = $_findend('shopadmin', $_LOCAL, -1);
			var k = '';
			var p = ( $_findend('/', href, -1) + '/' + u).replace(/\/\.\//, '/').split(':')[1].split('/');
			for(var i=0; i<p.length; i++){
				if( p[i] == '..' || p[i] == '.') continue;
				if( p[i+1] != '..') {
					k += p[i] + '/';
				}
			}
			return 'http:' + k.replace(/\/+$/, '/');
		}
		return $_SHOPBASE + u;
	},
	
	addrow: function ( obj, data, direct ) {
		if ( typeof data != object )
			return;

		var table, tr, row;
		direct = isNaN(direct) ? -1 : parseInt(direct);
		table = obj.getParent("table");

		if ( direct == -1 || obj.tagName.toLowerCase() == 'table' ) {
			row = table.insertRow(direct);
		}else {
			tr = obj.getParent("tr");
			row = direct ? table.insertRow(tr.rowIndex + 1) : table.insertRow(tr.rowIndex);
		}

		for ( var i = 0; i < data.length; i++ ) {
			var cell = row.insertCell(i);
			cell.colSpan = data[i][0];
			if (data[i][2]) {
				cell.className = data[i][2];
			}
			cell.innerHTML = data[i][1];
		}
	},
	
	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;
	}

};
