/**
 * ==========================================
 * base.js
 * Copyright (c) 2010 wwww.114la.com
 * Author: cai@115.com
 * ==========================================
 */
 
var mini=(function(){var b=/(?:[\w\-\\.#]+)+(?:\[\w+?=([\'"])?(?:\\\1|.)+?\1\])?|\*|>/ig,g=/^(?:[\w\-_]+)?\.([\w\-_]+)/,f=/^(?:[\w\-_]+)?#([\w\-_]+)/,j=/^([\w\*\-_]+)/,h=[null,null];function d(o,m){m=m||document;var k=/^[\w\-_#]+$/.test(o);if(!k&&m.querySelectorAll){return c(m.querySelectorAll(o))}if(o.indexOf(",")>-1){var v=o.split(/,/g),t=[],s=0,r=v.length;for(;s<r;++s){t=t.concat(d(v[s],m))}return e(t)}var p=o.match(b),n=p.pop(),l=(n.match(f)||h)[1],u=!l&&(n.match(g)||h)[1],w=!l&&(n.match(j)||h)[1],q;if(u&&!w&&m.getElementsByClassName){q=c(m.getElementsByClassName(u))}else{q=!l&&c(m.getElementsByTagName(w||"*"));if(u){q=i(q,"className",RegExp("(^|\\s)"+u+"(\\s|$)"))}if(l){var x=m.getElementById(l);return x?[x]:[]}}return p[0]&&q[0]?a(p,q):q}function c(o){try{return Array.prototype.slice.call(o)}catch(n){var l=[],m=0,k=o.length;for(;m<k;++m){l[m]=o[m]}return l}}function a(w,p,n){var q=w.pop();if(q===">"){return a(w,p,true)}var s=[],k=-1,l=(q.match(f)||h)[1],t=!l&&(q.match(g)||h)[1],v=!l&&(q.match(j)||h)[1],u=-1,m,x,o;v=v&&v.toLowerCase();while((m=p[++u])){x=m.parentNode;do{o=!v||v==="*"||v===x.nodeName.toLowerCase();o=o&&(!l||x.id===l);o=o&&(!t||RegExp("(^|\\s)"+t+"(\\s|$)").test(x.className));if(n||o){break}}while((x=x.parentNode));if(o){s[++k]=m}}return w[0]&&s[0]?a(w,s):s}var e=(function(){var k=+new Date();var l=(function(){var m=1;return function(p){var o=p[k],n=m++;if(!o){p[k]=n;return true}return false}})();return function(m){var s=m.length,n=[],q=-1,o=0,p;for(;o<s;++o){p=m[o];if(l(p)){n[++q]=p}}k+=1;return n}})();function i(q,k,p){var m=-1,o,n=-1,l=[];while((o=q[++m])){if(p.test(o[k])){l[++n]=o}}return l}return d})();

if ( typeof Ylmf == 'undefined' ) {
    var Ylmf = {};
}

Function.prototype.method = function(name,fn) {
    this.prototype[name]=fn;
    return this;
};
if (!Array.prototype.forEach) {
    Array.method('forEach',
    function(fn, thisObj) {
        var scope = thisObj || window;
        for (var i = 0,
        j = this.length; i < j; ++i) {
            fn.call(scope, this[i], i, this);
        }
    }).method('every',
    function(fn, thisObj) {
        var scope = thisObj || window;
        for (var i = 0,
        j = this.length; i < j; ++i) {
            if (!fn.call(scope, this[i], i, this)) {
                return false;
            }
        }
        return true;
    }).method('some',
    function(fn, thisObj) {
        var scope = thisObj || window;
        for (var i = 0,
        j = this.length; i < j; ++i) {
            if (fn.call(scope, this[i], i, this)) {
                return true;
            }
        }
        return false;
    }).method('map',
    function(fn, thisObj) {
        var scope = thisObj || window;
        var a = [];
        for (var i = 0,
        j = this.length; i < j; ++i) {
            a.push(fn.call(scope, this[i], i, this));
        }
        return a;
    }).method('filter',
    function(fn, thisObj) {
        var scope = thisObj || window;
        var a = [];
        for (var i = 0,
        j = this.length; i < j; ++i) {
            if (!fn.call(scope, this[i], i, this)) {
                continue;
            }
            a.push(this[i]);
        }
        return a;
    }).method('indexOf',
    function(el, start) {
        var start = start || 0;
        for (var i = start,
        j = this.length; i < j; ++i) {
            if (this[i] === el) {
                return i;
            }
        }
        return - 1;
    }).method('lastIndexOf',
    function(el, start) {
        var start = start || this.length;
        if (start >= this.length) {
            start = this.length;
        }
        if (start < 0) {
            start = this.length + start;
        }
        for (var i = start; i >= 0; --i) {
            if (this[i] === el) {
                return i;
            }
        }
        return - 1;
    });
}

(function() {
    Ylmf.register = function(REG) {
		function __$(el){
			
			if(typeof el=="string"){
				var elArr =  mini(el);
				
				if(!elArr||elArr=="" || typeof(elArr) == "undefined"=="undefined"){
					//alert("No $!");
					return false;
				}
				
				
				if(elArr.length==1){
					this.el = elArr[0];
				}else if(elArr.length>1){
					this.el = elArr;
				}
			}else if(el.nodeType ==1){
				this.el = el;
			}
			 
		};
        __$.method(REG.each,function(fn){
			if(!this.el){
			//	fn.call(this,false);
				return
			}						 
			if(!this.el.length){
				fn.call(this,this.el);
			}else{			 
				for(var i= 0,len = this.el.length; i<len; ++i){
					fn.call(this,this.el[i]);
				}
			}
			return this;
		}).method(REG.hasClass, function(c,fn){	
			this.each(function(el){
				var col = el.className.split(/\s+/).toString();
				var result = (col.indexOf(c)>-1)?true:false;
				(function(){
					fn(result);	  
				})();
			});
			return this;
		}).method(REG.addClass, function(classNames){	
			this.each(function(el){
				var col = (classNames || "").split(/\s+/);
				for(var i = 0; i < col.length; i++){
					var item = col[i];
					this.hasClass(el,function(b){
						if(!b){
							el.className += (el.className ? " " : "") + item;
						}
					
					})
				}

			});
			return this;
		}).method(REG.removeClass, function(c){	
			this.each(function(el){
				if(c != undefined){
					var col = el.className.split(/\s+/);
					var hasCol = [];
					for(var i =0,len = col.length;i<len;++i){
						var item = col[i];
						
						if(item!=c){
							hasCol.push(item);
						}					
						
					}
					
					el.className = hasCol.join(" ");
				}else{
					el.className = "";
				}

	
			});
			return this;
		}).method(REG.replaceClass, function(oc,nc){
	
			this.removeClass(oc);
			this.addClass(nc);
			return this;
		}).method(REG.setStyle, function(prop,val){	
			this.each(function(el){
				el.style[prop] = val;
			});
			return this;
		}).method(REG.setCSS, function(styles) {
            for(var prop in styles){
				if(!styles.hasOwnProperty(prop)) continue;
				this.setStyle(prop,styles[prop]);
			}
            return this;
			
        }).method(REG.getStyle,function(prop,fn){
				var currentStyle = null;
			
				if(document.defaultView){// firefox,opera,safari
					currentStyle =  document.defaultView.getComputedStyle(this.el,null).getPropertyValue(prop);
				} else {//ie
					prop=prop.replace(/\-([a-z])([a-z]?)/ig,function(prop,a,b){return a.toUpperCase()+b.toLowerCase();});//转化为驼峰写法
					currentStyle =  this.el["currentStyle"][prop];
				}
				fn.call(this,currentStyle);
			
			return this;
		}).method(REG.show,function(n){
			if(n==0){
				this.setStyle("display","");
			}else if(n==1){
				this.setStyle("display","");
			}else{
				this.setStyle("display","block");
			}
			return this;
		}).method(REG.hide,function(){
			this.setStyle("display","none");
			return this;
		}).method(REG.toggle,function(t){
			this.each(function(el){
				if(el.style.display =="none"){
					if(t){
						t==1?el.style.display= "inline":el.style.display= ""
					}else{
						el.style.display= "block";
					}
					
				}else{
					el.style.display="block";
				}
			});
			return this;
		}).method(REG.on,function(type,fn){

			var add = function(el){
				var f = function(){

					fn(el)
				};
				if(window.addEventListener){
					el.addEventListener(type,f,false);
				}else if(window.attachEvent){
					el.attachEvent('on'+type,f);
				}	
			}
			if(!this.el){
				return;
			}
			
			if(this.el.length==0){
				add(this.el);
			}else{
				this.each(function(el){
					add(el);
				});
			}
			return this;
		}).method(REG.getRect,function(fn){
			var oRect = this.el.getBoundingClientRect();
			
			fn.call(this,oRect)
			
			return this;
		}).method(REG.create,function(el,o,cb){
			var el = document.createElement(el);
            for ( prop in o ) {
                el.setAttribute(prop, o[prop]);
            }
            if (cb) {
                cb.call(this, el);
            }
			
			return this;
		}).method(REG.append,function(element){
			this.el.appendChild(element);
			return this;
		}).method(REG.remove,function(element){
			if(element){
				this.el.removeChild(element);
			}
			return this;
		});
        
        window[REG.namespace] = function(el) {
            return new __$(el);
        };
        // sugar array shortcuts
        window[REG.namespace].forEach = Array.prototype.forEach;
        window[REG.namespace].every = Array.prototype.every;
        window[REG.namespace].some = Array.prototype.some;
        window[REG.namespace].map = Array.prototype.map;
        window[REG.namespace].filter = Array.prototype.filter;
				
        Ylmf.extendChain = function(name, fn) {
            __$.method(name, fn);
        };
		
		
    };
})();

Ylmf.register({
    namespace : '$',
	each:'each',
	addClass:'addClass',
	hasClass:'hasClass',
	removeClass:'removeClass',
	replaceClass:'replaceClass',
	setStyle:'setStyle',
	getStyle:'getStyle',
	setCSS:'setCSS',
	show:'show',
	hide:'hide',
	toggle:'toggle',
	on:'on',
	getRect:'getRect',
	append:'append',
	create:'create',
	remove:'remove'
});

Browser = (function() {
		var H = navigator.userAgent,
		F = 0,
		E = 0,
		I = 0,
		D = 0,
		A = 0,
		_ = 0,
		C = 0,
		B;
		if (H.indexOf("Chrome") > -1 && /Chrome\/(\d+(\.d+)?)/.test(H)) C = RegExp.$1;
		if (H.indexOf("Safari") > -1 && /Version\/(\d+(\.\d+)?)/.test(H)) F = RegExp.$1;
		if (window.opera && /Opera(\s|\/)(\d+(\.\d+)?)/.test(H)) I = RegExp.$2;
		if (H.indexOf("Gecko") > -1 && H.indexOf("KHTML") == -1 && /rv\:(\d+(\.\d+)?)/.test(H)) A = RegExp.$1;
		if (/MSIE (\d+(\.\d+)?)/.test(H)) D = RegExp.$1;
		if (/Firefox(\s|\/)(\d+(\.\d+)?)/.test(H)) _ = RegExp.$2;
		if (H.indexOf("KHTML") > -1 && /AppleWebKit\/([^\s]*)/.test(H)) E = RegExp.$1;
		try {
			B = !!external.max_version
		} catch($) {}
		function G() {
			var _ = false;
			if (navigator.plugins) for (var B = 0; B < navigator.plugins.length; B++) if (navigator.plugins[B].name.toLowerCase().indexOf("shockwave flash") >= 0) _ = true;
			if (!_) {
				try {
					var $ = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
					if ($) _ = true
				} catch(A) {
					_ = false
				}
			}
			return _
		}
		return ({
			isStrict: document.compatMode == "CSS1Compat",
			isChrome: C,
			isSafari: F,
			isWebkit: E,
			isOpera: I,
			isGecko: A,
			isIE: D,
			isFF: _,
			isMaxthon: B,
			isFlash: G(),
			isCookie: (navigator.cookieEnabled) ? true: false
		})
})(),

Ajax = function(url, callback) {

		var xhr;
		if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
		else {
			var versions = ["Microsoft.XmlHttp", 
			 				"MSXML2.XmlHttp",
			 			    "MSXML2.XmlHttp.3.0", 
			 			    "MSXML2.XmlHttp.4.0",
			 			    "MSXML2.XmlHttp.5.0"];
			 for(var i = 0, len = versions.length; i < len; i++) {
			 	try {
			 		xhr = new ActiveXObject(versions[i]);
			 		break;
			 	}
			 	catch(e){}
			 } // end for
		}
		xhr.onreadystatechange = ensureReadiness;
		function ensureReadiness() {
			if(xhr.readyState < 4) {
				return;
			}
			
			if(xhr.status !== 200) {
				return;
			}
			if(xhr.readyState === 4) {
				callback(xhr);
			}			
		}
		xhr.open('GET', url, true);
		xhr.send('');
	
},
cache = (function() {
    var cacheBox = {};
    function _get(name) {
        if (cacheBox[name]) return cacheBox[name];
        return null
    }
    function _set(name, value, A) {
        if (!A) {cacheBox[name] = value;}
        else {
            if (Yl.getType(cacheBox[name])!="array"){ cacheBox[name] = [];}
            cacheBox[name].push(value)
        }
    }
    function _remove(name) {
        delete cacheBox[name]
    }
    function _is(name) {
        return (_get(name) == null) ? false: true
    }
    return {
        get: _get,
        set: _set,
        is: _is,
        remove: _remove
    }
})(),
format = function(_, B) {
    if (arguments.length > 1) {
        var F = format,
        H = /([.*+?^=!:${}()|[\]\/\\])/g,
        C = (F.left_delimiter || "{").replace(H, "\\$1"),
        A = (F.right_delimiter || "}").replace(H, "\\$1"),
        E = F._r1 || (F._r1 = new RegExp("#" + C + "([^" + C + A + "]+)" + A, "g")),
        G = F._r2 || (F._r2 = new RegExp("#" + C + "(\\d+)" + A, "g"));
        if (typeof(B) == "object") return _.replace(E,
        function(_, A) {
            var $ = B[A];
            if (typeof $ == "function") $ = $(A);
            return typeof($) == "undefined" ? "": $
        });
        else if (typeof(B) != "undefined") {
            var D = Array.prototype.slice.call(arguments, 1),
            $ = D.length;
            return _.replace(G,
            function(A, _) {
                _ = parseInt(_, 10);
                return (_ >= $) ? A: D[_]
            })
        }
    }
    return _
}


var qucikSearch = (function(){
    var Q = $("#q_int");
    var I = $("#q_int input");
    var R = $("#qs-result");
    var Btn = false;
    var defaultValue = I.el.value = "请输入店铺名或拼音";
    var inputState = 0; //0 普通  1 focus
    var sendDelay, countDelay,timer = 200;
    var lastValue;
    
    I.on("focus", function(el){
        Q.el.className = "f";
        if (el.value == defaultValue) {
            el.value = "";
        }
        inputState = 1;
    });
    
    I.on("keyup", function(el){
        if (el.value == "") {
            closeSearch();
            return;
        }
        if (lastValue && el.value == lastValue) {
            return; //无改变
        }
        if (!Btn) {
            Q.create("a", {
                id: "qs-btn",
				rel:'nr',
                href: "javascript:void(0);",
                target: "_parent",
                title: "关闭"
            }, function(el){
                el.onclick = function(){
                    inputState = 0;
                    closeSearch();
                }
                this.append(el);
            });
            Btn = true;
        }
        if (el.value!="") {
            if (sendDelay) {
                window.clearTimeout(sendDelay);
            }
			if (countDelay) {
                window.clearTimeout(countDelay);
            }
            send(el.value);
        }
        
    })
    
    I.on("blur", function(el){
        Q.el.className = "n";
        if (el.value == "") {
            el.value = defaultValue;
        }
        
    });
    
    function closeSearch(clear){
        R.hide();
        if (Btn) {
            Q.el.removeChild($("#qs-btn").el);
            Btn = false;
        }
        if (inputState == 0 || clear == true) {
            I.el.value = defaultValue;
            //K.el.blur();
        }
        cache.remove("HAS_SHOW_QS");
    }
    function send(query){
		if(query==""){return}
        lastValue = query;
        sendDelay = window.setTimeout(function(){
			R.show();
            cache.set("HAS_SHOW_QS", true);
            R.el.innerHTML = '<ul><li>正在搜索中...</li></ul>';
            var api = './search.php?keyword=' + encodeURIComponent(query) ;
			//var api = 'search.txt?k=1';
			Ajax(api+ '&rd=' + new Date().getTime(), callback);
        }, timer);
		
        countDelay = window.setTimeout(function(){
			KeywordCount({
			type: "qs",
			word: query,
			url: window.location.href
			}, "http://www.tjj.com/click.php");
		},1000);
        
        function callback(xhr){
            if (xhr.responseText == '') {
                R.el.innerHTML = '<ul><li>没有搜索到相关站点!</li></ul>';
            }
            else {
                R.el.innerHTML = '<ul class="clearfix">' + xhr.responseText + '</ul>';
            }
        }
        
    }
    return {
        close: closeSearch
    }
})();//网址快速搜索



var Suggest = (function(){
    var K , S = $("#suggest"), Query,//输入值
 currentKey = -1, dataScript = null,//数据脚本
 dataResult,//结果数据
 KeywordItems, //li
 mouseSelect = false, stopRequest = false, Hidestate = false, isClose = false;
var KEL;
	$(".sf .int").each(function(el){
		K = $(el);
		
		
		K.el.onkeydown = function(e){
			var e = e || window.event;
			if (isClose) {
				return;
			}
			KEL = this
			switch (e.keyCode) {
				case 38:
					if (Hidestate) {
						if (this.value == "") 
							return;
						S.show();
						Hidestate = false;
					}
					else {
						currentKey--
					}
					selectItem();
					break;
				case 40:
					if (Hidestate) {
						if (this.value == "") 
							return;
						S.show();
						Hidestate = false;
					}
					else {
						currentKey++
					}
					selectItem();
					break;
				case 27:
					this.value = Query;
					hideSuggest();
					break;
				case 13:
					hideSuggest();
					break;
				default:
					//stopRequest = false;
					break;
			}
		}

    K.el.onkeyup = function(e){
        var e = e || window.event;
        if (isClose) {
            return;
        }
        
		var myKey = Number(this.getAttribute("index"));
		for(var j = 0, jlen = inputTxtArr.length; j < jlen; j++){
			var oKey = Number(inputTxtArr[j].getAttribute("index"));
			if(oKey != myKey){
				inputTxtArr[j].value = this.value;
			}
		}
        Query = this.value;
       
        switch (e.keyCode) {
            case 38:
                stopRequest = true;
                
                break;
            case 40:
                stopRequest = true;
                break;
            case 8:
                if (this.value == "") {
                    hideSuggest();
                }
                else {
                    requestData();
                }
                break;
            case 27:
                this.value = Query;
                hideSuggest();
            case 13:
                hideSuggest();
                break;
            default:
                if (Query != "") {
                    requestData();
                }
                
                break;
        }
    }
	
	
	
    K.el.onblur = function(){
        if (!mouseSelect) {
            hideSuggest();
        }
    }
	
    function selectItem(){
        if (!KeywordItems) 
            return;
        var len = KeywordItems.length;
        
        stopRequest = true;
        if (currentKey < 0) {
            currentKey = len - 1;
        }
        else 
            if (currentKey >= len) {
                currentKey = 0;
            }
        for (var i = 0, len = KeywordItems.length; i < len; i++) {
            KeywordItems[i].className = "";
        }
        KeywordItems[currentKey].className = "hover";
        //K.el.value = KeywordItems[currentKey].innerHTML;
		for(var j = 0, jlen = inputTxtArr.length; j < jlen; j++){
			inputTxtArr[j].value = KeywordItems[currentKey].innerHTML;
		}
    }
    
    function showSuggest(){
        if (typeof(dataResult) != "object" || typeof(dataResult) == "undefined") 
            return;
        var html = '<ul>';
        dataResult.forEach(function(el, index, arr){
                html += '<li key="' + index + '">' + el + '</li>';
        });
        html += '</ul><div class="close"><a id="closeSugBtn">关闭</a></div>';
        KeywordItems = S.el.getElementsByTagName("li");
        S.el.innerHTML = html;
        S.show();
        currentKey = -1;
        Hidestate = false;
        mouseHandle();
    }
    function hideSuggest(){
        S.hide();
        Hidestate = true;
        
    }
    
    function closeSuggest(){
        KEL.setAttribute("autocomplete", "on");
        KEL.focus();
        S.hide();
        isClose = true;
    }
    
    function mouseHandle(){
        S.el.onmouseover = function(e){
            var e = e || window.event, target = e.target || e.srcElement;
            
            if (target.tagName.toUpperCase() == "LI") {
                for (var i = 0, len = KeywordItems.length; i < len; i++) {
                    KeywordItems[i].className = "";
                }
                target.className = "hover";
                currentKey = parseInt(target.getAttribute("key"));
                
                $(target).on("mouseout", function(el){
                    el.className = "";
                })
            }
            mouseSelect = true;
        }
        S.el.onmouseout = function(){
            mouseSelect = false;
        }
        
        S.el.onclick = function(e){
            var e = e || window.event, target = e.target || e.srcElement;
            if (target.tagName.toUpperCase() == "LI") {
				for(var j = 0, jlen = inputTxtArr.length; j < jlen; j++){
					inputTxtArr[j].value = target.innerHTML;
				}
                hideSuggest();
               var SF =  KEL.parentNode;
			   //SF.onsubmit();
			   SF.submit();
            }
            if (target.id == "closeSugBtn") {
                closeSuggest();
            }
            
        }
    }

    function requestData(){
        var head = $("head").el;
        if (!Browser.isIE) {
            if (dataScript) {
                head.removeChild(dataScript);
            }
            dataScript = null;
        } // IE不需要重新创建script元素
        if (!dataScript) {
            var script = document.createElement("script");
            script.type = "text/javascript";
			script.charset = "gb2312";
            head.insertBefore(script, head.firstChild);
            dataScript = script;
        }
        var rd = new Date().getTime();
        var key = encodeURIComponent(K.el.value);
        var Url = "http://suggestion.baidu.com/su?wd=" + key + "&sc=114la&rd=" + rd;
       dataScript.src = Url;
    }
	
    //baidu
    window.baidu = {};
    window.baidu.sug = function(O){
        if (typeof(O) == "object" && typeof(O.s) != "undefined" && typeof(O.s[0]) != "undefined") {
            dataResult = O.s;
            showSuggest();
        }
        else {
            hideSuggest();
        }
    };
	
	
	});
})();//搜索自动完成