/**
 * @author Bob
 */
var CROWCODER;
if(!CROWCODER) CROWCODER = {};

/**
* @classDescription Emits a countdown timer to a webpage.
* @author Robert Crowley, www.crowcoder.com 2008
* @version 1.0
* @constructor
* @param {date} p_target_dt The Date/Time that the coundown
* is counting down to. THIS MUST BE UNIVERSAL TIME so
* display will be correct for any time zone
* @param {string} p_elem The HTML element id to emit the
* countdown display to.
* @param {string} p_msg The message to display in place of the
* countdown once time has run out.
*/

CROWCODER.JSCountdown = function(p_elem, p_msg) 
{
	
    // The number of milliseconds in one day
    var ONE_DAY = 86400000; 
    // ms in one hour
    var ONE_HR = 3600000;
    // ms in one min
    var ONE_MIN = 60000;
    // ms in one second
    var ONE_SEC = 1000;
     
    
    var target;
    var displayElem = document.getElementById(p_elem);
    var countdown_msg = p_msg;
    var event_started = false; 
    var getCountdown;
    var show_countdown;
    var _interval;
    var postUrl;
    var postUpdateFieldId;
    var appendText;
    var prependText;
    //Methods
    
    this.setDateString = function (dateString) {
    	var d = new Date(0);
    	d = CD_Parse(dateString);
    	this.setDateDate(d);
    }
    
    this.setDateDate = function (dt) {
    	target = dt;
    }
	
    this.setPostUrl = function(url) {
    	postUrl = url;
    }
    
    this.postUpdateFieldId = function(fieldId) {
    	postUpdateFieldId(fieldId);
    }
    
    this.setAppendText = function(text) {
    	appendText = text;
    }
    
    this.setPrependText = function(text) {
    	prependText = text;
    }
    /**
    * @method Updates the countdown display once per second.
    * @param {string} p_elem the id of the HTML element to emit the countdown display to
    * @param {date} p_target The date to countdown to
    * @param {string} p_msg The text to display in place of the countdown when time runs down
    */
    
    show_countdown = function()
    { 
        //Call this function each second to give an animated appearance to the countdown
        if(! this.event_started)
        {
            //Resets the time with each function call
            //var today = new Date();
            //var tdate = new Date(target);
            //Write the return of start_countdown to the chosen html element
            displayElem.innerHTML = getCountdown();
            displayElem.style.display='';
        }
        else
        {
            clearInterval(_interval);
        }
    }
    
    this.start = function ()
    {
    	if (!isNaN(target)) {
        _interval = setInterval(show_countdown, 1000);
        } 
    } 
    
    // Get Date() object from 2006-01-01 00:00:00 GMT+00:00 date format
	CD_Parse = function (strDate) {
		// Pattern match to a countdown date
	//	var objReDte = /(\d{4})\-(\d{1,2})\-(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{0,2})\s+GMT([+\-])(\d{1,2}):?(\d{1,2})?/;
		var objReDte = /(\d{4})\-(\d{1,2})\-(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{0,2})\s+([+\-])(\d{1,2})?/;
		if (strDate.match(objReDte)) {
			// Start with a default date and build it up into the countdown date through Date setter methods
			var d = new Date(0);
	
			d.setUTCFullYear(+RegExp.$1,+RegExp.$2-1,+RegExp.$3); // Set YYYY-MM-DD directly as UTC
			d.setUTCHours(+RegExp.$4,+RegExp.$5,+RegExp.$6); // Set HH:MM:SS directly as UTC
	
			// If there is a timezone offset specified then we need to compensate for the offset from UTC
			var tzs	= (RegExp.$7 == "-" ? -1 : 1); // Timezone sign
			var tzh = +RegExp.$8; // Get requested timezone offset HH (offset ahead of UTC)
		//	var tzm = +RegExp.$9; // Get requested timezone offset MM (offset ahead of UTC)
			var tzm = 00;
			if (tzh) {
				d.setUTCHours(d.getUTCHours() - tzh*tzs); // Compensate for timezone HH offset from UTC
			}
			if (tzm) {
				d.setUTCMinutes(d.getUTCMinutes() - tzm*tzs); // Compensate for timezone MM offset, depending on whether the requested MM offset is ahead or behind of UTC
			}
			return d; // Date now correctly parsed into a Date object correctly offset from UTC internally regardless of users current timezone.
		}
		else {
			return NaN; // Didn't match required date format
		};
	}
    
    /**
    * @method _get_countdown Returns HTML markup tagged for css formatting that
    * displays the countdown as 'xxdays:xxhrs:xxmins:xxsec'
    * @param {date} p_target The date/time the event to count down to starts
    * @param {date} p_today The date/time right now
    * @param {string} p_msg The text to display when time has hit zero
    */
    getCountdown = function()
    {
        //the HTML to emit with the countdown display
        var retval;        
        var p_today = new Date();
        // Convert both dates to milliseconds
        var target_ms = target.getTime();
        var now_ms = p_today.getTime();
        //The number of milliseconds between now and the target date/time
        var date_diff = target_ms - now_ms;
        
        //Stop timer when time ticks down
        if(date_diff > 0)
        { 
            // Number of days between now and target datetime is
            var difference_days = Math.abs(target_ms - now_ms);
            var num_days = Math.floor(difference_days/ONE_DAY);
            //We will subtract days_ms from date_diff to get the hrs, mins, secs left
            var days_ms = num_days * ONE_DAY;
            var difference_hrs = Math.abs(days_ms - date_diff);
            var num_hrs = Math.floor(difference_hrs/ONE_HR);
            var hrs_ms = num_hrs * ONE_HR;
            var difference_mins = Math.abs(((hrs_ms + days_ms)) - date_diff);
            var num_mins = Math.floor(difference_mins/ONE_MIN);
            var mins_ms = num_mins * ONE_MIN;
            var difference_secs = Math.abs((days_ms + hrs_ms + mins_ms) - date_diff);
            var num_secs = Math.floor(difference_secs/ONE_SEC);
            
            retval = '<span class="countdown"> ';
            if (prependText) {
            	 retval = retval +'<span class="preText">' + prependText + '</span>';
            }	 
            if (num_days > 0) {
            	 retval = retval +'<span class="days">' + num_days.toString() + '</span><span class="time_delim"> days: </span>';
           	}
           	if (num_hrs >0) {
            	retval = retval +'<span class="hrs">' + num_hrs.toString() + '</span><span class="time_delim"> hrs: </span>';
            }
            retval = retval +'<span class="mins">' + num_mins.toString() + '</span><span class="time_delim"> min: </span>';
            retval = retval +'<span class="secs">' + num_secs.toString() + '</span><span class="time_delim">s</span> ';
            if (appendText) {
            	 retval = retval +'<span class="postText">' + appendText + '</span>';
            }	  
            retval = retval + '</span>';
        }
        else
        {
            event_started = true;
            retval = countdown_msg;
            
            if (postUrl) {
				// Redirect to a URI
				location.href = postUrl;
			}
			
			if (postUpdateFieldId) { 
				document.getElementById(postUpdateFieldId).value = 1;
			}
        }
        return retval;
    }
    
    function ToLocalTime(p_target_dt)
    {
        var rightow = new Date();
        var rightNowUTC = p_target_dt;
        var timediff = rightow.getTimezoneOffset();
        
        rightNowUTC.setMinutes(rightNowUTC.getMinutes() - timediff);
        
        return rightNowUTC;
    }
}

