(function($){

	$.fn.radiomatic = function(options) {

		// The $parent is the DIV we're targeting for all the content
		var $parent = $(this);
		$parent.addClass('_parent itemParent');
		
		// Save the options data about this widget in the parent
		$parent.data('options', options);
		
		// Set hover for parent
		$parent.hover(function(){
			// Hover ON
			if(!$('html').data('editMode')){
//				$(this).css('border','2px solid blue');
			}
		}, function(){
			// Hover OFF
			if(!$('html').data('editMode')){
//				$(this).css('border','');
			}
		});
		
		$.getJSON(options.json, { }, function(data) {

			// Merge all the items into the parent and store the collection of $items
//			var $items = $parent.append($(options.view).tmpl(data));
			$parent.append($(options.view).tmpl(data));			
			
			// Add editing stuff if logged in
			var login = ($.cookie('radiomaticAUTH') == 'yes') ? true : false;
			
			if(login){
			
				// Add edit button and events to each item that was just added.
				//addItemEvents($parent.children('._item'));
				$parent.find('._item').editable();

			} // if(login)
			
	
			// This next line is needed to fix the height of elements on the home page after data has been loaded. This should be moved to a callback so it's not embedded in here...
			if(typeof options.callback == 'function'){
				callback.call(this)	
			}
			
			return $(this);
		});

	}})( jQuery );
		
(function($){
	
	$.fn.editable = function(callback) {
		
		var $items = $(this);

//		$items.append('<a class="_edit" href="#">edit</a>'); // This is now moved to the template to allow for more flexibility
				
		// Toggle the display of items as we hover over them
		$items.hover(function(){
			// Hover on, only if not currently in edit more
			if(!$('html').data('editMode')){
				$(this).addClass('editHover'); //.find('._edit').show();
			}
		}, function(){
			// Hover off
			$(this).removeClass('editHover'); //.find('._edit').hide();
		});
		
		
		// Wire up any approve/decline buttons
		$items.find('._status').click(function(e){
			console.log("status to change");
			e.preventDefault();
			
			// Get all the needed objects
			var $item = $(this).closest('._item');
			var $parent = $(this).parents('._parent');
			var options = $parent.data('options');
			var currentIndex = $item.index($parent);
			var key = $item.data('key');

			// Submit this to the back-end
			$.getJSON(options.json, { action: $(this).text().toLowerCase(), itemIndex: currentIndex, id: key }, function(data) {
				// action is either approve or decline
				if(data[0].response_status == 'OK'){
					$(options.view).tmpl(data).replaceAll($item).editable(function(){});
				}
				else {
					alert('Oops...there was a problem. This can happen if you haven\'t used the system in a while and your session timed out. Please try logging in again.');
				}
			});
			
		});

		
		
		

		// This handles clicks to edit button, or doubleclick
		$items.find('._edit').click(function(e){
			// Make sure we don't actually fire off the <a>
			e.preventDefault();
			
			// Show that we're currently in edit mode
			$('html').data('editMode', true);
			
			// Get all the needed objects
			var $parent = $(this).parents('._parent');
			var $items = $parent.find('._item');
			var options = $parent.data('options');
			
			// Remove any 'editing' formatting currently applied to all the $items
			$items.removeClass('editActive');
			
			// Get the current <a> being clicked
			var $this = $(this);
			var $item = $this.closest('._item');

			// Get the position of our form, which will be beneath this item
			var posTop = ($item.offset().top + $item.height()) + "px";
			var posLeft  = ($item.offset().left) + "px";
			
			// Save the index position of the item we're editing, so we can update it later
			var currentIndex = $('._item').index($this.parent('._item'));

			// Grab the ID of this record, from the HREF, and store it
			var key = $item.data('key');
									
			// Highlight the item we're editing
			$item.addClass('editActive');
										
			// Get the data with JSONP
			$.getJSON(options.json, { id: key, action: 'get' }, function(data) {

				// Use a template to merge the JSON data into the form
				var $form = $(options.form).tmpl(data).appendTo($parent);
				$form.addClass('_form');
				
				// Position the form below the item
				$form.css('position', 'absolute').css('top', posTop).css('left', posLeft).show();
			
				// Wire up the cancel button
				$form.find('._cancel').click(function(){
					$items.removeClass('editActive');
					$('html').data('editMode', false);					
					$form.remove();
				});
				
				// Wire up the submit button for the form
				$form.submit({ itemKey: key, itemIndex: currentIndex, item: $item }, function(e){
					e.preventDefault();
					
					// Send everything to the server
					$.getJSON(options.json, $form.serializeArray(), function(data) {
						// Check for success or failure, then tell the user.
						if(data[0].response_status == 'OK'){
							
							// Update the item with fresh data and indicate the update. Later move this to a banner notification instead.
							$(options.view).tmpl(data).replaceAll($item).editable(function(){
								// This will flash the update green and then fade to WHITE. BROKEN. Instead show status update in bar at top of page.
//								$(this).animate( { backgroundColor: 'green' }, 50 ).animate( { backgroundColor: 'transparent' }, 1500 ).attr('style','background-color="auto"');
							});

							// Fade out the form and get rid of it
							$form.fadeOut('fast', function(){
								$form.remove(); // Completely remove the form now that we're done with it.
								$('html').data('editMode', false);
							});
							
						}
						else if(data[0].response_status=='error'){
							alert('Error - not authenticated.\nYou are not authenticated to the system. This can happen if you haven\'t been using the system for 2 hours and your session is automatically signed off.');	
							$form.remove(); // Completely remove the form now that we're done with it.
							$('html').data('editMode', false);
						}
						else {
							alert('Oops...there was a problem submitting the form.');
							$form.remove(); // Completely remove the form now that we're done with it.
							$('html').data('editMode', false);
						}
						
					}); // getJSON
				});
			});					
		});
		if(typeof callback == 'function'){
			callback.call(this)	
		}
		return $(this)

	}})( jQuery );
		
		
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Create multiple cookies at once stored in an object, with optional parameters affecting them all.
 *
 * @example $.cookie({ 'the_cookie' : 'the_value' });
 * @desc Set/delete multiple cookies at once.
 * @example $.cookie({ 'the_cookie' : 'the_value' }, { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Set/delete multiple cookies with options.
 *
 * @param Object name An object with multiple cookie name-value pairs.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the names and values of all cookies for the page.
 *
 * @example $.cookie();
 * @desc Get all the cookies for the page
 *
 * @return an object with the name-value pairs of all available cookies.
 * @type Object
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined'  ||  (name  &&  typeof name != 'string')) { // name and value given, set cookie
        if (typeof name == 'string') {
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = name + '=' + encodeURIComponent(value) + expires + path + domain + secure;
        } else { // `name` is really an object of multiple cookies to be set.
          for (var n in name) { jQuery.cookie(n, name[n], value||options); }
        }
    } else { // get cookie (or all cookies if name is not provided)
        var returnValue = {};
        if (document.cookie) {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (!name) {
                    var nameLength = cookie.indexOf('=');
                    returnValue[ cookie.substr(0, nameLength)] = decodeURIComponent(cookie.substr(nameLength+1));
                } else if (cookie.substr(0, name.length + 1) == (name + '=')) {
                    returnValue = decodeURIComponent(cookie.substr(name.length + 1));
                    break;
                }
            }
        }
        return returnValue;
    }
};



















// Global functions and such

function overlay(display, options){

	if(!options){
		options = {};
		options.iframe = null;
	}

	if(!options.iframe) options.iframe = null;
	
	var $under = $('._rm_underlay');
	var $over = $('._rm_overlay');
	
	if($over.length==0){
		$('body').append('<div class="_rm_overlay"><a href="javascript:overlay(false);" style="float:right">Hide</a><div></div></div>');
		$over = $('._rm_overlay');
	}
	
	if($under.length==0){
		$('body').append('<div class="_rm_underlay">&nbsp;</div>');
		$under = $('._rm_underlay');
	}

	console.log(options.iframe);

	if(display){
		if(options.iframe != null){
			$over.find('div').empty().append('<iframe src="' + options.iframe + '" frameborder="0"></iframe>');
			$over.find('iframe').css('width', '100%').css('height', $over.height());
			
		}
		$under.show();
		$over.show();
	}
	else {
		$under.hide();
		$over.hide();		
	}

}






