
var _level  = -1;
var _period = 3;
var _notifyOnMotion = false;
var _notifInterval  = 1;
var MONTH           = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var SETTING_TYPE    = new Array("account_status", "personal_info", "change_password", "motion_notifications_settings", "notification_reports", "general");
//var SETTING_CAPTION = new Array("account status", "personal info", "change password", "motion notifications settings", "sms notification reports", "general");

var SETTINGS        = new Array();

function initSettings()
{
    var set   = null;
    
    // account status
    set                 = new Object();
    set.type            = "account_status";      
    set.name            = "Account status";  
    SETTINGS[set.type]  = set;
    set.show            = function(container) 
    {
        var name = this.name;
        
	Accountant.getUserInfo(function(data) 
	{
            var resp = data.parseJSON();
            if(true == resp.successful)
            {
                    var userInfo    = resp.data.parseJSON();
                    
                    Accountant.getServiceDetails(function(data) 
                    {
                        var content         = ""; 

                        // status
                        content         += "<h1>" + name + "</h1>";
                        content         += "<div class='searchform'>";
                        content         += "<table class='table' width='400'>";

                        content         += "<tr>";
                        content         += "<td>Service&nbsp;level</td>";
                        content         += "<td align='right'><strong>" + userInfo.service_level + "</strong></td>";
                        content         += "</tr>";

                        if("" != userInfo.expiration_date)
                        {
                            content         += "<tr>";
                            content         += "<td>Valid&nbsp;until&nbsp;(yy-mm-dd)</td>";
                            content         += "<td align='right'><strong>" + (("" != userInfo.expiration_date)? userInfo.expiration_date : "never") + "</strong></td>";
                            content         += "</tr>";
                        }
                            
                        resp = data.parseJSON();
                        if(resp.successful)
                        {
                            var serviceDetails  = resp.data.parseJSON();
                            
                            content         += "<tr>";
                            content         += "<td>Simultaneous&nbsp;active&nbsp;cameras</td>";
                            content         += "<td align='right'><strong>" + serviceDetails.simultcams + "</strong></td>";
                            content         += "</tr>";

                            content         += "<tr>";
                            content         += "<td>Simultaneous&nbsp;spectators&nbsp;per&nbsp;camera</td>";
                            content         += "<td align='right'><strong>" + serviceDetails.simultspecs + "</strong></td>";
                            content         += "</tr>";
                            
                            content         += "<tr>";
                            content         += "<td>Used/Total&nbsp;additional&nbsp;camera&nbsp;licenses</td>";
                            content         += "<td align='right'><strong>" + serviceDetails.used_cam_licenses + "/" + serviceDetails.total_cam_licenses + "</strong></td>";
                            content         += "</tr>";
                        }

                        content         += "</table>";
                        content         += "</div>";

                        document.getElementById(container).innerHTML  = content;
                    });
                    
                    
                    /*/
                    
                    
                    
                    var content     = ""; 

                    // status
                    content         += "<h1>" + name + "</h1>";
                    content         += "<div class='searchform'>";
                    content         += "<table class='table' width='400'>";

                    content         += "<tr>";
                    content         += "<td>Service&nbsp;level</td>";
                    content         += "<td align='right'><strong>" + userInfo.service_level + "</strong></td>";
                    content         += "</tr>";

                    if("" != userInfo.expiration_date)
                    {
                        content         += "<tr>";
                        content         += "<td>Valid&nbsp;until&nbsp;(yy-mm-dd)</td>";
                        content         += "<td align='right'><strong>" + (("" != userInfo.expiration_date)? userInfo.expiration_date : "never") + "</strong></td>";
                        content         += "</tr>";
                    }

                    content         += "</table>";
                    content         += "</div>";

                    document.getElementById(container).innerHTML  = content;
*/

            }
            else
                document.getElementById(container).innerHTML  = "";
                     
	});
    }
    
    
    // personal info
    set                 = new Object();
    set.type            = "personal_info";      
    set.name            = "Personal info";  
    SETTINGS[set.type]  = set;
    set.show            = function(container) 
    {
        var name = this.name;
        
	Accountant.getUserInfo(function(data) 
	{
		var resp = data.parseJSON();
		if(true == resp.successful)
		{
			var userInfo    = resp.data.parseJSON();
                        var content     = ""; 
                        
                        // personal info
                        content         += "<h1>" + name + "</h1>";
                        content         += "<label id='update_user_info_status'></label>";
                        content         += "<div class='searchform'>";
                        content         += "<table class='table' width='400'>";
                        
                        content         += "<tr>";
                        content         += "<td>First&nbsp;name</td>";
                        content         += "<td align='right'><input name='fname' id='fname' class='textbox' type='text' onkeydown='updateUserInfoOnEnter(event.keyCode)'/></td>";
                        content         += "</tr>";

                        content         += "<tr>";
                        content         += "<td>Last&nbsp;name</td>";
                        content         += "<td align='right'><input name='lname' id='lname' class='textbox' type='text'  onkeydown='updateUserInfoOnEnter(event.keyCode)'/></td>";
                        content         += "</tr>";

                        content         += "<tr>";
                        content         += "<td>Email</td>";
                        content         += "<td align='right'><input name='email' id='email' class='textbox' type='text' onkeydown='updateUserInfoOnEnter(event.keyCode)'/></td>";
                        content         += "</tr>";
                        
                        content         += "<tr>";
                        content         += "<td>Phone<br>(international, including country code, phone number)</td>";
                        content         += "<td align='right'><input name='phone' id='phone' class='textbox' type='text' onkeydown='updateUserInfoOnEnter(event.keyCode)'/></td>";
                        content         += "</tr>";

                        content         += "<tr>";
                        content         += "<td colspan='2' align='right'><input name='update_user_info' class='button' value='Update' type='button' onclick='updateUserInfo()'/></td>";
                        content         += "</tr>";

                        content         += "</table>";
                        content         += "</div>";
                        
                        document.getElementById(container).innerHTML  = content;
                        document.getElementById("fname").focus();
                        
                        
                        dwr.util.setValue("fname", userInfo.fname);
                        dwr.util.setValue("lname", userInfo.lname);
                        dwr.util.setValue("email", userInfo.email);
                        dwr.util.setValue("phone", userInfo.phone);

		}
                else
                    document.getElementById(container).innerHTML  = "";
                     
	});
    }
    
    
    
    // change password
    set                 = new Object();
    set.type            = "change_password";      
    set.name            = "Change password";  
    SETTINGS[set.type]  = set;
    set.show            = function(container) 
    {
        var name = this.name;
        
	Accountant.getUserInfo(function(data) 
	{
		var resp = data.parseJSON();
		if(true == resp.successful)
		{
			var userInfo    = resp.data.parseJSON();
                        var content     = ""; 
                        
                        // password
                        content         += "<h1>" + name + "</h1>";
                        content         += "<label id='update_password_status'></label>";
                        content         += "<div class='searchform'>";
                        content         += "<table class='table' width='400'>";
                        
                        content         += "<tr>";
                        content         += "<td>Current&nbsp;password</td>";
                        content         += "<td align='right'><input name='current_password' id='current_password' class='textbox' type='password' onkeydown='updatePasswordOnEnter(event.keyCode)'/></td>";
                        content         += "</tr>";

                        content         += "<tr>";
                        content         += "<td>New&nbsp;password</td>";
                        content         += "<td align='right'><input name='new_password' id='new_password' class='textbox' type='password' onkeydown='updatePasswordOnEnter(event.keyCode)'/></td>";
                        content         += "</tr>";
                        
                        content         += "<tr>";
                        content         += "<td>New&nbsp;password&nbsp;(confirm)</td>";
                        content         += "<td align='right'><input name='new_password_conf' id='new_password_conf' class='textbox' type='password' onkeydown='updatePasswordOnEnter(event.keyCode)'/></td>";
                        content         += "</tr>";

                        content         += "<tr>";
                        content         += "<td colspan='2' align='right'><input name='update_password' class='button' value='Change' type='button' onclick='updatePassword()'/></td>";
                        content         += "</tr>";

                        content         += "</table>";
                        content         += "</div>";
                        
                        document.getElementById(container).innerHTML  = content;
                        document.getElementById("current_password").focus();
                        
		}
                else
                    document.getElementById(container).innerHTML  = "";
                     
	});
    }
    
    
    // motion notifications settings
    set                 = new Object();
    set.type            = "motion_notifications_settings";      
    set.name            = "Motion notifications settings";  
    SETTINGS[set.type]  = set;
    set.show            = function(container) 
    {
        var content     = ""; 

        // Motion notification channels
        content         += "<h1>" + this.name + "</h1>";
        content         += "<label id='update_user_settings_status'></label>";
        content         += "<div class='searchform'>";
        content         += "<span id='notif_channels'></span>"
        content         += "</div>";

        document.getElementById(container).innerHTML  = content;
        
          
        getNotificationChannels();
    }
    
    
    // notification reports
    set                 = new Object();
    set.type            = "notification_reports";      
    set.name            = "SMS notification reports";  
    SETTINGS[set.type]  = set;
    set.show            = function(container) 
    {
          var content     = ""; 

          // notification reports
          content         += "<h1>" + this.name + "</h1>";
          content         += "<code>Select desired dates range and hit <strong>Show</strong> to display the report here or <strong>Mail</strong> to receive it by email.</code>";
          content         += "<label id='notification_report_status'></label>";
          content         += "<div class='searchform'>";
          content         += "<table class='table' width='400'>";

          content         += "<tr>";
          content         += "<td>From</td>";

          content         += "<td align='right'>";
          var now         = new Date();

          content         += "<select id='report_date_from_month' name='report_date_from_month' class='combobox_narrow'>";
          for(var j=0; j<MONTH.length; j++)
              content += "<option value='"+ ((j+1 < 10)? "0"+(j+1) : (j+1)) + "' " + ((now.getMonth() == j)? "selected":"") + ">" + MONTH[j] + "</option>";
          content         += "</select>"; 

          content         += "<select id='report_date_from_day' name='report_date_from_day' class='combobox_narrow'>";
          for(var j=1; j<=31; j++)
              content += "<option value='"+ ((j < 10)? "0"+j : j) + "' " + ((now.getDate() == j)? "selected":"") + ">" + j + "</option>";
          content         += "</select>"; 

          content         += "<select id='report_date_from_year' name='report_date_from_year' class='combobox_narrow'>";
          for(var j=2000; j<=now.getFullYear(); j++)
              content += "<option value='"+ j + "' " + ((now.getFullYear() == j)? "selected":"") + ">" + j + "</option>";
          content         += "</select>"; 

          content         += "</td>";
          content         += "</tr>";

          content         += "<tr>";
          content         += "<td>To</td>";

          content         += "<td align='right'>";
          now.setTime(now.getTime() + 1000*3600*24);

          content         += "<select id='report_date_to_month' name='report_date_to_month' class='combobox_narrow'>";
          for(var j=0; j<MONTH.length; j++)
              content += "<option value='"+ ((j+1 < 10)? "0"+(j+1) : (j+1)) + "' " + ((now.getMonth() == j)? "selected":"") + ">" + MONTH[j] + "</option>";
          content         += "</select>"; 

          content         += "<select id='report_date_to_day' name='report_date_to_day' class='combobox_narrow'>";
          for(var j=1; j<=31; j++)
              content += "<option value='"+ ((j < 10)? "0"+j : j) + "' " + ((now.getDate() == j)? "selected":"") + ">" + j + "</option>";
          content         += "</select>"; 

          content         += "<select id='report_date_to_year' name='report_date_to_year' class='combobox_narrow'>";
          for(var j=2000; j<=now.getFullYear(); j++)
              content += "<option value='"+ j + "' " + ((now.getFullYear() == j)? "selected":"") + ">" + j + "</option>";
          content         += "</select>"; 
          content         += "</tr>";

          content         += "<tr>";
          content         += "<td>Recipient<br>(leave blank for all recipients)</td>";
          content         += "<td align='right'><input name='notif_recipient' id='notif_recipient' class='textbox' type='text' value='' onkeydown='getNotificationReportOnEnter(event.keyCode)'/></td>";
          content         += "</tr>";

          content         += "<tr>";
          content         += "<td colspan='2' align='right'><input name='btn_get_notification_report' class='button' value='Show' type='button' onclick='getNotificationReport()'/>&nbsp;<input name='btn_mail_notification_report' class='button' value='Mail' type='button' onclick='mailNotificationReport()'/></td>";
          content         += "</tr>";

          content         += "</table>";
          content         += "<span id='notification_reports_table'></span>";
          content         += "</div>";

          document.getElementById(container).innerHTML  = content;
          
    }
    
    
    // general
    set                 = new Object();
    set.type            = "general";      
    set.name            = "General";  
    SETTINGS[set.type]  = set;
    set.show            = function(container) 
    {
        var name = this.name;
        
        Accountant.getUserInfo(function(data) 
	{
		var resp = data.parseJSON();
		if(true == resp.successful)
		{
			var userInfo    = resp.data.parseJSON();
                        var content     = ""; 
                        
                         // general
                        content         += "<h1>" + name + "</h1>";
                        content         += "<label id='update_user_settings_status'></label>";
                        content         += "<div class='searchform'>";
                        content         += "<table class='table' width='400'>";
                        
                        content         += "<tr>";
                        content         += "<td colspan='2' align='left'><input type='checkbox' id='sys_notif'" + (userInfo.sys_notif? "checked":"")  +  " onclick='updateUserSettings()'/>&nbsp;Send&nbsp;me&nbsp;system&nbsp;notifications,&nbsp;newsletters,&nbsp;etc.</td>";
                        content         += "</tr>";

                        content         += "<tr>";
                        content         += "<td colspan='2' align='left'><input type='checkbox' id='show_foreign_cams'" + (userInfo.show_foreign_cams? "checked":"")  +  " onclick='updateUserSettings()'/>&nbsp;Display&nbsp;public&nbsp;cameras&nbsp;in&nbsp;my&nbsp;cameras&nbsp;list</td>";
                        content         += "</tr>";
                        _notifyOnMotion = userInfo.notify_on_motion;
                        _notifInterval  = userInfo.motion_notif_int;
                        content         += "</table>";
                        content         += "</div>";
                        
                        document.getElementById(container).innerHTML  = content;
                        
		}
                else
                    document.getElementById(container).innerHTML  = "";
                     
	});
          
        
    }
    
}

function uninit() 
{
	dwr.util.setValue("access", "");
	dwr.util.setValue("quality", "");
	dwr.util.setValue("simult-cams", "");
	dwr.util.setValue("total", "");
	document.getElementById("buy-button").innerHTML       = "";
        //document.getElementById("user-info").innerHTML        = "";
        //document.getElementById("user-info-menu").innerHTML   = "";
        
        document.getElementById("settings-menu").innerHTML    = "";
        document.getElementById("settings").innerHTML         = "";
}

/*
function hideHelp(text)
{
    document.getElementById("help").innerHTML = "";
}

function showHelp(text)
{
    document.getElementById("help").innerHTML = "<code><img src='res/info.png'><br><br>" + text + "</code><table width='100%'><tr><td align='right'><a href='javascript:;' onclick='hideHelp()'>hide</a></td></tr></table>";
    document.getElementById("help").scrollIntoView(false);
}
*/

function levelChanged(level)
{
    _level = level.options[level.selectedIndex].value;
    getServicePolicy(-1, -1, -1);//getSimultCams(), getSimultSpectators(), getCamPermissions());
}

function periodChanged(period)
{
    _period = period.options[period.selectedIndex].value;
    getServicePolicy(getSimultCams(), getSimultSpectators(), getCamPermissions());
}


function serviceAcqusitionParamChanged(selector)
{
    getServicePolicy(getSimultCams(), getSimultSpectators(), getCamPermissions());
}

function getSimultCams()
{
    var selector = document.getElementById('simult-cams-selector');
    if(null != selector)
        return selector.options[selector.selectedIndex].value;
    
    return -1;
}

function getSimultSpectators()
{
    var selector = document.getElementById('simult-spectators-selector');
    if(null != selector)
        return selector.options[selector.selectedIndex].value;
    
    return -1;
}

function getCamPermissions()
{
    var selector = document.getElementById('cam-permissions-selector');
    if(null != selector)
        return selector.options[selector.selectedIndex].value;
    
    return -1;
}

function createSimultaneousCamsSelector(min, max, selected)
{
    if(selected < 0)
        selected = min;
    
    var content     = ""; 

    content         += "<select id='simult-cams-selector' name='simult-cams-selector' "  + ((min == max)? "disabled":"") +  " class='combobox' onchange='serviceAcqusitionParamChanged(this)' onkeyup='serviceAcqusitionParamChanged(this)'>";
    for(var j=min; j<=max; j++)
        content += "<option value='"+ j + "' " + ((selected == j)? "selected":"") + ">" + j + "</option>";
        
    content         += "</select>"; 

    return content;
}

function createSimultaneousSpectatorsSelector(min, max, selected)
{
    if(selected < 0)
        selected = min;
    
    var content     = ""; 

    content         += "<select id='simult-spectators-selector' name='simult-spectators-selector' "  + ((min == max)? "disabled":"") +  " class='combobox' onchange='serviceAcqusitionParamChanged(this)' onkeyup='serviceAcqusitionParamChanged(this)'>";
    for(var j=min; j<=max; j++)
        content += "<option value='"+ j + "' " + ((selected == j)? "selected":"") + ">" + j + "</option>";
        
    content         += "</select>"; 

    return content;
}

function createCamPermissionsSelector(min, max, selected)
{
    if(selected < 0)
        selected = min;
    
    var content     = ""; 

    content         += "<select id='cam-permissions-selector' name='cam-permissions-selector' "  + ((min == max)? "disabled":"") +  " class='combobox' onchange='serviceAcqusitionParamChanged(this)' onkeyup='serviceAcqusitionParamChanged(this)'>";
    for(var j=min; j<=max; j++)
        content += "<option value='"+ j + "' " + ((selected == j)? "selected":"") + ">" + j + "</option>";
        
    content         += "</select>"; 

    return content;
}

function getServicePolicy(cams, spectators, permissions) 
{
	Accountant.getServicePolicy(_level, _period, cams, spectators, permissions, function(data) 
	{
		var resp = data.parseJSON();
		if(true == resp.successful)
		{
			var policy = resp.data.parseJSON();
			
			_level = policy.level;

			var level = document.getElementById("level");
			for (var i = 0; i < level.length; i++) 
			{
				if(i == _level)
				{
					level.options[i].selected = true;
				}
				else
				{
					level.options[i].selected = false;
				}
			}

			dwr.util.setValue("access", policy.access);
			dwr.util.setValue("quality", policy.quality);
                        document.getElementById("simult-cams").innerHTML        = createSimultaneousCamsSelector(policy.simultcams, policy.max_simultcams, cams);
                        document.getElementById("simult-spectators").innerHTML  = createSimultaneousSpectatorsSelector(policy.simultspecs, policy.max_simultspecs, spectators);
                        document.getElementById("cam-permissions").innerHTML    = createCamPermissionsSelector(policy.cam_permissions, policy.max_cam_permissions, permissions);
			dwr.util.setValue("total", policy.total);

			if("" != policy.buybutton)
				document.getElementById("buy-button").innerHTML = policy.buybutton;
			else
				document.getElementById("buy-button").innerHTML = "<strong>Please sign in to complete transaction.</strong>";
		}
	});
}

function updateUserInfoOnEnter(keyCode) 
{
	if (keyCode == 13)
		return updateUserInfo();
	else
		return true;
}

function updatePasswordOnEnter(keyCode) 
{
	if (keyCode == 13)
		return updatePassword();
	else
		return true;
}

function updateUserInfo() 
{
    //alert("Oops! Not implemented yet.");
    dwr.util.setValue("update_user_info", "...");
    dwr.util.setValue("update_user_info_status", "updating...");
    
    Accountant.updateUserInfo(dwr.util.getValue("fname"), dwr.util.getValue("lname"), dwr.util.getValue("email"), dwr.util.getValue("phone"), function(data) 
    {
        var resp = data.parseJSON();
        if(true != resp.successful)
            alert(resp.error);
        else
        {
            var userInfo = resp.data.parseJSON();
            //alert(userInfo.fname);
            dwr.util.setValue("fname", userInfo.fname);
            dwr.util.setValue("lname", userInfo.lname);
            dwr.util.setValue("email", userInfo.email);
            dwr.util.setValue("phone", userInfo.phone);
        }
        
        dwr.util.setValue("update_user_info", "Update");
        dwr.util.setValue("update_user_info_status", "");
    });
}

function onNotifyOnMotion() 
{
    document.getElementById("motion_notif_int").disabled = !document.getElementById("notify_on_motion").checked;
    updateUserSettings();
}

function updateUserSettings() 
{
    dwr.util.setValue("update_user_settings", "...");
    dwr.util.setValue("update_user_settings_status", "updating...");
    
    Accountant.updateUserSettings(  document.getElementById("show_foreign_cams").checked, 
                                    _notifyOnMotion, //document.getElementById("notify_on_motion").checked, 
                                    document.getElementById("sys_notif").checked, 
                                    _notifInterval, //dwr.util.getValue("motion_notif_int"), 
                                    function(data) 
    {
        var resp = data.parseJSON();
        if(true != resp.successful)
        {
            alert(resp.error);
            setUserInfo();
        }
        
        dwr.util.setValue("update_user_settings", "Update");
        dwr.util.setValue("update_user_settings_status", "");
    });
}

function updatePassword() 
{
    if("" == dwr.util.getValue("current_password"))
    {
        alert("Current password must be set!");
        document.getElementById("current_password").focus();
        return;
    }
    
    if("" == dwr.util.getValue("new_password"))
    {
        alert("New password must be set!");
        document.getElementById("new_password").focus();
        return;
    }
    
    if(dwr.util.getValue("new_password") != dwr.util.getValue("new_password_conf"))
    {
        alert("'New password' and 'New password (confirm)' must be identical!");
        document.getElementById("new_password_conf").focus();
        dwr.util.setValue("new_password_conf", "");
        return;
    }

    dwr.util.setValue("update_password", "...");
    dwr.util.setValue("update_password_status", "changing...");
    
    Accountant.updatePassword(dwr.util.getValue("current_password"), 
                              dwr.util.getValue("new_password"), 
                              function(data) 
    {
        dwr.util.setValue("update_password", "Change");
        dwr.util.setValue("update_password_status", "");

        var resp = data.parseJSON();
        if(true != resp.successful)
            alert(resp.error);
        else
            dwr.util.setValue("update_password_status", "Your password has been changed successfully.");
        
        dwr.util.setValue("current_password", "");      
        dwr.util.setValue("new_password", "");
        dwr.util.setValue("new_password_conf", "");
        document.getElementById("current_password").focus();
        
    });
    
}

function sendPasswordOnEnter(keyCode) 
{
	if (keyCode == 13)
		return sendPassword();
	else
		return true;
}

function sendPassword() 
{
    if("" == dwr.util.getValue("send_password_login"))
    {
        alert("Login must be set!");
        return;
    }
    

    dwr.util.setValue("send_password", "...");
    dwr.util.setValue("send_password_status", "sending...");
    
    Accountant.sendPassword(dwr.util.getValue("send_password_login"), function(data) 
    {
        var resp = data.parseJSON();
        if(true != resp.successful)
         {
            alert(resp.error);
            setUserInfo();
         }
        
        dwr.util.setValue("send_password", "Send");
        dwr.util.setValue("send_password_status", resp.data);
    });
    
}

function addRecipientOnEnter(type, keyCode)
{
    if (keyCode == 13)
        return addRecipient(type);
    else
	return true;
}

function addRecipient(type)
{
    //alert("add: " + type + ", value: " + dwr.util.getValue("recipient_" + type));
    
    dwr.util.setValue("add_recipient_" + type, "...");
    dwr.util.setValue("update_user_settings_status", "adding...");
    
    Accountant.addRecipient(type, 
                            dwr.util.getValue("recipient_" + type),
                            function(data) 
    {
        var resp = data.parseJSON();
        if(true != resp.successful)
        {
            alert(resp.error);
            dwr.util.setValue("add_recipient_" + type, "Add");
            document.getElementById("recipient_" + type).focus();
            document.getElementById("recipient_" + type).select();
        }
        else
        {
            //document.getElementById("add_" + type).innerHTML  = "";
            getNotificationChannels() ;
        }
        
        dwr.util.setValue("update_user_settings_status", "");
    });
    
    
}

function onAddRecipient(type)
{
    
    var content = "";
    
    content     += "<input name='recipient_" + type + "' id='recipient_" + type + "' class='textbox_wide' type='text' onkeydown='addRecipientOnEnter(\"" + type +  "\", event.keyCode)'/>";
    content     += "<br>";
    content     += "<input name='add_recipient_" + type + "' class='button' value='Add' type='button' onclick='addRecipient(\"" + type +  "\")'/>";
    
    document.getElementById("add_" + type).innerHTML  = content;
    document.getElementById("recipient_" + type).focus();
    
}

function onRemoveRecipient(type)
{
    if(document.getElementById(type).selectedIndex < 0)
        return;
    
    dwr.util.setValue("update_user_settings_status", "updating...");
    
    Accountant.removeRecipient( type, 
                                document.getElementById(type).options[document.getElementById(type).selectedIndex].value,
                                function(data) 
    {
        var resp = data.parseJSON();
        if(true != resp.successful)
        {
            alert(resp.error);
        }
        else
        {
            getNotificationChannels() ;
        }
        
        dwr.util.setValue("update_user_settings_status", "");
    });
    
}


function addBalanceOnEnter(keyCode)
{
    if (keyCode == 13)
        return addBalance();
    else
	return true;
}

function addBalance()
{
    //alert("balance: " + dwr.util.getValue("balance"));
    
    //if(dwr.util.getValue("balance") <= 0)
        //alert("what the fuck?");
    
    /*
    dwr.util.setValue("add_recipient_" + type, "...");
    dwr.util.setValue("update_user_settings_status", "updating...");
    
    Accountant.addRecipient(type, 
                            dwr.util.getValue("recipient_" + type),
                            function(data) 
    {
        var resp = data.parseJSON();
        if(true != resp.successful)
        {
            alert(resp.error);
            dwr.util.setValue("add_recipient_" + type, "Update");
            document.getElementById("recipient_" + type).focus();
            document.getElementById("recipient_" + type).select();
        }
        else
        {
            //document.getElementById("add_" + type).innerHTML  = "";
            getNotificationChannels() ;
        }
        
        dwr.util.setValue("update_user_settings_status", "");
    });
    */
    
}

function onAddBalance()
{
    
    var content = "";
    
    content     += "<input name='balance' id='balance' class='textbox' type='text' onkeydown='addBalanceOnEnter(event.keyCode)'/>";
    content     += "<input name='add_balance_button' class='button' value='Update' type='button' onclick='addBalance()'/>";
    
    document.getElementById("add_balance").innerHTML  = content;
    document.getElementById("balance").focus();
    
}

function refreshAddBalanceButton() 
{
    Accountant.createBuySmsCreditsButton(   document.getElementById("balance").options[document.getElementById("balance").selectedIndex].value, 
                                            function(data) 
    {
        var resp    = data.parseJSON().data.parseJSON();
        document.getElementById("add_balance_button_placeholder").innerHTML  = resp.button;
        document.getElementById("notifications_amount").innerHTML  = "(approximately&nbsp;" + resp.notifications + "&nbsp;notifications)";
        
        //document.getElementById("add_balance_button_placeholder").scrollIntoView(false);
    });
}

function showSmsCreditAcquisitionForm()
{
    var content     = ""; 

    content         += "<select id='balance' name='balance' class='combobox_narrow' onchange='refreshAddBalanceButton()' onkeyup='refreshAddBalanceButton()'>";
    for(var j=2; j<=100; j++)
    {
        switch(j)
        {
            case 2:
            case 5:
            case 10:
            case 20:
            case 50:
            case 100:
                content += "<option value='"+ j + "' " + ((10 == j)? "selected":"") + ">" + j + "</option>";
                break;
            default:
                continue;
        }
    }
    content         += "</select>&nbsp;USD"; 

    document.getElementById("sms_balance").innerHTML  = content;

    refreshAddBalanceButton();
}

function getBalance() 
{
    Accountant.getBalance(function(data) 
    {
        var resp    = data.parseJSON();
        
        if(true == resp.successful)
        {
            resp          = resp.data.parseJSON();
            
            var content   = "";
            content       += "<code>balance:&nbsp;<strong>" + resp.funds + "&nbsp;USD</strong>";
            if(resp.notifications > 0)
                content   += "<br>(approximately " + resp.notifications + " notifications)";
            
            content       += "<br><a href='javascript:;' onclick='showSmsCreditAcquisitionForm()'><strong>buy more</strong></a>";
            content       += "</code>";
            
            document.getElementById("current_balance_funds").innerHTML          = content;
        }
        else
            alert(resp.error);

    });
}


function getNotificationChannels() 
{
    Accountant.getNotificationChannels(function(data) 
    {
          var resp = data.parseJSON();
          if(true == resp.successful)
          {
                var channels    = resp.data.parseJSON();
                var content     = ""; 
                
                //content         += "<code>here you can configure how notifications will be sent to you</code>";

                content         += "<table class='table' width='400'>";


                content         += "<tr>";
                content         += "<td colspan='2' align='left'>here you can configure how notifications will be sent to you</td>";
                content         += "</tr>";

                for(var i=0; i<channels.length; i++)
                {
                    content         += "<tr><td colspan='2'><h2>" + channels[i].name + "</h2></td></tr>";


                    if("" != channels[i].description && ("sms" != channels[i].type))
                      content         += "<tr><td colspan='2'>" + (("" != channels[i].description)? "<code>"+channels[i].description+"</code>" : "") + "</td></tr>";
                    else if("sms" == channels[i].type)
                        content         += "<tr><td colspan='2'><span id='current_balance_funds'></span></td></tr>";

                    content         += "<tr>";
                    
                    if("mail" == channels[i].type)
                        content         += "<td>Email address</td>";
                    else if("sms" == channels[i].type)
                        content         += "<td>International (including country code) phone number</td>";
                    else if("xmpp" == channels[i].type)
                        content         += "<td>GoogleTalk user name</td>";
                    else if("mobile" == channels[i].type)
                        content         += "<td>LiveStream user name</td>";
                    else
                        content         += "<td></td>";

                    content         += "<td align='right'>";
                    content         += "<select id='" + channels[i].type + "' name='" + channels[i].type + "' class='combobox_wide' " + ((0 < channels[i].recipients.length)? "" : "disabled")  + ">";
                    for(var j=0; j<channels[i].recipients.length; j++)
                        content += "<option value='"+ channels[i].recipients[j] + "'>" + channels[i].recipients[j] + "</option>";
                    content         += "</select>"; 

                    content         += "<br>";
                    content         += "<a href='javascript:;' onclick='onAddRecipient(\"" + channels[i].type + "\")'>add</a>|<a href='javascript:;' onclick='onRemoveRecipient(\"" + channels[i].type + "\")'>remove</a>"
                    //content         += "<br><br>";
                    //content         += "<span id='add_" + channels[i].type + "'></span>"

                    content         += "</td></tr>";
                    
                    content         += "<tr><td>&nbsp;</td></tr>";
                    content         += "<tr><td colspan='2' align='right'><span id='add_" + channels[i].type + "'></span></td></tr>";
                    
                    
                    if("sms" == channels[i].type)
                    {
                        content         += "<tr>";
                        content         += "<td colspan='1'><span id='sms_balance'></span></td>"
                        content         += "<td colspan='1' align='right'><span id='notifications_amount'></span></td>"
                        content         += "</tr>";

                        content         += "<tr>";
                        content         += "<td colspan='2' align='right'><span id='add_balance_button_placeholder'></span></td>"
                        content         += "</tr>";
                    }
                    
                    //content         += "<tr><td>&nbsp;</td></tr>";

                }

                content         += "</table>";

                document.getElementById("notif_channels").innerHTML  = content;

                getBalance();
          }

    });
}

function getNotificationReportOnEnter(keyCode) 
{
    if (keyCode == 13)
        return getNotificationReport();
    else
	return true;
    
}

function getNotificationReport() 
{
    dwr.util.setValue("btn_get_notification_report", "...");
    dwr.util.setValue("notification_report_status", "retrieving...");
    
    var from = document.getElementById("report_date_from_year").options[document.getElementById("report_date_from_year").selectedIndex].value + 
               "-" + 
               document.getElementById("report_date_from_month").options[document.getElementById("report_date_from_month").selectedIndex].value + 
               "-" + 
               document.getElementById("report_date_from_day").options[document.getElementById("report_date_from_day").selectedIndex].value; 
           
    var to = document.getElementById("report_date_to_year").options[document.getElementById("report_date_to_year").selectedIndex].value + 
               "-" + 
               document.getElementById("report_date_to_month").options[document.getElementById("report_date_to_month").selectedIndex].value + 
               "-" + 
               document.getElementById("report_date_to_day").options[document.getElementById("report_date_to_day").selectedIndex].value; 

    //alert(from);
    Accountant.getNotificationReport( from, //dwr.util.getValue("report_date_from"),
                                      to, //dwr.util.getValue("report_date_to"),
                                      dwr.util.getValue("notif_recipient"),
                                      function(data) 
    {
          dwr.util.setValue("btn_get_notification_report", "Show");
          dwr.util.setValue("notification_report_status", "");
    
          var resp = data.parseJSON();
          if(true == resp.successful)
          {
                var data        = resp.data.parseJSON();
                var content     = ""; 

                content         += "<table class='table' width='400'>";
                content         += "<thead>";
                content         += "<tr>";
                content         += "<td></td>";
                content         += "<td><strong>date</strong></td>";
                content         += "<td><strong>cost&nbsp;(USD)</strong></td>";
                content         += "<td><strong>recipient</strong></td>";
                content         += "<td><strong>destination</strong></td>";
                content         += "</tr>";
                content         += "</thead>";

                var regEx = new RegExp (' ');  
                for(var i=0; i<data.entries.length; i++)
                {
                    content         += "<tr>";

                    content         += "<td>" + (i+1) + "</td>";
                    content         += "<td>" + data.entries[i].date.replace(regEx, '&nbsp;') + "</td>";
                    content         += "<td>" + data.entries[i].cost + "</td>";
                    content         += "<td>" + data.entries[i].recipient + "</td>";
                    content         += "<td>" + data.entries[i].dest + "</td>";
                    content         += "</tr>";
                }
                
                content         += "<tr>";
                content         += "<td colspan='2' align='right'><strong>total</strong></td>";
                content         += "<td><strong>" + data.total + "</strong></td>";
                content         += "<td colspan='2'></td>";
                content         += "</tr>";

                content         += "</table>";

                document.getElementById("notification_reports_table").innerHTML  = content;
          }
          else
              alert(resp.error);
              

    });
}

function mailNotificationReport() 
{
    dwr.util.setValue("btn_mail_notification_report", "...");
    dwr.util.setValue("notification_report_status", "sending...");
    
    var from = document.getElementById("report_date_from_year").options[document.getElementById("report_date_from_year").selectedIndex].value + 
               "-" + 
               document.getElementById("report_date_from_month").options[document.getElementById("report_date_from_month").selectedIndex].value + 
               "-" + 
               document.getElementById("report_date_from_day").options[document.getElementById("report_date_from_day").selectedIndex].value; 
           
    var to = document.getElementById("report_date_to_year").options[document.getElementById("report_date_to_year").selectedIndex].value + 
               "-" + 
               document.getElementById("report_date_to_month").options[document.getElementById("report_date_to_month").selectedIndex].value + 
               "-" + 
               document.getElementById("report_date_to_day").options[document.getElementById("report_date_to_day").selectedIndex].value; 

    //alert(from);
    Accountant.mailNotificationReport( from, //dwr.util.getValue("report_date_from"),
                                      to, //dwr.util.getValue("report_date_to"),
                                      dwr.util.getValue("notif_recipient"),
                                      function(data) 
    {
          dwr.util.setValue("btn_mail_notification_report", "Mail");
          dwr.util.setValue("notification_report_status", "");
    
          var resp = data.parseJSON();
          if(true == resp.successful)
              dwr.util.setValue("notification_report_status", "successfully sent");
          else
              alert(resp.error);
              

    });
}

function getDefaultFromToDates() 
{
    Accountant.getDefaultFromToDates(function(data) 
    {
          var resp = data.parseJSON();
          if(true == resp.successful)
          {
              resp = resp.data.parseJSON();
              //dwr.util.setValue("report_date_from", resp.from);
              //dwr.util.setValue("report_date_to", resp.to);
          }

    });
}

function showSettings(tab)
{
    // tab menu
    var menu        = "<ul>";
    
    var index = 0;
    for(type in SETTINGS)
    {
        index++;
        if(index > SETTING_TYPE.length)
            break;
        
        var name        = SETTINGS[type].name;
        
        if(type == tab)
          name = "<strong>" + name + "</strong>";
        
        menu            += "<li><a href='javascript:;' onclick='showSettings(\"" + type + "\")'>" + name + "</a></li>";
    }
    
    menu        += "</ul>";

    document.getElementById("settings-menu").innerHTML  = menu;

   
    SETTINGS[tab].show("settings");
}



