var isIE	= (navigator.userAgent.toLowerCase().indexOf("msie") == -1 ? false : true);
var isIE6	= (navigator.userAgent.toLowerCase().indexOf("msie 6") == -1 ? false : true);
var isIE7	= (navigator.userAgent.toLowerCase().indexOf("msie 7") == -1 ? false : true);
var isChrome= (navigator.userAgent.toLowerCase().indexOf("chrome") == -1 ? false : true);

function addCommas(nStr){
	nStr += ''; x = nStr.split(',');	x1 = x[0]; x2 = ""; x2 = x.length > 1 ? ',' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + '.' + '$2'); } return x1 + x2;
}

function checkForm(form_name, arrControl){
	frm	= eval("document." + form_name + ";");
	for(i=0; i<arrControl.length; i++){
		arrTemp	= arrControl[i].split("{#}");
		type	= arrTemp[0];
		defVal	= arrTemp[1];
		control	= arrTemp[2];
		title	= arrTemp[3];
		ob		= eval("frm." + control + ";");
		ob1 	= eval("frm." + control + "_retype;")
		errMsg	= "";
		switch(type){
			case "0": if($.trim(ob.value) == "" || $.trim(ob.value) == defVal){ errMsg = "Bạn chưa nhập " + title + "."; } break;
			case "1": if(parseFloat(ob.value) <= parseFloat(defVal)){ errMsg = title + " phải lớn hơn " + defVal + "."; } break;
			case "2": if(ob.value == defVal){ errMsg = "Bạn chưa chọn " + title + "."; } break;
			case "3": if(!isEmail(ob.value)){ errMsg = title + " không hợp lệ."; } break;
			case "4": if($.trim(ob.value).length < defVal){ errMsg = title + " phải có ít nhất " + defVal + " ký tự."; } break;
			case "5": if(!isUrl(ob.value)){ errMsg = title + " không hợp lệ."; } break;
			case "6": if(parseFloat(ob.value) < parseFloat(defVal)){ errMsg = title + " phải lớn hơn hoặc bằng " + defVal + "."; } break;
			case "7": if(!isMobile(ob.value)){ errMsg = title + " không hợp lệ."; } break;
			case "8": if($.trim(ob.value) != $.trim(ob1.value)){ errMsg = "Nhập lại " + title + " không đúng."; } break;
			case "9": if(!isNumber(ob.value)){ errMsg = title + " không hợp lệ."; } break;
			case "10": if(!isImage(ob.value)){ errMsg = title + " chỉ chấp nhận jpg, jpeg, gif, png."; } break;
			case "11": if(!isBanner(ob.value)){ errMsg = title + " chỉ chấp nhận jpg, jpeg, gif, png, swf."; } break;
		}
		
		if(errMsg != ""){
			alert(errMsg);
			if($(".header_bar").length){
				// Check xem có moveScrollTop hay không
				defTop = 40;
				if(typeof($("form[name='" + form_name + "']").attr("fixScrollTop")) != "undefined"){
					defTop	= $("form[name='" + form_name + "']").attr("fixScrollTop");
				}
				move		= 0;
				obTemp	= $("form[name='" + form_name + "'] [name='" + control + "']");
				if($(window).scrollTop() + defTop < obTemp.offset().top){
					if((obTemp.offset().top - ($(window).scrollTop() + $(window).height())) > 0) move = 1;
				}
				else move = 1;
				// Move or focus
				if(move == 0) ob.focus();
				else moveScrollTop(obTemp, { top: defTop, finish: function(){ obTemp.focus(); } });
			}
			else{
				try{ob.focus();}
				catch(e){}
			}
			return false;
		}
	}
	
	// Nếu có thêm javascript thì execute
	args	= checkForm.arguments;
	if(typeof(args[2]) != "undefined"){
		opts	= { stop: false, callback: null }
		switch(typeof(args[2])){
			case "string"	: eval(args[2]); break;
			case "function": args[2](); break;
			case "object"	: $.extend(opts, args[2]); break;
		}
		if(typeof(opts.callback) == "function") opts.callback();
		if(opts.stop == true) return false;
	}
	
	//if(typeof(formErrorOnSubmit) != "undefined" && formErrorOnSubmit[form_name] == 1) return false;
	// Nếu là form final thì khi không có lỗi phải disabled mấy nút submit đi để user không click nhiều, tránh duplicate
	if(form_name == "final"){
		$("form[name='" + form_name + "'] :submit").attr("disabled", "disabled").val("Vui lòng đợi...").blur();
	}
	// Submit form
	frm.submit();
}

function checkAll(ob, type){
	ob2	= ob.find("input[name='c\[\]']");
	if(type == 0){
		ob2.attr("checked", false);
		ob.removeClass("checked");
	}
	else if(type == 1){
		ob2.attr("checked", true);
		ob.addClass("checked");
	}
	else{
		ob2.each(function(){
			$(this).click();
		});
	}
}

function fixAnchorLink(){
	hrefTemp	= window.location.href;
	if(hrefTemp.indexOf("#") != -1){
		arrTemp	= hrefTemp.split("#");
		obTemp	= $("#" + arrTemp[arrTemp.length-1]);
		if(obTemp.length) $(window).scrollTop(obTemp.offset().top - 40);
	}
}

function fixImageSize(width, height, maxWidth, maxHeight){
	// Check if the current width is larger than the max
	ratio		= maxWidth / width;   // Get ratio for scaling image
	w			= maxWidth;
	h			= height * ratio;    // Reset height to match scaled image
	// Check if current height is larger than max
	if(h > maxHeight){
		ratio	= maxHeight / height; // Get ratio for scaling image
		w		= width * ratio;    // Reset width to match scaled image
		h		= maxHeight;
	}
	return Array(parseInt(w), parseInt(h));
}

function isEmail(s){
	var re	= /^(\w|[^_]\.[^_]|[\-])+(([^_])(\@){1}([^_]))(([a-z]|[\d]|[_]|[\-])+|([^_]\.[^_]) *)+\.[a-z]{2,3}$/i;
	return re.test(s);
}

function isUrl(s){
	var re	= /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	return re.test(s);
}

function isMobile(s){
	var re	= /^(\+([0-9])+\s)*(([0-9])+([-.])*([0-9])+)+$/;
	return re.test(s);
}

function isNumber(s){
	var re	= /^\d+$/;
	return re.test(s);
}

function isImage(s){
	var re	= /([^\s]+(\.(jpg|png|gif|jpeg))$)/i;
	if (s != "") {
		return re.test(s);
	}
	else {
		return true;
	}
}

function isBanner(s){
	var re	= /([^\s]+(\.(jpg|png|gif|jpeg|swf))$)/i;
	if (s != "") {
		return re.test(s);
	}
	else {
		return true;
	}
}


function moveScrollTop(ob){
	args	= moveScrollTop.arguments;
	opts	= {
		top	: 40,
		time	: 1000,
		finish: false
	};
	if(typeof(args[1] != "undefined")) $.extend(opts, args[1]);
	if(!isChrome) $("html").animate({ scrollTop: (ob.offset().top - opts.top) }, opts.time, "easeOutExpo", opts.finish);
	else $("body").animate({ scrollTop: (ob.offset().top - opts.top) }, opts.time, "easeOutExpo", opts.finish);
}

// Nếu ảnh bị lỗi thì thay bằng no_photo.gif
function pictureError(sel){
	$(sel + " .picture_xx_small img").error(function(){ $(this).attr("src", fs_imagepath + "no_photo_xx_small.gif"); });
	$(sel + " .picture_x_small img").error(function(){ $(this).attr("src", fs_imagepath + "no_photo_x_small.gif"); });
	$(sel + " .picture_small img").error(function(){ $(this).attr("src", fs_imagepath + "no_photo_small.gif"); });
	$(sel + " .picture_medium img").error(function(){ $(this).attr("src", fs_imagepath + "no_photo_medium.gif"); });
	$(sel + " .picture_larger img").error(function(){ $(this).attr("src", fs_imagepath + "no_photo_larger.gif"); });
	
	$(sel + " .avatar_xx_small img").error(function(){ $(this).attr("src", fs_imagepath + "no_avatar_xx_small.gif"); });
	$(sel + " .avatar_x_small img").error(function(){ $(this).attr("src", fs_imagepath + "no_avatar_x_small.gif"); });
}

// Resize image with maxWidth + maxHeight
function resizeImage(){
	$("img[maxWidth],img[maxHeight]").each(function(){
		var maxWidth	= $(this).attr("maxWidth"); // Max width for the image
		var maxHeight	= $(this).attr("maxHeight"); // Max height for the image
		var width		= $(this).width();    // Current image width
		var height		= $(this).height();  // Current image height
		// Fix maxWidth
		if(isNaN(maxWidth) || maxWidth <= 0) maxWidth	= width;
		// Check if the current width is larger than the max
		ratio		= maxWidth / width;   // Get ratio for scaling image
		width		= maxWidth;
		height	= height * ratio;    // Reset height to match scaled image
		// Check if current height is larger than max
		if(height > maxHeight){
			ratio		= maxHeight / height; // Get ratio for scaling image
			height	= maxHeight;
			width		= width * ratio;    // Reset width to match scaled image
		}
		// Chỉ resize những ảnh có độ rộng hoặc độ cao vượt quá giới hạn
		if($(this).attr("resizeType") == "overflow"){
			if($(this).width() < width && $(this).height() < height) return;
		}
		// Resize image
		$(this).attr({ width: width, height: height });
	});
}

function resizeImageSrc(src, width, height, maxWidth, maxHeight){
	opts	= {
		resizeLess	: true,
		html			: ""
	}
	args	= resizeImageSrc.arguments;
	if(typeof(args[5]) != "undefined") $.extend(opts, args[5]);
	
	if(opts.resizeLess == true || (width > maxWidth || height > maxHeight)){
		// Check if the current width is larger than the max
		ratio		= maxWidth / width;   // Get ratio for scaling image
		width		= maxWidth;
		height	= height * ratio;    // Reset height to match scaled image
		// Check if current height is larger than max
		if(height > maxHeight){
			ratio		= maxHeight / height; // Get ratio for scaling image
			height	= maxHeight;
			width		= width * ratio;    // Reset width to match scaled image
		}
	}
	
	return '<img src="' + src + '" width="' + parseInt(width) + '" height="' + parseInt(height) + '" ' + opts.html + '/>';
}

function moveScrollTop(ob){
	args	= moveScrollTop.arguments;
	opts	= {
		top	: 40,
		time	: 1000,
		finish: false
	};
	if(typeof(args[1] != "undefined")) $.extend(opts, args[1]);
	if(!isChrome) $("html").animate({ scrollTop: (ob.offset().top - opts.top) }, opts.time, "easeOutExpo", opts.finish);
	else $("body").animate({ scrollTop: (ob.offset().top - opts.top) }, opts.time, "easeOutExpo", opts.finish);
}

function makeRequest(url, obj_response, method, parameters, linkImagesLoad) {
	var http_request	= false;
	var show_id			= document.getElementById(obj_response);
	if (!show_id) {
		//alert('Cannot find object response data !');	
		return false;
	}
	if(url == ""){
		return false;
	}
	show_id.innerHTML	= linkImagesLoad;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request	= new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			//set type accordingly to anticipated content type
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject('Msxml2.XMLHTTP');
		} catch (e) {
			try {
				http_request = new ActiveXObject('Microsoft.XMLHTTP');
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	
	http_request.onreadystatechange=	function(){
													if (http_request.readyState == 4) {
														if (http_request.status == 200) {
															//alert(http_request.responseText);
															show_id.innerHTML = http_request.responseText;     
														} else {
															//alert('There was a problem with the request.');
															return false;
														}
													}
												}
	if(method == 'GET'){
		http_request.open('GET', url, true);
		http_request.send('');
	}
	else if(method == 'POST'){
		http_request.open('POST', url, true);
		http_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		http_request.setRequestHeader('Content-length', parameters.length);
		http_request.setRequestHeader('Connection', 'close');
		http_request.send(parameters);
	}
}

function ShowGoldPrice(){
	var sHTML = '';
	sHTML = sHTML.concat('<table width="100%" border="0px" cellpadding="2px" cellspacing="1px" class="tbl-weather">');
	sHTML = sHTML.concat('	<tr>');
	sHTML = sHTML.concat('		<td class="td-weather-title" width="30%">Loại</td>');
	sHTML = sHTML.concat('		<td class="td-weather-data txtr" width="35%">Mua</td>');
	sHTML = sHTML.concat('		<td class="td-weather-data txtr" width="35%">Bán</td>');
	sHTML = sHTML.concat('	</tr>');
	sHTML = sHTML.concat('	<tr>');
	sHTML = sHTML.concat('		<td width="30%">SBJ</td>');
	sHTML = sHTML.concat('		<td width="35%">').concat(vGoldSbjBuy).concat('</td>');
	sHTML = sHTML.concat('		<td width="35%">').concat(vGoldSbjSell).concat('</td>');
	sHTML = sHTML.concat('	</tr>');
	sHTML = sHTML.concat('	<tr>');
	sHTML = sHTML.concat('		<td width="30%">SJC</td>');
	sHTML = sHTML.concat('		<td width="35%">').concat(vGoldSjcBuy).concat('</td>');
	sHTML = sHTML.concat('		<td width="35%">').concat(vGoldSjcSell).concat('</td>');
	sHTML = sHTML.concat('	</tr>');
	sHTML = sHTML.concat('	<tr>');
	sHTML = sHTML.concat('		<td colspan="3" align="center">(Nguồn:<a href="http://www.sacombank-sbj.com" target="_blank"><img style="border: 0px none ; vertical-align: middle; width: 75px; height: 9px;" src="http://vnexpress.net/Images/logoSb.gif" alt="Sacombank"></a>)</td>');
	sHTML = sHTML.concat('	</tr>');
	sHTML = sHTML.concat('</table>');
	gmobj('eGold').innerHTML = sHTML;
}	

function ShowForexRate(){
	var sHTML = '';
	sHTML = sHTML.concat('<table width="100%" border="0" cellpadding="2" cellspacing="2" id="tblforex">');
	for(var i=0;i<vForexs.length;i++){
		sHTML = sHTML.concat('	<tr>');
		sHTML = sHTML.concat('		<td width="30%">').concat(vForexs[i]).concat('</td>');
		sHTML = sHTML.concat('		<td width="70%" align="right">').concat(vCosts[i]).concat('</td>');
		sHTML = sHTML.concat('	</tr>');				
	}
	sHTML = sHTML.concat('	<tr>');
	sHTML = sHTML.concat('		<td colspan="2" align="center">(Nguồn: <a href="http://www.eximbank.com.vn/"><img src="http://vnexpress.net/Images/logo-EXIM.gif"></a>)</td>');
	sHTML = sHTML.concat('	</tr>');
	sHTML = sHTML.concat('</table>');
	gmobj('eForex').innerHTML = sHTML;
}

function fiximage() {
	$("img.npro").error(function(){$(this).attr("src", "/images/skins/no_photo_small.gif").css('width', '120px')})
	$("img.pics-product").error(function(){$(this).attr("src", "/images/skins/no_photo_small.gif").css('width', '158px')})
}

function loadcaptcha() {
	document.getElementById('captcha').src = '/lib/captcha.asp?'+ Date()
}
