var PT = PT || {};

/**
 * Client-side timezone handling
 */
PT.timezone = {};

/**
 * Retreive the timezone UTC offset from browser and submit to server
 */
PT.timezone.submitTimeOffset = function (event, options) {
    var callback = options.reloadCallback || function () {};
    // get the UTC offset (in minutes) of the current client computer
    // note: the negative sign here inverts the time because this function
    // returns positive numbers to left of UTC (e.g. America)
    // and negative numbers to the right of UTC (e.g. Japan)
    // but we want the opposite, because that is how UTC is calculated
    // e.g. Mountain time is -7:00 (whereas this function returns +420)
//    var timeZoneOffset = -(new Date().getTimezoneOffset());
    var timeZoneOffset = PT.timezone.detectTimezone();
    // send it to the time zone handler on the server
    $j.get('/TimeZone/SubmitTimeZoneOffset/time_zone_offset:' + timeZoneOffset, {}, callback);
};

/**
 * Execute submitTimeOffset AND reload the page
 */
PT.timezone.refreshTimeZone = function (event, options) {
    SDNA.loading(options.target);
    var reloadCallback = function () {
        window.location.reload();
    }; 
    SDNA.Event.trigger(
        'submit_time_offset',
        {
            target : this,
            reloadCallback : reloadCallback
        }
    );
};

/**
 * Handle click events to refresh time zone
 */
PT.timezone.refreshTimeZone.click = function (event) {
    event.preventDefault();
    SDNA.Event.trigger(
        'refresh_time_zone',
        {
            target : this
        }
    );
};

// Setup events

SDNA.Event.create('refresh_time_zone', PT.timezone.refreshTimeZone);
SDNA.Event.create('submit_time_offset', PT.timezone.submitTimeOffset);

// Bind time zone link

$j('#refresh_time_zone').live('click.refresh_time_zone', PT.timezone.refreshTimeZone.click);

/**
 * Get the UTC offset in minutes respecting daylight savings time
 * 
 * @see http://www.michaelapproved.com/articles/timezone-detect-and-ignore-daylight-saving-time-dst/
 * @author Michael Khalili
 */
PT.timezone.detectTimezone = function () {
    var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
    var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
    var intMonth;
    var intHoursUtc;
    var intHours;
    var intDaysMultiplyBy;

    //go through each month to find the lowest offset to account for DST
    for (intMonth=0;intMonth < 12;intMonth++){
        //go to the next month
        dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);

        //To ignore daylight saving time look for the lowest offset.
        //Since, during DST, the clock moves forward, it'll be a bigger number.
        if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
            intOffset = (dtDate.getTimezoneOffset() * (-1));
        }
    }

    return intOffset;
}
