﻿var nocount = false;

var SmsMessages =
{
	selectMessages: null
	,confirmDelete: null
	,deleteFailed: null
}

var SmsSettings =
{
	_rule: null
	,_validationExpression: null
	,_validationExpression2: null
	
	,alertWindow: null
	,sendButton: null
	,maxMessageLength: 0
	,maxRecipients: null
	
	,singleSmsLimit: 0
	,singleSmsSent: 0
	
	,singleSmsValue: null
	,massSmsValue: null
	,todaySent: 0
	,dailyLimit: -1
	,defaultSender: null
}

function apply_filter(caller, value)
{
	$('div[id=messages]').find('tr[id$=Row]').show();
	$('div[id=sms_filters]').find('div').each(function(index)
	{
		$(this).attr('class', 'sms_filter');
		
		if(index == 1)
			$(this).addClass('sms_bigmargin');
		
		if(this == caller)
			$(this).addClass('sms_filter_selected');
	});
	
	if(value != null)
	{
		$('div[id=messages]').find('tr[id$=Row]').each(function(index)
		{
			if($(this).attr('s') == value.toString())
			{
				$(this).show();
			}
			else
				$(this).hide();
		});
	}
	
	$('div[id=messages]').find('tr[id$=Row]:not([display=none])').each(function(index)
	{
		if(index > 0 && index % 2 == 0)
			$(this).attr('class', 'sms_alterrow');
		else
			$(this).attr('class', 'sms_row');
    });
	
	var count = 0;
	$('#empty_row').hide();
	
	$('div[id=messages]').find('tr[id$=Row]').each(function()
	{
	    if(this.style.display != 'none')
	        count++;
	});
	
	if(count == 0)
	    $('#empty_row').show();
}

function view_details(smsId)
{
	$('#message').val(smsId);
	
	details.show();
}

function delete_messages()
{
	var items = [];
	
	$('#smsList').find('input[type=checkbox][checked=true]').each(function()
	{
		if(this.value != 'on')
			items.push(this.value);
	});
	
	if(items.length == 0)
		alert(SmsMessages.selectMessages);
	else
	{
		if(confirm(SmsMessages.confirmDelete))
			delete_messages_execute(items);
	}
}

function delete_messages_execute(items)
{
	// Disable UI
	$.blockUI(
	{
		message: $('<div id="_spinner" style="display: none;"><img src="/images/sp.gif" border="0" /></div>')
		,css: {border: '0px'}
		,baseZ: 1000001
	});
	
	PageMethods.DeleteMessages(items,
	function(value)
	{
		$.unblockUI();
		
		if(value)
		{
			$('#smsList').find('input[type=checkbox][checked=true]').closest('tr').remove();
			if($('#smsList').find('tr').size() < 3)
				document.location.href = document.location.href;
		}
		else
			alert(SmsMessages.deleteFailed);
	},
	function(ex)
	{
		$.unblockUI();
		alert(SmsMessages.deleteFailed);
	});
}

function mark_allmessages(caller)
{
	$('#smsList').find('input[type=checkbox]').each(function()
	{
		if((caller.checked && !this.checked) || (!caller.checked && this.checked))
			$(this).click();
			
	});
}

function mark_message(caller)
{
	$(caller).closest('tr').find('td').each(function()
	{
		this.style.textDecoration = (caller.checked ? 'line-through' : 'none');
	});
}

function cancelClick()
{
    var modalPopupBehavior = $find('modal');
    modalPopupBehavior.hide();
}

function body_onkeydown(e)
{
    if (e.keyCode == 27)
    {
        try
        {
            var popup = $(mp);
            if (popup != null)
            popup.hide();
        }
        catch(err){}
    }
}

// Handle keyup event
function handle_keyup(src)
{
    if (nocount)
        nocount = false;
    else
        src.value = src.value.substring(0, (SmsSettings.maxMessageLength - SmsSettings._rule));
    count_letters(src);
}

function handle_keydown(e)
{
    var key = e.keyCode;
    if (key == 13)
    {
        nocount = true;
        return (false);
    }
    else if (key > 36 && key < 41 || key == 46 || key == 8)
        nocount = true;
    return (true);
}

// Count letters	
function get_count() { return parseInt($get('Count').innerHTML); }
function count_letters(src)
{
    var allow = (SmsSettings.maxMessageLength - SmsSettings._rule);
    if (src.value.length >= allow + 1)
        src.value = src.value.substring(0, allow);
    else
        $get('Count').innerHTML = allow - src.value.length;
}

function validate_recipients(sender, args)
{
	var isValid = true;
	var r = new RegExp(SmsSettings._validationExpression);
	
	var lines = args.Value.trim().split('\n');
	if(lines.length > 0)
	{
		var phones = [];
		
		// Remove empty lines
		for(var i = 0; i < lines.length; i++)
		{
			var line = lines[i].trim().replace(String.fromCharCode(13), '');
			if(line.length > 0)
				phones.push(line);
		}
		
		var errors = [];
		for(var i = 0; i < phones.length; i++)
		{
			var phone = phones[i];
			if(!r.test(phone))
				errors.push(phone);
		}
		
		// Ok no errors
		if(errors.length > 0)
			isValid = false;
	}
	else
		isValid = false;
	
	args.IsValid = isValid;
}

function validate_recipients_count(sender, args)
{
	var count = _recipientsCount(args.Value);
	
	if(SmsSettings.dailyLimit != -1 && (count + SmsSettings.todaySent) > SmsSettings.dailyLimit)
	{
		args.IsValid = false;
		sender.errormessage = 'Η αποστολή δεν μπορεί να γίνει γιατί θα υπερβείτε το ημερήσιο όριο.';
	}
	else
	{
		args.IsValid = (count <= SmsSettings.maxRecipients);
		sender.errormessage = 'Ξεπεράσατε το μέγιστο όριο παραληπτών.';
	}
}

function _recipientsCount(list)
{
	var phones = [];
	var lines = list.trim().split('\n');
	
	if(lines.length > 0)
	{
		// Remove empty lines
		for(var i = 0; i < lines.length; i++)
		{
			var line = lines[i].trim().replace(String.fromCharCode(13), '');
			if(line.length > 0 && Array.indexOf(phones, line) == -1)
			{
				phones.push(line);
			}
		}
	}
	
	return phones.length;
}

function validate_balance(sender, args){args.IsValid = true;}

function calculate_cost(count)
{
	var single = SmsSettings.singleSmsLimit - SmsSettings.singleSmsSent;
	if(single < 0)
		single = 0;
		
	var singleCount = (count < single ? count : single);
	var massCount = (count < single ? 0 : count - single);
	
	var singleCost = ((count < single ? count : single) * SmsSettings.singleSmsValue);
	var massCost = (count < single ? 0 : (count - single) * SmsSettings.massSmsValue);
	
	return{single:{count: singleCount, cost: singleCost}, mass: {count: massCount, cost: massCost}};
}

// Register event handlers
$(document).click(body_onkeydown);

function display_values()
{
	var count = _recipientsCount($('textarea[id$=PhoneList]:first').val());
	var cost = calculate_cost(count);
	
	var sb = new Sys.StringBuilder();
	sb.append('<b>{0} SMS</b> συνολικής αξίας <b>{1} points</b><br /><br />'.Format((cost.single.count + cost.mass.count), (cost.single.cost + cost.mass.cost).toFixed(0)));
	if(cost.single.count > 0 || cost.mass.count > 0)
	{
		sb.append('<span class="sms_block">ανάλυση κόστους:<br />');
		if(cost.single.count > 0)
			sb.append('<b>{0}</b> promo SMS: <b>{1} points</b>'.Format(cost.single.count, cost.single.cost.toFixed(0)));
		
		if(cost.mass.count > 0)
		{
			if(cost.single.count > 0)
				sb.append('<br />');
			sb.append('<b>{0}</b> normal SMS: <b>{1} points</b>'.Format(cost.mass.count, cost.mass.cost.toFixed(0)));
		}
		sb.append('</span>');
	}
	
	$('#confirmation').html(sb.toString());
}

Sys.Application.add_load(register_display_values);

function register_display_values()
{
	if(typeof(SmsSettings) != 'undefined')
	{
		var mp = $find(SmsSettings.alertWindow);
		if(mp != null)
		{
			// Display cost
			mp.add_showing(function()
			{
				var show = $('input[id$=ShowCost][type=checkbox]:first').is('[checked=true]');
				if(show)
					display_values();
			});
			
			mp.add_shown(function()
			{
				var show = $('input[id$=ShowCost][type=checkbox]:first').is('[checked=true]');
				if(!show)
				{
					window.setTimeout(mp.get_OnOkScript(), 0);
					mp.hide();
				}
			});
		}
	}
}

function disable_sms_buttons(){disable_button($('input[id$=SendMessage]').get(0), true, 'sms_send_inactive');}
function enable_sms_buttons(){disable_button($('input[id$=SendMessage]').get(0), false ,'sms_send');}

function set_sender(caller)
{
	var value = $(caller).val();
	$('input[id$=CustomSender]').css('display', (value == '-' ? '' : 'none'));
	
	var userName = $('label[id$=UserName]');
	userName.css('display', (value.toString() == '0' ? '' : 'none'));
	
	if(value.toString() == '0')
		SmsSettings._rule = userName.html().length;
	else
		SmsSettings._rule = 0;
	$('textarea[id$=Message]').trigger('keyup');
}

function validate_sender(sender, args)
{
	var drop = $('select[id$=SenderList]');
	var valid = (drop.val() != '-');
	if(!valid)
	{
		var digits = new RegExp(/\d/gi);
		var letters = new RegExp(/[A-Za-z]/gi);
		if(args.Value.trim().length == 0)
		{
			valid = false;
			sender.errormessage = 'Συμπληρώστε τον αποστολέα';
		}
		else if(args.Value.trim().toLowerCase() == SmsSettings.defaultSender.toLowerCase())
		{
			valid = false;
			sender.errormessage = 'Δεν μπορείτε να χρησιμοποιήσετε το VivaSms σαν αποστολέα';
		}
		else
		{
			valid = (letters.test(args.Value) || (digits.test(args.Value) && letters.test(args.Value))) && (args.Value.length < 12);
			sender.errormessage = 'Ο αποστολέας είναι λάθος. Μπορεί να είναι 1-11 λατινικοί χαρακτήρες και να περιέχει τουλάχιστον ένα γράμμα.';
		}
	}
	
	args.IsValid = valid;
}