var ctx = "";
var c_UserInfo = "";
var c_UserID = "";
$$(document).ready(function() {
	// 初始化top
	// 未登录时候
	if("" == c_UserInfo || "null" == c_UserInfo)
	{		
		$$("#doLogin").hide();
		$$("#notLogin").show();
		$$("#userLogoutLink").hide();
		$$("#userNotLoginShow").show();
	} 
	else 
	{
		$$("#userNotLoginShow").hide();
		$$("#notLogin").hide();
		$$("#doLogin").show();
		$$("#userLogoutLink").show();
	}

	ninfor.post(ctx+"/commons/userInfo.shtml?method=initNewMsgNum", {userId: c_UserID}, null, function(text) {
		eval("var obj = "+text);
		$$("b[id^='newMsgNum']").each(function() {
			$$(this).html(obj.num);
		});
	});

});

function goOrderMsg(){
	window.location.href = ctx+"/commons/index.shtml?method=initOrderMsgCtrl";
}


// 登录输入提示
function txtTipInput(vObj, strTip){
    var m_oTxt    = typeof(vObj)=="object" ? vObj : document.getElementById(vObj);
    if(m_oTxt==null)
        return;
    
    function in_onFocus()
    {               
        if(m_oTxt.value=="" || m_oTxt.value==strTip)    
        {
            m_oTxt.value = "";
        }
    }
    
    function in_onBlur()
    {
        if(m_oTxt.value=="")
            m_oTxt.value = strTip;
    }
    
    m_oTxt.onfocus = in_onFocus;
    m_oTxt.onblur = in_onBlur;
    in_onBlur();  
}

var diag_login = null;
$$(document).ready(function() {
	if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent) {
	   alphaBackgrounds();
	}
	$$("#changeCity").bind("click",function(){ // 切换城市
		$$("#topTips").slideToggle("slow");
		var a=$$("#topTips").attr('name').replace(/topTips_/,"");
		$$("#topTips").css('width',59*a);
	});
	$$("#topTips").bind("mouseleave",function(event){
		$$(this).hide();
		var a=$$("#topTips").attr('name').replace(/topTips_/,"");
		$$("#topTips").css('width',59*a);
	});
	
	$$("a[id^='netUserLogin']").bind("click", netUserLogin); // 用户登录
	$$("a[id^='userLogout']").bind("click", userLogout); // 用户退出
	$$("#setAsHomepage").bind("click", function() { // 设置首页
		if (document.all){  
			document.body.style.behavior = 'url(#default#homepage)';  
	        document.body.setHomePage('http://www.aifan.com');  
	    } else if (window.sidebar){  
	        if (window.netscape){  
	            try {  
	                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
	            } catch(e) {  
	                alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true");  
	            }
	        }
			var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);  
			prefs.setCharPref('browser.startup.homepage', 'http://www.aifan.com');  
		}  
	});

	// 通用意见反馈方法 ddl 2010-4-2 1:58:00
	$$("a[id^='messageHelp']").bind("click", function() {
		window.location.href = ctx+"/jsp/helpcenter/help_message.jsp";
	});
	
	$$("#tuanLogin").click(function(){
		netUserLogin(goTuanStep);
	});
});



function goTuanStep(){
	diag_tuan = new Dialog("Diag1");
	diag_tuan.Width = 569;
	diag_tuan.Title = "服务条款";
	diag_tuan.SkinPath= ctx+"/scripts/dialog/skin/canting/";
	diag_tuan.innerElementId = "showTuanService";
	diag_tuan.okBtnShow=false;//确认按钮是否显示
	diag_tuan.cancelBtnShow=false;//取消按钮是否显示
	diag_tuan.OKEvent = function(){
		window.location.href = ctx+"/group/group.shtml?method=initGroupFeast";
	};
	diag_tuan.CancelEvent = function() {
		diag_tuan.close();
	}
	diag_tuan.showD();
	return true;
}


function netUserLogin(fnCall) {
	var args=[];

	if(fnCall && typeof(fnCall)== "function")
	{
		for(var i=1; i<arguments.length; i++)
	        args.push(arguments[i]);
	}					        	

	//-已登录-
	if($$("#netUserName").html() != "")
	{ 
		if(fnCall && typeof(fnCall)== "function")
            fnCall.apply(window, args);
		return true;
	}
		        
	diag_login = new Dialog("Diag1");
	diag_login.Width = 569;
	diag_login.Title = "用户登录";
	diag_login.SkinPath= ctx+"/scripts/dialog/skin/canting/";
	diag_login.innerElementId = "showNetUserLogin";
	diag_login.okBtnShow=false;//确认按钮是否显示
	diag_login.cancelBtnShow=false;//取消按钮是否显示
	diag_login.OKEvent = function() {
		var netUserLoginName = ($$("#netUserLoginName").val() == "请输入邮箱或手机号")? "":$$("#netUserLoginName").val();
		var netUserPwd = $$("#netUserPwd").val();
		if(ninfor.trim(netUserLoginName) == ""){
			$$("#showMsg").html("<font color='#FF0000'>请输入用户名！</font>");
			return false;
		}
		if(!ninfor.checkMobilePhoneNum(netUserLoginName) && !ninfor.checkEmail(netUserLoginName)){
			$$("#showMsg").html("<font color='#FF0000'>错误的用户名！请输入手机或邮箱</font>");
			return false;
		}
		if(netUserPwd == ""){
			$$("#showMsg").html("<font color='#FF0000'>请输入密码！</font>");
			return false;
		}
		var isRememberMe = $$("#rememberMe").get(0).checked;
		ninfor.post(
				ctx+'/commons/userInfo.shtml?method=userLogin',
			{loginName: ninfor.trim(netUserLoginName), password: netUserPwd, isRememberMe: isRememberMe},
			null,
			function(text){
				eval("var obj = "+text);
				if(obj.success == "unValidation")
				{
					$$("#showMsg").html("<font color='blue'>"+obj.msg+"<a onclick='validateNow("+obj.userId+");' class='red'>现在验证？</a></font>");
				} 
				else if(obj.success == "true" || obj.success == "firstLogin")
				{
					if(obj.success == "true")
					{
						diag_login.close();
					} 
					else if(obj.success == "firstLogin")
					{
						diag_login.close();
						showFirstLogin();
					}
					// 登录成功，写cookie
					ninfor.writeCookies(obj.loginName, obj.password);
					
					// 如果选择了“记住我”
					if(obj.isRememberMe == "true")
					{ 
						ninfor.cookie('COOKIE_NET_USER_NAME', obj.loginName, {expires: 30, path: '/', domain: 'aifan.com'});
						ninfor.cookie('COOKIE_NET_USER_PWD', obj.password, {expires: 30, path: '/', domain: 'aifan.com'});
					}
					
					$$("#userNotLoginShow").hide();
					$$("#notLogin").hide();
					$$("#netUserName").html(obj.userName);
					$$("b[id^='newMsgNum']").each(function() {
						$$(this).html(obj.num);
					});
					$$("#doLogin").show();
					$$("#newMsgSpan").show();
					$$("#userLogoutLink").show();
					$$(".new-login").hide();
					
					//-登录成功，非第一次-
					if(obj.success == "true" && fnCall && typeof(fnCall)== "function")
					{
			            fnCall.apply(window, args);
					}
				} 
				else 
				{
					$$("#showMsg").html("<font color='blue'>"+obj.msg+"</font>");
				}
			}
		)
	};
	diag_login.CancelEvent = function() {
		$$("#netUserLoginName").val("");
		$$("#netUserPwd").val("");
		$$("#rememberMe").attr("checked", "");
		$$("#showMsg").html("");
		diag_login.close();
	}
	diag_login.showD();
	txtTipInput('netUserLoginName', "请输入邮箱或手机号");
	return true;
}

function userLogout() {
	ninfor.cookie('COOKIE_NET_USER_NAME', null, {domain: 'aifan.com', path: '/'});
	ninfor.cookie('COOKIE_NET_USER_PWD', null, {domain: 'aifan.com', path: '/'});
	ninfor.cookie('COOKIE_NET_USER_NAME_AUTO', null, {domain: 'aifan.com', path: '/'});
	ninfor.cookie('COOKIE_NET_USER_PWD_AUTO', null, {domain: 'aifan.com', path: '/'});
	ninfor.post(ctx+'/commons/userInfo.shtml?method=userLogout');
}

function validateNow(userId) {
	var loginName = $$("#netUserLoginName").val();
	ninfor.post(ctx+'/commons/userInfo.shtml?method=validateNow', {userId: userId, loginName: loginName});
}

function updateInfoNow() {
	window.location.href = ctx+'/jsp/user/personal_ctrl_basic.jsp';
}

function leaveMeAlone(){
	diag_login.close();
}
			
function alphaBackgrounds(){
   var rslt = navigator.appVersion.match(/MSIE (d+.d+)/, '');
   var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
   for (i=0; i<document.all.length; i++){
      var bg = document.all[i].currentStyle.backgroundImage;
      if (bg){
         if (bg.match(/.png/i) != null){
            var mypng = bg.substring(5,bg.length-2);
   //alert(mypng);
            document.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+mypng+"', sizingMethod='crop')";
            document.all[i].style.backgroundImage = "url('')";
   //alert(document.all[i].style.filter);
         }                                              
      }
   }
}

var diag_firstLogin = new Dialog("diag_firstLogin");
function showFirstLogin() {
	diag_firstLogin.Width = 569;
	diag_firstLogin.Title = "提示";
	diag_firstLogin.SkinPath = ctx+"/scripts/dialog/skin/canting/";
	diag_firstLogin.innerElementId = "showFirstLoginMsg";
	diag_firstLogin.okBtnShow = false;
	diag_firstLogin.cancelBtnShow = false;
	diag_firstLogin.showD();
}

//加入收藏代码 Start
function AddFavorite(url, title) { 
	if (document.all) {
		try {
			window.external.addFavorite(url, title);
		} 
		catch (e1) {
			try {
				window.external.addToFavoritesBar(url, title, "slice");
			} catch (e2) {
				alert('加入收藏失败，请使用"ctrl+d"加入。')
			}
		}
	} else if (window.sidebar) {
		window.sidebar.addPanel(title, url, "");
	} else if (window.external) {
		window.sidebar.addPanel(title, url, "");
	} else {
		alert('加入收藏失败，请使用"ctrl+d"加入。')
	}
}
//加入收藏代码 End

//and by laichao
var diag_search = null;
function search_destine(){
	diag_search = new Dialog("Diag2");
	diag_search.Width = 570;
	diag_search.Height = 360;
	diag_search.URL = ctx+"/corp/clientOrder.shtml?method=searchDestine";	//chy-check 2010-07-01 localhost:8080/pizza下不起作用
	diag_search.showIframe();
	diag_search.callback_func = function(param){
		 param.lowerAvgExpense=param.lowerAvgExpense==null?"":param.lowerAvgExpense;
		 param.largerAvgExpense=param.largerAvgExpense==null?"":param.largerAvgExpense;
		 param.keyword=param.keyword==null?"":param.keyword;
		 param.date=param.date==null?"":param.date;
		 param.time=param.time==null?"":param.time;
		 param.area=param.area==null?"":param.area;
		 ninfor.post(ctx+"/corp/clientOrder.shtml?method=searchCorpInfo&pageNum=1&lowerAvgExpense="+param.lowerAvgExpense+"&largerAvgExpense="+param.largerAvgExpense+"&date="+param.date+"&time="+param.time+"&area="+param.area+"&orderBy=&reverse=&sign=0"+"&keyword="+param.keyword); 
	}
}

$$(document).ready(function() 
{
	$$("#topSearchBtn").click(function() {
		var keyword = $$.trim($$("#findCorpKey").val());
		if(keyword == "请输入要搜索的餐厅名、地址、菜系，任意关键字..."){
			keyword = "";
		}
		if(keyword == "")
		{
			alert("请输入要搜索的餐厅名、地址、菜系，任意关键字...");
			return;
		}
		ninfor.post(ctx+"/searching/"+ keyword);
	});
	$$("#findCorpKey").keydown(function(e) {		
		if (e.keyCode == 13) {$$("#topSearchBtn").click();return false;}
	}); 
});



//店铺搜索
//店铺搜索
$$(document).ready(function(){
 	$$("#findCorpKey").focus(onFocus);
 	$$("#findCorpKey").blur(onBlur);
 	$$("#findCorpKey").keyup(onInput);
 });

 function onFocus(event) 
 {
 	event.preventDefault();
	if(null)
	{
		doSuggest();
	} 
	else 
	{
		if(ninfor.checkNotNull($$("#findCorpKey").val()))
		{
			doSuggest();
		}
	}
}

function onBlur(event) 
{
	event.preventDefault();
	setTimeout(function() { $$("#suggest_findCorpKey").hide()}, 200);
}

function onInput(event) 
{
	event.preventDefault();
	if(!ninfor.checkNotNull($$("#findCorpKey").val()) && null != "true")
	{
		$$("#suggest_findCorpKey").hide();
		return false;
	}
	if(/13$|27$|38$|40$/.test(event.keyCode))
	{
		switch(event.keyCode)
		{
			case 38:	selectUp();break;
			case 40:	selectDown();break;
			case 13:
				var obj = $$("#suggest_findCorpKey").children("ul").children("li.suggest_select").children("a").html();
				if(obj == '' || obj == null)
				{
					doSuggest();
				} 
				else 
				{
					if("pizza" == "pizza")
					{
						var corpId = document.getElementById(obj).value;							
						window.location.href='/corp/'+corpId;
					}
					selectItem();
				}
				break;
			case 27:	selectEsc();break;
		}
	} 
	else 
	{
		doSuggest();
	}
}

 function doSuggest() 
 {
		var str = $$("#findCorpKey").val();
		ninfor.post(ctx+'/corp/home.shtml?method=getCorpName',
			{str: str},
			null,
			function(text) 
			{
				eval('var obj =' + text );
				display(obj);
			}
		);
}

 function display(obj) 
 {
 	var html = '';
 	if(obj.success == "false")
 	{
			if("pizza" == "pizza")
			{
				html += '<div class="gray"></div>';
			}
			else
			{
				html += '<div class="gray">' + obj.reason + '</div>';
			}
	} 
 	else 
 	{
			var suggestNames = obj.returnStr.split(",");
			var showNum = 0;
			if(null != null)
			{
				showNum = (suggestNames.length > null)? null : suggestNames.length;
			} 
			else 
			{
				showNum = suggestNames.length;
			}
			if(obj.tag == 1)
			{
				for(var i = 0; i != showNum; i++)
				{
					var corpInfo = suggestNames[i].split(":");
					html += '<li><a target=_self href=/corp/'+corpInfo[1]+'>' + corpInfo[0] + '</a><input type=hidden value='+corpInfo[1]+' id='+corpInfo[0]+'></li>';
				}
			}
			else
			{
				for(var i = 0; i != showNum; i++)
				{
					var corpInfo = suggestNames[i].split(":");
					html += '<li><a>'+ corpInfo[0] + '</a></li>';
				}
			}
		}
		html = '<ul>'+ html + '</ul>';
		$$("#suggest_findCorpKey").html(html).show();
		resetPos();
		$$("#suggest_findCorpKey").children('ul')
				.children('li')
				.mouseover(function() {
					$$("#suggest_findCorpKey").children("ul").children("li.suggest_select").removeClass("suggest_select");
					$$(this).addClass("suggest_select");
				})
				.click(function(event) {
				if(obj.tag != 1){
					event.preventDefault();
				}
					selectItem();
				});
	}

function selectUp() 
{
	var $$currentItem = $$("#suggest_findCorpKey").children("ul").children("li.suggest_select");
	if(!$$currentItem.length){
		$$("#suggest_findCorpKey").children("ul").children("li:last-child").addClass("suggest_select");
	} else {
		$$currentItem.removeClass("suggest_select").prev().addClass("suggest_select");
	}
}

function selectDown() 
{
	var $$currentItem = $$("#suggest_findCorpKey").children("ul").children("li.suggest_select");
	if(!$$currentItem.length)
	{
		$$("#suggest_findCorpKey").children("ul").children("li:first-child").addClass("suggest_select");
	} 
	else 
	{
		$$currentItem.removeClass("suggest_select").next().addClass("suggest_select");
	}
}

function selectItem() 
{
	var text = $$("#suggest_findCorpKey").children("ul").children("li.suggest_select").children("a").html();
	var corpInfo = text.split(",");
	$$("#findCorpKey").val(corpInfo[0]);
	$$("#suggest_findCorpKey").hide();
	if(null != null) 
	{
		eval('var cb =' + null );
		cb.apply(text);
	}
}

function selectEsc() 
{
	$$("#findCorpKey").val("");
	$$("#suggest_findCorpKey").hide();
}

function resetPos() 
{
	var offset = $$("#findCorpKey").offset();
	var tagWidth = $$("#findCorpKey").width();
	$$("#suggest_findCorpKey").css({
		top: (offset.top + $$("#findCorpKey").get(0).offsetHeight) + 'px',
		left: '310px',
		width: tagWidth + 'px'
	});
}
