// ----

$( function() {

    // -- Update the time counter
    //updateTime();

    var hideTip = false;
    
    $('.SearchTextField')
        .tooltip({
            tip: '#valid_msisdn',
            position: 'bottom center',
            offset: [15, 11],
            // -- The spaces are required here to get IE6 working
            events: { def: " ,blur", input: " ,blur", widget: " ,blur" }
        })
        .keypress(function(e){
            var err = $(this).tooltip('#valid_msisdn');
            
            if(e.which != 8 && e.which != 13 && e.which != 27 && e.which != 9)
            {
                if(this.value.length == 0 && e.which != 48){ err.show(); return false; }
                if(this.value.length == 1 && e.which != 55){ err.show(); return false; }
                if(this.value.length == 11){ err.show(); return false; }
                
                var c = String.fromCharCode(e.which);
                if(!is_int(c))
                {
                    err.show();
                    return false;
                }
            }
            
            if(err.isShown()){
                hideTip = true;
                err.hide();
            }
        });
        
    // -- Required Field Validation
    $('.RequiredField')

    // -- Support for replacable default text-fields
    $('.DefaultedTextField')
        .focus( function() { PreContentOnClick($(this)); } )
        .blur( function() { PreContentOnUnclick($(this)); } );
        
    $('.IntegerField')
        .focus( function() { TM_NumberValidationFocus($(this), false); } )
        .blur( function() { TM_NumberValidationBlur($(this), false); } )
        .each( function() { if( $(this).val() == "" ) $(this).val("0"); } )
        .keydown( function(event) { return TM_NumberValidationPress($(this), event, false); } )
        .keyup( function(event) { TM_ValidateNumberKeyUnPress($(this), event, false) } )
        .tooltip( {
            tip: '#TM_tooltip',
            position: 'bottom center',
            // -- The spaces are required here to get IE6 working
            events: { def: " ,blur", input: " ,blur", widget: " ,blur" },
            onBeforeShow: function() {  }
            } );
        
    $('.DecimalField')
        .focus( function() { TM_NumberValidationFocus($(this), true); } )
        .blur( function() { TM_NumberValidationBlur($(this), true); } )
        .each( function() { if( $(this).val() == "" ) $(this).val("0"); } )
        .keyup( function(event) { TM_ValidateNumberKeyUnPress($(this), event, true) } )
        .keyup( function(event) { TM_ValidateNumberKeyUnPress($(this), event, true) } )
        .tooltip( {
            tip: '#TM_tooltip',

            // -- The spaces are required here to get IE6 working
            events: { def: " ,blur", input: " ,blur", widget: " ,blur" },
            onBeforeShow: function() {  }
            } );
    
    // -- Styling of the first and last menu elements
    $('#pageMenu ul li:first').addClass("first");
    $('#pageMenu ul li:last').addClass("last");
    
    $('#pageMenu ul li a:not(.disabled)').hover(
        function() { $(this).addClass('over'); },
        function() { $(this).removeClass('over'); }
    );
    
    // -- Support for AccordianContainer
    $('.AccordianContainer').each(
        function() {
            $(this).accordion({
                autoHeight: true,
                collapsible: true,
                fillSpace: true,
                active: parseInt($.cookie($(this).attr('id'))),
                animated: $.browser.msie && $.browser.version.substr(0,2) == "6." ? false : 'slide',
                change: function(event, ui) { var index = $(this).find("h3").index ( ui.newHeader[0] ); $.cookie($(this).attr('id'), index); }
            });
        }
    );
    
    // -- Support for Date Fields
	$('.DatePickerField').mask('99/99/9999').datepicker( { changeMonth: true, changeYear: true, dateFormat: 'dd/mm/yy', maxDate: '+30y', minDate: '-0d' } );
	$('.TimePickerField').mask('99:99').clockpick( { starthour: 0, endhour: 23, minutedivisions: 6, military: true } );
	
	// -- Support for Tabs
	$('.TabContainer').each( function() { $(this).tabs({ fx: { opacity: 'toggle' } }); } );
	$('.TabContainerMemory').each( function() { $(this).tabs({ fx: { opacity: 'toggle' }, cookie: { expires: 30 } }); } );
	
	// -- Text Counter Fun
	$('.TextMessageContainer tr').each(
	    function() {
	        RegisterTextCounter(
	            $(this).children('td').children('textarea'),
	            $(this).children('td').children('span'),
	            160
	        );
	    }
	);
} );

// ----

// -- Update the time value in the master template

function updateTime()
{
    $.get(TimeUrl, {r: Math.random()},
        function(data)
        {
            $('#lblCurrentDateTime').html(data); setTimeout('updateTime()', 30000);
        }
    );
}

// ----

var PreContentValues = new Array();

function PreContentOnClick( i )
{
    var id = i.attr('id');
    var v = PreContentValues[id];
    
    if( v == null )
        v = PreContentValues[id] = i.val();
    
    if( i.val() == v ) { i.val(''); }
}

function PreContentOnUnclick( i )
{
    var id = i.attr('id');
    var v = PreContentValues[id];
    
    if( i.val() == '' ) { i.val(v); }
}

// ----

var TM_NumberValidationFieldValues = new Array();

// -- Validate Key-Press Event
function TM_NumberValidationPress(c, event, IsDecimal)
{
    if( c.attr('readonly') != "" )
        return false;

    // -- 1. Check for removal characters first, they're always allowed
    if( event.keyCode == 46 // delete
     || event.keyCode == 8 // backspace
     || event.keyCode == 9 ) // backspace
        return true;
    
    // -- 3. Numeric keys, allowed in all cases
    if( TM_GetNumberFromEventCode(event.keyCode) != -1 )
        return true;

    // -- Other characters
    switch( event.keyCode ) {
        case 13: // enter
            if( !TM_NumberValidate(c, false) )
                return false;
            return true;
        
        case 9: // tab - allowed for accessibility reasons
            return true;
        
        // -- Special condition for decimals
        case 190: // . (windows mis-interpretation)
        case 110: // . (lunix correctish interpretation)
        case 78: // . (browser specific)
            if( !IsDecimal )
            {
                TM_ShowInputTooltip(c, "You cannot put a decimal point into an integer field.");
                return false;
            }
            // -- period can't be the first character
            if( c.val() == "" )
            {
                // -- so put a 0 in there first
                c.val("0.");
                return false;
            }
            // -- there can't be more than one period
            if( c.val().indexOf('.') > -1 )
            {
                TM_ShowInputTooltip(c, "You cannot input more than one decimal point.");
                return false;
            }
            return true;
        
        default:
            if( IsDecimal )
                TM_ShowInputTooltip(c, "This field should contain a decimal number (ie. 5.06)");
            else
                TM_ShowInputTooltip(c, "This field should contain a whole number (ie. 45)");
            return false;
    }
}

function TM_ValidateNumberKeyUnPress( c, event, IsDecimal )
{
    if( c.attr('readonly') != "" )
        return false;

    // -- 2. Maximum length check
    var MaxLen = c.attr('maxlength');
    var MaxLenVal = parseFloat(MaxLen);
    if( MaxLenVal != -1 )
        if( MaxLenVal < parseFloat(c.val()) )
        {
            c.val(MaxLenVal);
            TM_ShowInputTooltip(c, "The maximum value for this field is " + MaxLen + ".");
        }
}

function TM_ShowInputTooltip( c, msg )
{
    $('#TM_tooltip').text(msg);
    var tooltip = c.tooltip('#TM_tooltip');
    
    c.parent().eq(0).append($('#TM_tooltip'));
    
    if( !tooltip.isShown() )
        tooltip.show();
    else
        $('#TM_tooltip').effect('transfer', {to: c}, 10);
}

function TM_GetNumberFromEventCode( eventCode )
{
    switch( eventCode )
    {
        case 48: case 96: return 0;
        case 49: case 97: return 1;
        case 50: case 98: return 2;
        case 51: case 99: return 3;
        case 52: case 100: return 4;
        case 53: case 101: return 5;
        case 54: case 102: return 6;
        case 55: case 103: return 7;
        case 56: case 104: return 8;
        case 57: case 105: return 9;
        default: return -1;
    }
}

function TM_NumberValidate( i, isDecimal )
{
    // var err = $(this).tooltip('#valid_msisdn');

    // -- Check the existing value
    if( isNaN(i.val()) )
        return false;
    
    var val = 0;
    
    // -- Handle like a decimal or an integer
    if( isDecimal )
        val = parseFloat(i.val());
    else
        val = parseInt(i.val());
    
    // -- Maximum value, 2 billion
    if( val > 2000000000 )
        val = 2000000000;
    
    // -- Check the new value
    if( isNaN(val) )
        return false;
    
    i.val(val);
        
    return true;
}

function TM_NumberValidationFocus( i, isDecimal )
{
    var id = i.attr('id');
    var v = TM_NumberValidationFieldValues[id];
    
    if( v == null )
        v = TM_NumberValidationFieldValues[id] = i.val();
}

function TM_NumberValidationBlur( i, isDecimal )
{
    var id = i.attr('id');
    var v = TM_NumberValidationFieldValues[id];
    
    if( !TM_NumberValidate(i, isDecimal) )
        i.val(TM_NumberValidationFieldValues[id]);
}

// ----

var submitted = false;

function TM_PreventDoubleSubmit()
{
    if( submitted ) // && !confirm('This form has already been submitted once.  Are you sure you want to submit it again?  (this may result in double-entries).') )
        return false;
    
    submitted = true;
    return true;
}

// ----

var RegisterTextCounter_Ids = new Array();
var RegisterTextCounter_Items = new Array();
var RegisterTextCounter_Length = new Array();

function RegisterTextCounter( c, o, limit )
{
    var cid = c.attr('id');
    
    RegisterTextCounter_Ids.push(cid);
    RegisterTextCounter_Items.push(o);
    RegisterTextCounter_Length.push(limit);
    
    c.focus( function() { $(this).attr('rows', '3').parent().parent().attr('class', 'selected') } )
        .blur( function() { $(this).attr('rows', '2').parent().parent().attr('class', ''); } );
    
    c.blur();
    
    c.keydown( function( event ) { return RegisterTextCounter_EventDown($(this), event); } )
        .keypress( function() { RegisterTextCounter_EventPress($(this)); } )
        .keyup( function() { RegisterTextCounter_EventUp($(this)); } );
    
    RegisterTextCounter_Event(c);
}

function RegisterTextCounter_GetKeyFromId( cid )
{
    for( var i = 0; i < RegisterTextCounter_Ids.length; i++ )
    {
        if( RegisterTextCounter_Ids[i] == cid )
        {
            return i;
        }
    }
    
    return 0;
}

function RegisterTextCounter_Event( c )
{
    var cid = c.attr('id');
    var aid = RegisterTextCounter_GetKeyFromId(cid);
    var oi = RegisterTextCounter_Items[aid];
    var ll = RegisterTextCounter_Length[aid];
    var lu = c.val().length;
    var lr = ll - lu;
    
    // -- Limit Condition
    if( lr < 0 )
    {
        c.val( c.val().substring(0, 160) );
        lr = 0;
        
        alert("You have exceeded the 160 character limit.  The message will be truncated (cut down) to 160 characters.");
    }

    oi.text("("+ lr +" characters remaining)");
}

function RegisterTextCounter_EventPress( c )
{
    RegisterTextCounter_Event(c);
}

function RegisterTextCounter_EventUp( c )
{
    RegisterTextCounter_Event(c);
}

function RegisterTextCounter_EventDown( c, event )
{
    var cid = c.attr('id');
    var aid = RegisterTextCounter_GetKeyFromId(cid);
    var ll = RegisterTextCounter_Length[aid];
    var lu = c.val().length;
    var lr = ll - lu;

    if( lr <= 0 )
    {
        switch (event.keyCode)
        {
            case 8: // backspace
            case 46: // delete
                break;
            
            case 9: // tab - allowed for accessibility reasons
                return true;
            
            case 37: // left
            case 38: // right
            case 39: // up
            case 40: // down
                return true;
            
            default:
                return false;
        }
    }

    RegisterTextCounter_Event(c);
}

// ----


var RegisterTextLimit_Ids = new Array();
var RegisterTextLimit_Length = new Array();

function RegisterTextLimit( c, limit )
{
    var cid = c.attr('id');
    
    RegisterTextLimit_Ids.push(cid);
    RegisterTextLimit_Length.push(limit);
    
    c.keydown( function( event ) { return RegisterTextLimit_EventDown($(this), event); } )
        .keypress( function() { RegisterTextLimit_Event($(this)); } )
        .keyup( function() { RegisterTextLimit_Event($(this)); } );
}

function RegisterTextLimit_GetKeyFromId( cid )
{
    for( var i = 0; i < RegisterTextLimit_Ids.length; i++ )
        if( RegisterTextLimit_Ids[i] == cid )
            return i;
    return 0;
}

function RegisterTextLimit_Event( c )
{
    var cid = c.attr('id');
    var aid = RegisterTextLimit_GetKeyFromId(cid);
    var ll = RegisterTextLimit_Length[aid];
    var lu = c.val().length;
    var lr = ll - lu;

    // -- Limit Condition
    if( lr < 0 )
    {
        c.val( c.val().substring(0, ll) );
        lr = 0;
        alert("You have exceeded the "+ String(ll) +" character limit.  The message will be truncated (cut down) to "+ String(ll) +" characters.");
    }
}

function RegisterTextLimit_EventDown( c, event )
{
    var cid = c.attr('id');
    var aid = RegisterTextLimit_GetKeyFromId(cid);
    var ll = RegisterTextLimit_Length[aid];
    var lu = c.val().length;
    var lr = ll - lu;

    if( lr <= 0 )
    {
        switch (event.keyCode)
        {
            case 8: // backspace
            case 46: // delete
                break;
            
            case 9: // tab - allowed for accessibility reasons
                return true;
            
            case 37: // left
            case 38: // right
            case 39: // up
            case 40: // down
                return true;
            
            default:
                // if( lr == 0 )
                //    alert("You have reached the "+ String(ll) +" character limit.  No further text can be entered in this field.");
                // else
                    RegisterTextLimit_Event(c);
                return false;
        }
    }

    RegisterTextLimit_Event(c);
}


// ----

function is_int( value )
{
    var regexInt = /[0-9]/;
    
    if (regexInt.test(value)) {
	    return true;
    } else {
	    return false;
    }
}

function validateMsisdn( msisdn ) {
    var regexMsisdn = /07[0-9]{9}/;
    if(regexMsisdn.test(msisdn)) {
        return true;
    } else {
        return false;
    }
}
	    
// ----
