/**
 * [OEmarry] (C)2010-2099 OEMARRY.COM Inc.
 * This is NOT a freeware, use is subject to license terms
 * Email: service@phpcoo.com, phpcoo@qq.com
 * $Last update 2015-05-10 by OEdev $
*/

/**
 * AJAX上传图片 全站通用
 * @param:: string $file input file name
 * @param:: string $url post url
 * @param:: string $callback callback js name
 * @return::
*/
function oemarryUploadImg($file, $url, $callback) {
	if (typeof($callback) == "undefined") {$callback = "";}
	if (_oemarryCheckImgType($file) == true) {
		$obj_loading = $("#"+$file+"_loading");
		if ($obj_loading.length > 0) {
			$obj_loading.show();
		}
		$.ajaxFileUpload({
			"url": $url,
			"secureuri": false,
			"fileElementId": $file,
			"dataType": "json",
			"data": {
				uploadpart: $file
			},
			async: this.async,
			beforeSend: function ($xmlobj) {},
			complete: function ($data) {},
			success: function ($data) {
				$json = eval($data);
				$response = $json.response;
				$result = $json.result;
				$imgthumb = $json.thumbimg;
				$imgurl = $json.uploadimg;

				if ($response == "1") {
					if ($("#"+$file+"_thumb").length > 0) {
						$("#"+$file+"_thumb").val($imgthumb);
					}
					if ($("#"+$file+"_url").length > 0) {
						$("#"+$file+"_url").val($imgurl);
					}
					if ($("#"+$file+"_preview").length > 0) {
						$img = _ROOT_PATH+$imgurl+"?r="+get_rndnum(8);
						$("#"+$file+"_preview").attr("src", $img);
						$("#"+$file+"_preview").show();
					}
					if ($obj_loading.length > 0) {
						$obj_loading.hide();
					}
				}
				else {
					if ($obj_loading.length > 0) {
						$obj_loading.hide();
					}
					if ($result.length > 0 ) {
						ToastShow($result);
					}
					else {
						ToastShow("上传失败，请检查图片。");
					}
				}

				//callback js
				if ($callback.length > 0) {
					$fun = eval($callback);
					if (typeof($fun) == "function") {
						$fun.call(this);
					}
				}

			},
			error: function ($data, e, b) {
				if ($obj_loading.length > 0) {
					$obj_loading.hide();
				}
				ToastShow("上传失败，请检查网络...");
			}
		});

	}
}


//判断图片格式
function _oemarryCheckImgType(filepart) {
	$res = true;
	$oe_file_obj = $("#"+filepart);
	$oe_file_val = $oe_file_obj.val();
	$oe_file_size = 0;
	//$oe_sys_max_size = (_UPLOAD_MAXSIZE*1024*1024);
	if ($oe_file_val.length == 0) {
		ToastShow("请选择要上传的图片");
		$res = false;
	}
	if(!/.(gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG)$/.test($oe_file_val)){ 
		ToastShow("图片格式不正确");
		$res = false;
	}
	/*
	if ($res == true) {
		if (typeof($oe_file_obj[0]) != "undefined") {
			if (typeof($oe_file_obj[0].files[0]) != "undefined") {
				if (typeof($oe_file_obj[0].files[0].size) != "undefined") { //IE10以上才支持
					$oe_file_size = $oe_file_obj[0].files[0].size;
					if (typeof($oe_file_size) != "undefined") {
						if ($oe_file_size > $oe_file_size) {
							ToastShow("图片大小不能超过"+_UPLOAD_MAXSIZE+"M");
							$res = false;
						}
					}
				}
			}
		}
	}
	*/
	return $res;
}