var delayPing;
var AccInfo = new Object();
var isSecure = false;
var protocol = window.location.protocol;
if (protocol == 'https:')
	isSecure = true;

$.LeftSide = new function()
{
	this.panel;
	this.InfoBlock;
	this.page;
	this.Access = new Object();
	this.Level;
	this.AccInfo = new Object();
};

$.LeftSide.logit = function(mess) {
	window.console.log(mess);
};

$.LeftSide.QueueDelay = function(func, time) {
	var rand = Math.floor(Math.random()*11);

	var cmd = 'delay_'+rand+' = setTimeout("'+func+'", '+time+');';
	eval(cmd);
};

$.LeftSide.Emstrong = function(bStrong){
    var sEmTag = "em";
    var sStrongTag = "strong";
    var txt = this.toString();
    var sTag = (bStrong) ? sStrongTag : sEmTag;
    return "<" + sTag + ">" + txt + "</" + sTag + ">";
};

$.LeftSide.refreshAccInfo = function() {

	if ( $.cookie('AccessCard') != null && $.access('level') < 500 )
	{
		var level = $.access('level');
		var domain = "";
		var email = "";

		this.AccInfo = new Object();
		this.AccInfo["Username"] = $.access('user');
		this.AccInfo["AccountID"] = $.access('rserverid');
		this.AccInfo["HostopianID"] = $.access('hostopianid');
		this.AccInfo["WebHostPlan"] = 1;
		this.AccInfo["HostingDomains"] = 1;

		if ($.access('level') == 100) {
			parts = $.access('user').split('@');
			domain = parts[1];
		}

		$.ajax({
			type: 'GET',
			async: false,
			url: "/api/db/mail/info/"+domain+".json",
			success: function(data) {
				res = eval( '(' + data + ')' );
				$.LeftSide.AccInfo = ($.array_merge($.LeftSide.AccInfo, res));
			},
			error: function(req, desc, obj) {
				return;
			}
		});
	}

	if ( $.cookie('AccessCard') != null && $.access('level') == 500 )
	{
		var level = $.access('level');

		//$.LeftSide.getEmailsLimits('');
		
		$.ajax({
			type: 'GET',
			async: false,
			url: "/api/db/mail/info/.json",
			success: function(data) {
				res = eval( '(' + data + ')' );
				$.LeftSide.AccInfo = ($.array_merge($.LeftSide.AccInfo, res));
			},
			error: function(req, desc, obj) {
//				alert("Error:\nCan't retrive Mail Info");
				return;
			}
		});
	
		$.ajax({
			type: "GET",
			async: false,
			url: "/api/rrad/account/payment/" + $.access("user") + ".json",
			success: function(data) {
                res = eval( '(' + data + ')' );
                $.LeftSide.AccInfo = ($.array_merge($.LeftSide.AccInfo, res));
            },
            error: function(req, desc, obj) {
//				alert("Error:\nCan't retrive CCInfo");
                return;
            }
        });

		$.ajax({
			type: 'GET',
			url: "/api/mail/home/system/INBOX.json?unseen",
			success: function(data) {
				if ( data.indexOf("{") == -1) return;
				else res_data = eval( '('+ data +')' );
				res['UnEmails'] = res_data['unseen'];
				$.LeftSide.AccInfo = ($.array_merge($.LeftSide.AccInfo, res));
			},
				error: function(req, desc, obj) {
					//alert("Error:\nCan't retrive Account Info");
					return;
				}
		});

		$.ajax({
            type: 'GET',
			async: false,
            url: "/api/db/account/info/"+$.access('user')+".json",
            success: function(data) {
                //$.LeftSide.AccInfo = eval( '(' + data + ')' );
				res = eval( '(' + data + ')' );
				$.LeftSide.AccInfo = ($.array_merge($.LeftSide.AccInfo, res));
				$.LeftSide.Access = eval( '(' + $.cookie('AccessCard') + ')' );
				$.LeftSide.Level = ($.LeftSide.Access['level']) / 100;
				if ($("#welcomeUserName"))
					$("#welcomeUserName").text($.LeftSide.AccInfo['FirstName']);
			},
			error: function(req, desc, obj) {
//				alert("Error:\nCan't retrive Account Info");
				return;
			}
		});

		//delay = setTimeout("$.LeftSide.setAccInfo();", 2000);
		$.LeftSide.QueueDelay("$.LeftSide.setAccInfo();", 2000);
	}
};

$.LeftSide.pingPresentAccInfoOnPage = function() {
	if ( $("#AccInfo").html() == "" )
		$.LeftSide.setAccInfo();

	clearTimeout(delayPing);
	if ( $.cookie("AccessCard") && ($.access('level') / 100) == 5 ) pingUnseenMess();
};

function pingUnseenMess()
{
	var delay = null;
	clearTimeout(delay);
	$.LeftSide.getUnseenMessages(true);
	delay = setTimeout("pingUnseenMess()", 600000);
}

$.LeftSide.setAccInfo = function() {
	$.accInfo = this.AccInfo;
    this.cleanServicesInfo();
    var typeStats;
    var mHist = ($.browser.msie) ? window.location.toString() : $.history._curHash;
    var method = mHist.substring(mHist.indexOf('#')+1);
    if (method.indexOf('/')!=-1) method = method.substring(0, method.indexOf('/'));
    if ($("#userName").text() == "")
        this.setDefAccInfo();

	if (mHist.lastIndexOf('/detail') != -1)
	{
		$.query.load(document.location.href);
		var statusMeth = ($.browser.msie) ? mHist.substring(mHist.indexOf('#')).replace('#'+method+'/', '') : mHist.replace('#'+method+'/', '');
		var account = "";
		if ( $.query.get('username') ) account = $.query.get('username');
		if ( $.query.get('domain') ) account = $.query.get('domain');
		if ( $.query.get('email') ) account = $.query.get('email');
		if (account.indexOf('&') != -1) account = account.substring(0, account.indexOf('&'));

		var typeDetail = "";
		if (mHist.indexOf('_main') != -1) typeDetail = "main";
		if (mHist.indexOf('_additional') != -1)
		{
			account = $.query.get('username');
			typeDetail = "additional";
		}
		var keyMeth = ($.query.get('type')) ? $.query.get('type') : statusMeth.substring(0, statusMeth.indexOf('/detail'));
		if (keyMeth == "")
			statusMeth = "set_for_"+method+"_StatusInfo";
		else
			statusMeth = "set_for_"+keyMeth+"_StatusInfo";

		if (eval('(this.'+statusMeth+')'))
			eval('(this.'+statusMeth+'("'+( keyMeth ? keyMeth : method )+'","'+typeDetail+'","'+account+'"))');
    }
	else
	{
		if (!method) return;
	    this.setHeadAccInfo();
		if (eval('($.LeftSide.set_'+method+'_AccInfo)'))
			eval('($.LeftSide.set_'+method+'_AccInfo())');
	}

	//this.delay = setInterval("$.LeftSide.getUnseenMessages(true);", 60000);

	if ($.access("status") && $.access("status") != "OK"
		&& $.access("status") != "EMPTY")
	{
		$('#topmenu').ringmenu({disable:'all',enable:'domains account logout'});
	}
};

$.LeftSide.getEmailsLimits = function(code) {
	code = code ? code : "BGRSERVERAPLUSPERSONAL";
	var url = "/api/db/list/packages.json?code="+code+"&q=MailBoxes,MailListLimit,MailForwardLimit,FtpUserLimit";
	$.ajax({
		type:'GET',
		url: url,
		success:function(data) {
			res = eval('('+data+')');
			$.LeftSide.AccInfo = ($.array_merge($.LeftSide.AccInfo, res[0]));
		},	
		error:function(req, stat, mess){
			return false;
		}
	});	
};

$.LeftSide.getFreeServices = function(domain) {
	var url = "/api/db/list/freeservices/"+domain+".json?q=FreeFtpUserCount,FreeMySqlDBCount,FreeMailListCount,FreeMailForwardCount,FreeDomainCount,FreeMSSQLCount";

	$.ajax({
		type:'GET',
		url: url,
		success:function(data) {
			res = eval('('+data+')');
			$.LeftSide.AccInfo = ($.array_merge($.LeftSide.AccInfo, res));
		},
		error:function(req, stat, mess){
			return false;
		}
	});	
};

$.LeftSide.getAccInfVal = function(key) {
	this.Info = $.LeftSide.AccInfo;
	if ( typeof this.Info[key] != 'undefined' )
		return this.Info[key];

	return null;
};

$.LeftSide.setCollMethod = function(method) {
	//if ( this.in_array(method))
	var as = method;
	var fn = eval('($.LeftSide.set_'+as+'_AccInfo())');
	fn;

	return true;
};

$.LeftSide.setGlobUtilityDomain = function(domain) {
	if (!domain) return;
	var UtilDomain = false;
	try { UtilDomain = $.LeftSide.AccInfo['UtilObj'][domain].utility; }
	catch(e) 
	{ 
		UtilDomain = $.query.get("domain");
		var UtilitySuffix = $.LeftSide.AccInfo.UtilitySuffix;
/*		if (UtilDomain.indexOf(UtilitySuffix) != -1
			|| UtilDomain.indexOf(".site.aplus.net") != -1)
		{*/
			var xeshUtilDomain = $.base64Encode('{"domain":" ","utility":"'+UtilDomain+'"}');
			$.cookie('CN_TRELLIX_UTILL', xeshUtilDomain, { expires: '', path: '/', secure: isSecure });	
/*		}*/
		return;
	}
	if (!UtilDomain) return;
	var xeshUtilDomain = $.base64Encode('{"domain":"'+domain+'","utility":"'+UtilDomain+'"}');
	var oldDomain = $.access('domain');
	if ( domain == oldDomain )
	{
		$.LeftSide.QueueDelay("$.LeftSide.AccInfo['CurrentDomain'] = $.access('domain');", 2000);
		$.cookie('CN_TRELLIX_UTILL', xeshUtilDomain, { expires: '', path: '/', secure: isSecure });
		return;
	}
	else
	{
		$.cookie('CN_TRELLIX_UTILL', xeshUtilDomain, { expires: '', path: '/', secure: isSecure });
	}
	$.setdomain(domain);
};

$.LeftSide.setGlobDomain = function(domain) {
	if (!domain) return;
	var xeshDomain = $.base64Encode(domain);
	var oldDomain = $.access('domain');
	if ( domain == oldDomain )
	{
		$.LeftSide.QueueDelay("$.LeftSide.AccInfo['CurrentDomain'] = $.access('domain');", 2000);
		$.cookie('CurrentDomain', xeshDomain, { expires: '', path: '/', secure: isSecure });
		return;
	}
	else
	{
		$.cookie('CurrentDomain', xeshDomain, { expires: '', path: '/', secure: isSecure });
		if ( $.LeftSide.AccInfo == 'undefined' ) {
			$.LeftSide.setAccInfo();
		}
	}
	$.setdomain(domain);
};

$.LeftSide.getGlobDomain = function () {
	var Domain = $.base64Decode($.cookie('CurrentDomain'));
	return Domain;
};

$.LeftSide.setGlobEmailAcc = function(email) {
	if (!email) return;
    var xeshEmail = $.base64Encode(email);
	var oldEmail = $.access('mail');

	if (email == oldEmail) {
		$.LeftSide.QueueDelay("$.LeftSide.AccInfo['CurrentEmailAcc'] = $.access('mail');", 2000);
		return;
	}
	else
	{
		$.cookie('CurrentEmailAcc', xeshEmail, { expires: '', path: '/', secure: isSecure });
        if ( $.LeftSide.AccInfo == 'undefined' ) {
			$.LeftSide.setAccInfo();
		}
    }
	$.setemail(email);
};

$.LeftSide.getGlobEmailAcc = function () {
    var Email = $.base64Decode($.cookie('CurrentEmailAcc'));
    return Email;
};

$.LeftSide.setGlobFTPUser = function(account, domain, isMain) {
	if ( !account && !domain ) return;
	var xeshFTPUser = $.base64Encode(account);
	var oldFTPDomain = $.access('domain');
	$.LeftSide.AccInfo['FTPMain'] = isMain;
	if ( domain == oldFTPDomain && isMain )
	{
		$.LeftSide.QueueDelay("$.LeftSide.AccInfo['CurrentDomain'] = $.access('domain');", 2000);
		$.cookie('CurrentFTPUser', xeshFTPUser, { expires: '', path: '/', secure: isSecure });
		return;
	}
	else
	{
		$.cookie('CurrentFTPUser', xeshFTPUser, { expires: '', path: '/', secure: isSecure });
		if ( $.LeftSide.AccInfo == 'undefined' ) {
			$.LeftSide.setAccInfo();
		}
	}
	$.setdomain(domain);
	//$.setftpuser(account);
};

$.LeftSide.getGlobFTPUser = function () {
    var Account = $.base64Decode($.cookie('CurrentFTPUser'));
    return Account;
};

$.LeftSide.getContactInfo = function(key) {
	if ( typeof(this.AccInfo[key]) != 'undefined' && this.AccInfo[key] != '' )
		return (this.AccInfo[key]);

	return false;
};

$.LeftSide.getPaymentInfo = function(key) {
    if ( typeof(this.AccInfo[key]) != 'undefined' && this.AccInfo[key] != '' )
        return (this.AccInfo[key]);

	return false;
};

$.LeftSide.setContactInfo = function(key, info) {
	if ( typeof (info) != 'undefined' && info != '' && info != null ) {
		$("#"+key).text(info);
		this.AccInfo[key] = info;
	}
	return true;	
};

$.LeftSide.setPaymentInfo = function(key, info) {
	if ( typeof (info) != 'undefined' && info != '' && info != null ) {
		$("#CCBox_"+key).show();
        if (key == 'CardNumber') 
			$("#"+key).text(info.replace(/\*/g, 'x'));
		else
			$("#"+key).text(info);
        this.AccInfo[key] = info;
    }
    return true;	
};

$.LeftSide.pingDomainPointer = function(point, domain) {
	var host = domain;
	if ( !host ) 
	{
		host = document.location.host;
		domain = host.substring(host.indexOf('.')+1);
	}
	var pointDomain = point+'.'+domain;
	var activePoint = 'webmail.aplus.net';
	$.ajax({
	    url: '/ring/accessories/resellers/checkStatus.php',
	    type: 'POST',
		async: false,
	    data: 'domain='+domain+'&record='+point,
	    success: function(res) {
	        if ( res.indexOf(pointDomain) != -1 ||
	             res.indexOf('Active') != -1 
	            )
	           	activePoint = pointDomain; 
	    }
	});
	return activePoint;
};

$.LeftSide.addService = function(service, cnt) {
	if ( $("#"+service).length <= 0 && typeof($.LeftSide.AccInfo[service]) == 'undefined' )
		return null;

	this.accCnt = parseInt($("#"+service).text());
	this.newCnt = this.accCnt + cnt;
	$("#"+service).text(this.newCnt);
	if (parseInt($("#"+service).text()) == this.newCnt)
	{
		if ( typeof $.LeftSide.AccInfo[service] != 'undefined' )
			$.LeftSide.AccInfo[service] = this.newCnt;
	}

	if (service == 'unMess')
	{
		if (this.newCnt != -1)
		{
			$.LeftSide.AccInfo['UnEmails'] = this.newCnt;
			$.LeftSide.setUnread();
		}
	}
};

$.LeftSide.removeService = function(service, cnt) {
    if ( $("#"+service).length <= 0 && typeof($.LeftSide.AccInfo[service]) == 'undefined' )
		return null;

	this.accCnt = parseInt($("#"+service).text());
	this.newCnt = this.accCnt - cnt;
	if (this.newCnt != -1)
	{
		$("#"+service).text(this.newCnt);
		if (parseInt($("#"+service).text()) == this.newCnt)
		{
			if ( typeof $.LeftSide.AccInfo[service] != 'undefined' )
	            $.LeftSide.AccInfo[service] = this.newCnt;
		}
	}

	if (service == 'unMess')
	{
		if (this.newCnt != -1)
		{
			$.LeftSide.AccInfo['UnEmails'] = this.newCnt;
			$.LeftSide.setUnread();
		}
	}
};

$.LeftSide.setUnreadMessages = function(cnt) {
        $("#unMess").text(cnt);
        this.setUnread();
};

$.LeftSide.setUnread = function() {
	var cntMess = parseInt($("#unMess").text());
	if (cntMess > 0)
		$("#unMess").attr("style","color: #FF0000;");
	else
		$("#unMess").attr("style",null);
};

$.LeftSide.getHelpLink = function(appid) {
	var helpLink = $.LeftSide.AccInfo.HelpLink;
	var url = document.location.host;
	var lang = $.access('lang');	

	helpLink = helpLink.replace('%URL%', url);
	helpLink = helpLink.replace('%LANG%', lang);
	helpLink = helpLink.replace('%APPID%', appid);

	if (url == 'hosting.testsitesc40.hostopia.com' || url == 'cp2.aplus.net')
		helpLink = "https://websupportwiki.com/"+lang+"/index.php/"+appid;

	return helpLink;
};

$.LeftSide.getAccInfoVal = function(key) {
	if ( typeof(this.AccInfo[key]) == 'undefined' )
		return null;

	return this.AccInfo[key];
};	

$.LeftSide.getAccInfo = function() {
	$.ajax({
		type: 'GET',
		url: "/api/db/account/info/"+$.access('user')+".json",
		success: function(data) {
			$.LeftSide.getCCInfo();
			$.LeftSide.getMailInfo();
			$.LeftSide.AccInfo = eval( '(' + data + ')' );

			if ($("#welcomeUserName"))
				$("#welcomeUserName").text($.LeftSide.AccInfo['FirstName']);
		},
		error: function(req, desc, obj) {
			//alert("Error from server!");
			return;
		}
	});
};

$.LeftSide.getCCInfo = function() {
    $.ajax({
        type: "GET",
        url: "/api/rrad/account/payment/" + $.access("user") + ".json",
        success: function (data) {
			res = eval( '(' + data + ')' );
			for (key in res)
			{
				$.LeftSide.AccInfo[key] = res[key];
			}	
        },
        error: function(req, desc, obj) {
			//alert("Error from server!");
        }
    });			
};

$.LeftSide.getMailInfo = function() {
	var level = $.access('level');
	var mailInfoURL = (level == '500') ? "/api/db/mail/info/.json" : "/api/db/mail/info/"+$.access('domain')+".json";
	$.ajax({
		type: 'GET',
		url: mailInfoURL,
		async: false,
		success: function(data) {
			res = eval( '(' + data + ')' );
			for (key in res)
			{
				$.LeftSide.AccInfo[key] = res[key];
			}
		},
		error: function(req, desc, obj) {
			alert("Error: \nCan't retrive MailInfo from server");
			return;
		}
	});

};

$.LeftSide.getUnseenMessages = function(check) {
    $.ajax({
                type: 'GET',
                url: "/api/mail/home/system/INBOX.json?unseen",
                success: function(data) {
                        if ( data.indexOf("{") == -1) return;
                        else res_data = eval( '('+ data +')' );

                        if (check) {
                                $.LeftSide.setUnreadMessages(res_data['unseen']);
                                return;
                        }
                        else {
                                res['UnEmails'] = res_data['unseen'];
                                $.LeftSide.AccInfo = ($.array_merge($.LeftSide.AccInfo, res));
                        }
                },
                error: function(req, desc, obj) {
                        //alert("Error:\nCan't retrive Account Info");
                        return;
                }
        });
};

$.LeftSide.getURLCHPASS = function() {
	var level = ( $.access('level') / 100 );
	var AccParams = {url:'',type:''};
	switch (level)
	{
		case 5:
			AccParams['url'] = "#account/changepass";
			AccParams['type'] = "Account";
			break;
		case 4:
			AccParams['url'] = "#web/ftp/changepass&domain="+$.access('user');
			AccParams['type'] = "FTP";
			break;
		case 3:
			AccParams['url'] = "#domains/changepass&domain="+$.access('user');
			AccParams['type'] = "Domain";
			break;
		case 1:
			AccParams['url'] = "#email/boxes/changepass&email="+$.access('user');
			AccParams['type'] = "Email";
			break;
	}
	return (AccParams);
};

$.LeftSide.setDefAccInfo = function() {
	var params = this.AccInfo;
	var user = $.access('user');
	var fullName = params['FirstName']+" "+params['LastName'];
	var showFullName = "";

	if (user.length > 33) {
        var userBlock = "<span title='"+user+"'>"+user.substring(0, 30)+"...</span>";
    }

	if ( typeof(params['FirstName']) === "undefined" )
		showFullName = "display: none;";

	this.HTML = '<tr style="'+showFullName+'"><td height="19" class="color_white">';
	this.HTML += '<b id="fullName">'+fullName+'</b>';
	this.HTML += '</td></tr>';
	this.HTML += '<tr><td></td></tr>';
	this.HTML += '<tr><td height="18" class="color_white">';

	var AccParams = this.getURLCHPASS();	
	this.HTML += '<a href="'+AccParams.url+'" rel="*">Change '+AccParams['type']+' Password</a>';
	this.HTML += '</td></tr>';

	if ($.access("level") == 500)
	{
		this.HTML += '<tr id="CCBox_PayMethod"';
		if (!params["PayMethod"]) this.HTML += ' style="display: none;" ';
		this.HTML += '>';
		this.HTML += '<td class="color_white">';
		this.HTML += '<b>Payment Method:</b>&nbsp;';
		this.HTML += '<span id="PayMethod">'+ ((params["PayMethod"] == "PO") ? "Cheque" : params["PayMethod"] ) +'</span>';
		this.HTML += '</td></tr>';
	
		this.HTML += '<tr id="CCBox_CardType"';
		if (!params["CardType"]) this.HTML += ' style="display: none;" ';
		this.HTML += '>';
		this.HTML += '<td class="color_white">';
		this.HTML += '<b>Card Type:</b>&nbsp;';
		this.HTML += '<span id="CardType">'+params["CardType"]+'</span>';
		this.HTML += '</td></tr>';
	
		this.HTML += '<tr id="CCBox_CardNumber"';
		if (!params["CardNumber"]) this.HTML += ' style="display: none;" ';
		this.HTML += '>';
		this.HTML += '<td height="28" class="color_white">';
		this.HTML += '<b>Last digits:</b>&nbsp;';
		if (params["CardNumber"])
			this.HTML += '<span id="CardNumber">'+params["CardNumber"].replace(/\*/g, "x")+'</span>';
		this.HTML += '</td></tr>';
		this.HTML += '<tr><td class="color_white">';
		this.HTML += '<a href="#account/customer-info" rel="*">Update Account Information</a>';
		this.HTML += '</td></tr>';
		this.HTML += '<tr><td height="27" class="color_white">';
		this.HTML += '<a href="#account/payment-info" rel="*">Update Payment Information </a>';
		this.HTML += '</td></tr>';
		this.HTML += '<tr><td class="color_white">';
		this.HTML += '<a href="#account/my-services" rel="*">View Plan Details</a>';
		this.HTML += '</td></tr>';
		var unEmails = params["UnEmails"] ? params["UnEmails"] : '0';
		this.HTML += '<tr><td class="color_white">';
		this.HTML += 'Unread messages: <b id="unMess">'+unEmails+'</b>.';
		this.HTML += '</td></tr>';
		this.HTML += '<tr><td height="17" class="color_white">';
		this.HTML += '<a href="#account/pmc&Selection=1" rel="*">View Unread Messages</a>';
		this.HTML += '</td></tr>';
	}

	this.HTML += '<tr><td height="6" class="padding0px color_white" align="right">';
	this.HTML += '<img src="images/separator.gif" />';
	this.HTML += '</td></tr>';
	this.HTML += '<tr><td class="color_white">';
	this.HTML += '<table width="99%"><tbody id="ServicesInfo">';
	this.HTML += '</tbody></table>';
	this.HTML += '</td></tr>';

	//$("#userName").append($.access('user'));
	this.setUserName();
	$("#AccInfo").append(this.HTML);
	if (unEmails > 0) this.setUnread();
	$('#AccInfo').ringmenu();
};

$.LeftSide.setUserName = function() {
	var user = $.access('user');
	var userBlock = user;

	if (user.length > 20) {
		userBlock = "<span title='"+user+"'>"+user.substring(0, 20)+"...</span>";
	}

	$("#userName").append(userBlock);
};

$.LeftSide.setHeadAccInfo = function() {
	this.HTML = '<tr><td><b>Service</b></td>';
    this.HTML += '<td align="right"><b>Accounts</b></td></tr>';
	$("#ServicesInfo").append(this.HTML);
};

$.LeftSide.set_home_AccInfo = function() {
    var params = this.AccInfo;
    var HTML = "";
    HTML += this.setServicesInfo({
            "Domain|Registrat":params['RegisteredDomains'] ? params['RegisteredDomains'] : 0,
            "Parking_Aliases":params['ParkedDomains'] ? params['ParkedDomains'] : 0,
            "Email|Accounts":params['EmailAccounts'] ? params['EmailAccounts'] : 0, 
//				(params['EmailAccounts'] ? params['EmailAccounts'] : 0)+(params['Mailboxes'] ? "/"+params['Mailboxes'] : ''),
            "Alias|Accounts":params['AliasAccounts'] ? params['AliasAccounts'] : 0,
            "FTP|Accounts":params['FTPAccounts'] ? params['FTPAccounts'] : 0,
//				(params['FTPAccounts'] ? params['FTPAccounts'] : 0)+(params['FtpUserLimit'] ? "/"+params['FtpUserLimit'] : ''),
            "WebHostPlan":params['WebHostPlan'] ? params['WebHostPlan'] : 0,
            "Money|Makers":params['MoneyMakers'] ? params['MoneyMakers'] : 0,
            "WebDesignPlans":params['WebDesignPlans'] ? params['WebDesignPlans'] : 0
            });

    $("#ServicesInfo").append(HTML);
    $('#AccInfo').ringmenu();
};

$.LeftSide.set_web_AccInfo = function() {
    var params = this.AccInfo;
	
	if ($.access("level") == 500)
	{
		this.HTML = this.setServicesInfo({
            "Parking_Aliases":params['ParkedDomains'] ? params['ParkedDomains'] : 0,
            "WebHostPlan":params['WebHostPlan'] ? params['WebHostPlan'] : 0,
            "Hosting|Domains":params['HostingDomains'] ? params['HostingDomains'] : 0
		});
	}
	else
	{
		this.HTML = this.setServicesInfo({
			"WebHostPlan":params['WebHostPlan'] ? params['WebHostPlan'] : 0,
			"Hosting|Domains":params['HostingDomains'] ? params['HostingDomains'] : 0
		});
	}

	$("#ServicesInfo").append(this.HTML);
    $('#AccInfo').ringmenu();
};

$.LeftSide.set_for_hosting_StatusInfo = function(keyMeth, typeMeth, account) {
	var params = this.AccInfo;
	this.HTML = this.setStatusInfo({
			"key":typeMeth ? keyMeth+'_'+typeMeth : keyMeth,
			"account":account,
			"status":params['Status']
			}); 

	$("#ServicesInfo").append(this.HTML);
	var moreInfo = this.makeLinkMoreInfo(keyMeth, account);
	$("#ServicesInfo").append(moreInfo);
	$('#AccInfo').ringmenu();
};

$.LeftSide.set_for_ftp_StatusInfo = function(keyMeth, typeMeth, account) {
    var params = this.AccInfo;
    this.HTML = this.setStatusInfo({
            "key":typeMeth ? keyMeth+'_'+typeMeth : keyMeth,
            "account":account,
            "status":'OK'//params['Status']
            });

    $("#ServicesInfo").append(this.HTML);
	var moreInfo = this.makeLinkMoreInfo(keyMeth, account, typeMeth);
    $("#ServicesInfo").append(moreInfo);
    $('#AccInfo').ringmenu();
};

$.LeftSide.set_email_AccInfo = function() {
	var params = this.AccInfo;
    this.HTML = this.setServicesInfo({
            "Email|Accounts":params['EmailAccounts'] ? params['EmailAccounts'] : 0,
            "Alias|Accounts":params['AliasAccounts'] ? params['AliasAccounts'] : 0
            });

	$("#ServicesInfo").append(this.HTML);
	$('#AccInfo').ringmenu();
};

$.LeftSide.set_for_boxes_StatusInfo = function(keyMeth, typeMeth, account) {
    var params = this.AccInfo;
    this.HTML = this.setStatusInfo({
            "key":typeMeth ? keyMeth+'_'+typeMeth : keyMeth,
            "account":account,
            "status":'OK' //params['Status']
            });

    $("#ServicesInfo").append(this.HTML);
	var moreInfo = this.makeLinkMoreInfo(keyMeth, account);
    $("#ServicesInfo").append(moreInfo);
    $('#ServicesInfo').ringmenu();
};

$.LeftSide.set_for_forwarders_StatusInfo = function(keyMeth, typeMeth, account) {
    this.set_for_boxes_StatusInfo(keyMeth, typeMeth, account);
};

$.LeftSide.set_for_groups_StatusInfo = function(keyMeth, typeMeth, account) {
    this.set_for_boxes_StatusInfo(keyMeth, typeMeth, account);
};

$.LeftSide.set_domains_AccInfo = function() {
	var params = this.AccInfo;
	var HTML = "";
	HTML += this.setServicesInfo({
			"Domain|Registrat":params['RegisteredDomains'] ? params['RegisteredDomains'] : 0
			});

	$("#ServicesInfo").append(HTML);
	$('#AccInfo').ringmenu();
};

$.LeftSide.set_for_domains_StatusInfo = function(keyMeth, typeMeth, account) {
    var params = this.AccInfo;
    this.HTML = this.setStatusInfo({
            "key":keyMeth ? keyMeth : "domains",
            "account":account,
            "status":'OK' //params['Status']
            });

    $("#ServicesInfo").append(this.HTML);
	var moreInfo = this.makeLinkMoreInfo(keyMeth, account);
    $("#ServicesInfo").append(moreInfo);
    $('#ServicesInfo').ringmenu();	
};

$.LeftSide.set_account_AccInfo = function() {
	this.set_home_AccInfo();
};

$.LeftSide.set_buyservices_AccInfo = function() {
	this.set_home_AccInfo();
};

$.LeftSide.setServicesInfo = function(params) {
	this.HTML = "";
	for ( key in params )
	{
		this.HTML += '<tr><td>';
		this.HTML += key.replace("_", "/").replace("|", " ");
		this.HTML += '</td><td align="right" id="'+key.replace("_", "").replace("|", "")+'">';
		this.HTML += params[key];
		this.HTML += '</td></tr>';
	}
	return this.HTML;
};

$.LeftSide.makeLinkMoreInfo = function(serv, account, type) {
	var tr = document.createElement("tr");
	var td = document.createElement("td");
	var a = document.createElement("a");

	$(td).attr("colspan", "2");
	$(a).attr("style", "cursor: pointer;");
	$(a).click(
		function(e) {
			$.LeftSide.getMoreDetails(e, serv, account, type);
	});
	$(a).text("More Details");
	$(td).append(a);
	$(td).append("<br /><br />");
	$(tr).append(td);

	return (tr);
};

$.LeftSide.setStatusInfo = function(params) {
    var account = params['account'];
    if (account.length > 20) account = account.substring(0, 17)+'...';

	this.StatusTitles = new Object();
	this.StatusTitles['hosting'] = "Domain Hosting:";
	this.StatusTitles['ftp_main'] = "Main FTP Account:";
	this.StatusTitles['ftp_additional'] = "Additional FTP Account:";
	this.StatusTitles['add-on_crm'] = "CRM Chat:";
	this.StatusTitles['add-on_icrm'] = "iCRM:";
	this.StatusTitles['boxes'] = "eMail Account:";
	this.StatusTitles['forwarders'] = "eMail Forwarder:";
	this.StatusTitles['lists'] = "eMail Lists:";
	this.StatusTitles['groups'] = "eMail Group:";
	this.StatusTitles['domains'] = "Domain registration " + params['account'].substring(params['account'].lastIndexOf('.'));

	this.HTML = "";
	this.HTML += '<tr><td colspan="2">';
	this.HTML += '<b>'+this.StatusTitles[params['key']]+'</b>';
	this.HTML += '</td></tr>';
	this.HTML += '<tr><td colspan="2">';
	this.HTML += '<b id="accUserName" title="'+params['account']+'">'+account+'</b>';
	this.HTML += '</td></tr>';
	if (params['key'] == 'domains')
	{
		this.HTML += '<tr><td><b>State</b></td>';
		this.HTML += '<td><b> &nbsp; Registered</b></td></tr>';
	}
	this.HTML += '<tr><td><b>Status</b></td>';
	this.HTML += '<td> &nbsp; <b id="accStatus">';
	switch(params['status'])
	{
		case 'NEW': this.HTML += '<font color="blue">New</font>'; break;
		case 'OK': this.HTML += '<font color="green">Active</font>'; break;
		case 'SUSPEND': this.HTML += '<font color="#000000">Suspend</font>'; break;
		case 'KILL': this.HTML += '<font color="red">Kill</font>'; break;
		case 'NOSVC': this.HTML += '<font color="Sienna">No svc</font>'; break;
		case 'DISABLE': this.HTML += '<font color="grey">Disable</font>'; break;
	}
	this.HTML += '</b></td></tr>';

    return this.HTML;
};

$.LeftSide.xWinStarter = function(p) {
	if (!p.wide) p.wide = 300;
	if (!p.high) p.high = 140;

	$("<div></div>").xWindow({
            draggable: false,
            closable: true,
            content: p.sHtml,
            status: p.status,
            title: p.title,
            position: {
                left: ( p.leftPos ? p.leftPos : (($.wWide()-p.wide) / 2) ),
                top: ( p.topPos ? p.topPos : (($.wHigh()-p.high) / 2) )
            },
            width: p.wide,
            height: p.high,
            modal: true,
            overlayOpacity: p.opac,
            stayInView: false,
            resizable: p.resize ? true : false,
            maximizable: p.max,
            minimizable: p.min
	});
};

$.LeftSide.xWinDestroy = function() {
        $(".xWindow").remove();
        $(".xWindow-overlay").remove();
};

$.LeftSide.getMoreDetails = function(e, serv, account, type) {
	var user = account ? account : $("#accUserName").attr("title");
	var stat = $("#accStatus").text();
	var mPos = new $.mousePos(e);
	var wide = 250;
	if (user.length > 25)
		wide = wide + ((user.length - 25) * 10);
	
	var sHtml = "";

	sHtml += '<div class="blockMoreInfo">';
	sHtml += '<table width="100%"><tr>';
	sHtml += '<td class="lTab">Username:</td><td class="rTab">'+(user).em(true)+'</td>';
	sHtml += '</tr><tr>';
	sHtml += '<td class="lTab">Password:</td><td class="rTab" id="targetPass">'+"******".em(true)+'</td>';
	sHtml += '</tr><tr>';
	sHtml += '<td colspan="2" class="cTab">';
	sHtml += '<a href="javascript:void(0)" onclick="$.LeftSide.ShowPassword(\''+serv+'\', \''+account+'\'';
	if (type == 'additional') sHtml += ", '"+$.access('domain')+"'";
	sHtml += ');">Show pass</a></td>';
	sHtml += '</tr></table>';
	sHtml += '</div>';

	var params = {
		drag: false,
		title: 'Account Details',
		sHtml: sHtml,
		leftPos: (mPos.x - 2),
		topPos: (mPos.y -2),
		wide: wide,
		hide: 150,
		opac: 0,
		max: false,
		min: false
	};
	this.xWinStarter(params);
};

$.LeftSide.ShowPassword = function(type, account, domain, key) {
	var targ = $("#targetPass");
	var url = "/api/";
	var results = "";

	//if ($.cookie('AlexIshimikli')) alert(type+" - "+account+" - "+domain+" - "+key);

	switch(type)
	{
		case "boxes": 

			var parts = account.split('@');
			var user = parts[0];
			var domain = parts[1];
			url += "db/mail/accounts/"+domain+".json?&q=Account,Domain,Password&type=passwd&account="+user;

			break;

		case "forwarders":
		case "groups":
			return;
			var parts = account.split('@');
			var user = parts[0];
			var domain = parts[1];
			url += "db/mail/accounts/"+domain+".json?&q=Account,Domain,Password&type=alias&account="+user;

			break;

		case "lists":
			
			var parts = account.split('@');
			var user = parts[0];
			var domain = parts[1];
			url += "db/mail/accounts/"+domain+".json?&q=Account,Domain,Password&type=alias&account="+user;
			//alert(url);	
			//return;

			break;

		case "hosting":
		case "domains":
		case "ftp":

			if (type == "ftp")
			{
				if ( domain )
					account = domain+"/"+account;
			}
			url += "db/ftp/password/"+account+".txt";

			break;
	}

    $.ajax({
        type:'GET',
        url:url,
		async: false,
        success:function(data) {
            if (type == 'boxes') {
                res = eval( '('+data+')' );
                var passwd = $.LeftSide.getPassword(user, domain, res);
                if ( !key ) targ.html((passwd).em(true));
				else results = passwd;
            }
            else
			{
                if ( !key ) targ.html((data).em(true));
				else results = data;
			}
        },
        error:function() {
//          alert("Error from server!");
        }
    });

    return (results);
};

$.LeftSide.getPassword = function(user, domain, params) {
    for (eKey in params)
    {
        if ( params[eKey]['Account'] == user && params[eKey]['Domain'] == domain )
            return params[eKey]['Password'];
    }
};

$.LeftSide.cleanServicesInfo = function() {
	//if (!$.browser.safari) $("#ServicesInfo").html("");
	$("#ServicesInfo").html("");

	//setTimeout("$.LeftSide.pingPresentAccInfoOnPage()", 2000);
	$.LeftSide.QueueDelay("$.LeftSide.pingPresentAccInfoOnPage();", 2000);
};

String.prototype.em = $.LeftSide.Emstrong;
//$.getInfo = $.LeftSide.getAccInfVal;
//$.getContactInfo = $.LeftSide.getContactInfo;
//$.getPaymentInfo = $.LeftSide.getPaymentInfo;
//$.setContactInfo = $.LeftSide.setContactInfo;
//$.setPaymentInfo = $.LeftSide.setPaymentInfo;
//$.addService = $.LeftSide.addService;
//$.delService = $.LeftSide.removeService;
//$.getMore = $.LeftSide.getMoreDetails;
//$.loadPasswd = $.LeftSide.ShowPassword;

