/**
 * MISC for jQuery
 *
 * http://19dog.com
 *
 * Copyright (c) 2007 Jcan.Zhong[ jcan.zhong(#)gmail.com]
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */
$.browser.unie7 = /msie (5|6)/i.test(navigator.userAgent);
$.extend({
	//一个可能值: ad87dk1cghc
	uid : function()
	{
		return (new Date().getTime()*10000+Math.random(1)*10000).toString(32);
	},

	showMask : function(opacity)
	{
		if (!opacity) {
			$('#jmask').hide();
			return;
		}

		$('#jmask').length && $('#jmask').remove();

		var jMask = $(document.createElement('div'));
		var doc = $.browser.opera ? document.body : document.documentElement;
		jMask.appendTo(document.body)
			.attr('id', 'jmask')
			.css({
				position	: 'absolute',
				left		: 0,
				top		: 0,
				background	: '#000',
				display		: 'block',
				filter		: 'alpha(opacity=' + opacity*100 + ')',
				opacity		: opacity,
				width		: doc.clientWidth,
				height		: Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) + 'px'
			});
	},

	goldenEl : function(jel)
	{
		var el = jel[0];
		var doc = $.browser.opera ? document.body : document.documentElement;
		jel.css({
			position:	'absolute',
			left	:	parseInt((doc.clientWidth-el.offsetWidth)/2) + 'px',
			top	:	Math.max(0, doc.scrollTop + parseInt((doc.clientHeight - el.offsetHeight)*0.382)) + 'px'
		});
	},

	//options = {str: '', type: 'alert', legend: '系统提示', focus: '', submit: '确定', onSubmit: null}
	// options = '测试'
	msg	: function(options)
	{
		var settings = {};
		if (typeof options == 'string') {
			settings.str = options;
			options = {};
		} else {
			settings.str = options.str;
		}
		settings.type = options.type || 'alert';
		settings.legend = options.legend || (settings.type=='alert' ? '系统提示' : '友情提醒');
		settings.submit = options.submit || '确定';
		if (typeof options.opacity == 'undefined') settings.opacity = 0.2;
		else settings.opacity = options.opacity;

		this.showMask(settings.opacity);

		$('#jmsg').length && $('#jmsg').remove();

		var jMsg = $(document.createElement('div'))
		jMsg.appendTo(document.body)
			.attr({'id': 'jmsg', 'class': 'msg ' + settings.type})
			.html('<fieldset><legend>'
				+ settings.legend
				+ '</legend><div id="jmsgbox"><div id="jmsginfo"></div><p><button id="jmsgsubmit">'
				+ settings.submit
				+ '</button></p></div></fieldset>');
		$('#jmsginfo').html(settings.str);
		this.goldenEl(jMsg);

		jMsg.slideDown(300);
		$('#jmsgsubmit').focus().one('click', function(){
			$.showMask(0);
			jMsg.fadeOut(300);

			settings.onSubmit && settings.onSubmit.apply(null);
			settings.focus && settings.focus.focus();
			//$(this).unbind('click', arguments.callee);
		});
	},

	confirm	: function(options)
	{
		var settings = {
			str	: '',
			legend	: '系统提示',
			submit	: '确定',
			cancel	: '取消',
			focus	: null,
			onSubmit: null,
			onCancel: null,
			opacity	: 0.2
		};
		$.extend(settings, options);

		this.showMask(settings.opacity);

		$('#jconfirm').length && $('#jconfirm').remove();

		var jConfirm = $(document.createElement('div'))
		jConfirm.appendTo(document.body)
			.attr({'id': 'jconfirm', 'class': 'confirm'})
			.html('<fieldset><legend>'
				+ settings.legend
				+ '</legend><div id="jconfirmbox"><div id="jconfirminfo"></div><p><button id="jconfirmsubmit">'
				+ settings.submit
				+ '</button> <button id="jconfirmcancel">'
				+ settings.cancel
				+ '</button></p></div></fieldset>');

		$('#jconfirminfo').html(settings.str);
		this.goldenEl(jConfirm);

		jConfirm.slideDown(300);
		$('#jconfirmsubmit').one('click', function(){
			$.showMask(0);
			jConfirm.fadeOut(300);
			settings.onSubmit && settings.onSubmit.call();
			return true;
		});
		$('#jconfirmcancel').one('click', function(){
			$.showMask(0);
			jConfirm.fadeOut(300);
			settings.onCancel && settings.onCancel.call();
			return false;
		});
		settings.focus && $('#jconfirm'+settings.focus).focus();
	},

	quickmsg : function(options, callback)
	{
		if (typeof options == 'string') {
			options = {str: options};
		}

		var settings = {
			str	: '',
			opacity	: 0.2,
			delay	: 900
		};
		$.extend(settings, options);

		this.showMask(settings.opacity);

		$('#jquickmsg').length && $('#jquickmsg').remove();

		var jQuickmsg = $(document.createElement('div'))
		jQuickmsg.appendTo(document.body)
			.attr({'id': 'jquickmsg', 'class': 'quickmsg ' + settings.type})
			.html('<div>' + settings.str + '</div>');
		this.goldenEl(jQuickmsg);

		jQuickmsg.fadeIn(150, function(){
			setTimeout(
				function(){
					jQuickmsg.fadeOut(150, function(){
						$.showMask(0);
						callback && callback.call(this);
					});
				}, settings.delay
			);
		});
	},

	showmsg : function(options)
	{
		if (typeof options == 'string') {
			options = {str: options};
		}

		var settings = {
			str	: '',
			opacity	: 0.2
		};
		$.extend(settings, options);

		this.showMask(settings.opacity);

		$('#jshowmsg').length && $('#jshowmsg').remove();

		var jShowmsg = $(document.createElement('div'))
		jShowmsg.appendTo(document.body)
			.attr({'id': 'jshowmsg', 'class': 'showmsg ' + settings.type})
			.html('<div>' + settings.str + '</div>');
		this.goldenEl(jShowmsg);
	},

	hidemsg : function(callback)
	{
		$('#jshowmsg').hide();
		callback && callback.call(this);
	},


	//取得iframe数据
	//example:
	//	<iframe name='uploadIframe' id='uploadIframe' src='t.php'></iframe>
	//	$.getIframeData( 'uploadIframe', function(iframeData){alert(iframeData);} );
	getIframeData : function(iframe, callback)
	{
		if (document.getElementById(iframe).contentDocument) {
			$('#' + iframe).load(function(){
				callback.call(null, document.getElementById(iframe).contentDocument.body.innerHTML);
			});
			return true;
		} else {
			try {
				rv = window.frames[iframe].document;
			} catch(e) {
				alert('产生异常,请稍候再试');
				return false;
			}
		}
		if(rv.readyState=="complete") {
			var data = rv.body.innerHTML ? rv.body.innerHTML : '{}';
			callback.call(null, data);
		}
		else {
			setTimeout(function(){$.getIframeData(iframe, callback);}, 100);
		}
	},

	listObj : function(o)
	{
		var str = '';
		for (i in o) {
			str += i + '\t\t' + o[i] + '\n';
		}
		alert(str);
	}
});

$.fn.extend({
	trim : function()
	{
		this.val(this.val().trim());
		return this.val();
	},

	len : function()
	{
		return this.val().len();
	},

	/**
	 * $('#xxx').layer({...})
	 */
	layer : function(options)
	{
		var settings = {
			start : null,
			onSubmit: null,
			onCancel: function(){return true;},
			onClick: null,
			opacity	: 0.2
		};
		$.extend(settings, options);

		$.showMask(settings.opacity);

		this.appendTo(document.body).fadeIn('fast');
		$.goldenEl(this);

		var _self = this;
		var _html = this.html();
		settings.start && settings.start.call(this);
		settings.onSubmit && $('form', this).submit(function(){
			$('button[@type=submit]', this).attr('disabled', 'disabled');
			if (settings.onSubmit.call(_self)) {
				$.showMask(0);
				_self.fadeOut('fast', function(){this.innerHTML=_html;});
			} else {
				$('button[@type=submit]', this).attr('disabled', false);
			}
			return false;
		});
		settings.onClick && $('button[@type=submit]', this).click(function(e){
			$(this).attr('disabled', 'disabled');
			if (settings.onClick.call(_self, e)) {
				$.showMask(0);
				_self.fadeOut('fast', function(){this.innerHTML=_html;});
			} else {
				$(this).attr('disabled', false);
			}
			return false;
		});
		settings.onCancel && $('button[@type=reset]', this).click(function(){
			$(this).attr('disabled', 'disabled');
			if (settings.onCancel.call(_self)) {
				$.showMask(0);
				_self.fadeOut('fast', function(){this.innerHTML=_html;});
			} else {
				$(this).attr('disabled', false);
			}
			return false;
		});
	},

	fastSerialize : function()
	{
		var a = [];

		$('input,textarea,select,button', this).each(function() {
			var n = this.name;
			var t = this.type;

			if ( !n || this.disabled || t == 'reset' ||
				(t == 'checkbox' || t == 'radio') && !this.checked ||
				(t == 'submit' || t == 'image' || t == 'button') && this.form.clicked != this ||
				this.tagName.toLowerCase() == 'select' && this.selectedIndex == -1)
				return;

			if (t == 'image' && this.form.clicked_x)
				return a.push(
					{name: n+'_x', value: this.form.clicked_x},
					{name: n+'_y', value: this.form.clicked_y}
				);

			if (t == 'select-multiple') {
				$('option:selected', this).each( function() {
					a.push({name: n, value: this.value});
				});
				return;
		}

		a.push({name: n, value: this.value});
		});

		return a;
	},


	/**
	//Example:
	$('#postcreate').ajaxData({
		start: function() {
			alert('start' + this.innerHTML);
		},
		success: function(){
			...
		},
		complete: function() {
			alert('success' + this.innerHTML);
		}
	});
	/////////////////
	json数据结构为: {error:'error or exception',success:true, focus:'username',redirect:'/'}
	*/
	ajaxData : function(settings)
	{
		var _self = this;
		$.ajax({
			type: settings.type || 'get',
			url: settings.url + '?' + Math.random(),
			dataType: 'json',
			data: settings.data || '',
			beforeSend : function(){
				settings.start && settings.start.call(_self);
			},
			complete : function(){
				settings.complete && settings.complete.call(_self);
			},
			success: function(json){

				if (json.error) {
					if (!json.delay) json.delay = 0.9;
					$.quickmsg({str: json.error, delay: json.delay*1000}, function(){
						if (json.focus) $('[@name=' + json.focus + ']', _self)[0].focus();
						if (json.redirect) {
							if (json.redirect == 'reload') window.location.reload();
							else window.location = json.redirect;
						}
					});
					return;
				}
				if (json.success && json.success != true) {
					if (!json.delay) json.delay = 0.9;
					$.quickmsg({str: json.success, delay: json.delay*1000}, function(){
						settings.success && settings.success.call(_self, json);
						if (json.focus) $('[@name=' + json.focus + ']', _self)[0].focus();
						if (json.redirect) {
							if (json.redirect == 'reload') window.location.reload();
							else window.location = json.redirect;
						}
					});
					return;
				}
				if (json.success && json.success == true) {
					settings.success && settings.success.call(_self, json);
					if (json.focus) $('[@name=' + json.focus + ']', _self)[0].focus();
					if (!json.delay) json.delay = 0;
					if (json.redirect) {
						if (json.redirect == 'reload') setTimeout(function(){window.location.reload();}, json.delay*1000);
						else setTimeout(function(){window.location = json.redirect;}, json.delay*1000);
					}
					return;
				}

				if (!json.delay) json.delay = 0;
				if (json.redirect) {
					if (json.redirect == 'reload') setTimeout(function(){window.location.reload();}, json.delay*1000);
					else setTimeout(function(){window.location = json.redirect;}, json.delay*1000);
				}
			}
		});
		return false;
	},
	/**
	自动绑定事件执行ajaxData方法
	*/
	ajaxBind : function(settings)
	{
		var tag = this[0].tagName.toLowerCase();
		if (tag == 'a') {
			this.bind('click', function(){
				if(settings.before) settings.before.call(this);
				settings.type = 'get';
				settings.url = this.href;
				$(this).ajaxData(settings); return false;
			});
		} else if (tag == 'form') {
			this.bind('submit', function() {
				if(settings.before) if(settings.before.call(this) == false) return false;
				settings.type = this.method;
				settings.url = this.action;
				settings.data = $(this).fastSerialize();
				$(this).ajaxData(settings); return false;
			});
		}
		return this;
	},

	/**
		//@example 1
		options = {
			url : 'uploadprogress.php?id=abc',
			interval : 500,
			start : function(){},
			cycle : function(json){},
			success : function(data){}
		}
		//@example 2
		$('form').upload({
			site : '<a href="http://www.19dog.com/" target="_blank">狗狗佳缘</a>',
			url : 'uploadprogress.php?id=abc',
			validate : function(){
				if ($('input[@name=user]',this)=='') return false;
			},
			success : function(data){
				$.quickmsg("上传成功");
				this[0].reset();
			}
		});
	*/
	upload : function(options)
	{
		var settings = {
			interval : 400,
			dataType : 'json',
			validate : null,
			start : function(){
				$.showMask(0.2);
				$('#uploadprogress').length && $('#uploadprogress').remove();
				$(document.body).append('<div id="uploadprogress">'
						+ '<div>正在上传文件' + (settings.site ? '到' + settings.site : '') + ', 请稍等...</div><div id="uploadprogressbarwrapper"><div id="uploadprogressbar"></div></div>'
						+ '<div id="uploadprogressdesc"></div>'
						+ '</div>');
				$.goldenEl($('#uploadprogress'));
			},
			cycle : function(json){
				var settings = {
					time_start	: 'unknown',
					time_last	: 'unknown',
					speed_average	: 0,
					speed_last	: 0,
					bytes_uploaded	: 0,
					bytes_total	: 'unknown',
					files_uploaded	: 0,
					est_sec		: 'unknown'
				};
				$.extend(settings, json);

				//剩余时间begin
				sec = parseInt(settings.est_sec);
				if (typeof sec != 'number' || isNaN(sec)) {
					timestr = 'unknown';
				} else {
					hour = Math.floor(sec/3600);
					minuter = Math.floor(sec%3600/60);
					second = sec%3600%60;
					if (hour) {
						timestr = hour + '小时 ' + minuter + '分钟 ' + second + '秒';
					} else if (minuter) {
						timestr = minuter + '分钟 ' + second + '秒';
					} else {
						timestr = second + '秒';
					}
				}
				//剩余时间end

				var getFileSize = function(bytes)
				{
					if (bytes >= 1048576) {
						mb = Math.round(100*bytes/1048576)/100;
						sizestr = mb + ' MB';
					} else if (bytes >= 1024) {
						kb = Math.round(100*bytes/1024)/100;
						sizestr = kb + ' KB';
					} else {
						sizestr = bytes + ' byte';
					}
					return sizestr;
				}
				//已上传大小
				uploadedStr = typeof(parseInt(settings.bytes_uploaded))=='number'
							? getFileSize(settings.bytes_uploaded)
							: 'unknown';
				//总共大小
				totalStr = typeof(parseInt(settings.bytes_total))=='number'
							? getFileSize(settings.bytes_total)
							: 'unknown';
				//当前上传速度
				speedStr = typeof(parseInt(settings.speed_last))=='number'
							? getFileSize(settings.speed_last) + '/秒'
							: 'unknown';

				//上传百分比
				var uploadedPercent = parseInt(settings.bytes_uploaded*100/settings.bytes_total) + "%";
				if (typeof uploadedPercent != 'string') {
					uploadedPercentStr = 'unknown';
				} else {
					uploadedPercentStr = '(' + uploadedPercent + ')';
					$('#uploadprogressbar').css({width: uploadedPercent});
				}

				var desc = "剩余时间: " + timestr + "(已上传 " + uploadedStr + ", 共 " + totalStr + ")<br />"
						+ "传输速度: " + speedStr;
				$('#uploadprogressdesc').html(desc);
			}
		}
		$.extend(settings, options);


		intervalName = null;
		_self = this;
		settings.success2 = function(data) {
			$('#uploadprogressbar').css('width', '100%');
			$.showMask(0);
			$('#uploadprogress').fadeOut();
			clearInterval(intervalName);
			if (settings.dataType == 'json') {
				if (/^\{.+\}$/.test(data)) {
					eval("data = " + data);
				} else {
					alert("上传时产生异常, 请稍候再试");
					return false;
				}
			}
			settings.success.call(_self, data);
		}

		//产生UPLOAD_IDENTIFIER
		var uid = $.uid();
		if ($('#UPLOAD_IDENTIFIER').length) {
			uid = $('#UPLOAD_IDENTIFIER').val();
		} else {
			this.prepend('<input type="hidden" name="UPLOAD_IDENTIFIER" id="UPLOAD_IDENTIFIER" value="' + uid + '" />');
		}

		this.bind('submit', function(){
			//产生隐藏的iframe
			if ($('#uploadIframe').length) $('#uploadIframe').remove();
			$(document.body).append('<iframe id="uploadIframe" name="uploadIframe" class="none"></iframe>');
			this.target = 'uploadIframe';

			if (settings.validate && settings.validate.call(this) === false) {
				return false;
			}
			settings.start && settings.start.call(this);
			intervalName = setInterval(function(){
				$.ajax({
					type : 'get',
					url : settings.url,
					data : 'id=' + uid + '&s=' + Math.random(),
					dataType : 'json',
					success : settings.cycle
				});
			}, settings.interval);
			$.getIframeData('uploadIframe', settings.success2);
		});
	},

	radioVal : function()
	{
		var retval = null;
		this.each(function(){
			if (this.checked) {
				retval = this.value;
				return;
			}
		});
		return retval;
	}
});

//@version 0.35
$.fn.deserialize = function(d,config) {
	var data= d;
	me  = this;

	if (d === undefined) {
		return me;
	}

	config = $.extend({ isPHPnaming	: false,
						overwrite	: true},config);

	// check if data is an array, and convert to hash, converting multiple entries of
	// same name to an array
	if (d.constructor == Array)	{
		data={};
		for(var i=0; i<d.length; i++) {
			if (typeof data[d[i].name] != 'undefined') {
				if (data[d[i].name].constructor!= Array) {
					data[d[i].name]=[data[d[i].name],d[i].value];
				} else {
					data[d[i].name].push(d[i].value);
				}
			} else {
				data[d[i].name]=d[i].value;
			}
		}
	}

	// now data is a hash. insert each parameter into the form
	$('input,select,textarea',me)
	.each(function() {
			  var p=this.name;
			  var v = [];

			  // handle wierd PHP names if required
			  if (config.isPHPnaming) {
				  p=p.replace(/\[\]$/,'');
			  }
			  if(p && data[p] != undefined) {
				  v = data[p].constructor == Array ? data[p] : [data[p]];
			  }
			  // Additional parameter overwrite
			  if (config.overwrite === true || data[p]) {
				  switch(this.type || this.tagName.toLowerCase()) {
				  case "radio":
				  case "checkbox":
					  this.checked=false;
					  for(var i=0;i<v.length;i++) {
						  this.checked|=(this.value!='' && v[i]==this.value);
					  }
					  break;
				  case "select-multiple" || "select":
					  for( i=0;i<this.options.length;i++) {
						  this.options[i].selected=false;
						  for(var j=0;j<v.length;j++) {
							  this.options[i].selected|=(this.options[i].value!='' && this.options[i].value==v[j]);
						  }
					  }
					  break;
				  case "button":
				  case "submit":
					  this.value=v.length>0?v.join(','):this.value;
						  break;
				  default:
					  this.value=v.join(',');
				  }
			  }
		  });
	return me;
};

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toGMTString)) {
            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.toGMTString(); // use expires attribute, max-age is not supported by IE
        }
        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].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && 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 (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
 * Example: str.trim()
 * Function: 删除字符串前后所有全角与半角空格
 */
String.prototype.trim = function()
{
	return this.replace(/(^[　\s]*)|([　\s]*$)/g, "");
}

/**
 * Example: str.ltrim()
 * Function: 删除字符串前面所有全角与半角空格
 */
String.prototype.ltrim = function()
{
	return this.replace(/^[　\s]*/g, "");
}

/**
 * Example: str.rtrim()
 * Function: 删除字符串后面部分所有全角与半角空格
 */
String.prototype.rtrim = function()
{
	return this.replace(/[　\s]*$/g, "");
}

/**
 * Example: str.trueLength()
 * Function: 返回字符串的真实长度(一个全角字符的长度为2)
 */
String.prototype.len = function()
{
	return this.replace(/[^\x00-\xff]/g, "**").length;
}

/**
 * usage: '我是中国人'.left(5)
 * Example: 一个汉字当成两个字符截取
 */
String.prototype.left = function(num) {
	var str = this.replace(/[^\x00-\xff]/g, "%^");
	num = str.substr(0, num).replace(/\%\^/g, "^").replace(/\%$/, "").length;
	return this.substr(0, num);
}


//on ready
$(function(){
	if ($.cookie('hideToolBar')) {
		$('#topNav').hide();
	}
	$('#topNavBtn').mouseover(function(){
		if ($('#topNav').is(':hidden')) $('#topNav').fadeIn();
		$.cookie('hideToolBar', 0, {expires: -1, path: '/', domain: DOMAIN});
	});
	$('#topNav .close').focus(function(){
		this.blur();
	}).click(function(){
		$.cookie('hideToolBar', 1, {expires: 3, path: '/', domain: DOMAIN});
		$('#topNav').fadeOut();
		return false;
	});
});