
/*
	[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 uname = Cookie.get('S[UNAME]');
			uname = uname ? '<em>' + uname + '</em>' : '';
		var s = $_CONFIG['lang']['welcome'].replace(/\{username\}/, uname);

		if(!Cookie.get('S[MEMBER]')){
			s += '<cite>[';
			s += '<a href="' + $_SHOPBASE + 'passport-login.html">' + $_CONFIG['lang']['login'] + '</a>';
			s += '|<a href="' + $_SHOPBASE + 'passport-signup.html">' + $_CONFIG['lang']['signup'] + '</a>';
			s += '|<a href="' + $_SHOPBASE + 'passport-lost.html">' + $_CONFIG['lang']['lost'] + '</a>';
			s += ']</cite>';
		}else{
			s += '[<a href="'+$_SHOPBASE+'passport-logout.html">' + $_CONFIG['lang']['logout'] + '</a>]';
		}
		document.write(s)
	},
	
	goSearch: function(f){
		f.action = this.searchurl ? this.searchurl : ($_SHOPBASE+'search-result.html')
	},
	
	cartbtn: function(){
		var btns = { 
			account: 'cart.html',
			myorder: 'member-orders.html'
		};
		var s = '';
		for(var k in btns)
			s += '<a href="' + $_SHOPBASE + btns[k] + '" class="cartbtn ' + k + '"></a>';
		document.write(s)
	},

	initHead: function () {

		this.showItemSet = false;

		window.addEvent('domready', function(){
			var navcurr=false;
			var re = $_LOCAL.replace(/\/+(\?)*$/, '/');
			$$('#menus a').each(function(a, i){
				if(!navcurr){
					if(re==a.href.replace(/\/+(\?)*$/, '/')){
						a.getParent().addClass('current');
						navcurr=true;
					}
				}
			});
		});

		/*初始化搜索框*/
		var f = $E('#search .SearchBar');
		if ( f ) {
			var f = $E('#search .SearchBar');
			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;
		}

	},
	
	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');
			}
		});

	},

	setLayout: function(){
		var customLayout=null, rl=false;
		try{
			customLayout = $E('.resetLeft.bg')||$E('.pagelist')||$E('.priceItem')||$E('.border_item');
			if ( customLayout ){
				customLayout.getParent('.mainbox').addClass('bg');
				rl=true;
			}
			if ( rl||(customLayout = $E('.resetLeft')) ){
				customLayout.getParent().setStyle('width', 185);
			}
			if ( (customLayout = $E('.resetRight')) ){				
				customLayout.getParent().setStyle('margin-left', 0);
				customLayout.getParent().addClass('rightColumn');
			}
		}
		catch(e){}

		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;
	}

};
