tbImgServerId = Math.floor(Math.random()*5+1);
$(document).ready(function() {
	initCommonFunc();
	initMainSearch();
	initURL();
	lazyLoadImg();
	
	setTimeout("lazyLoadImg()", 6000);
});

function lazyLoadImg() {
	$(".lazy-img-loader").each(function(){
		var that = $(this);
		var img = $("img", that);
		var src = img.attr("data-src");
		if (src !== undefined && src !== '') {
			src = $.mz.decodeTbUrl(src);
		}
		if(src == null || src.indexOf("http://") != 0) {
			src = "http://s.mizhe.com/image/icons/no-pic.png";
			img.hide().css("width","50px").attr("src", src);
		} else {
			img.hide().attr("src", src);
		}
		img.load(function(){
			if(this.complete) {
				that.removeClass("lazy-img-loader");
				img.fadeIn();
			}
		});
	});
}

function initURL() {
	if(typeof(g) == "undefined") {
		return;
	}
	var server = $.base64Decode(g.__b__);

	$(".redirect-tbk").each(function() {
		var dataCfg = $(this).attr('data-config');
		if(dataCfg === undefined || dataCfg === '') {
			return;
		}
		dataCfg = $.mz.parseJSON(dataCfg);
		// 重要！参数顺序不可调整，半角空格为IE hack
		var url = " " + server + "rebate/detail/" + dataCfg.type + "-" + dataCfg.nick + "-" + dataCfg.id + ".html?p=" + dataCfg.p + "&target=" + dataCfg.target + "&r=" + dataCfg.r + "&stop=" + (dataCfg.stop!=undefined ? dataCfg.stop : "");
		$(this).attr("rel","nofollow").attr("href", url).removeClass("redirect-tbk").mousedown(function(){
			var clickData = "trace=tbkclick&t=" + dataCfg.type + "&i=" + dataCfg.id + "&nick=" + dataCfg.nick + "&p=" + dataCfg.p + "&r=" + dataCfg.r + "&g=" + dataCfg.target;
			var img = new Image();
			img.src = "http://stat.mizhe.com/tracelog/click.html?" + clickData + "&_t=" + new Date().getTime();
		});
	});
}

function initCommonFunc() {
	if(typeof String.prototype.trim !== 'function') {
		String.prototype.trim = function() {
			return this.replace(/^\s+|\s+$/g, '');
		};
	} 
	
	$("input[type='text'], input[type='password']").focus(function(){$(this).addClass("i-focus");});
	$("input[type='text'], input[type='password']").blur(function(){$(this).removeClass("i-focus");});
	
	$(".logout-back").click(function(e){
		e.preventDefault();
		var base = $(this).attr("href");
		if (base.indexOf('?') === -1) {
			base += '?done=';
		} else {
			base += '&done=';
		}
		var target = base + encodeURIComponent(window.location);
		window.location = target;
	});
	$('a').attr('hideFocus', 'true');
}

function initMainSearch() {

	$(".main-search .tab-panel").each(function(i) {
		var self = $(this);
		var searchFileds = $(".search-fields", self);
		var q = $("input", searchFileds), hint = $("span", searchFileds).text();
		var qSubmit = $(".search-submit", self);
		if (q.val() === "") {
			q.val(hint).addClass("hint");
		}
		q.focus(function() {
			qVal = q.val().trim();
			if (qVal === "" || qVal === hint) {
				q.val("").removeClass("hint");
			}
		});
		q.blur(function() {
			qVal = q.val().trim();
			if (qVal === "" || qVal === hint) {
				q.val(hint).addClass("hint");
			}
		});
		
		qSubmit.click(function(e) {
			qVal = q.val().trim();
			if (qVal === "" || qVal === hint) {
				alert(hint);
				e.preventDefault();
				return;
			} else {
				e.preventDefault();
				var url = $("form", self).attr("action");
				url = url + "?q=" + encodeURIComponent(qVal);
				
				window.location = url;
			}
		});
	});
	
	$("#offer-q").highlightcomplete({
		source: function(request, response) {
			$.ajax({
				url: "http://suggest.taobao.com/sug?code=utf-8",
				dataType: "jsonp",
				data: {
					q: request.term
				},
				success:function(data) {
					response(
						$.map(data.result, function(item) {
							var tokens = String(item).split(",");
							return {
								label: tokens[0],
								value: tokens[0]
							};
						})
					);
				}
			});
		},
		minLength: 1,
		position: {
			offset: "-1"
		},
		delay: 500,
		select: function(event, ui) {
			$(this).val(ui.item.value);
			$("#offer-submit").click();
		}
	});

	$(".main-search .search-tabs li").each(function(i) {
		$(this).click(function() {
			_changeSearchTab($(this), i);
		});
	});

	function _changeSearchTab(self, i) {
		if (self.hasClass("current")) {
			return;
		}
		$(".main-search .tab-panel").hide();
		$(".main-search .search-tabs li.current").removeClass("current");
		$(".main-search .tab-panel:eq(" + i + ")").show();
		self.addClass("current");
	}

	$(".main-search .search-tabs li a").click(function(e) {
		e.preventDefault();
		$(this).blur();
	});
}

(function($) {
	var Browser = function() {
        var o = {
            ie: 0,
            opera: 0,
            gecko: 0,
            webkit: 0
        };
        var ua = navigator.userAgent, m;
        if ( ( /KHTML/ ).test( ua ) ) {
            o.webkit = 1;
        }
        // Modern WebKit browsers are at least X-Grade
        m = ua.match(/AppleWebKit\/([^\s]*)/);
        if (m&&m[1]) {
            o.webkit=parseFloat(m[1]);
        }

        if (!o.webkit) { // not webkit
            // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
            m=ua.match(/Opera[\s\/]([^\s]*)/);
            if (m&&m[1]) {
                o.opera=parseFloat(m[1]);
            } else { // not opera or webkit
                m=ua.match(/MSIE\s([^;]*)/);
                if (m&&m[1]) {
                    o.ie=parseFloat(m[1]);
                } else { // not opera, webkit, or ie
                    m=ua.match(/Gecko\/([^\s]*)/);
                    if (m) {
                        o.gecko=1; // Gecko detected, look for revision
                        m=ua.match(/rv:([^\s\)]*)/);
                        if (m&&m[1]) {
                            o.gecko=parseFloat(m[1]);
                        }
                    }
                }
            }
        }
        return o;
    }();
	$.extend({mz:{}});
	$.extend($.mz,{
		decodeTbUrl : function(ori_url) {
			url = ori_url.replace('_','/');
			url = url.replace('-','+');
			decodeUrl = $.base64Decode(url);
			if(decodeUrl === '') {
				url += "=";
				decodeUrl = $.base64Decode(url);
			}
			if(decodeUrl === '') {
				url += "=";
				decodeUrl = $.base64Decode(url);
			}
			if(typeof(tbImgServerId) != 'undefined' && tbImgServerId<8) {
				decodeUrl = decodeUrl.replace(/^tbpic([0-9]*)/i, 'img0'+tbImgServerId+'.taobaocdn.com');
			} else {
				decodeUrl = decodeUrl.replace(/^tbpic([0-9]*)/i, 'img$1.taobaocdn.com');
			}
			decodeUrl = decodeUrl.replace('tbsite/', 'taobao.com/');
			decodeUrl = decodeUrl.replace('tbkurl/', 's.click.taobao.com/');
			if (decodeUrl.indexOf("http://") < 0){
				decodeUrl = 'http://' + decodeUrl;
			}
			return decodeUrl;
		},
		parseJSON : function(text) {
			var __json = null;
		    if ( typeof JSON !== "undefined" ) {
		        __json = JSON;
		    }
		    var browser = Browser;
            if ( __json !== null ) {
                return __json.parse( text );
            }
            if ( browser.gecko ) {
                return new Function( "return " + text )();
            }
            return eval( "(" + text + ")" );
		},
		redirect : function(url) {
			var isIE = (document.all) ? true:false;
			if(isIE) {
				var linka = document.createElement('a');
				linka.href = url;
				if(self!=top) {
					linka.target = '_parent';
				}
				document.body.appendChild(linka);
				linka.click();
			} else {
				if(self!=top) {
					parent.location.href = url;
				} else {
					window.location = url;
				}
			}
		}
	});
})(jQuery);
