<div id="Flash"></div>
<?php

if(!isset($this->contact))
{
    $this->contact = array('Account' => '',
        'UserFirstName' => '',
        'UserMiddleName' => '',
        'UserLastName' => '',
        'UserEmail' => '');
}

$this->message = false;
$this->fullName = '';
$this->contactEmailAndGroup = '';

$domainDisabled = ( $this->domainEnabled == 0 );

$contactBlank = !array_key_exists('Account', $this->contact);
if($contactBlank)
{
    if( !empty($this->searchQuery) && !count($this->users))
    {
        $this->message = $this->translate('Found no users matching search criteria.') . '<br />' .
            $this->translate('Try using  name: surname: company: lastlogin: department: country: group: sort: order:(ASC,DESC) to filter results by specific fields (combinations allowed)');
    }
    else
    {
        if($this->global['install_type'] == 'server')
        {
            if( isset($this->listType) && $this->listType == 'user' )
            {
                $this->message = $this->translate('This group contains no users. Drag and drop users to this groups to add them.');
                if( $domainDisabled )
				    $class = "noUserGroup domainDisabled";
                else
				$class = "noUserGroup";
            }
            else
            {
                $this->message = $this->translate('No users exist at this domain.');
                if( $domainDisabled )
    				$class = "noUser domainDisabled";
				else
				$class = "noUser";
            }
        }
        else
        {
            if( isset($this->listType) && $this->listType == 'user' )
            {
                $this->message = $this->translate('This group contains no users. Drag and drop users to this groups to add them.');
            }
            else
            {
                $this->message = $this->translate("No users exist in the Webmail client. Login with a user via the Webmail login page first.");
            }
        }

        if(count($this->users))
        {
            $this->message = $this->translate('No User Selected');
        }
    }
}
else
{
    $this->fullName = $this->contact['UserFirstName'] .
        (strlen($this->contact['UserMiddleName']) > 0 ? ' ' . $this->contact['UserMiddleName'] : '') .
        (strlen($this->contact['UserLastName']) > 0 ? ' ' . $this->contact['UserLastName'] : '');
    $this->contactEmailAndGroup = $this->contact['UserEmail'] . ($this->contact['Ugroup'] != 'default' && $this->group != $this->contact['Ugroup'] ? ' (' . $this->contact['Ugroup'] . ')' : '');
}
$this->contactUgroup = ($this->contact['Ugroup']!='default'&&$this->group!=$this->contact['Ugroup']?' ('.$this->contact['Ugroup'].')':'');

// Do not show the group edit button if in 'All Users' or 'External Accounts'
$this->groupEditButton = false;
if( $this->userData['UMasterAdmin'] != 1 )
    $this->groupEditButton = false;
else if( $this->currentGroup == 'domain' )
{
   $this->groupEditButton = true;
   $this->groupEditButtonMsg = "Edit Domain Settings";
}
else if( $this->currentGroup == 'group' )
{
    $this->groupEditButton = true;
    $this->groupEditButtonMsg = "Edit Group Settings";
}

$this->accountEditButton = false;
$this->accountLoginButton = false;
$this->showDetails = true;
$this->user_disabled = false;

if( !$this->isExternal && $this->global['userPasswordEncryptionType'] == Atmail_Enum::PASSWORD_PLAIN )
{

    if ((int)$this->contact['UserStatus'] == 0 && (int)$this->contact['DomainStatus'] == 1)
    {

        $this->accountLoginButton = true;
        $this->accountEditButton = true;

    }
    else if( !$contactBlank )
    {
        $this->accountEditButton = true;
        $this->user_disabled = true;
        $this->message = ((int)$this->contact['DomainStatus'] == 1) ? $this->translate('User Disabled') : $this->translate('Domain Disabled');
		$class = "disabled";

    }

}

if( $this->userData['UMasterAdmin'] != 1 && $this->userData['UModify'] != 1 )
    $this->accountEditButton = false;

if($contactBlank)
{
    $this->showDetails = false;
}

?>

<table id="contact_table" contactid="<?php echo $this->contact['Account'] ?>">
    <tbody>
    <tr>
        <?php if ($this->showDetails) { ?>
			<td class="photo" id='UserPhoto'>
				<div>
                    <img id='Photo' src="<?php echo $this->moduleBaseUrl ?>/users/viewphoto/id/<?php echo $this->contact['id'] . "/" . md5($this->contact['UserPhoto']); ?>" style='max-height: 80px; max-width: 60px;'/>
 				</div>
			</td>
        <?php } ?>

        <td>
			<div class="viewUserInfo">
	            <span class="full_name"><?php echo $this->fullname; ?></span>
	
	            <div class='email'><?php echo $this->contactEmailAndGroup; ?> <?php if ($this->user_disabled) { ?>
                    <span class="user_disabled"><?php echo ((int)$this->contact['DomainStatus'] == 1) ? $this->translate('User Disabled') : $this->translate('Domain Disabled'); ?></span>
                <?php } ?>
</div>
	            
			</div>
            <div class="userManagerBtns">
                <?php if ($this->groupEditButton) { ?>
                    <div id="back_button" class='groupEditButton <?php echo $class; ?> <?php echo ($this->showDetails ? 'details' : ''); ?> <?php echo $this->groupEditButtonMsg; ?>'><a href="#"><span><?php echo $this->groupEditButtonMsg; ?></span></a></div>
                <?php } ?>
                <?php if ($this->accountEditButton) { ?>
                    <div id="back_button" class='accountEditButton'><a href="#"><span><?php echo $this->translate("Edit User") ?> </span></a></div>
                <?php } ?>
                <?php if ($this->accountLoginButton) { ?>
                    <div id="back_button" class='accountLoginButton'><a href="#"><span><strong><?php echo $this->translate("Login") ?> </strong><?php echo $this->translate("to Account") ?></span></a></div>
                <?php } ?>
            </div>
        </td>
    </tr>
    </tbody>
</table>
<?php if (!$this->user_disabled && $this->message !== false) {
?>
<div id="nomsgselect"><p><?php echo $this->message; ?></p></div>
    <?php if( $domainDisabled ) : ?>
        <span class="user_disabled" id="domain_disabled"><?php echo $this->translate('Domain Disabled') ?></span>
    <?php endif; ?>
<?php
}
?>
<?php if($this->showDetails) { ?>

<div id="clearDivide"></div>

<div class="usertabs">
<!-- The tabs -->
<ul class="tabs">
    <li class="tab1">
        <a class="tab1 tab">
            Summary
        </a>
    </li>
        <li class="tab2">
            <a class="tab2 tab">
                Account Stats
            </a>
        </li>
        <li class="tab3">
            <a class="tab3 tab">
                Graphs
            </a>
        </li>
        <li class="tab4">
            <a class="tab4 tab">
                Map
            </a>
        </li>
</ul>
<!-- tab 1 -->
<div class="tab1 tabsContent">
    <div>
        <table id="contact_table" class='contact_profile' contactid="<?php echo $this->contact['Account'] ?>">
            <tbody>
            <tr style="border-top: none !important;">
                <td class="contact_field" align='top'>
                    <?php echo $this->translate('Settings Inherited'); ?>
                </td>
                <td class="contact_info">
                    <?php echo $this->contact['Ugroup'] == 'default' ? 'Global Settings' : $this->contact['Ugroup']; ?>
                    <?php if ($this->contact['Ugroup'] != 'default') { ?>
                        <small
                            class="customized-settings"><?php echo $this->translate('This user is part of a domain or group which has customized services and settings.'); ?></small>
                    <?php } ?>
                </td>
            </tr>
            <?php if ($this->global['install_type'] == 'server' && $this->contact['UsedQuota'] >= 0) : ?>
                <tr>
                    <?php
                    $usedQuota = $this->contact['UsedQuota'];
                    $totalQuota = $this->contact['UserQuota'];
                    ?>

                    <td class="contact_field" align='top'>
                        <?php echo $this->translate('Quota Usage') ?>
                    </td>
                    <td class="contact_info">
                        <?php echo $this->translate("Currently using " . Atmail_Quota::toHumanReadable($usedQuota, Atmail_Quota::MB)) ?>
                        <?php if (!empty($this->contact['UserQuota'])) : ?>
                            <?php echo " of " . Atmail_Quota::toHumanReadable($totalQuota, Atmail_Quota::MB); ?> (<?php echo round(($usedQuota / $totalQuota) * 100, 1); ?>%)
                        <?php else: ?>
                        <?php endif ?>
                        <div id="arc"></div>
                    </td>
                </tr>
            <?php endif ?>
            <?php

            $allNumberFields = array('UserHomePhone', 'UserHomeMobile', 'UserHomeFax', 'UserWorkPhone', 'UserWorkMobile', 'UserWorkFax');
            $translationHash = array('UserHomePhone' => 'Home Phone', 'UserHomeMobile' => 'Private Mobile', 'UserHomeFax' => 'Private Fax',
                'UserWorkPhone' => 'Work Phone', 'UserWorkMobile' => 'Work Mobile', 'UserWorkFax' => 'Work Fax');
            $usedNumberFields = array();

            foreach ($allNumberFields as $k) {
                if (strlen($this->contact[$k]) != 0)
                    $usedNumberFields[] = $k;
            }

            foreach ($usedNumberFields as $k) : ?>
                <tr>
                    <td class="contact_field"><?php echo translateHash($k, $translationHash) ?></td>
                    <td class="contact_info"><?php echo $this->contact[$k] ?></td>
                </tr>
            <?php
            endforeach;

            $allEmailFields = array('UserEmail2', 'UserEmail3', 'UserEmail4', 'UserEmail5');
            $translationHash = array('UserEmail' => 'Email', 'UserEmail2' => 'Email', 'UserEmail3' => 'Email', 'UserEmail4' => 'Email', 'UserEmail5' => 'Email');
            $usedEmailFields = array();

            foreach ($allEmailFields as $k) {
                if (strlen($this->contact[$k]) != 0)
                    $usedEmailFields[] = $k;
            }

            foreach ($usedEmailFields as $k) : ?>
                <tr>
                    <td class="contact_field"><?php echo translateHash($k, $translationHash) ?></td>
                    <td class="contact_info"><?php echo $this->contact[$k] ?></td>
                </tr>
            <?php
            endforeach;
            ?>

            <!-- Home Address -->
            <?php if (strlen($this->contact['UserHomeAddress']) != 0 ||
                strlen($this->contact['UserHomeCity']) != 0 ||
                strlen($this->contact['UserHomeState']) != 0 ||
                strlen($this->contact['UserHomeZip']) != 0 ||
                strlen($this->contact['UserHomeCountry']) != 0
            ) : ?>
                <tr>
                    <td class="contact_field"><?php echo $this->translate('Home Address') ?></td>
                    <td class="contact_info">
                        <?php
                        echo $this->contact['UserHomeAddress'] . (strlen($this->contact['UserHomeAddress']) != 0 ? "<br />\n" : "") .
                            $this->contact['UserHomeCity'] . (strlen($this->contact['UserHomeCity']) != 0 ? "&nbsp;\n" : "") .
                            $this->contact['UserHomeState'] . (strlen($this->contact['UserHomeState']) != 0 ? "&nbsp;\n" : "") .
                            $this->contact['UserHomeZip'] . (strlen($this->contact['UserHomeZip']) != 0 ? "<br/>\n" : "") .
                            $this->contact['UserHomeCountry']
                        ?>
                    </td>
                </tr>
            <?php endif; ?>

            <!-- Work Address -->
            <?php if (strlen($this->contact['UserWorkAddress']) != 0 ||
                strlen($this->contact['UserWorkCity']) != 0 ||
                strlen($this->contact['UserWorkState']) != 0 ||
                strlen($this->contact['UserWorkZip']) != 0 ||
                strlen($this->contact['UserWorkCountry']) != 0
            ) : ?>
                <tr>
                    <td class="contact_field"><?php echo $this->translate('Work Address') ?></td>
                    <td class="contact_info">
                        <?php
                        echo $this->contact['UserWorkAddress'] . (strlen($this->contact['UserWorkAddress']) != 0 ? "<br />\n" : "") .
                            $this->contact['UserWorkCity'] . (strlen($this->contact['UserWorkCity']) != 0 ? "&nbsp;\n" : "") .
                            $this->contact['UserWorkState'] . (strlen($this->contact['UserWorkState']) != 0 ? "&nbsp;\n" : "") .
                            $this->contact['UserWorkZip'] . (strlen($this->contact['UserWorkZip']) != 0 ? "<br/>\n" : "") .
                            $this->contact['UserWorkCountry']
                        ?>
                    </td>
                </tr>
            <?php endif; ?>

            <?php foreach (array('UserWorkCompany', 'UserTitle', 'UserURL', 'UserWorkTitle', 'UserWorkDept') as $field) : ?>
                <?php if (!empty($this->contact[$field])) : ?>
                    <tr>
                        <td class="contact_field" align='top'>
                            <?php echo translateHash($field, $translationHash) ?>
                        </td>
                        <td class="contact_info">
                            <?php if ($field == 'UserURL') : ?>
                                <a href='<?php echo $this->contact[$field] ?>'
                                   target='_blank'><?php echo $this->contact[$field] ?></a>
                            <?php else : ?>
                                <?php echo $this->contact[$field] ?>
                            <?php endif ?>
                        </td>
                    </tr>
                <?php endif ?>
            <?php endforeach ?>

            <?php if (!empty($this->contact['UserDOB'])) : ?>
                <?php
                $UserDOB = $this->contact['UserDOB'];
                $UserDOB = str_replace("00:00:00", '', $UserDOB);
                ?>
                <tr>
                    <td class="contact_field" align='top'>
                        <?php echo translateHash('UserDOB', $translationHash) ?>
                    </td>
                    <td class="contact_info">
                        <?php echo $UserDOB; ?>
                    </td>
                </tr>
            <?php endif ?>

            <?php if (!empty($this->contact['UserInfo'])) : ?>
                <tr>
                    <td class="contact_field" align='top'>
                        <?php echo translateHash('Notes', $translationHash) ?>
                    </td>
                    <td class="contact_info">
                        <textarea name="contact[UserInfo]"
                                  id='UserInfo'><?php echo $this->contact['UserInfo'] ?></textarea>
                    </td>
                </tr>
            <?php endif ?>

            </tbody>
        </table>
    </div>
</div>
<!-- end of t1 -->
<!-- tab 2 -->
<div class="tab2 tabsContent">
<div>
<div id='accountStats'>

<!-- left -->
<div class='statsLeft'>

    <?php /*
					<h1>Mobile Devices using ActiveSync:</h1>
					<ul>
						<?php foreach($this->mobileDevice as $device) :?>
						<li><?php echo $mobile['os'] ?> <span>ID <?php echo $mobile['deviceId'] ?></span></li>
						<?php endforeach ?>

					</ul>
					*/
    ?>

    <h1>Services Used</h1>
    <ul class="alternate">
        <?php if ($this->lastLogin == 0) : ?>
            <li>You do not have permission to access this information.</li>
        <?php else : ?>
            <?php foreach ($this->lastLogin as $key => $value) : ?>
                <li class="icon<?php echo $key ?>"><?php echo ucfirst($key) . "" ?>
                    <span>
        						<?php if (empty($value)) : ?>
                                    <?php echo $this->translate('Never') ?>
                                <?php else : ?>
                                    <?php echo $value ?> <?php echo $this->translate('ago') ?>
                                <?php endif ?>
    							    </span>
                </li>
            <?php endforeach ?>
        <?php endif ?>
    </ul>

    <h1>User Data</h1>
    <ul class="alternate">
        <?php if ($this->dataStats == 0) : ?>
            <li>You do not have permission to access this information.</li>
        <?php else : ?>
            <li class="icon-contacts">Contacts: <span><?php echo $this->dataStats['contacts'] ?></span></li>
            <li class="icon-cal">Calendar Events: <span><?php echo $this->dataStats['calendarEvents'] ?></span></li>
        <?php endif ?>
    </ul>

    <h1>ActiveSync Devices</h1>
    <ul class="alternate">
        <?php if ($this->mobileStats == 0) : ?>
            <li>You do not have permission to access this information.</li>
        <?php elseif (!is_array($this->mobileStats[0])) : ?>
            <li>No devices connected for this account.</li>
        <?php else : ?>
            <?php foreach ($this->mobileStats as $device) : ?>
                <li class="icon-device">Device Type: <span><?php echo $device['DeviceType'] ?></span></li>
                <li class="icon-device">Device ID: <span><?php echo $device['DeviceID'] ?></span></li>
                <li class="icon-device">Date First Synced: <span><?php echo $device['LogDate'] ?></span></li>
            <?php endforeach ?>
        <?php endif ?>
    </ul>

</div>

<!-- right -->
<div class='statsRight'>

    <h1>Top Senders</h1>
    <ul id="topSendersEmail" class="alternate">
        <?php if ($this->usageStats == 0) : ?>
            <li><span>You do not have permission to access this information.</span></li>
        <?php else : ?>
			<?php if (!is_array($this->usageStats['incoming'])) : ?>
				<li><span>Data not available</span></li>
			<?php elseif (!is_array($this->usageStats['incoming'][0])) : ?>
				<li><span>No recent activity</span></li>
			<?php else : ?>

				<?php foreach ($this->usageStats['incoming'] as $stat) : ?>
                <li id="<?php echo $stat['md5'] ?>"><span class="account"><?php echo $stat['Account'] ?></span>
                    <span>(<?php echo $stat['total'] ?>)</span></li>
    	        <?php endforeach ?>
			<?php endif ?>
        <?php endif ?>
    </ul>

    <h1>Top Receivers</h1>
    <ul id="topReceiversEmail" class="alternate">
        <?php if ($this->usageStats == 0) : ?>
            <li><span>You do not have permission to access this information.</span></li>
        <?php else : ?>
			<?php if (!is_array($this->usageStats['outgoing'])) : ?>
				<li><span>Data not available</span></li>
			<?php elseif (!is_array($this->usageStats['outgoing'][0])) : ?>
				<li><span>No recent activity</span></li>
			<?php else : ?>
				<?php foreach ($this->usageStats['outgoing'] as $stat) : ?>
				<li id="<?php echo $stat['md5'] ?>"><span class="account"><?php echo $stat['Account'] ?></span>
					<span>(<?php echo $stat['total'] ?>)</span></li>
				<?php endforeach ?>
			<?php endif ?>
        <?php endif ?>
    </ul>
    <script language='Javascript'>

        // Define the data as a two-dimensional array of numbers. If you had other
        // data to associate with each number, replace each number with an object, e.g.,
        // `{key: "value"}`.
        <?php
        $usedQuota = array_key_exists('UsedQuota',$this->contact)&&!empty($this->contact['UsedQuota']) ? $this->contact['UsedQuota'] : 0;
        $totalQuota = array_key_exists('UserQuota',$this->contact)&&!empty($this->contact['UserQuota']) ? $this->contact['UserQuota'] : 0;
        ?>
		var usedQuota = <?php echo $usedQuota ?>;
		var totalQuota = <?php echo $totalQuota ?>;
		var remainingQuota = totalQuota - usedQuota;
        var usedPercent = <?php echo ($totalQuota>0?round( ($usedQuota / $totalQuota) * 100, 1) : 0) ?>;
        var usedStr = "".concat(usedPercent);
        var usedStr = usedStr.concat('%');

        var data = [
            [usedQuota, remainingQuota]
        ];

        // Define the margin, radius, and color scale. The color scale will be
        // assigned by index, but if you define your data using objects, you could pass
        // in a named field from the data object instead, such as `d.name`. Colors
        // are assigned lazily, so if you want deterministic behavior, define a domain
        // for the color scale.
        var m = 10,
            r = 48;
        var z = d3.scale.ordinal()
            .range(["#eee", "#eee"]);

        // Insert an svg:svg element (with margin) for each row in our dataset. A
        // child svg:g element translates the origin to the pie center.
        var svg = d3.select("#arc").selectAll("svg")
            .data(data)
            .enter().append("svg:svg")
            .attr("width", (r + m) * 2)
            .attr("height", (r + m) * 2)
            .attr("class", "graphArc")
            .append("svg:g")
            .attr("transform", "translate(" + (r + m) + "," + (r + m) + ")");

        // Gradient
        var gradient = svg.append("svg:defs")
            .append("svg:linearGradient")
            .attr("id", "gradient")
            .attr("x1", "0%")
            .attr("y1", "100%")
            .attr("x2", "0%")
            .attr("y2", "0%")
            .attr("spreadMethod", "pad");

        gradient.append("svg:stop")
            .attr("offset", "0%")
            .attr("stop-color", "#007eb2")
            .attr("stop-opacity", 1);

        gradient.append("svg:stop")
            .attr("offset", "100%")
            .attr("stop-color", "#33a8d9")
            .attr("stop-opacity", 1);

        // The data for each svg:svg element is a row of numbers (an array). We pass
        // that to d3.layout.pie to compute the angles for each arc. These start and end
        // angles are passed to d3.svg.arc to draw arcs! Note that the arc radius is
        // specified on the arc, not the layout.
        svg.selectAll("path")
            .data(d3.layout.pie())
            .enter().append("svg:path")
            .attr("d", d3.svg.arc()
                .innerRadius(r / 1.21)
                .outerRadius(r))
            .style("stroke", "#ccc")
            .style("fill", function (d, i) {
                return z(i);
            });

        svg.select("path")
            .attr("id", "arc-gradient1")
            .style("stroke", "#1f6db6")
            .style("fill", "url(#gradient)");

        //Add the SVG Text Element to the svgContainer
        var text = svg.selectAll("path")
            .data(data)
            .enter().append("text");

        //Add SVG Text Element Attributes
        svg.append("svg:text")
            .attr("dy", ".35em")
            .attr("text-anchor", "middle")
            .text(usedStr)
            .style("font-weight", "bold")
            .style("font-size", "15px")
            .style("fill", "#444");

        // Every so often, start a transition to a new random angle. Use transition.call
        // (identical to selection.call) so that we can encapsulate the logic for
        // tweening the arc in a separate function below.
        /*
         setInterval(function() {
         foreground.transition()
         .duration(750)
         .call(arcTween, Math.random() * τ);
         }, 1500);
         */

        // Creates a tween on the specified transition's "d" attribute, transitioning
        // any selected arcs from their current angle to the specified new angle.
        function arcTween(transition, newAngle) {

            // The function passed to attrTween is invoked for each selected element when
            // the transition starts, and for each element returns the interpolator to use
            // over the course of transition. This function is thus responsible for
            // determining the starting angle of the transition (which is pulled from the
            // element's bound datum, d.endAngle), and the ending angle (simply the
            // newAngle argument to the enclosing function).
            transition.attrTween("d", function (d) {

                // To interpolate between the two angles, we use the default d3.interpolate.
                // (Internally, this maps to d3.interpolateNumber, since both of the
                // arguments to d3.interpolate are numbers.) The returned function takes a
                // single argument t and returns a number between the starting angle and the
                // ending angle. When t = 0, it returns d.endAngle; when t = 1, it returns
                // newAngle; and for 0 < t < 1 it returns an angle in-between.
                var interpolate = d3.interpolate(d.endAngle, newAngle);

                // The return value of the attrTween is also a function: the function that
                // we want to run for each tick of the transition. Because we used
                // attrTween("d"), the return value of this last function will be set to the
                // "d" attribute at every tick. (It's also possible to use transition.tween
                // to run arbitrary code for every tick, say if you want to set multiple
                // attributes from a single function.) The argument t ranges from 0, at the
                // start of the transition, to 1, at the end.
                return function (t) {

                    // Calculate the current arc angle based on the transition time, t. Since
                    // the t for the transition and the t for the interpolate both range from
                    // 0 to 1, we can pass t directly to the interpolator.
                    //
                    // Note that the interpolated angle is written into the element's bound
                    // data object! This is important: it means that if the transition were
                    // interrupted, the data bound to the element would still be consistent
                    // with its appearance. Whenever we start a new arc transition, the
                    // correct starting angle can be inferred from the data.
                    d.endAngle = interpolate(t);

                    // Lastly, compute the arc path given the updated data! In effect, this
                    // transition uses data-space interpolation: the data is interpolated
                    // (that is, the end angle) rather than the path string itself.
                    // Interpolating the angles in polar coordinates, rather than the raw path
                    // string, produces valid intermediate arcs during the transition.
                    return arc(d);
                };
            });
        }


    </script>

</div>
</div>
</div>
</div>
<!-- end of t2 -->
<!-- tab 3 -->
<div class="tab3 tabsContent">

    <?php include('application/modules/admin/views/scripts/dashboard/loginstats.phtml'); ?>

</div>
<!-- end of t3 -->
<!-- tab 4 -->
<div class="tab4 tabsContent">
    <div id="licence-error" class='versionDiv' style='display: none;'>
        <img class="regerror" src="<?php echo $this->siteBaseUrl ?>images/icons/error.png"/>
        <span></span>
    </div>

    <div id='activityMap'>
        <div id="userMap"></div>
    </div>

    <div id="activityMapSide">

        <h2>Logins</h2>
        <ul>
            <li class="webmail">
				<span>
					<input type="checkbox" class='chkLogin' name="chkWebmail" checked /> Webmail <span
                        class="chkLoginCount">(<span id="webmailCount" style="padding-left:0px">0</span>)</span>
				</span>
            </li>
<?php if ($this->global['install_type'] == 'server') : ?>
            <li class="imap">
				<span>
					<input type="checkbox" class='chkLogin' name="chkIMAP" checked> IMAP <span
                        class="chkLoginCount">(<span id="imapCount" class="chkLoginCount"
                                                     style="padding-left:0px">0</span>)</span>
				</span>
			</li>
            <li class="pop3">
				<span>
					<input type="checkbox" class='chkLogin' name="chkPOP3" checked> POP3 <span
                        class="chkLoginCount">(<span id="pop3Count" class="chkLoginCount"
                                                     style="padding-left:0px">0</span>)</span>
				</span>
			</li>
<?php endif ?>
            <li class="dav">
				<span>
					<input type="checkbox" class='chkLogin' name="chkDAV" checked> DAV <span
                        class="chkLoginCount">(<span id="davCount" class="chkLoginCount"
                                                     style="padding-left:0px">0</span>)</span>
				</span>
			</li>
            <li class="activesync">
				<span>
					<input type="checkbox" class='chkLogin' name="chkActiveSync" checked> ActiveSync <span
                        class="chkLoginCount">(<span id="asCount" class="chkLoginCount"
                                                     style="padding-left:0px">0</span>)</span>
				</span>
			</li>
        <ul>

    </div>


    <div id="activitySlider">
        <center>
            <br>
            <select name="map_days" id="map_days" style="display:none;" disabled>
                <?php for ($i = 1; $i <= $this->mapDayRange; $i++) : ?>
                    <?php if ($i > 28 && $i % 7) {
                        continue;
                    } ?>
                    <option value='<?php echo $i ?>' <?php if ($i == 7) {
                        echo 'selected';
                    } ?>>
                        <?php echo $i; ?> <?php if ($i == 1) {
                            echo $this->translate('day');
                        } else {
                            echo $this->translate('days');
                        } ?>
                    </option>
                <?php endfor ?>
            </select>

            <br>

            <small
                id="mapRangeDesc"><?php print $this->translate('Select the range for log visulization. Oldest login ') ?> <?php echo $this->mapDayRange ?> <?php echo $this->translate('days ago') ?></small>

            <div class='mapLoading' style="display:none;">
                <img src="<?php echo $this->siteBaseUrl ?>images/25.gif"/>
                <small>Calculating user activity ...</small>
            </div>
        </center>

    </div>

</div>
<!-- end of t4 -->

</div><!-- usertabs ends here-->

<!-- Account Stats -->
<table id="contact_table">
    <tr id='moreInformation'>
        <td class="contact_field">

            <!--	<div id='expandAccountStats' class="lessinfo">
				<span id="expandMoreInfoText"><?php echo $this->translate('Account Stats') ?></span>
			</div> -->

        </td>
        <td>
            &nbsp;
        </td>
    </tr>
</table>

<div id="clearDivide"></div>

<!-- Account Stats -->
<table id="contact_table">
    <tr id='moreInformation'>
        <td class="contact_field">

            <!--		<div id='expandActivityStats' class="lessinfo">
				<span id="expandMoreInfoText"><?php echo $this->translate('Activity Map') ?></span>
			</div> -->

        </td>
        <td>
            &nbsp;
        </td>
    </tr>
</table>


</div>

<div id="clearDivide"></div>

<!-- Top Sender / Receciver -->
<table id="contact_table">
    <tr id='moreInformation'>
        <td class="contact_field">

            <!--	<div id='expandUsageStats' class="lessinfo"><span id="expandMoreInfoText"><?php echo $this->translate('Usage Stats') ?></span></div> -->

        </td>
        <td>
            &nbsp;
        </td>
    </tr>
</table>


<div id="clearDivide"></div>
<?php } ?>


<script type="text/javascript" language="JavaScript">
$(function () {

    $(".groupEditButton", "#Users").unbind('click')
    $(".groupEditButton", "#Users").bind('click', function () {
        groupEdit($('#listcontacts #listType', '#Users').attr('value'), unescape($('#listcontacts #listGroup', '#Users').attr('value')))
    });

    //Alternate row color
    $('.alternate li:nth-child(odd)').addClass('alternate');

    // Remove all rows added via "New User" which have not been saved
    $(".user_row[contactid='']").each(function () {
        $(this).remove()
    })

    // Select the current viewed contact
    $('.contactRow:checked').each(function () {
        this.checked = false
        $(this).parent().parent().removeClass('selected')
    })

    $(".user_row[contactid=<?php echo $this->contact['Account'] ?>]").find('.contactRow').each(function () {
        this.checked = true
        $(this).parent().parent().addClass('selected')
    })

    // Highlight any search results
    searchQuery = $('#searchQuery').attr('value');

    if (searchQuery.length > 0)
        $('#contact_info').highlight(searchQuery);

    $('#expandGraphLogin').bind('click', function () {
        if ($('#Users #usageGraph').is(':hidden')) {
            $('#Users #usageGraph').show('fast');
            $('#expandGraphLogin').removeClass('moreinfo');
            $('#expandGraphLogin').addClass('lessinfo');
        } else {
            $('#Users #usageGraph').hide('fast');
            $('#expandGraphLogin').removeClass('lessinfo');
            $('#expandGraphLogin').addClass('moreinfo');
        }
    });

    $('#expandProfileInfo').bind('click', function () {
        if ($('#Users TABLE.contact_profile').is(':hidden')) {
            $('#Users TABLE.contact_profile').show('fast');
            $('#expandProfileInfo').removeClass('moreinfo');
            $('#expandProfileInfo').addClass('lessinfo');
        } else {
            $('#Users TABLE.contact_profile').hide('fast');
            $('#expandProfileInfo').removeClass('lessinfo');
            $('#expandProfileInfo').addClass('moreinfo');
        }

    });

    $("#expandAccountStats").bind('click', function () {
        if ($('DIV#accountStats').is(':hidden')) {
            $('DIV#accountStats').show('fast');
            $('#expandAccountStats').removeClass('moreinfo');
            $('#expandAccountStats').addClass('lessinfo');
        } else {
            $('DIV#accountStats').hide('fast');
            $('#expandAccountStats').removeClass('lessinfo');
            $('#expandAccountStats').addClass('moreinfo');
        }
    });

    $("#expandActivityStats").bind('click', function () {
        if ($('DIV#activityMap').is(':hidden')) {
            $('DIV#activityMap').show('fast');
            $('#expandActivityStats').removeClass('moreinfo');
            $('#expandActivityStats').addClass('lessinfo');
        } else {
            $('DIV#activityMap').hide('fast');
            $('#expandActivityStats').removeClass('lessinfo');
            $('#expandActivityStats').addClass('moreinfo');
        }
    });

    $("#expandUsageStats").bind('click', function () {
        if ($('DIV#usageStats').is(':hidden')) {
            $('DIV#usageStats').show('fast');
            $('#expandUsageStats').removeClass('moreinfo');
            $('#expandUsageStats').addClass('lessinfo');
        } else {
            $('DIV#usageStats').hide('fast');
            $('#expandUsageStats').removeClass('lessinfo');
            $('#expandUsageStats').addClass('moreinfo');
        }
    });

    // Update the times in timeAgo format
    //$("SPAN.timeAgo").each(function () {
    //var orig = $(this).html();
    //var d = $.timeago.parse($(this).html());
    //$(this).html( d.toString() ); //show title in users local time
    //$(this).attr('title', orig );
    //});

    $('div.usertabs div.tabsContent').hide();//tabsContent class is used to hide all the tabs content in the start
    $('div.tab1').show(); // It will show the first tab content when page load, you can set any tab content you want - just put the tab content class e.g. tab4
    $('div.usertabs ul.tabs li.tab1 a').addClass('tab-current');// We will add the class to the current open tab to style the active state
    //It will add the click event on all the anchor tag under the usertabs class to show the tab content when clicking to the tab
    $('div.usertabs ul li a').click(function () {
        var thisClass = this.className.slice(0, 4);//"this" is the current anchor where user click and it will get the className from the current anchor and slice the first part as we have two class on the anchor
        $('div.usertabs div.tabsContent').hide();// It will hide all the tab content
        $('div.' + thisClass).show(); // It will show the current content of the user selected tab
        $('div.usertabs ul.tabs li a').removeClass('tab-current');// It will remove the tab-current class from the previous tab to remove the active style
        $(this).addClass('tab-current'); //It will add the tab-current class to the user selected tab

        if (thisClass == 'tab2') {

        }
        else if (thisClass == 'tab3') {

            // If we have already rendered the graphs previously, don't do it again
            if ($("DIV#loginGraphBig canvas.base", "#Users").length == 1)
                return;

            $("div.tab3").height($("#Users .statLeft").height() + 300);

            $('#Users .statGraphSmall').each(function (n) {
                var myid = this.id;
                var myrecord = this;
                var data = [];
                //$.plot($(this), data, optionsSmall);

                var logtype = $(this).attr('logtype');

                $.ajax({
                    url: "<?php echo $this->moduleBaseUrl ?>/graph/json/view/month/log/Log_Login/account/<?php echo $this->contact['Account'] ?>/type/" + logtype,
                    method: 'GET',
                    dataType: 'json',
                    success: function (graphdata, type) {
                        $(myrecord).onDataReceivedSmall(graphdata);

                        // Open the 'all login' graph, zoomed at the top.
                        if (!logtype) {
                            zoomGraph($("#Users .statGraph"), $(myrecord));
                        }

                    }
                });


                // Now, bind when the user clicks!
                $(myrecord).bind('click', function () {
                    zoomGraph($("#Users .statGraph"), $(myrecord));
                });

            });

        } else if (thisClass == 'tab4') {

            // If we have already rendered the map, don't do it again
            if ($("DIV.leaflet-container").length == 1)
                return;

            // Count of different log types
            var webmailCount;
            var imapCount;
            var pop3Count;
            var davCount;
            var asCount;

            // Layers to contain different log types - used for hiding and showing points
            var webmailPoints;
            var imapPoints;
            var pop3Points;
            var davPoints;
            var asPoints;

            var options = {sliderOptions : { range: false, change: function (e, ui) {
                    // Disable the slider and show the loading symbol
                    $("small#mapRangeDesc").hide();
                    $("DIV.mapLoading").show();
                    $("DIV#Slider", "#Users").css('opacity', '0.3');

                    // When the user changes the selection, get the new value, and render the markers
                    var range = $('select#map_days option', "#Users").eq(ui.values[0]).val();
                    $("DIV.userMap").getLogs(range);
                }}
            };

            // Make the select box a slider
            $('select#map_days', "#Users").selectToUISlider(options);

            // Create the map variable
            var map = L.map('userMap', {attributionControl:false}).setView([13.754000, 100.501404], 2);
 //.setView([response.features[0].geometry.coordinates[1],response.features[0].geometry.coordinates[0]], 5);

            // Zoom to the selected map
            L.tileLayer('http://a.tiles.mapbox.com/v3/atmail.map-jmsws3l8/{z}/{x}/{y}.png', {
                maxZoom: 16
            }).addTo(map);

            <?php if( time() > strtotime(Zend_Registry::get('config')->reg['expiry']) && Zend_Registry::get('config')->reg['expiry'] != '' ) : ?>
            var message = 'This feature requires a valid license. Renew anytime via the Atmail Store.';
            $('.versionDiv SPAN', '#contact_info').html(message);
            $('.versionDiv').show();
            $("DIV.mapLoading").hide();
            return;
            <?php endif; ?>
            var loading = false;
            <?php 	if( !array_key_exists("resolveLogIPsToGeoLocationViaAtmailGeoLocationServer", $this->global) || $this->global['resolveLogIPsToGeoLocationViaAtmailGeoLocationServer'] != true ) : ?>
            var message = 'Feature disabled in Webadmin: To enable this feature go to Services > API > enable Geo-location.';
            $('.versionDiv SPAN', '#contact_info').html(message);
            $('.versionDiv').show();
            $("DIV.mapLoading").hide();
            <?php else : ?>
            $("DIV.mapLoading").show();
            loading = true
            <?php endif ?>

            var myIcon = L.Icon.extend({
                options: {
                    shadowUrl: "<?php echo $this->siteBaseUrl?>images/marker-shadow.png",
                    iconSize: [26, 41],
                    shadowSize: [41, 41],
                    iconAnchor: [13, 41],
                    shadowAnchor: [13, 41],
                    popupAnchor: [0, -41]
                }
            });

            // Different icons to display different log types
            var purpleIcon = new myIcon({iconUrl: "<?php echo $this->siteBaseUrl ?>images/marker-purple.png"}),
                redIcon = new myIcon({iconUrl: "<?php echo $this->siteBaseUrl ?>images/marker-red.png"}),
                blueIcon = new myIcon({iconUrl: "<?php echo $this->siteBaseUrl ?>images/marker-blue.png"}),
                greenIcon = new myIcon({iconUrl: "<?php echo $this->siteBaseUrl ?>images/marker-green.png"}),
                orangeIcon = new myIcon({iconUrl: "<?php echo $this->siteBaseUrl ?>images/marker-orange.png"});

            // Get the log type from the log type number
            function getLogType(feature) {
                switch (feature.properties.popupContent.LogType) {
                    case '1' :
                        return "POP3";
                    case '3' :
                        return "IMAP";
                    case '5' :
                        return "Webmail";
                    case '6' :
                        return "DAV";
                    case '7' :
                        return "ActiveSync";
                    case '8' :
                        return "DAV";
                    default :
                        return "Unknown";
                }
                return "An error occurred";
            }

            // When a marker is clicked, show a HTML popup with relevant content
            function onEachFeature(feature, layer) {
                var popupContent = "<h3>Access Details</h3>";

                if (feature.properties && feature.properties.popupContent) {
                    // Get the log type
                    var logType = getLogType(feature);

                    // Add information to popup
                    popupContent += "<span id='popupContentTitle'>Log Date: </span><span id='popupContentValue'>" + feature.properties.popupContent.LogDate + "</span></br>";
                    popupContent += "<span id='popupContentTitle'>Log IP: </span><span id='popupContentValue'>" + feature.properties.popupContent.LogIP + "</span></br>";
                    popupContent += "<span id='popupContentTitle'>Log Type: </span><span id='popupContentValue'>" + logType + "</span></br>";
                    popupContent += "<span id='popupContentTitle'>Country: </span><span id='popupContentValue'>" + feature.properties.popupContent.data.country_code + "</span></br>";
                    popupContent += "<span id='popupContentTitle'>City: </span><span id='popupContentValue'>" + feature.properties.popupContent.data.city + "</span></br>";
                    popupContent += "<span id='popupContentTitle'>Latitude: </span><span id='popupContentValue'>" + feature.properties.popupContent.data.lat + "</span></br>";
                    popupContent += "<span id='popupContentTitle'>Longitude: </span><span id='popupContentValue'>" + feature.properties.popupContent.data.long + "</span></br>";
                }

                layer.bindPopup(popupContent);
            }

            // Var holding the layers for markers
            var geojsonLayer;

            $("small#mapRangeDesc").hide();
            $("DIV#Slider", "#Users").css('opacity', '0.3');

            // Function to query the server for new IP 2 location
            $.fn.getLogs = function (range) {

                // Reset the log counts
                webmailCount = 0;
                imapCount = 0;
                pop3Count = 0;
                davCount = 0;
                asCount = 0;

                // Create groups for layers, removed old group points
                webmailPoints = new L.LayerGroup();
                imapPoints = new L.LayerGroup();
                pop3Points = new L.LayerGroup();
                davPoints = new L.LayerGroup();
                asPoints = new L.LayerGroup();

                $.ajax({
                    type: "POST",
                    url: "<?php echo $this->siteBaseUrl ?>index.php/admin/graph/useripmap",
                    data: {
                        Account: "<?php echo $this->contact['Account'] ?>",
                        range: range
                    },
                    dataType: 'json',
                    success: function (response) {

                        // Clear previous markers if we select a new range
                        if (geojsonLayer)
                            geojsonLayer.clearLayers();

                        // Render the new icons on the map
                        geojsonLayer = L.geoJson(response, {
                            pointToLayer: function (feature, latlng) {
                                switch (getLogType(feature)) {
                                    case 'POP3' :
                                        pop3Count++;
                                        return L.marker(latlng, {icon: greenIcon}).addTo(pop3Points);
                                    case 'IMAP' :
                                        imapCount++;
                                        return L.marker(latlng, {icon: purpleIcon}).addTo(imapPoints);
                                    case 'Webmail' :
                                        webmailCount++;
                                        return L.marker(latlng, {icon: blueIcon}).addTo(webmailPoints);
                                    case 'DAV' :
                                        davCount++;
                                        return L.marker(latlng, {icon: redIcon}).addTo(davPoints);
                                    case 'ActiveSync' :
                                        asCount++;
                                        return L.marker(latlng, {icon: orangeIcon}).addTo(asPoints);
                                    case 'DAV' :
                                        davCount++;
                                        return L.marker(latlng, {icon: redIcon}).addTo(davPoints);
                                    default :
                                        return L.circleMarker(latlng, {
                                            // Log type not found - display a yellow dot in location
                                            radius: 7,
                                            fillColor: "yellow",
                                            color: "#000",
                                            weight: 1,
                                            opacity: 1,
                                            fillOpacity: 0.8
                                        });
                                }
                            },
                            onEachFeature: onEachFeature
                        }).addTo(map);

                        // Add layers containing log points to the map
                        map.addLayer(webmailPoints);
                        map.addLayer(pop3Points);
                        map.addLayer(imapPoints);
                        map.addLayer(davPoints);
                        map.addLayer(asPoints);

                        // If a checkbox is not selected then hide the points associated with that checkbox
                        if (!$("INPUT.chkLogin", ".webmail").attr('checked'))
                            map.removeLayer(webmailPoints);
                        if (!$("INPUT.chkLogin", ".imap").attr('checked'))
                            map.removeLayer(imapPoints);
                        if (!$("INPUT.chkLogin", ".pop3").attr('checked'))
                            map.removeLayer(pop3Points);
                        if (!$("INPUT.chkLogin", ".dav").attr('checked'))
                            map.removeLayer(davPoints);
                        if (!$("INPUT.chkLogin", ".activesync").attr('checked'))
                            map.removeLayer(asPoints);

                        // Show the log counts
                        $('#webmailCount').text(webmailCount);
                        $('#imapCount').text(imapCount);
                        $('#pop3Count').text(pop3Count);
                        $('#davCount').text(davCount);
                        $('#asCount').text(asCount);
                        // Hide the loading symbol and activate the slider
                        $("small#mapRangeDesc").show();
                        $("DIV.mapLoading").hide();
                        $("DIV#Slider", "#Users").css('opacity', '1');
                    }
                });
            }

            if(loading)
            {
                if (options.sliderOptions.range)
                    $("DIV.userMap").getLogs(options.sliderOptions.range);
                else
                    $("DIV.userMap").getLogs(7);

                // Show or hide layers on changing the checkboxes
                $("INPUT.chkLogin").change(function () {
                    if ($(this).attr('checked')) {
                        // Show layers
                        switch ($(this).attr('name')) {
                            case 'chkWebmail' :
                                map.addLayer(webmailPoints);
                                return;
                            case 'chkIMAP' :
                                map.addLayer(imapPoints);
                                return;
                            case 'chkPOP3' :
                                map.addLayer(pop3Points);
                                return;
                            case 'chkDAV' :
                                map.addLayer(davPoints);
                                return;
                            case 'chkActiveSync' :
                                map.addLayer(asPoints);
                                return;
                            default :
                                return;
                        }
                    }
                    else {
                        // Hide layers
                        switch ($(this).attr('name')) {
                            case 'chkWebmail' :
                                map.removeLayer(webmailPoints);
                                return;
                            case 'chkIMAP' :
                                map.removeLayer(imapPoints);
                                return;
                            case 'chkPOP3' :
                                map.removeLayer(pop3Points);
                                return;
                            case 'chkDAV' :
                                map.removeLayer(davPoints);
                                return;
                            case 'chkActiveSync' :
                                map.removeLayer(asPoints);
                                return;
                        }
                    }
                });
            }
        }
    });

    /*
    var defaultGravatarURL = location.href;
    defaultGravatarURL = defaultGravatarURL.replace(/index\.php.* /, '/images/default-img.png');

    $("UL#topSendersEmail LI, UL#topReceiversEmail LI").each(function () {

        // get the email
        var email = $(this).text();

        // create a new image with the src pointing to the user's gravatar
        var gravatar = $('<img>').attr({src: 'http://www.gravatar.com/avatar/' + $(this).attr('id') + "?s=33&d=404"});

        // append this new image to some div, or whatever
        $(this).prepend(gravatar);

    });
    */

    // Edit User
    $('#back_button.accountEditButton a').bind("click", function () {

        if (userIsDisabled($(this)) || actions_disabled_users == true) {

            return false

        }

        //this block of code mainly put here for cleaner structure and also to access $this->translate
        if ($(this).attr("demo") == 'true') {

            alert('<?php echo $this->translate("Disabled in online demo") ?>')
            return false

        }

        userEditFirstSelected();
        return false;
    });


    // bind to the form's submit event and cancel legacy submit
    $('#back_button.accountLoginButton a').bind('click', function () {
        var executeLogin = true;
        <?php $global = Zend_Registry::get('config')->global;
        if(!array_key_exists('exclusive_sessions', $global) || (array_key_exists('exclusive_sessions', $global) && $global['exclusive_sessions']))
        {	?>
        var r = confirm("This will log out your admin session if you proceed.");
        if (r != true) {
            executeLogin = false;
        }
        <?php
    }	?>

        if (executeLogin) {
            <?php $global = Zend_Registry::get('config')->global;
            if(!array_key_exists('exclusive_sessions', $global) || (array_key_exists('exclusive_sessions', $global) && $global['exclusive_sessions']))
            {	?>
            window.location = "<?php echo $this->appBaseUrl ?>/admin/index/logout";
            <?php
        }	?>
            $('#accountLoginForm-<?php echo str_replace('=', '', base64_encode($this->contact['Account'])) ?>').submit();
        }
    });

});

</script>

<?php if ($this->accountLoginButton) { ?>
    <form id="accountLoginForm-<?php echo str_replace('=', '', base64_encode($this->contact['Account'])) ?>"
          action="<?php echo $this->appBaseUrl ?>/mail/auth/processlogin" method="POST" target="_blank">
        <input type="hidden" name="emailName" value="<?php echo $this->contact['emailName'] ?>"/>
        <input type="hidden" name="password" value="<?php echo $this->contact['Password'] ?>"/>
        <input type="hidden" name="emailDomain" value="<?php echo $this->contact['emailDomain'] ?>"/>
        <input type="hidden" name="requestedServer" value="<?php echo $this->contact['MailServer'] ?>"/>
    </form>
<?php } ?>
