﻿
//JS订单类
var ShopCart = new function()
{
    this.orderCookieName = "orderCookies";
    this.userInfoCookieName = "userInfoCookie";
    this.wantTimeLimit = 30;
	this.moveCart = function(_divID)
	{
		if (typeof window.pageXOffset != 'undefined') {
			scrollPosTop = window.pageYOffset;
			scrollPosLeft = window.pageXOffset;
		}
		else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
			scrollPosTop = document.documentElement.scrollTop;
			scrollPosLeft = document.documentElement.scrollLeft;
		}
		else if (typeof document.body != 'undefined') {
			scrollPosTop = document.body.scrollTop;
			scrollPosLeft = document.body.scrollLeft;
		}
		var shopDiv = document.getElementById(_divID);
		if(scrollPosTop <= 130)
		{
			shopDiv.style.top = "130px"
		}else{
			shopDiv.style.top = (scrollPosTop + 11) + "px";
		}
	};
	
    this.changeOpacity = function(_divID,_opacity)
	{
		var _div = document.getElementById(_divID);
		if(_div == null) return;
		_div.style.filter = "alpha(opacity=" + _opacity + ")";
		_div.style.opacity = (_opacity/100).toString();
	};
	//隐藏订餐列表
	this.hiddenCart = function(_divID,_replaceDivID)
	{
		var shopDiv = document.getElementById(_divID)
		shopDiv.style.display = "none";
		ShopCart.changeOpacity(_replaceDivID,100);
	};
    //显示订餐列表
    this.showCart = function(_divID,_divWidth,emptyNoticeMsg)
    {
        var cookies = new JSCookie();
		var _mealIdList = cookies.GetCookie(this.orderCookieName);
		//alert(_mealIdList);
        if (_mealIdList == null || _mealIdList == "undefined")//如果为0，不显示购物车
		{
			if(document.getElementById(_divID) !=null)	this.hiddenCart(_divID,"rightArea");
			if(emptyNoticeMsg!='undefined' && emptyNoticeMsg!=null) alert(emptyNoticeMsg);
			return false;
		}
        var arrayMealId = _mealIdList.split('|');
    	var body = document.getElementsByTagName("body")[0];
	    var scrollPosTop,scrollPosLeft;
	    if (typeof window.pageXOffset != 'undefined') {
		    scrollPosTop = window.pageYOffset;
		    scrollPosLeft = window.pageXOffset;
	    }
	    else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
		    scrollPosTop = document.documentElement.scrollTop;
		    scrollPosLeft = document.documentElement.scrollLeft;
	    }
	    else if (typeof document.body != 'undefined') {
		    scrollPosTop = document.body.scrollTop;
		    scrollPosLeft = document.body.scrollLeft;
	    }
	    
	    if(document.getElementById(_divID)==null){
		    var div = document.createElement("div");
		    div.style.position = "absolute";
		    //div.style.top = (scrollPosTop + 500) + "px";
		    div.style.left = (scrollPosLeft + 810) + "px";
		    div.style.width = _divWidth + "px";
		    //div.style.margin = "-50px 0 0 -100px";		
		    //div.style.padding = "5px";
		    //div.style.backgroundColor = "#F5F5F5";
		    //div.style.border = "1px dotted #333333";
		    //div.style.color = "#FFFFFF";
		    div.style.fontSize = "12px";
		    div.style.display = "none";
		    div.style.zIndex = "1001";
		    div.id = _divID;
		    body.appendChild(div);
	    }

        var shopDiv = document.getElementById(_divID);
        var _mealCount = arrayMealId.length;
        shopDiv.innerHTML = "<table cellspacing=0 cellpadding=0 style='background:url(images/cartTop.gif) no-repeat; height:26px;'><tr><td width="+ (_divWidth-20) +" class='LightText01' style='padding-left:5px;'>饭盒子里有<span style='margin-left:5px; margin-right:5px;'>"+_mealCount+" 种</span>餐点 </td><td id='"+_divID+"closeInco' title='关闭' style='cursor:pointer; color:#999999' align='right'><img src=\"images/iconClose.gif\"  style=\"margin-left:5px; margin-right:5px;\" /></td></tr></table>";
		/**/
        var mealListStr="";
		var _totalQuantity=0,_totalPrice=0;
        for(var i = 0; i < arrayMealId.length; i++)
        {
			if(cookies.GetCookie(arrayMealId[i]) != null){
			    if(i>0){ mealListStr += ""; }
			    var _mQuantity = cookies.GetChild(arrayMealId[i],"mQuantity");
			    var _mPrice = cookies.GetChild(arrayMealId[i],"mPrice");
			    _totalQuantity += parseInt(_mQuantity);
			    _totalPrice += parseFloat(_mPrice)*parseInt(_mQuantity);
                mealListStr += "<div style='border-bottom:solid 1px #CCCCCC; margin-top:5px; margin-bottom:5px; padding-bottom:5px;'> <span class='LightText05'>" + cookies.GetChild(arrayMealId[i],"mTitle") + "</span>  <img src='images/icon_del.gif' style='border:0px; cursor:pointer; margin-left:11px;' title='删除' onclick='ShopCart.delFromCart(\"" + arrayMealId[i].substr(4) + "\")'>  <br/>  ￥" + _mPrice + " × " + "<input type='text' id=" + arrayMealId[i] + " value=" + _mQuantity + " size='2' style='width:15px; margin-bottom:-2px;' onchange='ShopCart.modifyQuanity(\"" + arrayMealId[i].substr(4) + "\",this.value);' /> 份</div>";
            }else{
                this.delFromCart(arrayMealId[i].substr(4));
            }
        }
		mealListStr ="<div style='margin:5px; background:#FFFFFF; padding:5px;' >" + mealListStr + "</div>";
		var _info = cookies.GetCookie(this.userInfoCookieName),_address = "",_trueName = "", _wantTime = this.wantTimeLimit;
		if(_info!="undefined" && _info != null){
		    if(cookies.GetChild(this.userInfoCookieName,"address")!="undefined" && cookies.GetChild(this.userInfoCookieName,"address")!=null) _address = cookies.GetChild(this.userInfoCookieName,"address");
		    if(cookies.GetChild(this.userInfoCookieName,"trueName")!="undefined" && cookies.GetChild(this.userInfoCookieName,"trueName")!=null) _trueName = cookies.GetChild(this.userInfoCookieName,"trueName");
		    if(cookies.GetChild(this.userInfoCookieName,"wantTime")!="undefined" && cookies.GetChild(this.userInfoCookieName,"wantTime")!=null) _wantTime = cookies.GetChild(this.userInfoCookieName,"wantTime");
		}else{
		    _info = cookies.GetCookie("loginCookies");
		    if(_info!="undefined" && _info != null){
		        _address = cookies.GetChild("loginCookies","address");
		        _trueName = cookies.GetChild("loginCookies","trueName");
		        ShopCart.saveUserInfo("address",_address);
		        ShopCart.saveUserInfo("trueName",_trueName);
		        ShopCart.saveUserInfo("wantTime",_wantTime);
		    }
		}
	    if(_info!="undefined" && _info != null) mealListStr += "<div style='margin:5px; background:#FFFFFF; padding:5px;' >时间:<input type='text' id='wantTime' value='"+ _wantTime +"' style='width:25px;margin-bottom:5px;' onchange='ShopCart.setWantTime(this.value);' /> 分钟后送至<br>地址:<input type='text'value='"+ _address +"' style='width:135px;margin-bottom:5px;' onchange='ShopCart.saveUserInfo(\"address\",this.value);' /><br>昵称:<input type='text'value='"+ _trueName +"' style='width:50px;' onchange='ShopCart.saveUserInfo(\"trueName\",this.value);' /></div>";
		mealListStr += "<div style='margin:10px; margin-top:11px;'><span style='margin-right:21px;'>总计 ￥" + _totalPrice + " 元</span> <img src='images/icon_sendOrder.gif' style='margin-bottom:-3px; cursor:pointer;' onclick='ShopCart.sendOrderList();' /></div>";
		shopDiv.innerHTML += "<div style='border:1px solid #CCCCCC; background:#F5F5F5;'>" + mealListStr + "</div>";

		var _replaceDiv = document.getElementById("rightArea");
	    if(_replaceDiv.style.display != "none")
	    {
			this.changeOpacity("rightArea",5);
            shopDiv.style.display = "block";
            var _timer = setInterval("ShopCart.moveCart(\"" + _divID + "\");", 500);	    
	    }
       
        //点击关闭窗口
        var closeIcon = document.getElementById(_divID+"closeInco");
        closeIcon.onclick = function(){
            shopDiv.style.display = "none";
			ShopCart.changeOpacity("rightArea",100);
        }
    };

    //加入订餐列表
    this.addToCart = function(_businessId,_mealId,_mealName,_mealPrice,_mealQuantity)
    {
        if(_mealQuantity == null) _mealQuantity = 1;
        if(_mealName!=null && _mealPrice!=null){
            var cookies = new JSCookie();
            var expireHour = 2;
            var orderCookieValue = cookies.GetCookie(this.orderCookieName);
            var _isExist = false;
            if(orderCookieValue == null)
            {
                orderCookieValue = "meal" + _mealId;
            }else{
                var arrayMealId = orderCookieValue.split('|');
                for(var i=0;i<arrayMealId.length;i++){
                    if(arrayMealId[i] == "meal" + _mealId)
                    {
                        _isExist = true;
                        break;
                    }
                }
                if(!_isExist) orderCookieValue = orderCookieValue.Trim().substr(0,orderCookieValue.length+1) + "|meal" + _mealId;
            }
            if(_isExist && cookies.GetCookie(arrayMealId[i])!=null)
            {
                this.modifyQuanity(_mealId,parseInt(cookies.GetChild("meal" + _mealId,"mQuantity")) + _mealQuantity);
            }else{
                cookies.SetCookie(this.orderCookieName,orderCookieValue,expireHour);
                cookies.SetChild("meal" + _mealId,"mTitle",_mealName,expireHour);
                cookies.SetChild("meal" + _mealId,"mPrice",_mealPrice,expireHour);
                cookies.SetChild("meal" + _mealId,"mQuantity",_mealQuantity,expireHour);  
                cookies.SetChild("meal" + _mealId,"businessId",_businessId,expireHour);
            }
        }
        this.showCart("shopCart","200");
    };
    
    //从订餐列表删除
    this.delFromCart = function(_mealId)
    {
		var cookies = new JSCookie();
		var expireHour = 2;
		var _mealIdList = cookies.GetCookie(this.orderCookieName);
		var arrayMealId = _mealIdList.split('|');
		_mealIdList = "";
		for(var i=0;i<arrayMealId.length;i++)
		{
			if("meal" + _mealId != arrayMealId[i] )
			{
				if(_mealIdList != "") _mealIdList += "|";
				_mealIdList += arrayMealId[i];
			}
		}
		
		cookies.Expire("meal" + _mealId);
		if(_mealIdList!="")
		{
			cookies.SetCookie(this.orderCookieName,_mealIdList,expireHour);
		}else{
			cookies.Expire(this.orderCookieName);
		}

		this.showCart("shopCart","200");
    };
    
    //修改菜点数量
    this.modifyQuanity = function(_mealId,_mealQuantity)
    {
        var cookies = new JSCookie();
        var expireHour = 2;
        cookies.SetChild("meal" + _mealId,"mQuantity",_mealQuantity,expireHour);
		this.showCart("shopCart","200");
    };
    
    //发送订餐订单
    this.sendOrderList = function()
    {
	    var afterSendOrderList = function(_obj){
            var statusCode,statusTitle;
            var xmlDoc=_obj.responseXML;
            var showElements = xmlDoc.getElementsByTagName("status")[0];
            if(showElements!=null){
                statusCode = showElements.getAttribute("code");
                statusTitle = showElements.getAttribute("title");
            }
            
            switch (statusCode) {
                case "0" :
                    var showSubElements = xmlDoc.getElementsByTagName("orderStatus");
                    var alertContent = statusTitle+"\n\n";
                    var cookies = new JSCookie();
                    for(var j=0;j<showSubElements.length;j++){
                        var businessTitle = showSubElements[j].getAttribute("businessTitle");
                        if(showSubElements[j].getAttribute("code")=="0"){
                            alertContent +="√ "+(j+1)+" "+businessTitle;
                            //删除成功发送的订单
                            var arrayMealCookiesDel=showSubElements[j].getAttribute("mealCookiesDel").split(',');
                            for(var n=0;n<arrayMealCookiesDel.length;n++){ ShopCart.delFromCart(arrayMealCookiesDel[n].replace("meal","")); }
                        }else{
                            alertContent+="× "+(j+1)+" "+businessTitle;
                            alertContent+=" <失败>: ";
                        }
                        alertContent+=showSubElements[j].getAttribute("content")+"\n";
                        //if(showSubElements[j].getAttribute("code")=="8") alertContent+=showSubElements[j].getAttribute("workTime")+"\n";
                    }
                    alert(alertContent);
                    break;
                case "1" :
                    if(confirm(statusTitle+"\n登录后才能使用在线订餐,要登录吗?")) window.location.href = "/memberLogin.aspx?perUrl="+escape(window.location.href);
                    break;
                case "2" :
                    if(confirm(statusTitle+"\n请确保你的手机通过了验证。\n\n要更新您的资料么？")) window.location.href = "/MemberUpd.aspx?perUrl="+escape(window.location.href);
                    break;
                case "4" :
                    alert(statusTitle + "\n请重新发送订单。\n\n可能的原因:网络延时。");
                    break;
                default:
                    alert(statusTitle);
            } 
        };
        
        var cookies = new JSCookie();
        var _loginInfo = cookies.GetCookie(this.userInfoCookieName)
        var _address="",_trueName="",_wantTime="";
        if(_loginInfo == null || _loginInfo == "undefined"){
            if(confirm("登录后才能使用在线订餐,要登录吗?")) window.location.href = "memberLogin.aspx?perUrl="+escape(window.location.href);
            return false;
        }
        _address=cookies.GetChild(this.userInfoCookieName,"address");
        _trueName=cookies.GetChild(this.userInfoCookieName,"trueName");
        if(_address == null || _address == "undefined") {
            alert("您没有填写送餐地址.");
            return false;
        }else if(_trueName == null || _trueName == "undefined"){
            alert("请留下您的称呼.")
            return false;
        }
        
        _wantTime=cookies.GetChild(this.userInfoCookieName,"wantTime");
        if(_wantTime == null || _wantTime == "undefined") _wantTime=this.wantTimeLimit;
        if(_wantTime<this.wantTimeLimit){
            alert("预订送达时间不能少于"+this.wantTimeLimit+"分钟");
            return false;
        }
        
        if(confirm("您选择的餐点将生成订单并发送\n\n"+_wantTime+"分钟后,送至：<"+_address+","+_trueName+"> 确定？")){
            var orderOperatorUrl;
            orderOperatorUrl = "OrderOperator.aspx";
            Request.send(orderOperatorUrl,"",afterSendOrderList,"urlData");
        }
    };
	
	this.setWantTime = function(_wantTime){
	    _wantTime = _wantTime.replace(/[^\d]/g,'')
        if(_wantTime>=this.wantTimeLimit){
	        ShopCart.saveUserInfo("wantTime",_wantTime);
	    }else{
	        alert("预约时间不能小于"+this.wantTimeLimit+"分钟。");
	        document.getElementById("wantTime").value=this.wantTimeLimit;
	    }
	}
    
    this.saveUserInfo = function(_userInfoKey,_value){
        var cookies = new JSCookie();
        var expireHour = 2;
        cookies.SetChild(this.userInfoCookieName,_userInfoKey,_value,expireHour);
    }
}