/*
 * Count Down Events
 * (c) 2009 Digicom Pty Ltd <andrew.mason@digicom.net.au>
 * 
 *
 */

function eventCountDown( displayInCurTimeZone )
{
    // Get all elements with a class of 'datetime' 
    // as these are used for events 
    $(document).ready(function(){
        var events = $('.datetime');

        if( events )
        {
            events.each( function(){
                
                var date = $(this).attr('jws:date');

                var id   = $(this).attr('id');
      
                // Define default messages
                var message_pre    = $(this).attr('jws:countdown_pre');
                var message_during = $(this).attr('jws:countdown_during');
                var message_post   = $(this).attr('jws:countdown_post');
                var duration       = $(this).attr('jws:duration');
                
                
                // the element must have a jws:date AND an xml/sgml id
                if( id && date )
                {

                    var myDate = dateToArray( date );
                    if ($(this).attr('jws:countdown_pre')) {
                        message_pre = $(this).attr('jws:countdown_pre');
                    }
                    if ($(this).attr('jws:countdown_during')) {
                        message_during = $(this).attr('jws:countdown_during');
                    }
                    if ($(this).attr('jws:countdown_post')) {
                        message_post = $(this).attr('jws:countdown_post');
                    }
                    if ($(this).attr('jws:countdown_duration')) {
                        duration = $(this).attr('jws:countdown_duration');
                    }
                    
                    displayTZCountDown( 
                        setTZCountDown(myDate['year'],myDate['month'], myDate['day'], myDate['hour'], 
                        myDate['minute'], myDate['UTCOffset']), id, message_pre, message_during, 
                        message_post, duration );

                }
            });
        }
    });
}

/**
 * Grab all of the elements on the page which have a class of 'yourtime'
 * and see if they have a title attribute set. If they do and the title attribute
 * is of a given date format then display that date in the timezone of the clients
 * browser
 * 
 */
function dateInYourTime()
{
    $(document).ready(function(){
                
        var yourtime = $('.yourtime');
        yourtime.each( function(){
            
            var date = $(this).attr('jws:date');
            if( date )
            {
                var myDate        = dateToArray( date );
                var eventDate     = dateAtTimeZone( myDate, myDate['UTCOffset'] );
                var yourTimeText  = $(this).text();
                
                if( yourTimeText != null )
                {
                    // replace the time 
                    if( yourTimeText != null  )
                    {
                        var str       = eventDate.format('dddd, d mmmm, h:MM TT ');
                        var timeGMT   = eventDate.format('HH:MM');
                        var offsetGMT = eventDate.format( eventDate.format('o') );
                        $(this).html( str );
                    }
                }
            }
        });

        var yourtimezone = $('.yourtimezone');
        yourtimezone.each( function(){
            
            var tzText = $(this).attr('title');
            var eventDate = new Date();
            if( tzText != null )
            {
                // replace the text
                if( tzText.indexOf('__tz__') >= 0 )
                {
                    tzText  = tzText.replace( /__tz__/, eventDate.format('o'));
                    var x = $(this).text(tzText);
                    
                }
            }
        });
    });
}
                        
function callInYourTime()
{
    $(document).ready(function(){
                
        var events = $('.callyourtime');
        events.each( function(){
            var date = $(this).attr('jws:date');
            
            if( date )
            {
                var myDate = dateToArray( date );
                var eventDate = dateAtTimeZone( myDate, myDate['UTCOffset']);
                var yourTimeText = $(this).attr('description');
                
                if( yourTimeText != null )
                {
                    if( yourTimeText.indexOf('__time__') >= 0 )
                    {
                        var str = eventDate.format('dddd, mmmm d, h:MM TT<br />[ HH:MM')+' GMT '+eventDate.format('o') + ' ]';
                        yourTimeText = yourTimeText.replace( /__time__/, str );
                        $(this).html(yourTimeText);
                    }
                }
            }
        });
     });
}                   
            
function dateToArray( datestr )
{

    var mydate = new RegExp( "^([0-9]{4})[-]([0-9]{2})[-]([0-9]{1,2})[-]([0-9]{1,2})[-]([0-9]{1,2})[-]([-|+])([0-9]{2})([0-9]{2})" , 'g');
    var x = mydate.exec( datestr );
    
    var components = new Object();
    if( x != null )
    {

        components.year     = x[1];
        components.month    = x[2];
        components.day      = x[3];
        components.hour     = x[4];
        components.minute   = x[5];
        components.tzsign   = x[6];
        components.tzhour   = parseInt(x[7]);
        components.tzminute = parseInt(x[8]);
        if( components.tzminute != 00 )
        {
           components.tzminute = (components.tzminute/60) ;
        }
        else
        {
            components.tzminute = parseInt(x[8]);
        }

        var i = (components.tzhour+components.tzminute);
        i = i.toFixed(2);
        components.UTCOffset = components.tzsign+i;
        
        
    }
    return components;
}
        
/**
 *
 *
 */        
function dateAtTimeZone( eventDate, Tz )
{
    var clientDate = new Date();
    var event = new Date();
    var eventts;
    var clientOffset;
    var eventOffset;
        
    // get the event offset in mins
    eventOffset = tztomins( Tz );
    eventOffset = eventOffset*1000;
        
    // get client offset
    clientOffset = (clientDate.getTimezoneOffset()*1000);

    // get the time of the event in seconds 
    //  The -1 is because for some unknown reason month is zero indexed whilst
    //  everything else isn't.
    eventts = Date.UTC(eventDate['year'],(eventDate['month']-1),eventDate['day'],
                       eventDate['hour'] ,eventDate['minute'],'00','00');

    eventts = (eventts + eventOffset);
    return new Date(eventts);

}

function tztomins( Tz )
{
    // we * by -1 because if the offset is -4 we actually need to 
    // add 4 hours to get to UTC time. if its +4 we need to -4 to get to 
    // UTC time 
    return (((Tz*3600)*-1));
}
        
function setTZCountDown(year, month, day, hour, mins, tz) 
{
    year = parseInt(year, 10);
    month = parseInt(month, 10) - 1;
    day = parseInt(day, 10);
    hour = parseInt(hour, 10);
    mins = parseInt(mins, 10);
    tz = parseFloat(tz);

    var toDate = new Date();
    toDate.setFullYear(year, month, day);
    toDate.setHours( hour );
    toDate.setMinutes( mins - (tz*60) );
    toDate.setSeconds( 0 );

    var fromDate = new Date();
    fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());

    var diffDate = new Date(0);
    diffDate.setMilliseconds(toDate - fromDate);

    countdown_msec = Math.floor( diffDate.valueOf() );
    countdown_sec = Math.floor( countdown_msec/1000 );

    // Automatically refresh the page 10 seconds after countdown ends
    if (countdown_sec > 0) {
        refresh_msec = countdown_msec + 10000;
        if (refresh_msec > 2147483647) {
            refresh_msec = 2147483647;
        }
        // writeError('window.location: refresh_msec = ' + refresh_msec);
        setTimeout('window.location = window.location;', refresh_msec);
    }

    return(countdown_sec);
}

function displayTZCountDown(countdown, elementID, preMsg, duringMsg, postMsg, duration) 
{
    var poscount = countdown;

    // writeError('elementid = ' + elementID);
    // writeError('countdown1 = ' + countdown);

    if (!document.getElementById(elementID)) {
        
        return;
    }

    // Ensure countdown is positive
    if (countdown < 0) {
        poscount = 0 - countdown;
    }

    // Break countdown into days/hours/mins/secs
    var secs = poscount % 60; 
    if (secs < 10) secs = '0' + secs;
    var poscount1 = (poscount - secs) / 60;
    var mins = poscount1 % 60; 
    if (mins < 10) mins = '0' + mins;
    poscount1 = (poscount1 - mins) / 60;
    var hours = poscount1 % 24;
    // if (hours < 10) hours = '0' + hours;
    var days = (poscount1 - hours) / 24;

    // Create the countdown string: x days 00:00:00
    var countdownStr = '';
    if (days > 0) {
        countdownStr = days + ' day' + (days == 1 ? '' : 's') + ', ';
    }
    countdownStr += hours + ':' + mins + ':' + secs;



    if (countdown > 0) {
        // PRE Phase: Countdown is progressing

         var el = document.getElementById(elementID);
//         preMsg.replace(/__countdown__/, countdownStr)
           innerXHTML(el , preMsg.replace(/__countdown__/, countdownStr));
    }
    else if (countdown < 0 && poscount < duration) {
        // DURING Phase

        if (duration > 0) {
            if (duringMsg.indexOf('__countdown__') >= 0) {
                var el = document.getElementById(elementID); 
                innerXHTML(el , duringMsg.replace(/__countdown__/, countdownStr));

                // Refresh the page at end of post count
                if (poscount >= duration - 2 && poscount <= duration) {
                    setTimeout('window.location = window.location;', 3000);
                }
                if (poscount > duration) {
                    
                    var el = document.getElementById(elementID); 
                    innerXHTML(el , '');
                    return;
                }
            }
            else {
                // Refresh the page at end of post count
                setTimeout('window.location = window.location;',
                    (duration + countdown) * 1000);
                return;
            }
        }
        else {
            var el = document.getElementById(elementID); 
            innerXHTML(el , duringMsg.replace(/__countdown__/, ''));
        }
    }  
    else if (countdown < 0 && poscount >= duration ) {
        // this function doesn't take into account the year so as a hack we just make sure that 
        // the month of the event is less than or equal to the the current month
        // POST Phase

        // writeError('POST Phase poscount = ' + poscount);

        var el = document.getElementById(elementID); 
        innerXHTML(el , postMsg);
        return;
    }

    // Note: Could also consider using setInterval which uses same args
    setTimeout('displayTZCountDown('+(countdown-1)+',\''+elementID+'\',\''+preMsg+'\',\''+duringMsg+'\',\''+postMsg+'\','+duration+');', 999);
}

/**
 * EVERYTHING BELOW THIS LINE 
 * 
 * 
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

