
var agendaContainerId;var agendaContentId;var agendaTransactionId;var agendaCaseReference;var agendaConsolidated;var agendaBlockId;var specificAgendaServiceUrl;function reloadAgenda(){if(!specificAgendaServiceUrl)
{return;}
if(agendaBlockId!==null)
{block(agendaBlockId);}
var bodyHeight=$("body").height()-$(agendaContainerId).height()+50;$(agendaContainerId).height($(window).height()-bodyHeight);$(window).resize(function(){$(agendaContainerId).height($(window).height()-bodyHeight);});$.ajax({cache:false,url:specificAgendaServiceUrl,data:{p:0},dataType:"html",complete:function(XMLHttpRequest,textStatus){if(agendaBlockId!==null){unblock(agendaBlockId);}},success:function(data,textStatus){$(agendaContentId).html(data);$(agendaContainerId).flexiPagination({url:specificAgendaServiceUrl,currentPage:0,totalResults:10000,margin:25,perPage:1,container:agendaContainerId,content:agendaContentId,pagerVar:"p",loaderImgPath:basePath+'/img/ajax-loader-large.gif',debug:1,backward:true,stopPagingAfterText:"There are no dates to display"});}});}
function showAgenda(containerid,contentid,transactionid,casereference,consolidated,blockid){agendaContainerId=containerid;agendaContentId=contentid;agendaBlockId=blockid;specificAgendaServiceUrl=agendaServiceUrl+"?c="+(consolidated?"true":"false");if(transactionid!==null&&transactionid!==undefined&&transactionid>0)
{specificAgendaServiceUrl+="&t="+encodeURIComponent(transactionid);}
if(casereference!==null&&casereference!==undefined&&casereference!=="")
{specificAgendaServiceUrl+="&r="+encodeURIComponent(casereference);}
reloadAgenda();}
var auditLogDialog=null;var openedAuditLog=false;function initializeAuditDialog(){var content=$("#content");$.ajax({type:"GET",url:ajaxIncludePath+"auditlogdialog.aspx",dataType:"html",success:function(data,status){content.append(data);auditLogDialog=$("#auditLogDialog",content);}});}
$(document).ready(function(){initializeAuditDialog();$(".audit").click(function(){var link=$(this);var t=link.attr("t");var f=link.attr("f");if(f===undefined)
{f="";}
var i=link.attr("i");if(i===undefined)
{i="";}
var title=link.attr("title");if(title===null||title.length===0)
{title="Audit Log";}
var columnWidth=link.attr("columnwidth");if(columnWidth===undefined)
{columnWidth=80;}
var singleField=f!==null&&f.length>0&&f.indexOf(",")==-1;var dialogWidth=link.attr("dialogwidth");if(dialogWidth===undefined)
{dialogWidth=singleField?'347px':'485px';}
var params=[{name:"m",value:"getchanges"},{name:"t",value:t},{name:"f",value:f},{name:"i",value:i}];if(openedAuditLog){$("#auditLogTable").flexOptions({params:params});$("#auditLogTable").flexReload();}else{$("#auditLogTable",auditLogDialog).flexigrid({url:servicePath+"changelogservice.aspx",params:params,dataType:'json',colModel:[{display:'Date/Time',name:'DateTime',width:110,sortable:false,align:'left'},{display:'Field',name:'FieldName',width:110,sortable:false,align:'left',hide:singleField},{display:'Old Value',name:'OldValue',width:columnWidth,sortable:false,align:'left'},{display:'New Value',name:'NewValue',width:columnWidth,sortable:false,align:'left'}],nowrap:false,usepager:true,useRp:true,rp:25,rpOptions:[5,10,25,50,100,500],showTableToggleBtn:false,showToggleBtn:false,resizable:false,height:'200',onError:function(msg){growlError(msg,"Error");},onReturnEmptyTotal:function(){}});}
auditLogDialog.dialog("destroy").dialog({buttons:{"OK":function(){$(this).dialog("close");}},title:title,modal:true,autoResize:true,width:dialogWidth,draggable:true,resizable:true,overlay:{opacity:0.5,background:"black"}});openedAuditLog=true;return false;});});
var changeBooleansToCheckboxesForDiv=function(columnIndex){$.each($('td:nth-child('+columnIndex+') div',$("#changesTable")),function(i,item){var div=$(item);var value=div.html();if(value!="False"&&value!="True"){return;}
var boolVal=value=="True";var checkbox=$(document.createElement("input")).attr({type:"checkbox"});div.html("").append(checkbox);checkbox.attr({checked:boolVal,disabled:"disabled"});});};function loadChangeDialogGrid(transactionDateId){$("#changesTable").flexigrid({dataType:'json',url:transactionDateServiceUrl,params:[{name:"m",value:"GetTransactionDateChanges"},{name:"TransactionDateId",value:transactionDateId}],colModel:[{display:'',name:'action',width:35,sortable:false,align:'left',hide:true},{display:'User',name:'User',width:100,sortable:false,align:'left'},{display:'Date/Time',name:'DateTime',width:50,sortable:false,align:'left'},{display:'Type',name:'Type',width:120,sortable:false,align:'left'},{display:'Changed From',name:'OldValue',width:240,sortable:false,align:'left'},{display:'Changed To',name:'NewValue',width:240,sortable:false,align:'left'}],nowrap:false,sortname:"DateTime",sortorder:"desc",usepager:true,useRp:true,rp:10,showTableToggleBtn:false,showToggleBtn:false,height:300,onReturnEmptyTotal:function(){growl("There are no changes for this date.","Change Log");},onSuccess:function(){changeBooleansToCheckboxesForDiv(5);changeBooleansToCheckboxesForDiv(6);$("#changeLogDialog").dialog("destroy").dialog({buttons:{"Close":function(){$(this).dialog("close");}},modal:true,autoResize:true,width:900,draggable:true,resizable:false,overlay:{opacity:0.5,background:"black"}});$("#changesTable").data("isLoaded",true);}});return false;}
function openChangeLogDialog(transactionDateId){if($("#changesTable").data("isLoaded")===undefined||!$("#changesTable").data("isLoaded")){loadChangeDialogGrid(transactionDateId);}
$("#changesTable").flexOptions({url:transactionDateServiceUrl,params:[{name:"m",value:"GetTransactionDateChanges"},{name:"TransactionDateId",value:transactionDateId}]}).flexReload();}
function doesDeadlinesHaveChanges(transactionDateId,results){$.ajax({type:"GET",url:transactionDateServiceUrl,data:{m:"haslogchanges",TransactionDateId:transactionDateId},dataType:"json",success:function(data){callFunction(results,data);}});}
function sendChargeStatementEmail(customerChargeStatementId,containerToBlock){if(customerChargeStatementId===undefined||customerChargeStatementId===null||customerChargeStatementId<1)
{return false;}
if(containerToBlock===undefined)
{containerToBlock=null;}
$.ajax({type:"POST",url:servicePath+'ChargesService.aspx',data:{m:"SendStatementEmail",ccsid:customerChargeStatementId},dataType:"json",beforeSend:function(){if(containerToBlock!==null)
{block(containerToBlock);}},complete:function(){if(containerToBlock!==null)
{unblock(containerToBlock);}},success:function(data){growlAjaxResult(data,"Send Charges Statement");if($("#charges").length>0)
{$("#charges").flexReload();}}});}
function initializeLink(link){var fileName=link.attr("filename");if(fileName===undefined||fileName===null||fileName.length===0)
{return;}
if(link.data("cmsdialog")!==undefined){link.show().effect("highlight",{},3000);return;}
var url="/content/raw/"+fileName;if(link.attr("basepath")){url=link.attr("basepath")+fileName;}
dontGrowlErrorsForUrls[url]=true;var isjson=link.attr("isjson")==="true";$.ajax({type:"GET",url:url,dataType:isjson?"json":"html",cache:true,error:function(msg){link.hide();},success:function(data,status){if(data!==null&&(isjson||(!isjson&&data.length>6))){link.data("cmsdialog",data);if(link.hasClass("ui-helper-hidden"))
{link.show().effect("highlight",{},3000);}}else{link.data("cmsdialog",null);link.hide();}}});}
function showDialog(link){var cmsDialog=$("#cmsDialog");if(cmsDialog.length===0){$("#container").append('<div id="cmsDialog" class="ui-helper-hidden"></div>');cmsDialog=$("#cmsDialog");}
var fileName=link.attr("filename");if(link.data("cmsdialog")===undefined){var url="/content/raw/"+fileName;if(link.attr("basepath")){url=link.attr("basepath")+fileName;}
dontGrowlErrorsForUrls[url]=true;var isjson=link.attr("isjson")==="true";$.ajax({type:"GET",url:url,dataType:isjson?"json":"html",cache:true,success:function(data,status){if(data!==null&&(isjson||(!isjson&&data.length>6))){link.data("cmsdialog",data);showDialog(link);}else{link.data("cmsdialog",null);growl("The text is currently unavailable.  Please try again later.","Warning");}},error:function(){link.data("cmsdialog",null);growl("The text is currently unavailable.  Please try again later.","Warning");}});return;}
else if(link.data("cmsdialog")===null){growl("The text is currently unavailable.  Please try again later.","Warning");return;}
var width=link.attr("width");var title=link.attr("title");if(link.attr("isjson")==="true"){var data=link.data("cmsdialog");var jsontitle=link.attr("jsontitle");var jsontext=link.attr("jsontext");title=data[jsontitle];var text=data[jsontext];cmsDialog.html(text);}
else{cmsDialog.html(link.data("cmsdialog"));}
if(width===undefined||width===null||width===0||isNaN(width))
{width=800;}
if(title===undefined||title===null||title.length===0)
{title="Deadlines On Demand";}
cmsDialog.dialog("destroy").dialog({buttons:{"Close":function(){$(this).dialog("close");}},modal:true,title:title,autoResize:true,width:width,bgiframe:true,draggable:true,overlay:{opacity:0.5,background:"black"}});}
function initializeCmsDialogs(){var cmsDialogs=$(".cmsdialog");if(cmsDialogs.length===0){return;}
$.each(cmsDialogs,function(i,link){var linkObj=$(link);var precache=linkObj.attr("precache");if(precache===undefined||precache.length===0||precache==="true"){initializeLink(linkObj);}});cmsDialogs.unbind('click').click(function(){var link=$(this);showDialog(link);return false;});}
$(document).ready(function(){initializeCmsDialogs();});
var creditCardContainer;var creditCardDialog=null;function configureCreditCardMask(container,selectedValue){var txtCard=$("#txtCard",container);if(selectedValue=="American Express")
{txtCard.unmask().mask("9999-999999-99999");}
else
{txtCard.unmask().mask("9999-9999-9999-9999");}}
function setCreditCardMaskDefault(container){var option=$("#ddlType select",container).children(":selected");if(option.length===0)
{return;}
configureCreditCardMask(creditCardDialog,option.html());}
function saveCreditCard(isDefault,customerCreditCardId,onSaveCreditCardCallback){var name=$("#txtName",creditCardDialog).val();var number=$("#txtCard",creditCardDialog).val();var expYear=$("#txtYear",creditCardDialog).val();var expMonth=$("#txtMonth",creditCardDialog).val();var type=$("#ddlType",creditCardDialog).children("select").children("option:selected").val();var address1=$("#txtAddress1",creditCardDialog).val();var address2=$("#txtAddress2",creditCardDialog).val();var city=$("#txtCity",creditCardDialog).val();var zip=$("#txtZip",creditCardDialog).val();var phone=$("#txtPhone",creditCardDialog).length?$("#txtPhone",creditCardDialog).val():null;var state=$("#ddlState",creditCardDialog).children("select").children("option:selected").val();if(address2.indexOf("Optional")>-1)
{address2="";}
$.ajax({cache:false,type:"POST",url:servicePath+'ManageCreditCardsService.aspx',data:({m:"save",customerId:customerId,customerCreditCardId:customerCreditCardId,isDefault:isDefault,name:name,type:type,number:number,expMonth:expMonth,expYear:expYear,address1:address1,address2:address2,city:city,zip:zip,phone:phone,state:state}),dataType:"json",success:function(data){growlAjaxResult(data,"Save credit card");if(data.Success){if(onSaveCreditCardCallback!==undefined&&$.isFunction(onSaveCreditCardCallback)){onSaveCreditCardCallback(data);}
creditCardDialog.dialog("close");}}});}
function getCardImage(cardId){var imageUrl="";var imageName="";switch(cardId){case 3:imageName='Amex.gif';break;case 4:imageName='Visa.gif';break;case 5:imageName='MasterCard.gif';break;case 6:imageName='Discover.gif';break;}
imageUrl=imagePath+'CreditCards/'+imageName;return $(document.createElement("img")).attr("src",imageUrl).css("height","32px").css("width","50px");}
function selectCardImage(container,cardId){var imageUrl=getCardImage(cardId);$("#cardImage",container).hide();if(imageUrl!=="")
{$("#cardImage",container).html("").append($(imageUrl).css("verticalAlign","middle")).show();}
$("#ddlType select").focus();}
function PadDigits(n,totalDigits){n=n.toString();var pd='';if(totalDigits>n.length){for(i=0;i<(totalDigits-n.length);i++){pd+='0';}}
return pd+n.toString();}
function bindCreditCardDialogData(creditCardDialog,dialogData){selectCardImage(creditCardDialog,parseInt(dialogData.Type,10));$("#txtName",creditCardDialog).val(dialogData.Name);$("#txtMonth",creditCardDialog).val(PadDigits(dialogData.ExpirationMonth,2));$("#txtYear",creditCardDialog).val(dialogData.ExpirationYear);$("#cardTypes",creditCardDialog).children("option[value='"+dialogData.Type+"']").attr("selected","selected");$("#txtCard",creditCardDialog).val(dialogData.CardNumber);$("#txtCard",creditCardDialog).data("originalValue",dialogData.CardNumber);$("#txtAddress1",creditCardDialog).val(dialogData.Address1);$("#txtAddress2",creditCardDialog).val(dialogData.Address2===null?"":dialogData.Address2);if(!dialogData.Address2||dialogData.Address2=="(Optional)"){setWatermark("#txtAddress2","(Optional)");}
$("#txtCity",creditCardDialog).val(dialogData.City);$("#txtZip",creditCardDialog).val(dialogData.ZipCode);$("#txtPhone",creditCardDialog).val(dialogData.Phone);if($("#ddlState select").children("option").length>0)
{$("#ddlState select").children("option[value='"+dialogData.StateCode+"']",creditCardDialog).attr("selected","selected");}
else
{$("#ddlState").data("state",dialogData.StateCode);}
$("#txtCard",creditCardDialog).focus(function(){$(this).val("");configureCreditCardMask(creditCardDialog,$("#cardTypes",creditCardDialog).children(":selected").html());});}
function afterDropDownChange(container,dropDownId){$(dropDownId,container).children("select").bind("change",function(){configureCreditCardMask(container,$(this).children(":selected").html());selectCardImage(container,parseInt($(this).children(":selected").attr("value"),10));});}
function fillCardTypes(container,element,asDropDown,finishedLoading){element=$(element,container);var retVal;$.getJSON(creditCardServiceUrl,{m:"getcardtypes"},function(cardtypesdata){if(cardtypesdata===null){return;}
if(!asDropDown)
{return cardtypesdata;}
var select=$("#cardTypes",element);if(select.length===0){select=$(document.createElement("select")).attr("id","cardTypes").css("width","130px");}else{select.empty();}
$.each(cardtypesdata,function(i,val){if(val===null){return;}
var option=$(document.createElement("option")).append(val.Second).attr("value",val.First);$(select).append(option);});element.append($(select));element.css("padding-right","15px");afterDropDownChange(container,"#ddlType");$("#ddlType select",container).keydown(function(e){if(e.which!=38&&e.which!=40){return;}
var cardId=-1;var cardName="";if(e.which==38){var option=$(this).children(":selected").prev("option");if($(option).length===0)
{return;}
cardId=parseInt($(option).attr("value"),10);cardName=$(option).html();}
else if(e.which==40){var option2=$(this).children(":selected").next("option");if($(option2).length===0)
{return;}
cardId=parseInt($(option2).attr("value"),10);cardName=$(option2).html();}
configureCreditCardMask(container,cardName);selectCardImage(container,cardId);});var cardTypeId=parseInt($("#ddlType select",container).children("option:selected").val(),10);if(isNaN(cardTypeId))
{return false;}
selectCardImage(container,cardTypeId);callFunction(finishedLoading);});}
function clearDialog(){$("#txtName",creditCardDialog).val("").next(".ui-widget").remove();$("#txtCard",creditCardDialog).val("").next(".ui-widget").remove();$("#txtMonth",creditCardDialog).val("").next(".ui-widget").remove();$("#txtYear",creditCardDialog).val("").next(".ui-widget").remove();$("#txtAddress1",creditCardDialog).val("").next(".ui-widget").remove();$("#txtAddress2",creditCardDialog).val("");$("#txtCity",creditCardDialog).val("").next(".ui-widget").remove();$("#txtZip",creditCardDialog).val("").next(".ui-widget").remove();$("#txtPhone",creditCardDialog).val("").next(".ui-widget").remove();$(".error-message",creditCardDialog).html("");$(".error-highlight",creditCardDialog).removeClass("error-highlight");$("#cardTypes",creditCardDialog).children(":first-child").attr("selected","true");$("#states",creditCardDialog).children(":first-child").attr("selected","true");$("#states",creditCardDialog).parent("span").next(".ui-widget").remove();$("#ccValidationErrors",creditCardDialog).empty();$("#creditCardDialog",creditCardDialog).simpleValidationEmpty();}
function setupCreditCardDialog(action,creditCardDialog){var container=creditCardDialog.parent();if($("#ui-dialog-title-creditCardDialog",container).length>0){if($("#creditCardDialog",container).length===0){creditCardDialog.attr("title",action+" Credit Card");return;}
var newText="";var title=$("#creditCardDialog",container).data('dialog.title').originalTitle;if(action=="Edit")
{newText=title.replace("Add",action);}
else
{newText=title.replace("Edit",action);}
$("#creditCardDialog",container).data('dialog.title').originalTitle=newText;}
var isEditing=action=="Edit";$("#txtCard",creditCardDialog).attr("disabled",isEditing?"disabled":"");$("#ddlType select",creditCardDialog).attr("disabled",isEditing?"disabled":"");creditCardDialog.attr("title",action+" Credit Card");}
function loadCreditCardDialog(container,cardId,onSaveCreditCardCallback){if(creditCardDialog===null||creditCardDialog.length===0)
{creditCardDialog=$("#creditCardDialog",creditCardContainer);}
if(cardId===null||cardId<1){clearDialog();setupCreditCardDialog("Add",creditCardDialog);creditCardDialog.dialog("destroy").dialog({buttons:{"OK":function(){if(creditCardDialog.simpleValidation({container:"ccValidationErrors"})){saveCreditCard(false,0,onSaveCreditCardCallback);}},"Cancel":function(){$(this).dialog("close");}},modal:true,autoResize:true,width:450,draggable:true,resizable:false,overlay:{opacity:0.5,background:"black"},open:function(event,ui){setCreditCardMaskDefault(creditCardDialog);setWatermark("#txtAddress2","(Optional)");},close:function(event,ui){destroyWatermark("#txtAddress2",creditCardDialog);}});return;}
$.getJSON(creditCardServiceUrl,{m:"getCard",id:cardId},function(data){if(data===null){return;}
clearDialog();setupCreditCardDialog("Edit",creditCardDialog);bindCreditCardDialogData(creditCardDialog,data);creditCardDialog.dialog("destroy").dialog({buttons:{"OK":function(){if(creditCardDialog.simpleValidation({container:"ccValidationErrors",valueMustChangeMessage:"For security reasons, please re-enter card number."})){saveCreditCard(data.IsDefault,data.CustomerCreditCardId,onSaveCreditCardCallback);}},"Cancel":function(){$(this).dialog("close");}},modal:true,autoResize:true,width:450,draggable:true,open:function(event,ui){},close:function(event,ui){destroyWatermark("#txtAddress2",creditCardDialog);},overlay:{opacity:0.5,background:"black"}});});}
function fillStates(container,element,asDropDown,finishedLoading){element=$(element,container);var retVal;$.getJSON(creditCardServiceUrl,{m:"getstates"},function(statesdata){if(statesdata===null){return;}
if(!asDropDown)
{return statesdata;}
var select=$("#states",element);if(select.length===0){select=$(document.createElement("select")).attr("id","states");}else{select.empty();}
$(select).append($(document.createElement("option")));$.each(statesdata,function(i,state){if(state===null){return;}
var option=$(document.createElement("option")).append(state).attr("value",state);$(select).append(option);});element.append($(select));if(element.data("state")!==undefined&&element.data("state").length>0){element.children("select").children("option[value='"+element.data("state")+"']").attr("selected","selected");element.data("state","");}
callFunction(finishedLoading);});}
function initializeCreditCardDialog(container,finishedLoadingCreditCardDialogCallback){creditCardContainer=$("#"+container);var path=ajaxIncludePath+"creditcarddialog.aspx";$.ajax({type:"GET",cache:false,url:path,dataType:"html",success:function(data,status){creditCardContainer.html(data);$("#txtMonth",creditCardContainer).mask("99");$("#txtYear",creditCardContainer).mask("9999");$("#txtZip",creditCardContainer).mask("99999?-9999");$("#txtPhone",creditCardContainer).mask("(999) 999-9999? x99999");if(creditCardDialog===null||creditCardDialog.length===0){creditCardDialog=$("#creditCardDialog",creditCardContainer);}
if($.browser.safari){$("#txtMonth",creditCardContainer).attr("size","2");$("#txtYear",creditCardContainer).attr("size","4");}
fillCardTypes(creditCardDialog,"#ddlType",true,function(){fillStates(creditCardDialog,"#ddlState",true,function(){callFunction(finishedLoadingCreditCardDialogCallback);});});}});}
function openCreditCardDialog(container,cardId,onSaveCreditCardCallback){if($("#creditCardDialog").length===0){initializeCreditCardDialog(container,function(){loadCreditCardDialog(container,cardId,onSaveCreditCardCallback);});return false;}
loadCreditCardDialog(container,cardId,onSaveCreditCardCallback);}
(function($){var allCreditCardSelectTargets=[];var target;var options;var defaults={creditCardDialogContainer:"creditCardContainer",creditCardDialogReturnedCallback:null,creditCards:null,isAdmin:false,addCreditCardsViewDialog:true,textBeforeSelect:"Credit Card ending with: ",textBeforeCreditCardNumber:null,markDefaultCard:false,selectDefault:true,customOptions:null,dropdown:null,dropdownCreatedCallback:null,replaceWithText:null};$.fn.creditCardSelect=function(new_options){target=$(this);var dataOptions=target.data("creditCardSelect-options");if(dataOptions!==undefined&&dataOptions!==null)
{options=dataOptions;}
else{options=null;allCreditCardSelectTargets.push(target);}
var instance=true;if(new_options!==undefined&&new_options!==null&&typeof(new_options)=='object'){options=$.extend({},defaults,options,new_options);target.data("creditCardSelect-options",options);instance=false;}
if(options.dropdown===null)
{options.dropdown=$(".ddlCreditCards",target);}
if(options.dropdown.length===0)
{options.dropdown=null;}
this.prependOption=function(selected,value,text){var option=createOption(value,text,selected);options.dropdown.prepend(option);return option;};this.appendOption=function(selected,value,text){var option=createOption(value,text,selected);options.dropdown.append(option);return option;};this.insertAfterOption=function(selected,value,text,element){var option=createOption(value,text,selected);options.dropdown.insertAfter(element);return option;};this.getSelectList=function(){return options.dropdown;};this.selectedOption=function(){var selectList=this.getSelectList();if(selectList){return this.getSelectList().find("option:selected");}else{return $("<option/>");}};this.addCard=function(card){var addingFirstCard=false;var isDuplicateCard=false;var addNewLink=$("#addNewCreditCardLink",target);if(addNewLink.length>0){addNewLink.remove();addingFirstCard=true;}
if(options.creditCards===null||options.creditCards.length===0){var cards=[];cards.push(card);options.creditCards=cards;}else{options.creditCards.push(card);}
displayCreditCardDropDown(card);if(addingFirstCard){if($.isFunction(options.dropdownCreatedCallback)){options.dropdownCreatedCallback(options.dropdown);}}};if(!instance){if(options.replaceWithText){displayText();}
else{displayCreditCardDropDown();}}
return this;};function displayText(){if(options.dropdown!==null){options.dropdown.hide();}
var addNewLink=$("#addNewCreditCardLink",target);if(addNewLink.length>0){addNewLink.remove();}
var adminAddCard=$("#adminAddCard",target);if(adminAddCard.length>0){adminAddCard.remove();}
var span=$(".creditCardReplacedText",target);if(span.length===0){target.append('<span class="creditCardReplacedText">'+options.replaceWithText+'</span>');}else{span.show();}}
function displayCreditCardDropDown(defaultCard){$(".creditCardReplacedText",target).hide();var creditCards=options.creditCards;var customOptions=options.customOptions;var addNewLink=$("#addNewCreditCardLink",target);if(addNewLink.length>0){addNewLink.remove();}
var adminAddCard=$("#adminAddCard",target);if(adminAddCard.length>0){adminAddCard.remove();}
var noCards=creditCards===null||creditCards.length===0||creditCards==="";if(noCards&&(!customOptions||customOptions.length<1)){var ccPaymentText="";if(options.isAdmin)
{ccPaymentText="<a href='#' id='addNewCreditCardLink'>Click to add a credit card.</a>";}
else
{ccPaymentText='<span id="adminAddCard">Please ask an administrator to add a new credit card.</span>';}
target.html(ccPaymentText);$("#addNewCreditCardLink",target).click(function(){addCreditCard();return false;});return;}
if(options.textBeforeSelect!==undefined&&options.textBeforeSelect!==null&&$.trim(options.textBeforeSelect).length>0&&$("#textBeforeSelect",target).length===0){target.append('<span id="textBeforeSelect">'+options.textBeforeSelect+'</span>');}
appendCreditCardDropDown(creditCards,defaultCard);}
function appendCreditCardDropDown(creditCards,defaultCard){if(options.dropdown===null)
{options.dropdown=$(document.createElement("select")).attr("class","ddlCreditCards");}
else
{options.dropdown.empty().show();}
var addText="";if(options.textBeforeCreditCardNumber!==undefined&&options.textBeforeCreditCardNumber!==null&&$.trim(options.textBeforeCreditCardNumber).length>0)
{addText=options.textBeforeCreditCardNumber;}
var defaultOption=null;if(options.customOptions!==null){for(var i=0;i<options.customOptions.length;i++){var option=options.customOptions[i];options.dropdown.append(option);if(i===0){option.attr("selected","selected");defaultOption=option;}}}
var hasCustomOptions=options.customOptions&&options.customOptions.length>0;var addedCards=[];for(var cardIndex=0;cardIndex<creditCards.length;cardIndex++){var value=creditCards[cardIndex];if(!value){return;}
if(addedCards[value.CustomerCreditCardId]!==undefined){continue;}
addedCards[value.CustomerCreditCardId]=true;var text=addText+value.CardNumberLastFour+" ("+value.Type+")";if(options.markDefaultCard&&creditCards.length>1&&value.IsDefault){text+=" [default]";}
var isDefault=!hasCustomOptions&&options.selectDefault&&value.IsDefault;if(defaultCard&&!hasCustomOptions){isDefault=value.CustomerCreditCardId===defaultCard.CustomerCreditCardId;}
var newOption=createOption(value.CustomerCreditCardId,text,isDefault);options.dropdown.append(newOption);if(isDefault){defaultOption=newOption;}}
if(options.isAdmin){var addNewCardOption=$(document.createElement("option")).append("Add new card");options.dropdown.append(addNewCardOption);}
options.dropdown.change(function(){if(!options.isAdmin)
{return;}
if($(this).children("option:selected").text()=="Add new card"){addCreditCard();}});target.append(options.dropdown);if(defaultOption!==null){defaultOption.attr("selected",true);defaultOption.attr("defaultSelected","true");}}
function addCreditCard(closeAllGrowls){if(!options.isAdmin)
{return;}
if(closeAllGrowls&&$.isFunction(growlCloseAll))
{growlCloseAll();}
if(options.addCreditCardsViewDialog)
{openCreditCardDialog(options.creditCardDialogContainer,null,creditCardDialogReturnedCallback);}
else
{document.location=basePath+'Accounts/ManageCreditCards.aspx';}}
function creditCardDialogReturnedCallback(data){if(data.Success===false){options.dropdown.children("[defaultSelected!='true']").removeAttr("selected");options.dropdown.children("[defaultSelected='true']").attr("selected","selected");return false;}
for(var i=0;i<allCreditCardSelectTargets.length;i++){allCreditCardSelectTargets[i].creditCardSelect().addCard(data.Card);}
if($.isFunction(options.creditCardDialogReturnedCallback))
{options.creditCardDialogReturnedCallback(data.Card);}}
function createOption(value,text,selected){var option=$(document.createElement("option")).attr("value",value).append(text);if(selected){option.attr("selected","selected");option.attr("defaultSelected","true");}
return option;}
function selectOption(option){$(":selected",options.dropdown).removeAttr("selected");option.attr("selected","selected");}})(jQuery);
var dateChangeContainer;var reloadedDateChangeDialogData=null;var dateChangeDialog=null;var unskipChildDialog=null;var transactionDateInfo;var recursive=false;var newTimeWatermark="(optional)";var isTimed;var paymentSummary;var sendDatesInProgress=false;var getTransactionDateInformationInProgress=false;function getLockedDatesCount(){var tree=$("#relatedDeadlinesTree","#dateChangeDialog");var totalChecked=$(".ui-dynatree-selected-locked",tree).length;var root=$("#ui-dynatree-id-root",tree);if(root.hasClass("ui-dynatree-selected-locked"))
{totalChecked--;}
return totalChecked;}
function enableDisableSaveButton(){var enabled=false;var hasChildren=transactionDateInfo.ChildCount>0;if(!hasChildren||$("#confirmChangeFee",dateChangeDialog).html()=="$0.00"||$("#chkConfirm").hasClass("ui-dynatree-selected")){enabled=true;}
var textToDate=formatDateTextToDate("#newDate");if(textToDate=="Invalid Date"||isNaN(textToDate)||textToDate===null)
{textToDate=formatDateFromText("#newDate");}
if(textToDate===false){$(".confirm").hide();if($("#newTime").val()!==""&&$("#newTime").val()!==newTimeWatermark&&$("#newTime").val()!==transactionDateInfo.TransactionDate.TimeDisplay){enabled=true;}
else{enabled=false;}}
else{$(".confirm").show();}
if($("#confirmChangeFee",dateChangeDialog).html()=="$0.00"){$(".confirm").hide();}
var button=$(":button:contains('Save')",$("[aria-labelledby='ui-dialog-title-dateChangeDialog']"));if(enabled)
{button.attr("disabled",false).removeClass("ui-state-disabled").removeAttr("disabled").css("cursor","pointer");}
else
{button.attr("disabled",true).addClass("ui-state-disabled").css("cursor","default");}}
function checkOrUncheckAllRelatedDates(){var parent=$("#checkAll",dateChangeDialog).parent();var selectAll=!parent.hasClass("ui-dynatree-selected-locked");parent.toggleClass("ui-dynatree-selected-locked");$("#relatedDeadlinesTree","#dateChangeDialog").dynatree("getRoot").visit(function(dtnode){dtnode.select(selectAll);});}
function validateNewDate(){$("#chkConfirm").removeClass("ui-dynatree-selected");enableDisableSaveButton();}
function selectedDay(date){if(date=="Invalid Date")
{return;}
var day=new Date(date);var now=new Date();var hideCal=false;if(day.getDay()===0||day.getDay()==6){growl("The event date you have selected is a weekend day.","Warning");}
else if(day.getMonth()+"-"+day.getDate()+"-"+day.getFullYear()==now.getMonth()+"-"+now.getDate()+"-"+now.getFullYear()){growl("The event date you have selected is today.","Warning");}
else if(day.getTime()<now.getTime()){growl("The event date you have selected has already passed.","Warning");}
$("#newDate").val(day.format("m/d/Y"));validateNewDate();return true;}
function reloadDateChangeData(returnedCallback){$.ajax({type:"POST",url:servicePath+'TransactionDateService.aspx',data:{m:"gettransactiondateinfo",TransactionDateId:dateDialogTransactionDateInfo.TransactionDate.TransactionDateId,change:true},dataType:"json",success:function(data){if(data.Success){reloadedDateChangeDialogData=data;callFunction(returnedCallback);}else
{growlAjaxResult(data,"Get Transaction Date Information");}},complete:function(XMLHttpRequest,textStatus){getTransactionDateInformationInProgress=false;}});}
function binddateChangeDialogData(dateChangeDialog,transactionDateInfo){var hasChildren=transactionDateInfo.ChildCount>0;if(transactionDateInfo.TransactionDate.Locked){$(".hideIfDateChanged",dateChangeDialog).hide();}else{$(".hideIfDateChanged",dateChangeDialog).show();}
if(hasChildren){$(".triggerDateRow",dateChangeDialog).show();$("#changeDateHelp").attr("filename","change_date_trigger");}else{$(".triggerDateRow",dateChangeDialog).hide();$("#changeDateHelp").attr("filename","change_date_nontrigger");}
initializeCmsDialogs();isTimed=transactionDateInfo.TransactionDate.IsTimed;$("#currentDate",dateChangeDialog).html(dateFormat(transactionDateInfo.TransactionDate.localStartDate,"shortDate"));if(isTimed){$("#currentTime",dateChangeDialog).html(transactionDateInfo.TransactionDate.TimeDisplay);$("#newTime",dateChangeDialog).val(transactionDateInfo.TransactionDate.TimeDisplay);$("#newTime",dateChangeDialog).removeClass("watermarkOn");}else{$("#currentTime",dateChangeDialog).html("");}
if(transactionDateInfo.TransactionDate.localStartDate<new Date().zeroTime()&&!transactionDateInfo.TransactionDate.Locked)
{$("#priorDateWarning",dateChangeDialog).show();}
else
{$("#priorDateWarning",dateChangeDialog).hide();}
$("#authority",dateChangeDialog).text(transactionDateInfo.TransactionDate.Authority);$("#caseReference",dateChangeDialog).text(transactionDateInfo.Transaction.CaseReference);$("#description",dateChangeDialog).html(transactionDateInfo.TransactionDate.DescriptionWithNotes.replace(/\n/g,'<br/>'));if(hasChildren){var treeRoot=$("#relatedDeadlinesTree",dateChangeDialog).dynatree("getRoot");treeRoot.removeChildren();treeRoot.append(transactionDateInfo.RelatedTreeNodes);}
var uncheckAll=function(){var rootNode=$("#relatedDeadlinesTree",dateChangeDialog).dynatree("getRoot");rootNode.select(false);};paymentSummary=dateChangeDialog.paymentSummary({calculationPaymentInfo:transactionDateInfo.CalculationPaymentInfo,isDateChange:true,childCount:transactionDateInfo.ChildCount,paymentMethodChangedCallback:enableDisableSaveButton,lockedDates:getLockedDatesCount(),isAdmin:isAdmin});dateChangeDialog.dialog("destroy").dialog({title:hasChildren?"Deadline Date Change - TRIGGER DATE":"Deadline Date Change",zIndex:3999,resizable:false,open:function(event,ui){$(":button:contains('Save')",$("[aria-labelledby='ui-dialog-title-dateChangeDialog']")).attr("disabled",true).addClass("ui-state-disabled");$("#newDate",dateChangeDialog).focus();},buttons:{"Cancel":function(){uncheckAll();dateChangeDialog.dialog("close");},"Save":function(){block("[aria-labelledby='ui-dialog-title-dateChangeDialog']");var newDate=formatDateTextToDate($("#newDate",dateChangeDialog));var newTime=$("#newTime",dateChangeDialog).val()==newTimeWatermark?"":$("#newTime",dateChangeDialog).val();var creditCardId=null;if(!newDate||newDate.getFullYear()<new Date(1988,0,1).getFullYear()){growlError("Please enter an event date after 1987.","Event date error");unblock("[aria-labelledby='ui-dialog-title-dateChangeDialog']");return false;}
var lockedDateIds="";$.each($(".ui-dynatree-selected-locked",$("#relatedDeadlinesTree",dateChangeDialog)),function(i,value){var id=$(value).attr("id");var transactionDateId=id.substr(id.lastIndexOf("-")+1);if(lockedDateIds.length>0)
{lockedDateIds+=","+transactionDateId;}
else
{lockedDateIds+=transactionDateId;}});var paymentMethod;if(hasChildren){paymentMethod=paymentSummary.selectedPaymentMethod();if(paymentMethod==paymentSummary.paymentMethods().CreditCard)
{creditCardId=paymentSummary.selectedCreditCardId();}}
var currentTime=new Date().getTime();sendDatesInProgress=currentTime;$.ajax({actiondescription:"Your date change request",url:servicePath+'TransactionDateService.aspx',type:"POST",dataType:"json",timeout:60000,data:{m:"ChangeDate",TransactionDateId:transactionDateInfo.TransactionDate.TransactionDateId,date:newDate.format('n/d/Y'),time:newTime,timezoneid:$("input[name=timezoneid]:checked").val(),hasChildren:hasChildren,TransactionId:transactionDateInfo.Transaction.TransactionId,jurisdictionId:transactionDateInfo.Transaction.JurisdictionId,paymentMethod:paymentMethod,creditCard:creditCardId,lockedDateIds:lockedDateIds},success:function(data){if(!sendDatesInProgress){return;}
sendDatesInProgress=false;growlAjaxResult(data,"Date Change");if(data.Success===true&&!data.PaymentError){if(data.ChangingDate!==undefined&&data.ChangingDate!==null){updateDetailDialogDateTime(data.ChangingDate);}
var newEventDate=null;if(data.NewEventDate!==null){newEventDate=parseJsonDate(data.NewEventDate);}
updateView(data.ChangedDates,null,newEventDate);$("#charges").flexReload();uncheckAll();unblock("[aria-labelledby='ui-dialog-title-dateChangeDialog']");dateChangeDialog.dialog("close");reloadDateChangeData(function(){});toggleViewChangeLogButtonEnabled(true);}else{unblock("[aria-labelledby='ui-dialog-title-dateChangeDialog']");if(data.CalculationPaymentInfo!==null){displayBillingInfo(data.CalculationPaymentInfo,dateChangeDialog,true);}}},error:function(XMLHttpRequest,textStatus,errorThrown){ajaxErrorHandler(this,XMLHttpRequest,textStatus,errorThrown);if(textStatus=='timeout'){if(sendDatesInProgress!=currentTime){return;}
sendDatesInProgress=false;unblock("[aria-labelledby='ui-dialog-title-dateChangeDialog']");}}});}},modal:true,autoResize:true,width:hasChildren?890:890,draggable:true,overlay:{opacity:0.5,background:"black"}});}
function gotTransactionDateInformation(data){transactionDateInfo=data;if(transactionDateInfo.TransactionDate.IsTimed){transactionDateInfo.TransactionDate.localStartDate=parseJsonDate(transactionDateInfo.TransactionDate.StartDateTimeOffset.DateTimeOffset);}else{transactionDateInfo.TransactionDate.localStartDate=new Date(transactionDateInfo.TransactionDate.DateDisplay);}
$("#datepickerdiv").datepicker('destroy').datepicker({defaultDate:transactionDateInfo.TransactionDate.localStartDate,beforeShowDay:isWeekend,onSelect:selectedDay,changeMonth:true,changeYear:true,duration:'',numberOfMonths:1,minDate:new Date(1988,0,1)});$(".confirm").hide();$("#chkConfirm").removeClass("ui-dynatree-selected");$("#paymentMethod",parent).empty();$("#costText",parent).empty();$("#newDate").val("");$("#newTime").val("");$("#newDate").change(function(){var date=formatDateTextToDate(this);if(date<new Date(1988,0,1)){$("#newDate").val("");return false;}
$("#datepickerdiv").datepicker('setDate',date);validateNewDate();}).keyup(function(e){if(e.keyCode==13){var button=$(":button:contains('Save')",$("[aria-labelledby='ui-dialog-title-dateChangeDialog']"));if(!button.attr("disabled")){button.focus().trigger('click');}}
var date=formatDateTextToDate(this);if(date<new Date(1988,0,1)){return;}
$("#datepickerdiv").datepicker('setDate',date);validateNewDate();});$("#newTime").change(validateNewDate);setWatermark("#newTime",newTimeWatermark);if(transactionDateInfo.hasChildren&&(transactionDateInfo.Transaction.JurisdictionId===null||transactionDateInfo.Transaction.JurisdictionId==='')){$("#jurisdictionChangedDialog",dateChangeContainer).dialog("destroy").dialog({buttons:{"OK":function(){$(this).dialog("close");}},modal:true,autoResize:true,width:480,draggable:true,overlay:{opacity:0.5,background:"black"}});return;}
if(transactionDateInfo.UpdateNotificationId!==null&&transactionDateInfo.UpdateNotificationId>0){var cnsChangedateChangeDialog=$("#cnsChangeDateDialog",dateChangeContainer);var transactionLink=$("#transactionLink",cnsChangedateChangeDialog);var url=transactionLink.attr("href")+basePath+"/Notifications/Transaction.aspx?updateid="+transactionDateInfo.UpdateNotificationId+"&transid="+transactionDateInfo.Transaction.TransactionId;transactionLink.attr("href",url);cnsChangedateChangeDialog.dialog("destroy").dialog({buttons:{"OK":function(){$(this).dialog("close");}},modal:true,autoResize:true,width:480,draggable:true,overlay:{opacity:0.5,background:"black"}});return;}
if(dateChangeDialog===null||dateChangeDialog.length===0){dateChangeDialog=$("#dateChangeDialog",dateChangeContainer);}
var transactionTimeZoneInfo=transactionDateInfo.Transaction.TimeZoneInfo;var browserTimeZoneInfo=transactionDateInfo.BrowserTimeZoneInfo;if(transactionTimeZoneInfo&&transactionTimeZoneInfo.Id)
{$("#rbTransactionTimeZoneId").val(transactionTimeZoneInfo.Id);}
if(transactionTimeZoneInfo&&transactionTimeZoneInfo.Id&&browserTimeZoneInfo&&browserTimeZoneInfo.Id&&transactionTimeZoneInfo.Id!=browserTimeZoneInfo.Id){$("#rbTransactionTimeZoneIdText").text("Transaction time zone: "+transactionTimeZoneInfo.DisplayName);$("#rbLocalTimeZoneId").val(browserTimeZoneInfo.Id);$("#rbLocalTimeZoneIdText").text("Your time zone: "+browserTimeZoneInfo.DisplayName);if(transactionDateInfo.Transaction.IsTimed){$("#trTimeZone",dateChangeDialog).show();}else{$("#trTimeZone",dateChangeDialog).hide();}
$("#newTime",dateChangeDialog).change(function(){if($(this).val()==='')
{$("#trTimeZone",dateChangeDialog).fadeOut("fast");}
else
{$("#trTimeZone",dateChangeDialog).fadeIn("fast");}});}
binddateChangeDialogData(dateChangeDialog,transactionDateInfo);}
function GetTransactionDateInformation(dateDialogTransactionDateInfo){if(dateDialogTransactionDateInfo===null){growlError("Internal error, please try again.","Transaction Date Information error");return;}
if(noteHasChanged!==undefined&&noteHasChanged){reloadDateChangeData(function(){gotTransactionDateInformation(reloadedDateChangeDialogData);noteHasChanged=false;});}else{if(reloadedDateChangeDialogData===null)
{gotTransactionDateInformation(dateDialogTransactionDateInfo);}
else
{gotTransactionDateInformation(reloadedDateChangeDialogData);}}
getTransactionDateInformationInProgress=false;}
function clearChangeDateData(){reloadedDateChangeDialogData=null;}
function initializeDateChange(container,finishedLoadingCallback){dateChangeContainer=$("#"+container);var path=ajaxIncludePath+"datechangedialog.aspx";$.ajax({type:"GET",url:path,dataType:"html",cache:false,success:function(data,status){dateChangeContainer.html(data);initializeCmsDialogs();var tree=$("#relatedDeadlinesTree","#dateChangeDialog");tree.dynatree({title:"Check to lock/Uncheck unlock (this box for all)",autoFocus:false,autoCollapse:false,rootVisible:true,persist:false,clickFolderMode:1,fx:{height:"toggle",duration:200},onSelect:function(selected,dtnode){if(recursive){return;}
var update=true;if(selected&&dtnode.hasChildren()){recursive=true;dtnode.visit(function(node,cache){node.select(true);},null,false);recursive=false;}
if(!selected){if(dtnode.getLevel()==1){recursive=true;dtnode.parent.select(false);recursive=false;}else if(dtnode.getLevel()>1){if(dtnode.parent.isSelected()){recursive=true;dtnode.select(true);recursive=false;if(unskipChildDialog!==null){unskipChildDialog.dialog('open');}else{unskipChildDialog=$("#unskipChildDialog",dateChangeContainer);unskipChildDialog.dialog("destroy").dialog({buttons:{"OK":function(){unskipChildDialog.dialog("close");}},modal:true,autoResize:true,width:480,draggable:true,overlay:{opacity:0.5,background:"black"}});}
update=false;return;}
update=false;}
if(dtnode.hasChildren()){recursive=true;dtnode.visit(function(node,cache){node.select(false);},null,false);recursive=false;}}
var excluded=$("#chkConfirm").removeClass("ui-dynatree-selected");if(paymentSummary!==null){var lockedDates=getLockedDatesCount();paymentSummary.updateFees(lockedDates);}
enableDisableSaveButton();},classNames:{checkbox:"ui-dynatree-checkbox-locked",selected:"ui-dynatree-selected-locked",container:"ui-dynatree-container",folder:"ui-dynatree-folder",document:"ui-dynatree-document",empty:"ui-dynatree-empty",vline:"ui-dynatree-vline",expander:"ui-dynatree-expander",connector:"ui-dynatree-connector",nodeIcon:"ui-dynatree-icon",nodeError:"ui-dynatree-statusnode-error",nodeWait:"ui-dynatree-statusnode-wait",hidden:"ui-dynatree-hidden",combinedExpanderPrefix:"ui-dynatree-exp-",combinedIconPrefix:"ui-dynatree-ico-",active:"ui-dynatree-active",expanded:"ui-dynatree-expanded",lazy:"ui-dynatree-lazy",focused:"ui-dynatree-focused",partsel:"ui-dynatree-partsel",lastsib:"ui-dynatree-lastsib"},onActivate:function(node){node.deactivate();setTimeout(function(){$("#relatedDeadlinesTree","#dateChangeDialog").parent().attr({scrollLeft:0});},0);},checkbox:true});if(paymentSummary)
{paymentSummary.updateFees(getLockedDatesCount());}
$("#checkAllLabel",dateChangeContainer).click(checkOrUncheckAllRelatedDates);$("#checkAll",dateChangeContainer).click(checkOrUncheckAllRelatedDates);$("#chkConfirm").click(function(){$("#chkConfirm").toggleClass("ui-dynatree-selected");enableDisableSaveButton();});if(finishedLoadingCallback!==undefined&&$.isFunction(finishedLoadingCallback))
{finishedLoadingCallback();}}});}
function openDateChangeDialog(dateDialogTransactionDateInfo){if(getTransactionDateInformationInProgress){return;}
if(dateDialogTransactionDateInfo===null){return;}
if($("#dateChangeDialog").length===0){initializeDateChange("dateChangeContainer",function(){GetTransactionDateInformation(dateDialogTransactionDateInfo);});return false;}
GetTransactionDateInformation(dateDialogTransactionDateInfo);}
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return"Not Yet Supported";},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(this.getTimezoneOffset()<0?'-':'+')+(this.getTimezoneOffset()/60<10?'0':'')+(this.getTimezoneOffset()/60)+'00';},T:function(){return"Not Yet Supported";},Z:function(){return this.getTimezoneOffset()*60;},c:function(){return"Not Yet Supported";},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};
var dateChangeContainer;var dateDialog=null;var dateDialogTransactionDateInfo;var sendDatesInProgress=false;var dateDialogGetTransactionDateInformationInProgress=false;function initializeDateDialog(container,finishedLoadingCallback){dateChangeContainer=$("#"+container);var path=ajaxIncludePath+"datedialog.aspx";$.ajax({type:"GET",url:path,dataType:"html",success:function(data,status){dateChangeContainer.html(data);if(finishedLoadingCallback!==undefined&&$.isFunction(finishedLoadingCallback)){finishedLoadingCallback();}}});}
function toggleViewChangeLogButtonEnabled(enabled){if(enabled===undefined||enabled===null){return;}
var value="disabled";if(enabled){value="";}
var button=dateDialog.parent().find(".ui-dialog-buttonpane").children("button:contains('View Change Log')");if(button===null||button.length===0){return;}
if(value==button.attr("disabled")){return;}
if(value=="disabled"){button.css("cursor","pointer");button.addClass("ui-state-disabled");}else{button.removeClass("ui-state-disabled");}
button.attr("disabled",value);}
function reloadTransactionDateInfo(transactionDateId,callback){block("#content");$.ajax({type:"POST",url:servicePath+'TransactionDateService.aspx',data:{m:"gettransactiondateinfo",TransactionDateId:transactionDateId},dataType:"json",success:function(data){if(data.Success){dateDialogTransactionDateInfo=null;}else{growlAjaxResult(data,"Get Transaction Date Information");}
callFunction(callback);},complete:function(XMLHttpRequest,textStatus){unblock("#content");}});}
function updateDetailDialogDateTime(transactionDate){$("#currentDate",dateDialog).html(transactionDate.DateDisplay);if(transactionDate.IsTimed){$("#currentTime",dateDialog).html(transactionDate.TimeDisplay);}else{$("#currentTime",dateDialog).html("");}
if(transactionDate.LastChangedOn===null||transactionDate.LastChangedOn.DateTimeOffset===null){return;}
var date=parseJsonDate(transactionDate.LastChangedOn.DateTimeOffset);$("#lastChangedDateTime",dateDialog).html(dateFormat(date,"shortDate"));$(".hideIfDateNotChanged",dateDialog).show();}
function updateDescriptionWithNotes(newdescription){$("#description",dateDialog).html(newdescription.replace(/\n/g,'<br/>'));}
function bindDateDialogData(dateDialog,transactionDateInfo){var hasChildren=transactionDateInfo.ChildCount>0;$("#transactionDateId").html("("+transactionDateInfo.TransactionDate.TransactionDateId+")");$("#transactionLink",dateDialog).html("<a href=\""+basePath+"Transaction/DateList.aspx?t="+escape(transactionDateInfo.TransactionDate.TransactionId)+"\">"+transactionDateInfo.TransactionDate.TransactionId+"</a>");if(transactionDateInfo.TransactionDate.AddedOn===null||transactionDateInfo.TransactionDate.AddedOn.DateTimeOffset===null){$("#addedOnDateTime",dateDialog).html("an unknown date");}else{var date=parseJsonDate(transactionDateInfo.TransactionDate.AddedOn.DateTimeOffset);$("#addedOnDateTime",dateDialog).html(dateFormat(date,"shortDate"));}
if(transactionDateInfo.TransactionDate.LastChangedOn===null||transactionDateInfo.TransactionDate.LastChangedOn.DateTimeOffset===null){$("#lastChangedDateTime",dateDialog).html("");$(".hideIfDateNotChanged",dateDialog).hide();}else{var date2=parseJsonDate(transactionDateInfo.TransactionDate.LastChangedOn.DateTimeOffset);$(".hideIfDateNotChanged",dateDialog).show();$("#lastChangedDateTime",dateDialog).html(dateFormat(date2,"shortDate"));}
if(transactionDateInfo.UserName===""){$("#addedBy",dateDialog).html("Unknown");}else{$("#addedBy",dateDialog).html(transactionDateInfo.UserName);}
updateDetailDialogDateTime(transactionDateInfo.TransactionDate);$("#authority",dateDialog).text(transactionDateInfo.TransactionDate.Authority);var caseRef=transactionDateInfo.Transaction.CaseReference;$("#caseReference",dateDialog).html("<a href=\""+basePath+"Case.aspx?c="+escape(caseRef)+"\">"+caseRef+"</a>");$("#description",dateDialog).html(transactionDateInfo.TransactionDate.DescriptionWithNotesDoubleSpaced.replace(/\n/g,'<br/>'));dateDialog.dialog("destroy").dialog({title:"Deadline Detail",zIndex:3999,open:function(event,ui){$(":button:contains('Save')",$("[aria-labelledby='ui-dialog-title-dateDialog']")).attr("disabled",true).css("cursor","default");doesDeadlinesHaveChanges(transactionDateInfo.TransactionDate.TransactionDateId,function(hasChanges){if(!hasChanges){$.onOffCalendarChanged('datedialog',function(data){toggleViewChangeLogButtonEnabled(true);});toggleViewChangeLogButtonEnabled(false);}});$("#offCalendar",dateDialog).attr("checked",transactionDateInfo.TransactionDate.OffCalendar).offCalendar({transactionDate:transactionDateInfo.TransactionDate});},buttons:{"Ok":function(){$(this).dialog("close");},"View Change Log":function(){openChangeLogDialog(transactionDateInfo.TransactionDate.TransactionDateId);},"User Notes":function(){openNotesDialog(transactionDateInfo.TransactionDateDetail,transactionDateInfo.TransactionDate.TransactionDateId);},"Change Date":function(){openDateChangeDialog(dateDialogTransactionDateInfo);}},modal:true,closeOnEscape:true,autoResize:true,width:600,draggable:true,resizable:true,overlay:{opacity:0.5,background:"black"},beforeclose:function(event,ui){clearNotesData();clearChangeDateData();}});}
function dateDialogGotTransactionDateInformation(data){dateDialogTransactionDateInfo=data;if(dateDialog===null||dateDialog.length===0){dateDialog=$("#dateDialog",dateChangeContainer);}
if(dateDialogTransactionDateInfo&&dateDialogTransactionDateInfo.Transaction&&dateDialogTransactionDateInfo.Transaction.IsTimed){var transactionTimeZoneInfo=dateDialogTransactionDateInfo.Transaction.TimeZoneInfo;if(transactionTimeZoneInfo&&transactionTimeZoneInfo.DisplayName){$("#transactionTimeZone").text(transactionTimeZoneInfo.DisplayName);}}
bindDateDialogData(dateDialog,dateDialogTransactionDateInfo);}
function dateDialogGetTransactionDateInformation(transactionDateId){dateDialogGetTransactionDateInformationInProgress=true;$.ajax({type:"POST",url:servicePath+'TransactionDateService.aspx',data:{m:"gettransactiondateinfo",TransactionDateId:transactionDateId},dataType:"json",success:function(data){if(data.Success){dateDialogGotTransactionDateInformation(data);}else{growlAjaxResult(data,"Get Transaction Date Information");}},complete:function(XMLHttpRequest,textStatus){dateDialogGetTransactionDateInformationInProgress=false;unblock("#content");}});}
function openDateDialog(transactionDateId){block("#content");if(dateDialogGetTransactionDateInformationInProgress){return false;}
if(transactionDateId===null){return false;}
if($("#dateDialog").length===0){initializeDateDialog("dateDialogContainer",function(){dateDialogGetTransactionDateInformation(transactionDateId);});return false;}
dateDialogGetTransactionDateInformation(transactionDateId);return false;}
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return"Not Yet Supported";},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(this.getTimezoneOffset()<0?'-':'+')+(this.getTimezoneOffset()/60<10?'0':'')+(this.getTimezoneOffset()/60)+'00';},T:function(){return"Not Yet Supported";},Z:function(){return this.getTimezoneOffset()*60;},c:function(){return"Not Yet Supported";},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};
var loadedGrid=false;var lastGridExclude;function dateGridRowClick(cell){var currentCell=$(this);var rowId=currentCell.parent().attr("id");var rowTransactionDateId=parseInt(rowId.substring(3),10);if(isNaN(rowTransactionDateId)){return;}
if($(".isuserevent",currentCell).length===0)
{openDateDialog(rowTransactionDateId);}
else
{$.userEvent('edit',{transactionDateId:rowTransactionDateId});}}
function loadGrid(params,usePaging,afterLoad,showExclude,blockid){var columns=[{display:'Exclude',name:'Exclude',width:40,sortable:true,align:'left',hide:!showExclude},{display:'Due',name:'DaysRemaining',width:60,sortable:true,align:'left'},{display:'Date/Time',name:'StartDateTimeOffset',width:50,sortable:true,align:'left'},{display:'Description',name:'DescriptionWithNotes',width:600,sortable:true,align:'left'},{display:'Authority',name:'Authority',width:110,sortable:true,align:'left'}];if(loadedGrid){$("#dateList").flexOptions({params:params});if(showExclude!=lastGridExclude){lastGridExclude=showExclude;$("#dateList").flexToggleCol(0);}
$("#dateList").flexReload();return;}
lastGridExclude=showExclude;$("#dateList").flexigrid({url:dateListServiceUrl,params:params,dataType:'json',colModel:columns,nowrap:false,sortname:"DaysRemaining",sortorder:"asc",usepager:usePaging,useRp:usePaging,rp:(usePaging?25:250),rpOptions:[5,10,15,25,50,100,150,250],showTableToggleBtn:false,showToggleBtn:false,height:'auto',onSuccess:function(){var theGrid=$("#dateList");var tbody=$("tbody",theGrid).attr("title","Click on an individual deadline for the Deadline Detail Dialog box with functions that allow you to (1) Change the date of, (2) Add notes to the description of and (3) View the changes that have been made to that specific deadline.");$('tr td',tbody).unbind().click(dateGridRowClick);var firstColumnInEachRow=$('tr td:first-child',tbody).unbind();$("span[class*='offcalendar-icon']",firstColumnInEachRow).addClass("ui-icon-cancel").css("float","right").parents("tr").addClass("offCalendar");loadedGrid=true;$("#dateList").noSelect(true);unblock(blockid);if(typeof(afterLoad)=="function"){afterLoad();}},onError:function(msg){unblock(blockid);growlError(msg,"Error");},onSubmit:function(){return block(blockid);},onReturnEmptyTotal:function(){unblock(blockid);}});}
function toggleExcludeFromGrid(transactionDateId,target){var checkbox=$(target);setExclude(transactionDateId,!checkbox.is(".ui-dynatree-selected"));checkbox.toggleClass("ui-dynatree-selected");}
var loadedTree;var treeReturnedOk;var showingExcludeOnTree;var nodesCache=[];function toggleExcludeFromTree(exclude,node){setExclude(node.data.TransactionDateId,exclude);}
function loadTree(params,lazyLoad,afterLoad,showExclude,blockid){showingExcludeOnTree=showExclude;block(blockid);$.ajax({url:dateListServiceUrl,data:params,dataType:"json",complete:function(XMLHttpRequest,textStatus){unblock(blockid);},success:function(data,textStatus){if(loadedTree){var tree=$("#datetree").dynatree("getTree");tree.options.checkbox=showExclude;var treeRoot=$("#datetree").dynatree("getRoot");treeRoot.removeChildren();treeRoot.append(data);return;}
loadedTree=true;$("#datetree").dynatree({title:"Date Tree (Click on any description to add/edit your own notes)",autoFocus:false,autoCollapse:false,rootVisible:false,persist:false,clickFolderMode:1,fx:{height:"toggle",duration:200},children:data,onSelect:function(flag,dtnode){if(!treeReturnedOk){return;}
dtnode._select(!flag,false,false);toggleExcludeFromTree(flag,dtnode);},onActivate:function(node){node.deactivate();if(node.data.TransactionDateId>0){if(node.data.isUserEvent)
{$.userEvent('edit',{transactionDateId:node.data.TransactionDateId});}
else
{openDateDialog(node.data.TransactionDateId);}
setTimeout(function(){$("#datetree").parent().attr({scrollLeft:0});},0);}},checkbox:showExclude,onLazyRead:function(dtnode){if(!lazyLoad){return;}
params.parent=dtnode.data.TransactionDateId;params.showExcluded=showingExcludeOnTree;dtnode.appendAjax({url:dateListServiceUrl,data:params,cache:true});nodesCache=[];}});treeReturnedOk=true;if(typeof(afterLoad)=="function"){afterLoad();}}});}
function GetNodesForTransactionDateId(treename,transactionDateId){if(!nodesCache[treename]){var treeElement=$(treename);if(treeElement===undefined||treeElement===null||treeElement.length===0){return null;}
var tree=treeElement.dynatree("getTree");if(!tree){return null;}
nodesCache[treename]=[];tree.getRoot().visit(function(node,cache){if(node.data.TransactionDateId){if(!cache[node.data.TransactionDateId])
{cache[node.data.TransactionDateId]=[];}
cache[node.data.TransactionDateId][cache[node.data.TransactionDateId].length]=node;}
return true;},nodesCache[treename],false);}
var idarray=nodesCache[treename][transactionDateId];if(idarray){return idarray;}
return null;}
function EachNodeForTransactionDateId(treename,transactionDateId,callback){var array=GetNodesForTransactionDateId(treename,transactionDateId);if(array){for(var name in array){if(array.hasOwnProperty(name)){callback(array[name]);}}}}
function GetNodeForTransactionDateId(treename,transactionDateId){var array=GetNodesForTransactionDateId(treename,transactionDateId);if(array&&array.length>0)
{return array[0];}
return null;}
function GetNodeForExclusionId(treename,exclusionId){var foundNode;$(treename).dynatree("getTree").getRoot().visit(function(node,exclusionId){if(node.data.exclusionId!=exclusionId)
{return true;}
foundNode=node;},exclusionId,false);return foundNode;}
function getExpandedNodes(treeRoot,expandedNodesRetVal,isParentExpanded){if(treeRoot===null||expandedNodesRetVal==null)return;if(treeRoot.data.key!=undefined&&!expandedNodesRetVal.contains(treeRoot.data.key)&&treeRoot.data.key!="root"){if((!treeRoot.data.isFolder&&isParentExpanded)||(treeRoot.data.isFolder))
expandedNodesRetVal.push(treeRoot.data.key);}
if(treeRoot.childList!=null&&treeRoot.childList.length>0&&treeRoot.bExpanded){for(var i=0;i<treeRoot.childList.length;i++){getExpandedNodes(treeRoot.childList[i],expandedNodesRetVal,treeRoot.bExpanded);}
return expandedNodesRetVal;}}
function openDialog(title,message,question,width,height,redirectUrlOrYesCallback,noCallback){$("#dialog").attr("title","");$("#dialogMessage").text("");$("#dialogQuestion").text("");$("#dialog").attr("title",title);$("#dialogMessage").html(message);$("#dialogQuestion").text(question);$("#dialog").dialog({buttons:{"Yes":function(){$(this).dialog("close");if(!$.isFunction(redirectUrlOrYesCallback))
{window.location=redirectUrlOrYesCallback;}
else
{redirectUrlOrYesCallback();}},"No":function(){$(this).dialog("close");if(noCallback!==null&&$.isFunction(noCallback))
{noCallback();}}},modal:true,height:height==-1?200:height,width:width==-1?300:width,draggable:true,overlay:{opacity:0.5,background:"black"}});}
function dialogClose(){}
function emailButton(params){$("#emailButton").attr('disabled',true).addClass('ui-state-disabled');$.ajax({type:"GET",url:dateListServiceUrl,data:params,dataType:"json",success:function(result){$("#emailButton").attr('disabled',false).removeClass('ui-state-disabled');growlAjaxResult(result,"Email List");}});return false;}
var constants={maxdays:10,navheight:25,scrollbarwidth:21,timebarwidth:50,timehourheight:50,secondsperday:86400,maxeventspermonthday:10,maxalldayeventsperday:10,minwidth:512,minheight:384,elementid:'jEventCalendar',mainTarget:null};function GetShowWeekendsFromCookie(){return $.cookie('HideWeekends')===null;}
var globals={firstDayRendered:null,lastDayRendered:null,firstDayVisible:null,lastDayVisible:null,currentDate:new Date().zeroTime(),currentView:'month',dayWidth:null,days:null,consolidated:false,includeClosedCases:false,serviceUrl:null,caseReferenceFilter:null,printView:false,printDayUrl:null,OnDrawEventsComplete:null,showWeekends:GetShowWeekendsFromCookie(),moreDialog:null,ddlMatterReference:$("#ddlMatterReference"),chkIncludeClosedCases:$("#chkIncludeClosedCases")};var timedEventData={};var alldayEventData={};function consolelog(x){if(window.console){console.log(x);}}
function Resize(){if(globals.printView){$("#emptyupperleft").hide();$("#emptyupperright").hide();$("#container").width(665);$(".timedevents_day").width(579);return;}
var browserwidth=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;var browserheight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;var containerwidth=$("#container").width();var containerheight=$("#container").height();var calendarwidth=Math.max(browserwidth-45,constants.minwidth);$("#container").width(browserwidth-20);var calendarheight=Math.max(browserheight-$("#banner").height()-$("#copyright").height()-80,constants.minheight);var firstDayOfMonth=new Date(globals.currentDate);firstDayOfMonth.setDate(1);var cellsNeeded=firstDayOfMonth.getDay()+firstDayOfMonth.getDaysInMonth();var rowsNeeded=Math.ceil(cellsNeeded/7);var calendarDayHeight=Math.floor((calendarheight-constants.navheight-$("#weekdaynamerow").height())/rowsNeeded);var eventsPerDay=Math.floor(calendarDayHeight/15)-2;eventsPerDay=Math.min(eventsPerDay,constants.maxeventspermonthday);for(var i=0;i<=constants.maxeventspermonthday;i++){if(i<eventsPerDay){$(".event_"+i).show();$(".morelink_"+i).hide();}else{$(".event_"+i).hide();$(".morelink_"+i).show();}}
var calendarDayWidth=Math.floor(calendarwidth/(globals.showWeekends?7:5));$(".calendar_day").height(calendarDayHeight);$(".calendar_day").width(calendarDayWidth);if(!globals.printView){$("#timeofdaydiv").height(calendarheight-constants.navheight-$("#daysheader").height()-$("#alldayevents").height()-10);}
var daywidth;if(globals.days){var days=globals.days;if(days===7&&!globals.showWeekends){days=5;}
daywidth=Math.floor((calendarwidth-constants.timebarwidth-constants.scrollbarwidth)/days);$(".dayheader").width(daywidth);$(".timedevents_day").width(daywidth);}
consolelog("Resize: browser="+browserwidth+"x"+browserheight+", container="+containerwidth+"x"+containerheight+", calendar="+calendarwidth+"x"+calendarheight+", calendar_day_cell: "+calendarDayWidth+"x"+calendarDayHeight+", daywidth="+daywidth);}
function SetupMonthView(){var tbody=$("<tbody />");var weekdaynamerow=$("<tr />").attr("id","weekdaynamerow");var i;for(i=0;i<7;i++){var weekdaynamecell=$("<td />").css({"font-weight":"bold","text-align":"center"}).text(Date.abbrDayNames[i]);if(i===0||i===6){weekdaynamecell.addClass("weekend");if(!globals.showWeekends){weekdaynamecell.hide();}}
weekdaynamerow.append(weekdaynamecell);}
tbody.append(weekdaynamerow);for(i=0;i<42;i++){var weekRow;var isWeekend=false;if(i%7===0){weekRow=$("<tr />").addClass("calendar_week").attr("id","week_"+Math.floor(i/7));isWeekend=true;}
var dayCell=$("<td />").attr("id","day_"+i+"_cell").addClass("calendar_day_cell");var dayDiv=$("<div />").attr("id","day_"+i).addClass("calendar_day").dblclick(function(){return function(){var date=$(this).attr("date");$.userEvent('create',{caseReference:globals.caseReferenceFilter,date:date});return false;};}());var dateDiv=$("<div />").attr("id","day_"+i+"_date").addClass("calendar_day_number").append($("<a/>").attr("id","day_"+i+"_date_link").attr("href","#").addClass("daylink"));dayDiv.append(dateDiv);dayCell.append(dayDiv);weekRow.append(dayCell);if((i+1)%7===0){tbody.append(weekRow);isWeekend=true;}
if(isWeekend){dayCell.addClass("weekend");if(!globals.showWeekends){dayCell.hide();}}}
return $("<table />").attr("border",1).append(tbody);}
function SetupDaysView(){var toptable=$("<table cellspacing='0' />").append($("<thead />").append($("<tr />").attr("id","daysheader"))).append($("<tbody />").attr("id","alldayevents"));var topwrappertablerow=$("<tr />").append($("<td />").append($("<div />").attr("id","emptyupperleft").width(constants.timebarwidth))).append($("<td />").append(toptable)).append($("<td />").append($("<div />").attr("id","emptyupperright").width(constants.scrollbarwidth)));var topwrappertable=$("<table />").attr("id","b").append(topwrappertablerow);var timedeventsrow=$("<tr />");var i;for(i=0;i<constants.maxdays;i++){var timedeventsday=$("<div />").attr("id","timedevents_day_"+i).addClass("timedevents_day").css("position","relative").height(24*constants.timehourheight);timedeventsrow.append($("<td />").addClass("tdTimedevents_day").append(timedeventsday));}
var timedeventstable=$("<table cellspacing='0' />").height(24*constants.timehourheight);timedeventstable.append(timedeventsrow);var timedeventscell=$("<td />").attr("valign","top").append(timedeventstable);var timesofdaycell=$("<td />");for(i=0;i<24;i++){var hour=i%12;if(hour===0){hour=12;}
hour+=(i<12)?"am":"pm";var timediv=$("<div />").addClass("hour").height(constants.timehourheight).width(constants.timebarwidth).text(hour);timesofdaycell.append(timediv);}
var timeofdaytable=$("<table />").height(24*constants.timehourheight);timeofdaytable.append($("<tr />").append(timesofdaycell).append(timedeventscell));var timeofdaydiv=$("<div />").attr("id","timeofdaydiv").css("position","relative");if(!globals.printView){timeofdaydiv.height("500px").css("overflow-y","scroll");}
timeofdaydiv.append(timeofdaytable);var outertable=$("<table />");outertable.append($("<tr />").append($("<td />").append(topwrappertable)));outertable.append($("<tr />").append($("<td />").append(timeofdaydiv)));return outertable;}
function SetupAgendaView(){return $("<div/>").attr("id","agendacontainer").css("overflow","auto").append($("<div/>").attr("id","agendacontent").css("overflow","none"));}
function blockcalendar(id){consolelog("blocking");if($(".blockUI",$(id)).length===0){$(id).block({message:'<span id="calWaiting"><strong>Loading calendar ...</strong></span>',css:{padding:4,margin:'auto auto',xtop:'40%',xleft:'25%',textAlign:'center',color:'#000',backgroundColor:'#fff',cursor:'wait',border:'3px solid black'},overlayCSS:{backgroundColor:'#000',opacity:'0.2'}});}
return true;}
function DrawCalendar(){blockcalendar("#content");setTimeout(executeDrawCalendar,50);}
function SetCurrentDate(date){var oldDate=new Date(globals.currentDate);var newDate=new Date(date).zeroTime();globals.currentDate=newDate;consolelog("Changed globals.currentDate from "+oldDate+" to "+newDate);}
function ChangeViewDate(direction){var oldDate=new Date(globals.currentDate);var newDate;var view=globals.currentView;if(direction===0){var today=new Date().zeroTime();if(oldDate.valueOf()===today.valueOf()){consolelog("ChangeViewDate was already on "+today);return;}
newDate=today;}else if(direction===-2||direction===2){var increment=direction/Math.abs(direction);if(view==='month'){newDate=new Date(oldDate).addYears(increment).zeroTime();}else if(view==='week'||view==='5day'){newDate=new Date(oldDate).addMonths(increment).zeroTime();}else if(view==='day'){newDate=new Date(oldDate).addDays(7*increment).zeroTime();}else{alert('Invalid view in ChangeViewDate: '+view);consolelog('Invalid view in ChangeViewDate: '+view);return;}}else{if(direction!==-1&&direction!==1){growlError('Invalid direction in ChangeViewDate: '+direction);}
if(view==='month'){newDate=new Date(oldDate).addMonths(direction).zeroTime();}else if(view==='week'||view==='day'){newDate=new Date(oldDate).addDays(globals.days*direction).zeroTime();}else if(view==='5day'){newDate=new Date(oldDate).addDays(7*direction).zeroTime();}else{alert('Invalid view in ChangeViewDate: '+view);consolelog('Invalid view in ChangeViewDate: '+view);return;}}
SetCurrentDate(newDate);DrawCalendar();}
function ShowGoButton(){$("#btnGo").show();}
function DateDropdownChange(){var monthdropdown=$("#monthdropdown");var yeardropdown=$("#yeardropdown");var date=new Date(yeardropdown.val(),monthdropdown.val(),1);if(globals.currentView!=='month'){var daydropdown=$("#daydropdown");var day=daydropdown.val();if(day>date.getDaysInMonth()){day=date.getDaysInMonth();}
date.setDate(day);}
SetCurrentDate(date);DrawCalendar();return false;}
function SetDaysVisible(){if(globals.showWeekends||globals.currentView!=='week'){globals.firstDayVisible=new Date(globals.firstDayRendered);globals.lastDayVisible=new Date(globals.lastDayRendered);}else{globals.firstDayVisible=new Date(globals.firstDayRendered).addDays(1).zeroTime();globals.lastDayVisible=new Date(globals.lastDayRendered).addDays(-1).zeroTime();}
consolelog("SetDaysVisible: "+globals.firstDayVisible+" - "+globals.lastDayVisible+" (rendered "+globals.firstDayRendered+" - "+globals.lastDayRendered+")");}
function SetTitle(){var title;if(globals.currentView==='month'){title='Month View';}else if(globals.currentView==='week'){title='Week View';}else if(globals.currentView==='5day'){title='5 Day View';}else if(globals.currentView==='day'){title='Day View';}
var datetext;if(globals.currentView==="month"){datetext=globals.currentDate.asString("mmmm, yyyy");}else{if(globals.firstDayVisible.getYear()!==globals.lastDayVisible.getYear()){datetext=globals.firstDayVisible.asString("mmmm d, yyyy")+"-"+globals.lastDayVisible.asString("mmmm d, yyyy");}else if(globals.firstDayVisible.getMonth()!==globals.lastDayVisible.getMonth()){datetext=globals.firstDayVisible.asString("mmmm d")+"-"+globals.lastDayVisible.asString("mmmm d, yyyy");}else if(globals.firstDayVisible.getDate()!==globals.lastDayVisible.getDate()){datetext=globals.firstDayVisible.asString("mmmm d")+"-"+globals.lastDayVisible.asString("d, yyyy");}else{datetext=globals.firstDayVisible.asString("mmmm d, yyyy");}}
title+=" - "+datetext;if(window.SetPageTitle){SetPageTitle(title);}}
function UpdateYearDropdown(){var currentYear=globals.currentDate.getFullYear();if(globals.currentView==='week'||globals.currentView==='5day'){currentYear=globals.firstDayVisible.getFullYear();}
if(currentYear!==globals.previousDropdownYear){globals.previousDropdownYear=currentYear;consolelog("Refilling year dropdown");var yeardropdown=$("#yeardropdown");yeardropdown.empty();var yearsToShow=5;for(var i=-yearsToShow;i<=yearsToShow;i++){var option=$("<option/>").text(currentYear+i);if(i===0){option.attr("selected","selected");}
yeardropdown.append(option);}}}
function UpdateMonthDropdown(){var currentMonth=globals.currentDate.getMonth();if(globals.currentView==='week'||globals.currentView==='5day'){currentMonth=globals.firstDayVisible.getMonth();}
$("#monthdropdown").val(currentMonth);}
function UpdateDayDropdown(){var daydropdown=$("#daydropdown");var dropdownDate=globals.currentDate;if(globals.currentView==='week'||globals.currentView==='5day'){dropdownDate=globals.firstDayVisible;}
if(dropdownDate.getMonth()!==globals.previousDayDropdownMonth||globals.currentView!==globals.previousDayDropdownView||globals.showWeekends!==globals.previousShowWeekends){globals.previousDayDropdownMonth=dropdownDate.getMonth();globals.previousDayDropdownView=globals.currentView;globals.previousShowWeekends=globals.showWeekends;consolelog("Refilling day dropdown");daydropdown.empty();var selectedDay,option;if(globals.currentView==='day'){selectedDay=globals.currentDate.getDate();for(var i=1;i<=dropdownDate.getDaysInMonth();i++){option=$("<option/>").text(i);if(i===selectedDay){option.attr("selected","selected");}
daydropdown.append(option);}}else{var firstWeekdayShown=0;if(globals.currentView==='5day'||!globals.showWeekends){firstWeekdayShown=1;}
var startingDay=new Date(dropdownDate.getFullYear(),dropdownDate.getMonth(),1);if(startingDay.getDay()<firstWeekdayShown){startingDay.addDays(firstWeekdayShown-startingDay.getDay());}else if(startingDay.getDay()>firstWeekdayShown){startingDay.addDays(7-startingDay.getDay()+firstWeekdayShown);}
selectedDay=globals.firstDayVisible.getDate();for(var date=new Date(startingDay);date.getMonth()===startingDay.getMonth();date.addDays(7).zeroTime()){option=$("<option/>").text(date.getDate());if(date.getDate()===selectedDay){option.attr("selected","selected");}
daydropdown.append(option);}}}else{if(globals.currentView==='day'){daydropdown.val(globals.currentDate.getDate());}else{daydropdown.val(globals.firstDayVisible.getDate());}}}
function UpdateCurrentMonthYear(){UpdateYearDropdown();UpdateMonthDropdown();if(globals.currentView!=='month'){UpdateDayDropdown();}
$("#btnGo").hide();}
function SetShowWeekends(value){if(globals.showWeekends!==value){globals.showWeekends=value;if(value){$.cookie('HideWeekends',null);$(".weekend").show();}else{$.cookie('HideWeekends','true',{expires:1000});$(".weekend").hide();}
Resize();SetDaysVisible();SetTitle();UpdateCurrentMonthYear();}}
function SwitchView(view,date){if(globals.currentView===view&&!date){return;}
if(view==='day'||view==='5day'){$("#lblShowWeekends").hide();}else{$("#lblShowWeekends").show();}
globals.currentView=view;var daydropdown=$("#daydropdown");if(view==='month'){daydropdown.hide();}else{daydropdown.show();}
if(view==='day'){$(".printDayLink").show();}else{$(".printDayLink").hide();}
if(date){SetCurrentDate(date);}
DrawCalendar();}
function SetupNav(){var changeDateLinks=$("<div />").append($("<a />").attr("href","#").text("<<").click(function(){ChangeViewDate(-2);return false;})).append(" &nbsp; ").append($("<a />").attr("href","#").text("Prev").click(function(){ChangeViewDate(-1);return false;})).append(" &nbsp; ").append($("<a />").attr("href","#").text("Today").click(function(){ChangeViewDate(-0);return false;})).append(" &nbsp; ").append($("<a />").attr("href","#").text("Next").click(function(){ChangeViewDate(1);return false;})).append(" &nbsp; ").append($("<a />").attr("href","#").text(">>").click(function(){ChangeViewDate(2);return false;}));var monthdropdown=$("<select />").attr("id","monthdropdown").css("font-weight","bold").change(ShowGoButton);for(var i=0;i<12;i++){monthdropdown.append($("<option />").val(i).text(Date.monthNames[i]));}
var daydropdown=$("<select />").attr("id","daydropdown").css("font-weight","bold").change(ShowGoButton).css("display","none");var yeardropdown=$("<select />").attr("id","yeardropdown").css("font-weight","bold").change(ShowGoButton);var gobutton=$("<input/>").attr("type","button").attr("id","btnGo").val("Go").click(DateDropdownChange).css("display","none");var currentDateDiv=$("<div />").attr("id","calendar_current_date").append(monthdropdown).append(daydropdown).append(yeardropdown).append(gobutton);var viewSelector=$("<div />").append($("<a />").addClass("printDayLink").addClass("ui-helper-hidden").text("Print").attr("href","#").click(function(){var y=globals.currentDate.getFullYear();var m=globals.currentDate.getMonth()+1;var day=globals.currentDate.getDate();var date=m+"/"+day+"/"+y;window.open(globals.printDayUrl+"?d="+date,"base");return false;})).append($("<label/>").attr("id","lblShowWeekends").attr("for","chkShowWeekends").addClass("checkboxContainer").css("display","inline").append($("<input/>").attr("id","chkShowWeekends").attr("type","checkbox").click(function(){SetShowWeekends($(this).attr("checked"));})).append(" Show Weekends")).append(" &nbsp; ").append($("<span />").addClass("printDayLink").addClass("ui-helper-hidden").html(" &nbsp; ")).append($("<a />").text("Month").attr("href","#").click(function(){SwitchView('month');return false;})).append(" &nbsp; ").append($("<a />").text("Week").attr("href","#").click(function(){SwitchView('week');return false;})).append(" &nbsp; ").append($("<a />").text("Day").attr("href","#").click(function(){SwitchView('day');return false;}));var nav=$("<div />").attr("id","calendar_controls").height(constants.navheight);nav.append($("<table />").attr("width","100%").append($("<tr />").append($("<td width='33%' align='left' />").append(changeDateLinks)).append($("<td width='33%' align='center' />").append(currentDateDiv)).append($("<td width='33%' align='right' />").append(viewSelector))));return nav;}
function ClearCachedData(){timedEventData={};alldayEventData={};}
function SetConsolidated(value){if(globals.consolidated!==value){globals.consolidated=value;ClearCachedData();DrawCalendar();}}
function SetIncludeClosedCases(value){if(globals.includeClosedCases!==value){globals.includeClosedCases=value;ClearCachedData();DrawCalendar();}}
function ChangeCaseReferenceFilter(filter){if(!filter){filter=null;}
globals.caseReferenceFilter=filter;DrawCalendar();}
function SetupBottomControls(){var bottomTable=$('<table border="0" width="100%"><tbody><tr><td align="left"><div id="showCombinedContainer"><input id="chkConsolidated" type="checkbox" /> <label for="chkConsolidated">Include cases for all users on this account</label></div></td>'+'<td align="left"><div id="includeClosedCasesContainer"><input id="chkIncludeClosedCases" type="checkbox" /> <label for="chkIncludeClosedCases">Include closed cases</label></div></td>'+'<td align="right"><select id="ddlMatterReference"><option value="">(Show all Cases)</option></select></td></tr></tbody></table><div id="linksContainer" class="ui-helper-hidden"><a style="cursor:pointer" onclick="addCourtEventClick()" class="addCourtEvent">Add new court ruled event</a><br /><a style="cursor:hand" onclick="addUserEventClick()" class="addUserEvent">Add user event</a></div>');$("#chkConsolidated",bottomTable).click(function(){SetConsolidated($(this).attr("checked"));});globals.chkIncludeClosedCases=$("#chkIncludeClosedCases",bottomTable);globals.chkIncludeClosedCases.click(function(){SetIncludeClosedCases($(this).attr("checked"));});globals.ddlMatterReference=$("#ddlMatterReference",bottomTable);globals.ddlMatterReference.change(function(){ChangeCaseReferenceFilter($(this).val());});return bottomTable;}
function hideIfStillShown(){var hideLinks=$("#linksContainer").data("hideLinks");if(hideLinks){$("#linksContainer").hide();}}
function SetupAddEventLinks(){$(".calendar_day").css("position","relative").hover(function(){var date=$(this).attr("date");var div=$("<div/>").attr("id","links"+$(this).attr("id")).addClass("addUserEventLink");var calendarDay=$(this);div.append($("<a/>").attr("id","lnkAddEvent"+$(this).attr("id")).text("Add Event").css("cursor","hand")).click(function(){var hideLinks=true;var scrollOffsetTop=0;var pos=calendarDay.offset();var browserwidth=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;if($.browser.msie){var iebody=(document.compatMode&&document.compatMode!="BackCompat")?document.documentElement:document.body;scrollOffsetTop=document.all?iebody.scrollTop:window.pageYOffset;if($.browser.version=="6.0"){$("#linksContainer").css("bottom",0);scrollOffsetTop=0;pos=calendarDay.position();}}else{scrollOffsetTop=window.pageYOffset;}
var left=pos.left+calendarDay.width()-5;var top=pos.top+calendarDay.height()-5;if(scrollOffsetTop>0){top-=scrollOffsetTop;}
$("#linksContainer").data("date",date).css("left",left+"px").css("top",top+"px").show();var cutOffSize=0;var combinedWidth=left+parseInt($("#linksContainer").width(),10);if($.browser.msie&&$.browser.version=="6.0")
{combinedWidth+=30;}
else
{combinedWidth+=10;}
if(combinedWidth>browserwidth){var existingLeft=$("#linksContainer").css("left");existingLeft=existingLeft.substring(0,existingLeft.indexOf("px"));if($.browser.safari||$.browser.mozilla){existingLeft-=10;}
$("#linksContainer").css("left",(existingLeft-130)+"px");}
$("#linksContainer").mouseleave(function(){if($(this).data("hideLinks")!==true){$(this).data("hideLinks",true);}
$(this).hide();}).mouseover(function(){if($(this).data("hideLinks")){$(this).data("hideLinks",false);}});setTimeout(hideIfStillShown,2500);});$(this).append(div);div.fadeIn();},function(){$(".addUserEventLink").fadeOut().remove();$("#linkContainer"+$(this).attr("id")).remove();});}
function addCourtEventClick(){var date=$("#linksContainer").data("date");if(date===null||date===undefined){return false;}
var caseRef=$("#ddlMatterReference").children(":selected").val();if(caseRef.toLowerCase().indexOf("show all cases")>0){caseRef="";}
blockcalendar("#content");$.ajax({type:"GET",url:globals.serviceUrl,data:{m:"getAddCourtRuledUrl",date:date,caseReference:encodeURIComponent(caseRef)},dataType:"json",success:function(data,textStatus){if(data.length>0){window.location=data;}},complete:function(XMLHttpRequest,textStatus){unblock("#content");}});}
function addUserEventClick(){var date=$("#linksContainer").data("date");if(date===null||date===undefined){return false;}
$.userEvent('create',{caseReference:globals.caseReferenceFilter,date:date});}
var caseInDropdown={};function ClearMatterReferences(consolidated){var toRemove;if(consolidated){toRemove=globals.ddlMatterReference.children().not(":first");if(toRemove.length>0){toRemove.remove();}}else{toRemove=globals.ddlMatterReference.children().not(":first").not(":selected");if(toRemove.length>0){toRemove.remove();}}
if(globals.chkIncludeClosedCases.attr("checked")===false){if(globals.ddlMatterReference.children("option:selected").data("isClosed")){globals.ddlMatterReference.children("option:selected").remove();ChangeCaseReferenceFilter(globals.ddlMatterReference.children("first-child").val());}else{var options=globals.ddlMatterReference.children("option");$.each(options,function(i,arg){var option=$(arg);if(option===null){return true;}
if(option.data("isClosed")){var toRemove=globals.ddlMatterReference.children("option:eq("+i+")");if(toRemove.length>0){toRemove.remove();}}});}}
caseInDropdown={};}
function GetDateString(date){var month=date.getMonth()+1;var dayOfMonth=date.getDate();return date.getFullYear()+(month<10?"0":"")+month+(dayOfMonth<10?"0":"")+dayOfMonth;}
function ClearEvents(){var removing=$(".event,.morelinkdiv");for(var i=0;i<removing.length;i++){removing[i].parentNode.removeChild(removing[i]);}
$("#alldayevents").empty();$(".timedevents_day").empty();}
var casecolors={};function GetCaseReferenceColor(casereference){var color=casecolors[casereference.toLowerCase()];if(!color){var minimumColorDifference=50;var retries=0;var maxRetries=20;for(retries=0;retries<maxRetries;retries++){color={red:Math.floor((Math.random()*256+255)/2),green:Math.floor((Math.random()*256+255)/2),blue:Math.floor((Math.random()*256+255)/2)};if(retries===10){minimumColorDifference=minimumColorDifference*0.75;}
var distinctEnough=true;for(var key in casecolors){if(casecolors.hasOwnProperty(key)){var existingcolor=casecolors[key];if(Math.abs(existingcolor.red-color.red)<minimumColorDifference&&Math.abs(existingcolor.green-color.green)<minimumColorDifference&&Math.abs(existingcolor.blue-color.blue)<minimumColorDifference){distinctEnough=false;break;}}}
if(distinctEnough){break;}}
casecolors[casereference.toLowerCase()]=color;}
return"rgb("+color.red+","+color.green+","+color.blue+")";}
function AddCaseReferenceToDropdownIfNotPresent(casereference,isClosed){if(!casereference){return;}
if(caseInDropdown[casereference.toLowerCase()]){return;}
caseInDropdown[casereference.toLowerCase()]=true;var includeClosedCases=globals.chkIncludeClosedCases.attr("checked");if(globals.ddlMatterReference.length===1&&!includeClosedCases?!isClosed:true){var newoption=$("<option />").append(casereference).css("background-color",GetCaseReferenceColor(casereference)).data("isClosed",isClosed);var options=$("option",globals.ddlMatterReference);if(options.length===1){options.after(newoption);}else{$.each(options,function(i){if(i===0){return true;}
var option=$(this);if(casereference.toLowerCase()<option.val().toLowerCase()){option.before(newoption);return false;}else if(casereference.toLowerCase()===option.val().toLowerCase()){return false;}else if(i===options.length-1){option.after(newoption);return false;}});}}}
function getEventsToDrawUnfiltered(events,max,outInfo){var eventsToDraw=[];var eventsDrawn=0;if(!max){return events;}
var eachindex;var event;for(eachindex=0;eachindex<events.length;eachindex++){event=events[eachindex];AddCaseReferenceToDropdownIfNotPresent(event.casereference,event.isClosed);if(++eventsDrawn>max){if(outInfo){outInfo.truncated=true;}}else{eventsToDraw.push(event);}}
return eventsToDraw;}
function getEventsToDrawForCaseReference(events,max,outInfo){var eventsToDraw=[];var casesSeen={};var eventsDrawn=0;var lowerCaseReference=globals.caseReferenceFilter.toLowerCase();for(var eachindex=0;eachindex<events.length;eachindex++){var event=events[eachindex];AddCaseReferenceToDropdownIfNotPresent(event.casereference,event.isClosed);if(lowerCaseReference===event.casereference.toLowerCase()){if(max&&++eventsDrawn>max){if(outInfo){outInfo.truncated=true;}}else{eventsToDraw.push(event);}}}
return eventsToDraw;}
function GetEventsToDraw(events,max,outInfo){if(events===undefined||events.length===0){return[];}
if(globals.caseReferenceFilter===null){return getEventsToDrawUnfiltered(events,max,outInfo);}else{return getEventsToDrawForCaseReference(events,max,outInfo);}}
function CheckValidEvent(event){if(typeof event.id==="undefined"){consolelog("Skipping event with no id");return false;}
if(typeof event.start==="undefined"){consolelog("Skipping event with no start");return false;}
if(typeof event.title==="undefined"){event.title="(No description)";}
return true;}
function GetEventTimeString(event){var timeString='';if(event.timed){var hour=event.start.getHours();var ampm=hour<12?"am":"pm";hour=hour%12;if(hour===0){hour=12;}
timeString=hour;var minutes=event.start.getMinutes();if(minutes>0){timeString+=':';if(minutes>9){timeString+=minutes;}else{timeString+='0'+minutes;}}
timeString+=ampm+" ";}
return timeString;}
function GetEventColor(eventOrCaseReference){var isclosed=false;var casereference=eventOrCaseReference;if(eventOrCaseReference.isClosed){isclosed=eventOrCaseReference.isClosed;}
if(eventOrCaseReference.casereference){casereference=eventOrCaseReference.casereference;}
AddCaseReferenceToDropdownIfNotPresent(casereference,isclosed);return GetCaseReferenceColor(casereference);}
function createEventLink(event,time){var innerHtml="";if(!globals.printView){var cssClass='eventLink';if(event.isuserevent){cssClass+=' isuserevent';}
var style="";if(event.bold){style=' style="font-weight:bold;"';}
innerHtml='<a class="'+cssClass+'" href="#" eid="'+event.id+'"'+style+'>'+time+event.title+'</a>';}else{innerHtml=event.casereference+': '+time+event.title;if(event.bold){innerHtml='<strong>'+innerHtml+'</strong>';}}
return innerHtml;}
function GetEventDiv(event,addClass){var time=GetEventTimeString(event);var backgroundColor=GetEventColor(event);var title=time+"["+event.casereference+'] '+event.title;if(event.jurisdiction!==undefined&&event.jurisdiction!==null&&event.jurisdiction.length>0){title+='\n('+event.jurisdiction+')';}
var cssClass="event";if(addClass!==undefined&&addClass!==null){cssClass+=" "+addClass;}
if(event.otheruser){cssClass+=" otheruserevent";}
return'<div eid="'+event.id+'" class="'+cssClass+'" title="'+title+'" style="background-color:'+backgroundColor+';">'+createEventLink(event,time)+'</div>';}
function ShowMoreEventsDialog(date){var datestring=GetDateString(date);consolelog("ShowMoreEventsDialog("+date+") "+datestring);var allEvents;if(alldayEventData[datestring]&&timedEventData[datestring]){allEvents=alldayEventData[datestring].concat(timedEventData[datestring]);}
else if(!alldayEventData[datestring]){allEvents=timedEventData[datestring];}
else{allEvents=alldayEventData[datestring];}
var events=GetEventsToDraw(allEvents);var title=events.length+' event'+(events.length===1?'':'s')+' on '+date.toLocaleDateString();if(globals.moreDialog===null){globals.moreDialog=$("#moreEventsDialog");}
globals.moreDialog.dialog("destroy").dialog({title:title,width:450,height:400,buttons:{"OK":function(){$(this).dialog("close");}},open:function(event,ui){var moreEventsSpan=$(".moreEvents",$(this));moreEventsSpan.empty();var eventDivs=[];for(var i=0;i<events.length;i++){eventDivs.push(GetEventDiv(events[i]));}
moreEventsSpan.append(eventDivs.join(''));}});}
function GetMoreLink(date,index){var cssClass="morelinkdiv";if(index!==undefined&&index!==null){cssClass+=" ui-helper-hidden morelink_"+index;}
return'<div class="'+cssClass+'"><a class="moreLink" date="'+date+'" href="#">More...</a></div>';}
function FindAllDayEventCell(startdayindex,eventdays){var foundCell;$.each($(".alldayrow"),function(eachindex){var alldayrow=$(this);var firstCellNeeded;var dayindex=0;$.each(alldayrow.children(),function(subeachindex){var cell=$(this);if(dayindex===startdayindex){firstCellNeeded=cell;}
if(dayindex>=startdayindex){return false;}
var colspan=parseInt(cell.attr("colspan"),10)||1;dayindex+=colspan;});if(!firstCellNeeded||firstCellNeeded.children().length>0){return true;}
if(eventdays>1){var otherCellsNeeded=firstCellNeeded.nextAll().slice(0,eventdays-1);if(otherCellsNeeded.children().length>0){return true;}
otherCellsNeeded.remove();firstCellNeeded.attr("colspan",eventdays);}
foundCell=firstCellNeeded;return false;});if(foundCell){return foundCell;}
var eventCell;var row=$("<tr />").addClass("alldayrow");$("#alldayevents").append(row);for(var i=0;i<globals.days;i++){var cell=$("<td />");var isWeekend=globals.days===7&&(i===0||i===6);cell.toggleClass("weekend",isWeekend);if(isWeekend&&!globals.showWeekends){cell.hide();}
row.append(cell);if(i===startdayindex){eventCell=cell;if(eventdays>1){cell.attr("colspan",eventdays);i+=eventdays;}}}
return eventCell;}
function DrawDayEventAllDay(dayindex,event){if(!CheckValidEvent(event)){return;}
var eventdays=1;var cell=FindAllDayEventCell(dayindex,eventdays);cell.append(GetEventDiv(event,"alldayevent"));}
function GetAllDayMoreLinkRow(){var alldaymorelinkrow=$("#alldaymorelinkrow");if(alldaymorelinkrow.length===0){alldaymorelinkrow=$("<tr />").attr("id","alldaymorelinkrow");for(var i=0;i<globals.days;i++){var cell=$("<td />");if(i===0||i===7){cell.addClass("weekend");if(!globals.showWeekends){cell.hide();}}
alldaymorelinkrow.append(cell);}
$("#alldayevents").append(alldaymorelinkrow);}
return alldaymorelinkrow;}
function DrawDayEventTimed(dayindex,event){if(!CheckValidEvent(event)){return;}
var startHour=event.start.getHours()+(event.start.getMinutes()/60);var lengthHours=1;if(startHour+lengthHours>24){lengthHours=24-startHour;}
var timedevent=$(GetEventDiv(event)).attr("id","transactiondate_"+event.id).addClass("timedevent").css("top",startHour*constants.timehourheight).css("height",lengthHours*constants.timehourheight);if(event.columncount){var columnwidthpercent=100/event.columncount;timedevent.css("left",(columnwidthpercent*event.columnindex)+"%").width(columnwidthpercent+"%");}else{timedevent.width("100%");}
$("#timedevents_day_"+dayindex).append(timedevent);}
function drawMonthViewEventsForDate(date,dayindex,datestring){if(alldayEventData[datestring]&&timedEventData[datestring]){var events=alldayEventData[datestring].concat(timedEventData[datestring]);var eventindex=0;var outInfo={truncated:false};var eventsToDraw=GetEventsToDraw(events,constants.maxeventspermonthday,outInfo);var dayDivs=[];for(var i=0;i<eventsToDraw.length;i++){eventindex=i;var event=eventsToDraw[i];if(!CheckValidEvent(event)){continue;}
dayDivs.push(GetEventDiv(event,"event_"+eventindex));}
if(outInfo.truncated){eventindex=constants.maxeventspermonthday;}
if(eventindex>0){dayDivs.push(GetMoreLink(date,eventindex));}
if(dayDivs.length>0){$("div#day_"+dayindex).append(dayDivs.join(''));}}}
function DrawEventsForDate(date,dayindex){var datestring=GetDateString(date);if(globals.currentView==='month'){drawMonthViewEventsForDate(date,dayindex,datestring);}else{var outInfo={truncated:false};var maxAllDayEventsToDraw=globals.printView?99999:constants.maxalldayeventsperday;var dayEventsToDraw=GetEventsToDraw(alldayEventData[datestring],maxAllDayEventsToDraw,outInfo);for(var dayEventsToDrawIndex=0;dayEventsToDrawIndex<dayEventsToDraw.length;dayEventsToDrawIndex++){DrawDayEventAllDay(dayindex,dayEventsToDraw[dayEventsToDrawIndex]);}
if(outInfo.truncated){GetAllDayMoreLinkRow().children().eq(dayindex).append(GetMoreLink(date));}
$(".alldayrow td:nth-child("+(dayindex+1)+")").toggleClass("today_timedevent_cell",date.valueOf()===new Date().zeroTime().valueOf());var timedEventsToDraw=GetEventsToDraw(timedEventData[datestring]);for(var timedEventsToDrawIndex=0;timedEventsToDrawIndex<timedEventsToDraw.length;timedEventsToDrawIndex++){DrawDayEventTimed(dayindex,timedEventsToDraw[timedEventsToDrawIndex]);}}}
function DrawEvents(){consolelog("Drawing events for "+globals.firstDayRendered+" - "+globals.lastDayRendered);for(var date=new Date(globals.firstDayRendered),i=0;date<=globals.lastDayRendered;date.addDays(1).zeroTime(),i++){DrawEventsForDate(date,i);}
Resize();if($.isFunction(globals.OnDrawEventsComplete)){globals.OnDrawEventsComplete();}}
function DrawFakeData(firstDateThatNeedsData,lastDateThatNeedsData){ClearEvents();for(var date=new Date(firstDateThatNeedsData);date<=lastDateThatNeedsData;date.addDays(1).zeroTime()){timedEventData[GetDateString(date)]=[{id:123,title:"A thing",timed:true,start:new Date(date).addHours(9).addMinutes(30),end:new Date(date).addHours(10).addMinutes(30)}];alldayEventData[GetDateString(date)]=[{id:456,title:"Another thing",timed:false,start:new Date(date)}];consolelog("Added eventData['"+GetDateString(date)+"']");}
alldayEventData["20090504"]=[{id:789,title:"Long thing",timed:false,start:new Date("5/4/2009"),end:new Date("5/5/2009")}];alldayEventData["20090505"]=[{id:111,title:"Multi-day thing",timed:false,start:new Date("5/5/2009"),end:new Date("5/8/2009")}];alldayEventData["20090513"]=[{id:222,title:"Thing with a really, really, really, really, really, really, really, really, really, really, really, really, really long title.",timed:false,start:new Date("5/5/2009")}];DrawEvents();}
function DatesOverlap(date1,date2){consolelog("* Comparing "+date1.id+" ("+date1.start+") to "+date2.id+" ("+date2.start+")");return Math.abs(date1.start.valueOf()-date2.start.valueOf())<(1000*60*60);}
function initializeEventDataArrays(firstDateThatNeedsData,lastDateThatNeedsData){for(var date=new Date(firstDateThatNeedsData);date<=lastDateThatNeedsData;date.addDays(1).zeroTime()){var datestring=GetDateString(date);timedEventData[datestring]=[];alldayEventData[datestring]=[];}}
function processEventData(data,firstDateThatNeedsData,lastDateThatNeedsData){initializeEventDataArrays(firstDateThatNeedsData,lastDateThatNeedsData);var previousdatestring;var overlapstartindex=-1;for(var eachindex=0;eachindex<data.length;eachindex++){var event=data[eachindex];var startdatetime=parseJsonDate(event.start);if(startdatetime){event.start=startdatetime;}
var datestring=GetDateString(event.start);if(alldayEventData[datestring]===undefined){alldayEventData[datestring]=[];}
if(timedEventData[datestring]===undefined){timedEventData[datestring]=[];}
if(event.timed){if(datestring===previousdatestring){var previousindex=eachindex-1;var previousitem=data[previousindex];if(DatesOverlap(event,previousitem)){consolelog("* * * Overlap: "+event.id+"("+event.start+") overlaps "+previousitem.id+"("+previousitem.start+")");if(overlapstartindex===-1){overlapstartindex=previousindex;}
if(!previousitem.columncount){previousitem.columncount=1;}
var columncount=previousitem.columncount+1;consolelog("Setting columncount to "+columncount+" for "+overlapstartindex+" - "+eachindex);for(var i=overlapstartindex;i<=eachindex;i++){data[i].columncount=columncount;data[i].columnindex=i-overlapstartindex;}}else{overlapstartindex=-1;}}else{overlapstartindex=-1;}
previousdatestring=datestring;timedEventData[datestring].push(event);}else{if(event.bold){alldayEventData[datestring].unshift(event);}else{alldayEventData[datestring].push(event);}}}
if(!(lastDateThatNeedsData<globals.firstDayRendered||firstDateThatNeedsData>globals.lastDayRendered)){ClearEvents();DrawEvents();}else{consolelog("Skipping DrawEvents call since the month being loaded is no longer displayed");}}
function LoadEvents(firstDateThatNeedsData,lastDateThatNeedsData){if(!globals.serviceUrl){return;}
var eventsUrl=globals.serviceUrl+'?m=getevents&startyear='+firstDateThatNeedsData.getFullYear()+'&startmonth='+(firstDateThatNeedsData.getMonth()+1)+'&startDay='+firstDateThatNeedsData.getDate()+'&endyear='+lastDateThatNeedsData.getFullYear()+'&endmonth='+(lastDateThatNeedsData.getMonth()+1)+'&endDay='+lastDateThatNeedsData.getDate()+'&consolidated='+globals.consolidated+'&includeclosedcases='+globals.includeClosedCases;consolelog("Calling getJSON against "+eventsUrl);ClearEvents();blockcalendar("#content");$.ajax({type:"GET",url:eventsUrl,data:null,dataType:"json",success:function(data,textStatus){consolelog("Processing json from "+eventsUrl+" with status "+textStatus);processEventData(data,firstDateThatNeedsData,lastDateThatNeedsData);},complete:function(XMLHttpRequest,textStatus){unblock("#content");},actiondescription:"Loading calendar data"});}
function OnDrawCalendarComplete(){consolelog("OnDrawCalendarComplete: "+globals.firstDayRendered+" - "+globals.lastDayRendered+")");var firstDateToCheck,lastDateToCheck;var firstDateThatNeedsData,lastDateThatNeedsData;firstDateToCheck=globals.firstDayRendered;lastDateToCheck=globals.lastDayRendered;for(var date=new Date(firstDateToCheck);date<=lastDateToCheck;date.addDays(1).zeroTime()){if(!timedEventData[GetDateString(date)]){if(!firstDateThatNeedsData){firstDateThatNeedsData=new Date(date);}
lastDateThatNeedsData=new Date(date);}}
var fakeIt=false;if(firstDateThatNeedsData&&lastDateThatNeedsData){consolelog("Need data for "+firstDateThatNeedsData+" - "+lastDateThatNeedsData+", consolidated="+globals.consolidated);consolelog("Need data for "+GetDateString(firstDateThatNeedsData)+" - "+GetDateString(lastDateThatNeedsData));if(fakeIt){DrawFakeData(firstDateThatNeedsData,lastDateThatNeedsData);}
else{LoadEvents(firstDateThatNeedsData,lastDateThatNeedsData,globals.consolidated);}}else{ClearEvents();DrawEvents();unblock("#content");}}
function DrawMonthCalendar(){var firstDayOfMonth=new Date(globals.currentDate);firstDayOfMonth.setDate(1);consolelog("Drawing month calendar for "+globals.currentDate+", starting on "+firstDayOfMonth);var lastDayOfMonth=new Date(firstDayOfMonth);lastDayOfMonth.setDate(lastDayOfMonth.getDaysInMonth());globals.firstDayRendered=new Date(firstDayOfMonth).addDays(-firstDayOfMonth.getDay()).zeroTime();globals.lastDayRendered=new Date(lastDayOfMonth).addDays(6-lastDayOfMonth.getDay()).zeroTime();SetDaysVisible();var today=new Date().zeroTime();for(var date=new Date(globals.firstDayRendered),i=0;date<=globals.lastDayRendered;date.addDays(1).zeroTime(),i++){var dateText=(i===0||date.getDate()===1?date.getMonthName(true)+" ":" ")+date.getDate();$("#day_"+i+"_date_link").text(dateText).unbind().click(function(){var switchToDate=new Date(date);return function(){SwitchView("day",switchToDate);return false;};}());var y=date.getFullYear();var m=date.getMonth()+1;var day=date.getDate();var dateData=m+"/"+day+"/"+y;$("#day_"+i).attr("date",dateData);$("#day_"+i+"_cell").toggleClass("othermonth_day_cell",date.getMonth()!==firstDayOfMonth.getMonth());$("#day_"+i+"_cell").toggleClass("today_day_cell",date.valueOf()===today.valueOf());$("#day_"+i+"_date").toggleClass("today_calendar_day_number",date.valueOf()===today.valueOf());}
var cellsNeeded=firstDayOfMonth.getDay()+firstDayOfMonth.getDaysInMonth();var rowsNeeded=Math.ceil(cellsNeeded/7);for(var j=4;j<=5;j++){if(rowsNeeded>j){$("#week_"+j).show();}
else{$("#week_"+j).hide();}}
OnDrawCalendarComplete();}
function DrawDaysCalendar(){globals.firstDayRendered=new Date(globals.currentDate);if(globals.days===7){globals.firstDayRendered.addDays(-globals.firstDayRendered.getDay()).zeroTime();}else if(globals.days===5){globals.firstDayRendered.addDays(1-globals.firstDayRendered.getDay()).zeroTime();}
globals.lastDayRendered=new Date(globals.firstDayRendered).addDays(globals.days-1).zeroTime();SetDaysVisible();var daysheader=$("#daysheader").empty();var today=new Date().zeroTime();for(var i=0,date=new Date(globals.firstDayRendered);i<globals.days;i++,date.addDays(1).zeroTime()){var dayheader=$("<th />").append($("<div />").addClass("dayheader").toggleClass("today_dayheader",date.valueOf()===today.valueOf()).css("text-align","center").append($("<a/>").attr("href","#").addClass("daylink").text(date.getDayName(true)+", "+date.getMonthName(true)+" "+date.getDate()+(globals.printView?', '+date.getFullYear():'')).click(function(){var switchToDate=new Date(date);return function(){if(globals.currentView!=="day"){SwitchView("day",switchToDate);}return false;};}())));var isWeekend=date.getDay()===0||date.getDay()===6;dayheader.toggleClass("weekend",isWeekend);daysheader.append(dayheader);$("#timedevents_day_"+i).toggleClass("today_timedevents_day",date.valueOf()===today.valueOf());$("#timedevents_day_"+i).parent().toggleClass("weekend",isWeekend);if(globals.showWeekends||!isWeekend||globals.currentView==='day'||globals.currentView==='5day'){dayheader.show();$("#timedevents_day_"+i).parent().show();}else{dayheader.hide();$("#timedevents_day_"+i).parent().hide();}}
for(var j=globals.days;j<constants.maxdays;j++){$("#timedevents_day_"+j).parent().removeClass("weekend").hide();}
OnDrawCalendarComplete();}
function executeDrawCalendar(){ClearMatterReferences();consolelog("Drawing calendar view "+globals.currentView);if(globals.currentView==='month'){$("#daysview_holder").hide();$("#monthview_holder").show();globals.days=null;DrawMonthCalendar();}else{$("#monthview_holder").hide();$("#daysview_holder").show();if(globals.currentView==='day'){globals.days=1;}
else if(globals.currentView==='5day'){globals.days=5;}
else if(globals.currentView==='week'){globals.days=7;}
else{alert('bad globals.currentView: '+globals.currentView);}
DrawDaysCalendar();}
SetTitle();UpdateCurrentMonthYear();$('#calendar_holder').fadeIn("fast");Resize();if(!globals.printView){$("#timeofdaydiv").scrollTop(400);}}
function daysBetween(date1,date2){var DSTAdjust=0;var oneMinute=1000*60;var oneDay=oneMinute*60*24;date1.setHours(0);date1.setMinutes(0);date1.setSeconds(0);date2.setHours(0);date2.setMinutes(0);date2.setSeconds(0);if(date2>date1){DSTAdjust=(date2.getTimezoneOffset()-date1.getTimezoneOffset())*oneMinute;}else{DSTAdjust=(date1.getTimezoneOffset()-date2.getTimezoneOffset())*oneMinute;}
var diff=Math.abs(date2.getTime()-date1.getTime())-DSTAdjust;return Math.ceil(diff/oneDay);}
function updateView(changedDates,cascade,updatedEventDate){ClearCachedData();DrawCalendar();}
function refreshCurrentViewWithNewData(){blockcalendar("#content");ClearCachedData();DrawCalendar();}
function SetupCalendar(){$("#moreEventsDialog").dialog({autoOpen:false,modal:true,width:400,height:500,maxHeight:800,buttons:{"OK":function(){$(this).dialog("close");}}});var monthviewholder=$("<div />").attr("id","monthview_holder");monthviewholder.append(SetupMonthView());var daysviewholder=$("<div />").attr("id","daysview_holder");daysviewholder.append(SetupDaysView());var holder=$("<div />").attr("id","calendar_holder").css("clear","both");holder.append(monthviewholder);holder.append(daysviewholder.hide());var element;if(constants.mainTarget===null){element=$('#'+constants.elementid);constants.mainTarget=element;}else{element=constants.mainTarget;}
element.empty();if(!globals.printView){element.append(SetupNav());}
element.append(holder);if(!globals.printView){element.after(SetupBottomControls());}
if(globals.showWeekends){$("#chkShowWeekends").attr("checked","checked");}
Resize();$(window).wresize(function(){Resize();});SetupAddEventLinks();$("a.eventLink").live("click",function(){var link=$(this);if(link.hasClass("isuserevent")===true){$.userEvent('edit',{transactionDateId:link.attr("eid")});}else{openDateDialog(link.attr("eid"));}
return false;});$("a.moreLink").live("click",function(){var dateText=$(this).attr("date");var date=new Date(dateText);ShowMoreEventsDialog(date);return false;});}
var excludedCount=0;var setExcludeInProgress=false;function setExclusionClientSide(result){if(result.ExclusionId){var node=GetNodeForExclusionId("#exclusionstree",result.ExclusionId);if(node.isSelected()!=result.Exclude){node._select(result.Exclude,false,false);}}}
function setExcludeAjax(data){if(setExcludeInProgress)
{return false;}
setExcludeInProgress=true;transactionInUsePingCount=0;block("#datecalctabs");if(data.exclude)
{excludedCount++;}
$.ajax({type:"POST",url:dateListServiceUrl,data:data,dataType:"json",success:function(result){growlAjaxResult(result,"Toggle Exclusion");if(result.Success){$("#includeDateCount").html(result.IncludedDateCount);$("#excludedDateCount").html(result.ExcludedDateCount);setExclusionClientSide(result);updateView(result.ChangedDates,true,null);}
resendEmail=true;},complete:function(XMLHttpRequest,textStatus){setExcludeInProgress=false;unblock("#datecalctabs");},actiondescription:'Toggling exclusion'});}
function setExclude(transactionDateId,exclude){setExcludeAjax({m:"exclude",transactionDateId:transactionDateId,exclude:exclude});}
function setExclusion(exclusionId,transactionId,exclude){setExcludeAjax({m:"exclusion",exclusionId:exclusionId,transactionId:transactionId,exclude:exclude});}
$(document).ready(function(){$("#chkExcludeFromSync").click(function(){if(toggleSyncInProgress){return;}
$(this).attr("lastsetting",$(this).attr("checked"));var callback=function(){var currentTime=new Date().getTime();toggleSyncInProgress=currentTime;$("#chkExcludeFromSync").attr('disabled',true).addClass('ui-state-disabled');$.ajax({actiondescription:"Your exclude setting change request",url:transactionServiceUrl,type:"POST",dataType:"json",timeout:15000,data:{m:"togglesync",transactionId:transactionid},success:function(result){if(!toggleSyncInProgress){return;}
toggleSyncInProgress=false;$("#chkExcludeFromSync").attr('disabled',false).removeClass('ui-state-disabled');growlAjaxResult(result,"Toggle Outlook&reg; Sync");},error:function(XMLHttpRequest,textStatus,errorThrown){ajaxErrorHandler(this,XMLHttpRequest,textStatus,errorThrown);if(textStatus=='timeout'){if(toggleSyncInProgress!=currentTime)
{return;}
var chkExcludeFromSync=$("#chkExcludeFromSync");chkExcludeFromSync.attr("checked",chkExcludeFromSync.attr("lastsetting"));toggleSyncInProgress=false;chkExcludeFromSync.attr('disabled',false).removeClass('ui-state-disabled');}}});};if(!$(this).attr("checked"))
{syncPriorToLaunchWarning(new Date($(this).attr("date")),callback);}
else
{callback();}});});
var loadedExclusions;var exclusionsReturnedOk;function loadExclusions(params,callback,showExclude,growlMessage,lazyLoad,blockid){if(blockid)
{block(blockid);}
$.ajax({url:dateListServiceUrl,data:params,dataType:"json",complete:function(XMLHttpRequest,textStatus){if(blockid)
{unblock(blockid);}},success:function(data,textStatus){if(data===null||data.length===0){$("#noExclusionsMessage").show();callFunction(callback,null);return;}
$("#noExclusionsMessage").hide();if(loadedExclusions){var tree=$("#exclusionstree").dynatree("getTree");if(tree===null){return;}
tree.options.checkbox=showExclude;var treeRoot=$("#exclusionstree").dynatree("getRoot");treeRoot.removeChildren();treeRoot.append(data);callFunction(callback,data);return;}
loadedExclusions=true;if(growlMessage)
{growl("The event you selected might have scheduled more deadlines than you need. Please review the <a href='#' onclick='showExclusionsTab();'>exclusions list</a> on the Exclusions tab and select any deadlines you wish to exclude from your generated dates.","Exclusion Dates",false,true);}
$("#exclusionstree").dynatree({title:"Exclusions Tree",autoFocus:false,autoCollapse:false,rootVisible:false,persist:false,fx:{height:"toggle",duration:200},checkbox:showExclude,children:data,clickFolderMode:1,onSelect:function(exclude,node){if(!exclusionsReturnedOk){return;}
node._select(!exclude,false,false);if(node.data.exclusionId>0)
{setExclusion(node.data.exclusionId,node.data.transactionId,exclude);}
else if(node.data.TransactionDateId>0)
{setExclude(node.data.TransactionDateId,exclude);}},onActivate:function(node){if(node.data.TransactionDateId===undefined||node.data.TransactionDateId==-1){node.toggleExpand();return false;}
openDateDialog(node.data.TransactionDateId);node.deactivate();setTimeout(function(){$("#exclusionstree").parent().attr({scrollLeft:0});},0);},onLazyRead:function(dtnode){if(!lazyLoad){return;}
params.parent=dtnode.data.TransactionDateId!=-1?dtnode.data.TransactionDateId:dtnode.data.TransactionId;dtnode.appendAjax({url:dateListServiceUrl,data:params,cache:true});nodesCache=[];}});exclusionsReturnedOk=true;callFunction(callback,data);}});}
(function($){var alertType={Warning:0,Error:1};var target;var options;var defaults={alert:null,hideLinkes:false,allowClose:true,showInstructions:false,slide:true};function getAlertTypeText(){switch(options.alert.MessageType){case alertType.Warning:return" Warning:";case alertType.Error:return" Error:";default:return" Error:";}}
function toggleUpdateCreditCardExpiration(globalAlertDiv){var link=$("#updateCreditCardExpiration",globalAlertDiv);var editMembershipLink=$("#editMembershipCreditCard",globalAlertDiv);var updateSpan=$("#updateCreditCardExpirationContainer",globalAlertDiv);if(link.is(":visible")){if(updateSpan.length===0){link.after('<div style="display:none;" id="updateCreditCardExpirationContainer"><span id="updateCardType" /> card ending in <span id="updateLastFour" /> expiration <select id="newExpMonth"><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option><option>11</option><option>12</option></select>/<select id="newExpYear"></select> <button type="button" class="ui-state-error ui-corner-all" id="btnUpdateCreditCardExpiration">Save</button><button type="button" class="ui-state-error ui-corner-all" id="btnCancelUpdateCreditCardExpiration">Cancel</button></div>');updateSpan=$("#updateCreditCardExpirationContainer",globalAlertDiv);var years=[];var currentYear=new Date().getFullYear();for(var year=currentYear;year<currentYear+20;year++){years.push('<option>'+year+'</option>');}
$("#newExpYear",updateSpan).append(years.join(''));$("#btnUpdateCreditCardExpiration",updateSpan).unbind('click').click(function(){var expirationMonth=$("#newExpMonth",updateSpan).val();var expirationYear=$("#newExpYear",updateSpan).val();if(expirationMonth==options.alert.ExpirationMonth&&expirationYear==options.alert.ExpirationYear){toggleUpdateCreditCardExpiration(globalAlertDiv);return;}
var newExprationDate=new Date.parse(expirationMonth+"/1/"+expirationYear);var currentDate=new Date();if(newExprationDate<=currentDate){growlError("Invalid expiration date.","Update Credit Card Expiration");return;}
block(globalAlertDiv);$.ajax({url:servicePath+'ManageCreditCardsService.aspx',dataType:"json",data:{m:'updateExpiration',card:options.alert.CustomerCreditCardID,expmonth:expirationMonth,expyear:expirationYear,getnextalert:true},cache:false,complete:function(){unblock(globalAlertDiv);},success:function(data){if(data){growlAjaxResult(data,"Update Credit Card Expiration");if(data.Success){globalAlertDiv.slideUp("slow");if(data.Alert){options=globalAlertDiv.data("alert");options.alert=data.Alert;target=globalAlertDiv;initialize();}}}}});});$("#btnCancelUpdateCreditCardExpiration",updateSpan).unbind('click').click(function(){toggleUpdateCreditCardExpiration(globalAlertDiv);});}
$("#updateCardType",updateSpan).html(options.alert.CardType);$("#updateLastFour",updateSpan).html(options.alert.LastFour);$("#newExpMonth",updateSpan).val(options.alert.ExpirationMonth);$("#newExpYear",updateSpan).val(options.alert.ExpirationYear);editMembershipLink.hide();link.hide();updateSpan.show();}else{editMembershipLink.show();updateSpan.hide();link.show();}}
function initialize(){if(!options.alert){return;}
if(target.length===0){$("#container").before('<div id="globalAlert" class="globalAlert"><div class="alertIcon icon"/><a href="#" class="alertClose" title="dismiss this notification">X</a><div class="alertHeader">'+options.alert.Header+getAlertTypeText()+'</div><div class="alertMessage"></div></div>');target=$("#globalAlert");target.data("alert",options);}
else{$(".alertHeader",target).html(options.alert.Header+getAlertTypeText());}
var message=options.alert.Message;if(options.showInstructions&&options.alert.Instructions){message+=" "+options.alert.Instructions;}
var links=$(".alertMessage",target).html(message).children("a");if(options.hideLinks){links.hide();}else{links.css("padding-left","20px").addClass("globalAlertText");}
var alertClose=$(".alertClose",target);if(!options.allowClose||!options.alert.CanDismiss){alertClose.hide();}else{alertClose.show().unbind('click').click(function(){$(".globalAlert").slideUp("slow",function(){$.ajax({cache:false,dataType:"json",url:servicePath+'globalalertservice.aspx',data:{m:"hidealert",t:options.alert.Type,getnextalert:true},success:function(data){if(data&&data.Alert){options.alert=data.Alert;initialize();}}});});return false;});}
var icon=$(".alertIcon",target);if(options.alert.BlinkIcon){for(var i=0;i<50;i++){icon.fadeOut(100).fadeIn(100);}}
$("#updateCreditCardExpiration",target).unbind('click').click(function(){toggleUpdateCreditCardExpiration($(this).parent().parent());return false;});$("#editMembershipCreditCard",target).unbind('click').click(function(){document.location=basePath+'subscription/manage.aspx?uc=1';return false;});if(options.slide){target.slideDown("slow");}else{target.show();}}
$.globalAlert=function(action,new_options){target=$("#globalAlert");if(action!='instance'){if(typeof(action)=='object'){new_options=action;action='default';}
if(options){}
if(new_options!==undefined&&new_options!==null&&typeof(new_options)=='object'){options=$.extend({},defaults,options,new_options);}}
if(action==='default'){initialize();}
return this;};$.fn.messageAlert=function(action,new_options){target=$(this);var dataOptions=target.data("alert");if(dataOptions!==undefined&&dataOptions!==null)
{options=dataOptions;}
if(action!='instance'){if(typeof(action)=='object'){new_options=action;action='default';}
if(options){}
if(new_options!==undefined&&new_options!==null&&typeof(new_options)=='object'){options=$.extend({},defaults,options,new_options);}}
if(action==='default'){initialize();}
return this;};})(jQuery);
function addChangeLogLinks(specificId){$("#gChanges"+specificId).show();}
function hideChangeLogLinks(specificId){$("#gChanges"+specificId).hide();}
function updateOffCalendar(date,row){var firstColumn=row.eq(0);var parent=firstColumn.parent().parent();if((parent.hasClass("offCalendar")&&date.OffCalendar)||(!parent.hasClass("offCalendar")&&!date.OffCalendar)){return;}
if(date.OffCalendar){parent.addClass("offCalendar");firstColumn.prepend('<span class="ui-icon offcalendar-icon ui-icon-cancel" title="This event is &quot;Off Calendar&quot; and will not show up on the calendar or be synced to Outlook." style="float: right;"/>');}else{parent.removeClass("offCalendar");$(".offcalendar-icon",firstColumn).remove();}}
function updateGridRow(data){var row=$("#dateList #row"+data.TransactionDate.TransactionDateId+" div");if(row.length===0){return;}
var newHtml=data.TransactionDate.DescriptionWithNotes;if(data.TransactionDate.IsUserEvent)
{row.eq(3).html('<span class="isuserevent">'+newHtml.replace(/\n/g,'<br/>')+'</span>');}
else
{row.eq(3).html(newHtml.replace(/\n/g,'<br/>'));}
var dateColumn=row.eq(2).children().eq(0);var dueColumn=row.eq(1);var excludeSpan=row.eq(0).children().eq(0);if(data.TransactionDate.Excluded){dateColumn.html("[Excluded]");dateColumn.addClass("excluded");excludeSpan.addClass("ui-dynatree-selected");dueColumn.html("");}
else{var date=eval(data.TransactionDate.StartDateTimeOffset.DateTimeOffset.toString().replace(/\\\/(Date\([0-9\-]+\))\\\//gi,'new $1'));dateColumn.html(dateFormat(date,"m/d/yyyy")+" "+data.TransactionDate.TimeDisplay);dateColumn.removeClass("excluded");excludeSpan.removeClass("ui-dynatree-selected");dueColumn.html(data.TransactionDate.DueDisplay);}
$(".locked",dateColumn).removeClass("locked");dateColumn.removeClass("locked");if(data.TransactionDate.Locked){dateColumn.addClass("locked");}
addChangeLogLinks(data.TransactionDate.TransactionDateId);updateOffCalendar(data.TransactionDate,row);}
function redrawTree(id){var treediv=$(id);if(treediv.length>0){var tree=treediv.dynatree("getTree");if(tree!==undefined&&tree!==null){tree.redraw();}}}
function UpdateGridAndTree(data,cascade,skipredraw){updateGridRow(data);if(typeof(EachNodeForTransactionDateId)=="function"){EachNodeForTransactionDateId("#datetree",data.TransactionDate.TransactionDateId,function(treeNode){if(treeNode!==null&&treeNode.data!==null){treeNode.data.title=data.TreeNode.title;treeNode.data.tooltip=data.TreeNode.tooltip;treeNode.data.addClass=data.TreeNode.addClass;treeNode._select(data.TransactionDate.Excluded,false,false);if(!skipredraw)
{redrawTree("#datetree");}}});EachNodeForTransactionDateId("#exclusionstree",data.TransactionDate.TransactionDateId,function(exclusionnode){if(exclusionnode!==null&&exclusionnode.data!==null){exclusionnode.data.title=data.TreeNode.title;exclusionnode.data.tooltip=data.TreeNode.tooltip;exclusionnode.data.addClass=data.TreeNode.addClass;exclusionnode._select(data.TransactionDate.Excluded,false,false);if(!skipredraw)
{redrawTree("#exclusionstree");}}});}
if(data.NoChanges)
{hideChangeLogLinks(data.TransactionDate.TransactionDateId);}
else
{addChangeLogLinks(data.TransactionDate.TransactionDateId);}
if(typeof(reloadAgenda)=="function")
{reloadAgenda();}}
function updateAgendaItem(data){var item=$("#agenda"+data.TransactionDate.TransactionDateId);$(".description",item).html(data.TransactionDate.DescriptionWithNotesHTML);$(".authority",item).html(data.TransactionDate.Authority);if(data.TransactionDate.IsTimed){$(".time",item).text(data.TransactionDate.TimeDisplay);$(".time",item).show();}
else{$(".time",item).hide();$(".time",item).html("");}
$(".description",item).html(data.TransactionDate.DescriptionWithNotesHTML);}
var supportAdminMessage="To edit this text, create a new HelpText in ExpressionEngine with the following title: ";var hideTheHelp=false;function toggleHideableBox(container,show){if(show){$(container.containerDiv).slideDown("fast");}else{$(container.containerDiv).effect('transfer',{to:'#showHelpLink'},500,function(){$("#showHelpLink").effect('highlight',1000);});$(container.containerDiv).slideUp("fast");}
$.ajax({type:"GET",dataType:"json",url:container.usersService,data:'m=ToggleHelpBoxDisplay&contentTitle='+container.contentTitle+'&isOpen='+show});}
function loadMessageByPage(hideableBoxData){$.ajax({type:"GET",dataType:'json',url:hideableBoxData.url,success:function(data){$(hideableBoxData.messageSpan).html(data.helptext);if(data.display_title!==null&&data.display_title!==""){$("#showHelpLink").html(data.display_title);$(".closeHideableBoxLink",$(hideableBoxData.containerDiv)).html("close "+data.display_title);}
if(hideableBoxData.loadPageHelpText&&hideableBoxData.showEditUrl){$(hideableBoxData.messageSpan).append("<p>Help content url: <a href=\""+hideableBoxData.url+"\">"+hideableBoxData.url+"</a> (<a href=\""+hideableBoxData.editUrl+"\">edit</a>)</p>");$(hideableBoxData.containerDiv).show();}
if($(hideableBoxData.messageSpan).html().length===0)
{return;}
$("#showHelpLinkContainer").show();var show=false;if(hideableBoxData.showUserSet)
{show=hideableBoxData.show;}
else
{show=data.default_visible||data.showEditUrl;}
if(!show)
{$("#showHelpLink").effect('highlight',{},1000);}
if(show)
{$(hideableBoxData.containerDiv).fadeIn("slow");}
$("#showHelpLink").toggle(function(){toggleHideableBox(hideableBoxData,!show);},function(){toggleHideableBox(hideableBoxData,show);});},error:function(XMLHttpRequest,textStatus,errorThrown){if(hideableBoxData.loadPageHelpText&&hideableBoxData.showPageBoxManually){$(hideableBoxData.messageSpan).html(supportAdminMessage+hideableBoxData.url);$(hideableBoxData.containerDiv).show("slow");}}});}
function loadMessageBox(data){if(data===null){growl("hideableBoxData is null");}
if(data.loadPageHelpText){loadMessageByPage(data);}else{if(data.show||data.showEditUrl){$(data.messageSpan).load(data.url,function(){if($(data.messageSpan).html().length>0)
{$(data.containerDiv).fadeIn("slow");}});}}}
function openHideableBox(hideableBoxData){$("#showHelpLink").click();}
function closeHideableBox(hideableBoxData){$("#showHelpLink").click();}
var dontGrowlErrorsForUrls=[];function block(id){if($(".blockUI",$(id)).length===0){$(id).block({message:'<img src="'+large_loader_path+'" />',css:{padding:0,margin:'auto auto',width:'100%',xtop:'40%',xleft:'25%',textAlign:'center',color:'#000',border:'none',backgroundColor:'Transparent',cursor:'wait'},overlayCSS:{backgroundColor:'#000',opacity:'0.2'}});}
return true;}
function unblock(id){$(id).unblock();}
var growlAnimateInProgress=false;function growlAfterOpen(element,message,options){if(growlAnimateInProgress)
{return;}
growlAnimateInProgress=true;$(element).animate({top:'-='+40+'px'},175).animate({top:'+='+40+'px'},120).animate({top:'-='+20+'px'},175).animate({top:'+='+20+'px'},120).animate({top:'-='+10+'px'},175).animate({top:'+='+10+'px'},120).animate({top:'-='+5+'px'},175).animate({top:'+='+5+'px'},120,null,function(){growlAnimateInProgress=false;});}
function growl(message,header,theme,sticky,timeout,growlId){if(timeout===null)
{timeout=10000;}
if(theme)
{$.jGrowl(message,{theme:theme,header:header,sticky:sticky,life:timeout,afterOpen:growlAfterOpen,growlId:growlId});}
else
{$.jGrowl(message,{header:header,sticky:sticky,life:timeout,afterOpen:growlAfterOpen,growlId:growlId});}}
function growlError(message,header,growlId){growl(message,header,"ui-state-error",true,undefined,growlId);}
function growlClose(growlId){$("div#"+growlId).trigger("jGrowl.close").remove();}
function growlAjaxResult(result,header){if(result===null){return false;}
if(result.Success){if(result.Message)
{growl(result.Message,header);}
else
{growl("Request successful.",header);}
return true;}
if(header===null||header==="")
{header="Error";}
if(result.Message)
{growlError(result.Message,header);}
else
{growlError("An unknown error occured.",header);}
return false;}
function growlCloseAll(){var jqueryCloseDiv=$(".jGrowl-notification").children("div.close");if(jqueryCloseDiv.length===0)
{return false;}
if(jqueryCloseDiv.length==1)
{jqueryCloseDiv.click();}
else
{$(".jGrowl-closer").click();}}
function growlAjaxError(this_AjaxRequest,XMLHttpRequest,textStatus,errorThrown){var description='A request to the server';if(this_AjaxRequest.actiondescription){description=this_AjaxRequest.actiondescription;}
var error=description+' failed due to an unknown error.';if(textStatus=='timeout'){error=description+' timed out.';}
if(textStatus=='notmodified'){error=description+' failed with the error "Response was not modified".';}
if(textStatus=='parsererror'){error=description+' failed due to a parser error.';}
if(textStatus=='error'){error=description+' failed with error '+XMLHttpRequest.status+'.';}
error+='<br /><br />Please try again later.';growlError(error,"Ajax Error @ "+new Date().toUTCString());if(window.console){console.log("ajax error: "+error);}}
function logAjaxError(ajaxRequest,XMLHttpRequest,textStatus,errorThrown){var errorData={textStatus:textStatus,errorThrown:errorThrown,errorUrl:ajaxRequest.url};if(XMLHttpRequest){try{errorData.xhrstatus=XMLHttpRequest.status;errorData.xhrstatusText=XMLHttpRequest.statusText;errorData.xhrtext=XMLHttpRequest.responseText;if(XMLHttpRequest.responseXML){errorData.xhrxml=XMLHttpRequest.responseXML.xml;errorData.xhrurl=XMLHttpRequest.responseXML.url;}}catch(ex){if(window.console){console.log("Exception gathering XMLHttpRequest error information: "+ex);}}}
$.ajax({cache:false,data:errorData,error:function(XMLHttpRequest,textStatus,errorThrown){if(window.console){console.log("Error logging error! "+textStatus);}},global:false,type:"POST",url:servicePath+"ajaxerror.aspx"});}
function ajaxErrorHandler(this_AjaxRequest,XMLHttpRequest,textStatus,errorThrown){var loggedOut=false;try{if(XMLHttpRequest&&XMLHttpRequest.status==403){loggedOut=true;}}catch(ex){}
if(!loggedOut&&(dontGrowlErrorsForUrls[this_AjaxRequest.url]===undefined||dontGrowlErrorsForUrls[this_AjaxRequest.url]===false)){growlAjaxError(this_AjaxRequest,XMLHttpRequest,textStatus,errorThrown);}
logAjaxError(this_AjaxRequest,XMLHttpRequest,textStatus,errorThrown);if(loggedOut){window.location='/Deadlines/Login.aspx?r='+encodeURIComponent(window.location.href);}}
function checkForEnter(event){if(event.keyCode==13){return false;}}
var isSafariNotChrome=$.browser.safari&&!/chrome/.test(navigator.userAgent.toLowerCase());var jsondateregex=/^\\?\/Date\(([0-9]{13})(-([0-9]{4}))?\)\\?\/$/;function parseJsonDate(date){if(date===null){return false;}
var dateString;if(date.DateTimeOffset)
{dateString=date.DateTimeOffset;}
else
{dateString=date;}
var match=dateString.match(jsondateregex);if(match){return new Date(parseInt(match[1],10));}}
function isWeekend(date){var day=date.getDay();if(day===0||day==6)
{return[true,'ui-state-disabled','Weekend'];}
return[true,''];}
function formatDateTextToDate(element){if(element===null||element===""){return false;}
try{var separator;if($(element).val().indexOf("/")>0)
{separator="/";}
else if($(element).val().indexOf("-")>0)
{separator="-";}
var date=$.datepicker.parseDate("mm"+separator+"dd"+separator+"yy",$(element).val());return date;}catch(e){return null;}}
function callFunction(funct,data){if(funct!==undefined&&$.isFunction(funct)){if(data===undefined)
{funct();}
else
{funct(data);}}}
function formatDateFromText(element){if(element===null||element===""){return false;}
var dayInt;var yearInt;var dateRetVal;var months=["january","february","march","april","may","june","july","august","september","october","november","december"];try{var text=$(element).val();var month=text.substring(0,text.indexOf(" ")).toLowerCase();var year=text.substring(text.lastIndexOf(" ")+1);var day=text.substring(text.indexOf(" ")+1);day=day.substring(0,day.indexOf(text.indexOf(",")==-1?" ":","));if(isNaN(parseInt(day,10))||isNaN(parseInt(year,10))||$.inArray(month,months)==-1)
{return false;}
if(year.length==2)
{year="20"+year;}
dateRetVal=new Date(year,$.inArray(month,months),day);}catch(e){return false;}
return dateRetVal;}
function replaceAll(text,strA,strB){return text.replace(new RegExp(strA,"g"),strB);}
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return"Not Yet Supported";},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(this.getTimezoneOffset()<0?'-':'+')+(this.getTimezoneOffset()/60<10?'0':'')+(this.getTimezoneOffset()/60)+'00';},T:function(){return"Not Yet Supported";},Z:function(){return this.getTimezoneOffset()*60;},c:function(){return"Not Yet Supported";},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};function DetectTimeZone(callback){var url=servicePath+'TimezoneService.aspx';var thisYear=new Date().getFullYear();var january1ms=new Date(thisYear,0,1,0,0,0,0).getTime();var march31ms=new Date(thisYear,2,31,0,0,0,0).getTime();var june1ms=new Date(thisYear,5,1,0,0,0,0).getTime();var data={m:"detect",january1ms:january1ms,march31ms:march31ms,june1ms:june1ms};$.ajax({type:"GET",url:url,data:data,dataType:"json",success:callback,error:function(XMLHttpRequest,textStatus,errorThrown){logAjaxError(this,XMLHttpRequest,textStatus,errorThrown);}});}
function formatCurrency(num){num=num.toString().replace(/\$|\,/g,'');var CurrencySymbol="$";if(isNaN(num))
{num="0";}
sign=(num==(num=Math.abs(num)));num=Math.floor(num*100+0.50000000001);cents=num%100;num=Math.floor(num/100).toString();if(cents<10)
{cents="0"+cents;}
for(var i=0;i<Math.floor((num.length-(1+i))/3);i++)
{num=num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));}
return(((sign)?'':'-')+CurrencySymbol+num+'.'+cents);}
Array.prototype.contains=function(obj){var i=this.length;while(i--){if(this[i]===obj){return true;}}
return false;};function setWatermark(element,defaultText){$(element).addClass("watermarkOn");$(element).attr("value",defaultText);$(element).emptyonclick();}
function destroyWatermark(element){$(element).removeClass("watermarkOn");}
$(document).ready(function(){$.jGrowl.defaults.position='center-right';$.jGrowl.defaults.closeTemplate="close";$('.ui-state-default').hover(function(){$(this).addClass('ui-state-hover');},function(){$(this).removeClass('ui-state-hover');});$.ajaxSetup({error:function(XMLHttpRequest,textStatus,errorThrown){ajaxErrorHandler(this,XMLHttpRequest,textStatus,errorThrown);}});});function getUrlParameterValue(jParam){if(jParam===undefined||jParam.length<1)
{return null;}
jParam=jParam+"=";if(window.location.search.substr(window.location.search.indexOf(jParam),jParam.length)==jParam){var startFromIndex=window.location.search.indexOf(jParam)+jParam.length;var endIndex=window.location.search.substring(startFromIndex).indexOf("&");if(endIndex==-1)
{return decodeURI(window.location.search.substr(startFromIndex));}
return decodeURI(window.location.search.substr(startFromIndex,endIndex));}
return null;}
function decodeURI(decodedTxt){var tempTxt=decodedTxt.replace(/\+/g,' ');return decodeURIComponent(tempTxt);}
var jseId="";var initFinished=false;var selectedJurisdiction=null;var lastJseSearch=null;function getJseSearchText(){if($("#jse_txt_search").is('.watermarkOn'))
{return'';}
return $.trim($("#jse_txt_search").val());}
function jsesearch(){var search=getJseSearchText();if(search==lastJseSearch){return;}
var tree=$("#jsetree").dynatree("getTree");var searchNode=tree.getNodeByKey("search");searchNode.removeChildren();if(search.length===0){$(searchNode.span).hide();lastJseSearch=null;return;}
searchNode.data.title="Search Results ('"+search+"')";searchNode.append({title:"Loading..."});searchNode.expand();searchNode.render();if(search.length>0)
{$(searchNode.span).show();}
$.ajax({url:jseServiceUrl,dataType:"json",data:{m:"tree",s:search},cache:true,success:function(data){lastJseSearch=search;searchNode.removeChildren();searchNode.append(data);}});}
function jurisdictionSelected(jurisdictionId,ajaxSuccess,ajaxError){$.ajax({type:"GET",url:jseServiceUrl,data:{m:"selected",jurisdictionId:jurisdictionId},dataType:"json",success:function(data){selectedJurisdiction=data.Jurisdiction;if(!data.Success){selectedJurisdiction=null;growlAjaxResult(data);return;}
$("#jsetree").dynatree("enable");$(".jselink").removeClass("disabledlink");$("#jseselectedloading").hide();callFunction(ajaxSuccess,data);},complete:function(XMLHttpRequest,textStatus){if(textStatus=="error"||textStatus=="timeout"){$("#jsetree").dynatree("enable");$(".jselink").removeClass("disabledlink");$("#jseselectedloading").hide();growl("Your jurisdiction selection request timed out.","Error","ui-state-error",true);callFunction(ajaxError);return false;}}});}
function loadJurisdictionTree(jseWatermarkText,beforeJurisdictionSelected,jurisdictionSelectedSuccess,jurisdictionSelectedError){if($("#jsetree").length===0){growlError("Page is missing an element, #jsetree","Page Error");return false;}
if(!initFinished){growlError("Jurisdiction tree did not load completely.","Page Error");return false;}
var jseIdFromUrl=getUrlParameterValue("j");if(jseIdFromUrl!==null)
{jseId=jseIdFromUrl;}
if(jseWatermarkText!==undefined&&jseWatermarkText!==""){$("#jse_txt_search").typeWatch({callback:jsesearch,highlight:true,wait:600,enterkey:true,captureLength:1,ignoreText:jseWatermarkText});}
$("#jsetree").dynatree({title:"Jurisdiction Selection",autoFocus:false,autoCollapse:true,rootVisible:true,persist:true,fx:{height:"toggle",duration:200},initAjax:{url:jseServiceUrl,data:{m:"tree",j:jseId},cache:true},onActivate:function(dtnode){if(dtnode.data.rulesets){$("#jsetree").dynatree("disable");$(".jselink").addClass("disabledlink");callFunction(beforeJurisdictionSelected);jurisdictionSelected(dtnode.data.jurisdictionId,jurisdictionSelectedSuccess,jurisdictionSelectedError);dtnode.deactivate();}
setTimeout(function(){$("#jsetree").parent().attr({scrollLeft:0});},0);},onLazyRead:function(dtnode){dtnode.appendAjax({url:jseServiceUrl,data:{m:"tree",p:dtnode.data.key,s:getJseSearchText()},cache:true});}});if(jseId){callFunction(beforeJurisdictionSelected);jurisdictionSelected(jseId,jurisdictionSelectedSuccess,jurisdictionSelectedError);}}
function initializeJurisdictionTree(jseWatermarkText,beforeJurisdictionSelected,jurisdictionSelectedSuccess,jurisdictionSelectedError){if(selectedJurisdiction!==null){if($("#jsetreecontainer").length===0){growlError("Page is missing an element, #jsetreecontainer","Page Error");return false;}
$("#jsetreecontainer").scrollTo($("#ui-dynatree-id-"+selectedJurisdiction.JurisdictionId),0,{offset:-100});}
if($.browser.mozilla)
{$("#jse_txt_search").keypress(checkForEnter);}
else
{$("#jse_txt_search").keydown(checkForEnter);}
setWatermark("#jse_txt_search",jseWatermarkText);initFinished=true;loadJurisdictionTree(jseWatermarkText,beforeJurisdictionSelected,jurisdictionSelectedSuccess,jurisdictionSelectedError);}
function loginLoading(action){if(action)
{block("#logincontrol");}
else
{unblock("#logincontrol");}}
function disableControls(){$(".loginControl").attr("disabled","disabled");}
function enableControls(){$(".loginControl").removeAttr("disabled");}
$(document).ready(function(){$("#userInfo").hide();$("#loginForm").hide();$("#btnUserLogin").hide();$("#imgLoading").hide();$("#btnUserLogin").click(function(){$("#loginForm").show();$("#txtEmail").focus();$("#btnUserLogin").hide();$("#loginlinks").hide();return false;});$("#txtPassword").keydown(function(event){if(event.keyCode==13){$("#btnSubmit").click();return false;}});$("#btnSubmit").click(function(){growlCloseAll();$(".hideOnLogin").hide();disableControls();loginLoading(true);var search=location.search;search=search.replace(/\?/,'');if(search!==null&&search!=='')
{search="&"+search;}
$.ajax({type:"POST",url:loginUserUrl,data:"email="+encodeURIComponent($("#txtEmail").val())+"&password="+encodeURIComponent($("#txtPassword").val())+"&rememberme="+$("#chkRememberMe").is(":checked")+search,dataType:"json",reenableUI:true,success:function(loginData){this.reenableUI=false;if(loginData.Success){document.cookie='PrevAuth=Yes; path=/';if(loginData.RedirectUrl!==null&&loginData.RedirectUrl.length>0)
{window.location=loginData.RedirectUrl;}
else
{window.location.reload();}}else{if(window.loginFailedUrl){window.location=window.loginFailedUrl+'?loginfailed='+escape($("#txtEmail").val());}else{growlAjaxResult(loginData);$("#lostpasswordlink").attr('href','');$("#lostpasswordlink").click(function(){loginLoading(true);growlCloseAll();disableControls();$.ajax({url:userServiceUrl,dataType:'json',data:{m:'sendlostpassword',email:$("#txtEmail").val()},success:function(json){growlCloseAll();growlAjaxResult(json,"Send Forgotten Password");},complete:function(XMLHttpRequest,textStatus){loginLoading(false);enableControls();}});return false;});this.reenableUI=true;}}},complete:function(XMLHttpRequest,textStatus){if(this.reenableUI){loginLoading(false);enableControls();}}});return false;});});
(function($){var target;var options;var hidden=true;var defaults={membershipJoinInfo:null,isAdmin:false,creditCardDialogReturnedCallback:null,userSelectionChanged:null,useButtons:false};function UserSelectionObject(yes,no,creditCardId){this.Yes=yes;this.No=no;this.CreditCardId=creditCardId;}
function display(){if(!options.membershipJoinInfo){target.hide();if(!options.useButtons){$("#membershipJoinYes",target).attr("checked",false);$("#membershipJoinNo",target).attr("checked",false);}
hidden=true;return;}
hidden=false;var membershipJoinInfo=options.membershipJoinInfo;$(".membershipJoinText",target).html(membershipJoinInfo.Text+" ");$(".membershipJoinCost",target).html(membershipJoinInfo.Cost+" ");$(".membershipJoinPercentage",target).html(membershipJoinInfo.DiscountPercentage);$(".membershipJoinSavings",target).html(membershipJoinInfo.Savings+" ");$(".membershipJoinSavingsPercent",target).html(membershipJoinInfo.SavingsDiscountPercentage+" ");$(".membershipJoinMonthlyCredit",target).html(membershipJoinInfo.MonthlyCredit+" ");$(".membershipJoinOriginalFee",target).html(membershipJoinInfo.TransactionOriginalFee+" ");$(".membershipJoinFee",target).html(membershipJoinInfo.TransactionFee+" ");$(".membershipNoThankYouDays",target).html(membershipJoinInfo.NoThankYouDays+" ");$("#membershipPaymentMethod",target).html("");$("#membershipPaymentMethod",target).creditCardSelect({creditCards:membershipJoinInfo.CreditCards,isAdmin:options.isAdmin,customOptions:null,creditCardDialogReturnedCallback:options.creditCardDialogReturnedCallback,markDefaultCard:false});$("#membershipJoinYes",target).click(function(){var userSelection="";if(!$.isFunction(options.userSelectionChanged)){return;}
var creditCardId=$("#membershipPaymentMethod",target).creditCardSelect().selectedOption().val();if(options.useButtons)
userSelection=new UserSelectionObject(true,false,creditCardId);else
userSelection=new UserSelectionObject($(this).attr("checked"),$("#membershipJoinNo",target).attr("checked"),creditCardId);options.userSelectionChanged(userSelection);});$("#membershipJoinNo",target).click(function(){var userSelection="";if(!$.isFunction(options.userSelectionChanged)){return;}
var creditCardId=$("#membershipPaymentMethod",target).creditCardSelect().selectedOption().val();if(options.useButtons)
userSelection=new UserSelectionObject(false,true,creditCardId);else
userSelection=new UserSelectionObject($("#membershipJoinYes",target).attr("checked"),$(this).attr("checked"),creditCardId);options.userSelectionChanged(userSelection);});target.show();}
$.fn.membershipJoinInfo=function(action,new_options){if(action!='instance'){if(typeof(action)=='object'){new_options=action;action='default';}
if(options){}
if(new_options!==undefined&&new_options!==null&&typeof(new_options)=='object'){options=$.extend({},defaults,options,new_options);}
target=$(this);}
this.isVisible=function(){return!hidden;};this.UserSelections=function(){if(hidden){return new UserSelectionObject(false,false,null);}
else{var creditCardId=$("#membershipPaymentMethod",target).creditCardSelect().selectedOption().val();if(options.useButtons)
return new UserSelectionObject(false,false,null);return new UserSelectionObject($("#membershipJoinYes",target).attr("checked"),$("#membershipJoinNo",target).attr("checked"),creditCardId);}};switch(action){case'default':display();break;case'UserSelections':return this.UserSelections();}
return this;};})(jQuery);
var sendNotesInProgress=false;var noteHasChanged=false;var reloadedNoteDialogData=null;function getNotesDialogCode(callback){if($("#notesDialogContainer").data("isLoaded")===undefined||!$("#notesDialogContainer").data("isLoaded")){$.ajax({type:"GET",url:ajaxIncludePath+"notedialog.aspx",dataType:"html",success:function(data,status){$("#notesDialogContainer").html(data);$("#notesDialogContainer").data("isLoaded",true);callFunction(callback);return false;}});}else{callFunction(callback);}}
function loadNotesDialogWithId(transactionDateId,returnedCallback){$.getJSON(transactionDateServiceUrl,{m:"GetTransactionDate",TransactionDateId:transactionDateId,TransactionId:transactionid},function(data){callFunction(returnedCallback,data);});}
function displayNotesDialogData(data,transactionDateId){var notesDialog=$("#notesDialog");var addToChildren=$(".addToChildren",notesDialog);var chkAddToChildren=$("#chkAddToChildren",addToChildren);chkAddToChildren.attr("checked",false);if(data===undefined){return false;}
if(data.ChildTransactionDateCount>0)
{addToChildren.show();}
else
{addToChildren.hide();}
var before=''+data.NoteBeforeDescription;var after=''+data.NoteAfterDescription;$("#description",notesDialog).html(data.Description);var txtNoteBefore=$("#txtNoteBefore",notesDialog);var txtNoteAfter=$("#txtNoteAfter",notesDialog);txtNoteBefore.val("");txtNoteAfter.val("");if(before!==null&&before.length>0&&before!='null')
{txtNoteBefore.val(before);}
if(after!==null&&after.length>0&&after!='null')
{txtNoteAfter.val(after);}
txtNoteBefore.blur();txtNoteAfter.blur();notesDialog.dialog("destroy").dialog({buttons:{"Cancel":function(){$(this).dialog("close");},"OK":function(){var before=txtNoteBefore.val();if(before==txtNoteBefore.attr("watermark")){before='';}
var after=txtNoteAfter.val();if(after==txtNoteAfter.attr("watermark")){after='';}
var addToChildren=chkAddToChildren.attr("checked")===true;if(before!=data.NoteBeforeDescription||after!=data.NoteAfterDescription||addToChildren){var currentTime=new Date().getTime();sendNotesInProgress=currentTime;$("#notesDialog").dialog("disable");$.ajax({actiondescription:"Your note editing request",type:"POST",url:transactionDateServiceUrl,timeout:30000,data:{m:"SaveTransactionDateNotes",TransactionDateId:transactionDateId,NoteBeforeDescription:before,NoteAfterDescription:after,addToChildren:addToChildren},dataType:"json",success:function(data){if(!sendNotesInProgress){return;}
$.each(data.ChangedTransactionDates,function(i,item){UpdateGridAndTree(item,false,true);updateDescriptionWithNotes(item.TransactionDate.DescriptionWithNotes);});redrawTree("#datetree");redrawTree("#exclusionstree");sendNotesInProgress=false;growlAjaxResult(data.Result,"Save User Note");$("#notesDialog").dialog("enable");$("#notesDialog").dialog("close");try{if(isNewCalc){resendEmail=true;}}catch(Error){}
loadNotesDialogWithId(transactionDateId,function(data){reloadedNoteDialogData=data;});noteHasChanged=true;toggleViewChangeLogButtonEnabled(true);},error:function(XMLHttpRequest,textStatus,errorThrown){ajaxErrorHandler(this,XMLHttpRequest,textStatus,errorThrown);if(textStatus=='timeout'){if(sendNotesInProgress!=currentTime){return;}
sendNotesInProgress=false;$("#notesDialog").dialog("enable");}}});}
else{$(this).dialog("close");}}},modal:true,autoResize:true,width:480,draggable:true,overlay:{opacity:0.5,background:"black"}});}
function openNotesDialog(data,transactionDateId){if(transactionDateId===undefined||transactionDateId===null){growlError("Unable to load notes dialog","Notes");return false;}
if(data===undefined||data===null)
{getNotesDialogCode(function(){loadNotesDialogWithId(transactionDateId,function(data){displayNotesDialogData(data,transactionDateId);});});}
else{getNotesDialogCode(function(){if(reloadedNoteDialogData===null)
{displayNotesDialogData(data,transactionDateId);}
else
{displayNotesDialogData(reloadedNoteDialogData,transactionDateId);}});}}
function clearNotesData(){noteHasChanged=false;reloadedNoteDialogData=null;}
(function($){var DATA_NAME="offCalendar-options";var target;var options;var defaults={blockTarget:"#content",transactionDate:null};var confirmDialog=null;var dateUpdatedCallbacks=[];function toggleOffCalendar(checked,relatedDates){block(options.blockTarget);$.ajax({cache:false,type:"POST",url:servicePath+'TransactionDateService.aspx',data:{m:"toggleOffCalendar",TransactionDateId:options.transactionDate.TransactionDateId,related:relatedDates},dataType:"json",success:function(data){growlAjaxResult(data,"Toggle Off Calendar");if(!data.Success){return;}
options.transactionDate.OffCalendar=!options.transactionDate.OffCalendar;for(var i=0;i<dateUpdatedCallbacks.length;i++){var callback=dateUpdatedCallbacks[i].callback;callback(data.ChangedDates);}},complete:function(XMLHttpRequest,textStatus){unblock(options.blockTarget);}});}
function confirmChildren(checked){if(!confirmDialog){target.after('<div id="confirmOffCalendarChildrenDialog" class="ui-helper-hidden" title="Related Deadlines"></div>');confirmDialog=$("#confirmOffCalendarChildrenDialog",target.parent());}
if(checked){confirmDialog.html('This deadline has related deadlines.<div>Click &quot;Yes&quot; if you would like to take the related deadlines off calendar as well.</div>');}else{confirmDialog.html('This deadline has related deadlines.<div>Click &quot;Yes&quot; if you would like any related deadlines that are &quot;Off Calendar&quot; put back on the calendar as well.</div>');}
var setChecked=function(){if(checked){target.attr("checked","checked");}else{target.removeAttr("checked");}};confirmDialog.dialog("destroy").dialog({title:"Related Deadlines",zIndex:3999,buttons:{"No":function(){$(this).dialog("close");toggleOffCalendar(checked,false);setChecked();},"Yes":function(){$(this).dialog("close");toggleOffCalendar(checked,true);setChecked();}},modal:true,closeOnEscape:true,autoResize:true,width:470,height:100,draggable:true,resizable:true,overlay:{opacity:0.5,background:"black"}});}
function initialize(){target.unbind("click").click(function(){var checked=$(this).attr("checked");if(options.transactionDate.ChildTransactionDateCount>0){confirmChildren(checked);return true;}
toggleOffCalendar(checked,null);});initializeCmsDialogs();}
$.onOffCalendarChanged=function(id,callback){if(callback===undefined){callback=id;id=undefined;}
if(id){for(var i=0;i<dateUpdatedCallbacks.length;i++){if(dateUpdatedCallbacks[i].id===id){return;}}}
dateUpdatedCallbacks.push({id:id,callback:callback});};$.fn.offCalendar=function(new_options){target=$(this);var dataOptions=target.data(DATA_NAME);if(dataOptions!==undefined&&dataOptions!==null)
{options=dataOptions;}
else{options=null;}
var instance=true;if(new_options!==undefined&&new_options!==null&&typeof(new_options)=='object'){options=$.extend({},defaults,options,new_options);target.data(DATA_NAME,options);instance=false;}
if(!instance){initialize();}
return this;};})(jQuery);
(function($){var initialized=false;var target;var options;var paymentMethodSelect;var paymentMethod={FreeCalculation:0,AccountCredit:1,AccountCreditAndCreditCard:2,CreditCard:3,Coupon:4,None:5,SubscriptionFreeCalculation:6,SubscriptionCredit:7,SubscriptionCreditAndAccountCredit:8,SubscriptionCreditAndAccountCreditAndCreditCard:9,SubscriptionCreditAndCreditCard:10};var defaults={selectedEvent:null,calculationPaymentInfo:null,isDateChange:false,lockedDates:0,childCount:0,paymentMethodChangedCallback:null,isAdmin:false};function processCouponChange(coupon){$.ajax({cache:false,url:servicePath+"couponservice.aspx",data:{coupon:coupon.val()},dataType:"json",complete:function(XMLHttpRequest,textStatus){},success:function(data,textStatus){if(!data.Success){return;}
coupon.data("coupon",data);if(!data.IsValid){$("#couponValidation",target).html('<span style="font-weight:normal;color:red;">'+data.Description+'</span>');}else{$("#couponValidation",target).html("");}
var paymentOptions=getPaymentOptions(options.calculationPaymentInfo);var paymentMethodDiv=$("#paymentMethod",target).creditCardSelect({customOptions:createCustomOptions(paymentOptions),replaceWithText:(paymentOptions.options.length==1&&paymentOptions.options[0].method===paymentMethod.None)?"None":null});paymentMethodSelected(paymentMethodSelect);}});}
$.fn.paymentSummary=function(action,new_options){if(action!='instance'){if(typeof(action)=='object'){new_options=action;action='display';}
if(options){options.calculationPaymentInfo=null;options.selectedEvent=null;}
if(new_options!==undefined&&new_options!==null&&typeof(new_options)=='object'){options=$.extend({},defaults,options,new_options);}
if(options.calculationPaymentInfo===null&&options.selectedEvent===null)
{return this;}
options.calculationPaymentInfo=options.selectedEvent!==null?options.selectedEvent.CalculationPaymentInfo:options.calculationPaymentInfo;target=$(this);}
this.paymentMethods=function(){return paymentMethod;};this.selectedPaymentMethod=function(){var paymentMethodElement=$("#paymentMethod",target);if(paymentMethodElement.is(':hidden')||paymentMethodElement.parents(':hidden').length>0){return paymentMethod.None;}
var method=$("option:selected",paymentMethodElement).data("PaymentMethod");if(method===undefined){method=paymentMethod.CreditCard;}
return method;};this.selectedCreditCardId=function(){var selectedOption=$("#paymentMethod option:selected",target);if(selectedOption.data("PaymentMethod")!==undefined)
{return null;}
return selectedOption.val();};this.updateFees=function(lockedDates){options.lockedDates=lockedDates;var info=options.calculationPaymentInfo;var paymentMethodDiv=$("#paymentMethod",target).creditCardSelect({customOptions:createCustomOptions(getPaymentOptions(info)),replaceWithText:null});paymentMethodSelected(paymentMethodSelect);var fee=info.TransactionFees.Fee;if(options.isDateChange){fee=getUpdatedFee();}
var method=this.selectedPaymentMethod();var noPayment=$("#noPayment",target);if(fee<=0&&(options.isDateChange||method!==paymentMethod.FreeCalculation&&method!==paymentMethod.SubscriptionFreeCalculation)){paymentMethodDiv.hide();if(noPayment.length===0){paymentMethodDiv.parent().append('<span id="noPayment">None</span>');}else{noPayment.show();}}else{if(noPayment.length!==0){noPayment.hide();}
paymentMethodDiv.show();}};this.getCoupon=function(){if(!$("#couponRow",target).is(":visible")){return null;}
var coupon=$("#coupon",target).data("coupon");if(!coupon){return null;}
return coupon;};switch(action){case'display':initializeDisplay();break;case'updateFees':this.updateFees(options.lockedDates);break;}
if(!initialized){var coupon=$("#coupon",target);if(coupon.length>0){coupon.blur(function(){var value=coupon.val();var data=coupon.data("coupon");if(!value||value.length===0){coupon.data("coupon",null);$("#couponAmount",target).html("");$("#couponValidation",target).html("");var paymentMethodDiv=$("#paymentMethod",target).creditCardSelect({customOptions:createCustomOptions(getPaymentOptions(options.calculationPaymentInfo)),replaceWithText:null});paymentMethodSelected(paymentMethodSelect);return;}
if(data){if(value===data.Text){return;}}
processCouponChange(coupon);});}}
initialized=true;return this;};function checkCouponForTemporaryMembership(){var coupon=$("#coupon",target);var couponData=coupon.data("coupon");if(!couponData){return;}
if(!couponData.MembersOnlyInvalid){return;}
var info=options.calculationPaymentInfo;var hasSubscriptionData=(info.SubscriptionCreditAmount>0||info.SubscriptionFreeCalcs>0);if(couponData.IsValid&&!hasSubscriptionData){couponData.IsValid=false;coupon.data("coupon",couponData);$("#couponValidation",target).html('<span style="font-weight:normal;color:red;">'+couponData.Description+'</span>');return;}
else if(!couponData.IsValid&&hasSubscriptionData){couponData.IsValid=true;coupon.data("coupon",couponData);$("#couponValidation",target).html("");}}
function initializeDisplay(){checkCouponForTemporaryMembership();var info=options.calculationPaymentInfo;var transactionFees=info.TransactionFees;var paymentMethodDiv=$("#paymentMethod",target);if(transactionFees.BillingMatrix){$("#numberOfDatesText",target).html(transactionFees.BillingMatrix.SummaryText);}
$("#researchLevelText",target).html(info.ResearchLevelText);$("#researchFee",target).html(toCurrency(transactionFees.OriginalFee));if(defaults.selectedEvent!==null)
{$("#selectedesetext",target).html(defaults.selectedEvent.FormulaDescription);}
if(transactionFees.DiscountPercentage===undefined||transactionFees.DiscountPercentage===null||transactionFees.DiscountPercentage.length===0||transactionFees.DiscountPercentage===0){$(".membershipDiscountCell",target).hide();$("#membershipDiscount",target).hide();}else{$(".membershipDiscountCell",target).show();$("#membershipDiscount",target).show();var membershipDiscountTarget=$("#membershipDiscount",target);membershipDiscountTarget.html(Math.abs(transactionFees.DiscountPercentage)+"%");}
var paymentOptions=getPaymentOptions(info);var selectDefaultCard=paymentOptions===null||paymentOptions.options===null||paymentOptions.options.length===0;var paymentDropDown=paymentMethodDiv.creditCardSelect({creditCards:info.CreditCards,textBeforeSelect:null,textBeforeCreditCardNumber:"Credit Card ending with: ",markDefaultCard:!selectDefaultCard,selectDefault:selectDefaultCard,customOptions:createCustomOptions(paymentOptions),isAdmin:options.isAdmin,dropdownCreatedCallback:function(dropdown){dropdown.change(function(){paymentMethodSelected($(this));});},creditCardDialogReturnedCallback:function(card){var info=options.calculationPaymentInfo;if(info.CreditCards===null||info.CreditCards.length===0){var cards=[];cards.push(card);info.CreditCards=cards;}else{var isDuplicateCard=false;for(var i=0;i<info.CreditCards.length;i++){var existingCard=info.CreditCards[i];if(existingCard==null||card==null)continue;if(card.CustomerCreditCardId==existingCard.CustomerCreditCardId)
isDuplicateCard=true;}
if(!isDuplicateCard)
info.CreditCards.push(card);}
var paymentOptions=getPaymentOptions(options.calculationPaymentInfo);var paymentMethodDiv=$("#paymentMethod",target).creditCardSelect({customOptions:createCustomOptions(paymentOptions),replaceWithText:(paymentOptions.options.length==1&&paymentOptions.options[0].method===paymentMethod.None)?"None":null});paymentMethodSelected(paymentMethodSelect);},replaceWithText:null});paymentMethodSelect=paymentDropDown.getSelectList();if(paymentMethodSelect!==null){paymentMethodSelect.change(function(){paymentMethodSelected($(this));});}
paymentMethodSelected(paymentMethodSelect);}
function createCustomOptions(paymentOptions){var customOptions=[];if(paymentOptions===null||paymentOptions.length===0)
{return customOptions;}
$.each(paymentOptions.options,function(i,option){var selectOption=$(document.createElement("option")).attr("value","PaymentMethod-"+option.method).append(option.text);if(customOptions.length===0)
{selectOption.attr("selected","selected");}
selectOption.data("PaymentMethod",option.method);customOptions.push(selectOption);});return customOptions;}
function getUpdatedFee(){if(!options.isDateChange){return options.calculationPaymentInfo.TransactionFees.OriginalFee;}
if(!initialized){return options.calculationPaymentInfo.TransactionFees.Fee;}
var relatedDates=options.childCount-options.lockedDates;if(relatedDates<0)
{relatedDates=0;}
return options.calculationPaymentInfo.TransactionFees.UnitFee*relatedDates;}
function getPaymentOptions(info){var retVal=[];var requiresCreditCard=false;checkCouponForTemporaryMembership();var transactionFees=info.TransactionFees;var creditAmount=info.CreditAmount;var subscriptionCreditAmount=info.SubscriptionCreditAmount;var fee=info.TransactionFees.Fee;if(options.isDateChange){fee=getUpdatedFee();}
fee=applyCoupon(fee);if(fee===0){retVal.push({method:paymentMethod.None,text:"None"});return{options:retVal,requiresCreditCard:false};}
var hasCreditCards=info.CreditCards&&info.CreditCards.length>0;var subscriptionFreeCalculation=(info.SubscriptionFreeCalcs>0);var freeCalculation=(info.FreeCalcs>0);var subscriptionCredit=(info.SubscriptionCreditAmount>0&&info.SubscriptionCreditAmount>=fee);var subscriptionCreditAndAccountCredit=(info.SubscriptionCreditAmount>0&&(info.SubscriptionCreditAmount+info.CreditAmount)>=fee);var accountCredit=(info.CreditAmount>0&&info.CreditAmount>=fee);var subscriptionCreditAndAccountCreditAndCreditCard=(hasCreditCards&&info.SubscriptionCreditAmount>0&&info.CreditAmount>0);var subscriptionCreditAndCreditCard=(hasCreditCards&&info.SubscriptionCreditAmount>0);var accountCreditAndCreditCard=(hasCreditCards&&info.CreditAmount>0);var defaultCard="[default] credit card";var hasDefaultCard=false;if(hasCreditCards){for(var i=0;i<info.CreditCards.length;i++){if(info.CreditCards[i].IsDefault){hasDefaultCard=true;defaultCard="credit card ending with "+info.CreditCards[i].CardNumberLastFour+" ("+info.CreditCards[i].Type+")";break;}}
if(!hasDefaultCard){growl("You do not currently have a default credit card. Please go to <a href='"+basePath+"Accounts/ManageCreditCards.aspx'>My Credit Cards</a> to select a default card.","Warning",null,true);}}
if(subscriptionFreeCalculation){retVal.push({method:paymentMethod.SubscriptionFreeCalculation,text:"Membership Free Monthly Calculation ("+info.SubscriptionFreeCalcs+" available)"});}
if(subscriptionCredit){retVal.push({method:paymentMethod.SubscriptionCredit,text:"Membership Credit ("+toCurrency(subscriptionCreditAmount)+" available)"});}
if(freeCalculation){retVal.push({method:paymentMethod.FreeCalculation,text:"Free Calculation ("+info.FreeCalcs+" available)"});}
if(!subscriptionCredit&&subscriptionCreditAndAccountCredit){retVal.push({method:paymentMethod.SubscriptionCreditAndAccountCredit,text:"Membership Credit ("+toCurrency(subscriptionCreditAmount)+" available) and Account Credit ("+toCurrency(creditAmount)+" available)"});}
if(accountCredit){retVal.push({method:paymentMethod.AccountCredit,text:"Account Credit ("+toCurrency(creditAmount)+" available)"});}
else if(!subscriptionCredit&&!subscriptionCreditAndAccountCredit){if(subscriptionCreditAndAccountCreditAndCreditCard){retVal.push({method:paymentMethod.SubscriptionCreditAndAccountCreditAndCreditCard,text:"Membership Credit ("+toCurrency(subscriptionCreditAmount)+" available) and Account Credit ("+toCurrency(creditAmount)+" available) and the "+defaultCard});requiresCreditCard=true;}
else if(subscriptionCreditAndCreditCard){retVal.push({method:paymentMethod.SubscriptionCreditAndCreditCard,text:"Membership Credit ("+toCurrency(subscriptionCreditAmount)+" available) and the "+defaultCard});requiresCreditCard=true;}
else if(accountCreditAndCreditCard){retVal.push({method:paymentMethod.AccountCreditAndCreditCard,text:"Account Credit ("+toCurrency(creditAmount)+" available) and the "+defaultCard});requiresCreditCard=true;}}
return{options:retVal,requiresCreditCard:requiresCreditCard};}
function toCurrency(value){if(value){return"$"+value.toFixed(2);}else{return"$0.00";}}
function applyCoupon(fee){var coupon=$("#coupon",target);if(coupon.length===0){return fee;}
var couponData=(coupon.length>0)?coupon.data("coupon"):null;if(!couponData||!couponData.IsValid){return fee;}
if(couponData.DiscountPercentage&&couponData.DiscountPercentage>0){return fee-(fee*couponData.DiscountPercentage/100);}else if(couponData.CreditAmuont){return(fee<couponData.CreditAmuont)?0:fee-couponData.CreditAmuont;}else{return fee;}}
function paymentMethodSelected(paymentMethodSelect){var method=$(":selected",paymentMethodSelect).data("PaymentMethod");if(method===undefined){method=paymentMethod.CreditCard;}
var info=options.calculationPaymentInfo;var transactionFees=info.TransactionFees;var fee=getUpdatedFee();var creditAmount=info.CreditAmount;var subscriptionCreditAmount=info.SubscriptionCreditAmount;var cost=fee;var unitFee=info.TransactionFees.UnitFee;var showConfirm=true;var paymentMethodDiv=$("#paymentMethod",target);var creditTarget=$("#credit",target);var subTotalTarget=$("#subTotal",target);var totalDueTarget=$("#totalDue",target);var subTotalRow=$("#subTotalRow",target);var creditRow=$("#creditRow",target);var paymentRow=$("#paymentRow",target);var couponRow=$("#couponRow",target);var coupon=$("#coupon",target);var couponData=(coupon.length>0)?coupon.data("coupon"):null;var couponValidation=$("#couponValidation",target);var couponAmount=$("#couponAmount",target);var validCoupon=couponData&&couponData.IsValid;var appliedCoupon=false;var feeRemaining,remaining,totalDue;var couponDiscount=0;subTotalRow.hide();if(transactionFees.DiscountPercentage===undefined||transactionFees.DiscountPercentage===null||transactionFees.DiscountPercentage.length===0||transactionFees.DiscountPercentage===0){subTotalRow.hide();}else if(!options.isDateChange){fee=fee+fee*transactionFees.DiscountPercentage/100;subTotalRow.show();}
if(couponRow.length>0){couponRow.show();}
if(paymentRow.length>0){paymentRow.show();}
if(validCoupon&&(method!==paymentMethod.FreeCalculation&&method!==paymentMethod.SubscriptionFreeCalculation)){subTotalRow.show();var newFee=applyCoupon(fee);if(newFee!==fee){couponDiscount=fee-newFee;appliedCoupon=true;fee=newFee;}}
subTotalTarget.html(toCurrency(fee));switch(method){case paymentMethod.FreeCalculation:subTotalRow.show();creditRow.show();creditTarget.html("1 free calculation (applied)");remaining=info.FreeCalcs-1;totalDueTarget.html("$0.00 ("+remaining+" free calculations remaining)");cost=0;showConfirm=false;break;case paymentMethod.AccountCredit:subTotalRow.show();creditRow.show();creditTarget.html(toCurrency(fee)+" (applied)");remaining=info.CreditAmount-fee;totalDueTarget.html("$0.00 ("+toCurrency(remaining)+" credit remaining)");cost=0;showConfirm=false;break;case paymentMethod.AccountCreditAndCreditCard:subTotalRow.show();creditRow.show();if(fee>info.CreditAmount){creditTarget.html(toCurrency(info.CreditAmount)+" (applied)");totalDue=fee-info.CreditAmount;totalDueTarget.html(toCurrency(totalDue)+" ($0.00 credit remaining)");cost=totalDue;}else{creditTarget.html(toCurrency(fee)+" (applied)");remaining=info.CreditAmount-fee;totalDueTarget.html("$0.00 ("+toCurrency(remaining)+" credit remaining)");cost=0;showConfirm=false;}
break;case paymentMethod.CreditCard:creditRow.hide();totalDueTarget.html(toCurrency(fee));break;case paymentMethod.Coupon:break;case paymentMethod.None:break;case paymentMethod.SubscriptionFreeCalculation:subTotalRow.show();creditRow.show();creditTarget.html("1 free membership calculation (applied)");remaining=info.SubscriptionFreeCalcs-1;totalDueTarget.html("$0.00 ("+remaining+" free membership calculations remaining)");cost=0;showConfirm=false;break;case paymentMethod.SubscriptionCredit:subTotalRow.show();creditRow.show();creditTarget.html(toCurrency(fee)+" (applied)");remaining=info.SubscriptionCreditAmount-fee;totalDueTarget.html("$0.00 ("+toCurrency(remaining)+" membership credit remaining)");cost=0;showConfirm=false;break;case paymentMethod.SubscriptionCreditAndAccountCredit:subTotalRow.show();creditRow.show();creditTarget.html(toCurrency(fee)+" (applied)");feeRemaining=fee-info.SubscriptionCreditAmount;remaining=info.CreditAmount-feeRemaining;totalDueTarget.html("$0.00 ($0.00 membership credit remaining), ("+toCurrency(remaining)+" credit remaining)");cost=0;showConfirm=false;break;case paymentMethod.SubscriptionCreditAndAccountCreditAndCreditCard:subTotalRow.show();creditRow.show();creditTarget.html(toCurrency(fee)+" (applied)");feeRemaining=fee-info.SubscriptionCreditAmount;if(feeRemaining>info.CreditAmount){creditTarget.html(toCurrency(info.CreditAmount+info.SubscriptionCreditAmount)+" (applied)");totalDue=feeRemaining-info.CreditAmount;totalDueTarget.html(toCurrency(totalDue)+" ($0.00 membership credit remaining), ($0.00 credit remaining)");cost=totalDue;}else{creditTarget.html(toCurrency(feeRemaining+info.SubscriptionCreditAmount)+" (applied)");remaining=info.CreditAmount-feeRemaining;totalDueTarget.html("$0.00 ($0.00 membership credit remaining), ("+toCurrency(remaining)+" credit remaining)");cost=0;showConfirm=false;}
break;case paymentMethod.SubscriptionCreditAndCreditCard:subTotalRow.show();creditRow.show();if(fee>info.SubscriptionCreditAmount){creditTarget.html(toCurrency(info.SubscriptionCreditAmount)+" (applied)");totalDue=fee-info.SubscriptionCreditAmount;totalDueTarget.html(toCurrency(totalDue)+" ($0.00 membership credit remaining)");cost=totalDue;}else{creditTarget.html(toCurrency(fee)+" (applied)");remaining=info.SubscriptionCreditAmount-fee;totalDueTarget.html("$0.00 ("+toCurrency(remaining)+" membership credit remaining)");cost=0;showConfirm=false;}
break;}
couponAmount.html("");if(validCoupon){couponValidation.html("");if(appliedCoupon){if(couponData.DiscountPercentage){couponAmount.html("-"+toCurrency(couponDiscount)+" ("+couponData.DiscountPercentage+'% discount applied) ');}else{couponAmount.html("-"+toCurrency(couponData.CreditAmuont)+' credit applied) ');}}else{couponAmount.html("");couponValidation.html("This coupon is valid, however it is not needed for this transaction.");}}
if(showConfirm){$("#confirmChangeFee",target).html(toCurrency(cost));}else{$("#confirmChangeFee",target).html("$0.00");}
if(options.isDateChange){var relatedDates=options.childCount-options.lockedDates;if(relatedDates<0)
{relatedDates=0;}
$("#perDateFee",target).html(toCurrency(relatedDates===0?0:unitFee));var relatedTarget=$("#relatedDateCount",target);if(relatedTarget.length>0)
{relatedTarget.html(relatedDates);}
var skippedTarget=$("#skippedDateCount",target);if(skippedTarget.length>0)
{skippedTarget.html(options.lockedDates);}
if(relatedDates===0){creditRow.hide();if(paymentRow.length>0){paymentRow.addClass("ui-helper-hidden");}
subTotalRow.hide();totalDueTarget.html("$0.00");}}
if($.isFunction(options.paymentMethodChangedCallback))
{options.paymentMethodChangedCallback();}}})(jQuery);
function updateDontShowSingleItemImportWarningAfterDialog(){dontShowSingleItemImportWarningConfirmed=$("#dialog #dontShowSingleItemImportWarning").attr("checked");if(dontShowSingleItemImportWarningConfirmed)
{$.post(settingsService,{m:"ConfirmedDontShowSingleItemImportWarning"});}}
function syncPriorToLaunchWarning(date,callback){var syncLaunch=new Date(syncLaunchDate);var transactionDate=new Date(date);if(dontShowSingleItemImportWarningConfirmed||(transactionDate>syncLaunch)){callback();return;}
openDialog('Warning','This transaction was generated prior to the addition of the Outlook Sync feature.  If you have loaded these deadlines into Outlook using the iCal file attached to the date list e-mail, then, to avoid getting duplicate deadline dates on your Outlook calendar, you will need to manually remove these deadlines from Outlook before you do your next sync.<br /><br /><input name="dontShowSingleItemImportWarning" id="dontShowSingleItemImportWarning" type="checkbox" /><label for="dontShowSingleItemImportWarning">Don\'t show this message again</label>','Are you sure you would like to start including these deadlines in your next sync?',400,255,function(){updateDontShowSingleItemImportWarningAfterDialog();callback();},function(){updateDontShowSingleItemImportWarningAfterDialog();});}
var transactionInUsePingCount=0;var transactionKeepInUse=false;function pingTransactionInUse(){if(transactionInUsePingCount>60){location.href=thankYouUrl+'?j='+escape(jurisdictionId);return;}
transactionInUsePingCount++;$.ajax({type:"POST",url:transactionServiceUrl,data:{m:"transactioninuse",transactionid:transactionid},dataType:"json",success:function(result){if(result.Success)
{setTimeout(pingTransactionInUse,30000);}
else
{growlAjaxResult(result,"Marking Transaction In Use");}}});}
$(document).ready(function(){if(transactionKeepInUse)
{setTimeout(pingTransactionInUse,30000);}});
(function($){var options;var container=null;var dialog=null;var confirmDeleteDialog=null;var initialized=false;var showCaseReferencesComboDone=false;var internalServicePath=servicePath;var defaults={timeWatermark:"(optional)",containerTargetName:"userEventDialogContainer",confirmDeleteTargetName:"userEventConfirmDelete",createCallback:null,editCallback:null,deleteCallback:null,caseReference:null,transactionDateId:null,userEvent:null,date:null};function internalBlock(target){block(target);}
function internalUnblock(target){unblock(target);}
function internalDateFormat(date,format){return dateFormat(date,format);}
function internalGrowl(message,header){growl(message,header);}
function internalGrowlAjaxResult(result,header){growlAjaxResult(result,header);}
function clearCurrentEventOptions(){options.caseReference=null;options.transactionDateId=null;options.userEvent=null;options.date=null;}
function initialize(finishedLoadingCallback){container=$("#"+options.containerTargetName);var fireLoadCallback=function(){if(finishedLoadingCallback!==undefined&&$.isFunction(finishedLoadingCallback))
{finishedLoadingCallback();}};if(initialized){fireLoadCallback();return;}
$.ajax({type:"GET",url:ajaxIncludePath+"addusereventdialog.aspx",dataType:"html",success:function(data,status){if(!initialized){initialized=true;container.html(data);initializeCmsDialogs();}
fireLoadCallback();}});}
function bindData(){if(dialog===null){dialog=$("#userEventDialog",container);}
var datePickerDefaultDate=null;var isEditing=(options.userEvent!==undefined&&options.userEvent!==null);var hasDefaultDate=(options.date!==undefined&&options.date!==null);if(!isEditing)
{datePickerDefaultDate=hasDefaultDate?options.date:internalDateFormat(new Date(),"shortDate");}
else
{datePickerDefaultDate=internalDateFormat(parseJsonDate(options.userEvent.EventDate),"shortDate");}
var txtTime=$("#eventtime",dialog);var txtWhat=$("#what",dialog);var txtEventDate=$("#eventdate",dialog);var chkOffCalendar=$("#offCalendar",dialog);var datePicker=$("#eventdatepickerdiv").datepicker('destroy').datepicker({beforeShowDay:isWeekend,onSelect:function(date){if(date=="Invalid Date")
{return false;}
var day=new Date(date);var now=new Date();var hideCal=false;if(day.getDay()===0||day.getDay()==6){internalGrowl("The event date you have selected is a weekend day.","Warning");}
else if(day.getMonth()+"-"+day.getDate()+"-"+day.getFullYear()==now.getMonth()+"-"+now.getDate()+"-"+now.getFullYear()){internalGrowl("The event date you have selected is today.","Warning");}
else if(day.getTime()<now.getTime()){internalGrowl("The event date you have selected has already passed.","Warning");}
txtEventDate.val(internalDateFormat(day,"shortDate"));return true;},changeMonth:true,changeYear:true,duration:'',numberOfMonths:1,minDate:new Date(1988,0,1),defaultDate:$.datepicker.parseDate("m/d/y",datePickerDefaultDate)});if(!isEditing){if(hasDefaultDate)
{txtEventDate.val(datePickerDefaultDate);}
else
{txtEventDate.val("");}
txtTime.val("");txtWhat.val("");}
else{txtTime.val(options.userEvent.EventTime);txtEventDate.val(datePickerDefaultDate);txtWhat.val(options.userEvent.What);chkOffCalendar.attr("checked",options.userEvent.OffCalendar?"checked":false);}
if(txtTime.val().length<=0)
{setWatermark("#eventtime",options.timeWatermark);}
$.getJSON(internalServicePath+'CalculationService.aspx',{m:"recentcases"},function(references){if(references===null){return;}
var select=$("#caseReference",dialog);var adding=(select.length===0);if(adding)
{select=$(document.createElement("select")).attr("id","caseReference");}
else
{select.empty();}
var selectOption=null;$.each(references,function(i,val){if(val===null){return;}
var option=$(document.createElement("option")).append(val);if(val==options.caseReference)
{selectOption=option;}
select.append(option);});var sexyCaseReference=null;if(adding){$("#recentReferenceContainer",dialog).append(select);if(!showCaseReferencesComboDone){select.sexyCombo({width:552,name:"sexyCaseReference",maxLength:200,blankImageSrc:scriptsPath+'plugin/sexycombo/s.gif'});sexyCaseReference=$("#sexyCaseReference",dialog);sexyCaseReference.attr("isSexyCombo","true");sexyCaseReference.attr("inlineContainer",".combo");sexyCaseReference.attr("name","New Case Reference");sexyCaseReference.addClass("required-field");showCaseReferencesComboDone=true;sexyCaseReference.focus();}}
if(sexyCaseReference===null)
{sexyCaseReference=$("#sexyCaseReference",dialog);}
sexyCaseReference.val(options.caseReference);});}
function checkCaseReference(caseReference,saveEvent){$.ajax({url:internalServicePath+'cases.aspx',dataType:"json",data:{m:"getcaseinfo",c:caseReference},cache:false,success:function(data){if(data.Open){saveEvent();return;}
var closedCaseName=$("#closedCaseName");if(closedCaseName.length===0)
{internalGrowl("Missing Closed Case Dialog","Warning");}
closedCaseName.html(caseReference);$("#closedCaseDialog").dialog("destroy").dialog({buttons:{"Cancel and Change Case Reference":function(){internalUnblock("#content,.ui-dialog");$(this).dialog("close");},"Reopen and Continue":function(){$.ajax({url:internalServicePath+'cases.aspx',dataType:"json",data:{m:"setopen",c:caseReference,o:true},cache:false});$(this).dialog("close");saveEvent();}},modal:true,width:400,height:100,draggable:true});}});}
function fireCallback(callback,data){if(callback!==undefined&&callback!==null&&$.isFunction(callback))
{callback(data);}}
function showEventDialog(title,caseReference,buttons,open){dialog.dialog("destroy").dialog({title:title,buttons:buttons,width:750,height:300,zIndex:3999,modal:true,closeOnEscape:true,autoResize:false,draggable:true,resizable:true,overlay:{opacity:0.5,background:"black"},open:function(event,ui){if(open!==undefined&&$.isFunction(open))
{open();}
dialog.css("overflow","hidden");}});}
function showEditEventDialog(){internalUnblock("#content,.ui-dialog");bindData();var saveFunction=function(){growlCloseAll();var newCaseReference=$("#sexyCaseReference",dialog).val();if(newCaseReference===undefined||newCaseReference===null||$.trim(newCaseReference).length===0){growlError("Case reference is required.","Edit User Event");return;}
var txtTime=$("#eventtime",dialog);var time=txtTime.val()==options.timeWatermark?"":txtTime.val();var what=$("#what",dialog).val();if(what===null||$.trim(what).length===0){growlError("Description is required.","Edit User Event");return;}
var offCalendar=$("#offCalendar",dialog).attr("checked");internalBlock("#content,.ui-dialog");var saveEvent=function(){$.post(internalServicePath+'usereventwebservice.aspx',{m:"saveevent",transactionDateId:options.userEvent.TransactionDateId,date:$("#eventdate",dialog).val(),time:time,what:what,casereference:newCaseReference,offCalendar:offCalendar},function(data){internalGrowlAjaxResult(data,"Edit User Event");internalUnblock("#content,.ui-dialog");if(data.Success===true){dialog.dialog("close");fireCallback(options.editCallback,data.Date);clearCurrentEventOptions();}},"json");};if(newCaseReference==options.caseReference)
{saveEvent();}
else
{checkCaseReference(newCaseReference,saveEvent);}};var confirmDeleteFunction=function(){if(confirmDeleteDialog===null)
{confirmDeleteDialog=$("#"+options.confirmDeleteTargetName,container);}
confirmDeleteDialog.dialog("destroy").dialog({title:"Delete User Event",zIndex:3999,buttons:{"Yes":function(){confirmDeleteDialog.dialog("close");internalBlock("#content,.ui-dialog");$.post(internalServicePath+'usereventwebservice.aspx',{m:"deleteevent",transactionDateId:options.userEvent.TransactionDateId},function(data){internalGrowlAjaxResult(data,"Delete User Event");internalUnblock("#content,.ui-dialog");if(data.Success===true){dialog.dialog("close");fireCallback(options.deleteCallback);clearCurrentEventOptions();}},"json");},"No":function(){confirmDeleteDialog.dialog("close");}},modal:true,autoResize:false,height:100,width:350,minHeight:50,draggable:true,resizable:false,overlay:{opacity:0.5,background:"black"}});};var openFunction=function(){if($.browser.msie&&$.browser.version.substr(0,1)<7){bindData();}
if(!options.userEvent.HasChanges){var value="disabled";var button=dialog.parent().find(".ui-dialog-buttonpane").children("button:contains('View Change Log')");if(button===null||button.length===0){return;}
if(value==button.attr("disabled")){return;}
if(value=="disabled"){button.css("cursor","pointer");button.addClass("ui-state-disabled");}else{button.removeClass("ui-state-disabled");}
button.attr("disabled",value);}};showEventDialog("Edit User Event",options.userEvent.CaseReference,{"Cancel":function(){$(this).dialog("close");clearCurrentEventOptions();},"Save":saveFunction,"Delete":confirmDeleteFunction,"View Change Log":function(){openChangeLogDialog(options.userEvent.TransactionDateId);}},openFunction);}
function getUserEventData(){$.ajax({type:"POST",url:internalServicePath+'usereventwebservice.aspx',data:{m:"getuserevent",TransactionDateId:options.transactionDateId},dataType:"json",success:function(data){if(data!==null){options.caseReference=data.CaseReference;options.userEvent=data;showEditEventDialog();}else{internalUnblock("#content,.ui-dialog");growlError("Unable to find the user event","Get Transaction Date Information");}}});}
function showNewEventDialog(){internalUnblock("#content,.ui-dialog");bindData();var saveFunction=function(){growlCloseAll();var newCaseReference=$("#sexyCaseReference",dialog).val();if(newCaseReference===undefined||newCaseReference===null||$.trim(newCaseReference).length===0)
{newCaseReference=options.caseReference;}
if(newCaseReference===undefined||newCaseReference===null||$.trim(newCaseReference).length===0){growlError("Case reference is required.","New User Event");return;}
var what=$("#what",dialog).val();if(what===null||$.trim(what).length===0){growlError("Description is required.","New User Event");return;}
var offCalendar=$("#offCalendar",dialog).attr("checked");internalBlock("#content,.ui-dialog");var saveEvent=function(){var txtTime=$("#eventtime",dialog);var time=txtTime.val()==options.timeWatermark?"":txtTime.val();$.post(internalServicePath+'usereventwebservice.aspx',{m:"saveevent",date:$("#eventdate",dialog).val(),time:time,what:what,casereference:newCaseReference,offCalendar:offCalendar},function(data){internalGrowlAjaxResult(data,"New User Event");internalUnblock("#content,.ui-dialog");if(data.Success===true){dialog.dialog("close");fireCallback(options.createCallback,data.Date);clearCurrentEventOptions();}},"json");};if(newCaseReference==options.caseReference){saveEvent();}
else{checkCaseReference(newCaseReference,saveEvent);}};if(options.caseReference===null)
{options.caseReference="";}
showEventDialog("Add User Event",options.caseReference,{"Cancel":function(){$(this).dialog("close");clearCurrentEventOptions();},"Save":saveFunction});}
$.userEvent=function(action,new_options){if(typeof(action)=='object'){new_options=action;action='';}
if(new_options!==undefined&&new_options!==null&&typeof(new_options)=='object'){options=$.extend({},defaults,options,new_options);}
switch(action){case'create':options.userEvent=null;internalBlock("#content,.ui-dialog");initialize(showNewEventDialog);break;case'edit':if(options.transactionDateId!==null){internalBlock("#content,.ui-dialog");initialize(getUserEventData);}
break;}
return options;};})(jQuery);
function sendtoprint(url){var selectedTabText=$('#datecalctabs li.ui-tabs-selected a');if(selectedTabText.length===0||selectedTabText.text().length===0){growlError("You've encountered an error while attempting to print. Please try again later.","Error");return false;}
var viewMode="";var results=selectedTabText.text().match(/\b[a-zA-Z]/ig);if(results===null)
{return"";}
$.each(results,function(i,arg){viewMode+=results[i];});if(viewMode.length===0)
{return"";}
url=url+"&v="+viewMode.toLowerCase();window.open(url,"base");return false;}