$().ready(function(){
    

    base_url = document.location.href.substring(0, document.location.href.indexOf('index.html'), 0);
	
    //$('#title').maxLength(150);
	
    $("#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,'+');

                if(type>0) p_type = "&type="+type;
                var action = "";
                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;
    });
    /*
	$('#formUpload').submit(function(){
		$('[id*=tip_]').html('');
	});
	*/
    $("input, select, textarea").focusin(function(){
        var id = $(this).attr('id');
        $('#error_' + id).hide();

        if(id == 'upload_pid') $('#error_upload_did').hide();
        else if(id == 'upload_cid') $('#error_upload_sub_cid').hide();
        else if(id == 'price' || id == 'mode_price') $('#error_option_price').hide();
		
        $('#tip_' + id).show();
    });
	
    $("input, select, textarea").focusout(function(){
        /*--Check price + mode price--*/
        var chkPrice = $('#price').val().replace(/\./g, '');
        var chkFalse = false;
        if(chkPrice.length > 0){
            var chkModePrice = $('#mode_price').val();
            if(chkModePrice == '0'){
                $('#error_option_price').show();
                chkFalse = false;
            }else{
                $('#error_option_price').hide();
                chkFalse = true;
            }
        }
    		
        var id = $(this).attr('id');
        $('#tip_' + id).hide();
    });

    
    $("#upload_cid").change(
        function()
        {
            var value = $.trim($(this).val());

            $.ajax({
                type: "GET",
                url: "process.php?act=category&pid="+value,
                beforeSend: function(req){
                },
                error: function(req, status, info){
                },
                complete: function(res){
                    $("#upload_sub_cid").html(res.responseText);
                    if(value == 31 || value == 29) {
                        var opt = '<option value="0">- - - Chọn - - -</option><option value="vnd">VNĐ</option><option value="vnd/m2">VNĐ / m2</option>';
                    }
                    else if(value == 30 || value == 28) {
                        var opt = '<option value="0">- - - Chọn - - -</option><option value="vnd/month">VNĐ / Tháng</option><option value="vnd/m2/month">VNĐ / m2 / Tháng</option>';
                    }
                    $('#mode_price').html(opt);
                }
            });

            return false;
        }
        );
            

    $("#upload_pid").change(function(){
        var value = $.trim($(this).val()) ;
        if(value>=0) {
            
            $.ajax({
                type: "GET",
                url: "process.php?act=upload-province&pid="+value,
                success: function(res){
                    $("#upload_did").html(res);
                }
            });
        /*if ($("#contactForm2").is(":hidden")){
//                $('#contactForm2').show();
//                if(typeof geocoder=="undefined"){
//                    loadMap();
//                }
//                showAddress($('#upload_pid option:selected').text()+', Vietnam');
//                $('#contactForm2').hide();
            }else{
                if(typeof geocoder=="undefined"){
                    loadMap();
                }
                showAddress($('#upload_pid option:selected').text()+', Vietnam');
            }*/
        }
        return false;
    }
    );
    $("input[id='street']").click(function(){
        if($(this).val()=="Đường phố"){
            $(this).val('');
            $("input[id='street_id']").val(''); 
        }
    });
    $("input[id='address']").click(function(){
        if($(this).val()=="Số nhà, ngõ ngách"){
            $(this).val('');
        }
    });
    $("input[id='street']").blur(function(){
        if($(this).val()==""){
            $(this).val('Đường phố');
            $("input[id='street_id']").val(''); 
        }
    });
    $("input[id='address']").blur(function(){
        if($(this).val()==""){
            $(this).val('Số nhà, ngõ ngách');
        }
    });
    $("#upload_did").change(function(){
        var value = $.trim($(this).val()) ;
        if($("input[id='street']").val()!="Đường phố"){
            $("input[id='street']").val('Đường phố');
            $("input[id='street_id']").val('');
        }
        if(value>=0)
        {
            $.ajax({
                type: "GET",
                url: "process.php?act=set-session-dist&did="+value,
                success: function(re){
                //alert(re);
                }
            });
			
        /*if ($("#contactForm2").is(":hidden")){
            //                    $('#contactForm2').css('opacity',0);
            //                    var mapWidth = $('#contactForm2').width();
            //                    var mapHeight = $('#contactForm2').height();
            //                    $('#contactForm2').width(0);
            //                    $('#contactForm2').height(0);
            //
            //                    $('#contactForm2').show();
            //                    if(typeof geocoder=="undefined"){
            //                        loadMap();
            //                    }
            //                    showAddress($('#upload_did option:selected').text()+ ', ' +$('#upload_pid option:selected').text()+', Vietnam');
            //                    $('#contactForm2').hide();
            //                    $('#contactForm2').width(mapWidth);
            //                    $('#contactForm2').height(mapHeight);
            //                    $('#contactForm2').css('opacity',1);
            }else{
                if(typeof geocoder=="undefined"){
                    loadMap();
                }
				if($('#upload_did option:selected').text()!='Khu vực khác' && $('#upload_did option:selected').text()!='- - - Quận/Huyện - - -'){
					showAddress($('#upload_did option:selected').text()+ ', ' +$('#upload_pid option:selected').text()+', Vietnam');
				}
                
            }*/
        }
        return false;
    }
    );
        
    $('#mode_price').change(function(){
        recommend_price();
    });
    
    /**
     *
     */
    $.validator.addMethod("validBoth", function(value, element,param) {
    	
        if($.trim($(param).val())<1){
            return false;
        }
        else
        {
            if(value<1) return false;
            else return true;
        }
    //return !this.optional(element) ;
    }, "Please select both the item and its amount.");

    /**
     * method price to check price of real estate
     * return boolean
     */
    $.validator.addMethod("price", function(value,element) {
        value = $.trim(value).replace(/\./g, '');
        var val = value.toLowerCase();
        
        if(val == "") {
            return true;
        }
        else {

            recommend_price();
            
            return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
        }

    }, 'Please enter "price"!');

    $.validator.addMethod("have_price", function(value, element) {
        var price = $('#price').val().replace(/\./g, '');

        if(price == '' || value != 0) {
            return true;
        }
        else return false;

    }, 'Please enter "mode price"!');

    $.validator.addMethod("floor_space", function(value, element) {
        var mode_price = $('#mode_price').val();

        if(value != 0) {
            return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
        }
        else if(mode_price != 'vnd/m2') {
            return true;
        }
        else return false;

    }, 'Please enter "floor space"!');
    
    /**
     * method price to check user phone
     * return boolean
     */
    $.validator.addMethod("phone", function(value,element) {
        value = $.trim(value);
        if(value.length>50) return false;
        else return this.optional(element) || /(\(?[+]?[0-9]{2}\))?([-]?[0-9]+)+$/.test(value);

    }, 'Please enter your phone!');

    /**
     * valid upload form
     */
    var container = $("#formUpload div.alert");
    $("#formUpload").validate(
    {
        invalidHandler: function(e, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = errors == 1
                ? '<img src="public/themes/rc/images/alert.gif"/> <font style="font-weight:bold;">Có tất cả ' + errors + ' lỗi xảy ra trong quá trình đăng tin</font>. <br/> '
                : '<img src="public/themes/rc/images/alert.gif"/> <font style="font-weight:bold;">Có tất cả ' + errors + ' lỗi xảy ra trong quá trình đăng tin</font>. <br/> ';
                $("li div.alert").html(message);
                $("li div.alert").show();
            //$("div.mark_warning").show();
            } else {
                $("form.formUpload li div.alert").hide();
            //$("div.mark_warning").hide();
            }
        },
        errorPlacement: function(error, element) {
        //$(element).focus();
        //error.appendTo($(element).parents("div.rowdangtin"));
        //error.appendTo( element.parent().next() );
        },
        highlight: function(element, errorClass) {
            var id = $(element).attr('name');
        	
            if(id == 'upload_pid') id = 'upload_did';
            else if(id == 'upload_cid') id = 'upload_sub_cid';
            else if(id == 'price' || id == 'mode_price') id = 'option_price';
        	
        	
            if(id=='title')
            {
                if($(element).val() != '')
                {
                    var img_src = $('#error_'+id).find('img').attr('src');
                    $('#error_'+id).find('span').html('<img src="'+img_src+'"> Tiêu đề tối đa 150 ký tự');        				
                }
            }
            $('#error_'+id).show();
        //$(element).addClass(errorClass).parent().prev().prev().children("select").addClass(errorClass);
        //$(element).parents("li").addClass("invalid");
        },
        unhighlight: function( element, errorClass, validClass ) {            
            var id = $(element).attr('id');
        	
            if(id == 'price' || id == 'mode_price') {
                var price = $('#price').val().replace(/\./g, '');
                var mode_price = $('#mode_price').val();

                if(price > 0 && mode_price != '0') id = 'option_price';
            } 

            $('#error_'+id).hide();        	
        //$(element).removeClass(errorClass).addClass(validClass);
        //$(element).parents("li").removeClass("invalid");
        },/*
		success: function(label) {
        	alert("co");return false;
        	var desc = CKEDITOR.instances.description.getData();
        	alert(desc);
        	desc = desc.replace(/(&nbsp;)/g," ");
        	CKEDITOR.instances.description.setData(desc, function()
		    {
                this.checkDirty();    // true
            });
		},*/
        submitHandler: function(form) 
        {
            $("#btnUpload").attr("disabled", true);
            form.submit();
        },
        onkeyup: false,
        //errorContainer: container,
        //errorLabelContainer: $("ul", container),
        //wrapper: 'li',
        rules: {
            title: {
                required:true,
                maxlength:150
            },
            upload_cid:
            {
                required:true,
                min:1
            },
            upload_sub_cid:
            {
                required:true,
                validBoth:'#upload_cid',
                min:1
            },
            upload_pid:
            {
                required:true,
                min:1
            },
            upload_did:
            {
                required:true,
                validBoth:'#upload_pid',
                min:1
            },
            floor_space:
            {
                required:true,
                floor_space: true
            },
            price:
            {
                //required:true,
                price:true                
            },
            mode_price:
            {
                //required:true,
                have_price:true
            },
            verify: {
                required:true
            },
            fullname:
            {
                required:true
            },
            phone:
            {
                required:true,
                phone:true
            },
            email:
            {
                required:true,
                email:true
            }
        },
        messages: {
            title:{
                required:"",
                maxlength: "Tiêu đề tối đa 150 kí tự"
            },
            upload_sub_cid:
            {
                required:" ",
                validBoth:" ",
                min:" "
            },
            upload_did:
            {
                required:"Bạn chưa chọn quận huyện",
                validBoth:' ',
                min:"Bạn chưa chọn quận huyện"
            },
            price:
            {
                price: "Giá tiền phải nhập bằng các chữ số"
            },
            unit_price:
            {
                required: "banj chua chon don vi"
            },
            verify:{
                required:"Bạn chưa nhập mã xác nhận"
            },
            fullname:
            {
                required:"Bạn chưa nhập Họ và Tên"
            },
            phone:
            {
                required:"Bạn chưa nhập số điện thoại",
                phone:"Số điện thoại không hợp lệ"
            },
            email:
            {
                required:"Bạn chưa nhập địa chỉ Email",
                email:"Email không chính xác - Ex: ten-email@domain.com"
            }
        }

    });
    
    /*CKEDITOR.instances.description.on('blur',function(){
    	alert(this);
    });*/
    /* upload preview*/
    $("#btnPreview").click(function()
    {    	
        /*CKEDITOR.instances.description.setData("co ca co la");
    	CKEDITOR.instances.description.updateElement();*/
        var content = CKEDITOR.instances.description.getData();
        //alert(content);
        
        $("#light.white_content .titlexemtruoc").html('Người đăng: <b>'+ $("#fullname").val() +'</b>  |  ĐT: <b>'+ $("#phone").val() +'</b>  |  Email: <font class="textblue"><a href="mailto:'+ $("#email").val() +'"><b>'+ $("#email").val() +'</b></a></font><br />	Chuyên mục: <b>'+ $("#upload_cid option:selected").text() +'</b>,  Loại hình: <b>'+ $("#upload_sub_cid option:selected").text() +'</b><br />Nơi đăng: <b>'+ $("#upload_did option:selected").text() +' - '+ $("#upload_pid option:selected").text() +'</b><br /><br />');
        $("#light.white_content .contentxemtruoc").html('Tiêu đề tin:<br /><font class="texttitle">'+ $("#title").val() +'</font><br /><br />'+ content +'');

        //show information
        $('#light').show();
        $('#fade').show();
        $('#iframeIE').show();

        //go to top page
        scroll(0,0);

        return false;
    });

    /* close upload preview*/
    $("#btnPreviewClose").click(function()
    {
        //hide information
        $('#light').hide();
        $('#fade').hide();
        $('#iframeIE').hide();
        return false;
    });

    $("#addImage").click(function(){
        //alert($("upload"));
        var index = $("#pIndex").val();
        fobj = document.getElementById("formUpload");
        regex = "upload";
        re = new RegExp(regex);
        Obj = 0;
        for(i = 0; i < fobj.elements.length; i++)
        {
            elm = fobj.elements[i];
            if (elm.type == 'file')
            {
                if (re.test(elm.name))
                {
                    var ext = $.trim(getExt(elm.value))+"";
                    //alert(ext);
                    if(ext==""){
                        alert("Bạn chưa chọn ảnh tải lên!");
                        return false;
                    }
                    if(ext=="jpg" || ext=="jpeg" || ext=="png" || ext=="gif")
                    {

                    }
                    else
                    {
                        alert("Bạn chỉ được chọn file có định dạng mở rộng là: *.jpg, *.png, *.gif");
                        return false;
                    }

                    Obj++;
                }
            }
        }

        if(Obj==5)
        {
            alert("Bạn chỉ được tải lên tối đa là 5 ảnh");
            return false;
        }
        else
        {
            $("#upload-image").append("<li id='li-upload-"+index+"'><input type='file' name='upload[]' id='upload-"+index+"' onChange='checkFile()' /><label id='lbl-upload-"+index+"'><a id='lbl-upload-"+index+"' href='#' onclick='deleteImage(\"lbl-upload-"+index+"\")'>xóa</a></label><br /></li>");
            index ++;
        }

        $("#pIndex").val(index);
        return false;
    });

    $(".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 url = 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){
                window.location.href = url;
            }
        });

    });

    $(".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){
                url = url.replace("#","");
                window.location.href = url;
            //document.frmIndex.action=url;
            //document.frmIndex.submit();
            }
        });
    });

    $(".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);

        $.tinysort.defaults.order = $(this).val();
        $("ul#announce>li").removeClass("end");
        $("ul#announce>li").tsort({
            attr:"abbr"
        });
        $("ul#announce>li:last").addClass("end");
    });

    $(".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;
    });
    
    /**
     * method price to check price of real estate
     * return boolean
     */
    $.validator.addMethod("numberWithDefault", function(value,element,param) {
        value = $.trim(value);
        var val = value.toLowerCase();
        
        if(val == $.trim(param)) {
            return true;
        }
        else {
			
            return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
        }

    }, 'Please enter Number !');
    
//    $("#formUserREQ").validate(
//    {
//        /*invalidHandler: function(e, validator) {
//            var errors = validator.numberOfInvalids();
//            if (errors) {
//                var message = errors == 1
//                ? '<img src="public/themes/rc/images/alert.gif"/> <font style="font-weight:bold;">Có tất cả ' + errors + ' lỗi xảy ra trong quá trình đăng tin</font>. <br/> '
//                : '<img src="public/themes/rc/images/alert.gif"/> <font style="font-weight:bold;">Có tất cả ' + errors + ' lỗi xảy ra trong quá trình đăng tin</font>. <br/> ';
//                $("li div.alert").html(message);
//                $("li div.alert").show();
//            //$("div.mark_warning").show();
//            } else {
//                $("form.formUserREQ li div.alert").hide();
//                //$("div.mark_warning").hide();
//            }
//        },*/
//        errorPlacement: function(error, element) {
//        	//$(element).focus();
//        	//error.appendTo($(element).parents("div.rowdangtin"));
//        	//error.appendTo( element.parent().next() );
//        },
//        highlight: function(element, errorClass) {
//        	var id = $(element).attr('name');
//        	        	
//        	/*if(id=='title')
//        	{
//        		if($(element).val() != '')
//        		{
//        			var img_src = $('#error_'+id).find('img').attr('src');
//        			$('#error_'+id).find('span').html('<img src="'+img_src+'"> Tiêu đề tối đa 150 ký tự');        				
//        		}
//        	}*/
//        	if(id == 'price_from' || id == 'price_to') id = 'price';
//        	else if(id == 'area_from' || id == 'area_to') id = 'area';
//        	else if(id == 'nfloor' || id == 'nroom') id = 'room';
//        	//alert(id);
//        	//$('#error_'+id).parent().parent().css("background", "#f2f2f2");
//        	$('#error_'+id).show();
//            //$(element).addClass(errorClass).parent().prev().prev().children("select").addClass(errorClass);
//            //$(element).parents("li").addClass("invalid");
//        },
//        unhighlight: function( element, errorClass, validClass ) {            
//        	var id = $(element).attr('name');
//        	
//        	/*if(id == 'price' || id == 'mode_price') {
//        		var price = $('#price').val();
//				var mode_price = $('#mode_price').val();
//
//				if(price > 0 && mode_price != '0') id = 'option_price';
//        	} */
//        	if(id == 'price_from' || id == 'price_to') id = 'price';
//        	else if(id == 'area_from' || id == 'area_to') id = 'area';
//        	else if(id == 'nfloor' || id == 'nroom') id = 'room';
//        	//alert(id);
//        	$('#error_'+id).hide();
//            //$(element).removeClass(errorClass).addClass(validClass);
//            //$(element).parents("li").removeClass("invalid");
//        },/*
//		success: function(label) {
//        	alert("co");return false;
//        	var desc = CKEDITOR.instances.description.getData();
//        	alert(desc);
//        	desc = desc.replace(/(&nbsp;)/g," ");
//        	CKEDITOR.instances.description.setData(desc, function()
//		    {
//                this.checkDirty();    // true
//            });
//		},*/
//        submitHandler: function(form) 
//        {
//        	$("#btnSendREQ").attr("disabled", true);
//        	form.submit();
//    	},
//        onkeyup: false,
//        //errorContainer: container,
//        //errorLabelContainer: $("ul", container),
//        //wrapper: 'li',
//        rules: {            
//    		txt_req_choice_did:
//            {
//                required:true
//            },
//            txt_req_choice_cid:
//            {
//            	required:true
//            },
//            price_from:
//            {
//            	numberWithDefault:'--- từ ---'
//            },
//            price_to:
//            {
//            	numberWithDefault:'--- đến ---'
//            },
//            area_from:
//            {
//            	numberWithDefault:'--- từ ---'
//            },
//            area_to:
//            {
//            	numberWithDefault:'--- đến ---'
//            },
//            nfloor:
//            {
//            	numberWithDefault:''
//            },
//            nroom:
//            {
//            	numberWithDefault:''
//            }
//        },
//        messages: {            
//        	txt_req_choice_did:
//            {
//                required:" "
//            },
//            txt_req_choice_cid:
//            {
//            	required:" "
//            }
//        }
//
//    });
    
});


function closeForm(){
    $("#messageSent").show("slow");
    setTimeout('$("#messageSent").hide();$("#contactForm").slideD("slow");$("#contactLink").slideUp("slow");', 2000);
}

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 baseURL + "/";
    }

}
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
}





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;
    }
}

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.fn.truncate = function(len)
{
    this.val(this.val().substring(0,len));
    return false;
}

jQuery.fn.maxLength = function(len)
{
    var maxLengthKeyPress = new Array();
    var maxLengthChange = new Array();
    var appleKeyOn = false;
  
    //the second argument should be true if len should be based on
    //the maxlength attribute instead of the input
    var useAttr = arguments.length>1 ? arguments[1] : false;
  
    var handleKeyUp = function(e)
    {
        //if the apple key (macs) is being pressed, set the indicator
        if(e.keyCode==224||e.keyCode==91)
            appleKeyOn = false;
    }
  
    var handleKeyDown = function(e)
    {
        //if the apple key (macs) is being released, turn off the indicator
        if(e.keyCode==224||e.keyCode==91)
            appleKeyOn = true;
    }
  
    var handleKeyPress = function(e)
    {   
        //if this keyCode does not increase the length of the textarea value,
        //just let it go
        if(appleKeyOn || (e.charCode==0&&e.keyCode!=13) || e.ctrlKey)
            return;

        //get the textarea element
        var textarea = $(this);
        //if the length should be based on the maxlength attribute instead of the
        //input, use that
        len = useAttr ? parseInt(textarea.attr('maxlength')) : len;
        //get the value of the textarea
        var val = textarea.val();
        //get the length of the current text selection
        var selected = Math.abs(textarea.attr('selectionStart') - textarea.attr('selectionEnd'));
        selected = isNaN(selected) ? 0 : selected;
        //if this is the maximum length
        if(val.length==len && selected<1)
            return false;
        else if(val.length>len && selected<(val.length-len))
            return textarea.truncate(len);
    };
  
    var handleChange = function(e)
    {
        //get the textarea element
        var textarea = $(this);
    
        //if the length should be based on the maxlength attribute instead of the
        //input, use that
        len = useAttr ? parseInt(textarea.attr('maxlength')) : len;
    
        //truncate the textarea to its proper length
        textarea.truncate(len);
    };
  
    //get the current keyup and change functions
    var removeKeyPress = maxLengthKeyPress[this.selector];
    var removeChange = maxLengthChange[this.selector];

    //remove the keyup and change functions from any matched elements in case
    //a maxlength was previously set and a new one is being set
    this.die('keypress', removeKeyPress);
    this.die('change', removeChange);
  
    if(len==0 && !useAttr)
        return;
  
    //set the keyup and change functions for this element set and all future
    //elements matching this selector
    this.live('keypress', handleKeyPress);
    this.live('change', handleChange);
    this.live('keydown', handleKeyDown);
    this.live('keyup', handleKeyUp);
  
    //save the current keyup and change functions so that they can be
    //remove later
    maxLengthKeyPress[this.selector] = handleKeyPress;
    maxLengthChange[this.selector] = handleChange;
  
    //trigger a keypress event so that the limit will be enforced
    this.keypress();
};

$(function()
{
    //limit the length of all textareas with the maxlength attribute
    //NOTE: setting maxlength on a textarea is NOT valid XHTML. this
    //was added for coders who want to code loosely--not me!
    $('textarea[maxlength]').maxLength(null, true);
});

/**
 * Remove vietnamese Accents
 * @param str
 * @return string str
 */
function ReVN(str) {  
    str= str.toLowerCase();  
    str= str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g,"a");  
    str= str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g,"e");  
    str= str.replace(/ì|í|ị|ỉ|ĩ/g,"i");  
    str= str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g,"o");  
    str= str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g,"u");  
    str= str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g,"y");  
    str= str.replace(/đ/g,"d");  
    str= str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g,"-"); 
    /* tìm và thay thế các kí tự đặc biệt trong chuỗi sang kí tự - */ 
    str= str.replace(/-+-/g,"-"); //thay thế 2- thành 1- 
    str= str.replace(/^\-+|\-+$/g,"");  
    //cắt bỏ ký tự - ở đầu và cuối chuỗi  
    return str;  
}   

function recommend_price(){
    // Limit price
    var price = parseInt($('#price').val().replace(/\./g, ''));   
    var mode  = $('#mode_price').val();
    var max   = 0;
    var min   = 0;

    if(mode != '0') {
        if(mode == 'vnd') {
            max = 100000000000;// 100 ty
            min = 20000000;// 20 trieu
        }
        else if(mode == 'vnd/m2') {
            max = 1000000000;// 1 ty
            min = 100000;// 100 nghin
        }
        else if(mode == 'vnd/month') {
            max = 500000000;// 500 trieu
            min = 100000;// 100 nghin
        }
        else if(mode == 'vnd/m2/month') {
            max = 2000000;// 2 trieu
            min = 10000;// 10 nghin
        }

        if(price > max) {
            $('#divAlertPriceMessage').html('<span style="color:#0F70C2"><img src="/public/themes/rc/images/icon_info.gif">Giá bất động sản của bạn quá cao, bạn nên kiểm tra lại!</span>');
            $('#liAlertPrice').show('fast');
            setTimeout("$('#liAlertPrice').hide('fast')",8000);
            return false;
        }else if(price <= min) {
            $('#divAlertPriceMessage').html('<span style="color:#0F70C2"><img src="/public/themes/rc/images/icon_info.gif">Giá bất động sản của bạn quá thấp, bạn nên kiểm tra lại!</span>');
            $('#liAlertPrice').show('fast');
            setTimeout("$('#liAlertPrice').hide('fast')",8000);
            return false;
        }else{
            $('#liAlertPrice').hide('fast');
        }
    }
}
function showPrice(){
    $("input[name=price]").val($("input[name=price]").val().replace(/[^0-9]/g, ''));
    $("#showPrice").html(addCommasToNumber($("input[name=price]").val().replace(/[^0-9]/g, '')));
    if($("input[name=price]").val()!=''){
        $("input[name=price]").val(addCommasToNumber($("input[name=price]").val()));
    }
}
function addCommasToNumber(numberStr){
    numberStr += '';
    x = numberStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}
