var config = new Object;

if (screen.width >= 1280) {
	_('<link rel="stylesheet" type="text/css" href="/common/v3/css/main-wide.css" />');
	config.checkScreen = true;
	config.theodongsukien = 6;
}
else {
	config.theodongsukien = 5;
	config.checkScreen = false;
}

var userAgent = navigator.userAgent.toLowerCase();
var ie = false;
var ie6 = false;
var ie7 = 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;
	}
}
else if (userAgent.indexOf('firefox') > -1) {
	firefox = true;
}

if (ie7) {
	_('<link rel="stylesheet" type="text/css" href="/common/v3/css/ie7.css" />');
}
if (ie6) {
	_('<link rel="stylesheet" type="text/css" href="/common/v3/css/ie6.css" />');
}

//_('<script type="text/javascript" src="/time/index.php?mod=tnf"></script>');

_('<script type="text/javascript" src="/common/v3/yui/yahoo-dom-event/yahoo-dom-event.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/animation/animation-min.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/element/element-min.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/connection/connection.js"></script>');

//_('<script type="text/javascript" src="/common/v3/yui/connection-min.js"></script>');


_('<script type="text/javascript" src="/common/v3/js/ads.js"></script>');
_('<script type="text/javascript" src="/common/v3/js/poll.js"></script>');
_('<script type="text/javascript" src="/common/v3/js/vckm_data.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/carousel/carousel-min.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/dragdrop/dragdrop.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/container/container_core-min.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/menu/menu-min.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/paginator/paginator-min.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/slider/slider-min.js"></script>');
_('<script type="text/javascript" src="/common/v3/yui/tabview/tabview-min.js"></script>');
_('<link rel="stylesheet" type="text/css" href="/common/v3/yui/carousel/assets/skins/sam/carousel.css">');


/*if (typeof($('megafun-tv')) == 'object') {
	_('<script type="text/javascript" src="http://megafun.vn/common/v2/js/tvonline.js"></script>');
}*/



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

function _(str) {
	document.write(str);
}

function bookmark(obj) {
	var url = 'http://bee.net.vn';
	if (ie) {
		obj.style.behavior = 'url(#default#homepage)';
		obj.setHomePage(url);
	}
	else if (firefox) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel('Bee.net.vn', url, '');
	}
}


function search_on_focus(field) {
 //if(field.value=='Nhập từ khóa...'){
	 field.value = '';
	// }
}

function search_on_blur(field) {
 if(field.value.split(' ').join('') == ''){
	 field.value='Nhập từ khóa...';
 }
}

function set_by_date() {
	var dt = new Date();
	var y  = dt.getFullYear();
	var d  = dt.getDate();
	var m  = dt.getMonth() + 1;

	for (i = 1; i < 32; i++) {
		var tem = document.createElement('option');
		tem.setAttribute('value', i);
		tem.appendChild(document.createTextNode(i));

		if(parseInt(d) == i ) {
			tem.setAttribute('selected', 'true');
		}
		$('view-date').appendChild(tem);
	}

	for(i = 1; i < 13; i++) {
		var tem = document.createElement('option');
		tem.setAttribute('value', i);
		tem.appendChild(document.createTextNode(i));

		if(parseInt(m) == i ) {
			tem.setAttribute('selected', 'true');
		}
		$('view-month').appendChild(tem);
	}

	for(i = 2005; i <= parseInt(y); i++) {
		var tem = document.createElement('option');
		tem.setAttribute('value', i);
		tem.appendChild(document.createTextNode(i));

		if(parseInt(y) == i ) {
			tem.setAttribute('selected', 'true');
		}
		$('view-year').appendChild(tem);
	}
}

function get_by_date() {
	str = 'http://' + location.hostname + '/channel/3641/?cateid=' + $('cate-id').innerHTML + '&type=date&key=' + $('view-year').value + '-' + $('view-month').value + '-' + $('view-date').value ;
	location.href = str;
}

function get_text_content1(url) {

	var html = "";

	if (config.checkScreen){
		url = url + "index.wide";
	}
	else
	{
		url = url + "index.normal";
	}

	var str_return;
	var handleSuccess = function(o) {
		if (o.responseText !== undefined) {
			str_return = o.responseText;
			document.write(str_return);
			};
	};

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

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

}


function get_text_content(url)
{
	var html = "";

	if (config.checkScreen){
		url = url + "index.wide";
	}
	else
	{
		url = url + "index.normal";
	}


	var req = false;
	// For Safari, Firefox, and other non-MS browsers
	if (window.XMLHttpRequest)
	{
		try
		{
			req = new XMLHttpRequest();
		}
		catch (e)
		{
			req = false;
		}
	}

	// For Internet Explorer on Windows
	else if (window.ActiveXObject)
	{
		try
		{
			req = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				req = false;
			}
		}
	}

	if (req)
	{
		// Synchronous request, wait till we have it all
		req.open('GET', url, false);
		req.send(null);
		html = req.responseText;
		document.write(html);
	}
}


function set_cookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays == null || nDays == 0) nDays = 1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString() + ";path=/";
}

function get_cookie( name ) {

	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}


// Weather

function change_weather_info(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];
	// Set cookie if on Change
	try
	{
	 set_cookie("bee_weather",wCity,365);
	}
	catch(e){}

	$('weainfo').innerHTML = "<div>" + wDescription + "</div>";

	var strTemp = "<img class=\"anhminhhoa\" src=\"/common/v3/image/weather/" + wImage + "\" alt=\"\"/>";
	if (wTemp) {
		 strTemp += "<img src=\"/common/v3/image/weather/" + wTemp  + ".gif\"  style = \"padding-top:10px\" alt=\"\"/>";wTemp = wLow + ' - ' +wHigh;
	}else {
		strTemp += "<img src=\"/common/v3/image/weather/" + wLow  + ".gif\"  style = \"padding-top:10px\" alt=\"\"/>";
		strTemp += " <img src=\"/common/v3/image/weather/" + wHigh  + ".gif\"  style = \"padding-top:10px\" alt=\"\"/>";
	}
	strTemp += "<img src=\"/common/v3/image/weather/c.gif\"  style = \"padding-top:10px\" />";
	$('wea').innerHTML = strTemp;

}



function init_weather()
{

	// Init the first Location
	 var selObj = document.getElementById("province");

	 var selIndex = selObj.selectedIndex;

	 var strInfo = selObj.options[selIndex].value;

	 if (get_cookie("bee_weather") != null)
	 {
	  	get_options(selObj,get_cookie("bee_weather"));
	 }
	 else
	 {
	  	change_weather_info(strInfo);
	 }
	// Init Onchange

	 var llocation = document.getElementById('province');

	 llocation.onchange = function() {
		 change_weather_info(llocation.options[llocation.selectedIndex].value);
	  }
}


function get_options(x,xValue)
{
	for (i=0;i<x.length;i++)
    {
      if (x.options[i].value.indexOf(xValue) > -1)
      {
          x.selectedIndex = i;
          change_weather_info(x.options[i].value);
      }
    }
}

function check_url(url) {
	return true;
}

function open_window(html, width, height) {
	try {
		winDef = 'status=no,resizable=no,scrollbars=no,toolbar=no,location=no,fullscreen=no,titlebar=yes,height='.concat(height).concat(',').concat('width=').concat(width).concat(',');
		winDef = winDef.concat('top=').concat((screen.height - height) / 2).concat(',');
		winDef = winDef.concat('left=').concat((screen.width - width) / 2);
		mediaWin = open('', '_blank', winDef);
		html = '<title>Bee.net.vn</title><body style="margin: 0;">' + html;
		mediaWin.document.writeln(html);
	}
	catch (e) {}
	return false;
}

function play_video(url) {

	if (!check_url(url)) {
		return false;
	}

	var html='<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="@width" height="@height" src="http://bee.net.vn/common/v3/player/player.swf" flashvars="file=@url&autostart=@autostart&allowfullscreen=true" wmode="transparent" />';

	var width = '400';
	var height = '300';
	var autostart = '1';


	html = html.replace(/@url/, url)
		.replace(/@width/, width)
		.replace(/@height/, height)
		.replace(/@autostart/, autostart);

	return open_window(html, width, height);
}



function get_list_video() {


	url = "/channel/2123/index.xml";

       var handleSuccess = function(o) {
	if (o.responseXML !== undefined)
	{

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


			var data_list = YAHOO.namespace('vSolutions');

			data_list.content = YAHOO.util.Dom.get('list-clip');

			var get_data = function(xmlData, row_per_page, page)
			{

				var rowData;
	            var totalRow = xmlData.getElementsByTagName("ROW").length;
	            var strData;
	            strData = "";

	            if (totalRow > 0)
	            {
			        rowData = xmlData.getElementsByTagName("ROW");
    		        var i;
	                var image_file_name;
	                var title;
	                var video_url;
	                var page_url;
	                var createdate;

					if (config.checkScreen)	{
						row_per_page = row_per_page;
					}
					else
					{
						row_per_page = 3;
					}

	                for (i = row_per_page * (page - 1) ; i < row_per_page * page ; i ++ )
		            {
		                image_file_name ='';
		                title='';
		                video_url='';
		                createdate='';
		                try
		                {
		                    image_file_name = rowData.item(i).getElementsByTagName("IMAGE_FILE_NAME").item(0).childNodes.item(0).data;
		                    title = rowData.item(i).getElementsByTagName("TITLE").item(0).childNodes.item(0).data;
		                    video_url = rowData.item(i).getElementsByTagName("VIDEO_URL").item(0).childNodes.item(0).data;
		                    page_url = rowData.item(i).getElementsByTagName("PAGE_URL").item(0).childNodes.item(0).data;
		                    createdate = rowData.item(i).getElementsByTagName("CREATEDATE").item(0).childNodes.item(0).data;
		                }
		                catch(e)
						{
						}

						if ( (i%2==0) || (row_per_page == 3))
						{
							strData =  strData + '<div class="item col-first">';
						}
						else
						{
							strData =  strData + '<div class="item">';
						}

						strData =  strData +  '<a  class="title" href="' + page_url + '" title="' + title + '"><img src="/dataimages/' + createdate + '/normal/' + image_file_name + '" alt="' + title + '" class="avatar" /></a>';
						strData =  strData + '<div><a  class="title" href="' + page_url + '" title="' + title + '">' + title + '</a></div>';
						strData =  strData + '<div class="clear">.</div>';
						strData =  strData + '</div>';

		            }
                    data_list.content.innerHTML =  strData;
				}
                else
                {
        		    data_list.content.innerHTML =  'KhÃ´ng cÃ³ dá»¯ liá»‡u';
        		}
			}

			var get_list = function(page, row_per_page)
			{
			    url = "/channel/2123/index.xml";
                var handleSuccess = function(o) {
					if (o.responseXML !== undefined) {
						get_data(o.responseXML, row_per_page, page) ;
					}
				};

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

				var callback = {
					success: handleSuccess,
					failure: handleFailure
				};

				var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
			};



			data_list.handlePagination = function(state){
			    get_list(state.page, state.rowsPerPage);
				data_list.paginator.setState(state);
			};

            try
            {
			        data_list.paginator = new YAHOO.widget.Paginator({
					rowsPerPage: 6,
					totalRecords: 48,
					containers: ['paging'],
					template : '{PreviousPageLink} {PageLinks} {NextPageLink}',
					previousPageLinkLabel : "Trước",
					nextPageLinkLabel : "Sau",
					nextPageLinkClass : 'next',
					previousPageLinkClass : 'prev',
					currentPageClass : 'active',
					alwaysVisible : true,
					updateOnChange : false,
					firstPageLinkLabel : config.firstPage,
					lastPageLinkLabel : config.lastPage,
					pageLinks : 4
			});
                     }
                     catch(e){};


			data_list.paginator.subscribe('pageChange', function() {
			});


			data_list.paginator.subscribe('changeRequest', data_list.handlePagination);
			data_list.paginator.render();
			data_list.handlePagination(data_list.paginator.getState());
		});
	}
    };

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

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

function gen_menu() {

	pcate = $('parentcate').getElementsByTagName('div');
	scate = $('subcate').getElementsByTagName('div');

	$c='';
	$p='';
	try {
		$c = $('cate-id').innerHTML;
		$p = $('parent-cate-id').innerHTML;
	}
	catch (e) {
		$c='';
		$p='';
	}


	strHtml = '<div class="bd"><ul class="first-of-type">';
	if (($c=='') && ($p==''))
		strHtml += "<li class='yuimenubaritem first-of-type active'>";
	else
		strHtml += "<li class='yuimenubaritem first-of-type'>";

	strHtml +=	"<a class='yuimenubaritemlabel' href='/'>Trang chủ</a>";
	strHtml +=	"</li>";

	var cssActive = '';
	for (var i = 0; i < pcate.length; i++ ) {

		cssActive = '';

		if ($p =='') {
			if ($c==pcate[i].id)
				cssActive = ' active';
			else
				cssActive = '';
		}
		else
		{
			if ($p==pcate[i].id)
				cssActive = ' active';
			else
				cssActive = '';
		}

		if(i == pcate.length -1)
			strHtml += "<li class='yuimenubaritem last" + cssActive + "'>";
		else
			strHtml += "<li class='yuimenubaritem" + cssActive + "'>";

		strHtml +="<a href='/channel/" + pcate[i].id + "/' class='yuimenubaritemlabel'>" + pcate[i].innerHTML + "</a>";
		strSubMenu = '';
		for (var j = 0; j < scate.length; j++ ) {
			if(scate[j].className == pcate[i].id)
			{
				strSubMenu += "<li class='yuimenuitem'><a href='/channel/" + scate[j].id + "/' class='yuimenuitemlabel'>" + scate[j].innerHTML + "</a></li>";
			}
		}
		if (strSubMenu != '') {
			strHtml += "<div class='yuimenu'><div class='bd'><ul>" + strSubMenu + "</ul></div></div>";
		}
		strHtml += "</li>";
	}
	strHtml += '</ul></div>';
	_(strHtml);
}

function clientSideInclude(id, url) {
		var handleSuccess = function(o) {
		if (o.responseText !== undefined) {
			$(id).innerHTML = o.responseText;
			if (o.responseText.length < 10) {
				$(id).style.display = 'none';
			}
		}
	};

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

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

function addCLickAdman(c,p,t) {
	//c=ad_right_1 (%23507)&p=ad_right_1 (%23413)&t=tran anh (%23360)
	var url = '/service/statistic/statcollector.do?u=221&s=181&c=' + c + '&p=' + p + '&t=' + t;
		var handleSuccess = function(o) {
				return;
		};

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

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

function Ie6CountDown() {
	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/v3/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';
}


var vsDateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = vsDateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
vsDateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
vsDateFormat.i18n = {
	dayNames: [
		"Chủ Nhật", "Thứ Hai","Thứ Ba","Thứ Tư","Thứ Năm","Thứ Sáu","Thứ Bảy"
	],
	monthNames: [
		"Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
	]
};
