document.domain = '5253.com';
//window.onerror = function(){};

var _c = {
	'domain':'http://www.5253.com/',
	'domain_common':'http://www.5253.com/',
	'actionPath':'http://www.5253.com/action.php',
	'picPath':[
		'http://img.5253.com/upload/game_img/',
		'http://img.5253.com/upload/left_pic/',
		'http://img.5253.com/upload/special_link/'
	],
	'gamePicPaths':[
		'http://img.5253.com/upload/game_img/',
		'http://i2.5253.com/upload/game_img/',
		'http://i3.5253.com/upload/game_img/'
	],
	'userFace':'http://udb.5253.com/avatar.php',
	'domain_my':'http://my.5253.com/',
	'domain_udb':'http://udb.5253.com/'
};

var userDb = {};
var backDb = {};
var actionDb = {};

/**
 * 游戏盒了相关数据
 */
var navBoxDb = {
	'type':1,
	'inited':false,
	'hallGameActionPage':-1,
	'gameActionPage':-1,
	'hallInited':false,
	'gameInited':false
};

//全页面初始化
$(document).ready(function(){
	
	//搜索相关
	if($('#keyword')[0]){
		//搜索提示
		var completeKeyword = _c.actionPath+'?s=/Search/complete_keyword/';
		var ac = $('#keyword').autocomplete({
	        serviceUrl: completeKeyword,
	        minChars: 1,
	        delimiter: /(\(\))/gi,
	        maxHeight: 400,
	        width: 285,
	        zIndex: 9999,
	        deferRequestBy: 0,
	        params: { country: 'Yes'},
	        onSelect: function(data, value){
	        	$('#search_form').submit();
	        }
	    });
		
		//提交搜索表单
		$('#search_form').submit(function(){
			var obj = $('#keyword')[0];
			var test=/^(\w|[\u4E00-\u9FA5]| )*$/;
			if(obj.value=='' || obj.value.length<2){
				alert('关键字不能少于两个字符！');
				return false;
			}else{
				return true;
			}
		});
	}
	
	//加载falsh存储对像
    if (typeof($.jStore) != 'undefined') {
        $.jStore.load();
        //清除游戏
        $('#clear_history_game').click(function(){
            clearHistoryGame();
        });
    }
    
    //加载用户登陆信息
	$.getJSON(_c.actionPath+'?s=/Udb/cget/callback/=?',function(data){
		userDb = data.data;
		if(userDb.islogin==1){
			logined_html();
		}else{
			$('#site-nav-box').css('display','block');
		}
	});
	
	//页面头部，其它链接
	var otherLinkBnt = setTimeout(function(){},100);
	$('#otherLinkBnt').add('#otherLinkBox').mouseover(function(){
		clearTimeout(otherLinkBnt);
		$('#otherLinkBox').show();
	}).mouseout(function(){
		otherLinkBnt = setTimeout(function(){
			$('#otherLinkBox').hide();
		},500);
	});
	
	//初始化公告
	ggInit();
	
	//添加一个隐藏的IF
	$('body').append('<iframe name="hiframe" id="hiframe" src="" style="display:none;"></iframe>');
	
	//微薄显示隐藏
	var weiboLinkBnt = setTimeout(function(){},100);
	$('#weibo_bnt').add('#weibo_box').mouseover(function(){
		clearTimeout(weiboLinkBnt);
		$('#weibo_box').show();
	}).mouseout(function(){
		weiboLinkBnt = setTimeout(function(){
			$('#weibo_box').hide();
		},500);
	});
	
	//$('body').append('<script type="text/javascript" src="http://tg.jutao.com/resources/js/5253.js" charset="UTF-8"></script>');
});

//读写cookie函数
function GetCookie(c_name){
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return null;
}

function SetCookie(c_name, value, expiredays, path){
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    var cookieStr = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ';';
    if (path != null) {
        cookieStr += "path=" + path + ";";
    }
    document.cookie = cookieStr; //使设置的有效时间正确。增加toGMTString()
}
/**
 * 搜索框得到焦点
 */
function keywordFocus(obj){
    if (obj.value == '植物大战僵尸') {
        obj.value = '';
//        if (obj.className.indexOf('_a') >= 0) {
//            obj.className = obj.className.substring(0, obj.className.indexOf('_a'));
//        }
//        else {
//            obj.className = obj.className + '_a';
//        }
    }
}

/**
 * 搜索框失去焦点
 */
function keywordBlur(obj){
    if (obj.value == '') {
        obj.value = '植物大战僵尸';
//        if (obj.className.indexOf('_a') >= 0) {
//            //obj.className = obj.className.substring(0, obj.className.indexOf('_a'));
//        }
//        else {
//            obj.className = obj.className + '_a';
//        }
    }
}


/**
 * 复制URL地址
 */
function copy_this(){
    var clipBoardContent = "首页：Hi，All！我在5253小游戏（http://www.5253.com）上找游戏，有一起玩的没？！";
	
	if ($.browser.msie) {
		window.clipboardData.setData("Text", clipBoardContent);
		alert("网址已复制好，Ctrl+V可以粘贴给朋友O(∩_∩)O~");
	}else{
		prompt("请复制网站地址:",clipBoardContent); 
	}
}

/**
 * 复制URL地址
 */
function copy_this_game(){
    var clipBoardContent = "Hi，All！我在5253小游戏（http://www.5253.com）发现 （  "+gameTitle+"  "+this.location.href+"）挺给力，来试试？！";
	if ($.browser.msie) {
		window.clipboardData.setData("Text", clipBoardContent);
		alert("网址已复制好，Ctrl+V可以粘贴给朋友O(∩_∩)O~");
	}else{
		prompt("请复制网站地址:",clipBoardContent); 
	}
}

/**
 * 添加到收藏
 */
function add_favorite(sURL, sTitle){
	if(typeof(sURL)=='undefined'){
		sURL = location.href;
	}
	if(typeof(sTitle)=='undefined'){
		sTitle = document.title;
	}
    if ($.browser.msie) {
    	try {
        	window.external.addFavorite(sURL, sTitle);
        } 
	    catch(e){
	        alert("加入收藏失败，请使用Ctrl+D进行添加");
	    }
	} else {
        window.sidebar.addPanel(sTitle, sURL, '');
    }
}

/**
 * 保存在桌面
 */
function save_desktop(title,url){
		location.href = _c.actionPath+'?s=/Createurl/get/title/'+encodeURIComponent(title)+'/url/'+url.replace(/\//g,'-.-');
}

/**
 * 玩过的游戏
 */
if (typeof($.jStore) != 'undefined') {

    $.extend($.jStore.defaults, {
        project: '5253.com',
        engine: 'flash',
        flash: _c.domain + 'images/jStore/jStore.Flash.html'
    });
    
    $.jStore.ready(function(engine){
        $.jStore.flashReady(function(){
            engine.ready(function(){
                //读取历史记录
                var engine = this;
                var history_games_id = engine.get('history_games_id');
                var history_games_title = engine.get('history_games_title');
                
                if (history_games_id === null) {
                    //读取推荐游戏
                    $.get(_c['domain'] + 'public/recommend_game.html', function(data){
                        $('#history_game').html(data);
                    });
                }
                else {
                    var historyGameStr = '<span class="red">我玩过的游戏：</span>';
                    var maxI = history_games_id.length;
                    for (var i = 0; i < maxI; i++) {
                        var gameId = history_games_id[i];
                        historyGameStr += '<a href="'+history_games_id[i]+'" target="_blank">' + history_games_title[i] + '</a>';
                    }
                    historyGameStr = '<div class="user_plays">' + historyGameStr + '</div><input type="button" class="btn_clear" value="清空" name="" id="clear_history_game" onClick="clearHistoryGame();">';
                    $('#history_game').html(historyGameStr);
                }
                
                //如果是游戏，则写入记录
                if (typeof(__width) != 'undefined') {
                    //定义新的空数组
                    var tmp1 = new Array();
                    var tmp2 = new Array();
					
					var thisRul = location.href;
                    
                    tmp1[0] = location.href;
                    tmp2[0] = gameTitle;
                    
                    if (history_games_id !== null) {
                        var maxI = history_games_id.length;
                        var j = 1;
                        for (var i = 0; i < maxI; i++) {
                            if (thisRul != history_games_id[i]) {
                                tmp1[j] = history_games_id[i];
                                tmp2[j] = history_games_title[i];
                                j++;
                            }
                        }
                    }
                    engine.set('history_games_id', $.toJSON(tmp1));
                    engine.set('history_games_title', $.toJSON(tmp2));
                    
                    tmp1 = null;
                    tmp2 = null;
                    
                    
                    //记录每个分类，每个Tag
                    var history_tag_obj = engine.get('history_tag_obj');
                    if (history_tag_obj == null) {
                        history_tag_obj = {};
                    }
                    history_tag_obj[classId] = thisRul;
                    var tagIdsArr = tagIds.split(',');
                    for (var i = 0; i < tagIdsArr.length; i++) {
                        history_tag_obj[tagIdsArr[i]] = thisRul;
                    }
                    engine.set('history_tag_obj', $.toJSON(history_tag_obj));
                    
                    history_tag_obj = null;
                }
                
                history_games_id = null;
                history_games_title = null;
                CollectGarbage();
            });
        });
    });
    
    /**
     * 清除玩过的游戏
     */
    function clearHistoryGame(){
        if (window.confirm('您确定要清空 "我玩过的游戏" 吗？')) {
            if ($.jStore.isFlashReady) {
                $.jStore.remove('history_games_id');
                $.jStore.remove('history_games_title');
                $.jStore.remove('history_tag_obj');
                
                //读取推荐游戏
                $.get(_c['domain'] + 'public/recommend_game.html', function(data){
                    $('#history_game').html(data);
                });
            }
        }
    }
}

function udb_logout(){
	$.ajax({
	   type: "GET",
	   url: _c.actionPath+"?s=/Udb/logout/callback/=?",
	   dataType:'json',
	   success: function(data){
			if(data.status==1){
				usetDb = {'islogin':0};
				$('#site-nav').html(backDb.nav);
				$('body').append(data.data);
				$('#site-nav-box').css('display','block');
				
				//页面头部，其它链接
				var otherLinkBnt = setTimeout(function(){
				}, 100);
				$('#otherLinkBnt').add('#otherLinkBox').mouseover(function(){
					clearTimeout(otherLinkBnt);
					$('#otherLinkBox').show();
				}).mouseout(function(){
					otherLinkBnt = setTimeout(function(){
						$('#otherLinkBox').hide();
					}, 500);
				});
				
				//微薄显示隐藏
				var weiboLinkBnt = setTimeout(function(){},100);
				$('#weibo_bnt').add('#weibo_box').mouseover(function(){
					clearTimeout(weiboLinkBnt);
					$('#weibo_box').show();
				}).mouseout(function(){
					weiboLinkBnt = setTimeout(function(){
						$('#weibo_box').hide();
					},500);
				});
			}else{
				alert('退出失败！请重试！');
			}
	   }
	});
}

/**
 * 用户登陆和退出
 */
function udb_login(){
	var username = $('#udb_username').val();
	var password = $('#udb_password').val();
	
	if(username=='' || password==''){
		alert('用户名或密码错误！');
		return false;
	}
	
	var href = location.href;
	/*
	if(href.indexOf('?test')>0){
		alert(sha1(password));
		alert(password);
	}
	*/
	$('#udb_password').attr('value',sha1(password));
	$('#flogin').attr('onsubmit','');
	$('#flogin').submit();
	$('#flogin').attr('onsubmit','return udb_login_submit();');
}

function udb_login_submit(){
	var username = $('#udb_username').val();
	var password = $('#udb_password').val();
	
	if(username=='' || password==''){
		alert('用户名或密码错误！');
		return false;
	}
	
	$('#udb_password').val(sha1(password));
	return true;
}

function logined_html_and_data(){
	$.getJSON(_c.actionPath+'?s=/Udb/cget/callback/=?',function(data){
		userDb = data.data;
		if(userDb.islogin==1){
			logined_html();
		}else{
			$('#site-nav-box').css('display','block');
		}
	});
}

function logined_html(){
	$.getJSON(_c.actionPath + '?s=/Index/cnav_logined/callback/=?', function(data){
		var body = data.data;
		data = null;
		body = body.replace(/\{username\}/g, userDb.username);
		body = body.replace(/\{uid\}/g, userDb.uid);
		backDb.nav = $('#site-nav').html();
		$('#site-nav').html(body);
		
		//页面头部，其它链接
		var otherLinkBnt = setTimeout(function(){
		}, 100);
		$('#otherLinkBnt').add('#otherLinkBox').mouseover(function(){
			clearTimeout(otherLinkBnt);
			$('#otherLinkBox').show();
		}).mouseout(function(){
			otherLinkBnt = setTimeout(function(){
				$('#otherLinkBox').hide();
			}, 500);
		});
		
		//微薄显示隐藏
		var weiboLinkBnt = setTimeout(function(){},100);
		$('#weibo_bnt').add('#weibo_box').mouseover(function(){
			clearTimeout(weiboLinkBnt);
			$('#weibo_box').show();
		}).mouseout(function(){
			weiboLinkBnt = setTimeout(function(){
				$('#weibo_box').hide();
			},500);
		});
		
		//页面头部，游戏盒子
		var navBoxTimeout = setTimeout(function(){
		}, 100);
		$('#nav_box_bnt').mouseover(function(){
			clearTimeout(navBoxTimeout);
			nav_box_open();
		});
		$('#nav_box').mouseover(function(){
			clearTimeout(navBoxTimeout);
		});
		$('#nav_box,#nav_box_bnt').mouseout(function(){
			navBoxTimeout = setTimeout(nav_box_clear, 500);
		});
		$('#a1,#a2').mouseover(function(){
			$('#a1,#a2').removeClass('hover');
			$(this).addClass('hover');
			
			$('#c-a1,#c-a2').css('display', 'none');
			$('#c-' + $(this).attr('id')).css('display', 'block');
			
			//定义上一页，下一页
			if ($(this).attr('id') == "a2") {
				nav_game();
				$('#game_prev').click(function(){
					showGame(actionDb.boxGame, --navBoxDb.gameActionPage);
				});
				$('#game_next').click(function(){
					showGame(actionDb.boxGame, ++navBoxDb.gameActionPage);
				});
			}
			else {
				nav_hall_game();
				$('#game_prev').click(function(){
					showHallGame(actionDb.boxHallGame, navBoxDb.hallGameActionPage - 1);
				});
				$('#game_next').click(function(){
					showHallGame(actionDb.boxHallGame, navBoxDb.hallGameActionPage + 1);
				});
			}
		});
		
		ggInit();
	});
}

/**
 * 游戏盒子
 */

function nav_box_open(){
	$('#nav_box').show();
	if(!navBoxDb.inited){
		nav_hall_game();
		navBoxDb.inited = true;
	}
}

function nav_hall_game(){
	if(!navBoxDb.hallInited){
		navBoxDb.hallInited = true;
		$.getJSON(_c.actionPath+'?s=/Box/cget/type/2/callback/=?',function(data){
			actionDb.boxHallGame = data.data;
			showHallGame(actionDb.boxHallGame,0);
		});
	}
}

//添加内容
function showHallGame(data,p){
	var total = data.length;
	if(total>0){
		var totalPage = Math.ceil(data.length / 5) - 1;
		if (p > totalPage) {
			p = 0;
		}
		if (p < 0) {
			p = totalPage;
		}
		navBoxDb.hallGameActionPage = p;
		var body = '';
		for (var i = p * 5; i < (p + 1) * 5 && i < total; i++) {
			var v = data[i];
			body += '<li> <a class="pica" href="' + v.url + '"><img src="' + v.small_pic + '"></a>'
			+'<p><a href="'+v.url +'">'+v.title+'</a></p>'
			+'  <div class="gn"><a target="_self" class="close" onclick="nav_box_del('+v.gid +',2,\''+v.title+'\'); return false;" href="javascript:void();"></a> </div>'
			+'</li>';
		}
		$('#c-a1').html(body);
	}
}

function nav_game(){
	if(!navBoxDb.gameInited){
		navBoxDb.gameInited = true;
		$.getJSON(_c.actionPath+'?s=/Box/cget/type/1/callback/=?',function(data){
			actionDb.boxGame = data.data;
			showGame(actionDb.boxGame,0);
		});
	}
}

	
//添加内容
function showGame(data,p){
	var total = data.length;
	var totalPage = Math.ceil(data.length / 9) - 1;
	if (p > totalPage) {
		p = 0;
	}
	if (p < 0) {
		p = totalPage;
	}
	navBoxDb.gameActionPage = p;
	var body = '';
	for (var i = p * 9; i < (p + 1) * 9 && i < total; i++) {
		var v = data[i];
		body += '<li><a class="red" target="_self" onclick="nav_box_del('+v.gid +',1,\''+v.title+'\');" href="javascript:void(0);">[删除]</a><a href="' + v.url + '">'+v.title+'</a></li>';
	}
	$('#c-a2').html(body);
}

/**
 * 关闭游戏合子
 */
function nav_box_clear(){
	$('#nav_box').hide();
}

/**
 * 删除游戏
 */
function nav_box_del(gid,type,title){
	if(confirm('您确认要从您的游戏盒子中把“'+title+'”移除吗？')){
		$.getJSON(_c.actionPath+'?s=/Box/cdel/type/'+type+'/gid/'+gid+'/callback/=?',function(data){
			if(data.status==1){
				navBoxDb.gameInited = false;
				nav_game();
			}else{
				navBoxDb.hallInited = false;
				nav_hall_game();
			}
		});
	}
}

/**
 * 顶部公告JS
 */
var GGDb = {
	'total':-1,
	'actionRow':0,
	'lineHeight':38,
	'timeout':setTimeout(function(){},100)
}

function ggInit(){
	clearTimeout(GGDb.timeout);
	
	GGDb.total = $('#ggContent li').length;
	$('#ggContent').append('<li>'+$('#ggContent li').eq(0).html()+'</li>');
	
	$('#ggContent li').mouseover(function(){
		clearTimeout(GGDb.timeout);
	}).mouseout(function(){
		GGDb.timeout = setTimeout(function(){
			ggNext();
		},3000);
	});
	
	GGDb.timeout = setTimeout(function(){
		ggNext();
	},3000);
}

function ggNext(){
	GGDb.actionRow++;
	if(GGDb.actionRow>(GGDb.total)){
		GGDb.actionRow = 1;
		$('#ggContent').css('top',0);
	}
	
	$("#ggContent").animate({'top': '-'+(GGDb.lineHeight*(GGDb.actionRow))}, "slow");
	
	GGDb.timeout = setTimeout(function(){
		ggNext();
	},3000);
}

/**
 * 推荐游戏
 */
function recommendGame(obj,gid){

    var saveid = GetCookie('recommend');
    if (saveid != null) {
        var saveids = saveid.split(',');
        var hasid = false;
        saveid = '';
        j = 1;
        for (i = saveids.length - 1; i >= 0; i--) {
            if (saveids[i] == gid && hasid) 
                continue;
            else {
                if (saveids[i] == gid && !hasid) 
                    hasid = true;
                saveid += (saveid == '' ? saveids[i] : ',' + saveids[i]);
                j++;
                if (j == 20 && hasid) 
                    break;
                if (j == 19 && !hasid) 
                    break;
            }
        }
        if (hasid) {
			alert('您已顶过该游戏！');
			$(obj).addClass('visited');
            return false;
        }
        else {
            $.getJSON(_c.actionPath + '?s=Index/set_game_recommend/gid/' + gid+'/callback/=?', function(data){
                if (data) {
                    $(obj).prev().html(data.data.recommend);
                }
				$(obj).addClass('visited');
				//统计
				if ($.isFunction(countAction)) {
					countAction('K', gid);
				}
				UTagPlus.checkandshow(1,gid);
            });
            saveid += ',' + gid;
        }
        SetCookie('recommend', saveid, 1);
    }
    else{
        $.getJSON(_c.actionPath + '?s=/Index/set_game_recommend/gid/' + gid+'/callback/=?', function(data){
            if (data) {
                $(obj).prev().html(data.data.recommend);
            }
			//统计
			if ($.isFunction(countAction)) {
				countAction('K', gid);
			}
			UTagPlus.checkandshow(1,gid);
        });
		$(obj).addClass('visited');
        SetCookie('recommend', gid, 1);
    }
}

/**
 * 收藏游戏
 */
function favoriteGame(gid){
    $.get(_c.actionPath + '?s=m/Index/a/count_game_favorite/gid/' + gid);
	
	if(typeof(userDb.islogin) != 'undefined'){
		if(userDb.islogin==1){
			set_box(gid);
		}else{
			add_favorite(location.href,document.title);
		}
	}else{
		add_favorite(location.href,document.title);
	}
	
    //统计
    if ($.isFunction(countAction)) {
        countAction('is_sc', gid);
    }
}

/**
 * 添加到游戏盒子
 */
function set_box(gid){
	$.getJSON(_c.actionPath+'?s=/Box/cset/gid/'+gid+'/notcount/1/callback/=?',function(data){
		nav_game();
		alert(data.info);
	});
}


/**
 * 搜索提示插件
 */
(function($){

    var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');
    
    function fnFormatResult(value, data, currentValue){
        var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
        return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
    }
    
    function Autocomplete(el, options){
    
        this.el = $(el);
        this.el.attr('autocomplete', 'off');
        this.suggestions = [];
        this.data = [];
        this.badQueries = [];
        this.selectedIndex = -1;
        this.currentValue = this.el.val();
        this.intervalId = 0;
        this.cachedResponse = [];
        this.onChangeInterval = null;
        this.ignoreValueChange = false;
        this.serviceUrl = options.serviceUrl;
        this.isLocal = false;
        this.options = {
            autoSubmit: false,
            minChars: 1,
            maxHeight: 300,
            deferRequestBy: 0,
            width: 0,
            highlight: true,
            params: {},
            fnFormatResult: fnFormatResult,
            delimiter: null,
            zIndex: 9999
        };
        this.initialize();
        this.setOptions(options);
    }
    
    $.fn.autocomplete = function(options){
        return new Autocomplete(this.get(0), options);
    };
    
    
    Autocomplete.prototype = {
    
        killerFn: null,
        
        initialize: function(){
        
            var me, uid, autocompleteElId;
            me = this;
            uid = Math.floor(Math.random() * 0x100000).toString(16);
            autocompleteElId = 'Autocomplete_' + uid;
            
            this.killerFn = function(e){
                if ($(e.target).parents('.autocomplete').size() === 0) {
                    me.killSuggestions();
                    me.disableKillerFn();
                }
            };
            
            if (!this.options.width) {
                this.options.width = this.el.width();
            }
            this.mainContainerId = 'AutocompleteContainter_' + uid;
            
            $('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:300px;"></div></div></div>').appendTo('body');
            
            this.container = $('#' + autocompleteElId);
            this.fixPosition();
            if (window.opera) {
                this.el.keypress(function(e){
                    me.onKeyPress(e);
                });
            }
            else {
                this.el.keydown(function(e){
                    me.onKeyPress(e);
                });
            }
            this.el.keyup(function(e){
                me.onKeyUp(e);
            });
            this.el.blur(function(){
                me.enableKillerFn();
            });
            this.el.focus(function(){
                me.fixPosition();
            });
            this.el.click(function(){
                me.onClick()
            })
        },
        
        setOptions: function(options){
            var o = this.options;
            $.extend(o, options);
            if (o.lookup) {
                this.isLocal = true;
                if ($.isArray(o.lookup)) {
                    o.lookup = {
                        suggestions: o.lookup,
                        data: []
                    };
                }
            }
            $('#' + this.mainContainerId).css({
                zIndex: o.zIndex
            });
            this.container.css({
                maxHeight: o.maxHeight + 'px',
                width: o.width
            });
        },
        
        clearCache: function(){
            this.cachedResponse = [];
            this.badQueries = [];
        },
        
        disable: function(){
            this.disabled = true;
        },
        
        enable: function(){
            this.disabled = false;
        },
        
        fixPosition: function(){
            var offset = this.el.offset();
            $('#' + this.mainContainerId).css({
                top: (offset.top + this.el.innerHeight()) + 'px',
                left: offset.left + 'px'
            });
        },
        
        enableKillerFn: function(){
            var me = this;
            $(document).bind('click', me.killerFn);
        },
        
        disableKillerFn: function(){
            var me = this;
            $(document).unbind('click', me.killerFn);
        },
        
        killSuggestions: function(){
            var me = this;
            this.stopKillSuggestions();
            this.intervalId = window.setInterval(function(){
                me.hide();
                me.stopKillSuggestions();
            }, 300);
        },
        
        stopKillSuggestions: function(){
            window.clearInterval(this.intervalId);
        },
        
        onKeyPress: function(e){
        
            if (this.disabled || !this.enabled) {
                return;
            }
            // return will exit the function
            // and event will not be prevented
            switch (e.keyCode) {
                case 27: //KEY_ESC:
                    this.el.val(this.currentValue);
                    this.hide();
                    break;
                case 9: //KEY_TAB:
                case 13: //KEY_RETURN:
                    if (this.selectedIndex === -1 || e.keyCode === 9) {
                        this.hide();
                        return;
                    }
                    this.select(this.selectedIndex);
                    break;
                case 38: //KEY_UP:
                    this.moveUp();
                    break;
                case 40: //KEY_DOWN:
                    this.moveDown();
                    break;
                default:
                    return;            }
            e.stopImmediatePropagation();
            e.preventDefault();
        },
        
        onKeyUp: function(e){
            if (this.disabled) {
                return;
            }
            switch (e.keyCode) {
                case 38: //KEY_UP:
                case 40: //KEY_DOWN:
                    return;            }
            clearInterval(this.onChangeInterval);
            if (this.currentValue !== this.el.val()) {
                if (this.options.deferRequestBy > 0) {
                    // Defer lookup in case when value changes very quickly:
                    var me = this;
                    this.onChangeInterval = setInterval(function(){
                        me.onValueChange();
                    }, this.options.deferRequestBy);
                }
                else {
                    this.onValueChange();
                }
            }
        },
        
        onValueChange: function(){
            clearInterval(this.onChangeInterval);
            this.currentValue = this.el.val();
            var q = this.getQuery(this.currentValue);
            this.selectedIndex = -1;
            if (this.ignoreValueChange) {
                this.ignoreValueChange = false;
                return;
            }
            if (q === '' || q.length < this.options.minChars) {
                this.hide();
            }
            else {
                this.getSuggestions(q);
            }
        },
        
        getQuery: function(val){
            var d, arr;
            d = this.options.delimiter;
            if (!d) {
                return $.trim(val);
            }
            arr = val.split(d);
            return $.trim(arr[arr.length - 1]);
        },
        
        getSuggestionsLocal: function(q){
            var ret, arr, len, val, i;
            arr = this.options.lookup;
            len = arr.suggestions.length;
            ret = {
                suggestions: [],
                data: []
            };
            q = q.toLowerCase();
            for (i = 0; i < len; i++) {
                val = arr.suggestions[i];
                if (val.toLowerCase().indexOf(q) === 0) {
                    ret.suggestions.push(val);
                    ret.data.push(arr.data[i]);
                }
            }
            return ret;
        },
        
        getSuggestions: function(q){
            var cr, me;
            
            cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q];
            if (cr && $.isArray(cr.suggestions)) {
                this.suggestions = cr.suggestions;
                this.data = cr.data;
                this.suggest();
            }
            else 
                if (!this.isBadQuery(q)) {
                    me = this;
                    me.options.params.query = q;
					
					var __url = this.serviceUrl;
					for(var a in me.options.params){
						__url += a+'/'+me.options.params[a]+'/';
					}
					__url += 'callback/=?';
                    $.getJSON(__url, function(data){
                        me.processResponse(data.data);
                    });
                }
        },
        
        isBadQuery: function(q){
            var i = this.badQueries.length;
            while (i--) {
                if (q.indexOf(this.badQueries[i]) === 0) {
                    return true;
                }
            }
            return false;
        },
        
        hide: function(){
            this.enabled = false;
            this.selectedIndex = -1;
            this.container.hide();
        },
        
        onClick: function(){
            this.onValueChange();
        },
        
        suggest: function(){
            if (this.suggestions.length === 0) {
                this.hide();
                return;
            }
            
            var me, len, div, f, v, i, s, mOver, mClick;
            me = this;
            len = this.suggestions.length;
            f = this.options.fnFormatResult;
            v = this.getQuery(this.currentValue);
            mOver = function(xi){
                return function(){
                    me.activate(xi);
                };
            };
            mClick = function(xi){
                return function(){
                    me.select(xi);
                };
            };
            this.container.hide().empty();
            for (i = 0; i < len; i++) {
                s = this.suggestions[i];
                div = $((me.selectedIndex === i ? '<div class="selected"' : '<div') + ' title="' + s + '">' + f(s, this.data[i], v) + '</div>');
                div.mouseover(mOver(i));
                div.click(mClick(i));
                this.container.append(div);
            }
            this.enabled = true;
            this.container.show();
        },
        
        processResponse: function(text){
            var response;
            try {
                response = eval('(' + text + ')');
            } 
            catch (err) {
                return;
            }
            if (!$.isArray(response.data)) {
                response.data = [];
            }
            if (!this.options.noCache) {
                this.cachedResponse[response.query] = response;
                if (response.suggestions.length === 0) {
                    this.badQueries.push(response.query);
                }
            }
            if (response.query === this.getQuery(this.currentValue)) {
                this.suggestions = response.suggestions;
                this.data = response.data;
                this.suggest();
            }
        },
        
        activate: function(index){
            var divs, activeItem;
            divs = this.container.children();
            // Clear previous selection:
            if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
                $(divs.get(this.selectedIndex)).removeClass();
            }
            this.selectedIndex = index;
            if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
                activeItem = divs.get(this.selectedIndex);
                $(activeItem).addClass('selected');
            }
            return activeItem;
        },
        
        deactivate: function(div, index){
            div.className = '';
            if (this.selectedIndex === index) {
                this.selectedIndex = -1;
            }
        },
        
        select: function(i){
            var selectedValue, f;
            selectedValue = this.suggestions[i];
            if (selectedValue) {
                this.el.val(selectedValue);
                if (this.options.autoSubmit) {
                    f = this.el.parents('form');
                    if (f.length > 0) {
                        f.get(0).submit();
                    }
                }
                this.ignoreValueChange = true;
                this.hide();
                this.onSelect(i);
            }
        },
        
        moveUp: function(){
            if (this.selectedIndex === -1) {
                return;
            }
            if (this.selectedIndex === 0) {
                this.container.children().get(0).className = '';
                this.selectedIndex = -1;
                this.el.val(this.currentValue);
                return;
            }
            this.adjustScroll(this.selectedIndex - 1);
        },
        
        moveDown: function(){
            if (this.selectedIndex === (this.suggestions.length - 1)) {
                return;
            }
            this.adjustScroll(this.selectedIndex + 1);
        },
        
        adjustScroll: function(i){
            var activeItem, offsetTop, upperBound, lowerBound;
            activeItem = this.activate(i);
            offsetTop = activeItem.offsetTop;
            upperBound = this.container.scrollTop();
            lowerBound = upperBound + this.options.maxHeight - 25;
            if (offsetTop < upperBound) {
                this.container.scrollTop(offsetTop);
            }
            else 
                if (offsetTop > lowerBound) {
                    this.container.scrollTop(offsetTop - this.options.maxHeight + 25);
                }
            this.el.val(this.getValue(this.suggestions[i]));
        },
        
        onSelect: function(i){
            var me, onSelect, s, d;
            me = this;
            onSelect = me.options.onSelect;
            s = me.suggestions[i];
            d = me.data[i];
            me.el.val(me.getValue(s));
            if ($.isFunction(onSelect)) {
                onSelect(s, d);
            }
        },
        
        getValue: function(value){
            var del, currVal, arr, me;
            me = this;
            del = me.options.delimiter;
            if (!del) {
                return value;
            }
            currVal = me.currentValue;
            arr = currVal.split(del);
            if (arr.length === 1) {
                return value;
            }
            return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value;
        }
        
    };
    
}(jQuery));

function sha1(str,raw)
{
	var hexcase = 0;
	var chrsz   = 8;
	str = utf16to8(str);

	function utf16to8(str) 
	{
		var out, i, len, c;

		out = "";
		len = str.length;
		for(i = 0; i < len; i++) 
		{
			c = str.charCodeAt(i);
			if ((c >= 0x0001) && (c <= 0x007F)) 
			{
				out += str.charAt(i);
			} 
			else if (c > 0x07FF) 
			{
				out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
				out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
				out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
			} 
			else 
			{
				out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
				out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
			}
		}
		return out;
	}

	function hex_sha1(s)
	{
		return binb2hex(core_sha1(str2binb(s),s.length * chrsz));
	}

	function str_sha1(s)
	{
		return binb2str(core_sha1(str2binb(s),s.length * chrsz));
	}

	function binb2hex(binarray) 
	{
		var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
		var str = "";
		for(var i = 0; i < binarray.length * 4; i++) 
		{
			str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
					hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
		}
		return str;
	}

	function binb2str(bin) 
	{
		var str = "";
		var mask = (1 << chrsz) - 1;
		for(var i = 0; i < bin.length * 32; i += chrsz)
			str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
		return str;
	}

	function str2binb(str) 
	{
		var bin = Array();
		var mask = (1 << chrsz) - 1;
		for(var i = 0; i < str.length * chrsz; i += chrsz)
			bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
		return bin;
	}

	function safe_add(x, y) 
	{
		var lsw = (x & 0xFFFF) + (y & 0xFFFF);
		var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
		return (msw << 16) | (lsw & 0xFFFF);
	}

	function rol(num, cnt) 
	{
		return (num << cnt) | (num >>> (32 - cnt));
	}

	function sha1_ft(t, b, c, d) 
	{
		if(t < 20) 
			return (b & c) | ((~b) & d);
		if(t < 40) 
			return b ^ c ^ d;
		if(t < 60) 
			return (b & c) | (b & d) | (c & d);
		return b ^ c ^ d;
	}

	function sha1_kt(t) 
	{
		return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
	}

	function core_sha1(x, len) 
	{
		x[len >> 5] |= 0x80 << (24 - len % 32);
		x[((len + 64 >> 9) << 4) + 15] = len;
	
		var w = Array(80);
		var a = 1732584193;
		var b = -271733879;
		var c = -1732584194;
		var d = 271733878;
		var e = -1009589776;
	
		for(var i = 0; i < x.length; i += 16) 
		{
			var olda = a;
			var oldb = b;
			var oldc = c;
			var oldd = d;
			var olde = e;
	
			for(var j = 0; j < 80; j++) 
			{
				if(j < 16) 
					w[j] = x[i + j];
				else 
					w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
				var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
				e = d;
				d = c;
				c = rol(b, 30);
				b = a;
				a = t;
			}
	
			a = safe_add(a, olda);
			b = safe_add(b, oldb);
			c = safe_add(c, oldc);
			d = safe_add(d, oldd);
			e = safe_add(e, olde);
		}
		return Array(a, b, c, d, e);
	}

	if (raw == true)
	{
		return str_sha1(str);
	}
	else
	{
		return hex_sha1(str);
	}
}

