/**
 * @author Xuan Dung
 */
$(document).ready(function(){

/**
 * Play video o trang chu
 * @param {Object} this
 */	

	
	$('.playvideo').click(function(){
		var url = $(this).attr('id');
		var url_thum = $(this).attr('title');
		var str1 = '<embed height="238" width="279" type="application/x-shockwave-flash" src="'+base_url+'flashplay/mediaplayer.swf" style="" id="MediaPlayer" name="MediaPlayer" quality="high" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" flashvars="width=278&amp;height=238&amp;file='+url+'&amp;image='+url_thum+'"/>';
		$("#id_video").html(str1);		
		return false;
	});
	
/**
 * xu ly anh qua lon o trang detai
*/
	
	$('.news-detail img').load(function(){
		var w = $(this).width();
		if(w>400){
			$(this).css('width','400px');
		}	
	})	 
/**
 * Hien Textbox sua o trang adminsource
 */
	$('.editSource').click(function(){
		var id = $(this).attr('id');
		var title = $(this).attr('title');
		var str = '<input type="text" class="editText" value="'+title+'" id="valfn'+id+'"/> <input type="button" value="HoÃ n táº¥t" id="fn'+id+'" onclick="editNameSource(this.id)"/><input type="button" value="ThoÃ¡t"  id="'+id+'e" title="'+title+'" onclick="exitEdit(this.id,this.title)"/>';
		document.getElementById(id+'edit').innerHTML=str;
		document.getElementById('valfn'+id).focus();
	})
	
/**
 * thu gon o trang rao vat
 */
	$('.title-ravat a').click(function(){
		var id ='#' + $(this).attr('id')+'thugon';
		$(id).toggle('slow');
		return false;
	})
	
	
	getWeather(4);
	createGold();
	createForex();
	imgdetail();
	
	$("#cboWeather").change(function(){
		getWeather($(this).val());
	})
	
	menu();
	$('#stockChange').change(function(){
		stockChange();
	})
	
})

function checkloadimage(divid){
 document.getElementById(divid).style.display='none';
 }

function menu(){
	
	j=$("#navid a").index($(".current")[0] );
	if(j>0 && document.getElementById('colen')!=null){
		var tabmenu = document.getElementById('colen').clientWidth;
		var  w = 0;
		for(k=0;k<j;k++){
			w+=document.getElementById('menu-'+k).clientWidth;
		}
		if((w+tabmenu/2)<940){
		var pad = w-tabmenu/2+30;
			if(pad>0){
			document.getElementById('navsubid').style.paddingLeft = pad+'px';
			document.getElementById('navsubid').style.width = (940-pad)+'px';
			}
		}else {
			//do nothing
		}
	}
}

function sourceLink(url){
	window.location.href = url;
}

function checkDomain(nname)
{
var arr = new Array(
'.com','.net','.org','.biz','.coop','.info','.museum','.name',
'.pro','.edu','.gov','.int','.mil','.ac','.ad','.ae','.af','.ag',
'.ai','.al','.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw',
'.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm',
'.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cc',
'.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.cr',
'.cu','.cv','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz',
'.ec','.ee','.eg','.eh','.er','.es','.et','.fi','.fj','.fk','.fm',
'.fo','.fr','.ga','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm',
'.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gv','.gy','.hk','.hm',
'.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io','.iq',
'.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki',
'.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li',
'.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.mg',
'.mh','.mk','.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt',
'.mu','.mv','.mw','.mx','.my','.mz','.na','.nc','.ne','.nf','.ng',
'.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.pa','.pe','.pf',
'.pg','.ph','.pk','.pl','.pm','.pn','.pr','.ps','.pt','.pw','.py',
'.qa','.re','.ro','.rw','.ru','.sa','.sb','.sc','.sd','.se','.sg',
'.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.sv',
'.sy','.sz','.tc','.td','.tf','.tg','.th','.tj','.tk','.tm','.tn',
'.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.um',
'.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.ws',
'.wf','.ye','.yt','.yu','.za','.zm','.zw');

var mai = nname;
var val = true;
var dot = mai.lastIndexOf(".");
var dname = mai.substring(0,dot);
var ext = mai.substring(dot,mai.length);
//alert(ext);
	
if(dot>2 && dot<57)
{
	for(var i=0; i<arr.length; i++)
	{
	  if(ext == arr[i])
	  {
	 	val = true;
		break;
	  }	
	  else
	  {
	 	val = false;
	  }
	}
	if(val == false)
	{
	  //	 alert("Your domain extension "+ext+" is not correct");
		 return false;
	}
	else
	{
		for(var j=0; j<dname.length; j++)
		{
		  var dh = dname.charAt(j);
		  var hh = dh.charCodeAt(0);
		  if((hh > 47 && hh<59) || (hh > 64 && hh<91) || (hh > 96 && hh<123) || hh==45 || hh==46)
		  {
			 if((j==0 || j==dname.length-1) && hh == 45)	
		  	 {
		 //	  	 alert("Domain name should not begin are end with '-'");
			      return false;
		 	 }
		  }
		else	{
		  //	 alert("Your domain name should not have special characters");
			 return false;
		  }
		}
	}
}
else
{
// alert("Your Domain name is too short/long");
 return false;
}	

return true;
}


function createXMLHttp(){
    var xmlHttp=null;
    try{
        xmlHttp=new XMLHttpRequest();
    }
    catch(e){
        try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
     }
     return xmlHttp;
};
function delSource(id){
	var url=base_url+"admin/adminsource/delsource/"+id+"/";
	if(confirm('Báº¡n cÃ³ cháº¯c cháº¯n muá»‘n xÃ³a khÃ´ng !')){
	var re=createXMLHttp();
	re.onreadystatechange=function(){ 	
	if(re.readyState==4)
            {
				var report = re.responseText;
				document.getElementById('alert').className = "alert";
				document.getElementById('alert').innerHTML = report;
				
				window.location.reload();
             }else document.getElementById('alert').innerHTML = 'Há»‡ thá»‘ng Ä‘ang xá»­ lÃ½...'
	  }
	  re.open("GET",url,true);
 	  re.send(null);
	  }
}

function editNameSource(id){	
	var val = document.getElementById('val'+id).value;
	var url=base_url+"admin/adminsource/editsource/"+val+"/"+id+"/";
	if(val!='' && checkDomain(val)){
		var re=createXMLHttp();
	re.onreadystatechange=function(){ 	
	if(re.readyState==4)
            {
				var report = re.responseText;
				document.getElementById('alert').className = "alert";
				document.getElementById('alert').innerHTML = report;
				window.location.reload();
             }else document.getElementById('alert').innerHTML = 'Há»‡ thá»‘ng Ä‘ang xá»­ lÃ½...';
	  }
	  re.open("GET",url,true);
 	  re.send(null);
	}
	else alert('TÃªn nguá»“n cá»§a báº¡n khÃ´ng há»£p lá»‡ !');
	
}

function exitEdit(id,name){
	document.getElementById(id+'dit').innerHTML = '<p>'+name+'</p>';
}

function changeStatus(id,stt){
	var url=base_url+"admin/adminsource/changestatus/"+id+"/"+stt+"/";
	var re=createXMLHttp();
	re.onreadystatechange=function(){ 	
	if(re.readyState==4)
            {
				var report = re.responseText;
				document.getElementById('alert').className = "alert";
				document.getElementById('alert').innerHTML = report;
				var t = setTimeout(window.location.reload(),10000);
             }else document.getElementById('alert').innerHTML = 'Há»‡ thá»‘ng Ä‘ang xá»­ lÃ½...';
	  }
	  re.open("GET",url,true);
 	  re.send(null);
}
function Trim(sString){
	while (sString.substring(0,1) == ' ')
	{
	sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
	sString = sString.substring(0,sString.length-1);
	}
	return sString;
}
/**
 *  Resize img
 * @param {Object} aImages
 * @param {Object} nImages
 * @param {Object} idimag
 * @param {Object} widthnew
 * @param {Object} heightnew
 */
function rsimg(id,wn,hn){
	
	var m = document.getElementById(id).src;
	var h = document.getElementById(id).height;
	var w = document.getElementById(id).width;
	if((w/h)>(wn/hn)){
			document.getElementById(id).style.width=wn+'px';
		}else document.getElementById(id).style.height=hn+'px';
}

function rsimgmar(id,wn,hn){
	var m = document.getElementById(id).src;
	var h = document.getElementById(id).height;
	var w = document.getElementById(id).width;
	if((w/h)>(wn/hn)){
			document.getElementById(id).style.width=wn+'px';
			var mar = hn  - h/w*wn;
			document.getElementById(id).style.marginTop = mar + 'px';
		}else document.getElementById(id).style.height=hn+'px';
}

function onPreload(aImages, nImages,idimag,widthnew,heightnew)
{
   try{ 
     var oIdimag;
     oIdimag = document.getElementById(idimag);
      
            if ( nImages == 1 ){
                  aImages =  resizePicture(aImages.src,widthnew,heightnew);
                  if(aImages.width != 0 && aImages.height != 0){
                  	oIdimag.style.width = aImages.width+"px";
                  	oIdimag.style.height = aImages.height+"px";
                  }
                  else{
                  	oIdimag.style.width = widthnew+"px";
                  oIdimag.style.height = heightnew+"px";
                  }
                  oIdimag.src=aImages.src;
                  return ;
               }else{
                     oIdimag.style.width = width+"px";
                     oIdimag.style.height = height+"px";
                     oIdimag.src='images/no-image.gif';
                     }
    
  }catch(e){
	    
      return false;
      }
}
/*
    - Ham thuc hien viec resize hinh anh theo mot kich thuc khac
*/
function resizePicture(url,rong,cao)
{
	const_width = rong;
	const_height = cao;
	oImg = new Image();
	oImg.src =url;
	if((rong > oImg.width )&& (cao > oImg.height )){
	return oImg;
	}
	else
	{	
		scale = (const_width/oImg.width > const_height/oImg.height) ? const_height/oImg.height : const_width/oImg.width;
		if(oImg.height * scale!=0 && oImg.width * scale!=0){
			oImg.height = oImg.height * scale;
			oImg.width = oImg.width * scale;
		}
		else{
			oImg.height = const_height;
			oImg.width = const_width;
		}
	}
	return oImg;
}

function loading(Image,Idimage,widthnew,heightnew)
{
      
	   try{
		 
     	   var urlsmall = [Image];
		  
          new ImagePreloader(urlsmall, onPreload,Idimage,widthnew,heightnew);
        }catch(e){
        alert(Image);
            return false;
}
}

/***
 * end resize;
 */

function getString(){
	var key = document.getElementById('key').value;
	key 	= trim(key);
	key 	= replacequery(key);
	key 	= encodeURIComponent(key);

	if((key!='') && key!=null){
		window.location.href = base_url+'search/'+key;
	}else document.getElementById('key').focus;
}

function replacequery(str) {	
	str = ltrim(str);	
	var str2 = str.indexOf('.');
	if ( str2 == 0 ) { 
		str = str.replace('.', '');
	}
	str = str.replace(/ /g,' ');
	str = str.replace(/\%20/g,' ');
	str = str.replace(/\?/g,'');
	str = str.replace("\|",'');
	str = str.replace(/\//g,'');
	str = str.replace(/\\/g,'');
	return str;
}
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function checkMail(){
	window.location.href = 'http://cpweb.vnn.vn/cp/ps/Main/login/Authenticate';
}
/**
 * Thoi tiet trang chu
 */
function getWeather(id){
	var url = base_url+'home/getWeather/'+id+'/';
	$.getJSON( url , function(data){	
		$(".boxWeather").fadeOut(1);
		$("#temp").html(data.temp);
		$("#imgW").attr("src", data.img);
		$("#infoWeather").html(data.text);
		$("#cboWeather").val(id);
		$(".boxWeather").fadeIn('slow');
	})	
}


/**
 * gold trang chu
 */

function createGold(){
	var str = '';
	str += '<table border="1" cellpadding="0" cellspacing="0">';
	str += '<tr>';
	str += '<td>Lo&#7841;i:</td>';
	str += '<td>Mua</td>';
	str += '<td>B&#225;n</td>';
	str += '</tr>';
	str += '<tr>';
	str += '<td>SBJ</td>';
	str += '<td>'+ vGoldSbjBuy +'</td>';
	str += '<td>'+ vGoldSbjSell +'</td>';
	str += '</tr>';
	str += '<tr>';
	str += '<td>SJC</td>';
	str += '<td>'+ vGoldSjcBuy +'</td>';
	str += '<td>'+vGoldSjcSell +'</td>';
	str += '</tr>';
	str += '</table>';
	$("#tableGold").html(str);
}

function createForex(){
	var str = '';
	str += '<table border="1" cellpadding="0" cellspacing="0">';
	str += '<tr>';
	str += '<td>Ngoại tệ</td>';
	str += '<td>VND</td>';
	str += '</tr>';
	for(var i =0; i <12 ; i++){
		str += '<tr>';
		str += '<td>'+vForexs[i]+'</td>';	
		str += '<td>'+vCosts[i]+'</td>';
		str += '</tr>';
	}
	str += '</table>';
	$("#tableForex").html(str);
}	

/*------------ stock ------------------*/

function stockChange(){
	var  sel = document.getElementById('stockChange').value;
	if(sel==1){
		document.getElementById('hastc').style.display = 'block';
		document.getElementById('hostc').style.display = 'none';
	}else {
		document.getElementById('hastc').style.display = 'none';
		document.getElementById('hostc').style.display = 'block';
	}
}


 $(function () {
					 $('div.demo marquee').marquee('pointer','height:30px').mouseover(function () {
					 $(this).trigger('stop');
					 }).mouseout(function () {
					 $(this).trigger('start');
					 }).mousemove(function (event) {
					 if ($(this).data('drag') == true) {
					 this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
					 }
					 }).mousedown(function (event) {
					 $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
					 }).mouseup(function () {
					 $(this).data('drag', false);
					 });
				 });
				 
				 			 
				
function imgdetail(){
	if(document.getElementById('imgdetail')!=null){
		var img = document.getElementById('imgdetail').getElementsByTagName('img');
		for(i=0;i<img.length;i++){
			if(img[i].width>420){
				img[i].width = 420;
			}
		}
		
		var tab = document.getElementById('imgdetail').getElementsByTagName('table');
		for(i=0;i<tab.length;i++){
			if(tab[i].clientWidth>470){
				tab[i].width = 470 ;
			}
		}
	//	alert(tab.length);
	}
}
/**
 * xem truoc bai viet tong admin
 */

