
/*
	[DUCEDIS] (C)2009-2011 ducedis.com
    This is a freeware, use is subject to license terms
    Script filename：dmb.js

    Support: www.ducedis.com

*/

void ($dmb = {

	version:"1.0.2",

	/*
	string 规定被搜索的字符串
	needle 规定要查找的字符串
	mode 截取模式 1=返回字符串头至最先出现处的字符串(包含要查找的字符串) 不指定参数返回字符串头至最先出现处的字符串(不包含要查找的字符串)
	*/
	strchr: function(string, needle, mode){
		if(!string || !needle) return string;
		var pos = string.indexOf(needle)>0 ? string.indexOf(needle) : 0;
		if(pos){
			string = string.substr(0, pos + (mode ? needle.length : 0));
		}
		return string.replace(/^(\/)*(index\.php)?(\?)?/i, '').replace(/%2C/ig, ',');
	},
		
	/*
	string 规定被搜索的字符串
	needle 规定要查找的字符串
	mode 截取模式 0=返回某字符串最后出现处起的字符串 1=返回字符串头至最后出现处的字符串(包含要查找的字符串) -1=返回字符串头至最后出现处的字符串(不包含要查找的字符串)
	fo 可选，如果指定参数则返回最后出现fo至最后出现needle间的字符串，mode必须指定1/-1
	*/
	strrchr: function(string, needle, mode, fo){
		if(!string || !needle) return string;
		var pos = string.indexOf(needle)>0 ? string.lastIndexOf(needle) : 0;
		var cut = fo && string.indexOf(fo)>0 ? string.lastIndexOf(fo) : 0;
		if(pos){
			string = !mode ? string.substr(pos) : string.substr(cut, pos + (mode == 1 ? needle.length : 0) - cut);
		}
		return string
			.replace(/^(\/)*(index\.php)?(\?)?/i, '')
			.replace(/%2C/ig, ',')
			.replace(/_ANY_/ig, '')
	},
	
	/*
	全局配置参数及DOM完成后执行的函数
	*/
	global: function(){
		window.$_config = window.$_fiximg = {};
		this.browserQString = this.strrchr(location.href, '/');
		this.screen = 0;
		this.leftColumn = 200;
		this.initCats = false;
		this.fixImgEls = new Array();
		var _this = this;		
		window.addEvent('domready', function(){$try(_this.OutEnd())})
	},

	/*
	重定位分类链接函数
	*/
	catsInit: function(els, toggle, s){
		var cats;
		if((this.initCats && !s) || !(cats = $$(els))) return;
		this.initCats = true;
		var _this = this;
		var currented = onSel = false;
		var id = 0;
		cats.each(function(cat, i){
			if(!cat.hasClass('cat-custom')){
				var a = cat.getElements('a');
				if(!a) return;
				if($_config['cats'] && $_config['cats'][id]){
					a[0].href = ($_config['cats'][id].test(/^http/) ? '' : _this.baseurl) + $_config['cats'][id];
				}
				id++;
				if(toggle != 'all'){
					if(!currented && _this.contUrl(a[0].href)){
						cat.addClass('current');
						currented = true;
					}
				}
				if(toggle && (toggle == 'all' || cat.hasClass('current'))){
					cat.addClass('c_toggle');
				}
				if(toggle && a[1]){
					if(!onSel) a.each(function(o){if(_this.contUrl(o.href)){o.addClass('onSel');cat.addClass('c_toggle');onSel=true;}});
					new Element('cite', {
						'events': {'click': function(){(cat.hasClass('c_toggle') ? $try(cat.removeClass('c_toggle')) : cat.addClass('c_toggle'))}}
					}).injectBefore(a[0]);
				}
			}
		});
	},
	
	fixPush: function(el){
		this.fixImgEls.push(el);
	},

	fixImgSize: function(ss, cell){
		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;
			if(img.getSize().x<10){
				img.setStyle('opacity', 0);
				box.setStyle('background','url("./statics/loading.gif") no-repeat center');
			}
			new Asset.image(src, {
				onload:function(){
					if(!this || !this.width){
						return img.store('resized',true).getParent().adopt(img.setStyle('opacity',1));
					}
					_this.imgZoom(img, this, box, cell);
				}
			})
		});
	},
	
	imgZoom: function(img, imgbuff, box, cell){
		box.setStyle('background','none');
		var box = img.getParent().getStyle('display') == 'block' ? img.getParent() : box;
		var f = this.getTrueSize(box, img);
		
		if(f.x < 1 || f.y < 1) return;

		var m = {x: imgbuff.get('width'), y: imgbuff.get('height')};
		var s = {width: m.x, height: m.y, opacity: 1};
		var a = cell == 'intro' ? 'w' : $_fiximg['p_align'];
		switch(a){
			case 'h':
				s['width'] = s['height'] = 'auto';
				s['max-width'] = m.x;
				if(m.y > f.y){
					s['height'] = f.y;
					m.x = (f.y*m.x/m.y).toInt();
				}
				s['width'] = m.x;
				if(m.x > f.x){
					s['margin-left'] = ((f.x-m.x)/2).toInt();
				}
				break;
			case 'w':
				s['width'] = s['height'] = 'auto';
				s['max-height'] = m.y;
				if(m.x > f.x){
					s['width'] = f.x;
					m.y = (f.x*m.y/m.x).toInt();
				}
				if(m.y > f.y){
					s['margin-top'] = ((f.y-m.y)/2).toInt();
				}
				break;
			default:
				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 && !['middle','intro'].contains(cell)){
			s['margin-top'] = ((f.y-m.y)/2).toInt();
		}
		img.setStyles(s).store('resized',true)//.fade('in');
	},

	/*
	修正getTrueSize兼容性BUG
	*/
	getPadding: function(o){
		return {
			x: (o.getStyle('padding-left').toInt()||0)+(o.getStyle('padding-right').toInt()||0),
			y: (o.getStyle('padding-top').toInt()||0)+(o.getStyle('padding-bottom').toInt()||0)
		}		
	},
	
	getMargin: function(o){
		return {
			x: (o.getStyle('margin-left').toInt()||0)+(o.getStyle('margin-right').toInt()||0),
			y: (o.getStyle('margin-top').toInt()||0)+(o.getStyle('margin-bottom').toInt()||0)
		}
	},
	
	getBorderWidth: function(o){
		return {
			left: o.getStyle('border-left-style')=='none' ? 0 : o.getBorderWidth().left,
			right: o.getStyle('border-right-style')=='none' ? 0 : o.getBorderWidth().right,
			top: o.getStyle('border-top-style')=='none' ? 0 : o.getBorderWidth().top,
			bottom: o.getStyle('border-bottom-style')=='none' ? 0 : o.getBorderWidth().bottom
		}
	},

	getBorder: function(o){
		var b = this.getBorderWidth(o);
		return {x: b.left + b.right, y: b.top + b.bottom}
	},

	getTrueSize: function(box, img){
		var o = img ? img.getParent() : null;
		var i = img ? this.getPadding(img) : {x:0, y:0};
		var n = !o || $(o) == $(box) ? i : {
			x: this.getPadding(o).x+this.getMargin(o).x+this.getBorder(o).x+i.x, 
			y: this.getPadding(o).y+this.getMargin(o).y+this.getBorder(o).y+i.y
		};
		var p = this.getPadding(box);
		var b = this.getBorder(box);
		//var m = this.getMargin(box);
		return {
			x:box.getSize().size.x-(p.x+b.x+n.x), 
			y:box.getSize().size.y-(p.y+b.y+n.y)
		}
	},

	contUrl: function(url){
		if(!this.request) this.request = this.parse(this.browserQString);
		if(url == location.href) return true;
		var pros = this.parse(url);
		if(pros['ctl'] == this.request['ctl'] && pros['args']['id'] == this.request['args']['id'] && pros['act'] == this.request['act']){
			var c1 = pros['args'].length; 
			var c2 = this.request['args'].length;
			if(c1 == c2 && c1 > 1){
				for(var k in pros['args']){
					if(pros['args'][k] != this.request['args'][k]) return false;
				}
			}
			return c1 == c2 ? true : false;
		}
		return false;
	},

	gotop: function(scroll){
		if(!this._gotop){
			this._gotop = new Element('a', {
				'class': 'gotop', 
				'styles': {cursor: 'pointer', position: window.ie6 ? 'absolute' : 'fixed', zIndex: 10, bottom: '10%', display: 'none'},
				'events': {'click': function(){$(document.body).scrollTo(0); this.setStyle('display', 'none'); return false;}}
			}).inject(document.body);
			var _this = this;
			window.addEvents({
				'scroll': function(){_this.gotop(1)},
				'resize': function(){_this.gotop()}
			});
		}
		if(scroll){
			if(window.getScrollTop() < 200){
				this._gotop.setStyle('display', 'none');
			}else{
				this._gotop.setStyle('display', 'block');
				if(window.ie6) this._gotop.setStyle('top', window.getScrollTop()+window.getHeight()-150);
			}
			return;
		}
		var main_w = this.screen ? 1200 : this.wrap_width;
		var body_w = window.getWidth();
		var float_x = main_w/2 + (body_w/2) + 5;
		
		this._gotop.setStyle('left', float_x + 20 > body_w ? body_w-25 : (float_x <= main_w + 5 ? main_w+5 : float_x));
	},
	
	parse: function(query){
		var ctl, act = 'index', args = {id: 0}, pros = [], k;
		if(pros = this.strrchr(query, '.', -1, '/').split('-')){
			if((ctl = pros.shift()) && ctl != 'index'){
				var c = pros.length;
				if(c > 0 && isNaN(pros[c-1])){
					act = pros.pop();
				}
			}
			args['id'] = pros[0] ? pros[0] : 0;
			if(pros[1] && pros[1].test(',')){
				pros = pros[1].split('_');
				for(var i=0;i<pros.length;i++){
					switch((k = pros[i].substr(0,1))){
						case 'b': 
						case 't': 
						case 'p': args[k] = pros[i].substr(2);
					}
				}
			}
		}
		return {ctl: ctl, act: act, args: args};
	},
	
	OutEnd: function(){
		this.wrap_width = $('ducedis_wrap').getSize().x;
		if(this.fixImgEls){
			for(var i=0; i<this.fixImgEls.length; i++){
				$try(this.fixImgSize($$(this.fixImgEls[i])));
			}
		}
		if(!this.request) this.request = this.parse(this.browserQString);
		if(window.ie6 && this.request['ctl'] == 'product' && $('goods-intro')){
			$('goods-intro').getElements('img').each(function(p){
				var u = p.get("init_src")||p.get("src");
				if(!u) return;
				new Asset.image(u, {
					onload:function(){
						if(!this||!this.width){
							return p.getParent().adopt(p);
						}
						var f = $dmb.getTrueSize($('goods-intro'),p);
						var s = {'width':this.width, 'height': this.height};
						if(this.width > f.x){
							s['width'] = f.x;
							s['height'] = f.x*this.height/this.width;
							p.setStyles(s);
						}						
					}
				});
			})
		}
		this.gotop();
		if($_config['favlink']){
			$$('a[fav=1]').addEvent('click', function(){
				if(document.all) window.external.addFavorite($_config['favlink']['host'], $_config['favlink']['title']);
				else if(window.sidebar) window.sidebar.addPanel($_config['favlink']['title'], $_config['favlink']['host'], "");
			});
		}
	},

	/*下拉迷你购物车*/	
	miniCart: function(handle, evt){
		var updateCart = function(){
			try{$$('.cart-number').set('text', Cookie.get('S[CART_NUMBER]')||0);}catch(e){}
		};
		if(handle){
			evt = new Event(evt).stop();
			$(handle).getNext().remove();
			new Request.HTML({update:$('duce_cart_popup'),url:$(handle).get('urlremove'), data:$(handle).getParent('form'), onComplete:function(){updateCart()}}).send();
			return false;
		}
		var __shopCart = $E('.duce_shopCart');
		if(!__shopCart) return;
		var duce_cart_popup = null;
		var remoteUrl = this.mkUrl('cart', 'viewCart');
		__shopCart.addEvents({
    		'mouseenter':function(){
				if(!duce_cart_popup){
					if(this.getStyle('position') != 'absolute') this.setStyle('position', 'relative');
					duce_cart_popup = new Element('div',{
						'id':'duce_cart_popup',
						'styles':{position:'absolute',display:'none',width:242,right:0,top:this.getSize().y}
					}).injectInside(this);
				}
				if(this.hasClass('duce_shopCart_over')) return;
				var _this = this.addClass('duce_shopCart_over');
				new Request({
					url: remoteUrl,
					method:'post',
					onComplete: function(re){
						if(re && _this.hasClass('duce_shopCart_over')){
							duce_cart_popup.set('html',re).show();
							//_this.getElement('.cart-container').set('href', 'javascript:void(0);');
							updateCart();
						}
					}
				}).send();
			},
			'mouseleave': function(){this.removeClass('duce_shopCart_over');duce_cart_popup.hide();}
		});
	},
	
	/*openfloatWin: function(scr, w, h){
		w = w ? w : 680;
		h = h ? h : 480;
		if(!$('myfloatWin')){
			new Element('div',{'id':'myfloatWin','class':'dialog mini-passport-dialog'}).set('html',$E('#template-modal .dialog').get('html').substitute({
			title:'',content:''})).setStyles({
				'position':'absolute',
				'z-index':10000,
				'display':'none'
			}).inject(document.body);
		}
		$('myfloatWin').getElement('.dialog-content').empty().adopt(new Element('iframe',{
			src: scr,
			styles:{border:'none'},
			width:w,
			height:h
		}));

		$('myfloatWin').show().amongTo(window);
	},*/

	mkUrl: function(ctl, act, args){
		var url = this.baseurl + ctl;
		if(args && $type(args) == 'array'){
			for(var i=0; i<args.length; i++){
				url += '-' + args[i];
			}
		}
		return url + (!act || act == 'index' ? '' : '-'+act) + '.html';
	}

}).global();

