/*
 * $ WG Ajax plug-in 1.0
 * Copyright (c) 2008 Roberto Lee
 */
 /*
 * $ plug-in WG Ajax  2.0
 *
 * Copyright (c) 2008 Roberto Lee (webgenerator.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Date: 2009-07-07
 * Rev: 2
 *
 * Comment remove log methods when live
 * todo location.protocol+"//"+location.host+"/
 */

(function($){
     $.fn.extend({
         WG_Ajax: function(options) {
	        var defaults = {
				path_loading_image: 'ajax_loading.gif',
				url: '',
				traverse_partial: '',
				default_error_msg: '',
				old_content_on_error: false,
				loadingpaddingtop: '15',
				loadingpaddingbottom: '0',
				refresh_interval_seconds: 0, //todo
				async: false,
				cache: false,
				cb: function(){},
				cb_success: function(){},
				cb_error: function(){}
	        };
	        var options = $.extend(defaults, options);

            return $(this).each(function(idx) {// Don't break the chain
				if($.trim(options.url) != '')
				{
							try {
				            	html_elem = this;
				            	//$.log($(html_elem).context.nodeName);
								var oldContent = $(this).html();
								var LoadingImageDiv = $('<div/>')	.addClass('ajax_container')
																	.css({
																		'color': 'red',  'font-size': '12px', 'text-align': 'center',
																		'width': '100%', 'margin': '0px',
																		'padding': options.loadingpaddingtop+'px 0px '+options.loadingpaddingbottom+'px 0px'
																	})
																	.append($('<img/>').attr({
																							'src':	options.path_loading_image,
																							'alt':  'loading...'
																						})
																);
								$(html_elem).html(LoadingImageDiv);
								GetContentAjax();

								//$(html_elem).bind('click', function(event) { GetContentAjax(); })
							}
							catch (e) {
								$(html_elem).html($(LoadingImageDiv).html(e.message));//Catch cross domain error
								//$.log(e.message + " - " + $(html_elem) );
							}
				}
				else
				{
					//$.log(options.url + ' - no or bad url');
				}


				function GetContentAjax()
				{
						var ajax_result = $('<div/>');
						$.ajax({
								async: options.async,
								cache: options.cache,
								url: options.url,
								beforeSend: function(){
								},
								success: function(data){
									ajax_result.append($.trim(data));
									if(ajax_result.find(options.traverse_partial).is('*'))
									{
										ajax_result = ajax_result.find(options.traverse_partial);
										//$.log(typeof(ajax_result));
									}
									options.cb_success.call();
								},
								error: function(xhr, ajaxOptions, thrownError){
									var errMsg = $.trim(options.default_error_msg) == '' ? xhr.statusText + " ("+xhr.status+")"   :   options.default_error_msg;
									ajax_result.html(options.old_content_on_error == false ? $(LoadingImageDiv).html(errMsg) : oldContent);
									//$.log('error: ' + errMsg);
									options.cb_error.call();
								},
								complete: function(){
									$(html_elem).html(ajax_result.html());
									options.cb.call();
								}
						})

							//if(options.refresh_interval_seconds > 0){setInterval(GetContentAjax, options.refresh_interval_seconds*1000)};

				}
            });
		}
    });
})(jQuery);

