/*
	Connect Daily Web Calendar Software

	Copyright 2007, MH Software, Inc. All Rights Reserved
        5023 W 120th Ave #311, Broomfield CO 80020
	+1 303 438 9585

	Last Edit By: "$Author: gsexton $"
	Last Checkin: "$Date: 2008/09/17 20:24:29 $"
	Revision #  : "$Revision: 1.4 $"
*/

/**
 *  This file contains functions used in rendering RSS items.
 */

/** 
 * Search for URLs embedded in the text, and make them clickable HTML links.
 * 
 * @param sInput The input to search and replace.
 */
function makeURLsClickable(sInput){
    return sInput
    .replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,
             '<a href="$&" class="AjaxLink" target="_blank'+(new Date().getTime())+'">$&</a>')
    .replace(/([^\/])(www[\S]+(\b|$))/gim,
             '$1<a href="http://$2" class="AjaxLink" target="_blank'+(new Date().getTime())+'">$2</a>')
}

/** 
 * Format the description for an item. Basically, make URLs clickable, and replace 
 * carriage return/line feeds characters with <br> tags.
 * 
 * @param sInput The event Description
 */
function formatDescription(sInput){
    var s=makeURLsClickable(sInput);
    s=s.replace(/(\r\n|[\r\n])/g, "<br>");
    return s;
}

/** 
 * Format a date in RFC822 format to locale date format.
 * If the date is midnight in local time, then only the
 * date portion is returned, otherwise the date and time
 * portions are returned.
 * 
 * @param s The input date.
 */
function formatRFCDate(s){
    var sResult;
    var oDate=new Date(Date.parse(s));
    if (oDate.getHours()==0 && oDate.getMinutes()==0 && oDate.getSeconds()==0) {
        sResult=oDate.toLocaleDateString();
    } else {
        //sResult=oDate.toLocaleString();
		sResult=dateFormat(oDate, "dddd, mmmm dS, yyyy h:MM TT");
    }
    return sResult;
}


/** 
 * Render an RSS feed Item. This is the method to change if
 * you want to modify how an item in the RSS feed is displayed.
 * 
 * @param oItem The XML node for the item.
 */
function renderItem(oItem){
    var s="<strong>"
    var sScratch,sLink;
    sScratch=getNodeValue(oItem,"title");
    s=s+sScratch;
    s=s+'</strong><br/>';
    
    sScratch=getNodeValue(oItem,"cdaily:eventStartDate");
    s=s+""+formatRFCDate(sScratch)+"&nbsp;";
    sScratch=getNodeValue(oItem,"cdaily:addlInfoURL");
    if (sScratch!=null) {
        //s=s+'<DT>URL<DD><A CLASS=AjaxLink TARGET=_BLANK HREF="'+sScratch+'">'+sScratch+"</A>"
        s=s+'<A CLASS=AjaxLink TARGET=_BLANK HREF="'+sScratch+'">View Details...</A><br/>'
	}
    sScratch=getNodeValue(oItem,"cdaily:contactName");
    var sContact=sScratch;
    if (sScratch!=null) {
        s=s+"Contact: "+sScratch+"<br/>";
    }
    sScratch=getNodeValue(oItem,"cdaily:contactInfo");
    if (sScratch!=null) {
	if (sContact==null){
		s=s+"Contact Info:";
	}
        s=s+" "
        if (sScratch.indexOf('@')>0) {
            s=s+'<A HREF="MAILTO:'+sScratch+'">'+sScratch+'</A><br/>';
        } else {
            s=s+sScratch;
        }
    }
    sScratch=getNodeValue(oItem,"description");
    if (sScratch!=null) {
        s=s+"Description: "+formatDescription(sScratch);
    }
    s=s+"<br/>";
    
    return s;
}


function renderSimpleList(xmlData,iResult){

    if (iResult==200) {
        var channel=xmlData.documentElement.firstChild;
        var aItems=xmlData.getElementsByTagName("item")
        var s="<UL Class=AjaxItemList>";
        for (var i=0; i < aItems.length; i++) {
            var oItem=aItems[i];
            var sLink=getNodeValue(oItem,"link"), sTitle=getNodeValue(oItem,"title");
            s=s+'<LI><A _TARGET=_AJAXITEM Class=AjaxLink HREF="'+sLink+'">'+sTitle+'</A>'
            renderItem(oItem);
        }
        s=s+'</UL>'
        document.getElementById(ContentID).innerHTML=s;
    } else {
        alert(xmlData);
    }
}

/*
 * Date Format 1.2.2
 * (c) 2007-2008 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 && (typeof date == "string" || date instanceof 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 new 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);
};
