// JavaScript Document

// Check xem trình duyệt là IE6 hay IE7
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);

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 ajaxLink(){
	$("a[rel^='ajax']").click(function(){
		domEle= $(this);
		temp	= domEle.attr("rel").match(/\[(.*?)\]/);
		if(temp !== null){
			sel	= temp[1];
			$.get(domEle.attr("href"), function(data){
				$(sel).html(data);
				if(typeof(domEle.attr("addJS")) != "undefined") eval(domEle.attr("addJS"));
			});
		}
		return false;
	});
}

function baokimPayment(){
	return '<a title="Thanh toán với Baokim.vn" class="colorbox_iframe_baokim" href="/ajax_v2/load_news.php?iData=7964" target="_blank" rel="nofollow"><img align="absmiddle" src="/images/baokim_icon.gif" /></a>';
}

function changePriceText(id, value){
	formatCurrency(id, value);
	if(parseInt(value) > 0) $("#" + id).css("display", "block");
	else $("#" + id).css("display", "none");
}

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);
		switch(type){
			case "0": if($.trim(ob.value) == "" || $.trim(ob.value) == defVal){ alert("Bạn chưa nhập " + title + "."); ob.focus(); return false; } break;
			case "1": if(parseFloat(ob.value) <= parseFloat(defVal)){ alert(title + " phải lớn hơn " + defVal + "."); ob.focus(); return false; } break;
			case "2": if(ob.value == defVal){ alert("Bạn chưa chọn " + title + "."); ob.focus(); return false; } break;
			case "3": if(!isEmail(ob.value)){ alert(title + " không hợp lệ."); ob.focus(); return false; } break;
			case "4": if($.trim(ob.value).length < defVal){ alert(title + " phải có ít nhất " + defVal + " ký tự."); ob.focus(); return false; } break;
		}
	}
	frm.submit();
}

function checkChangeBg(ob){
	ob.each(function(index, domEle){
		$(domEle).find("input[name='c\[\]']").click(function(){
			$(domEle).toggleClass("checked");
		});
	});
}

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 countDown(object){
	ob	= $("#" + object);
	if(ob.length == 0) return;
	ob.html(function(index, html){
		return (parseInt(html) - 1);
	});
	if(ob.html() > 0) setTimeout("countDown('" + object + "')", 1000);
	else window.location.href	= redirect;
}

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 formatCurrency(div_id, str_number){
	document.getElementById(div_id).innerHTML = addCommas(str_number);
}

function generateSort(type, value, def, url){
	arrType	= type.split("|");
	arrValue	= value.split("|");
	for(i=0; i<arrType.length; i++){
		src	= fs_imagepath + "sort" + arrType[i] + (arrValue[i] == def ? "_selected" : "") + ".gif";
		document.write('<a href="' + url + '&sort=' + arrValue[i] + '"><img hspace="2" src="' + src + '" style="margin-top:3px" /></a>');
	}
}

// Tao star binh chọn
function generateVote(numberstar){
	
	numberstar	= parseFloat(numberstar)
	intStar		= parseInt(numberstar);
	if(isNaN(numberstar)) return;
	
	// Kiểm tra sai số
	if(intStar < 0){ intStar = 0; numberstar = 0; }
	if(intStar > 10){ intStar = 10; numberstar = 10; }
	
	strReturn	= "";
	
	// Ghi star xịn ra
	for(i=1; i<=intStar; i++) strReturn = strReturn + '<img src="' + fs_imagepath + 'star_1.gif" />';
	
	// Neu intStar!=numberstar thi them 0,5 vao va cong intStar them 1
	if(intStar != numberstar){
		temp	= numberstar.toString().split(".");
		num	= parseInt(temp[1].substr(0, 1));
		if(num <= 3)		img = "star_0.3.gif";
		else if(num <= 7) img = "star_0.5.gif";
		else					img = "star_0.7.gif";
		strReturn	= strReturn + '<img src="' + fs_imagepath + img + '" />';
		intStar++;
	}
	
	// Ghi ra so sao = 0 con lai 
	for(i=intStar+1; i<=10; i++) strReturn = strReturn + '<img src="' + fs_imagepath + 'star_0.gif" />';
	
	return strReturn;
	
}

// Di chuột vào link show content ở header bar
function headerBarDropdown(){
	if(isIE6 || isIE7) $(".header_bar .hidden").css("margin-top", "-1px");
	$(".header_bar .bar_link, .header_bar .bar_text a").mouseenter(function(){
		$(".header_bar .hidden").hide();
		ob	= $(this).nextAll(".hidden");
		ob.show();
		// Set vị trí bên phải để tránh bị overflow
		if((ob.position().left + ob.width()) > $("body").width()){
			ob.css("right", "0px");
		}
	});
	$(".header_bar .close a").click(function(){
		$(".header_bar .hidden").hide();
	});
	$(".header,.header_search,.header_season,.header_banner,.header_navigate_div,div[class^='container_content_'],#container_content,#container_footer").mouseenter(function(){
		$(".header_bar .hidden").hide();
	});
}

function initColorBox(){
	$(".colorbox").colorbox({ maxWidth:"80%", maxHeight:"80%", current:"ảnh {current} / {total}" });
	$(".colorbox_iframe").colorbox({ iframe:true, width:"650px", height:"500px", overlayClose:false });
	$(".colorbox_iframe_baokim").colorbox({ iframe:true, width:"735px", height:"500px", overlayClose:false });
	$(".colorbox_iframe_upload").colorbox({ iframe:true, width:"800px", height:"545px" });
}

function isEmail(email) {
	var re = /^(\w|[^_]\.[^_]|[\-])+(([^_])(\@){1}([^_]))(([a-z]|[\d]|[_]|[\-])+|([^_]\.[^_]) *)+\.[a-z]{2,3}$/i;
	return re.test(email);
}

// 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");
	});
}

// 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
		// 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){
	// 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="' + width + '" height="' + height + '" />';
}

/*** Auto complete ***/
function setAutoComplete(){
	$(".search_keyword,.quick_search_keyword").autocomplete("/ajax/autocomplete.php", {
		width: 550,
		delay: 150,
		scroll: false,
		max: 11,
		selectFirst: false,
		formatResult: formatResult,
		formatItem: formatItem
	});
}

function removeAutoComplete(){
	$(":input").unautocomplete();
}

function formatItem(row){
	return row[0];
}

function formatResult(row){
	return row[1];
}
/*-- End Auto complete --*/

/*** Quick search ***/
var defaultLang	= "vn";
function changeSearchLang(){
	ob	= $(".image_language");
	if(defaultLang == "vn"){
		defaultLang	= "en";
		ob.attr("src", fs_imagepath + "en.gif");
		AVIMObj.setMethod(-1);
	}
	else{
		defaultLang	= "vn";
		ob.attr("src", fs_imagepath + "vn.gif");
		AVIMObj.setMethod(0);
	}
	$(".search_keyword").focus();
}

function changeSearchType(number){
	$("#search_shop").attr("disabled", true);
	frm	= $("form[name='header_search']");
	switch(parseInt(number)){
		case 0: frm.attr("action", "/home/quicksearch.php"); setAutoComplete(); break;
		case 1: frm.attr("action", "/raovat/quicksearch.php"); removeAutoComplete(); break;
		case 2: frm.attr("action", "/hoidap/quicksearch.php"); removeAutoComplete(); break;
		case 3: frm.attr("action", "/review/quicksearch.php"); removeAutoComplete(); break;
		case 4: frm.attr("action", "/home/shop.php"); $("#search_shop").attr("disabled", false); removeAutoComplete(); break;
		case 5: frm.attr("action", "/batdongsan/quicksearch.php"); removeAutoComplete(); break;
	}
	$(".search_keyword").focus();
}

function defaultValueHeaderSearch(){
	ob	= $("form[name='header_search'] input[name='keyword']");
	if(ob.val() == "" || ob.val() == defSearchKeyword){
		ob.val(defSearchKeyword).addClass("form_control_null_value");
	}
}
/*-- End Quick search --*/
