/*!
 * Name: jquery.z.js
 * Comment by Jumboluo 2012.1.13
 * 这是一个jQuery的自定义插件
 **/
(function($){
	if (typeof(console)=='undefined') {
		console = {
			log: function() {
			}
		}
	}
	var imageCache = [];
	$.fn.firstParent = function(selector) {
		return this.parents(selector).first();
	};
	//扩展：$().detectFocus()，将在获得焦点的时候有hasFocus的css类，而失去焦点的时候移除这个CSS类
	$.fn.detectFocus = function() {
		this.focus(function(){
			$(this).addClass("hasFocus");
		});
		this.blur(function(){
			$(this).removeClass("hasFocus");
		});
	};
	//扩展：$().liveDetectFocus()，作用同上，只是在匹配元素时及时元素是后来加进来的也一样有效果
	$.fn.liveDetectFocus = function() {
		this.live('focus',function(){
			$(this).addClass("hasFocus");
		});
		this.live('blur',function(){
			$(this).removeClass("hasFocus");
		});
	};
	//扩展：$().ajaxify(callback)
	$.fn.ajaxify = function(callback) {
		function applyCallback(self) {
			return function(response) {
				self.removeClass('loading');
				if (typeof(callback)=='function') {
					callback(response, self);
				}
			}
		}
		function doAjax(url, self, method) {
			var data = self.serialize();
			url += ((url.indexOf('?') == -1) ? '?' : '&') + 'ajax=1';
			if (method == 'post') {
				$.post(url, data, applyCallback(self), 'text');
			} else  {
				$.get(url, data, applyCallback(self), 'text');
			}
			return false;
		}
		function doClick(event) {
			var eventType = event.type.toLowerCase();
			var self = $(this);
			var confirmText = self.data('confirm');
			if (confirmText && !confirm(confirmText)) {
				return false;
			}
			var href = self.attr('href');
			if (href && eventType == 'click') {
				self.addClass('loading');
				doAjax(href, self, 'get');
				//event.preventDefault();
				return false;
			}
			var action = self.attr('action');
			if (action && eventType == 'submit') {
				if (event.type=='submit') {
					self.addClass('loading');
					doAjax(action, self, 'post');
					//event.preventDefault();
					return false;
				}
			}
		}
		this.bind('click submit', doClick);
		this.addClass('ajaxified');
	};
	$.fn.born = function() {
		// TODO
	};
	
	//扩展：$().oddEven() 将给偶数行添加odd的css类，而给基数行添加even的css类
	//这里特别留意到，似乎项目采用了PlayFramework！
	$.fn.oddEven = function() {
		// jQuery count from 0, but PlayFramework count from 1
		this.removeClass('odd');
		this.removeClass('even');
		this.filter(':odd').addClass('even');
		this.filter(':even').addClass('odd');
	}

	$.fn.toggleSlide = function() {
		//TODO
	}

	// parseJH / getJH / postJH
	// JSON + "\n\n" + HTML
	$.extend({
		//扩展：$.preloadImage(src)  预先载入图片到imageCache数组中
		preloadImage: function(src) {
			var image = document.createElement('img');
			image.src = src;
			imageCache.push(image);
		},
		//扩展：$.wbr(str)向str中没个3个字符就插入软换行（避开html代码和&...
		wbr: function(str) {
			var fragAry = [];
			for (var i=0;i<str.length;i=i+3) {
				var frag = str.substr(i,3);
				var fragLen=3;
				// prevent breaking html code
				while((frag.match(/<[^>]+$/))&&(fragLen<str.length-i)){
					fragLen++;
					frag = str.substr(i,fragLen);
				}
				// prevent breaking &...;
				while(
					(frag.match(/\&[a-zA-Z]{0,5}$/))
					&&str.substr(i+fragLen).match(/^[a-zA-Z]{0,5}\;/)
				){
					fragLen++;
					frag = str.substr(i,fragLen);
				}
				i+=(fragLen-3);
				fragAry.push(frag);
			}
			var newStr = fragAry.join('<wbr/>');
			return newStr;
		},
		//扩展：$.parseJH(response) 将response分成json和html返回。
		parseJH: function(response) {
			var json, html
			var index = response.indexOf("\n\n<!--JH-->\n");
			if (index == -1) {
				index = response.indexOf("\r\n\r\n<!--JH-->\r\n");
			}
			if (index != -1) {
				json = response.substr(0, index);
				html = response.substr(index + 2);
			} else {
				json = response;
			}
			json = $.parseJSON(json) || {"ret":-1};
			return {
				"json": json,
				"html": html
			};
		},

		//扩展：$.getJH(url, data, callback)，通过 ajax的get获取json和html
		//在common.feedback_box.js和fav_restaurants.add_delete.js里使用了
		getJH: function(url, data, callback) {
			if ( jQuery.isFunction( data ) ) {
				callback = data;
				data = null;
			}
			function processResponse(response) {
				callback($.parseJH(response));
			}
			return $.get(url, data, processResponse, 'text');
		},

		//扩展： $.postJH(url, data, callback)， 通过ajax的post方法获取json和html
		//暂时未见使用情况
 		postJH: function(url, data, callback) {
			if ( jQuery.isFunction( data ) ) {
				callback = data;
				data = {};
			}
			function processResponse(response) {
				callback($.parseJH(response));
			}
			return $.post(url, data, callback, 'text');
		}
	});
})(jQuery);
