<div id="templateSMSMain" class="mainPanel cssServiceProviderMainPanel cssSMSMainPanel" templateId="SIP.SMS" folder="SMS">
	<div class="cssMainHeadding jsMainHeadding">
		<div class="cssLeft" style="float: left;">
			<span class="jsMainHeaddingName"></span>
		</div>
<!--		<ul id="jsddm">
			<li class="sms_action"><a href="#"><span><strong>Actions</strong><span class="sms_arrow">▼</span></span></a>
				<ul id='menuOptions' class="menu_drop_more_sms">
					<li class="topRightCall"><a href="#" onclick="onTopRightMenuCall()">Call</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" class="jsSMSActionMore"><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="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("SMS folder is empty.") ?></div>
				<div class="cssNoMessagesToDisplay jsSummaryRowNoSearchResults" oid="" style="display:none; margin: 10px;"><?php echo $this->translate("No search results. Try again.") ?></div>
				<div class="jsSummaryTopMarker"></div>
				<!-- list Nodes get appended here -->
				<div class="cssSummaryRow jsSummaryRow SMSSummaryRow smsIncoming selected unread" pid="" oid="">
					<div class="sms-icon"></div>
					<div class="SMSSummaryDeliveredDatetime">3 mins ago</div>
					<div class="SMSSummaryType">Incoming</div>
					<div class="SMSSummaryFrom" title="0188889090">Dummy Friend1</div>
					<div class="SMSSummaryDevice">Personal Mobile</div>
					<div class="SMSSummaryMessage">SMS Test 1234</div>
				</div>

				<div class="cssSummaryRow jsSummaryRow SMSSummaryRow smsIncoming" pid="" oid="">
					<div class="sms-icon"></div>
					<div class="SMSSummaryDeliveredDatetime">2 hours ago</div>
					<div class="SMSSummaryType">Outgoing</div>
					<input type="checkbox" class="smsCheckbox" value="" />
					<div class="SMSSummaryTo" title="0127762233" style="margin-top: 13px;">Dummy Friend2</div>
					<div class="SMSSummaryDevice">Work Mobile</div>
					<div class="SMSSummaryMessage">SMS Test 1234</div>
				</div>
			</form>
		</div>
		<div class="cssMainDetailsPanel cssMainDetailsPanelSMS jsMainDetailsPanel jsMainDetailsPanelSMS">
			
			<div class="ViewEarlierSMS" style="display:none;">View earlier messages 
				<div class="SMSTimeline">
					<ul>
						<li><a href="">1 Day</a></li>
						<li><a href="">1 Week</a></li>
						<li><a href="">2 Weeks</a></li>
						<li><a href="">1 Month</a></li>
						<li><a href="">3 Months</a></li>
						<li><a href="">6 Months</a></li>
						<li><a href="">1 Year</a></li>
					</ul>
				</div>
			</div>

			<div class="cssDetailRow jsDetailRow SMSRow smsIncoming first unread" pid=""oid="">
				<div class="SMSDeliveredDatetime">3 mins ago</div>
				<div class="SMSType" style="display: none;">Incoming</div>
				<div class="SMSDevice">Personal Mobile</div>
				<div class="SMSFrom" title="0188889090">Dummy Friend1</div><div class="Call">Call</div><div class="SMS">SMS</div>
				<div class="SMSIcon"><img src=""/></div>
				<div class="SMSMessage">SMS Test 1234</div>
			</div>

			<div class="cssDetailRow jsDetailRow SMSRow smsOutgoing" pid=""oid="">
				<div class="SMSDeliveredDatetime">2 hours ago</div>
				<div class="SMSType" style="display: none;">Outgoing</div>
				<div class="SMSDevice">Work Mobile</div>
				<div class="SMSTo" title="0188889090">Dummy Friend1</div><div class="Call">Call</div><div class="SMS">SMS</div>
				<div class="SMSIcon"><img src=""/></div>
				<div class="SMSMessage">SMS Test 2345</div>
			</div>
			
			<div class="SMSComposerMessagePanel">
				<div class="SMSwrapper">
					<?php /* <div class="leftcompose"><span class="smsLengthCounter">160 msgs 1</span></div> */ ?>
					<div class="rightcompose">
						<input class="SMSViewMessageInput" value="Send a Reply ..." />
					</div>
					<ul class="sms-btn-send">
						<li class="buttonSend" id="phone-btn-blue"><a href="#"><span><strong>Send</strong></span></a></li>
					</ul>
				</div>
			</div>

			<span class="ViewMoreMessages" style="left: 38%; position: relative; display: none;">View 20 more messages</span>
			
		</div> <!-- End cssMainDetailsPanel -->
		<div class="sms-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 class="sms-tooltip noAddToContacts" style="display:none; color: black;">
			<ul>
				<li><a class="tooltipCall" href="#">Call</a></li>
				<li><a class="tooltipSms" href="#">SMS</a></li>
			</ul>
		</div>
	</div> <!-- End cssMainBody -->
	
</div> <!-- End templateSMS -->

<div id="templateSMSSummaryNodeGeneric" class="cssSummaryRow jsSummaryRow SMSSummaryRow smsIncoming smsOutgoing selected unread" pid="" oid="">
	<span class="unread"><strong></strong></span>
	<div class="SMSSummaryDeliveredDatetime"></div>
	<div class="SMSSummaryType"></div>
	<input type="checkbox" class="smsCheckbox" value="" />
	<div class="SMSSummaryFrom" title="" style="margin-top: 13px;"></div>
	<div class="SMSSummaryTo" title="" style="margin-top: 13px;"></div>
	<div class="SMSSummaryDevice"></div>
	<div class="SMSSummaryMessage"></div>
</div>

<div id="templateSMSDetailNodeGeneric" class="cssDetailRow jsDetailRow SMSRow smsIncoming smsOutgoing first" pid=""oid="" src="" dst="" srcAbookId="" dstAbookId="" >
	<div class="SMSDeliveredDatetime"></div>
	<div class="SMSType" style="display: none;"></div>
	<div class="SMSDevice"></div>
	<div class="SMSRowDetails">
		<div class="SMSIcon"><img src=""/></div>
		<div class="SMSTo" title="" style="display: none;"></div>
		<div class="SMSFrom" title="" style="display: none;"></div>
		<div class="deleteLog" style="display: none;"></div>
		<div class="SMSMessage"></div>
	</div>
</div>

<div id="templateSMSComposer" class="cssSMSComposer">
	<div class="message_outer">
		<div class="message_inner">
			<input type="hidden" name="SMSComposerPID" class="SMSComposerPID" value=""/>
			<input type="hidden" name="SMSComposerFolder" class="SMSComposerFolder" value=""/>
			<div class="SMSComposerToPanel">
				<div class="leftcompose">To: </div>
				<div class="rightcompose"><input name="SMSComposerTo" class="SMSComposerToInput" value="" /></div>
				<div class="SMSComposerMessagePanel">
					<div class="SMSwrapper">
						<?php /*<div class="leftcompose"><span class="smsLengthCounter">160 msg 1</span></div> */ ?>
						<div class="rightcompose"><textarea name="SMSComposerMessage" class="SMSComposerMessageInput" ></textarea></div>
						<ul class="sms-btn-send">
							<li id="phone-btn-blue" class="buttonSend"><a href="#"><span><strong>Send</strong></span></a></li>
						</ul>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>


<div id="templateSMSToaster" class="cssSMSToaster jsSMSToaster">
	<div class="cssSMSToasterHold">
	<div class="yellowTop"></div>
	<div class="title"><?php echo addslashes($this->translate("New SMS")) ?></div>
	<div class="from" style="padding-left: 10px;"></div>
	<div class="newSMSmessage"></div>
	<div class="buttonsPanel">
		<div class="buttonLeftEdge buttonViewSMS" pid="" oid="">
			<div class="buttonRightEdge">
				<ul>
					<li title="Close" class="phone-btn-grey SMSToasterMainButton"><a><span><strong>Close</strong></span></a></li>
				</ul>
			</div>	
		</div>
	</div>
	<div class="yellowBottom"></div>
</div>
		</div>

		<div id="templateCALLToaster" class="cssSMSToaster jsSMSToaster">
			<div class="cssSMSToasterHold">
			<div class="yellowTop"></div>
			<div class="title"><?php echo addslashes($this->translate("Incoming Call")) ?></div>
			<div class="accept-call" style="padding-top:10px;">
				<div class="photo">
					<img class="phoneRemoteImg" src="<?php echo $this->siteBaseUrl . 'images/themes/' . $this->UserSettings['cssStyleTheme'] . '/contact-photo.png' ?>" />
				</div>
				<div class="call-info">
					<div class="phoneRemoteName">Unknown</div>
					<div class="phoneRemoteNumber">0000000</div>
					<div class="phoneCallStatus"></div>
				</div>
				<div class="phoneCallStatus2" class="displayNone">&nbsp;</div>
				<div class="callNotifyIncomingphoneButtonArea" style="text-align:center;">	
					<ul style="margin: 0;">
							<li title="Answer" class="buttonAnswer"><a><span><strong>Answer</strong></span></a></li>
							<li title="Ignore" class="buttonIgnore"><a><span><strong>Ignore</strong></span></a></li>
							<?php /*<li title="Busy" class="buttonBusy"><a><span><strong>Busy</strong></span></a></li> */ ?>
					</ul>
				</div>
			</div>
			<div class="yellowBottom"></div>
		</div>
			</div>

<script language="Javascript">
	var $toaster = null

	/**
	 * detect phone number inside and format the phone number with div
	 * skip url
	 *
	 * @param message
	 * @return {String}
	 */
	function formatMessage(message) {
		if(!message) return '';

        message = message.replace(/\n/g, '<br>');

        message = message.replace(/ /gi, '&nbsp;');

		if( /https?\:\/\//.test(message) ) {
			return message;
		}

		return $phone.wrapPhoneNumbersInDivClass(message);
	}

	function isPhoneConnected() {
		
		if(!$phone) return false; 
		
		var status = $phone.params.flashConnectorHandle.getInfoAboutMe();
		return status['logged']==true? true : false;
	}	
	
	function showHideNoMessagesAtSummaryRow(show)
	{
		show? $('.jsSummaryRowNoMessages', "#messageList").show() : $('.jsSummaryRowNoMessages', "#messageList").hide()
	}

	function updateTotalUnread(pid)
	{
		totals = getUnreadCount( getLocalServiceData('SMS', pid) )
		$phone.notifyUIOfUnreadSMS(totals)
	}

	function getUriFromFistLog()
	{
		folder = getSelectedCallFolder()
		uri = null

		if(folder=='SMS') 
		{
			if( $('.cssDetailRow:first', '#Email').hasClass("smsOutgoing") )
				uri = $('.cssDetailRow:first', '#Email').attr('dst')	// TODO: should add .smsIncoming to filter after inbound/outbound implemented
			else
				uri = $('.cssDetailRow:first', '#Email').attr('src')	// TODO: should add .smsIncoming to filter after inbound/outbound implemented
				
		}
		else if(folder=='CDR') {
			if( $('.cssDetailRow:first', '#Email').hasClass("callOutgoing") )
				uri = $('.cssDetailRow:first', '#Email').attr('dst')
			else
				uri = $('.cssDetailRow:first', '#Email').attr('src')
		}

		return uri
	}

	function onTopRightMenuCall()
	{
		jsddm_close();

		uri = getUriFromFistLog();
		uri && $phone.initiateOutboundUICall(uri)
	}

	function onTopRightMenuSMS()
	{
		jsddm_close();

		uri = getUriFromFistLog();
		uri && $phone.newIM(uri)
	}

	function onTopRightMenuAddContact()
	{
		jsddm_close();

		uri = getUriFromFistLog();
		uri && $phone.addToContacts(uri)
	}

	function existFilteredItem(searchBase, item)
	{
		if(!item || !searchBase) return false
		return searchBase.toLowerCase().indexOf(item.toLowerCase())>=0
	}

	function withinDuration(searchBase, goBack)
	{
		if(!goBack) return true;
		startTime = Date.now()/1000 - 1296000 * goBack;		// 1296000 is 1 month in seconds
		return searchBase? searchBase-0 >= startTime : false
	}

	function existFilteredContents(data, filter)
	{
		if(filter==undefined) return true;
		
		var simple_result = existFilteredItem(data.message, filter.any) ||
				existFilteredItem(data.target_name, filter.any) ||
				existFilteredItem(data.source_name, filter.any) ||
				existFilteredItem(data.src, filter.any) ||
				existFilteredItem(data.dst, filter.any)


		var advance_result = (existFilteredItem(data.message, filter.body) ||
				existFilteredItem(data.target_name, filter.to) ||
				existFilteredItem(data.source_name, filter.from) ||
				existFilteredItem(data.dst, filter.to) ||
				existFilteredItem(data.src, filter.from) 
			) && withinDuration(data.initUnixGMT, filter.goBack)

		return simple_result || advance_result
	}

	function getSearchData(dataPacket, filter)
	{
		result = $.extend(true, {}, dataPacket);

		result.localDataNode.serviceData = []

		for(var i in dataPacket.localDataNode.serviceData)
		{
			data = dataPacket.localDataNode.serviceData[i]
			if(existFilteredContents(data, filter)) {
				result.localDataNode.serviceData.push(data)
			}
		}

		return result;
	}

	function getSmsLocalData()
	{
		var pid = $phone.getPid()
		var folder = 'SMS'
		var dataSourceUrl = "<?php echo $this->appBaseUrl ?>/api/unify/getSummary/folder/wall"
		var dataSourceParams = {
			pid : pid,
			folder : folder,
			limit : "500"
		}

		return $.localData.getLocalData(dataSourceUrl, dataSourceParams, $.localData.dataStore["pid"+pid].folders[folder]);
	}

	function searchCallLog()
	{
		var folder = getSelectedCallFolder();
		if(folder!='SMS' || $('.cssSummaryRow:first','#messageList').length==0)
			return;

		var filter = {
			any:	$('#searchQuery','#search_anything').attr('value'),
			from:	$('#advSearch input[name=from]').attr('value'),
			to:		$('#advSearch input[name=to]').attr('value'),
			body:	$('#advSearch input[name=body]').attr('value') || $('#advSearch input[name=subject]').attr('value'),
			goBack: $('#advSearch select[name=goBack]').val()
		}

		$('#searchQuery','#search_anything').attr('value','')
		$('#advSearch input[name=from]').attr('value','')
		$('#advSearch input[name=to]').attr('value','')
		$('#advSearch input[name=body]').attr('value','')
		$('#advSearch input[name=subject]').attr('value','')
		var dataPacket = getSmsLocalData()
		var dataFiltered = getSearchData(dataPacket, filter)

		if(dataFiltered.localDataNode.serviceData.length == 0)
		{
			console.error('Content was not found!  --templateSMS.pthml:385');
			return;
		}

		lastTabNumber++
		tabLabel = "Search";
		var searchOffset = $("#search_anything").offset();
		var lastTabOffset = $('ul#navMessages li:last').offset();
		var lastTabWidth =  $('ul#navMessages li:last').width()
		//TODO: browser style non-fitting tabs dropdown, currently oldest tab is dropped/removed
		if( (searchOffset.left - lastTabOffset.left - lastTabWidth) < 190 )
			$('div#navMessages').tabs('remove', 1)

		$('div#navMessages').tabs('add','#searchResultsTab' + lastTabNumber, tabLabel)
		$('#searchResultsTab' + lastTabNumber).addClass('viewmessageTab')


		$('#searchResultsTab' + lastTabNumber).bind('tabSelected', function() {

			//enableMailActions();

		});
		$('#searchResultsTab' + lastTabNumber).trigger('tabSelected')
		$('#searchResultsTab' + lastTabNumber).html('<div id="primary_header" class="loading"><h1>' + jsTranslate("Searching...") + '</h1></div><div id="primary_content"></div>');
		$('#searchResultsTab' + lastTabNumber + ' #primary_content').block({ message: "<h1 class='loading-text'><img class='loadingimg' src='" + siteBaseUrl + "images/25.gif' width='28' height='28'/><span class='loading'>Loading...</span></h1>", overlayCSS: {backgroundColor: 'transparent', opacity: 0.4}, css: {backgroundColor: 'transparent',color: '#575757',border: '0'} });

		var sanitized_array = $('#searchForm').serializeArray();
		for ( var i in sanitized_array )
		{
			// do a quick xss sanitize
			sanitized_array[i].value = sanitized_array[i].value.replace(/\</g, "");
			sanitized_array[i].value = sanitized_array[i].value.replace(/\>/g, "");
			sanitized_array[i].value = sanitized_array[i].value.replace(/'/g, "");
			sanitized_array[i].value = sanitized_array[i].value.replace(/"/g, "");
			sanitized_array[i].value = sanitized_array[i].value.replace(/\\/g, "");
		}

		var $contextMain = $('#searchResultsTab' + lastTabNumber)

		$.templateEngine.templates.SIP.SMS.render($contextMain, dataFiltered)

                if(filter.any)          $('.cssMainBody', $contextMain).highlight(filter.any)
                if(filter.body)         $('.cssMainBody', $contextMain).highlight(filter.body)
                if(filter.from)         $('.cssMainBody', $contextMain).highlight(filter.from)
                if(filter.to)           $('.cssMainBody', $contextMain).highlight(filter.to)

                if(filter.any)          $('.jsMainHeaddingName', $contextMain).highlight(filter.any)
                if(filter.body)         $('.jsMainHeaddingName', $contextMain).highlight(filter.body)
                if(filter.from)         $('.jsMainHeaddingName', $contextMain).highlight(filter.from)
                if(filter.to)           $('.jsMainHeaddingName', $contextMain).highlight(filter.to)

		return;
	}

	function closeToaster(fadeOut)
	{
		if(!fadeOut)
		{
			if( $toaster != undefined && $toaster != null )
			{
				$toaster.remove();
				$toaster = null;
			}
		}
		else
		{
			if( $toaster != undefined && $toaster != null )
			{
				$toaster.fadeOut(3000, function(){
					if( $toaster == null )
						return
					if( $toaster != undefined && $toaster != null )
						$toaster.remove();
					$toaster = null;
				});
			}
		}
	}

	function updateLogStatus(logObj, callback)
	{
		$.ajax(
		{
			url: "<?php echo $this->appBaseUrl ?>/api/unify/ucdbput",
			method: 'POST',
			dataType: 'json',
			data : logObj,
			success: function(response, type)
			{
				// Update Local data
				updateLocalServiceData('SMS', logObj.pid, logObj)
				
				callback && callback(response)
			}
		})

	}

	//List bindings
	$(function() {

		$(".tooltipCall", ".sms-tooltip").bind("mousedown", function() 
		{ 
			
			var oid = $(this).parent().parent().parent().parent().parent().parent().parent().qtip("api").elements.target.attr("oid")
			
			if( oid == undefined )
				var uri = $(this).parent().parent().parent().parent().parent().parent().parent().qtip("api").elements.target.text()
			else if( $(".jsDetailRow[oid=" + oid + "]").hasClass("smsOutgoing") )
				var uri = $(".jsDetailRow[oid=" + oid + "]").attr("dst")
			else
				var uri = $(".jsDetailRow[oid=" + oid + "]").attr("src")
			$phone.initiateOutboundUICall( uri )
			$(this).parent().parent().parent().parent().parent().parent().parent().qtip("hide");


			return false
		
		})
		$(".tooltipSms", ".sms-tooltip").bind("mousedown", function() 
		{ 
			
			var oid = $(this).parent().parent().parent().parent().parent().parent().parent().qtip("api").elements.target.attr("oid")
			
			if( oid == undefined )
				var uri = $(this).parent().parent().parent().parent().parent().parent().parent().qtip("api").elements.target.text()
			else if( $(".jsDetailRow[oid=" + oid + "]").hasClass("smsOutgoing") )
				var uri = $(".jsDetailRow[oid=" + oid + "]").attr("dst")
			else
				var uri = $(".jsDetailRow[oid=" + oid + "]").attr("src")

			$phone.newIM( $phone.humanize(uri) )
			$(this).parent().parent().parent().parent().parent().parent().parent().qtip("hide");
			return false

		})

		$(".tooltipNewContact", ".sms-tooltip").bind("mousedown", function() 
		{ 
			
			var oid = $(this).parent().parent().parent().parent().parent().parent().parent().qtip("api").elements.target.attr("oid")
			if( oid == undefined )
				var uri = $(this).parent().parent().parent().parent().parent().parent().parent().qtip("api").elements.target.text()
			else if( $(".jsDetailRow[oid=" + oid + "]").hasClass("smsOutgoing") )
				var uri = $(".jsDetailRow[oid=" + oid + "]").attr("dst")
			else
				var uri = $(".jsDetailRow[oid=" + oid + "]").attr("src")

			$phone.addToContacts( $phone.humanize(uri) )
			$(this).parent().parent().parent().parent().parent().parent().parent().qtip("hide");
			return false

		})
		
		$('#templateSMSMain #jsddm > li').bind('mousedown', jsddm_open)
		
		$.templateEngine.templates.SIP.SMS = { 
			_thisTemplate : this, 
			debug : false, 
			log : function(what) { if(this.debug) console.log(what) }, 
			contactsIdsHash : {"+61000000000" : 41}, 																						//cached hash of contacts numbers to ContactIds.  TODO: refactor into contacts once contacts refactored into json/template system
			contactsHash : { "contactId41" : {"UserFirstName" : "Allan Bojangles"} }, 														//cache of contacts. TODO: refactor into contacts once contacts refactored into json/template system
			SMSDraft : '', 
			SMSDraftTo : '', 
			inlineSMSDraft : '', 
			inlineSMSDraftTo : '', 
			matchContactsFromNumbersAsync : function($contextMain, numbersToMatch, callback )
			{
				
				if( numbersToMatch == undefined )
					throw  "$.templateEngine.templates.SIP.SMS.matchContactsFromNumbersAsync: you must specify numbersToMatch"
				//build complete list of contacts numbers and pass to server for processing into matched contacts data result
				//synchronous because needed
				//this.log(dataPacket)
				_thisTemplate = this
				$XMLHttpRequestObject = $.get("<?php $this->siteBaseUrl ?>/api/contact/searchByNumbers", {numbersToMatch:numbersToMatch}, function(response, textStatus) 
				{

					//_thisTemplate.log("entering processing response from the server")
					_thisTemplate.log(dataSourceParams)
					_thisTemplate.log( response )
					if( response.result == "false")
					{
						_thisTemplate.log("Request succeeded, but action failed with error: " + response.noteEnglish)
						$(".jsMainHeadding", $contextMain).removeClass("loading")
						return
					}	
					else if( response.data == undefined )
					{
						_thisTemplate.log( "unexpected data in response, returning without modifying data in local store: " )
						$(".jsMainHeadding", $contextMain).removeClass("loading")
						_thisTemplate.log(response)
						return
					}
					
					//CONSIDER: update contactsIdsHash and contactsHash instead of replace
					_thisTemplate.contactsIdsHash = response.contactsIdsHash
					_thisTemplate.contactsHash = response.contactsHash
					
					//TODO: decide how to handle multiple simultaneous get requests
					//$.templateEngine.templates[responseDataNode.serviceType][responseDataNode.serviceName].dataUpdated($callbackContext, dataPacket)
					if( callback != undefined  )
						callback($contextMain)
					$(".jsMainHeadding", $callbackContext).removeClass("loading")

				},"json")

			}, 
			updateUIWithContactMatches : function($contextMain)
			{
				
				//takes results from matchContactsFromNumbersAsync and updates ui
				
			},
			renderDummy : function($contextMain, dataPacket)
			{
				
				//can be used for any dummy setup required to show dumme content while devving the template
				
			}, 
			showFolderToaster : function($contextUnused, pid, oid, messageFrom, messageBody, toasterTitle )
			{
				
				/*
				<div id="templateSMSToaster" class="cssSMSToaster jsSMSToaster">
					<div class="yellowTop"></div>
					<div class="title"></div>
					<div class="from"></div>
					<div class="message"></div>
					<div class="buttonsPanel"><div class="buttonLeftEdge buttonViewSMS" pid="" oid=""><div class="buttonRightEdge">View SMS</div></div></div>
					<div class="yellowBottom"></div>
				</div>
				
				*/
				closeToaster();
				$toaster = $("#templateSMSToaster").clone().removeAttr("id") //TODO: rename templateSMSToaster to templateToaster (general use now)
				$toaster.hide()
				$(".buttonViewSMS", $toaster).attr("pid", pid)
				$(".buttonViewSMS", $toaster).attr("oid", oid)
				var $from = $(".from", $toaster)
				var humanizedMessageFrom = $phone.humanize(messageFrom)
				$from.html(humanizedMessageFrom)
				$.ajax({
					url: moduleBaseUrl + "/contacts/whois/search/" + humanizedMessageFrom,
					method: 'GET',
					dataType: 'json',
					success: function(data, type) 
					{
						if( data.result == 'found' && data.name != 'Unknown' )
							$from.html(data.name)
					}
		        });
				
				$(".newSMSmessage", $toaster).html(messageBody)
				
				if( toasterTitle != undefined )
					$(".title", $toaster).html(toasterTitle)
				$("#header").after($toaster)
				$toaster.show()
				$(".SMSToasterMainButton", $toaster).bind("click", function() { $(this).parent().parent().parent().parent().parent().parent().remove()  })
				setTimeout( function() { closeToaster(true) }, 8000 );

				if(getSelectedCallFolder() == 'SMS') {
					setTimeout(function() {
							$phone.refreshLog('SMS');
						}, 1000);
				}
				
			}, 
			setNameAndPictureOnIncomingCallToaster : function(callInfo, resultObj)
			{
				
				if( resultObj.name == 'Unknown' || resultObj.result == "not found" ) 
				{
				
					resultObj.name = ''
					
				}
				else
				{
				
					$('.phoneRemoteImg', $toaster).attr('src', resultObj.imageUrl)
					$('.phoneRemoteName', $toaster).html('<b>' + resultObj.name + '</b>' )
					
				}
				
			},
			
			showIncomingCallToaster : function(callObject)
			{
				closeToaster();

				$toaster = $("#templateCALLToaster").clone().removeAttr("id")
				$toaster.hide()

				
				// check 
				// $ajax
				// $phone.humanize(callObject.callInfo.caller)
				if( callObject.callInfo.visibleNameCaller != undefined && callObject.callInfo.visibleNameCaller && callObject.callInfo.visibleNameCaller.indexOf("Callback") != -1 )
				{

					callbackName = callObject.callInfo.visibleNameCaller.substring(0,callObject.callInfo.visibleNameCaller.indexOf("Callback"))
					$(".phoneRemoteName", $toaster).html( callbackName )
					$(".phoneRemoteNumber", $toaster).html( "Callback" )

				}
				else
				{
				
					searchString = $phone.humanize(callObject.callInfo.caller)
					$phone.searchForContact(searchString, callObject.callInfo, this.setNameAndPictureOnIncomingCallToaster)
					$(".phoneRemoteNumber", $toaster).html( $phone.humanize(callObject.callInfo.caller) )
					$(".phoneRemoteName", $toaster).html(callObject.callInfo.visibleNameCaller || $phone.humanize(callObject.callInfo.caller) )
				
				}
				$(".buttonIgnore", $toaster).bind("click", callObject['ignore']);
				$(".buttonAnswer", $toaster).bind("click", callObject['answer'])
				//$(".buttonBusy", $toaster).bind("click", callObject['busy'])
				

				$toaster.show()
				$("#header").after($toaster)
			}, 
			sendSMS : function(rawToURIString, message)
			{
				if($phone.params.flashConnectorHandle.sendMessage == undefined) {
					alert('Send Message failed. No connection to webphone server');
					return
				}

				recipientsInputSIPURIFormatArray = $phone.getBasicSIPURIArrayFromRawInput(rawToURIString.toLowerCase())//.join(",")
				if( recipientsInputSIPURIFormatArray.join(",").length < 3 )
				{
					alert("Recipients list appears to be empty. Please specify recipient(s).")
					return false
					
				}
				var maxRecipients = 30
				if( recipientsInputSIPURIFormatArray.length > maxRecipients )
				{
					
					alert("You can not send and SMS to more than " + maxRecipients + " recipients. Please revise your recipients.")
					return false
					
				}

				if( !message.length )
				{
					
					alert("You cannot send a blank message. Please specify a message to send.")
					return false
					
				}
				var maxRecipientsPerSend = 30
				
				var recipientsChunks = chunk(recipientsInputSIPURIFormatArray, maxRecipientsPerSend)
				this.log("sending")
				
				$.each( recipientsChunks, function( index, row) 
				{
				
					recipientsInputSIPURIFormat = recipientsChunks[index].join(",")
					messageObject = {
						id: $phone.generateUUID(), 
						to: "sip:adhoc@myimsserver.com", 
						recipients: recipientsInputSIPURIFormat, 
						body: message, 
						contentType: "multipart/mixed", 
						deliveryNotification: true
					}
					
					$phone.params.flashConnectorHandle.sendMessage(messageObject)
				
				
				})
				
				//update localData
				return true
				
			},
			renderComposer : function($contextMain, dataPacket)
			{
				
				// New SMS Composer
				_thisTemplate = this
				if( getSelectedCallFolder() != 'SMS' )
					return;
				
				//render complete panel with composer (i.e. clicking new sms from outside the SMS view context)
				var pid = $phone.params.pid
				dataPacket.suppressRenderingDetails = true
				dataPacket.suppressRenderingDetails = undefined
				delete dataPacket.suppressRenderingDetails
				
				$(".jsMainDetailsPanel", $contextMain).parent().parent().children(".jsMainHeadding").find(".jsMainHeaddingName").html("New SMS")
				
				$(".jsSummaryRow", $contextMain).removeClass("selected")
				$mainSMSComposer = $("#templateSMSComposer").clone().removeAttr("id")
				
				//reset send button from last disabled.
				//$(".buttonSend", $mainSMSComposer).attr("disabled","true").css("opacity","0.4")
				$button_send = $(".buttonSend", $mainSMSComposer)

				//Hitting enter button sends message
				$button_send.parent().parent().find(".SMSComposerMessageInput").unbind().bind('keypress', function(e)
				{
					if(e.keyCode == '13' && e.ctrlKey) {
						$button_send.click()
					}
				})

				$button_send.unbind().bind('click', function()
				{
					if( !isPhoneConnected() ) {
						alert("Sorry, your message was not sent. There may be something wrong with your network. Please try again later.");
						return;	
					}
					
					if( $(this).attr("disabled") == 'true' )
						return false

					$(".cssSMSMainPanel:last").block({ message: '<h1 class="loading-text" style="position: relative; top: 300px;left:250px;"><img class="loadingimg" src="' + siteBaseUrl + 'images/25.gif" width="28" height="28" /><span class="loading">Sending...</span></h1>', overlayCSS: {backgroundColor: "transparent", opacity: 0.4}, css: {backgroundColor: "transparent",color: "#575757",border: "0"} });
					var recipientsInput = $(this).parent().parent().parent().parent().parent().find(".SMSComposerToInput").attr("value")
					$input_box = $(this).parent().parent().find(".SMSComposerMessageInput")
					var message = $input_box.attr("value")
										
					$(this).attr("disabled","true").css("opacity","0.4")
					$('.jsMainHeadding', '#messageList').addClass('loading')
					success = _thisTemplate.sendSMS(recipientsInput, message)
					if( success )
					{

						$input_box.attr("value", '')
						setTimeout( '$(".jsServiceProvider[folder=SMS]:last").trigger("click")',4000);
						_thisTemplate.SMSDraft = ""
						_thisTemplate.SMSDraftTo = ""
						
					}
					else
					{
						$(this).attr("disabled","false").css("opacity","1")
						$('.jsMainHeadding', '#messageList').removeClass('loading')
					
					}
					setTimeout( '$(".cssSMSMainPanel:last").unblock();',3500);

				})
				
				//prepare any existing values in the to field (e.g. when composer poped by another event)
<?php $this->autocompleteSMSCacheSize = 50; ?>
<?php $this->autocompleteSMSMinFetchLength = 3; ?>
<?php $this->autocompleteSMSFetchThreshold = 10; ?>
<?php $this->autocompleteSMSFetchSize = 10; ?>
				// TextboxList and autocompleteSMS initialization prepopulated with any saved-draft addresses
				//empty old value in prep for autocompleteSMS etc.
				$('.SMSComposerToInput', $mainSMSComposer).attr('value', '');
				//initialize TextboxList on input
				var SMSToTextBoxListHandle = new TextboxList(  $('.SMSComposerToInput', $mainSMSComposer), 
				{
					bitsOptions:{ editable:{addOnBlur:true } }, 
					unique: true, 
					plugins: {autocomplete: {placeholder:false,cacheSize: <?php echo $this->autocompleteSMSCacheSize; ?>}}, 
					requireValidEmailOnBlur: false
				
				})
				SMSToTextBoxListHandle.addEvent("blur", function() { _thisTemplate.SMSDraftTo = $('.SMSComposerToInput', $mainSMSComposer).attr("value") })
				SMSToTextBoxListHandle.addEvent("bitRemove", function() { _thisTemplate.SMSDraftTo = $('.SMSComposerToInput', $mainSMSComposer).attr("value") })
				
				// Support clicking anywhere in the div box to get to the last "bitbox selection"
				$('.SMSComposerToInput', $mainSMSComposer).bind('click', function() { $(".textboxlist-bit-editable-input:last", $(this) ).focus(); })
				
				//$.jCacher.clear('autocompleteSMS');
				if( $.jCacher.get('autocompleteSMS') )
				{

					autocompleteSMS_values = $.jCacher.get('autocompleteSMS').value;
					SMSToTextBoxListHandle.plugins['autocomplete'].setValues( autocompleteSMS_values )

				}
				else
				{

				    $.ajax({
						cache:false, 
						url: '<?php echo $this->moduleBaseUrl ?>/contacts/autocomplete/need/sms/limit/<?php echo $this->autocompleteSMSFetchThreshold; ?>', 
						dataType: 'json', 
						success: function(r) 
						{
							SMSToTextBoxListHandle.plugins['autocomplete'].setValues(r)
							$.jCacher.add('autocompleteSMS', r, 3600)
						}
					})


				}
				SMSToTextBoxListHandle.plugins['autocomplete'].setOptions( 
				{
					placeholder: false,
					cacheSize: <?php echo $this->autocompleteSMSCacheSize; ?>,
					minRemoteLength: <?php echo $this->autocompleteSMSMinFetchLength; ?>,
					queryRemote: true,
					remote: {url: '<?php echo $this->moduleBaseUrl ?>/contacts/autocomplete/need/sms/limit/<?php echo $this->autocompleteSMSFetchSize; ?>'}
				})
				

				//for prepopulated composer pop
				if( dataPacket.dataSourceParams != undefined && dataPacket.dataSourceParams.toNumber )
					toNumber = dataPacket.dataSourceParams.toNumber
				else if( _thisTemplate.SMSDraftTo.length > 0 )
					toNumber = _thisTemplate.SMSDraftTo
				else
					toNumber = ""
				//$(".SMSComposerToInput", $mainSMSComposer).attr("value", toNumber )
				
				SMSToArray = activeSplit( toNumber );
				for(var rcpt in SMSToArray) 
				{
					value = SMSToArray[rcpt];
					if( value.length > 3 )
						SMSToTextBoxListHandle.add(value);
				}
				
				if( dataPacket.dataSourceParams && dataPacket.dataSourceParams.messageBody )
					this.SMSDraft = dataPacket.dataSourceParams.messageBody

				//if an unsent draft text exists, then repopulate it (clear it when sending)
				if( this.SMSDraft != undefined && this.SMSDraft.length > 0 )
					$('.SMSComposerMessageInput', $mainSMSComposer).attr("value", this.SMSDraft)
				if( this.SMSDraftTo != undefined && this.SMSDraftTo.length > 0 )
					$('.SMSComposerToInput', $mainSMSComposer).attr("value", this.SMSDraftTo)
				
				$('.SMSComposerMessageInput', $mainSMSComposer).bind("keyup", function() { _thisTemplate.SMSDraft = $(this).attr("value") })
				$('.SMSComposerToInput', $mainSMSComposer).bind("keyup", function() { _thisTemplate.SMSDraftTo = $(this).attr("value") })
				
				$(".jsMainDetailsPanel", $contextMain).html( $mainSMSComposer )
				//$(".jsMainDetailsPanel .SMSComposerMessageInput", $contextMain).focus()
				//hide recipient options if composing new
				if( dataPacket.dataSourceParams.suppressRecipientActions != undefined && dataPacket.dataSourceParams.suppressRecipientActions == true )
					$contextMain.find(".jsSMSActionMore").hide()
				$('.textboxlist-bit-editable-input',$contextMain).focus();
				
			}, 
			renderInlineComposer : function( $contextMain, to )
			{
				
				_thisTemplate = this
				//render inline composer into a visible thread
				if( $(".jsMainDetailsPanel:last .cssSMSComposer", $contextMain).length > 0 )
					return;
				var $inlineSMSComposer = $('.SMSComposerMessageViewPanel','#messageList');
				if(!$inlineSMSComposer.length) 
				{
					$inlineSMSComposer = $("#templateSMSComposer .SMSComposerMessagePanel:first").clone().removeAttr("id");
					$inlineSMSComposer.attr("class", "SMSComposerMessageViewPanel");
				}

				$hiddenToField = $('.SMSComposerToInput', $inlineSMSComposer);
				if(!$hiddenToField.length) 
				{
					$hiddenToField = $("#templateSMSComposer .SMSComposerToInput").clone().hide();  //.attr("type", "hidden") //IE Security cant hide visible a form input
					$inlineSMSComposer.append($hiddenToField);

				}

				$hiddenToField.attr("value", to)
				_thisTemplate.inlineSMSDraftTo = to

				$button_send = $(".buttonSend", $inlineSMSComposer);

                //Hitting enter button sends message
				$button_send.parent().parent().find(".SMSComposerMessageInput").unbind().bind('keypress', function(e)
				{
					if(e.	keyCode == '13' && e.ctrlKey)
						$button_send.click()
				})
				_this = this
				$button_send.unbind().bind('click', function()
				{
					if( !isPhoneConnected() ) {
						alert("Sorry, there may be something wrong with your network. Please try again later");
						return;	
					}
					
					if( $(this).attr("disabled") == 'true' )
						return false;
					
					$(".cssSMSMainPanel:last").block({ message: '<h1 class="loading-text" style="position: relative; top: 300px;left:250px;"><img class="loadingimg" src="' + siteBaseUrl + 'images/25.gif" width="28" height="28" /><span class="loading">Sending...</span></h1>', overlayCSS: {backgroundColor: "transparent", opacity: 0.4}, css: {backgroundColor: "transparent",color: "#575757",border: "0"} });
					$(this).attr("disabled","true").css("opacity","0.4");
					setTimeout(function() { $button_send.attr('disabled','').css('opacity','1.0'); }, 500);
			
					$('.jsMainHeadding', '#messageList').addClass('loading')

					//hook to ucdb goes here
					
					var recipientsInput = $(this).parent().parent().parent().find(".SMSComposerToInput").attr("value")
					var recipientsInputSIPURIFormat = $phone.getBasicSIPURIArrayFromRawInput(recipientsInput).join()
					if( recipientsInputSIPURIFormat.length < 3 )
					{
						alert("Recipients list appears to be empty. Please specify recipient(s).")
						return false
						
					}
					$input_box = $(this).parent().parent().find(".SMSComposerMessageInput")
					var message = $input_box.attr("value")
					if(!message)
						return false

					$input_box.attr("value", '')

					success = _thisTemplate.sendSMS(recipientsInput, message)
					if( success )
					{
						
						setTimeout( '$(".jsServiceProvider[folder=SMS]:last").trigger("click");',4000);
						_thisTemplate.inlineSMSDraft = ''
						_thisTemplate.inlineSMSDraftTo = ''
						
					}
					setTimeout( '$(".cssSMSMainPanel:last").unblock();',3500);
					
				})
				
				$('.SMSComposerToInput', $inlineSMSComposer).bind('click', function() { if( $(this).text() == $("#templateSMSComposer .SMSComposerToInput").text() ) $(this).focus() })
				
				//if an unsent inline draft text exists, then repopulate it (clear it when sending)
				if( this.inlineSMSDraft != undefined && this.inlineSMSDraft.length > 0 )
					$('.SMSComposerMessageInput', $inlineSMSComposer).attr("value", this.inlineSMSDraft)
				if( this.inlineSMSDraftTo != undefined && this.inlineSMSDraftTo.length > 0 )
					$('.SMSComposerToInput', $inlineSMSComposer).attr("value", this.inlineSMSDraftTo)
				
				$('.SMSComposerMessageInput', $inlineSMSComposer).bind("keyup", function() { _thisTemplate.inlineSMSDraft = $(this).attr("value") })
				
				$(".jsMainDetailsPanel:last", $contextMain).append( $inlineSMSComposer )
				
			}, 
			render : function($contextMain, dataPacket) //this renders the left hand summary, and then calls to render first details in right hand panel
			{ 

				_thisTemplate = this
				
				if( $(".mainPanel", $contextMain).attr("templateId") == undefined || $(".mainPanel", $contextMain).attr("templateId") != "SIP.SMS" ) // 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") )
				{
					
					this.update($contextMain, dataPacket)
					return
					
				}
				//<span style="left: 38%; position: relative; display: inline;" class="ViewMoreMessages">View 10 more messages</span>
				$contextMain.empty()
				$mainSMS = $("#templateSMSMain").clone(true).removeAttr("id")
				//empty out dummy data
				$(".jsSummaryRow", $mainSMS).remove()
				$(".jsDetailRow", $mainSMS).remove()
				$(".SMSComposerMessagePanel", $mainSMS).remove()
				
				$mainSMS.attr("serviceType", dataPacket.serviceType )
				$mainSMS.attr("serviceName", dataPacket.serviceName )
				$mainSMS.attr("folder", dataPacket.folder )
				var $uiContext = $contextMain.html( $mainSMS )
				var pid = dataPacket.pid
				var myId = dataPacket.myId || $.localData.dataStore["pid"+pid].myId || alert("templateSMS#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
				{
					
					serviceDataSummary = this.getSummaryData( dataPacket.localDataNode.serviceData )

					//window.open().document.body.innerHTML = "<pre>" + JSON.stringify(serviceDataSummary,null, 4) + "</pre>";
					$.each( serviceDataSummary, function( index, row) 
					{
					
						_thisTemplate.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.renderMethod != undefined && dataPacket.renderMethod == "renderComposer") || (dataPacket.dataSourceParams != undefined && dataPacket.dataSourceParams.renderMethod != undefined && dataPacket.dataSourceParams.renderMethod == "renderComposer") )
					{
						
						this.renderComposer($contextMain, dataPacket)
						
					}
					else if( serviceDataSummary.length > 0 && (dataPacket.suppressRenderingDetails == undefined || dataPacket.suppressRenderingDetails == false) )
					{

						//this.log("calling renderDetailsAction")
						var firstRow = serviceDataSummary[0]
						var oid = firstRow.id
						//this.log( "templateSMS#373::update: about to call renderDetailsAction on: " + pid + ":" + folder + ":" + oid )
						details = _thisTemplate.getDetailsFromSummaryId( pid, folder, oid)
						this.renderDetailsAction($contextMain, pid, myId, folder, oid, details)
						//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 SMS render and calling renderCompleteCallback()") 
				this.renderCompleteCallback()
				
			},
			renderCompleteCallback : function() { 
				/* this.log("renderCompleteCallback called") */ 

				setTimeout(function() {
					if($('.textboxlist-bit-box-deletable','#messageList').length>0)
					{
						$('input.SMSComposerMessageInput', '#messageList').focus();
					}
					else
					{
						$('.textboxlist-bit-editable-input','#messageList').focus();
					}

				}, 500)


			},
			getURIArray : function( rawString ) {
				
			}, 
			getSummaryData : function( data )
			{
				//if(!assertFolder('SMS'))
				//	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) )
						{
							foundInLatest = true
							if(row.initUnixGMT>row.initUnixGMT) {
								latestData[i2] = row
							}

							if(isUnread(row)) {
								++latestData[i2].countOfUnread;
							}
							return false // === Break each
						}
							
					})
					//if we get to here and foundInLatest == false then add it
					if( !foundInLatest ) 
					{
						row.countOfUnread = isUnread(row)? 1 : 0
						latestData[latestData.length] = row
					}
				
				}
				//this.log(latestData)
				return latestData.sort(function(a, b){
					return b.initUnixGMT - a.initUnixGMT;
				})
				
			},

			getDetailsFromSummaryId : function( pid, folder, oid ) 
			{
				
				_thisTemplate = this
				var serviceData = []
				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[serviceData.length] = row
					
				
				})
				return serviceData.reverse()
				
			}, 
			renderDetailsAction : function($contextMain, pid, myIds, folder, oid, details) 															// action used to render details view by id
			{
			
				//this.log( "renderDetailsAction #341: renderDetailsAction" )
				//this.log( 'templateSMS.phtml #696: pid, myId, folder, oid:' )
				//this.log( pid + ":" + myIds + ":" + folder + ":" + oid )
				
				//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
				//this.log( 'templateSMS.phtml #699: details:' )
				//this.log( details )
				
				
				var dataPacket = { pid : pid, folder : folder, localDataNode : {serviceData : details} }
				this.renderDetails($contextMain, dataPacket)
			
			}, 
			renderDetails : function( $contextMain, dataPacket, isAppend, scrollBottom ) 																			//takes a dataPacket clears jaMainDEtailsPanel and then and renders in the details view
			{
				if(!assertFolder('SMS'))
					return;

				var row = dataPacket.localDataNode.serviceData[0];
				
				var DetailsHeader = $phone.makeDetailHeader(row);
				var title = $phone.makeDetailHeaderTitle(row);
				
				//this.log( "templateSMS.phtml #272: renderDetails" )
				//this.log(dataPacket)

				if(!isAppend) 
				{
				
					$(".jsMainDetailsPanel .jsDetailRow", $contextMain).remove()
					$(".jsMainDetailsPanel .cssSMSComposer", $contextMain).remove() //remove a composer if there is one
				
				}
				//else 
				//	$('span.ViewMoreMessages','#messageList').hide();
				
				$(".jsMainDetailsPanel", $contextMain).parent().parent().children(".jsMainHeadding").find(".jsMainHeaddingName").attr('title',title).html(DetailsHeader)
				//this.log( 'templateSMS.phtml #750: dataPacket.localDataNode.serviceData[0]:' )
				//this.log( dataPacket.localDataNode.serviceData[0] )

				this.pushDetailsRows( $contextMain, dataPacket, scrollBottom )
				if( !isOutbound(dataPacket.localDataNode.serviceData[0].src) )
					var to = dataPacket.localDataNode.serviceData[0].src
				else
					var to = dataPacket.localDataNode.serviceData[0].dst
				//this.log( 'templateSMS.phtml #758: to:' )
				//this.log( to )
				
				this.renderInlineComposer($contextMain, to)
			
			},
			pushDetailsRows : function( $contextMain, dataPacket, scrollBottom )
			{
				if(scrollBottom == undefined) 
					scrollBottom = true;
				
				if(!assertFolder('SMS'))
					return;
				
				//this.log( "templateSMS.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, true)
											
					})

					if(showMore) {
						$('span.ViewMoreMessages','#messageList').show().unbind().bind('click', function(){
							
							
							var $clientDiv = $('.jsMainDetailsPanelSMS',$contextMain);
							var currentClientHeight = $clientDiv[0].scrollHeight;
							var currentScrollPos = $clientDiv.scrollTop();
							
							increasePageIndex();
							$.templateEngine.templates.SIP.SMS.renderDetails($contextMain, dataPacket, true, false);
							
							var newHeight = $clientDiv[0].scrollHeight;
							var scrollOffset = newHeight-currentClientHeight+currentScrollPos;
							
							$clientDiv.scrollTop( scrollOffset );
						})
					}
					else {
						$('span.ViewMoreMessages','#messageList').hide()
					}
				
				}
				
				// Show delete comment
				$(function() {
				 $(".SMSRowDetails").hover(function() {
				  $(this).find(".deleteLog").show();
				  },function(){
				  $(this).find(".deleteLog").hide();
				 });
				});

				// scroll to bottom
				$detailsPanelSMS = $('.cssMainDetailsPanelSMS', '#messageList')
				if(scrollBottom) 
					$detailsPanelSMS.scrollTop( $detailsPanelSMS[0].scrollHeight )
				
			},
			pushDetailsRow : function( $context, dataPacket, row, prepend )
			{

				//Update read status
				if( isUnread(row) ) {
					row.readUnixGMT = unixTimeStamp()

					ajaxData = {
						pid: 	row.pid, 
						itemtype: 'sms',
						id:		row.id,
						state:	row.status,
						//src:	row.src,
						//dst:	row.dst,
						//source_name:	row.source_name,
						//target_name:	row.target_name,
						readUnixGMT:	row.readUnixGMT
					}

					updateLogStatus(ajaxData)
				}

				//this.log("pushDetailsRow")
				//this.log(dataPacket)
				//this.log(row)
				//this.log(prepend)
				//copy template details node, populate and insert into panel
				$newNode = $("#templateSMSDetailNodeGeneric").clone().removeAttr("id").removeClass("first")
				$newNode.hide()
				$newNode.attr("pid", row.pid)
				$newNode.attr("oid", row.id)
				$newNode.attr("src", row.src)
				$newNode.attr("dst", row.dst)
				$newNode.attr("srcAbookId", row.srcAbookId || "")
				$newNode.attr("dstAbookId", row.dstAbookId || "")
                                             
				// Render the content differently, depending on the type
				if( isOutbound(row.src) )
				{
					
					//Outgoing SMS
					$newNode.removeClass("smsIncoming")
					var device = ""
					switch(row.target_device)
					{
						case undefined:
						case "Unknown":
						case "":
							device = "";
							break;
						case "UserHomeMobile":
							device = " Home Mobile";
							break;
						case "UserWorkMobile":
							device = " Work Mobile";
							break;
						case "UserHomePhone":
							device = " Home Phone";
							break;
						case "UserWorkPhone":
							device = " Work Phone";
							break;
					}
					
					$(".SMSFrom", $newNode).remove()
					$(".incoming-sms-img", $newNode).remove()
					//if( device == undefined || device == null || device == "" )
					//	participantString = (row.dstNames==null?$phone.humanize(row.dst):row.dstNames)
					//else
					//	participantString = device
					participantString = "Me"
					$(".SMSTo", $newNode).html( participantString )
					$(".SMSTo", $newNode).attr("title", $phone.humanize(row.dst))
					
				}
				else
				{
					//Incoming call
					$newNode.removeClass("smsOutgoing")
					var device = ""
					switch(row.source_device)
					{
						case undefined:
						case "Unknown":
						case "":
							device = "";
							break;
						case "UserHomeMobile":
							device = " Home Mobile";
							break;
						case "UserWorkMobile":
							device = " Work Mobile";
							break;
						case "UserHomePhone":
							device = " Home Phone";
							break;
						case "UserWorkPhone":
							device = " Work Phone";
							break;
					}
					$(".SMSTo", $newNode).remove()
					$(".outgoing-sms-img", $newNode).remove()
					if( row.source_name != undefined && row.source_name != null && row.source_name != "" )
						participantString = (row.source_name==null?$phone.humanize(row.src):row.source_name)
					else
						participantString = device
					$(".SMSFrom", $newNode).html( participantString )
					$(".SMSFrom", $newNode).attr("title", $phone.humanize(row.src) )
					
				}
				//$(".SMSDevice", $newNode).remove()
				//$(".SMSFrom", $newNode).remove()
				//$(".SMSTo", $newNode).remove()
				$(".SMSMessage", $newNode).html( formatMessage(row.message) )
				if( row.receivedUnixGMT == undefined || row.receivedUnixGMT == null || row.receivedUnixGMT == "0" )
					row.receivedLocale = row.initLocale

				$(".SMSDeliveredDatetime", $newNode).html( unixTimeStampToTimeAgo(row.initUnixGMT) )
				
				// update the summary view
			        $summary = $(".cssSummaryRow[oid='" + row.id + "']",'#messageList')
                                if($summary.length)
                                {
                                        $date = $summary.find('.SMSSummaryDeliveredDatetime');
                                        if($date.length) $date.html( unixTimeStampToTimeAgo(row.initUnixGMT) )
                                }

				//$(".SMSDeliveredDatetime", $newNode).timeago();
				$(".Call", $newNode).unbind().bind("click", function() { $phone.initiateOutboundUICall($(this).attr("uri")) })
				$(".SMS", $newNode).unbind().bind("click", function() { $phone.newIM($(this).attr("uri")) })
				
				var _thisTemplate = this
				$(".deleteLog", $newNode).unbind().bind("click", function(e) {
					e.stopPropagation()

					var $rowToDelete = $(this).parent().parent()

					var pid = $rowToDelete.attr('pid')
					var folder = 'SMS'
					var oid = $rowToDelete.attr('oid')

					var $summaryRow = $('.cssSummaryRow[oid='+oid+']','#messageList')
					if( $summaryRow.length && dataPacket.localDataNode.serviceData.length>1)
					{
						// the summary id is bo be deleted.
						var newSummaryRow = dataPacket.localDataNode.serviceData[1]

						$summaryRow.attr('oid', newSummaryRow.id)
						$(".SMSSummaryMessage", $summaryRow ).html( newSummaryRow.message )
						
					}

					deleteLogItems(pid, folder, [oid] );

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

						if(!$('.SMSRow:visible','#messageList').length) {
							if($('.ViewMoreMessages','#messageList').css('display')=='inline') {
								$('.ViewMoreMessages','#messageList').click()
							}
							else {
								$summaryRow = $('.jsSummaryRow.selected','#Email')
								if($summaryRow.length ==  1) $summaryRow.fadeOut(600, function(){
									$(this).remove()
									resetSummaryFocus()
								})
							}
						}
					})

				})
				
				// Qtip for Call actions
				$newNode.qtip({

					//container: $context,
					//target: $newNode.find(".newCallType"), 
					content: $('.sms-tooltip:first'),
					//show: 'click',
					style: { background: 'transparent', border: 'none', name: 'dark' },
					position: { corner: 'topLeft', adjust: { screen:true, x: -47, y: 52 } }, 
					hide : { "when" : { target:$(document),"event" : "mousedown"} }, 
					show:{when:{event:"click"},solo:true}

				});
				$(".bodyMatchedPhoneNumber",$newNode).qtip({

					//container: $context,
					//target: $newNode.find(".newCallType"), 
					content: $('.sms-tooltip:first'),
					//show: 'click',
					style: { background: 'transparent', border: 'none', name: 'dark' },
					position: { corner: 'topLeft', adjust: { x: -50, y: 10 } }, 
					hide : { "when" : { target:$(document),"event" : "mousedown"} }, 
					show:{when:{event:"click"},solo:true} 

				})
				$(".bodyMatchedPhoneNumber",$newNode).bind("click",function(event) 
				{
				
					event.preventDefault();
					event.stopPropagation();
					return false
					
				})
				
				
					
				$(".SMSTime", $newNode).html(row.answerDate) //TODO: timeago
				//if this is the only one then add class first
				if( $(".jsDetailRow", $context).length == 0 ) 
					$newNode.addClass("first")
				//Apply status icon
				$(".SMSIcon img", $newNode).attr("class","");
				$(".SMSIcon", $newNode).attr("title","");
				var statusIconClass = ""
				var statusHint = "";
				switch(row.status)
				{
					case undefined:
					case "":
						break;
					case "INITIATED":
						statusIconClass = "sending";
						statusHint = "Sending SMS";
						break;
					case "SENT":
					case "ACCEPTED":
						statusIconClass = "accepted";
						statusHint = "SMS is in-transit and has arrived at our server. Depending on the receiver's network, the message may have already reached the receiver.";
						break;
					case "DELIVERED":
					case "RECEIVED":
						statusIconClass = "received";
						statusHint = "SMS successfully delivered to receiver!";
						break;
					case "READ":
						statusIconClass = "read";
						statusHint = "SMS successfully delivered to receiver!";
						break;
					case "FAILED":
						statusIconClass = "failed";
						statusHint = "Sorry, we were not able to send your SMS. Please check your network connection and your credit balance and try again.";
						break;
				}
				$(".SMSIcon img", $newNode).attr("class", statusIconClass)
				$(".SMSIcon", $newNode).attr("title", statusHint);

				$detail_row = $(".jsMainDetailsPanel .jsDetailRow:first", $context)
				if( prepend && $detail_row.length)
					$detail_row.before($newNode)
				else
					$(".jsMainDetailsPanel", $context).append($newNode)
					
				$newNode.show()
			}, 
			pushSummaryRows : function($contextMain, dataPacket) 
			{
				if(!assertFolder('SMS'))
					return;
				
				//this.log( "templateSMS.phtml::pushSummaryRows#287: dataPacket:" )
				//this.log( dataPacket )
				updateTotalUnread(pid);
				
				var pid = dataPacket.pid
				var myId = $.localData.dataStore["pid"+pid].myId
				var myDisplayName = $.localData.dataStore["pid"+pid].myDisplayName
				
				if( dataPacket.localDataNode.serviceData != undefined && dataPacket.localDataNode.serviceData.length>0)
				{
					
					_this = this
					$.each( dataPacket.localDataNode.serviceData, function(i,dataNode) 
					{ 
						
						//_this.log( "templateSMS.phtml #380: dataNode:" )
						//_this.log( dataNode )
						
						dataNode.pid = pid
						dataNode.myId = myId
						dataNode.myDisplayName = myDisplayName
						_this.pushSummaryRow($contextMain, dataPacket, dataNode, false)
						
					})
				
				}
				updateDeleteAction();
				
			},
			pushSummaryRow : function( $context, dataPacket, row, prepend )
			{
				if(!assertFolder('SMS'))
					return;

				$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("templateSMS#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("templateSMS#771: folder not defined")
				var oid = row.id || alert("#52X: error, trying to push a list item with no id")

				var myURIs = ["sip:" + $phone.params.userId + "@" + $phone.params.domain, "tel:" + $phone.params.phoneNumber]				//list of all URIs that log lines can match on
				// OK, so we have a message. Who is it from?
				if( row == null )
				{

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

				}

				showHideNoMessagesAtSummaryRow(false)

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

				$newNode.attr("pid", pid)
				$newNode.attr("oid", oid)
				$newNode.attr("src", $phone.getBasicSIPURIFromRawInput(row.src) )
				$newNode.attr("dst", $phone.getBasicSIPURIArrayFromRawInput(row.dst).join() )

				var pid = $newNode.attr("pid")
				var folder = $newNode.attr("folder") || $(".mainPanel", $contextMain).attr("folder") || alert("folder not defined")
				var oid = $newNode.attr("oid") || alert("oid not defined")
				//_thisTemplate.log( "about to call renderDetailsAction( pid=" + pid + ", myId=" + myId + ", folder=" + folder + " oid=" + oid + ")" )

				var details = _thisTemplate.getDetailsFromSummaryId( pid, folder, oid)
				var countOfUnread = getUnreadCount(details)
			
				// Render the content differently, depending on the type
				if( row.outbound == undefined )
				{
					//this.log(" trying to match " + row.src + " or " + row.dst + " to my URIs: " + myURIs.join(","))
					row.outbound = isOutbound(row.src)? "1" : "0";
				}
				if( row.dst == "undefined")
					row.outbound = "0"
				
				if( row.source_name == undefined || row.source_name == '' || row.source_name == 'Unknown' )
					row.srcName = $phone.humanize(row.src)
				else
					row.srcName = row.source_name
				
				if( row.target_name == undefined || row.target_name == '' || row.target_name == 'Unknown' )
					row.dstNames = $phone.humanize(row.dst)
				else
					row.dstNames = row.target_name
				
				$(".SMSSummaryType", $newNode).remove()
				$(".SMSSummaryDevice", $newNode).remove()
				var devicesHuman = ""
				if( row.outbound == "1" )
				{ 
					
					$newNode.addClass("outbound")
					var targets = row.dst.split(',')
					
					if(targets.length == 1) 
					{
						
						var deviceHuman = $phone.deviceName(row.target_device)
						if( deviceHuman ) 
							deviceHuman = ' ' + deviceHuman

						
					}
					else
						var deviceHuman = ""
						
					$(".SMSSummaryTo", $newNode ).html( "" + row.dstNames)
					$(".SMSSummaryTo", $newNode ).attr("title", $phone.humanize(row.dst) )
					
					if( deviceHuman == undefined || deviceHuman == 'Unknown' || deviceHuman == '' )
						$(".SMSSummaryDevice", $newNode ).remove()
					else
						$(".SMSSummaryDevice", $newNode ).html( deviceHuman )

					$(".SMSSummaryFrom", $newNode ).remove()
					
				}
				else
				{
					
					$newNode.addClass("inbound")
					var targets = row.dst.split(',')
					
					if(targets.length == 1) 
					{
						
						var deviceHuman = $phone.deviceName(row.source_device)
						if( deviceHuman ) 
							deviceHuman = ' ' + deviceHuman
							
					}
					else
						var deviceHuman = ""
						
					$(".SMSSummaryFrom", $newNode ).html( " " + row.srcName )
					$(".SMSSummaryFrom", $newNode ).attr("title", $phone.humanize(row.src) )
					
					if( deviceHuman == undefined || deviceHuman == 'Unknown' || deviceHuman == '' )
						$(".SMSSummaryDevice", $newNode ).remove()
					else
						$(".SMSSummaryDevice", $newNode ).html( deviceHuman )
					
					$(".SMSSummaryTo", $newNode ).remove()
					
				}

				//$(".startLocale", $newNode ).html( row.startLocale )
				timeDiff = Date.now()-row.initUnixGMT*1000
				timeAgo = timeDiff<86400000? $.timeago.inWords(timeDiff) : $.datepicker.formatDate('d M', new Date(row.initUnixGMT*1000));
				$(".SMSSummaryDeliveredDatetime", $newNode ).html( timeAgo )
				$(".SMSSummaryMessage", $newNode ).html( row.message )

				//add bindings for SMS and callback and delete row
				_thisTemplate = this
				$newNode.find('.smsCheckbox:checkbox').bind('click', function(e) { 
					e.stopPropagation()
					
					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()
					
					$(this).addClass("selected") 																							//mark this jsSummaryRow as 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 + ")" )
					
					var details = _thisTemplate.getDetailsFromSummaryId( pid, folder, oid)

					_thisTemplate.renderDetailsAction($contextMain, pid, myId, folder, oid, details)
					
					var unreadCount = getUnreadCount(details)
					
					_thisTemplate.updateUnreadCount($(this), unreadCount)
					updateTotalUnread(pid)
					return false
					

				})

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

				if(countOfUnread)
					this.getUnreadNode($newNode).html("<strong>" + countOfUnread  + "</strong>").show()

				else
					this.getUnreadNode($newNode).hide()
			},
			
			getUnreadNode : function($summaryNode)
			{
				return $('span.unread', $summaryNode)
			},

			updateUnreadCount : function($summaryNode, newCount)
			{
				$unread = this.getUnreadNode($summaryNode)
				$unread.html("<strong>" + newCount + "</strong>")
				if(newCount==0) {
					if($unread.css('display'=='inline')) {
						$unread.fadeOut(2000)
					}
				}
				else {
					$unread.show()
				}
			},
			
			update : function($contextMain, dataPacket) 
			{

				//this.log( 'templateSMS.phtml #1551:update' )
				//this.log(dataPacket)
				
				_thisTemplate = this
				
				if( !assertFolder('SMS') )
					return;
				
				serviceDataSummary = this.getSummaryData( dataPacket.localDataNode.serviceData )
				//this.log(serviceDataSummary)
				
				//if( dataPacket.renderMethod == undefined || dataPacket.renderMethod != "renderComposer")
				//	$(".jsMainDetailsPanel .cssSMSComposer", $contextMain).remove() //remove a composer if there is one
					
				if( false && dataPacket.localDataNode == undefined || dataPacket.localDataNode.serviceData == undefined ) //TODO reqork to insert "No Records" notice
				{
					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
					
				}
				else
				{
					
					$(".jsSummaryRowNoSearchResults", $contextMain).hide()
					
					//if summary list was previously empty then trigger click of first item when done updating so that the main details panel is also updated
					var summaryWasEmpty = false
					if( $(".jsSummaryRow", $contextMain).length == 0)
						summaryWasEmpty = true
					
					//get list if existing oids from rows
					UIOIDs = []																												//UI Old UIDs
					$(".jsSummaryRow", $contextMain).each( function() { UIOIDs[UIOIDs.length] = $(this).attr("oid") })
					
					showHideNoMessagesAtSummaryRow( UIOIDs.length == 0 )

					//this.log( "UIOIDs" )
					//this.log( UIOIDs )
					
					//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', $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)
					$( serviceDataSummary ).each( function(index1, row) 
					{ 
					
						if( row.isLatest != "1")
							return //continue
					
						//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 )
							_thisTemplate.pushSummaryRow( $(".jsSummaryPanel .jsSummaryBottomMarker", $contextMain), dataPacket, row, prepend);
					
					})
					//if detail view was emptied because of changes from update then select top item for details render
					if( dataPacket.dataSourceParams!= undefined && dataPacket.dataSourceParams.renderMethod != undefined && dataPacket.dataSourceParams.renderMethod == "renderComposer" )
					{
						
						$(".jsSummaryRow", $contextMain).show()
						this.renderComposer($contextMain, dataPacket)
						
					}
					else if( true || $(".jsDetailRow", $contextMain).length == 0 )
					{

						$(".jsSummaryRow:first", $contextMain).addClass("selected")
						$(".jsSummaryRow", $contextMain).show()
						
						if( serviceDataSummary.length > 0 && (dataPacket.suppressRenderingDetails == undefined || dataPacket.suppressRenderingDetails == false) && ( dataPacket.renderMethod == undefined || dataPacket.renderMethod != "renderComposer") )
						{

							$(".jsSummaryRow:first", $contextMain).trigger("click")

						}
					
					}
//					enableMailActions()
					updateDeleteAction()
						
				}

			}, 
			searchList : function($context, searchTerm)
			{
				
				// Un-highlight previous selections
				$(".messageFrom > h3, .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 > h3, .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>
