/**
 *	jquery 的扩展类似于 .NET里的Systerm.IO.Path.Combine
 *	jhwang 2013/3/6
 * 	ref:https://github.com/joyent/node/blob/061f2075cf81017cdb40de80533ba18746743c94/lib/path.js
 */

define(function(require, exports, module) {

    // replace url like 'http:/xx.s/a.html' to 'http://xx.s/a.html'
    var httpReg = /^(http:\/)([^\/])/i;

	// Split a filename into [root, dir, basename, ext], unix version
	// 'root' is just a slash, or nothing.
	var splitPathRe =
		/^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/;
	var splitPath = function(filename) {
		var result = splitPathRe.exec(filename);
		return [result[1] || '', result[2] || '', result[3] || '', result[4] || ''];
	};

	// resolves . and .. elements in a path array with directory names there
	// must be no slashes, empty elements, or device names (c:\) in the array
	// (so also no leading and trailing slashes - it does not distinguish
	// relative and absolute paths)

	function normalizeArray(parts, allowAboveRoot) {
		// if the path tries to go above the root, `up` ends up > 0
		var up = 0;
		for (var i = parts.length - 1; i >= 0; i--) {
			var last = parts[i];
			if (last === '.') {
				parts.splice(i, 1);
			} else if (last === '..') {
				parts.splice(i, 1);
				up++;
			} else if (up) {
				parts.splice(i, 1);
				up--;
			}
		}

		// if the path is allowed to go above the root, restore leading ..s
		if (allowAboveRoot) {
			for (; up--; up) {
				parts.unshift('..');
			}
		}

		return parts;
	}

	// path.resolve([from ...], to)
	// posix version
	exports.resolve = function() {
		var resolvedPath = '',
			resolvedAbsolute = false;

		for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
			var path = (i >= 0) ? arguments[i] : process.cwd();

			// Skip empty and invalid entries
			if (typeof path !== 'string' || !path) {
				continue;
			}

			resolvedPath = path + '/' + resolvedPath;
			resolvedAbsolute = path.charAt(0) === '/';
		}

		// At this point the path should be resolved to a full absolute path, but
		// handle relative paths to be safe (might happen when process.cwd() fails)

		// Normalize the path
		resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) {
			return !!p;
		}), !resolvedAbsolute).join('/');

		return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
	};

	// path.normalize(path)
	// posix version
	exports.normalize = function(path) {
		var isAbsolute = path.charAt(0) === '/',
			trailingSlash = path.substr(-1) === '/';

		// Normalize the path
		path = normalizeArray(path.split('/').filter(function(p) {
			return !!p;
		}), !isAbsolute).join('/');

		if (!path && !isAbsolute) {
			path = '.';
		}
		if (path && trailingSlash) {
			path += '/';
		}

        path = (isAbsolute ? '/' : '') + path;

        // 类似 http://xxx.xxx.xx/ss.html的路径会被normalize成 http:/xxx.xxx.xx/ss.html,
        // 而以http:/ 开头的路径会被某些浏览器(如chrome)当成相对路径，所以此处做个正则替换
        // yuwang@iflytek.com 2013-07-25
        path = path.replace(httpReg, '$1/$2');

		return  path;
	};


	// posix version
	exports.join = function() {
		var paths = Array.prototype.slice.call(arguments, 0);
		return exports.normalize(paths.filter(function(p, index) {
			return p && typeof p === 'string';
		}).join('/'));
	};


	// path.relative(from, to)
	// posix version
	exports.relative = function(from, to) {
		from = exports.resolve(from).substr(1);
		to = exports.resolve(to).substr(1);

		function trim(arr) {
			var start = 0;
			for (; start < arr.length; start++) {
				if (arr[start] !== '') break;
			}

			var end = arr.length - 1;
			for (; end >= 0; end--) {
				if (arr[end] !== '') break;
			}

			if (start > end) return [];
			return arr.slice(start, end - start + 1);
		}

		var fromParts = trim(from.split('/'));
		var toParts = trim(to.split('/'));

		var length = Math.min(fromParts.length, toParts.length);
		var samePartsLength = length;
		for (var i = 0; i < length; i++) {
			if (fromParts[i] !== toParts[i]) {
				samePartsLength = i;
				break;
			}
		}

		var outputParts = [];
		for (var i = samePartsLength; i < fromParts.length; i++) {
			outputParts.push('..');
		}

		outputParts = outputParts.concat(toParts.slice(samePartsLength));

		return outputParts.join('/');
	};

	exports.dirname = function(path) {
		var result = splitPath(path),
			root = result[0],
			dir = result[1];

		if (!root && !dir) {
			// No dirname whatsoever
			return '.';
		}

		if (dir) {
			// It has a dirname, strip trailing slash
			dir = dir.substr(0, dir.length - 1);
		}

		return root + dir;
	};


	exports.basename = function(path, ext) {
		var f = splitPath(path)[2];
		// TODO: make this comparison case-insensitive on windows?
		if (ext && f.substr(-1 * ext.length) === ext) {
			f = f.substr(0, f.length - ext.length);
		}
		return f;
	};

    /**
     * 获取扩展名
     * @param path
     * @returns {*}
     */
	exports.extname = function(path) {
		return splitPath(path)[3];
	};

    /**
     * 获取文件名
     * @param path
     * @returns {*}
     */
	exports.filename=function(path){
		return splitPath(path)[2];
	}

    /**
     * 将C:\\test.txt 这样的路径转为 C:/test.txt
     * @param path
     * @returns {*}
     */
	exports.toPosix=function(path){
		if (/^[a-zA-Z]\:\\/.test(path)) {
			path=path.replace(/\\/g,'/');
		}
		return path;
	}

    exports.toWindows=function(path){
        return path.replace(/\//g,'\\\\');
    }

    /**
     * 将 file:/c:/test.txt 前的 file:/ 删除掉
     * @param path
     * @returns {*}
     */
	exports.trimPosix = function(path) {
		return path.replace(/\bfile:(\/+)/g, "");;
	}


	exports.sep = '/';
	exports.delimiter = ':';
});