<div id="templateCDRMain" class="mainPanel cssServiceProviderMainPanel cssCDRMainPanel" templateId="SIP.CDR" folder="CDR">
	<div class="cssMainHeadding jsMainHeadding">
		<div class="cssLeft" style="float: left;">
			<span class="jsMainHeaddingName">Calls</span>
		</div>
<!--		<ul id="jsddm">
			<li class="cdr_action"><a href="#"><span><strong>Actions</strong><span class="cdr_arrow">▼</span></span></a>
				<ul id='menuOptions' class="menu_drop_more_cdr">
					<li class="topRightCall"><a href="#" onclick="onTopRightMenuCall()">Call</a></li>
					<li class="topRightSMS"><a href="#" onclick="onTopRightMenuSMS()">SMS</a></li>
					<li class="topRightAdd bottom"><a href="#" onclick="onTopRightMenuAddContact()">Add to Contacts</a></li>
				</ul>

			</li>
		</ul> -->
		
		<ul id="jsddm">
			<li title="More" id="action_more"><a href="#" class="moredrop"><span><strong>Actions<span class="arrow">▼</span></strong></span></a>
				<ul class="menu_drop_more_viewmsgs" id="menuOptions">
					<li class="topRightCall"><a href="#" onclick="onTopRightMenuCall()">Call</a></li>
                    <li class="topRightSMS"><a href="#" onclick="onTopRightMenuSMS()">SMS</a></li>
					<li class="topRightAdd bottom"><a href="#" onclick="onTopRightMenuAddContact()">Add to Contacts</a></li>
				</ul>
			</li>
		</ul>
	</div>

	<div class="cssMainBody jsMainBody">
		<div class="cssSummaryPanel jsSummaryPanel">
			<form class="cssSummarySearch jsSummaryBottomMarker jsSearchForm">
					<input type="hidden" class="pid" name="pid" value="" />
					<input type="hidden" class="folder" name="folder" value="" />
				<div class="cssNoMessagesToDisplay jsSummaryRowNoMessages" oid="" style="display:none; margin: 10px;"><?php echo $this->translate("Call history is empty.") ?></div>
				<div class="cssNoMessagesToDisplay jsSummaryRowNoSearchResults" oid="" style="display:none; margin: 10px;"><?php echo $this->translate("No search results. Try again.") ?></div>
				<!-- list Nodes get appended here -->
				<div class="jsSummaryTopMarker"></div>
			</form>
		</div>
		<div class="cssMainDetailsPanel cssMainDetailsPanelCDR jsMainDetailsPanel">
			
			<div class='newCalls'>
				<span class="new-call">New</span>
				<div class='newCallRow callIncoming first'>
					<div class='CallIcon'>
					</div>
					<div class='newCallType'>Incoming</div>
					<div class='newCallDevice'>Home</div>
					<div class='newCallNumber'>0188889090</div>
					<div class='newCallTime'>3 mins ago</div>
				</div>

				<div class='newCallRow callIncoming'>
					<div class='CallIcon'>
					</div>
					<div class='newCallType'>Missed</div>
					<div class='newCallDevice'>Work</div>
					<div class='newCallNumber'>0127762233</div>
					<div class='newCallTime'>2 hours ago</div>
				</div>				
			</div>

			<div class="previousCalls">
				<span class="prev-call">Previous</span>
				<div class="newCallRow callIncoming first">
					<div class="newCallType">Outgoing </div>
					<div class="newCallDuration" title="Call duration">4 minutes</div>
					<div class="newCallDevice">Home</div>
					<div class="newCallNumber">0188889090</div>
					<div class="newCallTime">3 mins ago</div>
					
				</div>

				<div class="newCallRow callIncoming">
					<div class="newCallType">Incoming</div>
					<div class="newCallDuration" title="Call duration">47 minutes</div>
					<div class="newCallDevice">Work</div>
					<div class="newCallNumber">0127762233</div>
					<div class="newCallTime">2 hours ago</div>
					
				</div>
			
				<div class="newCallRow callIncoming">
					<div class="newCallType">Incoming</div>
					<div class="newCallDuration" title="Call duration">24 minutes</div>
					<div class="newCallDevice">Work</div>
					<div class="newCallNumber">0127762233</div>
					<div class="newCallTime">Nov 9</div>
					
				</div>

				<div class="newCallRow callIncoming">
					<div class="newCallType">Outgoing </div>
					<div class="newCallDuration" title="Call duration">2 hours 24 minutes</div>
					<div class="newCallDevice">Work</div>
					<div class="newCallNumber">0188889090</div>
					<div class="newCallTime">Nov 10</div>
					
				</div>

				<div class="newCallRow callIncoming">
					<div class="newCallType">Missed call </div>
					<div class="newCallDuration" title="Call duration">2 hours 24 minutes</div>
					<div class="newCallDevice">Work</div>
					<div class="newCallNumber">0127762233</div>
					<div class="newCallTime">Nov 10</div>
					
				</div>

			</div>		

		<span class="ViewMoreCalls" style="left: 38%; position: relative; display: none;">View 20 more calls</span>

		</div> <!-- End cssMainDetailsPanel -->
		<div class="cdr-tooltip" style="display:none;color:black;">
			<ul>
				<li><a class="tooltipCall" href="#">Call</a></li>
				<li><a class="tooltipSms" href="#">SMS</a></li>
				<li><a class="tooltipNewContact" href="#">Add to Contacts</a></li>
			</ul>
		</div>
	</div> <!-- End cssMainBody -->
</div> <!-- End templateCDR -->


<div id="templateCDRSummaryNodeGeneric" class="cssSummaryRow selected jsSummaryRow" pid="" oid="">
	<input type="checkbox" class="smsCheckbox" value="">
	<div class="CallStatus"></div>
	<div class="startLocale date mailDate dateFormat1">3 mins ago</div>
	<div class="srcName"></div>
	<!--<div class="dstName"></div>
	<div class="duration"></div>-->
	<div class="device">Mobile</div>
	<div class="disposition"></div>
</div>

<div id="templateCDRDetailNodeGeneric" class="cssDetailRow jsDetailRow newCallRow callIncoming first" pid=""oid="" src="" dst="" srcAbookId="" dstAbookId="" >
	<div class="CallIcon">
	</div>
	<div class="newCallType" style="font-size: 14px;">Incoming</div>
	<div class="newCallDuration" title="Call duration">45 Seconds</div>
	<div class="newCallDevice" style="margin-right: 30px;">Home</div>
	<div class="newCallNumber" style="cursor: pointer; ">0188889090</div>
	<div class="newCallTime">3 mins ago</div>
	<div class="newCallDelete" style="display: none;"></div>
	
</div>

<script language="Javascript">
	var currentPageIndex = 0
	var NUMBERLOG_PER_PAGE = 20

	function getCurrentPageIndex()
	{
		return currentPageIndex;
	}

	function increasePageIndex()
	{
		++currentPageIndex;
	}

	function resetPageIndex()
	{
		currentPageIndex=0;
	}

	function getOnePageDetailData(serviceData)
	{
		
		pageNo = getCurrentPageIndex();

		data = new Array()
		restCount = serviceData.length - pageNo*NUMBERLOG_PER_PAGE;
		

		showMore = false

		if(restCount>NUMBERLOG_PER_PAGE) {
			restCount=NUMBERLOG_PER_PAGE
			showMore = true
		}

		for(i=0; i<restCount; ++i) {
			data.push(serviceData[pageNo*NUMBERLOG_PER_PAGE+i])
		}

		return [data, showMore]
	
	}

	function getSelectedCallFolder()
	{
		
		return $(".jsServiceProvider[folder=CDR]", ".serviceFolderGroup").parent().hasClass("current")? "CDR" :
			$(".jsServiceProvider[folder=SMS]", ".serviceFolderGroup").parent().hasClass("current")? "SMS" :
			null;
			
	}

	function assertFolder(folder)
	{
		
		if(!folder || folder != getSelectedCallFolder())
			return false;
		return true;
		
	}
	
	function getSelectedPid()
	{
		if( $(".jsServiceProvider[folder=CDR]", ".serviceFolderGroup").parent().hasClass("current") )
			return $(".jsServiceProvider[folder=CDR]", ".serviceFolderGroup").attr("pid")
		else if( $(".jsServiceProvider[folder=SMS]", ".serviceFolderGroup").parent().hasClass("current") )
			return $(".jsServiceProvider[folder=SMS]", ".serviceFolderGroup").attr("pid")
		else 
			return null
	}

	/**
	* select call logs
	*/
	function selectAllLogs() 
	{
		jsddm_close();

		$(".smsCheckbox:checkbox","#messageList").each(function(){
			this.checked = true;
			$(this).parent().addClass("selected");
		})
	}

	function deselectAllLogs()
	{
		jsddm_close();
		$(".smsCheckbox:checkbox","#messageList").each(function(){
			this.checked = false;
			$(this).parent().removeClass("selected");
		})
	}

	function getSelectedIds(folder) 
	{
		if(!folder) return;
		
		var ids = new Array()
		
		$(".smsCheckbox:checkbox[checked=true]", "#messageList").parent().each( function(){
			
			var pid = $(this).attr("pid")
			var myId = $(this).attr("myid") || $.localData.dataStore["pid"+pid].myId || alert("myId not defined")
			var oid = $(this).attr("oid") || alert("oid not defined")
			
			var data = $.templateEngine.templates.SIP.CDR.getDetailsFromSummaryId(pid, folder, oid);
			
			for(var i=0; i<data.length; ++i) {
				ids.push(data[i].id)
			}
		})
		
		return ids
	}

	/**
	 * callBack function(response)
	 */
	function deleteLogItemsOnServer(folder, ids, callBack)
	{
		var target = ''
		if(folder=="CDR" || folder=="call")
		{
			target = "call"
		}
		else if(folder=="SMS" || folder=="sms")
		{
			target = "sms"
		}
		else
		{
			alert("Folder is invalid! " + folder);
			return;
		}
		
		if(ids == undefined ) {
			alert("No Item is selected");
			return;
		}
		
		var url = "<?php echo $this->appBaseUrl ?>/api/unify/ucdbdelete"
		
		var ajaxData = {
			"folder"	: target,
			"id[]"		: ids
		}			
		
		var _this = this
		_this.deleteSuccess = false
		$.ajax({
			async: true,
			url: url,
			type: "POST",
			dataType: "json",
			data : ajaxData,
			cache: false,
			timeout: 5000, 
			success: function(response, type)
			{
				callBack && callBack(response)
			}, 
			error: function(jqXHR, textStatus, errorThrown)
			{
				callBack && callBack({"error" : -1})
			}
		});
		
	}
	
	function deleteLogItemsOnLocalData(pid, folder, ids)
	{
		
		$.localData.deleteByIds($.localData.dataStore["pid"+pid].folders[folder].serviceData, ids)
		
	}
	
	function deleteLogItems(pid, folder, ids, refreshUI)
	{
		
		deleteLogItemsOnServer(folder, ids, function(response){
			if(response.error == 0) {
				deleteLogItemsOnLocalData(pid, folder, ids)

				if( refreshUI ){
					$phone.refreshLog(folder);
					resetSummaryFocus();
				}
			}
		})
	}

	function resetSummaryFocus()
	{
		var $summary = $(".cssSummaryRow:first", "#messageList")
		if( $summary.length ) {
			$summary.click()
		}
		else {
			$('span.jsMainHeaddingName','#messageList').html('')
		}
	}

	function deleteSelectedLogItemsAndUpdateUI() 
	{
		
		var pid = getSelectedPid()
		var folder = getSelectedCallFolder()
		var ids = getSelectedIds(folder)

		$(".smsCheckbox:checkbox[checked=true]", "#messageList").parent().each(function(){
			$(this).css('opacity', '0.4')
		})

		deleteLogItems(pid, folder, ids, true)
		resetSummaryFocus()

	}

	function updateDeleteAction() 
	{
		var enable = $(".smsCheckbox:checkbox[checked=true]","#messageList").length > 0? true : false
		if(enable) {
			$("#action_delete a").removeClass("disabled").attr("disabled","").css("opacity","1")
		}
		else {
			$("#action_delete a").addClass("disabled").attr("disabled","true").css("opacity","0.4")
		}
	}

	function getUriFromQtip($context)
	{
		var uri = ''
		var qtipDOM = $context.parent().parent().parent().parent().parent().parent().parent();
		var oid = qtipDOM.qtip("api").elements.target.attr("oid")

		if( $(".jsDetailRow[oid=" + oid + "]").hasClass("callIncoming") )
			uri = $(".jsDetailRow[oid=" + oid + "]").attr("src")
		else
			uri = $(".jsDetailRow[oid=" + oid + "]").attr("dst")

		qtipDOM.qtip("hide");

		return uri
	}

	//List bindings
	$(function() {
		var uri = ''

		if( typeof $phone != "undefined" && $phone.params.SIPServerType == "SIP" )
        {

            $('.tooltipSms').hide()
            $('.topRightSMS').hide()

        }

		$(".tooltipCall", ".cdr-tooltip:first").bind("click", function() 
		{
			uri = getUriFromQtip($(this))
			$phone.initiateOutboundUICall( uri )
			$(this).parent().parent().parent().parent().parent().parent().parent().qtip("hide");
			return false
		})

		$(".tooltipSms", ".cdr-tooltip:first").bind("click", function() 
		{ 
			uri = getUriFromQtip($(this))
			$phone.newIM( $phone.humanize(uri) )
			$(this).parent().parent().parent().parent().parent().parent().parent().qtip("hide");
			return false
		})

		$(".tooltipNewContact", ".cdr-tooltip:first").bind("click", function() 
		{ 
			uri = getUriFromQtip($(this))
			$phone.addToContacts( $phone.humanize(uri) )
			$(this).parent().parent().parent().parent().parent().parent().parent().qtip("hide");
			return false
		})
		
		
		$("#templateCDRMain #jsddm > li").bind("mousedown", jsddm_open)
		
		$.templateEngine.templates.SIP.CDR = { 
			_thisTemplate : this, 
			debug : false,
			log : function(what) { if(this.debug) console.log(what) }, 
			render : function($contextMain, dataPacket) //this renders the left hand summary, and then calls to render first details in right hand panel
			{ 
				if( $(".mainPanel", $contextMain).attr("templateId") == undefined || $(".mainPanel", $contextMain).attr("templateId") != "SIP.CDR" ) 			// if not the right template then clear $mainContext and start from scratch
				{
					$contextMain.empty()
				}
				
				//this template does not aggregate folders (it shows one folder at a time, so clear it if folder changes)
				if( dataPacket.folder == $(".mainPanel", $contextMain).attr("folder") )
				{
					
					$(".mainPanel", $contextMain).attr("folder", dataPacket.folder )
					this.update($contextMain, dataPacket)
					return
					
				}
				else
				{
					
					$contextMain.empty()
					
				}
				var $mainCDR = $("#templateCDRMain").clone(true).removeAttr("id")
				$mainCDR.attr("serviceType", dataPacket.serviceType )
				$mainCDR.attr("serviceName", dataPacket.serviceName )
				$mainCDR.attr("folder", dataPacket.folder )
				$(".jsMainDetailsPanel div", $mainCDR).each( function() { if( !$(this).hasClass("newCalls") ) $(this).remove() })
				var $uiContext = $contextMain.html( $mainCDR )
				var pid = dataPacket.pid
				var myId = dataPacket.myId || $.localData.dataStore["pid"+pid].myId || alert("templateCDR#157: myId not defined") 								//safe for stream when might have rows from different sources in one list
				var folder = dataPacket.folder

				if( dataPacket.localDataNode == undefined || dataPacket.localDataNode.serviceData == undefined )
				{
				
					this.pushSummaryRow( $(".jsSummaryPanel .jsSummaryBottomMarker", $contextMain), dataPacket, null, false) 									//CONSIDER: leave blank if local data is empty, only push no items message after attempting to update from the server
					$(".jsSummaryRow", $contextMain).show()
				
				}	
				else
				{
					
					_this = this
					serviceDataSummary = this.getSummaryData( dataPacket.localDataNode.serviceData )

					//window.open().document.body.innerHTML = "<pre>" + JSON.stringify(serviceDataSummary,null, 4) + "</pre>";
					$.each( serviceDataSummary, function( index, row) 
					{
					
						_this.pushSummaryRow( $(".jsSummaryPanel .jsSummaryBottomMarker", $contextMain), dataPacket, row, false)
					
					})
					$(".jsSummaryRow:first", $contextMain).addClass("selected")
					$(".jsSummaryRow", $contextMain).show()
					
					//dataNode.serviceData //inreverse the object - quick
					
					//N.B. currently only partial support for multiple Phone accounts (e.g. stream view of multiple corporate accounts) therefore not in a tab and therefore not context aware
					//CONSIDER upgrading to allow multiple accounts/tabs
					enableMailActions();

					if( dataPacket.localDataNode.serviceData.length > 0 )
					{

						var firstRow = dataPacket.localDataNode.serviceData[0]
						var oid = firstRow.id
						//this.log( "templateCDR#373::update: about to call renderDetailsAction on: " + pid + ":" + folder + ":" + oid )
						this.renderDetailsAction($contextMain, pid, myId, folder, oid)
						//we do this instead of triggering a click on the first item because might still be animate-removing prev items and we dont want to wind up loading previous first item again

					}

				}
				

				$(".jsSearchForm", $contextMain).submit( function() 
				{
					
					//TODO: trigger keyup again if necessary to do async search against server/full dataset
					return false
					
				})
				$(".jsSearchForm .q", $contextMain).unbind("click").bind("click", function() {

					if( $(this).attr("value") == "<?php echo $this->translate("Search") ?>" )
						$(this).select();

				});
				
				$(".jsSearchForm .q", $contextMain).unbind("blur").bind("blur", function() {

					if( $(this).attr("value") == "" )
						$(this).attr("value", "<?php echo $this->translate("Search") ?>")
					
				});
				
				
				$(".jsSearchForm .q", $contextMain).unbind('keyup').bind('keyup', function() 
				{
				
					this.searchList( $contextMain, $(this).attr('value'))
				
				})
				
				//call render complete callback (overloadable by main application as an event hook)
				//CONSIDER rather triggering a custom event so that other objects can bind to the event instead
				//this.log("leaving CDR render and calling renderCompleteCallback()") 
				this.renderCompleteCallback()
				
			},
			getSummaryData : function( data )
			{
				if(!assertFolder('CDR'))
					return;
				
				//this.log( 'templateSMS.phtml #623:getSummaryData data:' )
				//this.log( data )
				
				var _this = this
				var latestData = []

				for(var i=data.length-1; i>=0; --i)
				{
					row = data[i]
					//for each raw row, run through latestData and try find an existing latest entry, if not found add it 
					var foundInLatest = false
					$.each( latestData, function( i2, row2 )
					{
						if( messagesAreInTheSameThread(row,row2) )
						{
							if(row.initUnixGMT>row.initUnixGMT) {
								latestData[i2] = row
							}

							foundInLatest = true
							return false // === Break each
						}
							
					})
					
					//if we get to here and foundInLatest == false then add it
					if( !foundInLatest )
						latestData.push( row )
				
				}
				//this.log(latestData)
				return latestData.sort(function(a, b){
					return b.initUnixGMT - a.initUnixGMT;
				})
				
			},

			renderCompleteCallback : function() { /* this.log('renderCompleteCallback called') */ },
			getDetailsFromSummaryId : function( pid, folder, oid ) {
				
				_this = this
				var serviceData = new Array();
				var summaryRow = $.localData.findById( $.localData.dataStore["pid"+pid].folders[folder].serviceData, oid)
				//this.log($.localData.dataStore["pid"+pid].folders[folder].serviceData)
				//this.log("matched summaryRow")
				//this.log( summaryRow)
				//now match all calls incoming or outgoing
				$( $.localData.dataStore["pid"+pid].folders[folder].serviceData ).each( function(i,row) 
				{
					if( messagesAreInTheSameThread(summaryRow,row) )
					{
						serviceData.push(row)
					}				
				})
				return serviceData
				
			}, 
			renderDetailsAction : function($contextMain, pid, myId, folder, oid) 																				// action used to render details view by id
			{
			
				//this.log( 'renderDetailsAction #255: renderDetailsAction' )
				//in this template oid is the summary id, now use this id to find all details rows from complete dataset that relate to theis oid
				var details = this.getDetailsFromSummaryId( pid, folder, oid)
				details = details.sort(function(a, b){
					return b.initUnixGMT - a.initUnixGMT;
				})
				var dataPacket = { pid : pid, folder : folder, localDataNode : {serviceData : details} }
				this.renderDetails($contextMain, dataPacket)
			
			}, 
			renderDetails : function( $contextMain, dataPacket, isAppend ) 																								//takes a dataPacket and renders it to the details view
			{
				if(!assertFolder('CDR'))
					return;

				var row = dataPacket.localDataNode.serviceData[0];
				var DetailsHeader = $phone.makeDetailHeader(row);
				$(".jsMainDetailsPanel", $contextMain).parent().parent().children(".jsMainHeadding").find(".jsMainHeaddingName").html(DetailsHeader)

				
				//this.log( 'templateCDR.phtml #272: renderDetails' )
				//empty detailes panel
				//return
				//$(".jsMainDetailsPanel .newCalls", $contextMain).empty()
				if(!isAppend) {
					$(".jsMainDetailsPanel div", $contextMain).each( function() { if( !$(this).hasClass("newCalls") ) $(this).remove() })
				}
				else {
					$('span.ViewMoreCalls','#messageList').hide();
				}
				//renderDetailsRows
				this.pushDetailsRows( $contextMain, dataPacket )
			
			},
			pushDetailsRows : function( $contextMain, dataPacket )
			{
				if(getSelectedCallFolder()!='CDR')
					return;
				
				//this.log( 'templateCDR.phtml #282: pushDetailsRows' )
				//this.log(dataPacket)
				var pid = dataPacket.pid
				var myId = $.localData.dataStore["pid"+pid].myId
				var myDisplayName = $.localData.dataStore["pid"+pid].myDisplayName
				if( dataPacket.localDataNode.serviceData != undefined )
				{
					
					_thisTemplate = this
					result = getOnePageDetailData(dataPacket.localDataNode.serviceData)
					serviceData = result[0]
					showMore = result[1]
					
					$.each(serviceData, function(i,dataNode)
					{ 
						
						dataNode.pid = pid
						dataNode.myId = myId
						dataNode.myDisplayName = myDisplayName
						_thisTemplate.pushDetailsRow($contextMain, dataPacket, dataNode, false)
						
						
					})
					
					// Show delete row icon
					$(".newCallRow").hover(function() {
						$(this).find(".newCallDelete").show();
					},function(){
						$(this).find(".newCallDelete").hide();
					});
					
					if(showMore) {
						$('span.ViewMoreCalls','#messageList').show().unbind().bind('click', function(){
							increasePageIndex();
							$.templateEngine.templates.SIP.CDR.renderDetails($contextMain, dataPacket, true);
						})						
					}
					else {
						$('span.ViewMoreCalls','#messageList').hide()
					}

				}
				
			},
			getCallType : function(row)
			{
				return row.status == 'MISSED' ? 'Missed' :
					isOutbound(row.src)? 'Outgoing' :
					'Incoming';
			},
			pushDetailsRow : function( $context, dataPacket, row, prepend )
			{
				if(!assertFolder('CDR'))
					return;
				
				//this.log(">>>>>>>>>>>>>>>>> pushDetailsRow <<<<<<<<<<<<<<<<<<<<<<")
				//this.log(row)
				//copy template details node, populate and insert into panel												
				$newNode = $("#templateCDRDetailNodeGeneric").clone().removeAttr('id').removeClass('first')					
				$newNode.hide()              																				
				$newNode.attr('pid', row.pid)																				
				$newNode.attr('oid', row.id)																				
				$newNode.attr('src', $phone.humanize(row.src) )																				
				$newNode.attr('dst', $phone.humanize(row.dst) )		
				$newNode.attr("srcAbookId", row.srcAbookId || "")
				$newNode.attr("dstAbookId", row.dstAbookId || "")
																															
                                             																				
				// Render the content differently, depending on the type
				callType = this.getCallType(row)
				$newNode.find(".newCallType").html(callType)
				
				if( isOutbound(row.src) )
				{
					//Outgoing call
					$newNode.removeClass("callIncoming").addClass("callOutgoing")
					$newNode.find(".CallIcon").addClass("CallIconOutgoing").removeClass("CallIcon")
					$newNode.find(".newCallNumber").html( $phone.humanize(row.dst) )

					devicename = $phone.deviceName(row.target_device)
					if(!devicename) devicename = '&nbsp';
					$newNode.find(".newCallDevice").html(devicename)
				}
				else
				{
					
					//Incoming call
					$newNode.find(".newCallNumber").html( $phone.humanize(row.src) )
					devicename = $phone.deviceName(row.source_device)
					if(!devicename) devicename = '&nbsp';
					$newNode.find(".newCallDevice").html(devicename)

				}

				if(row.status == 'MISSED') {
					$newNode.find(".CallIcon").addClass("callIconMissed").removeClass("CallIcon")
				}
				

				//$newNode.find(".newCallNumber").unbind().bind("click", function() { $phone.initiateOutboundUICall($(this).html()) })
				var _thisTemplate = this
				$newNode.find(".newCallDelete").bind("click", function(e) {
					e.stopPropagation()

					var oid = $(this).parent().attr('oid')
					var folder = 'CDR'
					var pid = $(this).parent().attr('pid')
					deleteLogItems(pid, folder, [oid] );

					$(this).parent().fadeOut(200, function(){
						$(this).remove()

						if(!$('.newCallRow:visible','#messageList').length) {
							if($('.ViewMoreCalls','#messageList').css('display')=='inline') {
								$('.ViewMoreCalls','#messageList').click()
							}
							else {
								$summaryRow = $('.jsSummaryRow.selected','#Email')
								if($summaryRow.length ==  1) $summaryRow.fadeOut(600, function(){
									$(this).remove()
									resetSummaryFocus()
								})
							}
						}
						
					})
					
				})
				
				// Qtip for Call actions
				$newNode.qtip(
				{
					target: $newNode.find(".newCallType"), 
					content: $('.cdr-tooltip:first'),
					show: 'click',
					style: { background: 'transparent', border: 'none', name: 'dark' },
					position: { corner: 'topLeft', adjust: { screen:true, x: 28, y: 25 } },
					hide: { when: 'unfocus', fixed: false }
				});

				timeDiff = Date.now()-row.initUnixGMT*1000
				timeAgo = timeDiff<86400000? $.timeago.inWords(timeDiff) : $.datepicker.formatDate('d M', new Date(row.initUnixGMT*1000));
				
				$newNode.find(".newCallTime").html( timeAgo )
				
				// attempt update of summary listing
				$summary = $(".cssSummaryRow[oid='" + row.id + "']",'#messageList')
				if($summary.length)
				{
					$date = $summary.find('.date');
					if($date.length) $date.html( timeAgo )
				}

				if(row.durationSecs<60)
				{
					var duration = row.durationSecs==0? '' : row.durationSecs + " secs"
				}
				else
				{
					var duration = $.timeago.inWords(row.durationSecs * 1000)	// call jquery plugin
					duration = duration.substr(0, duration.length-4)		// remove last four 4 char ' ago''
				}

				$newNode.find(".newCallDuration").html(duration)				
				
				//if this is the only one then add class first
				if( $(".jsDetailRow", $context).length == 1 ) 
					$newNode.addClass("first")
					
				//this.log(" about to push:")
				//this.log($newNode.html())
				$context.find(".newCalls").append($newNode) //TODO prepend
				//this.log("done pushDetailsRow")
				//this.log($newNode.html())
				$newNode.show()

			}, 
			pushSummaryRows : function($contextMain, dataPacket) 
			{
				if(!assertFolder('CDR'))
					return;
				
				//this.log( 'templateCDR.phtml::pushSummaryRows#287: dataPacket:' )
				//this.log( dataPacket )
				
				var pid = dataPacket.pid
				var myId = $.localData.dataStore["pid"+pid].myId
				var myDisplayName = $.localData.dataStore["pid"+pid].myDisplayName
				
				if( dataPacket.localDataNode.serviceData != undefined )
				{
					
					_this = this
					$.each( dataPacket.localDataNode.serviceData, function(i,dataNode) 
					{ 
						
						//_this.log( 'templateCDR.phtml #380: dataNode:' )
						//_this.log( dataNode )
						
						//not more than 5
						if( $('.previousPostNode', $contextMain).length > 5 )
							return false
						if( dataNode.from.name != myDisplayName ) //if post not from me then skip
							return true
						if( $('.previousPostNode[oid="'+dataNode.id+'"]', $contextMain).length > 0 ) //skip if already in list
							return true
						
						dataNode.pid = pid
						dataNode.myId = myId
						dataNode.myDisplayName = myDisplayName
						_this.pushSummaryRow($contextMain, dataPacket, dataNode, false)
						
					})
				
				}
				
			},
			pushSummaryRow : function( $context, dataPacket, row, prepend )
			{

				$contextMain = $context.parent().parent().parent().parent() //should always be the div wrapping the complete rendered template panel (i.e. the tab wrapper div (ui-tabs-panel))

				var pid    = row.pid    || dataPacket.pid    || $contextMain.children('.mainPanel').attr('pid')    || alert("#52X: pid not defined")
				var serviceType = row.serviceType || dataPacket.serviceType || $.localData.dataStore["pid"+pid].serviceType || $contextMain.children('.mainPanel').attr('serviceType')    || alert("#52X: serviceType not defined")
				var serviceName = row.serviceName || dataPacket.serviceName || $.localData.dataStore["pid"+pid].serviceName || $contextMain.children('.mainPanel').attr('serviceName')    || alert("#52X: serviceName not defined")
				var myId = row.myId || dataPacket.myId || $contextMain.children('.mainPanel').attr('folder') || $.localData.dataStore["pid"+pid].myId || alert("templateCDR#770: myId not defined") //safe for stream when might have rows from different sources in one list
				var folder = row.folder || dataPacket.folder || $contextMain.children('.mainPanel').attr('folder') || alert("templateCDR#771: folder not defined")
				var oid = row.id || alert("#52X: error, trying to push a list item with no id")

				// OK, so we have a message. Who is it from?
				if( row == null )
				{

					$('.jsSummaryRowNoMessages', $(this)).show()
					return

				}

				showHideNoMessagesAtSummaryRow(false)

				$newNode = $("#templateCDRSummaryNodeGeneric").clone().removeAttr('id').removeClass('selected')
				$newNode.hide()

				$newNode.attr('pid', pid)
				$newNode.attr('oid', oid)
				$newNode.attr('src', row.src)
				$newNode.attr('dst', row.dst)

				// Render the content differently, depending on the type
				if( isOutbound(row.src) ) {
					$newNode.addClass("outbound")
					device = $phone.deviceName( row.target_device )
					displayName = row.target_name && row.target_name != 'Unknown'? row.target_name : $phone.humanize(row.dst)
					title = $phone.humanize(row.dst)
				}
				else {
					$newNode.addClass("inbound")
					device = $phone.deviceName( row.source_device )
					displayName = row.source_name && row.source_name != 'Unknown'? row.source_name : $phone.humanize(row.src)
					title = $phone.humanize(row.src)
				}

				if(row.status == 'MISSED') $newNode.addClass("missed")
				
				timeDiff = Date.now()-row.initUnixGMT*1000
				timeAgo = timeDiff<86400000? $.timeago.inWords(timeDiff) : $.datepicker.formatDate('d M', new Date(row.initUnixGMT*1000));

				$(".startLocale", $newNode ).html( timeAgo )
				$(".srcName", $newNode ).html( displayName )
				$(".srcName", $newNode ).attr( "title", title )
				//$(".dstName", $newNode ).html( dstName )
				//$(".dstName", $newNode ).attr( "title", $phone.humanize(row.dst) )
				$(".device", $newNode ).html( device )
				$(".duration", $newNode ).html( row.durationSecs + " Seconds" )
				$(".disposition", $newNode ).html( row.disposition )

				if(device == 'Unknown')
					$(".device", $newNode ).hide()


				//add bindings for SMS and callback and delete row
				_thisTemplate = this
				$newNode.find('.smsCheckbox:checkbox').bind('click', function(e) { 
					e.stopPropagation()
					//console.log($(this).attr('checked'))
					
					if($(this).attr('checked')) {
						$(this).parent().addClass('selected')
					}
					else {
						$(this).parent().removeClass('selected')
					}
					
					updateDeleteAction()
					
				}); 
				
				$newNode.bind('click', function() 
				{  
					resetPageIndex()
					
					$contextMain = $(this).parent().parent().parent().parent().parent() 																			//.ui-tabs-panel

					$('.jsSummaryRow', $contextMain).removeClass('selected') 																						//unselect all other jsSummaryRow
					$('.smsCheckbox', $contextMain).attr('checked',false)																						//unselect all other jsSummaryRow
					
					$(this).find('.smsCheckbox').attr('checked',true)
					updateDeleteAction()
					
					//mark this jsSummaryRow as selected
					$(this).addClass('selected')
					
					var pid = $(this).attr('pid')
					var myId = $(this).attr('myid') || $.localData.dataStore["pid"+pid].myId || alert("myId not defined")
					var folder = $(this).attr('folder') || $('.mainPanel', $contextMain).attr("folder") || alert("folder not defined")
					var oid = $(this).attr('oid') || alert("oid not defined")
					//_thisTemplate.log( "about to call renderDetailsAction( pid=" + pid + ", myId=" + myId + ", folder=" + folder + " oid=" + oid + ")" )
					_thisTemplate.renderDetailsAction($contextMain, pid, myId, folder, oid)
					return false
					

				})

				if( prepend ) //for pushing new rows on top instead of the bottom
					$('.jsSummaryTopMarker', $context).after( $newNode )
				else
					$context.append( $newNode )
				$newNode.show()

			}, 
			update : function($contextMain, dataPacket) {
				if(!assertFolder('CDR'))
					return;
				
				//this.log('entering CDR update')
				serviceDataSummary = this.getSummaryData( dataPacket.localDataNode.serviceData )
				//this.log(dataPacket)
				if( false && dataPacket.localDataNode == undefined || dataPacket.localDataNode.serviceData == undefined ) //TODO reqork to insert "No Records" notice
				{
					_thisTemplate.pushSummaryRow( $(".jsSummaryPanel .jsSummaryBottomMarker", $contextMain), dataPacket, null, false) //CONSIDER: leave blank if local data is empty, only push no items message after attempting to update from the server
					$('.jsSummaryRow', $contextMain).show()
					
				}
				else
				{
					
					$('.jsSummaryRowNoSearchResults', $contextMain).hide()
					
					//get list if existing oids from rows
					UIOIDs = []
					$('.jsSummaryRow', $contextMain).each( function() { UIOIDs[UIOIDs.length] = $(this).attr('oid') })
					//this.log( UIOIDs )

					showHideNoMessagesAtSummaryRow( UIOIDs.length == 0 )
					
					//delete deleted rows out of ui
					$(UIOIDs).each( function(index1, UIOID) {
					
						//for each UI OID run through new dataPacket and continue if found or delete if not found
						var UIOIDFoundInServiceData = false
						$( serviceDataSummary ).each( function(index, row) { 
							//if found then continue
							//this.log( UIOID + ":" + row.id + " = " + (UIOID.toString() == row.id.toString() ) )
							if( UIOID == row.id )
								UIOIDFoundInServiceData = true
						})
						if( !UIOIDFoundInServiceData )
						{
							$('.jsSummaryRow[oid="' + UIOID + '"]', $contextMain).remove()
							$('.jsDetailRow[oid="' + UIOID + '"]', $contextMain).remove()
						}
					})
					//quick fix to decide if new items should go on top = are there existing items in the list after culling
					if( $('.jsSummaryRow', $contextMain).length > 0 )
						prepend = true
					else
						prepend = false
					
					//push new rows in to ui - on top (must be new)
					_this = this
					$( serviceDataSummary ).each( function(index1, row) { 
					
						//if not found in MUIDs then add it
						var rowIdFoundInUIOIDs = false
						$(UIOIDs).each( function(index, UIOID) {
						
							if( UIOID == row.id )
							{
								rowIdFoundInUIOIDs = true
								return false //break
							}
						
						})
						if( !rowIdFoundInUIOIDs )
						{
							//only prepend rows are newer than top one
							//this.log( 'templateCDR.phtml #352: row.id:' )
							//this.log( row.id.split("_",4) )
							//var listListNodeId = $(".jsSummaryRow:first", $contextMain).attr('oid')
							//if( listListNodeId == undefined || listListNodeId == "" )
							//	listListNodeId = "0_0"
							//this.log( 'templateCDR.phtml #355: listListNodeId:' )
							//this.log( listListNodeId.split("_",4) )
							
							_this.pushSummaryRow( $(".jsSummaryPanel .jsSummaryBottomMarker", $contextMain), dataPacket, row, prepend)
						}
					
					})
					$('.jsSummaryRow:first', $contextMain).trigger("click")
					//$('.jsSummaryRow', $contextMain).show() //show all the new rows at once
					//CONSIDER: if none are selected at the end then select the top one - so that you dont wind up with an empty or stranded main body OR do we want the mast selected row to remain on screen incase person was reading it (wouldnt want it to suddenly dissapear cos of an auto reload)
				}
				//this.renderDetailsAction($contextMain, pid, myId, folder, oid)
				//this.log('leaving CDR update')
				
			}, 
			searchList : function($context, searchTerm)
			{
				
				// Un-highlight previous selections
				$(".messageFrom > div, .messageSubject > h3, .messagePreview", $context).each(function() 
				{
					$(this).removeHighlight();
				})

				// Require more then 3 characters to perform the search
				if(searchTerm.length < 3) 
				{
					$(".jsSummaryRow", $context).show()
					$('.jsSummaryRowNoSearchResults', $context).hide()
					return false
				}

				var searchMatches = 0
				var reg = new RegExp( searchTerm, 'i' )
				// Loop through each node and try match
				$(".jsSummaryRow", $context).each( function() 
				{
					
					var matchFound = false
					$(".messageFrom > div, .messageSubject > h3, .messagePreview", $(this)).each( function() 
					{
						
						if( reg.test($(this).text()) ) 
						{
							$(this).highlight(searchTerm)
							matchFound = true
						}
						
					})
					if( matchFound == true )
						searchMatches++;
					else
						$(this).hide()

				})
				if(searchMatches == 0)
					$('.jsSummaryRowNoSearchResults', $context).show()
				else
					$('.jsSummaryRowNoSearchResults', $context).hide()
				
			}
			
		}
		
	});
</script>
