﻿// JScript File

/*-----------------------------------------------
               doPost
-------------------------------------------------*/

function doPost(form,url,step){

function A(){  form.action = url; }
function B(){
               if(document.messageForm.AcceptedWarnings !=null){
			   form.AcceptedWarnings.value = document.messageForm.AcceptedWarnings.value;
			   }
			}
function C(){  form.submit();    }
function D(){  setSearchLimit(); }

var funarr=null;
switch(step){

case "Step3" :  
                   funarr=new Array(A,B,C);
                   ParentdoPost(funarr); 
                   break;

case "Step2" :
                   funarr=new Array(D,A,C); 
                   ParentdoPost(funarr);
                   break;
                   
     default:     
                   funarr=new Array(A,C);
                   ParentdoPost(funarr);
 }
 
}  
                

function ParentdoPost(Array){

for(i=0;i<Array.length;i++){
Array[i]();
}
 
}





/*----------------------------------------------------------------------------------
               DoPost
-------------------------------------------------------------------------------------*/                                            
function DoPost(url) {
	document.Allocations.action=url;
	document.Allocations.submit();
}


/*----------------------------------------------------------------------------------
               setPageFormValues
-------------------------------------------------------------------------------------*/
	
   function setPageFormValues(id){
      document.pageForm.InfoPopupfavorite_name.value = document.getElementById(id).value;
   }
		

/*----------------------------------------------------------------------------------
               SetStarsForServiceRating
-------------------------------------------------------------------------------------*/

   function SetStarsForServiceRating(numberOfStars) {
                document.forms.popupForm.serviceRating.value = numberOfStars;
                var elems = getElementsByClass('current-rating', null, null);
                var elem = elems[1];
                elem.style.width = numberOfStars*20+'%';
        }
        
 
/*----------------------------------------------------------------------------------
               SetStarsForFoodRating
-------------------------------------------------------------------------------------*/ 
 
    function SetStarsForFoodRating(numberOfStars) {
            document.forms.popupForm.foodRating.value = numberOfStars;
            var elems = getElementsByClass('current-rating', null, null);
            var elem = elems[0];
            elem.style.width = numberOfStars*20+'%';
       }


/*----------------------------------------------------------------------------------
               getElementsByClass
-------------------------------------------------------------------------------------*/
       
        function getElementsByClass(searchClass,node,tag) {
            var classElements = new Array();
            if ( node == null )
	        node = document;
            if ( tag == null )
	        tag = '*';
            var els = node.getElementsByTagName(tag);
            var elsLen = els.length;
            var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
            for (i = 0, j = 0; i < elsLen; i++) {
	        if ( pattern.test(els[i].className) ) {
	            classElements[j] = els[i];
	            j++;
	        }
            }
            return classElements;
        }
        
/*----------------------------------------------------------------------------------
                StoreAndClearEmail
-------------------------------------------------------------------------------------*/ 
        
     function StoreAndClearEmail(o) {

		o.style.color = "#333";
		o.style.fontWeight = "normal";

		if (o.value == 'Enter Email Address') {
		    textFieldStoreAndClear(o);
		}
		else {
		    //If they had an email and delete it, we'll store this to replace an empty box on blur.
		    o.originalText = 'Enter Email Address';
		}
	    }

/*----------------------------------------------------------------------------------
                getCookie
-------------------------------------------------------------------------------------*/ 	    
	    
	    function getCookie(name)
	    {
		var dc = document.cookie;
		var prefix = name + "=";
		var begin = dc.indexOf("; " + prefix);
		if (begin == -1)
		{
		    begin = dc.indexOf(prefix);
		    if (begin != 0) return null;
		}
		else
		{
		    begin += 2;
		}
		var end = document.cookie.indexOf(";", begin);
		if (end == -1)
		{
		    end = dc.length;
		}
		return unescape(dc.substring(begin + prefix.length, end));
	    }

/*----------------------------------------------------------------------------------
                GoToLogin
-------------------------------------------------------------------------------------*/ 	    
  function GoToLogin(consumerRedirectUrl) {
	    	var index = consumerRedirectUrl.lastIndexOf('/') + 1;
	    	var baseUrl = consumerRedirectUrl.substring(0,index);
	    	window.location = baseUrl + "login.m?internalReturnUrl=";
	    }
	 

/*----------------------------------------------------------------------------------
                Set_Cookie
-------------------------------------------------------------------------------------*/
function Set_Cookie( name, value, expires)  {
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime( today.getTime() );
		//alert("TODAY: " + today);
		/*
		if the expires variable is set, make the correct 
		expires time, the current script below will set 
		it for x number of days.  To make it for hours, 
		delete * 24, for minutes, delete * 60 * 24
		*/
		//alert("EXPIRES1: " + expires);
		if ( expires ) {
		    expires = expires * 1000 * 60 * 60 * 24;
		}
		//alert("EXPIRES2: + " + expires);
		var expires_date = new Date( today.getTime() + (expires) );
		//alert("EXPIRES_DATE: " + expires_date);
		document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" );
	    }
	    
	 
/*----------------------------------------------------------------------------------
                delete_cookie 
-------------------------------------------------------------------------------------*/
function delete_cookie ( cookie_name ) {
	      var cookie_date = new Date ( );  // current date & time
	      cookie_date.setTime ( cookie_date.getTime() - 1 );
	      document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
	    }

	    
/*----------------------------------------------------------------------------------
                 popUpVerisign
-------------------------------------------------------------------------------------*/	    
function popUpVerisign(url) {
		sealWin=window.open(url,"win",'toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=500,height=450');
		self.name = "mainWin"; 
}

/*----------------------------------------------------------------------------------
                 DeleteOverageCardAndUpdateAccount
-------------------------------------------------------------------------------------*/

	function DeleteOverageCardAndUpdateAccount() {
		document.my_account_info.OverageCCType.value = "";
		document.my_account_info.OverageCCNumber.value = "";
		document.my_account_info.OverageCCExpYear.value = "";
		document.my_account_info.OverageCCExpMonth.value = "";
		document.my_account_info.OverageCreditCardZipCode.value = "";
		document.my_account_info.OverageCreditCardSecurityCode.value = "";
		document.my_account_info.CCOverageEffectiveMonth.value = "";
		document.my_account_info.CCOverageEffectiveYear.value = "";
		document.my_account_info.OverageCreditCardIssueNumber.value = "";
		document.my_account_info.submit();
	}
/*----------------------------------------------------------------------------------
                DeletePrimaryCardAndUpdateAccount
-------------------------------------------------------------------------------------*/	
	
	function DeletePrimaryCardAndUpdateAccount() {
		document.my_account_info.PrimaryCCType.value = "";
		document.my_account_info.PrimaryCCNumber.value = "";
		document.my_account_info.PrimaryCCExpYear.value = "";
		document.my_account_info.PrimaryCCExpMonth.value = "";
		document.my_account_info.CreditCardZipCode.value = "";
		document.my_account_info.CreditCardSecurityCode.value = "";
		document.my_account_info.CCEffectiveMonth.value = "";
		document.my_account_info.CCEffectiveYear.value = "";
		document.my_account_info.CreditCardIssueNumber.value = "";
		document.my_account_info.submit();
	}	
	
/*----------------------------------------------------------------------------------
                UpdateFavoriteRank
-------------------------------------------------------------------------------------*/
	

	    function UpdateFavoriteRank(templateId){
		var temp;
		temp = allTimeoutIds.split(",");

		for(var i=0; i<temp.length; i++){
		    clearTimeout(temp[i]);
		}

		var favoriteRank = document.getElementById('template_' + templateId).value;

		if(isNaN(favoriteRank)){
		    toggleInProgressGraphic('',false);
		    toggleTableState('favoriteManagementTable',false)
		    alert("Please enter a Valid Favorite Rank. (Numbers Only)");
		    document.getElementById('template_' + templateId).focus();
		}else{
		    CreateCommand('<%=AjaxEnum.UPDATEFAVORITERANK.Code%>',templateId);
		}
	    }
	    

/*----------------------------------------------------------------------------------
                saveFavoriteRank
-------------------------------------------------------------------------------------*/
	    function saveFavoriteRank(templateId){
		checkIfValidKeyPress();
		if(isValidKeyPress){
		    toggleInProgressGraphic('Updating Favorite Rank...',true);
		    toggleTableState('favoriteManagementTable',true);
		    setTimer('UpdateFavoriteRank(' + templateId + ')');
		}
	    }
  

/*----------------------------------------------------------------------------------
               updateFirmLocationSMSCode
-------------------------------------------------------------------------------------*/
function updateFirmLocationSMSCode(firmLocationId){
        var smsLocationCode = document.getElementById('firmLocation_' + firmLocationId);
        smsLocationCode.value = smsLocationCode.value.toUpperCase();
        CreateCommand('<%=AjaxEnum.UPDATEFIRMLOCATIONSMSCODE.Code%>',firmLocationId);
    } 
    
/*----------------------------------------------------------------------------------
               saveFirmLocationCode
-------------------------------------------------------------------------------------*/
  
function saveFirmLocationCode(firmLocationId){
	checkIfValidKeyPress();
	if(isValidKeyPress == true){
	    toggleInProgressGraphic('Updating SMS Location Code...',true);
	    toggleTableState('firmLocationManagementTable',true);
	    setTimer('updateFirmLocationSMSCode(' + firmLocationId + ')');
	}
    }
    
 /*----------------------------------------------------------------------------------
             MakeSureTheyDidntClickSubmitAlreadyThenPost
-------------------------------------------------------------------------------------*/
 function MakeSureTheyDidntClickSubmitAlreadyThenPost(form, url){
			document.getElementById("submit_order_div").innerHTML = "<p>Please wait.<br />We are processing your order.</p>";
			doPost(form, url);
	}
	
/*----------------------------------------------------------------------------------
             RemoveAllocationSearchNameValues
-------------------------------------------------------------------------------------*/
	
function RemoveAllocationSearchNameValues() {
		    if(document.pageForm.LastName != null){
			document.pageForm.LastName.value="";
		    }
		    if(document.pageForm.FirstName != null){
			document.pageForm.FirstName.value="";
		    }
		}

/*----------------------------------------------------------------------------------
             deleteLine
-------------------------------------------------------------------------------------*/

function deleteLine(url,lineId){
		    document.pageForm.LineId.value=lineId;
		    doPost(document.pageForm, url)
		}

/*----------------------------------------------------------------------------------
             FixCurrency
-------------------------------------------------------------------------------------*/
		
function FixCurrency(currencyval) {
		    var zerostring = "";
		    currencyval = currencyval * 100;
		    currencyval = Math.round(currencyval);
		    if (Math.round(currencyval) == Math.round(currencyval / 10) * 10) 
			    zerostring = zerostring + "0";
		    if (Math.round(currencyval) == Math.round(currencyval / 100) * 100)
			    zerostring = ".00";
		    currencyval = currencyval / 100 + zerostring;
		    return currencyval;
}

/*----------------------------------------------------------------------------------
             showRecentEC
-------------------------------------------------------------------------------------*/
function showRecentEC(UserID, EC){
		UserSearchWindow = window.open("RecentExpenseCodes.asp?UserID=" + UserID + "&EC=" + EC, "RecentExpenseCodes","menubar=yes,toolbar=no,width=180,height=190,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no");
}


/*----------------------------------------------------------------------------------
             toggleEditCC
-------------------------------------------------------------------------------------*/
function toggleEditCC (show) {
		    var obj = document.getElementById("EditCreditCardInfo");
		    if (show) {
			obj.style.display = "block";
			obj.style.visibility = "visible";
			document.pageForm.creditCardNumber.focus();
		    } else {
			obj.style.display = "none";
			obj.style.visibility = "hidden";
		    }
}

/*----------------------------------------------------------------------------------
             SetFocusComments
-------------------------------------------------------------------------------------*/
function SetFocusComments() {
		    var obj = document.getElementById("AllocationComment");
		    obj.focus();
}

/*----------------------------------------------------------------------------------
             SelectSingleUser
-------------------------------------------------------------------------------------*/

function SelectSingleUser(userId) {
    document.Allocations.singleUserId.value = userId;
    DoPost('AddAllocations.m');
}


/*----------------------------------------------------------------------------------
             ShowAll
-------------------------------------------------------------------------------------*/
function ShowAll() {
    document.Allocations.lastName.value = '';
    document.Allocations.firstName.value = '';
    document.Allocations.submit();
}


/*----------------------------------------------------------------------------------
             SelectAll
-------------------------------------------------------------------------------------*/
function SelectAll(){
    f=document.forms[0];
    if (checked=="no"){
	for(i=0;i<f.elements.length;i++)
	{if(f.elements[i].name=="selected") 
		if(!f.elements[i].checked) f.elements[i].click();
	}
	checked="yes";
	//f.BottomSelectAll.value = "Clear All";
	//f.TopSelectAll.value = "Clear All";
    } else {
	UnSelectAll()
	//f.BottomSelectAll.value = "Select All";
	//f.TopSelectAll.value = "Select All";
    }
}


/*----------------------------------------------------------------------------------
             UnSelectAll
-------------------------------------------------------------------------------------*/
function UnSelectAll()
{f=document.forms[0];
 for(i=0;i<f.elements.length;i++)
  {if(f.elements[i].name=="selected") 
       if(f.elements[i].checked) f.elements[i].click();
  }
  checked="no";
}


/*----------------------------------------------------------------------------------
             LoginDisplayMessage
-------------------------------------------------------------------------------------*/
 function LoginDisplayMessage() {
		    alert(document.getElementById('displayLoginmessage').value);
 }
 
 /*----------------------------------------------------------------------------------
             ClickTrack
-------------------------------------------------------------------------------------*/
 function ClickTrack(vendorId, page, pageLocation, rank, precedencePolicyId) {
	document.getElementById("ClickRank").value = rank;
	document.getElementById("ClickPage").value = page;
	document.getElementById("ClickPageLocation").value = pageLocation;
	document.getElementById("VendorId").value = vendorId;
	document.getElementById("PrecedencePolicyId").value = precedencePolicyId;
        
	CreateCommand('<% =AjaxEnum.CLICKTRACK.Code %>', vendorId);
}

/*----------------------------------------------------------------------------------
             postURL
-------------------------------------------------------------------------------------*/
function postURL(DestURL,PostAction){
		    document.forms.orderAttributes.postAction.value = PostAction;
		    doPost(document.forms.orderAttributes, DestURL);
}


/*----------------------------------------------------------------------------------
            writeFave
-------------------------------------------------------------------------------------*/
function writeFave(favoriteId) {
		    document.pageForm.favoriteId.value = favoriteId;
}


/*----------------------------------------------------------------------------------
            doSort 
-------------------------------------------------------------------------------------*/
function doSort (searchString) {
		    document.DateSubmit.searchString.value = searchString;
		    document.DateSubmit.submit();
}

/*----------------------------------------------------------------------------------
            clearCateringCategory
-------------------------------------------------------------------------------------*/
function clearCateringCategory(){
		    document.pageForm.cateringCategory.value="";
}

/*----------------------------------------------------------------------------------
            copyAndSaveFavorite
-------------------------------------------------------------------------------------*/
function copyAndSaveFavorite(orderId) {
	    //Copy stuff and things.
	    document.pageForm.InfoPopupfavorite_orderId.value = orderId;
	    document.pageForm.InfoPopupfavorite_name.value = document.getElementById('InfoPopup_name_'+orderId).value;
	    saveFavorite();
}

/*----------------------------------------------------------------------------------
            setPageFormValuesForCateringOrderHistory
-------------------------------------------------------------------------------------*/
function setPageFormValuesForCateringOrderHistory(orderId) {
	    document.pageForm.InfoPopupfavorite_name.value = document.getElementById("InfoPopupfavoriteName_" + orderId ).value;
	    document.pageForm.favoriteDescription.value = document.getElementById("favorite_description_" + orderId).value;   
	    document.pageForm.InfoPopupfavorite_orderId.value = orderId;
	    if(document.getElementById("favorite_type_firm_" + orderId).checked) {
		document.pageForm.favoritePaymentType.value  = "F";
	    } else {
		document.pageForm.favoritePaymentType.value  = "C";
	    }	    
	    var cateringCategory = document.getElementById("InfoPopupCateringFavoriteList_" + orderId);
	    if(cateringCategory != null)
	    {
		document.pageForm.cateringCategory.value  = cateringCategory.options[cateringCategory.selectedIndex].value;
	    }	    
	    saveFavorite();
}


/*----------------------------------------------------------------------------------
             checkIfValidKeyPress
-------------------------------------------------------------------------------------*/
var isValidKeyPress = true;
function checkIfValidKeyPress(e){
    var keycode;

    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;

    if (keycode != 9 && keycode != 144 && keycode != 20) { //9=Tab, 144=NumLock , 20=CapsLock, 
	isValidKeyPress = true;
    }else{
	isValidKeyPress = false;
    }
}


/*----------------------------------------------------------------------------------
          SubmitReturnToOrder
-------------------------------------------------------------------------------------*/
function SubmitReturnToOrder() {
		document.ReturnToOrder.action = "ReturnToOrder.m";
		document.ReturnToOrder.submit();
}


/*----------------------------------------------------------------------------------
          toggleTableState
-------------------------------------------------------------------------------------*/
function toggleTableState(tableId,isDisabled){
                    if(document.getElementById(tableId) != null)
			document.getElementById(tableId).disabled = isDisabled;
}



/*----------------------------------------------------------------------------------
          setTimer
-------------------------------------------------------------------------------------*/
var allTimeoutIds = '';
var timeoutId;
            
  function setTimer(timedFunction){    
                timeoutId = window.setTimeout(timedFunction, 2000); 
                setAllTimeoutIds();
   }
   
   
/*----------------------------------------------------------------------------------
          setAllTimeoutIds
-------------------------------------------------------------------------------------*/
 function setAllTimeoutIds(){
                if(typeof allTimeoutIds != 'undefined'){
                    if(allTimeoutIds != ''){
                        allTimeoutIds += ',' + timeoutId;
                    }else{
                        allTimeoutIds = ',' + timeoutId;
                    }
                }else{
                    allTimeoutIds = ',' + timeoutId;
                }
      }
      
      
/*----------------------------------------------------------------------------------
         ClickAddToOrder
-------------------------------------------------------------------------------------*/ 
 
 function ClickAddToOrder(ajaxEnum,orderId) {
	    if(document.orderAttributes.addToOrderClicked.value != "Y") {
		document.orderAttributes.addToOrderClicked.value="Y";
		CreateCommand(ajaxEnum,orderId);
	    }
}
	

/*----------------------------------------------------------------------------------
         UpdateOrderTipAmount
-------------------------------------------------------------------------------------*/	
function UpdateOrderTipAmount(orderID,cssClass)
	{
	    var tipAmt = document.getElementById('tipAmount').value;	    
	    var params = "Update|" + orderID + "|" + tipAmt.toString() + "|" + cssClass;
	    CreateCommand('29', params);
	}
	
	
/*----------------------------------------------------------------------------------
         adjustItemPrice
-------------------------------------------------------------------------------------*/  
function adjustItemPrice(cartItemCount, totalPrice) {
	    var obj = document.getElementById("totalItemPrice" + cartItemCount);
	    //alert("OBJ: " + obj);
	    if (obj != null) {
		//alert("SETTING PRICE: " + totalPrice);
		obj.innerHTML = totalPrice;
	    }
	}
	
	
/*----------------------------------------------------------------------------------
         SetBirthDateHiddenField
-------------------------------------------------------------------------------------*/	
function SetBirthDateHiddenField() {
	    var strBirthDate = document.my_account_info.user_birth_month.value + "/" + document.my_account_info.user_birth_day.value + "/" + document.my_account_info.user_birth_year.value;
	    
	    document.my_account_info.BirthDate.value = strBirthDate;
}

/*----------------------------------------------------------------------------------
         editPhoneNumber
-------------------------------------------------------------------------------------*/
function editPhoneNumber()
{
	    document.getElementById('validatePhone').style.display = "none";
	    document.getElementById('setupPhone').style.display = "block";
}
	

/*----------------------------------------------------------------------------------
         DisplayAlert
-------------------------------------------------------------------------------------*/
function DisplayAlert() {
		    alert("E-mail successfully sent.");
		}
	
	
/*----------------------------------------------------------------------------------
         toggleInProgressGraphic
-------------------------------------------------------------------------------------*/
function toggleInProgressGraphic(displayText, show){
                if(show){
                    document.getElementById('ajaxIndicatorPlaceHolder').innerHTML = displayText + '<br><br><img src=\"images/ajaxIndicator.gif\" />';
                }else{
                    document.getElementById('ajaxIndicatorPlaceHolder').innerHTML = '';
                }
    }
    
 
/*----------------------------------------------------------------------------------
         EngageSearch
-------------------------------------------------------------------------------------*/ 
function EngageSearch(e,step) {
		    var keycode;
		    if (window.event) keycode = window.event.keyCode;
		    else if (e) keycode = e.which;
		    if (keycode == 13)
		    { 
               switch(step)
			   {
			      case "Thank You":      if (validateUserInfo(this.PersonalEmail, this.Password) == true) {
			                             doPost(document.pageForm, 'ConsumerAccountSetup.m?CorpUserId=<%=model.CurrentUser.UserId.ToString()%>');
		                                 }
		                                 break;
                        			
                  default:              SubmitSearch();
			  }
		    }
}


/*----------------------------------------------------------------------------------
         toggle
-------------------------------------------------------------------------------------*/
 function toggle()
 {
	var tmpElem;
	document.pageForm.ApprovedFirstName.disabled = false;
	document.pageForm.ApprovedLastName.disabled = false;
	content = "&nbsp;<input type=\"button\" onclick=\"javascript:UserSearch('ApprovedBy');\" name=\"VerifyApproval\" id=\"VerifyApproval\" class=\"CustomButton\"  value=\"Verify\"  style=\"width:40px\"/>";
	cell5.innerHTML = content;
    return;
}


/*----------------------------------------------------------------------------------
         updateAllocationTotal
-------------------------------------------------------------------------------------*/
function updateAllocationTotal(intAllocCount){
		    SumAllocs(intAllocCount);		    
}


/*----------------------------------------------------------------------------------
        UserSearch
-------------------------------------------------------------------------------------*/
function UserSearch(SearchType) {
    switch (SearchType) {
	case "AboutUs" :
	    UserSearchWindow = window.open("./public/AboutUs.html", "UserSearch","menubar=yes,toolbar=no,width=610,height=520,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no");
	    break;
	case "Contact" : 
	    UserSearchWindow = window.open("./public/contact.html", "UserSearch","menubar=yes,toolbar=no,width=610,height=520,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no");
	    break;
	case "TellaColleague" :
    	    UserSearchWindow = window.open("TellAColleague.m", "UserSearch","menubar=yes,toolbar=no,width=910,height=620,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no");
	    break;
	case "News" :
	    UserSearchWindow = window.open("./public/news.html", "UserSearch","menubar=yes,toolbar=no,width=610,height=520,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no");
	    break;
	case "Terms" :
	    UserSearchWindow = window.open("./public/conditions.html", "UserSearch","menubar=yes,toolbar=no,width=610,height=520,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no");
	    break;
	case "Privacy" :
	    UserSearchWindow = window.open("./public/privacy.html", "UserSearch","menubar=yes,toolbar=no,width=610,height=520,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no");
	    break;
	};
}

