var userAgent = navigator.userAgent.toLowerCase();
var ie6 = false;
var ie7 = false;
var chrome = false;

if (userAgent.indexOf('msie') > -1) {
	ie = true;
	if (userAgent.indexOf('msie 6.0') > -1) {
		ie6 = true;
	}
	if (userAgent.indexOf('msie 7.0') > -1) {
		ie7 = true;
	}
}

var config = new Object;
config.keyword = 'Tìm kiếm';
config.firstPage = 'Trang trước';
config.lastPage = 'Trang sau';
config.siteid = 242;
config.item_per_page = 12;
config.search_per_page = 12;


var stats_service_url = '/service/statistic/statcollector.do';

var module = ['carousel', 'tabview', 'connection', 'advertising'];

var search = document.getElementById('search');

var isCate = false;
var isArticle = false;

var cate = document.getElementById('cate-id');

/*Lấy time*/

Date.prototype.format = function(config) {
	this.formatString = config.format;
	this.lang = (config.lang) ? config.lang : 'vi';

	this.day = this.getDay();

	this.langText = {
		vi: [
			'Chủ Nhật',
			'Thứ Hai',
			'Thứ Ba',
			'Thứ Tư',
			'Thứ Năm',
			'Thứ Sáu',
			'Thứ Bảy'
		],
		en: [
			'Sunday',
			'Monday',
			'Tuesday',
			'Wednesday',
			'Thursday',
			'Friday',
			'Saturday'
		]
	};

	switch (this.lang) {
		case 'vi':
		case 'en':
		break;

		default:
			this.lang = 'vi';
	}

	this.day = this.langText[this.lang][this.day];

	return this.formatString
		.replace(/DAY/, this.day)
		.replace(/DD/, this.getDate())
		.replace(/MM/, this.getMonth() + 1)
		.replace(/YYYY/, this.getFullYear())
		.replace(/HH/, this.getHours())
		.replace(/MI/, this.getMinutes())
		.replace(/SS/, this.getSeconds())
};

var now = new Date().format({
	format: 'DAY, DD/MM/YYYY HH:MI (GMT+7)'
});


function $(id) {
	return document.getElementById(id);
}


if (cate) {
	var article = document.getElementById('article-id');

	if (article.innerHTML) {
		isArticle = true;
	}
	else {
		isCate = true;
	}
}

var loader = new YAHOO.util.YUILoader({ 
	base: '/common/v2/js/yui/build/', 
	skin: {
		base: 'assets/skins/',
		defaultSkin: 'sam',
		overrides: { 
			carousel: ['daklak'],
			tabview: ['daklak']
		}
	},

	onSuccess: function() {
		var tabView = new YAHOO.widget.TabView('priority-new-content');

		var carousel = new YAHOO.widget.Carousel("mycarousel", {
			isCircular: true, 
			numVisible: 3,
			animationSpeed: 0.5,
			scrollIncrement: 3,
			navMargin: 0
		});

		carousel.render();
		carousel.show();

		menuEffect();
		
		subCategory();

		if (isCate) {
			getSubMenu();

			var ipp = 10;
			var cateId = parseInt(cate.innerHTML);
			get_list_cate(ipp, cateId);
		}

		var currentTimeObj = document.getElementById('current-date');
		if(currentTimeObj) {
			currentTimeObj.innerHTML = now;
		}
		
		if (isArticle) {
			getSubMenu();

			try {
				document.getElementById('mycomment').value= '';
			 }
			 catch (e) {}

			 init_feedback();
			get_feedback(1);
		}

		if(search) {
			try {
				get_search_result();
			}
			catch (e) {}
		}

		try {
			load_ads();
		}
		catch (e) {}
	} 
});

loader.addModule({
	name: 'advertising',
	type: 'js',
	fullpath: '/common/v2/js/ad.js'
});

if (isArticle) {
	loader.addModule({
		name: 'article',
		type: 'js',
		fullpath: '/common/v2/js/article.js'
	});
	module.push('article');
}

if (isCate || isArticle || search) {
	module.push('paginator');
}

loader.require(module);
loader.insert();

function menuEffect() {
	var menuArea = document.getElementById("main-menu");
	var listLiTag = menuArea.getElementsByTagName("LI");
	var catId = null;
	//In case user doesn't click into menu item
	if (document.getElementById("cate_id") != null) {
		if (document.getElementById("cate_parent").value != 0) {
			catId = document.getElementById("cate_parent").value;
		} else {
			catId = document.getElementById("cate_id").value;
		}
		var menuId = document.getElementById('cat-' + catId);
		for (var j = 0; j < listLiTag.length; j++) {
			if (YAHOO.util.Dom.hasClass(listLiTag[j], 'active')) {
				YAHOO.util.Dom.removeClass(listLiTag[j], 'active');
			}
		}
		YAHOO.util.Dom.addClass(menuId, 'active');
	} else {
		var home = document.getElementById('cat-0');
		if (!YAHOO.util.Dom.hasClass(home, 'active')) {
			YAHOO.util.Dom.addClass(home, 'active');
		}
	}

	for (var i = 0; i < listLiTag.length; i++) {
		listLiTag[i].childNodes[0].onclick = function () {
			for (var j = 0; j < listLiTag.length; j++) {
				if (YAHOO.util.Dom.hasClass(listLiTag[j], 'active')) {
					YAHOO.util.Dom.removeClass(listLiTag[j], 'active');
				}
			}
			YAHOO.util.Dom.addClass(this.parentNode, 'active');
		}
	}
}

function subCategory() {
	var elements = YAHOO.util.Dom.getElementsByClassName('subcat-item');
	for (z in elements) {
		if (YAHOO.util.Dom.hasClass(elements[z], 'active')) {
			YAHOO.util.Dom.removeClass(elements[z], 'active');
		}
	}

	var hasCateId = document.getElementById("cate-id");
	if (hasCateId) {
		for (x in elements) {
			if (YAHOO.util.Dom.hasClass(elements[x], 'active')) {
				YAHOO.util.Dom.removeClass(elements[x], 'active');
			}

		}
		for (x in elements) {
			var catId = elements[x].id.substring(8);
			if (hasCateId.innerHTML == catId) {
				YAHOO.util.Dom.addClass(elements[x], 'active');
			}
		}
	}
}

function get_list_cate(ipp, category) {
	var rootBase = 'http://baodaklak.vn/';
	var callback = null;
	var item_per_page = (ipp == undefined) ? config.item_per_page : ipp;
	var url = rootBase + 'channel/' + category + '/index.next';
	var obj = document.createElement('div');

	var handleSuccess = function (o) {
		if (o.responseText != undefined) {
			obj.innerHTML = o.responseText;
			var items = obj.getElementsByTagName('blockquote');
			var data = new Array();
			for (var i = 0; i < items.length; i++) {
				data[i] = items[i].innerHTML;
			}

			YAHOO.util.Event.onDOMReady(function () {

				var list = YAHOO.namespace('vsolutions');
				list.content = YAHOO.util.Dom.get('list-cate-next');
				list.handlePagination = function (state) {
					var startIndex = state.recordOffset;
					recs = data.slice(startIndex, startIndex + state.rowsPerPage);
					list.content.start = startIndex + 1;
					list.content.innerHTML = recs.join('');
					list.paginator.setState(state);
				};
				list.paginator = new YAHOO.widget.Paginator({
					rowsPerPage: 15,
					totalRecords: data.length,
					containers: ['paging'],
					template: '{PreviousPageLink} | {NextPageLink}',
					nextPageLinkLabel: 'Trang sau',
					previousPageLinkLabel: 'Trang trước',
					nextPageLinkClass: 'yui-pg-next more'
				});
				list.paginator.subscribe('pageChange', function () {
					window.location.href = '#';
				});
				list.paginator.subscribe('changeRequest', list.handlePagination);
				list.paginator.render();
				list.handlePagination(list.paginator.getState());
			});
		}
	};

	var handleFailure = function (o) {
		if (o.responseText !== undefined) {
			return;
		}
	};

	callback = {
		success: handleSuccess,
		failure: handleFailure
	};
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

function getSubMenu() {
	var rootBase = 'http://baodaklak.vn/';
	var request = null;
	var callback = null;
	var category = null;
	var parent = document.getElementById("parent-cate-id");
	if (parent !== null) {
		var catId = document.getElementById("cate-id");
		var url = '';
		if (parseInt(parent.innerHTML) > 0) {
			category = parent.innerHTML;
			url = rootBase + 'channel/' + category + '/index.menu';
		} else {
			category = catId.innerHTML;
			url = rootBase + 'channel/' + category + '/index.menu';
		}
		var handleSuccess = function (o) {
			var menu = YAHOO.util.Dom.getElementsByClassName('content-box-menu');
			if (menu[0] != null) {
				menu[0].innerHTML = o.responseText;
			}
		};

		var handleFailure = function (o) {
			if (o.responseText !== undefined) {
				return;
			}
		};

		callback = {
			success: handleSuccess,
			failure: handleFailure
		};
		request = YAHOO.util.Connect.asyncRequest('GET', url, callback);

	}
	else {
	/*
		var el = YAHOO.util.Dom.getElementsByClassName('box-d-wrap');
		var id = '';
		var contentBoxMenu = null;
		var num = null;
		url = new Array();
		contentBoxMenu = new Array();
		callback = new Array();
		for (var x in el) {
			id = el[x].id;
			category = id.substring(9);
			url[x] = rootBase + 'channel/' + category + '/index.menu';
			contentBoxMenu[x] = el[x].childNodes[1];
			callback[x] = {
				success: function (o) {
					num = o.argument[0];
					if (contentBoxMenu[num]) {
						contentBoxMenu[num].innerHTML = o.responseText;
					}
				},
				argument: [x],
				failure: function () {
					return null;
				}
			};
		}
		for (i = 0; i < el.length; i++) {
			request = YAHOO.util.Connect.asyncRequest('GET', url[i], callback[i]);
		}
	*/
	}
}

/*Thời tiết*/
function changeWeatherInfo(strInfo) {
	var wImage = strInfo.split("|")[0];
	var wLow = strInfo.split("|")[1];
	var wHigh = strInfo.split("|")[2];
	var wDescription = strInfo.split("|")[3];
	var wCity = strInfo.split("|")[4];
	var wTemp = strInfo.split("|")[5];
	var str = wLow+'-'+ wHigh;
	$('w-sky').src = wImage;
	$('w-desc').innerHTML =wDescription;
	if (wTemp) {
		str = wTemp;
	}
	$('w-temp').innerHTML = str + '<sup>o</sup>C';
}

//this function is used for weblink mode
function link(boxmenu) {
	var url = boxmenu[boxmenu.selectedIndex].value;
	if (url != '') {
		window.open(url);
	}
}

//function init_weather() {
	var selObj = document.getElementById("location");
	if(selObj) {
		changeWeatherInfo(selObj.value);

		// Init Onchange
		selObj.onchange = function() {
			changeWeatherInfo(this.value);
		}
	}

//}


function search_on_focus(field) {
		if(field.value !=''){ field.value = ''; }
}

function search_on_blur(field) {
		var keyWord = '';
		obj = document.getElementById("search-keyword");
		if (obj.value == 'Search') {
			keyWord = 'Key word';
		} else {
			keyWord = 'Từ khoá';
		}
		if(field.value.split(' ').join('') == ''){ field.value = keyWord;}
}


try{
	if ((ie6) || (ie7)){
		var newdiv = document.createElement('div');
		var divIdName = 'isFloat';
		newdiv.setAttribute('id', divIdName);
		newdiv.style.clear = "both";
		newdiv.style.cursor = "pointer";
		newdiv.style.background = "#ffd url(/common/v2/image/warn.gif) no-repeat 5px center";
		newdiv.style.padding = "5px 10px 5px 30px";
		newdiv.style.marginBottom = "10px";
		newdiv.style.borderBottom = "1px solid black"; 
		newdiv.style.position = "relative";
		newdiv.style.zIndex = "1";
		newdiv.style.top="0";
		newdiv.style.font ="10pt Tahoma";
		newdiv.style.color="#000";
		newdiv.onmouseover= linkHover;
		newdiv.onmouseout = linkOut;
		newdiv.onclick = linkClick;
		newdiv.innerHTML="Trình duyệt Internet Explorer của bạn đã lỗi thời. Bấm vào đây để tải về bản mới, nhanh và an toàn hơn.";
		document.body.insertBefore(newdiv, document.getElementById('main'));
	}

}
catch (e){}

function linkClick() {
	window.open('http://windows.microsoft.com/en-us/internet-explorer/products/ie/home');
} 

function linkHover() {
	this.style.backgroundColor='#316ac5'; 
	this.style.color='white';
} 

function linkOut() {
	this.style.backgroundColor='#ffd'; 
	this.style.color='black';
}

