$().ready(function(){
	var uri =window.location.href;
	uri = uri.substr(0,uri.indexOf("#"));
	//alert(uri.indexOf("http://www.olo.vn/cam-nang"));
	if(uri.indexOf("http://www.olo.vn/cam-nang")>=0)
	{
		uri =window.location.href;
		qid = uri.substr(uri.indexOf("#")+1,uri.length - uri.indexOf("#"));
		//alert(qid);
		$(".answ").hide();
		$("#c_"+qid).show();
		
	}
	$("div[id*='ads_']").each(function() {
		
		$(this).cycle({
		    fx: 'fade',
		    timeout: $(this).attr('timeout'),
		    pause: 1,
		    speed: 1000,
		    random: 1
		 });
		 
        $(this).css({'float' : 'left', 'margin-top' : '5px'});
	});

    var q_id = 0;
    $(".question").click(function(){
        if(q_id > 0) {
        	$('#c_'+q_id).hide();
        }
        
        url = window.location.href;
        if(url.indexOf("#")>0)
    	{
    		url = url.substr(0,url.indexOf("#"));
    	}
        //url = url.replace("#","");
        window.location.href = url+"#"+$(this).attr("id");
        q_id = this.id;
    	$("#c_"+q_id).toggle();
    });

	$('.ads_class').click(function () {	
		var ads_id = $(this).attr('ads_id');
		var ads_href = $(this).attr('href');
		
		$.ajax({
			type: "POST",
			url: "process.php",
			data: "act=ads_click&ads_id=" + $(this).attr('ads_id'),
			success: function(msg) {
				window.location.href = ads_href;
			}
		});
		return false;
	});

	$(".province_change").change(function(){
	    var value = $.trim($(this).val()) ;
	    
	    if(value>=0) {
	        
	        $.ajax({
	            type: "GET",
	            url: "process.php?act=upload-province&pid="+value,
	            success: function(res){
	                $(".district_change").html(res);
	            }
	        });
	    }
	    return false;
	});
    /*window.onerror=function(msg, url, linenumber){
        var logerror='Error message: ' + msg + '. Url: ' + url + ' Line Number: ' + linenumber;
        alert(logerror);
        return true
    }
     */
	$('#home').click(function(){
		
		$.ajax({
            type: "GET",
            //url: "process.php?act=district&did="+id+"&url="+mod,
            url: "process.php?act=reset",
            /*data: {province_id:$.trim($("#pid option:selected").val())},*/
            beforeSend: function(req){
            //$("#cmt_loader").show();
            },
            error: function(req, status, info){
            //alert("CÃ³ lá»—i ");
            //alert(info);
            },
            complete: function(res, s){
                window.location.href = getBaseURL();
            }
        });
        return false;
	});
    //alert(Get_Cookie("GLOBAL_PROVINCE[url_friendly]"));
    $(".accordion h3:first").toggleClass("active");
    //$(".accordion .content:not(:first)").show();

    $(".accordion h3").click(function(){
        //$(this).next(".content").toggle("slow");

        if($(this).next(".content:first").is(":hidden"))
        {
            if(!$(this).hasClass("active"))
            {
                $(this).addClass("active");
            }
        }
        else
        {
            if($(this).hasClass("active"))
            {
                $(this).removeClass("active");
            }
        //alert("hien");

        }
        $(this).next(".content").toggle("slow");
    });

    $('li.hover').hover(
        function()
        {
            $(this).prev("li.hover").css({
                'border-bottom' : '1px #fff solid'
            });
            $(this).css({
                'border-top' : '1px #fdae2f solid',
                'border-bottom' : '1px #fdae2f solid'
            });
        },
        function()
        {
            $(this).prev("li.hover").css({
                'border-bottom' : '1px solid #D6D6D6'
            });
            $(this).css({
                'border-bottom' : '1px #d6d6d6 solid',
                'border-top' : '0'
            });
        }
    );

    base_url = document.location.href.substring(0, document.location.href.indexOf('index.html'), 0);

    
    $(".switch").click(function(){
        $(".hide").toggle();
        $(this).toggleClass("switch-off");
    });
    /*if(index_item!==undefined && index_item>0)
	{
		$(".hide-"+index_item).show();
		$("#show-"+index_item).hide();
		$("#hide-"+index_item).show();
	}*/
    /**
     * public function
     */
    /*$("#contactLink").click(function(){
		if ($("#contactForm").is(":hidden")){
			$("#contactForm").slideDown("slow");
		}
		else{
			$("#contactForm").slideUp("slow");
		}
	});*/
    /*$("#contactForm-close").click(function(){
		$("#contactForm").slideUp("slow");
	});
	$("#contactForm2-close").click(function(){
		$("#contactForm2").slideUp("slow");
	});
	$("#contactForm3-close").click(function(){
		$("#contactForm3").slideUp("slow");
	});
	$("#contactLink2").click(function(){
		if ($("#contactForm2").is(":hidden")){
			$("#contactForm2").slideDown("slow");
		}
		else{
			$("#contactForm2").slideUp("slow");
		}
	});

	$("#contactLink3").click(function(){
		if ($("#contactForm3").is(":hidden")){
			$("#contactForm3").slideDown("slow");
		}
		else{
			$("#contactForm3").slideUp("slow");
		}
	});*/

    $("#frmSearch").submit(function(){
        //alert($("#keyword").val());
        var key = $.trim($("#keyword").val());
        var type = $.trim($("#keyword").attr("abbr"));
        var p_type="";

        if(key.length>0)
        {
            if(key=="từ khóa ...")
            {
                alert("Bạn chưa nhập từ khóa!");
                return false;
            }
            else
            {
                var regex = /\s+/g;                                
                key = key.replace(regex,'+');
                //key = $.URLEncode(key);	
                
                if(type>0) p_type = "&type="+type;
                var action = getBaseURL()+"Tim-kiem?keyword="+key+p_type;
               //window.location.href=getBaseURL()+"Tim-kiem?keyword="+key+p_type;
                //alert(action);
                document.frmSearch.action=action;
                document.frmSearch.submit();
            }
        }
        else
        {
            alert("Bạn chưa nhập từ khóa!");
        }
        return false;
    });
    $("#btnSearchDetail").click(function(){
        var key = $.trim($("#search-detail").val());

        if(key.length>0)
        {
            if(key=="từ khóa ...")
            {
                alert("Bạn chưa nhập từ khóa!");
                return false;
            }
            else
            {
                var regex = /\s+/g;
                key = key.replace(regex,'+');

                var action = "";
                window.location.href=getBaseURL()+"Tim-kiem?keyword="+key;
            //alert(action);
            //document.frmSearch.action=action;
            //document.frmSearch.submit();
            }
        }
        else
        {
            alert("Bạn chưa nhập từ khóa!");
        }
        return false;
    });
    $(".province-choose").click(function(){

        var id = this.id;
        id = id.substring(16,id.length);

        $.ajax({
            type: "GET",
            url: "process.php?act=province&pid="+id,
            /*data: {province_id:$.trim($("#pid option:selected").val())},*/
            beforeSend: function(req){
            //$("#cmt_loader").show();
            },
            error: function(req, status, info){
            //alert("CÃ³ lá»—i ");
            //alert(info);
            },
            complete: function(res, s){
                //alert(res.responseText);
                //$("#did").html(res.responseText);
                //go back to current url
                //alert($('#hddCat').val());
                //var backUrl =  window.location.href;
                //backUrl = backUrl.replace(/#/,"");
                var cid =$.trim($('#hddCat').val());
                var curl = $.trim($('#hddCatUrl').val());
                var url = getBaseURL();
                if(cid>0)
                {
                    url = url+curl;
                }
                if((cid==0) && (curl!='tat-ca') && curl.length>0)
                {
                    url = url+curl;
                }
                if(curl=='tat-ca')
                {
                    url = url+"Muc-tin";
                }
                window.location.href = url;
            }
        });

    });

    /**
     * public function
     */
    $(".back-to-province").click(function(){
        var id = this.id;
        id = id.substring(17,id.length);
        $.ajax({
            type: "GET",
            url: "process.php?act=province&pid="+id,
            beforeSend: function(req){
            },
            error: function(req, status, info){
            },
            complete: function(res, s){
                var cid =$.trim($('#hddCat').val());
                var curl = $.trim($('#hddCatUrl').val());
                var url = getBaseURL();
                if(cid>0)
                {
                    url = url+curl;
                }
                if((cid==0) && (curl!='tat-ca') && curl.length>0)
                {
                    url = url+curl;
                }
                if(curl=='tat-ca')
                {
                    url = url+"Muc-tin";
                }
                window.location.href = url;
            }
        });
    });

    $(".district-choose").click(function(){
        //id obj
        var id = this.id;
        id = id.substring(16,id.length);

        //all parameters
        var mod = $("#hdCurrentUrl").val();
        var catParentUrl = $("#hddCatParentUrl").val();
        //alert(catParentUrl);
        $.ajax({
            type: "GET",
            //url: "process.php?act=district&did="+id+"&url="+mod,
            url: "process.php?act=district&did="+id+"&catParentUrl="+catParentUrl,
            /*data: {province_id:$.trim($("#pid option:selected").val())},*/
            beforeSend: function(req){
            //$("#cmt_loader").show();
            },
            error: function(req, status, info){
            //alert("CÃ³ lá»—i ");
            //alert(info);
            },
            complete: function(res, s){
                var cid =$.trim($('#hddCat').val());
                var curl = $.trim($('#hddCatUrl').val());
                //alert("this is getBaseUrl: " +getBaseURL());
                var url = getBaseURL();
                if(cid>0)
                {
                    url = url+curl;
                }
                if((cid==0) && (curl!='tat-ca') && curl.length>0)
                {
                    url = url+curl;
                }
                if(curl=='tat-ca')
                {
                    url = url+"Muc-tin";
                }
                //alert(curl);
                window.location.href = url;
            }
        });

    });

    /**
     * public function for choosing province in Project Area of Left Menu
     */
    $(".prj-province-choose").click(function(){
        var id = this.id;
        id = id.substring(20,id.length);
        $.ajax({
            type: "GET",
            url: "process.php?act=prjProvince&pid="+id,
            beforeSend: function(req){
            },
            error: function(req, status, info){
            },
            complete: function(res, s){
                var currentProjectUrl =$.trim($('#hddPrjUrl').val());
                var currentCatParentUrl =$.trim($('#hddCatParentUrl').val());
                var returnUrl = getBaseURL();
                returnUrl = returnUrl + "du-an_danh-sach_" + currentCatParentUrl ;
                window.location.href=returnUrl;
            }

        });

    });

    /**
     * public function for choosing province in District Area of Left Menu From  "du-an" page. Note this differ from the above function
     */
    $(".proj-province-choose").click(function(){
        var id = this.id;
        id = id.substring(21,id.length);
        $.ajax({
            type: "GET",
            url: "process.php?act=prjProvince&pid="+id,
            beforeSend: function(req){
            },
            error: function(req, status, info){
            },
            complete: function(res, s){
                var currentCatParentUrl =$.trim($('#hddCatParentUrl').val());
                var returnUrl = getBaseURL();
                returnUrl = returnUrl + "Muc-tin_" + currentCatParentUrl;

                window.location.href=returnUrl;
            }

        });

    });

    $(".project-choose").click(function(){
        var id = this.id;
        id = id.substring(15,id.length);
        $.ajax({
            type: "GET",
            url: "process.php?act=project&prjId="+id,
            beforeSend: function(req){
            },
            error: function(req, status, info){
            },
            complete: function(res, s){
            //var cid =$.trim($('#hddCat').val());
            //var curl = $.trim($('#hddCatUrl').val());
            //var url = "/";
            //if(cid>0)
            //{
            //  url = url+"chuyen-muc"+"_"+curl+"_"+cid;
            //}

            //window.location.href = url;
            }
        });

    });

    $(".prj-district-choose").click(function(){
        //id of district choose
        var id = this.id;
        id = id.substring(16,id.length);

        $.ajax({
            type: "GET",
            url: "process.php?act=district&did="+id,
            beforeSend: function(req){
            },
            error: function(req, status, info){
            },
            complete: function(res, s){
                var url = getBaseURL() + "Muc-tin";
                var currentCatParentUrl =$.trim($('#hddCatParentUrl').val());
                url = url + "_" + currentCatParentUrl;
                window.location.href = url;
            }
        });
    });
    $(".titleQuestion").click(function(){
        var id = this.id;
        id = id.substring(13,id.length);
        $('[class=boxreply]').each( function()
        {
            var boxReplyId = this.id;
            boxReplyId = boxReplyId.substring(8,boxReplyId.length);
            var boxId = '#boxreply'+boxReplyId;
            if (id == boxReplyId)
            {
                if ($(boxId).is(":hidden")){
                    $(boxId).slideDown("slow");
                }
                else{
                    $(boxId).slideUp("slow");
                }
            }
            else
            {
                $(boxId).slideUp("slow");
            //alert ("khác nhau rồi đấy thấy chưa");
            }
        });
    });

    $(".boxreply .textblue").click(function(){
        var id = this.id;
        id = id.substring(14,id.length);
        var boxId = '#boxreply'+ id;
        $(boxId).slideUp("slow");
    });
	/*
    $(".show-all").click(function(){
        var objID = this.id;
        index = objID.substring(5,objID.length);
        $(".hide-"+index+":gt(2)").show();
        $("#show-"+index).hide();
        $("#hide-"+index).show();
    });
    $(".hide-all").click(function(){
        var objID = this.id;
        index = objID.substring(5,objID.length);
        $(".hide-"+index+":gt(2)").hide();
        $("#show-"+index).show();
        $("#hide-"+index).hide();
    });
	*/
    $(".show-all").click(function(){
        var objID = this.id;
        index = objID.substring(5,objID.length);
        $(".hide-"+index).show();
        $("#show-"+index).hide();
        $("#hide-"+index).show();
    });
    $(".hide-all").click(function(){
        var objID = this.id;
        index = objID.substring(5,objID.length);
        $(".hide-"+index).hide();
        $("#show-"+index).show();
        $("#hide-"+index).hide();
    });

    $(".rows_per_page").click(function(){
        var row_id = this.id;
        var number_row = row_id.substr(5,row_id.length);
        var goUrl = window.location.href;
        //var mod = $("#hdModLink").val();
        $.ajax({
            type: "GET",
            //url: "process.php?act=district&did="+id+"&url="+mod,
            url: "process.php?act=rows_change&new="+number_row,
            /*data: {province_id:$.trim($("#pid option:selected").val())},*/
            beforeSend: function(req){
            //$("#cmt_loader").show();
            },
            error: function(req, status, info){
            //alert("CÃ³ lá»—i ");
            //alert(info);
            },
            complete: function(res, s){
            	if(goUrl.indexOf("#")>0)
            	{
            		goUrl = goUrl.substr(0,goUrl.indexOf("#"));
            	}
                window.location.href = goUrl;
            }
        });
        return false;
    });

    $(".display-type").click(function(){
        var type_id = this.id;
        var url = window.location.href;
        //alert(type_id);
        $.ajax({
            type: "GET",
            //url: "process.php?act=district&did="+id+"&url="+mod,
            url: "process.php?act=display_change&new="+type_id,
            /*data: {province_id:$.trim($("#pid option:selected").val())},*/
            beforeSend: function(req){
            //$("#cmt_loader").show();
            },
            error: function(req, status, info){
            //alert("CÃ³ lá»—i ");
            //alert(info);
            },
            complete: function(res, s){
            	if(url.indexOf("#")>0)
            	{
            		url = url.substr(0,url.indexOf("#"));
            	}
                //url = url.replace("#","");
                window.location.href = url;
                
            //document.frmIndex.action=url;


            //document.frmIndex.submit();
            }
        });
        return false;
    });

    $(".index-filter-province").click(function(){
        /*var url = window.location.href;
		 var id = this.id;

		 var vars = [];
		 var hashes = url.split('/');
		 if(hashes[hashes.length-1]=='')
		 {
			 hashes[hashes.length-1] = id;
		 }
		 else
		 {
			 var params = hashes[hashes.length-1].split("-");
			 var chr = params[0].substring(0,1).toLowerCase();
			 if(chr == "p")
			 {
				 params[0] = id;
				 hashes[hashes.length-1] = params.join("-");
			 }
			 else
			 {
				 hashes[hashes.length-1] = id+"-"+params.join("-");
			 }
		 }

		 url = hashes.join("/");
		 window.location.href = url;*/
        });

    $(".index-filter-project").click(function(){
        var url = window.location.href;
        var id = this.id;

        var vars = [];
        var hashes = url.split('/');
        if(hashes[hashes.length-1]=='')
        {
            hashes[hashes.length-1] = id;
        }
        else
        {
            var raw = hashes[hashes.length-1].toLowerCase();

            var params = hashes[hashes.length-1].split("-");
            var hash_param = [];

            if (raw.indexOf("p")!=-1)
            {
                hash_param[0] =  params[0];
                hash_param[1] =  id;

                if(raw.indexOf("j")!==-1)
                {
                    for(i=2;i<params.length;i++)
                    {
                        hash_param[i] = params[i];
                    }
                }
                else
                {
                    for(i=1;i<params.length;i++)
                    {
                        hash_param[i+1] = params[i];
                    }
                }

                hashes[hashes.length-1] = hash_param.join("-");
            }
            else
            {

                if(raw.indexOf("j")!==-1)
                {
                    //alert(raw);
                    params[0] = id;
                    hashes[hashes.length-1] = params.join("-");
                }
                else
                {
                    //alert("ko");
                    hashes[hashes.length-1] = id+"-"+params.join("-");
                }
            }
        }

        url = hashes.join("/");
        window.location.href = url;
    });

    $(".mn-opt-cat").click(function(){
        //alert(this.innerHTML);
        $(".mn-option").html(this.innerHTML);
        //$(".mn-option").removeClass(this.innerHTML);
        $("#keyword").attr("abbr",$(this).attr("abbr"));
        $("#contactForm").slideUp("slow");
    });

    $("#did-index-left").change(function(){
        var value = $.trim($(this).val()) ;
        if(value!="0")
        {
            window.location.href=getBaseURL()+value;
        }
    });

    $(".order-price").change(function(){
        //var id = this.id;
        //var type = id.substr(5,id.length);
    	var type = 	$(this).val();
        $.tinysort.defaults.order = type; 
        $("ul#announce>li").removeClass("end");
        $("ul#announce>li").tsort({
            attr:"abbr"
        });
        $("ul#announce>li:last").addClass("end");
        $.ajax({
            type: "GET",            
            url: "process.php?act=price-type&new="+type,
            /*data: {province_id:$.trim($("#pid option:selected").val())},*/
            beforeSend: function(req){
            //$("#cmt_loader").show();
            },
            error: function(req, status, info){
            //alert("CÃ³ lá»—i ");
            //alert(info);
            },
            complete: function(res, s){
                if(type == 'default') window.location.reload();

                //window.location.href = getBaseURL()+url;
            //
            //document.frmIndex.action=url;
            //document.frmIndex.submit();

            }
        });
    });

    $(".bcr_area").click(function(){
        var url = $(this).attr("abbr");//window.location.href;
        //url = url.substr(1,url.length);
        //alert($(this).attr("href"));
        //alert(getBaseURL());
        $.ajax({
            type: "GET",
            //url: "process.php?act=district&did="+id+"&url="+mod,
            url: "process.php?act=rm_area",
            /*data: {province_id:$.trim($("#pid option:selected").val())},*/
            beforeSend: function(req){
            //$("#cmt_loader").show();
            },
            error: function(req, status, info){
            //alert("CÃ³ lá»—i ");
            //alert(info);
            },
            complete: function(res, s){
                //alert(res.responseText);

                window.location.href = getBaseURL()+url;
            //
            //document.frmIndex.action=url;
            //document.frmIndex.submit();

            }
        });
        return false;
    });

    $(".bcr_path").click(function(){
        //var url = $(this).attr("abbr");//window.location.href;
        //url = url.substr(1,url.length);
        //alert($(this).attr("href"));
        //alert(getBaseURL());
        $.ajax({
            type: "GET",
            //url: "process.php?act=district&did="+id+"&url="+mod,
            url: "process.php?act=rm_category",
            /*data: {province_id:$.trim($("#pid option:selected").val())},*/
            beforeSend: function(req){
            //$("#cmt_loader").show();
            },
            error: function(req, status, info){
            //alert("CÃ³ lá»—i ");
            //alert(info);
            },
            complete: function(res, s){
                //alert(res.responseText);

                window.location.href = getBaseURL();
            //
            //document.frmIndex.action=url;
            //document.frmIndex.submit();

            }
        });
        return false;
    });


    $("#refresh-verify").click(function(){
        document.formUpload.captcha.src=getBaseURL()+"verify.php?ran=" + Math.random();
    });
    $("#user-refresh-verify").click(function(){
        document.formUserAuth.captcha.src=getBaseURL()+"verify.php?ran=" + Math.random();
    });
    
    saveAnnouncement();
    deletePostedAnnouncementMember();
    deletePostedAnnouncementMemberMulti();
    realDeletePostedAnnouncementMember();
    realDeletePostedAnnouncementMemberMulti();
    delMemberMailMulti();
    deleteReadingMail();
    delSavedAnnountmentByMember();
    delSavedAnnountmentByMemberMulti();
    $("#changePassword").click(function(){

        $("#mk1").toggle();
        $("#mk2").toggle();
        $("#mk3").toggle();
        $("#mkChangePassword").toggle();
    });
    $(".checkboxall").click(function(){
        var checked_status = this.checked;
        $("input[class=checkbox]").each(function(){
            this.checked = checked_status;
        });
    });


    /** upload **/
    $("ul.upload-files li a.delete").click(function()
    {
        //alert(this.id);
        imgs = Get_Cookie("uploadImage");

        var val = imgs.replace(this.id+";","");
        val = val.replace(";;",";");
        if(val=='')
        {
            Delete_Cookie("uploadImage");
        }
        else
        {
            Set_Cookie( "uploadImage", val, 1);
        }
        $(this).parents("li:first").remove();
    });
    
    $('#btnUserAuth').click(function()
    {
    	var code = $.trim($('#verify').val());
    	if(code!='')
    	{
    		
	    	$.ajax({
	            type: "GET",
	            //url: "process.php?act=district&did="+id+"&url="+mod,
	            url: getBaseURL()+ "get-ajax?type=auth&verify="+code,
	            /*data: {province_id:$.trim($("#pid option:selected").val())},*/
	            beforeSend: function(req){
	            //$("#cmt_loader").show();
	            },
	            error: function(req, status, info){
	            //alert("CÃ³ lá»—i ");
	            //alert(info);
	            },
	            complete: function(res, s){
	                var msg = res.responseText;
	                if(msg=='verify')
	                {	
	                	window.location.href = getBaseURL()+'up-tin_'+$.trim($('#verify').attr("abbr"));
	                }
	                else if(msg=='error')
	                {
	                	$('#verify').val('');
	                	$('#verify').focus();
	                	alert('Mã xác nhận không chính xác!');
	                	document.formUserAuth.captcha.src=getBaseURL()+"verify.php?ran=" + Math.random();
	                }
	            //
	            //document.frmIndex.action=url;
	            //document.frmIndex.submit();
	
	            }
	        });
    	}
    	else
    	{
    		$('#user_verify').focus();
    		alert('Bạn chưa nhập mã xác nhận !');    		
    	}
        return false;
    });
    
    /*function liftOff()
    {
	    $('#main-msg').remove();
	    $.ajax({
            type: "GET",
            //url: "process.php?act=district&did="+id+"&url="+mod,
            url: getBaseURL()+ "get-ajax?type=auth&remove=true",
            data: {province_id:$.trim($("#pid option:selected").val())},
            beforeSend: function(req){
            //$("#cmt_loader").show();
            },
            error: function(req, status, info){
            //alert("CÃ³ lá»—i ");
            //alert(info);
            },
            complete: function(res, s)
            {
				//res
            }
    	});
	    return false;
    } */
    
    $('.rmREQ').click(function(){
    	var val = $.trim($(this).attr("abbr"));
		var id = 'req_choice_did_'+ val;
		var old = $.trim($('#txt_req_choice_did').val());
		   		
		var nval = old.replace(val+';','');
		    		
		$('#txt_req_choice_did').val(nval);
		
		$('#'+id).remove();
		if(nval=='')
		{
			$("#reqDid").val(0);
		}
		return false;
	});
    
    $('#reqDid').change(function()
    {
    	var v= $.trim($("#reqDid option:selected").val());
    	var txt= $.trim($("#reqDid option:selected").text());
    	
    	if(v ==0)
    	{
    		//alert('Bạn chỉ được chọn tối đa 3 Quận/Huyện');
			return false;
    	}
    	var choice = $.trim($('#txt_req_choice_did').val());
    	if(choice !='')
    	{    		
    		var list = choice.split(';');
    		if(list.length > 3)
    		{
    			alert('Bạn chỉ được chọn tối đa 3 Quận/Huyện');
    			return false;
    		}
    		else
    		{   
    			var ok = true;
    			for(i=0;i<list.length;i++)
    			{
    				
    				list[i] = list[i].replace(';','');
    				if(list[i]==v)
    				{
    					ok = false;
    				}
    			}
    			if(ok)
    			{
    				$('#txt_req_choice_did').val(choice+v+';');
    			}
    			else
    			{
    				alert('Bạn đã chọn "'+txt+'" rồi !');
        			return false;
    			}
    		}
    	}
    	else
    	{    		
    		$('#txt_req_choice_did').val(v+';');
    	}
    	
    	$('#req_choice_did').append('<span id="req_choice_did_'+v+'">'+ txt +' <img title="xóa" class="rmREQ" abbr="'+v+'" src="'+getBaseURL()+'public/themes/rc/images/i-delete.gif" class="icon" style="cursor:pointer;"></span>');
    	
    	$('.rmREQ').click(function(){
    		var id = 'req_choice_did_'+$(this).attr("abbr");
    		var old = $('#txt_req_choice_did').val();
    		    		
    		old = old.replace($(this).attr("abbr")+';','');
    		    		
    		$('#txt_req_choice_did').val(old);
    		
    		$('#'+id).remove();
    		if(old=='')
    		{
    			$("#reqDid").val(0);
    		}
    	});
    	//alert(val);
    });
    
    /**
     * Add more request category
     */
    $('.rmCREQ').click(function(){
    	var val = $.trim($(this).attr("abbr"));
		var id = 'req_choice_cid_'+ val;
		var old = $.trim($('#txt_req_choice_cid').val());
		   		
		var nval = old.replace(val+';','');
		    		
		$('#txt_req_choice_cid').val(nval);
		
		$('#'+id).remove();
		
		if(nval=='')
		{
			$(".creq").val(0);
		}
		
		return false;
	});
    
    $('.creq').change(function()
    {
    	var v= $.trim($(".creq option:selected").val());
    	var txt= $.trim($(".creq option:selected").text());
    	
    	if(v ==0)
    	{    		
			return false;
    	}
    	var choice = $.trim($('#txt_req_choice_cid').val());
    	if(choice !='')
    	{    		
    		var list = choice.split(';');
    		if(list.length > 3)
    		{
    			alert('Bạn chỉ được chọn tối đa 3 chuyên mục');
    			return false;
    		}
    		else
    		{   
    			var ok = true;
    			for(i=0;i<list.length;i++)
    			{
    				
    				list[i] = list[i].replace(';','');
    				if(list[i]==v)
    				{
    					ok = false;
    				}
    			}
    			if(ok)
    			{
    				$('#txt_req_choice_cid').val(choice+v+';');
    			}
    			else
    			{
    				alert('Bạn đã chọn chuyên mục "'+txt+'" rồi !');
        			return false;
    			}
    		}
    	}
    	else
    	{    		
    		$('#txt_req_choice_cid').val(v+';');
    	}
    	
    	$('#req_choice_cid').append('<span id="req_choice_cid_'+v+'">'+ txt +' <img title="xóa" class="rmCREQ" abbr="'+v+'" src="'+getBaseURL()+'public/themes/rc/images/i-delete.gif" class="icon" style="cursor:pointer;"></span>');
    	
    	$('.rmCREQ').click(function(){
    		var id = 'req_choice_cid_'+$(this).attr("abbr");
    		var old = $('#txt_req_choice_cid').val();
    		    		
    		old = old.replace($(this).attr("abbr")+';','');
    		    		
    		$('#txt_req_choice_cid').val(old);
    		
    		$('#'+id).remove();
    		if(old=='')
    		{
    			$(".creq").val(0);
    		}
    	});
    	return false;
    });
});


function closeForm(){
    $("#messageSent").show("slow");
    setTimeout('$("#messageSent").hide();$("#contactForm").slideD("slow");$("#contactLink").slideUp("slow");', 2000);
}
/**
 * get current url and params
 * @param fname
 * @param act
 * @return
 */
$.extend({
    getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function(name){
        return $.getUrlVars()[name];
    }
});

function ChangeTextDefault(obj,string)
{
    var value = obj.value;
    value = value.toLowerCase();
    var strDefault = string.toLowerCase();
    
    if(value=='')
    {
        obj.value=string;//obj.style.color='#666666';
    //obj.style.fontStyle='italic';
    }
    else if(value==strDefault)
    {
    //obj.style.color='#666666';
    //obj.style.fontStyle='italic';
    }
    else
    {
//obj.style.color='#000000';
//obj.style.fontStyle='normal';
}
}

function ChangeTextFocus(obj,string)
{
    var value = obj.value;
    value = value.toLowerCase();
    var strDefault = string.toLowerCase();
    
    if(value==strDefault)
    {
        obj.value='';
    //obj.color='#000000';
    //obj.style.fontStyle='normal';
    }
}

function deleteImage(id)
{	
    var obj_id = id.substr(4,id.length);
    jQuery("#li-"+obj_id).remove();
    return false;
}
function getExt(file){
    return file.substr(file.indexOf(".")+1,file.length);
}
function getSize(filepath)
{
    var myFSO = new ActiveXObject("Scripting.FileSystemObject");
    //var filepath = document.upload.file.value;
    var thefile = myFSO.getFile(filepath);
    var size = thefile.size;
    alert(size + " bytes");
}
function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));
   

    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        //alert(pathname);
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return "/";
    }

}
function cleanWordFormat(c){
    c = c.replace(/<\!--[\s\S]*?-->/g, '');
    c = c.replace(/<o:p>\s*<\/o:p>/g, '');
    c = c.replace(/<o:p>[\s\S]*?<\/o:p>/g, '&nbsp;');
    c = c.replace(/\s*mso-[^:]+:[^;"]+;?/gi, '');
    c = c.replace(/\s*MARGIN: 0(?:cm|in) 0(?:cm|in) 0pt\s*;/gi, '');
    c = c.replace(/\s*MARGIN: 0(?:cm|in) 0(?:cm|in) 0pt\s*"/gi, '"');
    c = c.replace(/\s*TEXT-INDENT: 0cm\s*;/gi, '');
    c = c.replace(/\s*TEXT-INDENT: 0cm\s*"/gi, '"');
    c = c.replace(/\s*TEXT-ALIGN: [^\s;]+;?"/gi, '"');
    c = c.replace(/\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, '"');
    c = c.replace(/\s*FONT-VARIANT: [^\s;]+;?"/gi, '"');
    c = c.replace(/\s*tab-stops:[^;"]*;?/gi, '');
    c = c.replace(/\s*tab-stops:[^"]*/gi, '');
    
    //c = c.replace(/\s*face="[^"]*"/gi, '');
    //c = c.replace(/\s*face=[^ >]*/gi, '');
    //c = c.replace(/\s*FONT-FAMILY:[^;"]*;?/gi, '');
    
    c = c.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, '<$1$3');
    
    //c = c.replace(/<(\w[^>]*) style="([^\"]*)"([^>]*)/gi, '<$1$3');

    c = c.replace(/<STYLE[^>]*>[\s\S]*?<\/STYLE[^>]*>/gi, '');
    c = c.replace(/<(?:META|LINK)[^>]*>\s*/gi, '');
    c = c.replace(/\s*style="\s*"/gi, '');
    c = c.replace(/<SPAN\s*[^>]*>\s*&nbsp;\s*<\/SPAN>/gi, '&nbsp;');
    c = c.replace(/<SPAN\s*[^>]*><\/SPAN>/gi, '');
    c = c.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, '<$1$3');
    c = c.replace(/<SPAN\s*>([\s\S]*?)<\/SPAN>/gi, '$1');
    c = c.replace(/<FONT\s*>([\s\S]*?)<\/FONT>/gi, '$1');
    c = c.replace(/<\\?\?xml[^>]*>/gi, '');
    c = c.replace(/<w:[^>]*>[\s\S]*?<\/w:[^>]*>/gi, '');
    c = c.replace(/<\/?\w+:[^>]*>/gi, '');
    c = c.replace(/<(U|I|STRIKE)>&nbsp;<\/\1>/g, '&nbsp;');
    c = c.replace(/<H\d>\s*<\/H\d>/gi, '');
    c = c.replace(/<(\w+)[^>]*\sstyle="[^"]*DISPLAY\s?:\s?none[\s\S]*?<\/\1>/ig, '');
    c = c.replace(/<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, '<$1$3');
    c = c.replace(/<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, '<$1$3');
    c = c.replace(/<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, '<$1$3');

    c = c.replace(/<H1([^>]*)>/gi, '<div$1><b><font size="6">');
    c = c.replace(/<H2([^>]*)>/gi, '<div$1><b><font size="5">');
    c = c.replace(/<H3([^>]*)>/gi, '<div$1><b><font size="4">');
    c = c.replace(/<H4([^>]*)>/gi, '<div$1><b><font size="3">');
    c = c.replace(/<H5([^>]*)>/gi, '<div$1><b><font size="2">');
    c = c.replace(/<H6([^>]*)>/gi, '<div$1><b><font size="1">');
    c = c.replace(/<\/H\d>/gi, '</font></b></div>');
    var f = new RegExp('(<P)([^>]*>[\\s\\S]*?)(</P>)', 'gi');
    c = c.replace(f, '<div$2</div>');
    c = c.replace(/<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '');
    c = c.replace(/<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '');
    c = c.replace(/<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '');

    return c;
}

function loadMsg()
{
    //alert(window.location.href);
    var el=document.getElementById('loading');
    //el.style.display="none";
    $("#loading").hide();
}

// attach event after page loads
if( window.addEventListener ) {
    window.addEventListener('load',loadMsg,false); //legacy
} else if( document.addEventListener ) {
    document.addEventListener('load',loadMsg,false); //proper
} else if( window.attachEvent ) {
    window.attachEvent("onload", loadMsg); //IE only
}


//Quan Van Sinh
function strpos (haystack, needle, offset) {
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

function explode (delimiter, string, limit) {
    var emptyArray = {
        0: ''
    };
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||        typeof arguments[1] == 'undefined' ) {
        return null;
    }
    if ( delimiter === '' ||        delimiter === false ||
        delimiter === null ) {
        return false;
    }
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' ) {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function implode (glue, pieces) {
    var i = '', retVal='', tGlue='';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];                tGlue = glue;
            }
            return retVal;
        }
    }    else {
        return pieces;
    }
}

function deleteReadingMail(){
    $('.deleteReadingMail').click(function(){
        if(confirm('Bạn có chắc muốn xóa thư này?')){
            var link = this.lang;
            window.location = link;
        }
       
    });
}

function saveAnnouncement(){
	var base_url = getBaseURL();
	$('.luu').click(function(){
        var id = this.rev;
        $.ajax({
            type: "POST",
            url: "process.php",
            data: "act=saveAnnouncement&id="+id,
            success: function(msg){
                if($.trim(msg)!='ok'){
                    var cookieValues = Get_Cookie('saveAnnouncement');
                    if(cookieValues==null){
                        cookieValues = id;
                    }else{
                        if(strpos(cookieValues,id)==false){//neu' chua save'
                            cookieValues = cookieValues+','+id;
                        }
                    }
                    Set_Cookie('saveAnnouncement',cookieValues,30);
                    $("#re_mes").html('Click <a href="'+base_url+'tin-da-luu" style="padding:0;">vào đây</a> để xem các tin đã lưu.');
                }else{   
                $("#re_mes").html('Click <a href="'+base_url+'ca-nhan_tin-theo-doi" style="padding:0;">vào đây</a> để xem các tin đã lưu.');
            }
            }
        });
        $(this).addClass("daluu").removeClass("luu");
        $(this).attr("title","đã lưu");
        this.innerHTML = 'Đã lưu';
        var objImg = $(this).prev();
        $(objImg).attr('src','public/themes/rc/images/luuok.gif')
    });
}

function delSavedAnnountmentByMember(){
	$('.delSavedAnnountmentByMember').click(function(){
        var id = this.lang;
        if(id != ''){
            if(confirm("Bạn có chắc muốn xóa?")){
                $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: "act=delSavedAnnountmentByMember&id="+id,
                    success: function(msg){
                        if(msg=='ok'){
                            window.location.reload();
                        }
                    }
                });
            }
        }
    });
}

function delSavedAnnountmentByMemberMulti(){
    $('.delSavedAnnountmentByMemberMulti').click(function(){
        var aIdArray = [];
        $("#ul_member_dang_tin").find( "input[type=checkbox][checked]" ).each( function(){
            aIdArray.push($(this).val());
        });
        var strAId = implode(',',aIdArray);
        if(strAId != ''){
            if(confirm("Bạn có chắc muốn xóa mục đã chọn?")){
                $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: "act=delSavedAnnountmentByMemberMulti&strAId="+strAId,
                    success: function(msg){
                        if(msg=='ok'){
                            window.location.reload();
                        }
                    }
                });
            }
        }
    });
}

function deletePostedAnnouncementMember(){
    delSavedAnnountmentByMember
    $('.delAnnountmentByMember').click(function(){
        var id = this.lang;
        if(id != ''){
            if(confirm("Bạn có chắc muốn xóa?")){
                $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: "act=deletePostedAnnouncementMember&id="+id,
                    success: function(msg){
                        if(msg=='ok'){
                            window.location.reload();
                        }
                    }
                });
            }
        }
    });
}

function deletePostedAnnouncementMemberMulti(){
    $('.delAnnountmentByMemberMulti').click(function(){
        var aIdArray = [];
        $("#ul_member_dang_tin").find( "input[type=checkbox][checked]" ).each( function(){
            aIdArray.push($(this).val());
        });
        var strAId = implode(',',aIdArray);
        if(strAId != ''){
            if(confirm("Bạn có chắc muốn xóa mục đã chọn?")){
                $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: "act=deletePostedAnnouncementMemberMulti&strAId="+strAId,
                    success: function(msg){
                        if(msg=='ok'){
                            window.location.reload();
                        }
                    }
                });
            }
        }
    });
}
function realDeletePostedAnnouncementMember(){
    $('.realDelAnnountmentByMember').click(function(){
        var id = this.lang;
        if(id != ''){
            if(confirm("Bạn có chắc muốn xóa?")){
                $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: "act=realDeletePostedAnnouncementMember&id="+id,
                    success: function(msg){
                        if($.trim(msg)=='ok'){
                            window.location.reload();
                        }
                    }
                });
            }
        }
    });
    $('.recoverFromAnnouncementDeleted').click(function(){
        var id = this.lang;
        if(id != ''){
            $.ajax({
                type: "POST",
                url: "process.php",
                data: "act=recoverFromAnnouncementDeleted&id="+id,
                success: function(msg){
                    if($.trim(msg)=='ok'){
                        window.location.reload();
                    }
                }
            });
        }
    });
    
}

function realDeletePostedAnnouncementMemberMulti(){
    $('.realDelAnnountmentByMemberMulti').click(function(){
        var aIdArray = [];
        $("#ul_member_dang_tin").find( "input[type=checkbox][checked]" ).each( function(){
            aIdArray.push($(this).val());
        });
        var strAId = implode(',',aIdArray);
        if(strAId != ''){
            if(confirm("Bạn có chắc muốn xóa mục đã chọn?")){
                $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: "act=realDeletePostedAnnouncementMemberMulti&strAId="+strAId,
                    success: function(msg){
                        if(msg=='ok'){
                            window.location.reload();
                        }
                    }
                });
            }
        }
        
    });
}

function delMemberMailMulti(){
    $('.delMemberMail').click(function(){
        
        var mIdArray = [];
        $("#ul_member_mail_list").find( "input[type=checkbox][checked]" ).each( function(){
            mIdArray.push($(this).val());
        });
        var strMId = implode(',',mIdArray);
        var actionType = this.lang;
        if(strMId != ''){
            if(confirm("Bạn có chắc muốn xóa mục đã chọn?")){
                $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: "act=" + actionType + "&strMId=" + strMId,
                    success: function(msg){
                        if(msg=='ok'){
                            window.location.reload();
                        }
                    }
                });
            }
        }
    });
}

/*
Script Name: Javascript Cookie Script
Author: Public Domain, with some modifications
Script Source URI: http://techpatterns.com/downloads/javascript_cookies.php
Version 1.1.2
Last Update: 5 November 2009

Changes:
1.1.2 explicitly declares i in Get_Cookie with var
1.1.1 fixes a problem with Get_Cookie that did not correctly handle case
where cookie is initialized but it has no "=" and thus no value, the 
Get_Cookie function generates a NULL exception. This was pointed out by olivier, thanks
1.1.0 fixes a problem with Get_Cookie that did not correctly handle
cases where multiple cookies might test as the same, like: site1, site
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
*/

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );

// To use, simple do: Get_Cookie('cookie_name'); 
// replace cookie_name with the real cookie name, '' are required
function Get_Cookie( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    var i = '';
	
    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );
    // if the expires variable is set, make the correct expires time, the
    // current script below will set it for x number of days, to make it
    // for hours, delete * 24, for minutes, delete * 60 * 24
    if ( expires )
    {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    //alert( 'today ' + today.toGMTString() );// this is for testing purpose only
    var expires_date = new Date( today.getTime() + (expires) );
    //alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
    if ( Get_Cookie( name ) ) document.cookie = name + "=" +
        ( ( path ) ? ";path=" + path : "") +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// Jquery Until
(function($){$.each({nextUntil:"nextAll",prevUntil:"prevAll",parentsUntil:"parents"},function(a,b){$.fn[a]=function(e,f){var c=$([]),d=this.get();if(a.indexOf("p")===0&&d.length>1){d=d.reverse()}$.each(d,function(){$(this)[b]().each(function(){var g=$(this);if(g.is(e)){return false}else{if(!f||g.is(f)){c=c.add(this)}}})});return this.pushStack(c,a,e+(f?","+f:""))}})})(jQuery);

function explode (delimiter, string, limit) { 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' ) {
        return null;
    }
 
    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null ) {
        return false;
    }
 
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' ) {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function get_province_id(what)
{
	var current_province = explode('-', $(what).attr('abbr'));
	if(current_province == null) return false;
	else return current_province[1];
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}



//announce index

$(document).ready(function (){
/*$(".lightbox-2").lightbox({
                fitToScreen: true
            });

            $("#slider2").easySlider({
                auto: false,
                continuous: true
            });*/
$('#detailContact').click(function(){
    $('#captcha').attr('src',$('#captcha').attr('src')+'?ran='+Math.random());

});

$('#submitBad').click(function(){
    $('#badAlert').hide();

    var id = $('#reportBad').attr('rev');
    var content = $('#contentBad').val();
    $.ajax({
        type: "POST",
        url: "process.php",
        data: "act=reportBad&id="+id+"&content="+content,
        success: function(){
            $('#badAlert').show();
            $('#badAlertContent').html("Cám ơn bạn đã thông báo!");
            $('#badAlertContent').css('color','green');
            $('#reportBadImg').remove();
            $('#reportBad').remove();
            
        }
    });
});

$('#submitContact').click(function(){
    $('#contactAlert').hide();
    var email = $('#emailContact').val();
    var to = $('#to').val();
    var subject = $('#subjectContact').val();
    var content = $('#contentContact').val();
    var verify = $('#verify').val();
    var aTitle = $('#aTitle').html();
    var aLink = $('#aLink').val();
    if(email=='' || email==' '){
        $('#contactAlert').show();
        setTimeout("close('contactAlert')",10000);
        $('#contactAlertContent').html("Bạn chưa nhập email!");
        $('#contactAlertContent').css('color','red');
        $('#emailContact').focus();
        return false;
    }
    if(!isValidEmail(email)){
        $('#contactAlert').show();
        setTimeout("close('contactAlert')",10000);
        $('#contactAlertContent').html("Bạn nhập email không đúng!");
        $('#contactAlertContent').css('color','red');
        $('#emailContact').focus();
        return false;
    }
    if(subject=='' || subject==' '){
        $('#contactAlert').show();
        setTimeout("close('contactAlert')",10000);
        $('#contactAlertContent').html("Bạn chưa nhập tiêu đề!");
        $('#contactAlertContent').css('color','red');
    }
    if(content=='' || content==' '){
        $('#contactAlert').show();
        setTimeout("close('contactAlert')",10000);
        $('#contactAlertContent').html("Bạn chưa nhập nội dung!");
        $('#contactAlertContent').css('color','red');
        $('#contentContact').focus();
        return false;
    }
    if(verify=='' || verify==' '){
        $('#contactAlert').show();
        setTimeout("close('contactAlert')",10000);
        $('#contactAlertContent').html("Bạn chưa nhập mã bảo mật!");
        $('#contactAlertContent').css('color','red');
        $('#verify').focus();
        return false;
    }
    $.ajax({
        type: "POST",
        url: "process.php",
        data: "act=detailContact&email="+email+'&subject='+subject+'&content='+content+'&verify='+verify+'&to='+to+'&aTitle='+aTitle+'&aLink='+aLink,
        beforeSend: function(req){
            $('#submitContact').attr('src',"public/themes/rc/images/loading.gif");
            $('#submitContact').attr('disabled',true);
            $('#submitContact').css('cursor','default');
        },
        success: function(msg){
        	if($.trim(msg)=="erroremail"){
            	$('#contactAlert').show();
                setTimeout("close('contactAlert')",10000);
                $('#contactAlertContent').html("Email của thành viên bạn phải đăng nhập để xác thực.");
                $('#contactAlertContent').css('color','red');
                $('#emailContact').focus();
                return;
            }
            $('#submitContact').attr('src',"public/themes/rc/images/guidi.gif");
            $('#submitContact').attr('disabled',false);
            $('#submitContact').css('cursor','pointer');
            if(msg=='verify_die'){
                $('#contactAlert').show();
                setTimeout("close('contactAlert')",10000);
                $('#contactAlertContent').html("Bạn nhập mã bảo mật không đúng!");
                $('#contactAlertContent').css('color','red');
                $('#verify').val('');
                $('#captcha').attr('src',$('#captcha').attr('src')+'?ran='+Math.random());
                $('#verify').focus();
                return false;
            }else{
                //$('#TB_closeWindowButton').click();
                $('#contactAlert').show();
                //setTimeout("close('contactAlert')",20000);
                $('#contactAlertContent').html("Gửi tin liên hệ thành công!");
                $('#contactAlertContent').css('color','green');
                
                $('#subjectContact').val('');
                $('#contentContact').val('');
                $('#verify').val('');
                
                $('#captcha').attr('src',$('#captcha').attr('src')+'?ran='+Math.random());
            }

        }
    });
});
});
function contactAlert(){
alert('Người đăng tin này chưa hoạt động trên olO.vn');
}
function close(id){
$('#'+id).hide('slow');
};
function isValidEmail(str) {
return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
	output += match[1];
  x += match[1].length;
} else {
  if (clearString[x] == ' ')
    output += '+';
  else {
    var charCode = clearString.charCodeAt(x);
    var hexVal = charCode.toString(16);
    output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}
function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

/*
 * Single select checkbox in group
 */

function CheckOIG(regex,current)
{
	re = new RegExp(regex);
	var is_check = current.checked;
	for(i = 0; i < document.formUserREQ.elements.length; i++) {
	
		elm = document.formUserREQ.elements[i];
		//alert(elm.type);
		if (elm.type == 'checkbox') {
			//alert(elm.name);
		
			if (elm.name==current.name) 
			{			
				elm.checked = false;
			}
		}
	}
	//alert(current.name);
	
	if(is_check) current.checked = true;
	else current.checked = false;
	return false;
}


