//ie6 css 背景缓存
if (/* @cc_on @_jscript_version === 5.6 || @ */false) try {document.execCommand("BackgroundImageCache", false, true);} catch (err) {}

//FIXME: ie的userData存储区只能用于同一目录和对同一协议进行存储
/* Browser Storage */
(function(){if(!(window.google&&google.gears)){var c=null;if(typeof GearsFactory!="undefined")c=new GearsFactory;else try{c=new ActiveXObject("Gears.Factory");c.getBuildInfo().indexOf("ie_mobile")!=-1&&c.privateSetGlobalObject(this)}catch(g){if(typeof navigator.mimeTypes!="undefined"&&navigator.mimeTypes["application/x-googlegears"]){c=document.createElement("object");c.style.display="none";c.width=0;c.height=0;c.type="application/x-googlegears";document.documentElement.appendChild(c)}}if(c){window.google|| (google={});if(!google.gears)google.gears={factory:c}}}})(); (function(){function c(){return g.init()||h.init()||i.init()||j.init()||false}window.BrowserStore={isReady:false,initialize:function(){this.storage=c()||{};this.isReady=true},set:function(a,b){this.isReady||this.initialize();this.storage.setStorage(a,b?jQuery.toJSON(b):null);return this},get:function(a,b){this.isReady||this.initialize();this.storage.getStorage(a,b)},remove:function(a){if(!a||!this.storage)return false;this.storage.removeStorage(a);return this},clear:function(){if(!this.storage)return false; this.storage.clearStorage();return this}};var g={name:"Google Gears",init:function(){var a;try{if(a=google.gears.factory.create("beta.database")){a.open("Asa_database");a.execute("create table if not exists status (skey text, sval text)");this.db=a;this.Master="gears"}else return false}catch(b){return false}return this},setStorage:function(a,b){var d=this.db.execute("select * from status where skey=?",[a]);if(d.isValidRow()){this.db.execute("update status set sval=? where skey=?",[b,a]);d.close()}else this.db.execute("insert into status values (?,?)", [a,b])},getStorage:function(a,b){var d=this.db.execute("select * from status where skey=?",[a]);d.isValidRow()?b(d.field(1)):b();d.close()},removeStorage:function(a){this.db.execute("delete from status where skey=?",[a])},clearStorage:function(){this.db.execute("drop table status")}},h={name:"globalStorage",init:function(){if(!window.globalStorage)return false;this._storage=globalStorage[location.hostname];return this},setStorage:function(a,b){this._storage.setItem(a,b);return true},getStorage:function(a, b){var d=this._storage.getItem(a);b(d?d.value:null)},removeStorage:function(a){this._storage.removeItem(a);return true},clearStorage:function(){if(this._storage.clear)this._storage.clear();else for(c in this._storage)this._storage[c].value&&this.remove(c);return true}},i={name:"userdata",init:function(){this.Master="ie6+";if(!$.browser.msie)return false;var a=document.createElement("span");a.style.display="none";a.style.behavior="url('#default#userData')";document.body.appendChild(a);this._storage= a;return this},setStorage:function(a,b){this._storage.setAttribute(a,b);this._storage.save("AsaData");return true},getStorage:function(a,b){this._storage.load("AsaData");b(this._storage.getAttribute(a))},removeStorage:function(a){this._storage.removeAttribute(a);this._storage.save("AsaData");return true},clearStorage:function(){var a=new Date;a.setMinutes(a.getMinutes()-1);this._storage.expires=a.toUTCString();this._storage.save("AsaData");this._storage.load("AsaData");return true}},j={name:"openDatabase", init:function(){if(!window.openDatabase)return false;this._storage=window.openDatabase("viewState","1.0","Asa Storage",2E4);this._createTable();return this},setStorage:function(a,b){this._storage.transaction(function(d){d.executeSql("SELECT v FROM SessionStorage WHERE k = ?",[a],function(f,e){e.rows.length>0?f.executeSql("UPDATE SessionStorage SET v = ? WHERE k = ?",[b,a]):f.executeSql("INSERT INTO SessionStorage (k, v) VALUES (?, ?)",[a,b])})});return true},getStorage:function(a,b){this._storage.transaction(function(d){v= d.executeSql("SELECT v FROM SessionStorage WHERE k = ?",[a],function(f,e){if(e.rows.length>0)return b(e.rows.item(0).v);b(null)})})},removeStorage:function(a){this._storage.transaction(function(b){b.executeSql("DELETE FROM SessionStorage WHERE k = ?",[a])});return true},clearStorage:function(){this._storage.transaction(function(a){a.executeSql("DROP TABLE SessionStorage",[])});return true},_createTable:function(){this._storage.transaction(function(a){a.executeSql("SELECT COUNT(*) FROM SessionStorage", [],$empty,function(b){b.executeSql("CREATE TABLE SessionStorage (k TEXT, v TEXT)",[],$empty)})})}}})();

/*Protype*/
String.prototype.cnLength = function()
{
  return this.replace('/[^\x00-\xff]/ig',"**").length;
};
if (typeof $ENV == "undefined")
{
	$ENV = {};
}
$ENV.cookie_pre = 'QINBEI_e526_';
$ENV.cookie_domain = '';
$ENV.cookie_path = '/';
$ENV.user = { hasCheck:0, isLogin:0, username:'', userid:0 };

QB = {};
QB.pkg = function (ns)
{
    if (!ns || !ns.length) {
        return null;
    }
    var levels = ns.split(".");
    var nsobj = QB;
    for (var i = (levels[0] == "QB") ? 1 : 0; i < levels.length; ++i) {
        nsobj[levels[i]] = nsobj[levels[i]] || {};
        nsobj = nsobj[levels[i]];
    }
    return nsobj;
};

QB.pkg('Utils');
if (typeof Utils == "undefined") {
    Utils = QB.Utils;
}

QB.pkg("Utils.Cookie");
Utils.Cookie.getCookie = function (name)
{
	return jQuery.cookie( $ENV.cookie_pre + name ) || '';
};
Utils.Cookie.setCookie = function (name, value, expire)
{
	jQuery.cookie( $ENV.cookie_pre+name, value, {expires: 7, path:$ENV.cookie_path, domain:$ENV.cookie_domain });
};
Utils.Cookie.deleteCookie = function (name)
{
	jQuery.cookie( $ENV.cookie_pre+name, null);
};
Utils.addFavorite = function( url, title )
{
    if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addPanel == 'function'))
    {
        window.sidebar.addPanel(title,url,"");
    }
    else
    {
        window.external.AddFavorite(url,title);
    }
    return false;
};
Utils.setHomepage = function( url ){
    if (document.all){  
    	document.body.style.behavior = 'url(#default#homepage)';  
    	document.body.setHomePage( url );  
    }else if (window.sidebar){  
        if (window.netscape){  
            try {  
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
            }catch (e) {
            	alert("抱歉，您所使用的浏览器无法完成此操作。\n\n您需要手动将'http://www.qinbei.com/'设置为首页。");
            }  
        }
        else
        {
	        try {
	        	var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);  
	        	prefs.setCharPref('browser.startup.homepage', url); 
	        }catch(e) {
	        	alert("抱歉，您所使用的浏览器无法完成此操作。\n\n您需要手动将'http://www.sina.com.cn/'设置为首页。");
	        }
        }
    }
};

/*product*/
P = {};
P._model = [];
P.loadModel = function( mName ){
	if( typeof( this._model[mName] )=='function')
	{
		P[mName]=P._model[mName]();
		return true;
	}
	throw mName+' model is not exist';
};
P.addModel = function( mName, fun )
{
	if( typeof( this._model[mName] )!='undefined')
	{
		throw mName+' model is exist,will be override';
	}
	if( typeof( fun )=='function' )
	{
		P._model[mName] = fun;
	}
	else
	{
		throw 'Register model error,it`s not a function';
	}
};

P.checkLogin = function()
{
	if( $ENV.user.hasCheck )
	{
		return $ENV.user.isLogin;
	}	
	else
	{
		var auth = Utils.Cookie.getCookie( 'auth' );
		var info = Utils.Cookie.getCookie( 'USER_INFO' ).split('+');
		//var info = decodeURI(Utils.Cookie.getCookie( 'USER_INFO' )).split('+');
		$ENV.user.hasCheck = 1;
		if( auth && info.length>=2 )
		{
			$ENV.user.isLogin = 1;
			$ENV.user.username = info[0];
			$ENV.user.userid = info[1];	
		}
		else
		{
			$ENV.user.isLogin = 0;
		}
		return $ENV.user.isLogin;
	}
};

P.addModel('count',function(){
	var orbit = [
	             [20,-2, 0.8],
	             [22,-3, 0.7],
	             [24,-4, 0.6],
	             [28,-6, 0.4],
	             [32,-8, 0.3],
	             [36,-10,0.2],
	             [36,-10, 0 ]
	         ];
	var that = {};
	that.isVoted = false;
	that.animation = function(num){
		var _num = num.clone().css({
			position: 'absolute',
			left: 0,
			top: 0
		});
		num.after(_num);
		var current = 1;
		var width = _num.get(0).offsetWidth;
		var oL = orbit.length;
		var animation = function()
		{
			if( current == oL )
			{
				num.text( (parseInt(num.text()) || 0)+1 )
				_num.text((parseInt(_num.text()) || 0)+1);
			}
			if( current>=oL*2 )
			{
				clearInterval(t);
				_num.remove();
				num.removeAttr('style');
				return false;
			}
			var left = (width-_num.width())/4; //todo:文字无法居中
			var now = oL-Math.abs(current-oL)-1;
			_num.css({fontSize:orbit[now][0],top:orbit[now][1]+1,opacity:orbit[now][2],left:left});
			num.css({opacity:orbit[now][2]});
			current++;
		};
		var t = setInterval( animation,25 );
	};
	that.addGood = function()
	{
		if( this.isVoted ) return false;
		var num = $('#pCountGoodNum span').first();
		$product.count.good++;
		$.get('/count_good.html', { p: $product.key } );
		this.animation(num);
		this.update();
		this.isVoted = true;
		return true;
	};
	that.addBad = function()
	{
		if( this.isVoted ) return false;
		var num = $('#pCountBadNum span').first();
		$product.count.bad++;
		$.get('/count_bad.html', { p: $product.key } );		
		this.animation(num);
		this.update();
		this.isVoted = true;
		return true;
	};
	that.update = function()
	{
		var good = parseInt($product.count.good);
		var bad = parseInt($product.count.bad);
		var total = good+bad;
		var gw = good/total*100+'%';
		var bw = bad/total*100+'%';
		$('#pCountGoodBar').css({width:gw});
		$('#pCountBadBar').css({width:bw});
	};
	return that;
});

P.addModel('comment',function(){
var form = $('#comment-form');
// form.after( '<iframe id="form-iframe-comment" name="form-iframe-comment" style="display:none"></iframe>' );
var isInit = false;
$('#comments-textarea textarea').hover(function(){
	if( !P.checkLogin() ) $('#comments-textarea-tip').removeClass('hidden');
	else $('#comments-textarea-tip').addClass('hidden');
})
$('#comment-submit').click(function(){
	if( !P.checkLogin() ){
		alert('你没有登录，请先登录！');
		return false;
	}
	var valid = true;
	form.find('select,input,textarea').each(function(){
		var name = $(this).attr('name');
		var value = $(this).val();
		switch ( name ) {
			case 'title':	//点评标题
				if(value.cnLength()<2){
					alert('评价标题应不少于2个字');
					valid = false;
					return false;
				}
				if(value.cnLength()>25){
					alert('评价标题多于25个字');
					valid = false;
					return false;
				}
			break;
			case 'buy_place':	//购买地点
				if(value=='0') {
					alert('请填写"购买地点"');
					valid = false;
					return false;
				}
			break;
			case 'buy_price':	//购买价格
				if(!/^[1-9][0-9]{0,5}(\.[0-9]+)?$/.test(value)) {
					alert('请填写正确的"购买价格"');
					valid = false;
					return false;
				}
				break;
			case 'm'://产品质量
				if(!value) {
					alert('请为产品"质量"打分');
					valid = false;
					return false;
				}
				break;

			case 'content':			//内容
				if(value.cnLength()<10){
					alert('评价内容应不少于10个字');
					valid = false;
					return false;
				}
				if(value.cnLength()>500){
					alert('评价内容多于500个字请精简一下');
					valid = false;
					return false;
				}
				break;
		}
	});
	
	if( !isInit )
	{
		$('#form-iframe-comment').load(function(){
			$('#comment-submit').nextAll('.tip').remove();
			var json = $.trim( $(this).contents().find("body").text() );
			try {
				var jData = jQuery.parseJSON( json );
				if( jData.result ){
					alert('提交成功，感谢您的参与，谢谢！');
					window.location=window.location;
				}else{
					alert('发生错误，请重试');
				}
			} catch ( e ) {
				alert('发生错误，请重试');
			}
		});
		isInit = true;
	}
	if(valid) {
		// form.attr( {'target':'form-iframe-comment', 'action': '/comment_add.html?p='+$product.key});
		// $(this).attr('disabled',true);
		
		form.attr( { 'action': '/comment_add.html?p='+$product.key});
	//	$(this).after('<span class="tip">提交中...</span>');
		form.get(0).submit();
	}

});
	

});

P.addModel('funcDoing',function(){
	var buttons=$('#funcDoing a');
	var funcmsg=$('#funcDoingMsg span');
	var doing={
		a:function(){
			funcmsg.text('正在提交中...');
			this.request('touse');
		},
		b:function(){
			funcmsg.text('正在提交中...');
			this.request('using');
		},
		c:function(){
			funcmsg.text('正在提交中...');
			this.request('used');
		},
		request:function( doing )
		{
			$.ajax({
				  url: "/passport_doing.html",
				  data:{'uid':$product.uid,'do':doing},
				  cache: false,
				  dataType:'json',
				  success: function( json ){
				    if( json.result )
				    {
				    	alert('操作成功');
				    	$('#funcDoingMsg span').text( json.msg );
				    	$('#funcDoingMsg a').removeClass( 'hidden' );
				    }
				    else
				    {
				    	alert( json.msg );
				    }
				  }
				});	
		}
		
	};
	
	buttons.click(function(){
		if( !P.checkLogin() ){ alert('您还没有登录,请先登录'); return false; }
		if( $(this).attr('disabled') ){ alert('已经做过该操作！'); return false; }
		buttons.removeAttr('disabled');
		if( $(this).hasClass('button-collect-a') ){ $(this).attr('disabled','true'); doing.a(); return false; }
		if( $(this).hasClass('button-collect-b') ){ $(this).attr('disabled','true'); doing.b(); return false; }
		if( $(this).hasClass('button-collect-c') ){ $(this).attr('disabled','true'); doing.c(); return false; }
	})
	$('#funcDoingMsg a').click(function(){
		$.get("/passport_delDoing.html",{'uid':$product.uid});
		buttons.removeAttr('disabled');
		$(this).addClass('hidden');
		funcmsg.text('');
		return false;
	})
});
P.addModel('slider',function(){	
	loopedSlider = {
		total:null,
		now:null,
		slidParent:null,
		slids:null,
		time:null,
		handles:null,
		start:function(){
			loopedSlider.time = setInterval('loopedSlider.next()',3500);
		},
		clearTime:function(){
			clearInterval(loopedSlider.time);
		},
		next:function(index){
			if(index==undefined){
				var prev = loopedSlider.now;
				var next = (prev+1>=loopedSlider.total)?0:prev+1;
				
			}else{
				//相等不执行效果
				if( index==loopedSlider.now ) return;
				var prev = loopedSlider.now;			
				var next = index;
			}
			loopedSlider.slids.eq(prev).animate({opacity:0},{queue:false,duration:500}).removeClass('current');
			loopedSlider.slids.eq(next).animate({opacity:1},{queue:false,duration:500}).addClass('current');
			var href = loopedSlider.slids.eq(next).find('a').attr('href');
			loopedSlider.handles.children().removeClass('current');
			loopedSlider.handles.eq(next).children().addClass('current');
			loopedSlider.shade.attr('href',href);
			loopedSlider.now = next;
		},
		initEvent:function(){
			loopedSlider.handles.bind({
				'mouseover':function(){
					loopedSlider.clearTime();
					var index = loopedSlider.handles.index(this);
					loopedSlider.next(index);
				},
				'mouseleave':function(){
					loopedSlider.start();
				}
			})
		},
		init:function(){
			this.slidParent = $('#slider-list');
			this.slids = this.slidParent.children();
			this.total = this.slids.length;
			this.shade = $('#slider-shade');
			if(!this.total) return false;
			this.handles = $('#slider-btn a');
			this.now = 0;	
			//开始运行
			this.initEvent();
			this.start();
		}
	}
	loopedSlider.init();
});





/*util*/
util = {};

util.toShare = {
	    b_rr: function () {
	        var d = "http://share.xiaonei.com/share/buttonshare.do?link=" + encodeURIComponent(document.location.href) + "&title=" + encodeURIComponent(document.title);
	        if (!window.open(d, "xiaonei", "toolbar=0,resizable=1,scrollbars=yes,status=1,width=626,height=436")) {
	            location.href = d;
	        }
	    },
	    b_kx: function () {
	        var d = "http://www.kaixin001.com/repaste/share.php?rtitle=" + encodeURIComponent(document.title) + "& rurl=" + encodeURIComponent(document.location.href);
	        if (!window.open(d, "kaixin")) {
	            location.href = d;
	        }
	    },
	    b_db: function () {
	        var d = "http://www.douban.com/recommend/?url=" + encodeURIComponent(document.location.href) + "&title=" + encodeURIComponent(document.title);
	        if (!window.open(d, "douban", "toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=330")) {
	            location.href = d;
	        }
	    },
	    b_qq: function () {
	        var d = 'http://shuqian.qq.com/post?from=3&title=' + encodeURIComponent(document.title) + '&uri=' + encodeURIComponent(document.location.href) + '&jumpback=2&noui=1';
	        if (!window.open(
	        d, "qq", 'width=930,height=470,left=50,top=50,toolbar=no,menubar=no,location=no,scrollbars=yes,status=yes,resizable=yes')) {
	            location.href = d;
	        }

	    },
	    b_wb: function () {
	        var f = "http://v.t.sina.com.cn/share/share.php",
	            g = {
	                c: "spr_web_bd_hululady_weibo",
	                url: document.location.href,
	                title: document.title,
	                source: document.title,
	                sourceUrl: document.location.protocol + document.location.host,
	                content: "utf-8"
	            },
	            e = f + "?" + $.param(g);
	        if (!window.open(e, "mb", "toolbar=0,resizable=1,scrollbars=yes,status=1,width=440,height=430,left=" + (screen.width - 440) / 2 + ",top=" + (screen.height - 430) / 2)) {
	            location.href = e;
	        }
	    },
	    b_wy: function () {
	        var f = 'http://t.163.com/article/user/checkLogin.do';
	        var g = 'link=http://blog.163.com/&source=' + encodeURIComponent('挖贝网') + '&info=' + encodeURIComponent(document.title) + ' ' + encodeURIComponent(location.href) + '&' + new Date().getTime();
	        var e = f + '?' + g;
	        if (!window.open(e, "mb", "toolbar=0,resizable=1,scrollbars=yes,status=1,width=560,height=330,left=" + (screen.width - 560) / 2 + ",top=" + (screen.height - 330) / 2)) {
	            location.href = e;
	        }
	    }
};

util.doStar = function( select ){
	var select = $(select);
	if( !select.length ) {
		throw 'until.doStar '+select+'is empty';
		return;
	}
	select.each(function(){
		var stars = $(this).children('.star');
		var parent = $(this);
		var label = ['很差','比较差','还行','好','很好'];
		stars.mouseover(
			function(){
				$(this).nextAll().removeClass("star-hover star-active");
				$(this).addClass('star-hover').prevAll('.star').addClass("star-hover");
			}
		);
		stars.click(function(){
			var index = stars.index(this)+1;
			$(this).parent().attr('active',index);
			var input = $(this).parent().attr('do');
			if( input )
			{
				$('#'+input).val( index );
			}
		});
		$(this).mouseout(function(){
			var index = $(this).attr('active') || 0;
			stars.removeClass('star-hover star-active');
			if(index) stars.slice(0,Number(index)).addClass('star-active');
		});
	});
};

P.addModel('logging',function(){
	if( P.checkLogin() )
	{
		var chip = 
		['<div class="A-sinin">',
			'<div class="A-name" id="A-username"><a class="A-toggle icon icon-useroneline" id="A-login-sign" href="http://baobao.qinbei.com/home-space-do-home.html">' + $ENV.user.username + '</a></div>',
		'</div>',
		'<div class="A-content A-content-menu">',
		'<ul>',
			'<li><a href="http://baobao.qinbei.com/home-space-do-home.html">我的首页</a></li>',
			'<li><a href="http://baobao.qinbei.com/home-spacecp-ac-profile.html">帐号设置</a></li>',
			//'<li><a href="http://baobao.qinbei.com/member-logging-action-logout.html">退出</a></li>',
			'<li><a href="http://baobao.qinbei.com/member.php?mod=logging&action=logout">退出</a></li>',
		'</div>',	
		'</ul>'].join( "\r\n" );
		$('#logging-wrapper').html( chip );
	}
	else
	{
		var chip = 
			['<div class="A-sinin">',
			'<div class="A-name"><a href="http://baobao.qinbei.com/member.php?mod=zhuce">注册</a> / <a class="A-toggle" id="A-login-sign" href="http://baobao.qinbei.com/member.php?mod=logging&action=login">登录</a></div>',
			'</div>',
			'<div class="A-content A-content-form">',
			'<form method="post" action="http://baobao.qinbei.com/member.php?mod=logging&action=login&loginsubmit=yes">',
			'	<p class="textbox">',
			'		<label for="A-username">用户名</label>',
			'		<input type="text" id="A-username" name="username" value="" title="username"></p>',
			'	<p class="textbox">',
			'		<label for="A-password">密码</label>',
			'		<input type="password" id="A-password" name="password" value="" title="password"></p>',
			'	<p class="remember">',
			'		<input type="submit" id="A-submit" value=" 登录 ">',
			'		<input type="checkbox" id="A-remember" name="cookietime" value="2592000">',
			'		<label for="A-remember">记住密码</label>',
			'	</p>',
			'	<p class="forgot">',
			'		<a href="http://baobao.qinbei.com/member.php?mod=logging&action=login&viewlostpw">忘记密码？</a>',
			'	</p>',
			'</form>',
			'</div>'].join("\r\n");
		$('#logging-wrapper').html( chip );
	}
	
	var handle = $('#A-login-sign');
	var wrapper = $('#logging-wrapper');
	var content = $('#logging-wrapper div.A-content');
	function toggle(){ wrapper.removeClass('logging-show'); }
	handle.click(function(){ 
		if( wrapper.hasClass('logging-show') )
		{
			wrapper.removeClass('logging-show');
			$(document).unbind("click",toggle ) ;
		}
		else
		{
			wrapper.addClass('logging-show');
			$(document).bind("click",toggle ) ;
		}	
		return false;
	});
	content.click(function( event ){
		event.stopPropagation();
	});
	
});

