var meurl ='http://me.zing.vn';
var ME_ID = '';
var ME_UNAME = '';

function copyTextToClipboard(id)
{
    var doc = document.getElementById(id);
    doc.focus();
    doc.select();
    if(doc.createTextRange)
    {
        var CopiedTxt = doc.createTextRange();
        CopiedTxt.execCommand("Copy");
    }
}

function checkParentFrame(meurlshort, meurl)
{	
    if(window.parent.location.host != meurlshort) {
        window.location = meurl + window.location.pathname;
    }
}
function getTheHeight(opt_height,_document,_parent) 
{
    var newHeight = parseInt(opt_height, 10);
    if (isNaN(newHeight)) 
    {    
        var vh = _parent.height;
        var body = _document.body;
        var docEl = _document.documentElement;
        if (_document.compatMode === 'CSS1Compat' && docEl.scrollHeight)
        {
            newHeight = docEl.scrollHeight !== vh ? docEl.scrollHeight : docEl.offsetHeight;
        }
        else
        {
            var sh = docEl.scrollHeight;
            var oh = docEl.offsetHeight;
            if (docEl.clientHeight !== oh)
            {
                sh = body.scrollHeight;
                oh = body.offsetHeight;
            }
            if (sh > vh)
            {
                newHeight = sh > oh ? sh : oh;
            }
            else
            {
                newHeight = sh < oh ? sh : oh;
            }
        }
    }
    return newHeight;
}

function resizeFrame(name, sHeight, sHeightDefault) {
    if(sHeight == undefined || sHeight == "")
        sHeight = 600;
    if(sHeightDefault == undefined || sHeightDefault == "")
        sHeightDefault = 500;
    f = window.parent.document.getElementById(name);
		
    if(sHeightDefault > sHeight)
    {
        f.style.height =  sHeightDefault + 'px';
    }
	
    var _height = 0;
    _height = getTheHeight('',f.contentWindow.document,f);
		
    sHeightDefault = parseFloat(sHeightDefault);
    _height = parseFloat(_height);
    sHeight = parseFloat(sHeight);
    if(sHeightDefault < 0)
    {
        _height = _height + sHeightDefault ;
    }
	
    if(_height < sHeight) _height = sHeight;
    f.height = _height;
    document.getElementById('wrapper').style.height = _height + "px";
    f.style.height = _height + "px";
}

function resizeParent(sHeightDefault)
{	
    resizeFrame('123mua', 600, sHeightDefault);
}

function search()
{
    var text = $('#text').val();
	
    //Check empty
    if(text == '' || text == 'Bạn muốn mua gì cho ngày hôm nay?')
    {
        alert('Bạn cần nhập từ khóa cần tìm kiếm.');
        $('#text').focus();
        return false;
    }
	
    //Check length
    if(text.length < 3)
    {
        alert('Nhập ít nhất 3 ký tự để tìm kiếm.');
        $('#text').focus();
        return false;
    }
	
    //Get select
    var mod = $('#mod').val();
	
    //Check mod
    var action = $('#frmSearch').attr('action') ;
    if(mod == '1')
    {
        action += '/searchshop';
    }
    else
    {
        action += '/searchadvs';
    }
	
    //Submit form
    $('#frmSearch').attr('action', action) ;
    //$('#frmSearch').submit();
	
    return true;
}

function rollbackComment() 
{
    var str = $('#txtcomment').val() ;
    if(str == '')
    {
        $('#txtcomment').val(flgStr) ;
        flgBool = false ;
    }
}

function commentCallbackPost(jData)
{
    timeoutinteraction = setTimeout('Interaction_Comment.GoPage(1,\'zCommentID\')',300);
    flgBool = false ;
    clearText();
    //Send notify
    var sid = Math.random();
    var interaction_categoryid = $('#interaction_categoryid').val();
    var interaction_userid = $('#interaction_userid').val();
    var notifyurl = baseurl + "/product/notify?id="+interaction_categoryid+"&userid="+interaction_userid+"&sid="+sid+"&type=1";
    $.get(notifyurl, {}, function(data, textStatus){});
    return false;
}

function commentSubmit() 
{
    var str = $('#txtcomment').val() ;
    if(!str || !flgBool)
    {
        alert('Vui lòng nhập nội dung bình luận !!!');
        return false ;
    }
    Interaction_Comment.Post(0,'zCommentID');
    flgBool = false ;
    clearText();
    return false;
}

function emoticon_open()
{ 	
    document.getElementById('emoticon').style.display='block';
    document.getElementById('emoticon-lose').style.display='none';

	getEmoticonForm('emoticon');
}

function emoticon_close()
{ 	
    document.getElementById('emoticon').style.display='none';
    document.getElementById('emoticon-lose').style.display='block';
}				

function emoticon_msg(obj)
{
    clearText();
    document.getElementById('txtcomment').value +=	' '+obj+' ';
    document.getElementById('txtcomment').focus();
}

function clearText() 
{	
    emoticon_close();
    if(!flgBool)
    {
        flgStr = $('#txtcomment').val() ;
        $('#txtcomment').val('') ;
        flgBool = true ;
    }
}
var callbackNumber = 0;

function commentDel(CommentItemID, MessageID) 
{	
    var sid = Math.random();
    var categoryid = $('#interaction_categoryid').val();
    var interaction_totalcmd = $('#interaction_totalcmd').val();
    var getbaseurl = baseurl + '/product/delcomm?CommentItemID='+CommentItemID+'&MessageID='+MessageID+'&categoryid='+categoryid+"&totalcmd="+interaction_totalcmd+"&sid="+sid;
    $.get(getbaseurl, {}, function(data, textStatus){
        data = parseInt(data);
        if(data == 1)
        {
            callbackNumber = 0;
            alert('Xóa bình luận thành công!');
        }
        else
        {
            alert('Xóa bình luận không thành công!');
        }
        timeoutinteraction = setTimeout('Interaction_Comment.GoPage(1,\'zCommentID\')',100);
    });
    return false ;
}

function strReplaceAll( strTarget, strSubString, strText)
{	
    var intIndexOfMatch = strText.indexOf( strTarget );
    if(intIndexOfMatch == -1)
    {
        intIndexOfMatch = strText.indexOf( strTarget.toUpperCase() );
    }
	
    while(intIndexOfMatch != -1)
    {
        strText = strText.replace( strTarget, strSubString ) ;
        strText = strText.replace( strTarget.toUpperCase(), strSubString );
        intIndexOfMatch = strText.indexOf( strTarget );
    }
    return( strText );
}

function parseComment(str) 
{
    var str_replace = "";
    var i ;
    var img_smile_server = "http://static.me.zing.vn/images/smilley/default/";
		
    for(i in arr_emotion)
    {
        str_replace = '<img src="'+img_smile_server+arr_emotion[i]+'.jpg" style="cursor: pointer;" align="absmiddle"/>' ;
        str =  strReplaceAll(i, str_replace , str);
    }
    return str ;
}

function goCommentUrl(page)
{
    Interaction_Comment.GoPage(page,'zCommentID');
    return false ;
}

function getHeightView(url)
{
    var _height = document.getElementById(url).offsetTop;
    return _height ;
}

function commentCallback(jData)
{
    var strItem = "";
    var strPaging = "";
    var totalpage = 0 ;
    var curpage = 0 ;
    var prepage = 0 ;
    var nextpage = 0 ;
    var len = jData.CItem.length ;
    var comment = '' ;
    var frame_height = 1 ;
				
    if(timeoutinteraction)
    {
        clearTimeout(timeoutinteraction) ;
    }
	
    if(len > 0)
    {
        for(i =0; i < len; i++)
        {
            comment = parseComment(jData.CItem[i].Comment) ;
            strItem += '<div class="comment_post clearfix">';
			
            //Avatar
            if(delpermit)
            {
                strItem += '<div class="closeAll"><a href="#" onclick="return commentDel('+ jData.CItem[i].CommentItemID + ','+ jData.CItem[i].MessageID +');"><img height="14" border="0" width="14" src="'+imgurl+'/zme_closeAll2.png" onmouseover="this.src=\'http://img.me.zdn.vn/images/zme_closeAlls.png\'" onmouseout="this.src=\''+imgurl+'/zme_closeAll2.png\'" title="Xóa" alt="Xóa"></a></div>';
            }
            strItem += '<div class="avatar_min"><a target="_top" href="'+ meurl + '/'+ jData.CItem[i].DisplayName +'"><span href="'+ meurl + '/'+ jData.CItem[i].DisplayName + '" rel="ZMEA_' + jData.CItem[i].DisplayName + '?width=50&height=50"></span></a></div>' ;
			
            //Name
            strItem += '<div class="info_comment">' ;
            strItem += '<h1><a target="_top" href="'+ meurl + '/'+ jData.CItem[i].DisplayName +'"><span href="'+ baseurl + '/' + jData.CItem[i].DisplayName +'" rel="ZMED_' + jData.CItem[i].DisplayName + '"></span></a></h1>' ;
            strItem += '<span class="update_time">Vào lúc ' + jData.CItem[i].CommentDate + ' ' + jData.CItem[i].CommentTime + '</span>' ;
            strItem += '<p>'+comment+'</p>' ;
            strItem += '</div>' ;
            strItem += '</div>' ;
            frame_height++;
        }

        strPaging = '' ;
        totalpage = jData.CPaging.TotalPage;
        curpage = jData.CPaging.CurrentPage ;
        prepage = parseInt(curpage) - 1 ;
        nextpage = parseInt(curpage) + 1 ;
        $('#spTotal').html(jData.CPaging.TotalRecord);
        $('#interaction_totalcmd').val(jData.CPaging.TotalRecord);
        if(totalpage > 10)
        {
            totalpage = 10 ;
        }

        strPaging +='<div class="paging">';
        strPaging +='<div class="total">Có ' + jData.CPaging.TotalRecord + ' kết quả thích hợp </div>';
		
        if(totalpage>1)
        {
		    
			
            strPaging += '<div class="pageOn">' ;
            if( curpage > 1 )
            {
                strPaging += '<span class="sum"><a href="#CommentView" onclick="return goCommentUrl(' + prepage + ');">Trở vỿ</a></span>';
            }
						
            for(var i =1; i<= totalpage; i++)
            {
                if(i == jData.CPaging.CurrentPage)
                {
                    strPaging += '<span class="active">' + i + '</span>';
                }
                else
                {
                    strPaging += '<span><a href="#CommentView" onclick="return goCommentUrl(' + i + ');">' + i + '</a></span>';
                }
            }
			
            if( jData.CPaging.CurrentPage < totalpage )
            {
                strPaging += '<span class="sum"><a href="#CommentView" onclick="return goCommentUrl(' + nextpage + ');">Tiếp theo</a></span>';
            }
			
            strPaging += '</div>';
        }
		
        strPaging += '</div>';
    }
	
    strItem += strPaging ;
    $('#zCommentID').html(strItem);
	
    if(len > 0)
    {
        ZME_widget_mix();
    }
	
    /* Send notify */
    if(callbackNumber > 0)
    {
        var sid = Math.random();
        var interaction_categoryid = $('#interaction_categoryid').val();
        var interaction_userid = $('#interaction_userid').val();
        var interaction_totalcmd = $('#interaction_totalcmd').val();
        var commenturl = baseurl + "/product/comm?categoryid="+interaction_categoryid+"&userid="+interaction_userid+"&totalcmd="+interaction_totalcmd+"&sid="+sid;
        $.get(commenturl, {}, function(data, textStatus){});
    }
    callbackNumber++;
	
    return false ;
}

function number_format(number, decimals, dec_point, thousands_sep)
{   
    var n = !isFinite(+number) ? 0 : +number, 
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec);
        return '' + Math.round(n * k) / k;
    };
    /* Fix for IE parseFloat(0.55).toFixed(0) = 0;*/
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function loadStar(position)
{
    var i=0;
    for(i=1; i<=position; i++)
    {
        $("#add_start"+i).removeClass("starOut");
        $("#add_start"+i).addClass("starIn");
    }
    return false;
}

function unloadStar()
{	
    var i =1;
    for(i=1; i<=5; i++)
    {
        $("#add_start"+i).removeClass("starIn");
        $("#add_start"+i).addClass("starOut");
    }
    return false;
}

function findPosX(obj) {
    var curleft = 0;

    if(obj.offsetParent) {
        while(1) {
            curleft += obj.offsetLeft;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    } else if(obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;

    if(obj.offsetParent) {
        while(1) {
            curtop += obj.offsetTop;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    } else if(obj.y) {
        curtop += obj.y;
    }
    return curtop;
}

function findPos(obj) {
    var left = findPosX(obj);
    var top = findPosY(obj);

    return [left , top];
}

function findPosition( oElement ) {
    if( typeof( oElement.offsetParent ) != 'undefined' ) {
        for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
            posX += oElement.offsetLeft;
            posY += oElement.offsetTop;
        }
        return [ posX, posY ];
    } else {
        return [ oElement.x, oElement.y ];
    }
}

function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec);
        return '' + Math.round(n * k) / k;
    };
    /* Fix for IE parseFloat(0.55).toFixed(0) = 0; */
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function OpenWin(url, width, height)
{
    window.open(url,'pop_win','width=' + width + ',height=' + height + ',toolbar=no,status=no,resizable=no,scrollbars=no');
}

function validate(email) {	 
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   
   if(reg.test(email) == false) {       
      return false;
   }

   return true;
}

var bubbleTemplate = function(shopType)
{
    var title, rank, description;

    if (shopType == 'bestchoice')
    {
        rank = '01';
        title = 'Danh hiệu BEST CHOICE';
        description = 'Best Choice là danh hiệu uy tín nhất trên 123Mua (hiện nay) được BQT 123Mua trao tặng cho các shop bán hàng chất lượng và nghiêm túc. Khách mua hàng tại các shop có danh hiệu Best Choice có thể yên tâm về giao dịch, dịch vụ chăm sóc khách hàng của shop. Xem chi tiết <a href="javascript:OpenWin(\''+ baseurl +'/content/faqs/index_bestchoice.htm\',605,590);">tại đây.</a>';
    }
    else if (shopType == 'verified')
    {
        rank = '02';
        title = 'Shop đã xác thực';
        description = 'Thông tin của shop trên 123Mua.vn đã được xác thực là đúng và có thật. 123Mua.vn sẽ hỗ trợ bạn xác minh trong trường hợp có tranh chấp cần sự can thiệp của pháp luật.';
    }
    else if (shopType == 'unverified')
    {
        rank = '03';
        title = 'Shop chưa xác thực';
        description = '123Mua.vn chưa nhận được giấy tờ xác minh thông tin người bán theo qui định và sẽ không đảm bảo thông tin các shop này.<br /><strong>Bạn là chủ shop này?</strong> Mau chóng gửi giấy tờ theo hướng dẫn để được chứng thực.';
    }
    else if (shopType == 'vip')
    {
        rank = '04';
        title = 'Sản phẩm Thương Hiệu';
        description = 'Sản phẩm thương hiệu của các tên tuổi hàng đầu ở Việt Nam và Thế Giới. Bạn có thể hoàn toàn yên tâm về chất lượng sản phẩm khi mua hàng.';
    }
    else if (shopType == 'vip1')
    {
        rank = '05';
        title = 'Shop VIP';
        description = 'Danh hiệu Shop VIP là ghi nhận của 123Mua.vn về những shop đầu tư bán hàng nghiêm túc. Đến với các shop VIP, người mua sẽ nhận thấy sự khác biệt từ nội dung mô tả đến hình ảnh sản phẩm cũng như phong cách chăm sóc khách hàng chuyên nghiệp, giúp bạn yên tâm hơn khi mua hàng.';
    }
    else if (shopType == 'vip2')
    {
        rank = '06';
        title = 'Shop VIP';
        description = 'Danh hiệu Shop VIP là ghi nhận của 123Mua.vn về những shop đầu tư bán hàng nghiêm túc. Đến với các shop VIP, người mua sẽ nhận thấy sự khác biệt từ nội dung mô tả đến hình ảnh sản phẩm cũng như phong cách chăm sóc khách hàng chuyên nghiệp, giúp bạn yên tâm hơn khi mua hàng.';
    }
    

    return '<div class="popup_outside">'+
    '<img src="'+ imgurl  +'/bubble-tail.gif" alt="" />'+
    '<div class="popup">'+
    '<p class="title_ranking'+ rank +'">'+ title +'</p>'+
    '<p>'+ description +'</p>'+
    '</div>'+
    '</div>';
}

function cmd_keyword()
{	
    var keyword = $('#keyword').val();

	keyword = keyword.replace(/  /g," ");
    keyword = keyword.replace(/ /g,"+");
    if(keyword == '' || keyword == 'Bạn tìm gì cho ngày hôm nay?')
    {
        $(this).myBoxy (Boxy,{
            type: 'alert',
            message: 'Bạn cần nhập từ khóa cần tìm kiếm.'
        });
        $('#keyword').focus();
        return false;
    }
    var search_url = baseurl + '/tim-kiem/' +keyword + '/';
    $('#frmSearch').attr('action', search_url);	
}

function cmd_search()
{	
    var keyword = $('#keyword').val();

	keyword = keyword.replace(/  /g," ");
    keyword = keyword.replace(/ /g,"+");
    if(keyword == '' || keyword == 'Bạn tìm gì cho ngày hôm nay?')
    {
        $(this).myBoxy (Boxy,{
            type: 'alert',
            message: 'Bạn cần nhập từ khóa cần tìm kiếm.'
        });
        $('#keyword').focus();
        return false;
    }
    var search_url = baseurl + '/tim-kiem/' +keyword + '/';
    $('#frmSearch').attr('action', search_url);	
}

function submitLogin()
{
	$('#loginHead').submit();
}

function loadMessage()
{	
	$('.jewel').show();
	var msg = '';

	$.get('/user/msgunread/', function(data){
		msg = data;	
	});

	if(msg >0) {
		$('div.jewel').addClass('jewelNew');
		$('.jewelToggler').html('<span class="jewelCount"><span id="jewelRequestCount">' + msg + '</span></span>');
	}	
}

$(function(){
    $('.bubbleInfo').each(function () {
        var distance = 10;
        var time = 250;
        var showDelay = 500;
		var hideDelay = 300;

        var showDelayTimer = null;
		var hideDelayTimer = null;

        var beingShown = false;
        var shown = false;
        var trigger = $('.trigger', this);        

        var shopType;
        if ($(this).hasClass('shop_vip'))
        {
            shopType = 'vip';
        }
        else if ($(this).hasClass('shop_vip1'))
        {
            shopType = 'vip1';
        }
        else if ($(this).hasClass('shop_vip2'))
        {
            shopType = 'vip2';
        }
        else if ($(this).hasClass('shop_bestchoice'))
        {
            shopType = 'bestchoice';
        }
        else if ($(this).hasClass('shop_verified'))
        {
            shopType = 'verified';
        }
        else if ($(this).hasClass('shop_unverified'))
        {
            shopType = 'unverified';
        }

		var info;

        $(trigger.get(0)).mouseover(function () {

			var badget = this;
            info = $(badget).next();

            if (!info.length)
            {
                $(badget).after(bubbleTemplate(shopType));
                info = $(badget).next();
				
				info.mouseover(function(){
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
				}).mouseout(function(){
					$(trigger).mouseout();
				});
				
            }

            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            if (beingShown || shown) {
                /*/ don't trigger the animation again */
                return;
            } else {
				if (showDelayTimer)
				{
					clearTimeout(showDelayTimer);
				}
				
				showDelayTimer = setTimeout(function() {
					/*/ reset position of info box */
					beingShown = true;

					info.css({
						top: 26,
						left: -115 + ($(badget).width() / 2),
						width: 230,
						display: 'block'
					}).animate({
						top: '-=' + distance + 'px',
						opacity: 1
					}, time, 'swing', function() {
						beingShown = false;
						shown = true;
					});
				}, showDelay);                
            }

            return false;
        }).mouseout(function () {
			if (showDelayTimer)
			{
				clearTimeout(showDelayTimer);
			}

            if (hideDelayTimer)
			{
				clearTimeout(hideDelayTimer);
			}
            hideDelayTimer = setTimeout(function () {
                hideDelayTimer = null;
                info.animate({
                    top: '-=' + distance + 'px',
                    opacity: 0
                }, time, 'swing', function () {
                    shown = false;
                    info.css('display', 'none');
                });

            }, hideDelay);

            return false;
        });
    });
});

var resizeAds = function (zone, width, height)
{
	$('#' + zone + ' iframe').attr('width', width).attr('height', height);
}

var removeAds = function (zone)
{
	$('#' + zone).remove();
}

function getlogininfo(ver) {
	if (ver == 2) {
		$.get(baseurl+"/ajax/getlogininfo?v="+ new Date().getTime(),
			{},
			function(data){
				var loginHtml = '';
				if (data){
					if (data.account_name != '') {
						ME_ID = data.me_id;
						ME_UNAME = data.account_name;
						$("#notify_box").show();
						loginHtml = data.account_name+'<a title="Thoát" class="log-off" href="/user/logout">Thoát</a>';						
					}
					else {
						$("#notify_box").hide();
						loginHtml = '<a class="log-in" rel="nofollow" href="javascript:void(0);" onclick="submitLogin();">Đăng nhập</a><a rel="nofollow" href="http://id.me.zing.vn/register?ref=/user/session?redirect=&amp;getsession=1" target="_blank">Đăng ký</a>';
						//autochecklogin();
					}
					var helpHtml = '<li class="end"><a rel="nofollow" href="javascript:OpenWin(\'/content/faqs/index.htm\',600,590);">Trợ giúp</a></li>';
					$('#_loginAlr').html(loginHtml);	
					if (data.account_name != '') {
						$('.nav-user').show();
						loadMessage();
					}
				// callback function if login success
						if(typeof window._fnCallbackAfterLogin == 'function') {
							_fnCallbackAfterLogin();
						}
				}
			},
		"json");				
	}
};

function autochecklogin()
{
	$.ajax({
		url: 'http://123mua.apps.zing.vn/',
		dataType: 'jsonp',		  
		success: function(data) {
			if(data.isLogined)
			{
				submitLogin();
			}
		}
	});
}

function trackPageActivity(type)
{
	var pathname = window.location.pathname;
	$.post(baseurl+"/ajax/tracking", {uri: pathname, refer: document.referrer, type:type, user_agent: navigator.userAgent}, function(data){});
}

/*Menu*/
jQuery().ready(function(){
	$('.menu-expand').click(function() {
		if ($('.subnav-content').is(":hidden")) {
			$('.subnav-content').show();
		}
		else {
			$('.subnav-content').hide();
		}
	});
	$('.close-menu').click(function() {
		$('.subnav-content').hide();
	});
	$("ul.menu-inside li").hover(function(){
    
        $(this).addClass("hover");
        $('ul:first',this).css('visibility', 'visible');
    
    }, function(){
    
        $(this).removeClass("hover");
        $('ul:first',this).css('visibility', 'hidden');
    
    });    
    $("ul.menu-inside li ul li:has(ul)").find("a:first").append(" ");
	$('.btn-close-banner').click(function(){
		$('.banner-top').hide("2000");
	});
});
/*Jewel*/
jQuery().ready(function(){
	$("a.closeAlert").click(function() {
		$(".ctnAlert").hide();
		return false;
	});
	$(".min-jewel").click(function() {
		$("a.jewelToggler").click();
		return false;
	});
	$("a.jewelToggler").toggle(function(){
		if ($("#newestmessages").html() == '') {
			$.get(baseurl + '/ajax/newestmessages',
				function(data) {
					$('#newestmessages').html(data);
				}
			);
		}
	  $(this).addClass("jewelActive"); 
		$(".jewelBox").css("display","block");
	  }, function () {
	$(this).removeClass("jewelActive"); 
		$(".jewelBox").css("display","none");
	});
});
/*AutoComplete*/
function lookup(inputString) {
	if(inputString.length == 0) {
		$('#suggestions').hide();
	} else {
		$.post("rpc.php", {queryString: ""+inputString+""}, function(data){
			if(data.length >0) {
				$('#suggestions').show();
				$('#autoSuggestionsList').html(data);
			}
		});
	}
} 
function fill(thisValue) {
	$('#inputString').val(thisValue);
	setTimeout("$('#suggestions').hide();", 200);
}
/*nav-user*/
$(document).ready(function(){
	$(".nav-user").hoverIntent({
		over: makeTall,
		timeout: 100,
		out: makeShort
	});
});

function makeTall(){$(this).parent().find(".dropbox-user").show();}
function makeShort(){$(this).parent().find(".dropbox-user").hide();}

(function ($) {  
	
	/* begin shuffle */
	$.fn.shuffle = function() {
		return this.each(function(){
			var items = $(this).children().clone(true);
			return (items.length) ? $(this).html($.shuffle(items)) : this;
		});
	}
	
	$.shuffle = function(arr) {		
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	}
	/* end shuffle */

	$.fn.simpleSpy = function (limit, interval) {
    limit = limit || 8;
    interval = interval || 8000;
    
    return this.each(function () {
        // 1. setup
            // capture a cache of all the list items
            // chomp the list down to limit li elements
        var $list = $(this),
            items = [], // uninitialised
            currentItem = limit,
            total = 0, // initialise later on
            height = $list.find('> li:first').height();
            
        // capture the cache
        $list.find('> li').each(function () {
            items.push('<li>' + $(this).html() + '</li>');
        });
        
        total = items.length;
        
        $list.wrap('<div class="spyWrapper" />').parent().css({ height : height * limit });
        
        $list.find('> li').filter(':gt(' + (limit - 1) + ')').remove();

        // 2. effect        
        function spy() {
            // insert a new item with opacity and height of zero
            var $insert = $(items[currentItem]).css({
                height : 0,
                opacity : 0.2,
                display : 'none'
            }).prependTo($list);
                        
            // fade the LAST item out
            $list.find('> li:last').animate({ opacity : 0}, 1000, function () {
                // increase the height of the NEW first item
                $insert.animate({ height : height }, 700).animate({ opacity : 1 }, 100);
                
                // AND at the same time - decrease the height of the LAST item
                // $(this).animate({ height : 0 }, 1000, function () {
                    // finally fade the first item in (and we can remove the last)
                    $(this).remove();
                // });
            });
            
            currentItem++;
            if (currentItem >= total) {
                currentItem = 0;
            }
            
            setTimeout(spy, interval);
        }
        
        spy();
    });
};
    
})(jQuery);

$.fn.extend({
    simpleSlider: function(options)
    {
        var options = $.extend({item:2}, options);

        return this.each(function()
        {

            var li = $('ul li', this);
            var count = li.length;


            if (count <= options.item)
            {
                $('.go-next, .go-prev', this).remove();
                return;
            }

            var nextBtn = $('.go-next', this);

            nextBtn.parent().attr('rel', -options.item);

            $('.go-next, .go-prev', this).click(function()
            {
                li.hide();
                var parent = $(this).parent();
                var index = parseInt($(this).parent().attr('rel'));

                if ($(this).hasClass('go-next')){
					index = (index == -1)? 0 : index + options.item;
					if (index >= count)
					{
						index = 0;
					}
					
                }
                else
                {
					index = index - options.item;
                    if (index < 0)
                    {
                        var mod = (count % options.item);
						index = (mod == 0)? count - options.item : count - mod;
                    }
                }
				
				for (var i=0;i<options.item;i++)
				{
					li.eq(index + i).fadeIn();
				}
				
				parent.attr('rel', index);				
                return false;
            });
        });
    }
});
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);
// scroll
(function(d){var b="1.4.1",e={exclude:[],excludeWithin:[],offset:0,direction:"top",scrollElement:null,scrollTarget:null,beforeScroll:null,afterScroll:null,easing:"swing",speed:400},g=f(location.pathname),a=function(j){var k=[],i=false,h=j.dir&&j.dir=="left"?"scrollLeft":"scrollTop";this.each(function(){if(this==document||this==window){return}var l=d(this);if(l[h]()>0){k.push(this);return}l[h](1);i=l[h]()>0;l[h](0);if(i){k.push(this);return}});if(j.el==="first"&&k.length){k=[k.shift()]}return k};d.fn.extend({scrollable:function(h){var i=a.call(this,{dir:h});return this.pushStack(i)},firstScrollable:function(h){var i=a.call(this,{el:"first",dir:h});return this.pushStack(i)},smoothScroll:function(h){h=h||{};var i=d.extend({},d.fn.smoothScroll.defaults,h);this.die("click.smoothscroll").live("click.smoothscroll",function(k){var t=this,s=d(this),p=((location.hostname===t.hostname)||!t.hostname),j=i.scrollTarget||(f(t.pathname)||g)===g,r=c(t.hash),l=true;if(!i.scrollTarget&&(!p||!j||!r)){l=false}else{var m=i.exclude,v=0,n=m.length;while(l&&v<n){if(s.is(c(m[v++]))){l=false}}var q=i.excludeWithin,o=0,u=q.length;while(l&&o<u){if(s.closest(q[o++]).length){l=false}}}if(l){i.scrollTarget=h.scrollTarget||r;i.link=t;k.preventDefault();d.smoothScroll(i)}});return this}});d.smoothScroll=function(p,m){var h,j,o,n=0,k="offset",l="scrollTop",i={};if(typeof p==="number"){h=d.fn.smoothScroll.defaults;o=p}else{h=d.extend({},d.fn.smoothScroll.defaults,p||{});if(h.scrollElement){k="position";if(h.scrollElement.css("position")=="static"){h.scrollElement.css("position","relative")}}o=m||(d(h.scrollTarget)[k]()&&d(h.scrollTarget)[k]()[h.direction])||0}h=d.extend({link:null},h);l=h.direction=="left"?"scrollLeft":l;if(h.scrollElement){j=h.scrollElement;n=j[l]()}else{j=d("html, body").firstScrollable()}i[l]=o+n+h.offset;if(d.isFunction(h.beforeScroll)){h.beforeScroll.call(j,h)}j.animate(i,{duration:h.speed,easing:h.easing,complete:function(){if(h.afterScroll&&d.isFunction(h.afterScroll)){h.afterScroll.call(h.link,h)}}})};d.smoothScroll.version=b;d.fn.smoothScroll.defaults=e;function f(h){return h.replace(/^\//,"").replace(/(index|default).[a-zA-Z]{3,4}$/,"").replace(/\/$/,"")}function c(h){return h.replace(/(:|\.)/g,"\\$1")}})(jQuery);

jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();

var movingWithinSite 	= false;  // this is the var that determines if the unload was caused by a user leaving, or navigating in the site.
var codeToExecute		= function() {};

function userMovingWithinSite() {
	movingWithinSite = true;
}

// Code to detect refreshing of the page through keyboard use
var ctrlKeyIsDown = false;
function interceptKeyUp(e) {
	if( !e ) {
		if (window.event)
			e = window.event;
		else 
			return;
	}
	
	keyCode = e.keyCode;	
	if (keyCode == 17){
		ctrlKeyIsDown = false;
	}
}

function interceptKeyDown(e) {
	if( !e ) {
		if (window.event)
			e = window.event;
		else
			return;
	}
	
	keyCode = e.keyCode;
	// F5 detected
	if ( keyCode == 116 ) {
		userMovingWithinSite();
	}
	
	if (keyCode == 17){
		ctrlKeyIsDown = true;
	}

	// then they are pressing Ctrl+R
	if (ctrlKeyIsDown && keyCode == 82){	
		userMovingWithinSite();
	}	
}

function interceptKeyPress(e) {
	if( !e ) {
		if (window.event)
			e = window.event;
		else
			return;
	}

	var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : void 0;
	if(e.charCode == null || e.charCode == 0 ) {
		// F5 pressed
		if ( keyCode == 116 ) {
			userMovingWithinSite();
		}
	}
}

function attachEventListener( obj, type, func, capture ) {
	if(window.addEventListener) {
		//Mozilla, Netscape, Firefox
		obj.addEventListener( type, func, capture );
	} else {
		//IE
		obj.attachEvent( 'on' + type, func );
	}
}

(function($){	
	$.fn.onUserExit = function(options) {		
		var defaults = {
			execute:			"",	 // no function assigned by default
			internalURLs:		""		// used to detect whether the url is internal or not (you can add subdomains to this list so when a user hops between sites, they are still considered to be internal.
		};
		var options 			= $.extend(defaults, options);
		
		if (options.execute == "") {
			//alert("The onUserExit jQuery Plugin has been misconfigured.  Please add the function you wish to execute.");
		}
		if (options.internalURLs == "") {
			//alert("The onUserExit jQuery Plugin has been misconfigured.  Please add internal URLs so it know when the user is navigating internally.");
		}
		codeToExecute = options.execute;
				
		// add onClick function to all internal links
		$("a").each(function() {
			var obj = $(this); 

			var linkIsInternal = false;
			
			var myInternalURLs = options.internalURLs.split("|");
			
			for (i = 0; i < myInternalURLs.length; i++) {
				if(obj.attr("href") != null)
				{
					if (obj.attr("href").indexOf(myInternalURLs[i]) !== -1) {
						linkIsInternal = true;
					}
					// if it's a relative or absolute URL, so it's internal.
					if (obj.attr("href").indexOf("http://") == -1) {
						linkIsInternal = true;
					}
				}
			}

			if (linkIsInternal == true) {				
				obj.bind("click", function(){
					userMovingWithinSite();
    			});
			}
		});

		$("form").each(function() {
			var obj = $(this);
			currentonSubmit = obj.attr("onSubmit");	
			if (currentonSubmit === undefined) {
				currentonSubmit = "";
			}
			obj.attr("onSubmit", currentonSubmit + " userMovingWithinSite();");
		});		

		// for Refresh Detection
		attachEventListener(document,"keydown",interceptKeyDown,true);
		attachEventListener(document,"keyup",interceptKeyUp,true);
		attachEventListener(document,"keypress",interceptKeyPress,true);	
		
	};
	
	$(window).unload(function() { 
		// unloading the page when the user is leaving
		if (movingWithinSite == false) {
			codeToExecute();
		}
	});
	
		
})(jQuery);
$(document).ready(function() {
	$().onUserExit({
		execute:	function()
		{
			trackPageActivity(999999);
		},
		internalURLs:	"123mua.vn|www.123mua.vn"
	});
});
