

/*
 * Pops up an informational message with an Ok button. No input other than the
 * close event will be taken from the shown message box.
 */
function messageBox(title, message) {
    function closeHandler() {
        dialog.hide();
    }

    dialog = new YAHOO.widget.Dialog("MessageBox", {
        visible:true,
        buttons:[{
            text:"OK",
            handler: closeHandler,
            isDefault: true
        }],
        draggable:false,
        close:false,
        modal:true
    });
    dialog.setHeader(title);
    dialog.setBody(message);
    dialog.render(document.body);
    dialog.center();
}


/*
 * Pops up a modal dialog showing a message and an optional image.
 * This message box can only be closed programatically; No close button is shown.
 * This function returns the created dialog.
 */
function systemMessageBox( title, message, img ) {

    // dialog box body
    var dialogBody = "<div>" + message + "</div>";
    if( img ) {
        dialogBody += "<div><img src='" + img + "'/></div>";
    }

    dialog = new YAHOO.widget.Dialog("ProgressMessageBox", {
        visible:true,
        buttons:[],
        draggable:false,
        close:false,
        modal:true
    });
    dialog.setHeader(title);
    dialog.setBody(dialogBody);
    dialog.render(document.body);
    dialog.center();

    return dialog;
}


/**
 * Submits a form via ajax
 */
function ajaxSubmit( formId, successHandler, failureHandler ) {
    // Get the form
    var form = YAHOO.util.Dom.get( formId );
    YAHOO.util.Connect.setForm(form);

    // Make the ajax call
    var callback = {
        success: successHandler,
        failure: failureHandler,
        argument: ''
    };
    var transaction = YAHOO.util.Connect.asyncRequest('POST', form.action, callback);
}


/**
 * Performs a remote request
 */
function ajaxRequest(url, successHandler, failureHandler ) {
    // Make the ajax call
    var callback = {
        success: successHandler,
        failure: failureHandler,
        argument: ''
    };
    var transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

/**
 * Performs a remote POST request
 * contentType is optional.
 */
function ajaxPost(url, successHandler, failureHandler, message, contentType) {
	// Make the ajax call
	var callback = {
        success: successHandler,
        failure: failureHandler,
        argument: ''
    };
	
	if( contentType ) {
		YAHOO.util.Connect.setDefaultPostHeader(false);
		YAHOO.util.Connect.initHeader("Content-Type", contentType);
		YAHOO.util.Connect.initHeader("Accept", contentType);
	}
	
    var transaction = YAHOO.util.Connect.asyncRequest('POST', url, callback, message);
}

/**
 *Perform synchronous remote request
 *REQUIRES jQuery library
 */
function syncRequest(url, beforeSubmit, successHandler, failureHandler, timeout, dataType){
    $.ajax({
        url: url,
        beforeSend: beforeSubmit,
        success: successHandler,
        error: failureHandler,
        timeout: timeout,
        dataType: dataType,
        async: false
    });
}


/*
 * Initializesan auto-complete box tied to a particular component id
 */
function initAutoCompleBox( componentId, dataUrl ) {

    // Use an XHRDataSource
    var oDS = new YAHOO.util.XHRDataSource(dataUrl);
    // Set the responseType
    oDS.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
    // Define the schema of the JSON results
    oDS.responseSchema = {
        resultsList : "Suggestions",
        fields : ["value"]
    };

    // Instantiate the AutoComplete
    var oAC = new YAHOO.widget.AutoComplete(componentId, componentId+"_div", oDS);
    // Throttle requests sent
    oAC.queryDelay = .5;
    oAC.allowBrowserAutocomplete = false;
    // The webservice needs additional parameters
    oAC.generateRequest = function(sQuery) {
        var val = YAHOO.util.Dom.get(componentId).value;
        return "?output=json&value=" + val;
    };

    YAHOO.util.Event.onDOMReady(function(){
        //set the width of the auto-complete container to the width of the auto-complete input element
        YAHOO.util.Dom.setStyle(componentId+'_container', 'width', YAHOO.util.Dom.getStyle(oAC.getInputEl(),'width'));
    });

}


/**
 * Initializes a carousel
 */
function initCarousel(carouselId, carouselOpts) {
    var carousel = new YAHOO.widget.Carousel(carouselId + "_div", carouselOpts);
    return carousel;
}


/*
 * Initializes a calendar picker. This function is for internal framework use only.
 */
function initCalendarPicker(pickerId, dateFormat) {

    var Event = YAHOO.util.Event,
    Dom = YAHOO.util.Dom,
    dialog,
    calendar;

    var showBtn = Dom.get("show" + pickerId);

    Event.on(showBtn, "click", function() {

        // Lazy Dialog Creation - Wait to create the Dialog, and setup document click listeners, until the first time the button is clicked.
        if (!dialog) {

            // Hide Calendar if we click anywhere in the document other than the calendar
            Event.on(document, "click", function(e) {
                var el = Event.getTarget(e);
                var dialogEl = dialog.element;
                if (el != dialogEl && !Dom.isAncestor(dialogEl, el) && el != showBtn && !Dom.isAncestor(showBtn, el)) {
                    dialog.hide();
                }
            });


            function clearHandler() {
                // Clear the text field and hide the dialog
                Dom.get(pickerId).value = "";
                dialog.hide();

                // Reset the calendar
                calendar.clear();
                calendar.render();
            }

            function closeHandler() {
                dialog.hide();
            }

            dialog = new YAHOO.widget.Dialog(pickerId + "_container", {
                visible:false,
                context:["show" + pickerId, "tl", "bl"],
                buttons:[{
                    text:"Clear",
                    handler: clearHandler
                },
                  {
                    text:"Close",
                    handler: closeHandler,
                    isDefault: true
                }],
                draggable:false,
                close:true
            });
            dialog.setHeader('Pick A Date');
            dialog.setBody('<div id="cal"></div>');
            dialog.render(document.body);

            dialog.showEvent.subscribe(function() {
                if (YAHOO.env.ua.ie) {
                    // Since we're hiding the table using yui-overlay-hidden, we
                    // want to let the dialog know that the content size has changed, when
                    // shown
                    dialog.fireEvent("changeContent");
                }
            });
        }

        // Lazy Calendar Creation - Wait to create the Calendar until the first time the button is clicked.
        if (!calendar) {

            calendar = new YAHOO.widget.Calendar("cal", {
                iframe:false,          // Turn iframe off, since container has iframe support.
                hide_blank_weeks:true,  // Enable, to demonstrate how we handle changing height, using changeContent
                navigator:true          // Enable, to be able to easily navigate to dates
            });
            calendar.render();

            calendar.selectEvent.subscribe(function() {
                if (calendar.getSelectedDates().length > 0) {

                    var selDate = calendar.getSelectedDates()[0];
                    Dom.get(pickerId).value = selDate.format(dateFormat);
                    
                }
                else {
                    Dom.get(pickerId).value = "";
                }
                dialog.hide();
            });

            calendar.renderEvent.subscribe(function() {
                // Tell Dialog it's contents have changed, which allows
                // container to redraw the underlay (for IE6/Safari2)
                dialog.fireEvent("changeContent");
            });
        }

        var seldate = calendar.getSelectedDates();

        if (seldate.length > 0) {
            // Set the pagedate to show the selected date if it exists
            calendar.cfg.setProperty("pagedate", seldate[0]);
            calendar.render();
        }

        dialog.show();
        dialog.bringToTop();
    });
}

function addMarker( map, latitude, longitude, iconUrl, markerWindowNode ) {
    var point = new google.maps.LatLng(latitude, longitude);
    var pIcon = new google.maps.Icon(G_DEFAULT_ICON);
    pIcon.image = iconUrl;
    pIcon.iconSize = new google.maps.Size(32, 37);
    var options = {icon:pIcon};
    var marker = new google.maps.Marker(point, options);
    

    // OnClick event for the marker
    if( markerWindowNode != null ) {
        marker.bindInfoWindowHtml(markerWindowNode.innerHTML, {});
    }

    map.addOverlay(marker);

    return marker;
}


//** --------------- Third Party Code ------------------------------------------
/*
 * 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);
};





