var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
var now = new Date();
function htmlEncode( value )
{
    return $( '<div/>' ).text( value ).html();
}

function htmlDecode( value )
{
    return $( '<div/>' ).html( value ).text();
}

//  Emulate input placeholders
$( document ).ready( function ()
{
    $('body').find( ':input' ).focus(
        function ()
        {
            var input = $( this );
            if( input.val() == input.attr( 'placeholder' ) )
            {
                input.val( '' );
                input.removeClass( 'placeholder' );
            }

            //- Check if we are trying to style a "form" input, or a standard HTML input
            if( !input.hasClass('LayoutInput-input') )
            {
                input.addClass( 'input-focussed' );
            }
            else
            {
                //- Bubble up until we find the LayoutInput-box
                input.parents(".LayoutInput-box").addClass( 'input-focussed' );
            }
        }
    ).blur(
        function ()
        {
            var input = $( this );
            if(
                (input.attr( 'placeholder' ) != '' && input.attr( 'placeholder' ) != undefined ) &&
                (input.val() == '' || input.val() == input.attr( 'placeholder' ))
            )
            {
                input.addClass( 'placeholder' );
                input.val( input.attr( 'placeholder' ) );
            }

            //- Check if we are trying to style a "form" input, or a standard HTML input
            if( !input.hasClass( 'LayoutInput-input' ) )
            {
                input.removeClass( 'input-focussed' );
            }
            else
            {
                //- Bubble up until we find the LayoutInput-box
                input.parents( ".LayoutInput-box" ).removeClass( 'input-focussed' );
            }
        }
    ).blur();

    $( 'form' ).submit(
        function() {
            $.each( $( this ).find( ':input' ), function ()
            {
                if(
                    ($( this ).attr( 'placeholder' ) != '' && $( this ).attr( 'placeholder' ) != undefined ) &&
                    ($( this ).val() == $( this ).attr( 'placeholder' ))
                    )
                {
                    $( this ).val('');
                }
            } );
        }
    );
} );

var StatusDiv;
var StatusTimeout;
$( document ).ready( function () {
    StatusDiv = $( '.LayoutStatusMessage-floating' );

    $( window ).scroll( function () {
        if( StatusDiv.is( ":visible" ) )
        {
            StatusDiv.css( 'top', parseInt( $( window ).scrollTop() ) - 10 );
        }
    } );
} );

function ShowStatus( msg, type )
{
    var statusClass = 'LayoutStatusMessage-';
    switch( type )
    {
        case 'success':
        case 'info':
        case 'error':
        case 'none':
            statusClass += type;
            break;
        default:
            statusClass += 'info';
            break;
    }

    left = ( parseInt( $( window ).width() ) - 910 ) / 2;
    left = left < 0 ? 0 : left;

    scrolltop = parseInt( $( window ).scrollTop() ) - 10;

    StatusDiv.removeClass( 'LayoutStatusMessage-none' );
    StatusDiv.removeClass( 'LayoutStatusMessage-success' );
    StatusDiv.removeClass( 'LayoutStatusMessage-info' );
    StatusDiv.removeClass( 'LayoutStatusMessage-error' );

    StatusDiv.addClass( statusClass );
    StatusDiv.css( 'left', left );
    StatusDiv.html( msg );

    StatusDiv.animate( {top:scrolltop}, { duration:500, queue:false } ).fadeIn( 800 );

    clearTimeout( StatusTimeout );
    StatusTimeout = setTimeout( function() {
        StatusDiv.animate( {top:'-10px'}, { duration:500, queue:false } ).fadeOut( 800 );
    }, 10000 );
}

Number.prototype.toOrdinal = function ()
{
    var n = this % 100;
    var suff = ["th", "st", "nd", "rd", "th"]; // suff for suffix
    var ord = n < 21 ? (n < 4 ? suff[n] : suff[0]) : (n % 10 > 4 ? suff[0] : suff[n % 10]);
    return this + ord;
}

function to_html( text )
{
    if( text == undefined ) return ''

    return text
      .replace( /&/g, '&amp;'  )
      .replace( /</g, '&lt;'   )
      .replace( />/g, '&gt;'   )
      .replace( /"/g, '&quot;' )
      .replace( /'/g, '&#039;' )
}


//  Disable image dragging

document.ondragstart = function() { return false }

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = '' + string;
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function FindCurrentLocation( successFunction, errorFunction )
{
    // Try W3C Geolocation (Preferred)
    if( navigator.geolocation )
    {
        navigator.geolocation.getCurrentPosition
        (
            function( position )
            {
                successFunction( position.coords.latitude, position.coords.longitude )
            },
            function( error )
            {
                switch( error.code )
                {
                    case error.PERMISSION_DENIED:
                        errorText = 'You have denied iBuddy access to your location. Please enter a town/city.';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        errorText = 'We have been unable to determine your location. Please enter a town/city.';
                        break;
                    case error.UNKNOWN_ERROR:
                    default:
                        errorText = 'There has been an error determining your location. Please enter a town/city.';
                        break;
                }

                errorFunction( errorText )
            }
        );
        // Try Google Gears Geolocation
    }
    else if( google.gears )
    {
        var geo = google.gears.factory.create( 'beta.geolocation' );
        geo.getCurrentPosition
        (
            function( position )
            {
                successFunction( position.latitude, position.longitude )
            }
        );
    }
    else
    {
        errorFunction( 'We were unable to use GeoLocation to find you. Please type in your town/city.' )
    }
}

function GetTownName( lat, lng, successFunction, errorFunction )
{
    $.ajax( {
        url: '/ajax/get_town.php?lat=' + Url.encode(lat) + '&lng=' + Url.encode(lng),
        dataType: 'json',
        success: function( data ) {
            if( data.error != 0 )
            {
                errorFunction( 'Unable to find a town name.' );
            }
            else
            {
                successFunction( lat, lng, data.town );
            }
        }
    } );
}

function DimDiv( element, img, className )
{
    spinnerClass = 'LayoutDimDiv';
    if( className != '' && className != undefined )
        spinnerClass += ' ' + className;
    
    var div = $('<div class="' + spinnerClass + '"></div>');

    div.css({
        'width'  : element.outerWidth(),
        'height' : element.outerHeight(),
        'line-height': parseInt(element.height()) + 'px'
    });

    if( img == true )
    {
        div.html('<img src="/i/ajax-loader.gif" />');
    }

    //- Check if this element has a child
    if( $(':first', element).length != 0 )
        $(':first', element).before(div);
    else
        $(element).append(div);

    //- Check out the height of the image (the image height can be set by external css, hence why I have to add it to the document flow before checking)
    divImg = $( 'img', element );

    return div;
}

function lengthInUtf8Bytes(str) {
  // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
  var m = encodeURIComponent(str).match(/%[89ABab]/g);
  return str.length + (m ? m.length : 0);
}
