if (!ask)
    var ask = {};

ask.currentTime = {};

/* Current Time RRSA */

// Global vars

// This var tells us when if the clock is ticking
ask.currentTime.clockEnabled = false;

// Global Constants

ask.currentTime.HOURS = 0;
ask.currentTime.MINS = 1;
ask.currentTime.SECN = 2;
ask.currentTime.AM_PM = 3;
ask.currentTime.DAY = 4;
ask.currentTime.MONTH = 5;
ask.currentTime.DAY_OF_THE_MONTH = 6;
ask.currentTime.YEAR = 7;
ask.currentTime.SECOND = 1000;
ask.currentTime.INVALID = -1;
ask.currentTime.TRANSITION_TIME = "12:00:00";

var _Days = new Array("MONDAY","TUESDAY","WEDNESDAY","THURSDAY", "FRIDAY", "SATURDAY","SUNDAY");
var _Months = new Array("JANUARY","FEBRUARY","MARCH","APRIL", "MAY", "JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER");

// NOTE : the different time and date values we want to extract and manipulate in this script are found in current_time_da.tag
// IMPORTANT : very likely, a change to current_time_da.tag will have an effect on this script. 

ask.currentTime.init = function(){

    var rrsaClock = document.getElementById("ctHoursMinutes");

    // Check to see if there is a current time widget :
    if(rrsaClock != null && !ask.currentTime.clockEnabled){

        // Yes, there is a current time RRSA widget shown :

        // the clock is now ticking
        ask.currentTime.clockEnabled = true;

        // Do we need to compute a new offset or do we have one already ?
        if( ask.currentTime.getStoredOffset() != ask.currentTime.INVALID){
            // Yes, we have an offset we can use :

            // On firefox, we want to change the date & time values on the current time widget immediately :
            if(a10.browser.isFirefox()){
                // Force an immediate update of the current time widget
                ask.currentTime.updateClock();
            }
            setTimeout("ask.currentTime.updateClock()",ask.currentTime.SECOND);
            return;
        }

        var rrsaTimeItems = ask.currentTime.getItems();

        // Tokenize localTime :
        var ctItems = rrsaTimeItems.split(':');

        // Now, get the individual items :
        var AmOrPm = a10.util.trim(ctItems[ask.currentTime.AM_PM]);
        var year = Number(ctItems[ask.currentTime.YEAR]);
        var currentMonth = new String(ctItems[ask.currentTime.MONTH]).toUpperCase();

        // Plain vanilla loop to avoid cross-browsing problems :
        var i = 0;
        for( i; i < _Months.length; i++ ){
            if( currentMonth == _Months[i]){
                break;
            }
        }

        var month = i; // the numeric value of the month : 0-11

        var day = ctItems[ask.currentTime.DAY]; //Day by name

        var dayOfMonth = Number(ctItems[ask.currentTime.DAY_OF_THE_MONTH]); //Day of the month
        // To find the hours, we need to keep in mind that the hours range for Date object is : 0-23
        var hours = Number(ctItems[ask.currentTime.HOURS]);

        // Put hours into a 0-23 format :
        if(AmOrPm == "AM" && hours == 12){ // 12AM maps to 0
            hours = 0;
        } else if(AmOrPm == "PM" && hours != 12){ // Add 12 to all the PM hours (except 12) to put in range 11-23
            hours += 12;
        }

        var mins = Number(ctItems[ask.currentTime.MINS]);
        var secn = Number(ctItems[ask.currentTime.SECN]);

        // Compute the initial time offset :
        var offset = ask.currentTime.computeOffset(year,month,dayOfMonth,hours,mins,secn);

        // Validate data
        if( !ask.currentTime.validate(year,month,dayOfMonth,hours,mins,secn,offset) ){
            // We have invalid data, do nothing
            return;
        }

        //Store offset into a hidden field so that we can use it after a browser refresh
        ask.currentTime.setStoredOffset(offset);
        setTimeout("ask.currentTime.updateClock()",ask.currentTime.SECOND);
    } else {
        // the clock is up & running, try again in one second...
        setTimeout("ask.currentTime.init()",ask.currentTime.SECOND);
    }
}


//This function starts and updates the clock (makes it tick every second)
ask.currentTime.updateClock = function(){
    var ctWidget = document.getElementById("ctHoursMinutes");

    // Now, check to see if there is a current time widget :
    if(ctWidget != null ){

        // Yes, there is a current time RRSA widget shown :
        var clientDate = new Date();

        // First, retrieve the elements to be updated :
        var ctHoursMinutes = document.getElementById("ctHoursMinutes");
        var ctSecs = document.getElementById("ctSecs");
        var ctAmPm = document.getElementById("ctAmPm");
        var ctDate = document.getElementById("ctDate");

        // Compute offset in milliseconds from the old RRSA date to a new (current) one :
        var offset = ask.currentTime.getStoredOffset();
        var myTime = clientDate.getTime();
        var dateInMS = myTime  +  offset;

        // Create the new rrsa date using time offset :
        var rrsaDate = new Date();
        rrsaDate.setTime(dateInMS);

        // Get the updated time and date values from rrsa date :
        var AmOrPm = null;
        var year = rrsaDate.getFullYear();
        var month = rrsaDate.getMonth();
        var monthName = _Months[month]; // get month by name
        var dayOfMonth = rrsaDate.getDate();
        var today = _Days[rrsaDate.getDay()]; //day by name
        var hours = rrsaDate.getHours();
        var mins = rrsaDate.getMinutes();
        var secn = rrsaDate.getSeconds();

        // Validate data :
        if( !ask.currentTime.validate(year,month,dayOfMonth,hours,mins,secn,offset) ){
            // We have invalid data, do nothing
            return;
        }

        // Adjust AM / PM
        if (hours >= 12){
            AmOrPm="PM";
        } else{
            AmOrPm="AM";
        }

        // Apply formatting to the values :
        if (hours >= 13){
            hours -= 12;
        }

        if (hours == 0){
            hours = 12;
        }

        // Format seconds : SS
        if (secn < 10){
            secn = "0" + secn;
        }

        // Format minutes : MM
        if (mins < 10){
            mins = "0" + mins;
        }

        // Format hours : HH
        if (hours < 10){
            hours= "0" + hours;
        }

        var time = hours+":"+mins+":"+secn;
        if( time == ask.currentTime.TRANSITION_TIME ){ //Is it 12:00:00 AM/PM ?
            // Yes, then force a page refresh to avoid problems with AM to PM transitions and viceversa :
            window.location.reload(true);
        }

        // Set the new formatted values in the DOM tree :
        ctAmPm.innerHTML = "<b>" + AmOrPm + "</b><br/>";
        ctSecs.innerHTML =  ":" + secn;
        ctHoursMinutes.innerHTML = hours + ":" + mins;
        ctDate = today + "," + rrsaDate.getDate() + " " + monthName + " " + rrsaDate.getYear();
        setTimeout("ask.currentTime.updateClock()",ask.currentTime.SECOND);
    } else {
        // Since there is no RRSA clock widget, the clock is now invalidated :
        ask.currentTime.clockEnabled = false;
        ask.currentTime.setStoredOffset(ask.currentTime.INVALID);
    }
}

// Do a sanity check to verify that we have a valid time & date :
ask.currentTime.validate = function(year,month,dayOfMonth,hours,mins,secn,offset){
    if( !ask.currentTime.validateString(year) || !ask.currentTime.validateString(month) || !ask.currentTime.validateString(dayOfMonth) || !ask.currentTime.validateString(hours)
            || !ask.currentTime.validateString(mins) || !ask.currentTime.validateString(secn) || !ask.currentTime.validateString(offset) ) {
        // We have an invalid date & time, ignore these values and retry again in one second :
        ask.currentTime.clockEnabled = false;
        ask.currentTime.setStoredOffset(ask.currentTime.INVALID);
        setTimeout("ask.currentTime.init()",ask.currentTime.SECOND);
        return false;
    }
    return true;
}

// This is a helper function to validate strings. Invalid formats are any non-number, blanks, and empty strings
ask.currentTime.validateString = function(str){

    var noBlanksStr = a10.util.trim(new String(str));

    if( isNaN(noBlanksStr) || a10.util.isEmpty(noBlanksStr) ){
        // invalid string
        return false;
    }
    // otherwise, it is a valid string
    return true;
}


// Store offset into a hidden field
ask.currentTime.getStoredOffset = function(){
    if(document.getElementById("offset") == null){
        return ask.currentTime.INVALID;
    }
    return Number(document.getElementById("offset").value);
}

// Get offset from hidden field
ask.currentTime.setStoredOffset = function( offset ){
    if(document.getElementById("offset") != null){
        document.getElementById("offset").value = offset;
    }
}

//Retrieve initial time, date, and timezone from RRSA clock widget.
ask.currentTime.getItems = function(){
    var ctHoursMinutes = document.getElementById("ctHoursMinutes");
    var ctSecs = document.getElementById("ctSecs");
    var ctAmPm = document.getElementById("ctAmPm");
    var ctDate = document.getElementById("ctDate");

    // For easier processing, concat all values into a single time and date string :
    var ctWidgetDate = ctHoursMinutes.innerHTML;
    ctWidgetDate += ctSecs.innerHTML;
    ctWidgetDate += ":" + ctAmPm.innerHTML;
    var ctTemp = ctDate.innerHTML;

    // Does the date string contain the special char \u0020 ?
    if(ctTemp.indexOf('\u0020') != ask.currentTime.INVALID ){
        // Yes, extract all chars minus special char : \u0020
        var ctItems = ctTemp.split('\u0020');
        ctWidgetDate += ":" + ctItems[0]; //Day
        ctWidgetDate += ":" + ctItems[1]; //Day of the month
        ctWidgetDate += ":" + ctItems[2]; //Month
        ctWidgetDate += ":" + ctItems[3]; //Year
    } else {
        // No, then just assign the original string
        ctWidgetDate += ":" + ctTemp;
    }

    // Set uppercase to avoid problems with Opera and IE versions 7 and 6 :
    ctWidgetDate = ctWidgetDate.toUpperCase();

    // Replace HTML :
    var currentTime = ctWidgetDate.replace(new RegExp("<BR>", "mig")," ");
    currentTime = currentTime.replace(new RegExp("<B>", "mig")," ");
    currentTime = currentTime.replace(new RegExp("</B>", "mig")," ");

    // Finally, replace some useless chars :
    currentTime = currentTime.replace(new RegExp(",", "mig")," ");
    currentTime = currentTime.replace(new RegExp("\n", "mig")," ");
    currentTime = a10.util.trim(currentTime);
    return currentTime;
}

// Find time offset between local (client) date and the rrsa widget date
ask.currentTime.computeOffset = function(year,month,dayOfMonth,hours,mins,secn){
    // Local time and date (i.e. time in California PT)
    var clientDate = new Date();

    // RRSA time and date  (i.e. time in Paris, New York, Tokyo, etc)
    var rrsaDate = new Date();
    rrsaDate.setFullYear(year,month,dayOfMonth);
    rrsaDate.setHours(hours,mins,secn);

    // Use the date method getTime() to determine the number of milliseconds that have elapsed since January 1, 1970.
    var clientMS = clientDate.getTime();
    var rrsaMS = rrsaDate.getTime();

    // Find the time offset in milliseconds between the two dates :
    return rrsaMS-clientMS;
}


