var cd_rem = 0;
json_msgs = json_msgs_all; //alert(json_msgs.watchlist[4].cannot_modify);

// ------------------------------------------------------------------------

function toggle_photos()
{
	$("#auction_images").toggle();
	$("#auction_images_close_btn").toggle();
}

// ------------------------------------------------------------------------

function countdown()
{
	if (cd_rem > 0)
	{
		cd_rem--;
		var s = cd_rem % 60;
		var m = (cd_rem - s) / 60;

		var ts = s+'s';
		if (s < 10) ts = '0'+ts;
		if (m > 0) ts = m+'m '+ts;
		$('.countdown').text(ts);

		setTimeout("countdown()",1000);
	}
	else
	{
		$('.countdown').text('ENDED');
	}
}

function init_maps()
{
	geocoder = new google.maps.Geocoder();

	var latlng = new google.maps.LatLng(lat, lng);

	var opts = {
		zoom: 12,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas1"), opts);

	var marker = create_marker(latlng, 'test');
	marker.setMap(map);

	map2 = new google.maps.Map(document.getElementById("map_canvas2"), opts);
	marker = create_marker(latlng, "test");
	marker.setMap(map2);


}

function show_map()
{
	if (!map) init_maps();
	$("#map_container").show();
	// $(".property-image-container").hide();
	$(".auction-information-section .property-image-container.desktop-view").addClass("hideSlider");
	$("#google-address-button").show();
	if (!map2) init_maps();
	$("#map_container2").show();
	$(".property-image-container.mobile-view").hide();
	$("#google-address-button2").show();
	screen.width > 780 ? $('.mobile-view').hide() : $('.desktop-view').hide();
	return false;
}

function hide_map()
{
	var desktopMainSlider = document.querySelectorAll(
            ".property-image-container.desktop-view"
          );
	$("#map_container").hide();
	// $(".property-image-container").show();
	$(".auction-information-section .property-image-container.desktop-view").removeClass("hideSlider");
	$("#map_container2").hide();
	$(".property-image-container.mobile-view").show();
	screen.width > 780 ? $('.mobile-view').hide() : $('.desktop-view').hide();
	return false;
}


function toggle_map()
{
	if ($("#map_container:hidden").length) {
            show_map();
	} else if ($('#map_container2:hidden').length){
            show_map();
	} else {
            hide_map();
	}
	return false;
}


function create_marker(point, description)
{
	var marker = new google.maps.Marker({ title: description, position: point });
	google.maps.event.addDomListener(marker, 'click', function() {
		marker.openInfoWindowHtml(description);
	});
	return marker;
}

function extract_float(val, currency)
{
	switch (currency)
	{
		case 'AED':
		case 'EUR':
		case 'TRY':
			val = val.replace(/[\.]/g, '');
			val = val.replace(',', '.');
			break;
		default:
			//
	}

	return parseFloat(val.replace(/[^0-9\.]/g,''));
}

function init_map_button()
{
	$('#map_btn').unbind();
	$("#map_btn").bind('click', function(){
		return toggle_map();
	});
	$('#map_btn2').unbind();
	$("#map_btn2").bind('click', function () {
		return toggle_map();
	});
	$('#map_btn3').unbind();
	$("#map_btn3").bind('click', function () {
		return toggle_map();
	});
	$('#map_btn4').unbind();
	$("#map_btn4").bind('click', function () {
		return toggle_map();
	});
}

function init_form_tender_offer()
{
        var bidAjaxStatus = false;        
	$('#form_tender_offer').validate({
		rules: {
                    bid_amt:{
                        required: true,
                        number: ($('#is_reit_asset').val() == 0),
                        min : function() {
                            return $('#compare_min_bid').val();
                        }
                    },
                    tc: "required",
                    due_diligence_period: {
                        required: true,
                        number: true,
                        min:0
                    },
                    closing_period: {
                        required: true,
                        number:true,
                        min:0
                    },
                    primary_source_of_funds: "required",
                    percentage_financed: "required",
                    financing_contingency: "required"
		},
                messages: {                
                    bid_amt: {
                       min: function() {
                            return $('#min_bid_compare_error').html();
                       },
                       number : "Please enter a valid amount"
                   }
                },
		errorPlacement: function(error, element) {
			if (element.attr('name') == 'bid_amt')
			{
                            $('#min_bid_error').html( error );                            
			} else if(element.attr('name') == 'tc'){
                            $('#error-agree-tc').html( error );	
			} else if (element.attr('name') == 'due_diligence_period') {
                            $('#error-due-diligence').html( error );	
                        } else if (element.attr('name') == 'closing_period') {
                            $('#error-closing-period').html( error );	
                        } else if(element.attr('name') == 'financing_contingency'){
                            $('#error-financing-contingency').html( error );	
			} else if(element.attr('name') == 'percentage_financed'){
                            $('#error-percentage-financed').html( error );	
			} else {
                            element.before( error );
			}
		},
		submitHandler: function(form) {
                    var auction_type_id = $('#profile_auction_type_id').val(); //aucttype 14 = lease
                    if(auction_type_id != 14) {
                        $('#calculate_transaction_fee_btn').trigger('click');
                    }
                    var aURL = base_url + 'bidding/place_tender_bid';
                    // form = $("#form_tender_offer");
                    var formData = new FormData($('#form_tender_offer')[0]);
                    $("#spinwheel1").attr("style", "visibility: visible");
                    if ($('#hid_confirm').val() != 1) {
                        show_confirm_div();
                        return false;
                    }
                    $("#spinwheel1").attr("style", "visibility: hidden");
                    $("#spinwheel").attr("style", "visibility: visible");
                                    
                    if(!bidAjaxStatus){
                        bidAjaxStatus = true;
                        $.ajax({
                            type: "POST",
                            url: aURL,
                            //data: $("#form_tender_offer").serialize(), 
                            data: formData, 
                            mimeType: "multipart/form-data",
                            contentType: false,
                            cache: false,
                            processData: false,                 
                            success: function(data) {
                                bidAjaxStatus = false;
                                data = jQuery.parseJSON(data);
                                if (data.status === 1 || data.status === 100) {
                                    handleTenderAjaxSuccess(data);
                                } else {
                                    hide_confirm_div();
                                    if (data.status === 1000) { //File upload related
                                        $('#uploaded_files').html('');
                                        $('#err_file_upload').html(data.error.message);
                                    } else {
                                        var content = '<label for="bid_amt" generated="true" class="error minBidErrorText" style="display:inline-block;padding:0 .5em .5em .75em;width:48%;">'+data.error.message+'</label>';
                                        $('#bid_amt').after(content);
                                    }
                                    $("#spinwheel").attr("style", "visibility: hidden");
                                    $('#div_submit').attr('style', 'visibility: visible');
                                    $('#div_confirm').hide();  
                                    $('#hid_confirm').val(0);
                                }
                            }
                        });
                    }                    
		}				
	});
        
        $('#form_tender_offer input,#form_tender_offer checkbox,#form_tender_offer select').on('change',function(){
            $('#form_tender_offer').valid();
        })
}

function init_bid_form()
{    
	if ($('input[name=dt]').length)
	{
		$('input[name=dt]').rules("add", {
			required: true
		});
	}

        var bidConfirmAjaxStatus = false;
	$('#form_bid').validate({
		rules: {
                    amt: {
                        required: true,
                        number: ($('#is_reit_asset').val() == 0),
                        min : $('#compare_min_bid').val()
                    },
                    tc: "required"
		},
                messages:{
                    amt:{                        
                        number : "Please enter a valid amount",
                        min: $('#min_bid_compare_error').html()
                    }
                },
		errorPlacement: function(error, element) {                    
                    if (element.attr('name') == 'amt')
                    {
                        $('#min_bid_error').html( error );
                    } else if(element.attr('name') == 'tc'){
                        $('#error-agree-tc').html( error );	
                    }
                    else
                    {
                        $('#min_bid_error').html( error );
                    }
		},
		submitHandler: function(form) {     
                    
                    var auction_type_id = $('#profile_auction_type_id').val(); //aucttype 14 = lease
                    if(auction_type_id != 14) {
                        $('#calculate_transaction_fee_btn').trigger('click');
                    }
                    var aURL = base_url + 'bidding/place_bid';
                    form = $("#form_bid");
                    var formData = new FormData($('#form_bid')[0]);
                    
                    $("#spinwheel1").attr("style", "visibility: visible");
                    if ($('#hid_confirm').val() != 1) {
                        show_bid_confirm_div();
                        return false;
                    }

                    $("#spinwheel1").attr("style", "visibility: hidden");
                    $("#spinwheel").attr("style", "visibility: visible");

                    if(!bidConfirmAjaxStatus){                          
                            bidConfirmAjaxStatus = true;               
                            $.ajax({
                                type: "POST",
                                url: aURL,
                                data: form.serialize(), // serializes the form's elements.
                                success: function(data) {
                                    bidConfirmAjaxStatus = false;

                                    data = jQuery.parseJSON(data);
                                    if (data.status === 1 || data.status === 100) {
                                        handleAjaxSuccess(data);
                                    } else {                                                                                           
                                        hide_confirm_div();                                        
                                        if(data.error.code === -20 || data.error.code === -21 || data.error.code === -30 || data.error.code === -22){
                                            var content = '<label for="amt" generated="true" class="error minBidErrorText" style="display:inline-block;">'+data.error.message+'</label>';
                                            $('#min_bid_error').html( content );
                                        } else {
                                            $('.error').remove();
                                            var content = '<label for="amt" generated="true" class="error minBidErrorText" style="display:inline-block;">'+data.error.message+'</label>';
                                            $('#min_bid_error').html( content );
                                        }

                                        $("#spinwheel").attr("style", "visibility: hidden");
                                        $('#div_submit').attr('style', 'visibility: visible');
                                        $('#div_confirm').hide();  
                                        $('#hid_confirm').val(0);
                                    }
                                }
                            });
                        }
		}
	});
        
        $('#form_bid input,#form_bid checkbox,#form_bid select').on('change',function(){
            $('#form_bid').valid();
        })

	$('#form_demo_bid_confirm').validate({
		rules: {
			confirm_demo_amt_modal: {
				required: true
			}
		},
		submitHandler: function(form) {
			$.fancybox.showActivity();
			$('#confirm_amt').val($('#confirm_demo_amt_modal').val());
                        var hb = $("#hb").val();
                        $("input[name='amt']").val(hb);
			$('#form_bid').get(0).submit();
		}
	});
}

function reinitCheck ()
{
    /*$('#tc').iCheck('update');*/
    $('#tc').iCheck('destroy');
    $('#tc').iCheck({
      checkboxClass: 'icheckbox_fre',
      radioClass: 'iradio_white',
      increaseArea: '20%' // optional
    });
}

function handleAjaxSuccess(data)
{
    
    var is_auto_post_auction = $('#is_auto_post_auction').val();
    var is_post_link = $('#is_post_link').val();
    var post_auction_link = $('#post_auction_link').val();
    var auction_id = $('#aid').val();
    var auction_number = $('#anumber').val();
    var req_bid_deposit = $('#req_bid_deposit').val();
    var is_only_credit_deposit = $('#is_only_credit_deposit').val();
    var show_bidding = $('#hid_show_bidding').val();
//    var return_link = base_url + 'auctions/view/'+auction_id+'/0/srch';
    var return_link = is_post_link == '1' && post_auction_link != '' ? base_url + post_auction_link : base_url + auction_number;
    var atype = $('#atype').val();
    var title = 'Bid Confirmed';
    var sub_title = '';
    var redirect;
    
    var close_button = '<form id="form_bid_close">'+
        '<div class="pure-u-1 model-block__bid-input-container">'+
            '<input type="button" value="CLOSE" id="cancel_but" class="model-block__input-bid-submit model-block__input-submit">'+          
        '</div>'+
      '</form>';
      
    if(data.error.code === 1){
        sub_title = '';
    } else if(data.error.code === 2 && is_auto_post_auction != '1') {
        sub_title = 'Congratulations! you are currently the high bidder. You will be notified by email if you are outbid.';
        sub_title += '<br><a href="'+return_link+'" alt="click here">Click here</a> to return to auction.';
    } else if(data.error.code === 3) {
        title = 'Bid Confirmed pending bid deposit';
        sub_title = 'Your bid is not considered valid until the required bid deposit form and funds are submitted';
        if(is_only_credit_deposit == '1') {
            sub_title = 'Your Bid is not considered valid until you complete the bid deposit form and authorize your credit card for '+req_bid_deposit+'. Your card is not charged.';
        }
    } else if(data.error.code === 100) {
        title = 'Offer placed';
        sub_title = '';
    } else {
        sub_title = '';
    }
   
   if(is_post_link == '1' || is_auto_post_auction == '1') {
        sub_title = '';
   }
   
    if(data.error.code === 3) {
        var redirect_link = base_url + 'account/bid_deposit_form/' + auction_id;
        redirect = '<div class="pure-u-1 model-block__bid-input-container">'+
            '<a href="'+redirect_link+'">'+
              '<input type="submit" value="COMPLETE BID DEPOSIT FORM" class="model-block__input-bid-submit model-block__input-submit">'+
            '</a>'+
        '</div>';
        $( ".model-block__sub-title-txt" ).after(redirect);
    }       
       
    $('.model-block__title-txt').html(title);
    $('.model-block__sub-title-txt').html(sub_title);
    if(sub_title != ''){
        $('.model-block__sub-title-txt').show();
    }
    $('#form_bid').html('');
    $('.model-block__pricing_sub-title-txt').html('');
    if (data.error.code === 100) {
    	$('#form_bid').html('');
    }
    
//    if(sub_title === ''){
        $( ".model-block__sub-title-txt" ).after(close_button);
//    }
           
    setTimeout(function(){
//        location.href = return_link;
    },5000);
    
    $('.mfp-close').click(function(){
        location.href = return_link;
    });
    $(document).keyup(function(e) {
        if (e.key === "Escape") { // escape key maps to keycode `27`
            location.href = return_link;
        }
    });
}

function handleTenderAjaxSuccess(data)
{
        
    var is_auto_post_auction = $('#is_auto_post_auction').val();
    var is_post_link = $('#is_post_link').val();
    var post_auction_link = $('#post_auction_link').val();
    var auction_id = $('#aid').val();
    var auction_number = $('#anumber').val();
    var atype = $('#atype').val();
    var req_bid_deposit = $('#req_bid_deposit').val();
    var is_only_credit_deposit = $('#is_only_credit_deposit').val();
//    var return_link = base_url + 'auctions/view/'+auction_id+'/0/srch';     
    var return_link = is_post_link == '1'  && post_auction_link != '' ? base_url + post_auction_link : base_url + auction_number;
    var title = 'Receipt of Bid Confirmed'; //#3700
    var sub_title = '';
    var redirect;
    var close_button = '<form id="form_bid_close">'+
        '<div class="pure-u-1 model-block__bid-input-container">'+
            '<input type="button" value="CLOSE" id="cancel_but" class="model-block__input-bid-submit model-block__input-submit">'+          
        '</div>'+
      '</form>';
    if(data.error.code === 1){
        sub_title = '';
    } else if(data.error.code === 2 && is_auto_post_auction != '1') {
        //sub_title = 'Congratulations! you are currently the high bidder. You will be notified by email if you are outbid.';
        sub_title = '<a href="'+return_link+'" alt="click here">Click here</a> to return to auction.'; 
    } else if(data.error.code === 3) {
        title = 'Offer Confirmed Pending Receipt of Deposit';
        sub_title = 'Your offer is not considered valid until the required offer deposit form and funds are submitted.';
        if(is_only_credit_deposit == '1') {
            sub_title = 'Your Bid is not considered valid until you complete the bid deposit form and authorize your credit card for '+req_bid_deposit+'. Your card is not charged.';
        }
    } else if(data.error.code === 100) {
        title = 'Receipt of Bid Confirmed';
        sub_title = '';
    } else {
        sub_title = '';
    }
       
    if(is_post_link == '1' || is_auto_post_auction == '1') {
        sub_title = '';
    }
   
    if(data.error.code === 3) {
        var redirect_link = base_url + 'account/bid_deposit_form/' + auction_id;
        var btn_text = bid_deposit_btn_text;
        redirect = '<div class="pure-u-1 model-block__bid-input-container">'+
            '<a href="'+redirect_link+'">'+
              '<input type="submit" value="'+btn_text+'" class="model-block__input-bid-submit model-block__input-submit">'+
            '</a>'+
        '</div>';
        $( ".model-block__sub-title-txt" ).after(redirect);
    } else {
       /* if(atype != 'auction_plus_lastcall'){
            $('.mfp-close').trigger('click');
        }        
        hide_confirm_div();
        $("#spinwheel").attr("style", "visibility: hidden");
        $('#div_submit').attr('style', 'visibility: visible');
        $('#div_confirm').hide(); 
        $('#hid_confirm').val(0);
        if(atype != 'auction_plus_lastcall'){
           return false;
        }*/
    }
    $('.model-block__title-txt').html(title);
    $('.model-block__sub-title-txt').html(sub_title);
    if(sub_title != ''){
        $('.model-block__sub-title-txt').show();
    }
    $('#form_tender_offer').html('');
    $('.model-block__pricing_sub-title-txt').html('');
    if (data.error.code === 100) {
    	$('#form_tender_offer').html('');
    }    
    
//    if(sub_title === ''){
        $( ".model-block__sub-title-txt" ).after(close_button);
//    }
    
    setTimeout(function(){
//        location.href = return_link;
    },5000);
    
    $('.mfp-close').click(function(){
        location.href = return_link;
    });
    $(document).keyup(function(e) {
        if (e.key === "Escape") { // escape key maps to keycode `27`
            location.href = return_link;
        }
    });
}

function update_currency(that)
{       
        var alt_currency = $(that).val();
        $('#alt_currency').val(alt_currency); 
        $('input[name="alt_currency"]').val(alt_currency);
        
        var auction_currency = $('#auction_currency').val();
        if(auction_currency == '' || auction_currency == '0') {
            auction_currency = $('input[name="auction_currency"]').val();
        }
        
        var plusmnText = '&plusmn;';
        if(alt_currency == auction_currency) {
            plusmnText = '';
        }
        
        var auction_id = $('#auction_id').val();
        if(auction_id == '' || auction_id == '0') {
            auction_id = $('input[name="auction_id"]').val();
        }
        
        //console.log('update_currency' + ' :: ' + $('#alt_currency').val() + ' :: ' + $('#auction_currency').val() + ' :: ' + $(thi).val())
	// if ($('#alt_currency').val() == $('#auction_currency').val())
	// {
	// 	$('.alt_currency_mb, .alt_currency_sv, .alt_currency_bd, .alt_currency_bi').fadeOut(100);
	// }
	// else
	// {
		$.get(base_url+'services/auctions/get_alt_currency/'+ auction_id +'/' + alt_currency, function(r)
		{
			eval('var result = '+r);
			if (result.status == 1)
			{
				$('.alt_currency').show();

				if (result.data.list_price != '')
				{
					$('.alt_currency_lp').fadeOut(100, function(){
						$('.alt_currency_lp').html(plusmnText + result.data.list_price);
						$('.alt_currency_lp').fadeIn(100);
					});
				}
				if (result.data.current_bid != '')
				{
					$('.alt_currency_cb').fadeOut(100, function(){
						$('.alt_currency_cb').html(plusmnText + result.data.current_bid);
						$('.alt_currency_cb').fadeIn(100);
					});
				}
				if (result.data.minimum_bid != '')
				{
					$('.alt_currency_mb').fadeOut(100, function(){
						$('.alt_currency_mb').html(plusmnText + result.data.minimum_bid);
						$('.alt_currency_mb').fadeIn(100);
					});
				}
				if (result.data.suggested_value != '')
				{
					$('.alt_currency_sv').fadeOut(100, function(){
						$('.alt_currency_sv').html(plusmnText + result.data.suggested_value);
						$('.alt_currency_sv').fadeIn(100);
					});
				}
				if (result.data.current_payoff != '')
				{
					$('.alt_currency_tl').fadeOut(100, function(){
						$('.alt_currency_tl').html(plusmnText + result.data.current_payoff);
						$('.alt_currency_tl').fadeIn(100);
					});
				}
				if (result.data.bid_deposit != '')
				{
					$('.alt_currency_bd').fadeOut(100, function(){
						$('.alt_currency_bd').html(plusmnText + result.data.bid_deposit);
						$('.alt_currency_bd').fadeIn(100);
					});
				}
				if (result.data.bid_increment != '')
				{
					$('.alt_currency_bi').fadeOut(100, function(){
						$('.alt_currency_bi').html(plusmnText + result.data.bid_increment);
						$('.alt_currency_bi').fadeIn(100);
					});
				}
				if (result.data.total_purchase != '')
				{
					$('.alt_currency_tp').fadeOut(100, function(){
						$('.alt_currency_tp').html(plusmnText + result.data.total_purchase);
						$('.alt_currency_tp').fadeIn(100); 
					});
				}
				if (result.data.bid_per_share != '')
				{
					$('.alt_currency_bps').fadeOut(100, function(){
						$('.alt_currency_bps').html(plusmnText + result.data.bid_per_share);
						$('.alt_currency_bps').fadeIn(100);
					});
				}
			}
			else
			{
				// do nothing
			}
		});
	// }
}

function init_fin_form()
{
	$('#form_financing').validate({
		rules: {
			first_name: "required",
			last_name: "required",
			country: "required",
			address_line_1: "required",
			email: "required",
			primary_phone: "required"
		}
	});
	$('#form_financing').valid();
}

function init_auto_update()
{
	if ($('.countdown').val())
	{
		var countdown_data = $('.countdown').metadata();

		cd_rem = parseInt(countdown_data.remaining);
		setTimeout("countdown()",1000);
	}
}


function init_list_styles()
{
	$("table.list tbody tr:visible:odd").addClass('alt');
	$("table.no-alt tbody tr").removeClass('alt');

	// set mouseover/mouseleave states for clickable rows
	$("tr.clickable").bind("mouseenter", function() {
		$(this).children('td').addClass('hover');
	});

	$("tr.clickable").bind("mouseleave", function() {
		$(this).children('td').removeClass('hover');
	});

	$("table.list tbody tr.delayed-detail").show();

	//$("tr.clickable").removeClass('clickable');

	// deactivate event bubbling in clickable rows
	$("tr.clickable td input[type=checkbox]").bind("click", function(e) {
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	});

	$("tr.clickable td a").bind("click", function(e) {
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	});
}

function init_total_purchase_price()
{
	if ($("#num_of_shares").length > 0)
	{
		$("input[name=amt]").keyup(function()
		{
			var total_purchase_price = $(this).val() * $("input[name=num_of_shares]").val();
			total_purchase_price = Math.round(total_purchase_price*100)/100;

			if(total_purchase_price == 0)
			{
				$(".purchase_price").html("US $0.00");
			}
			else
			{
				if (!isNaN(total_purchase_price.toFixed(2)))
				{
					$(".purchase_price").html("US $" + addCommas(total_purchase_price.toFixed(2)));
				}
				else
				{
					$(".purchase_price").html("US $0.00");
				}
			}
		});
	}

	if ($("#num_of_shares").length > 0)
	{
		var total_purchase_price = $("input[name=amt]").val() * $("input[name=num_of_shares]").val();
		total_purchase_price = Math.round(total_purchase_price*100)/100;

		if(total_purchase_price == 0)
		{
			$(".purchase_price").html("US $0.00");
		}
		else
		{
			if (!isNaN(total_purchase_price.toFixed(2)))
			{
				$(".purchase_price").html("US $" + addCommas(total_purchase_price.toFixed(2)));
			}
			else
			{
				$(".purchase_price").html("US $0.00");
			}
		}

	}
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.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;
}

function init_access_data_gate_gate()
{
	$(".access_data_gate").fadeTo("fast", 0.2, function()
	{
		$(".access_data_gate").show();
		$(".access_data_gate_popup").fadeIn("slow");
	});

}

function init_currenty_auction()
{ //not in use
	if ($("select[name=alt_currency]").length)
	{
		$("select[name=alt_currency] option[value=" + $("#auction_currency").val() + "]").attr('selected','selected');
		update_currency();
	}
}

function init_magnificpopup_close ()
{
    
    //$('.error').remove();
    
    $('#cancel_but,#cancel_but_confirm').on('click',function () {
        $.magnificPopup.close();
        location.reload();
    });
    
    $(document.body).on('click','.cancel_but,.cancel_but_confirm',function () {
        $.magnificPopup.close();
        location.reload();
    });
    
    $(document.body).on('click','#cancel_but,#cancel_but_confirm',function () {
        $.magnificPopup.close();
        location.reload();
    });
}

function init_form_follow ()
{
    $('#follow_email_btn').on('click',function(event){
        event.preventDefault();
        event.stopImmediatePropagation();
        var form = $("#form_follow");
        var aURL = form.attr('action');
        _startLoading();
        $.ajax({
            type: "POST",
            url: aURL,
            data: form.serialize(), // serializes the form's elements.
            success: function(data) {
                //$('#label_follow_email').remove();
                //console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
                var data_parse = jQuery.parseJSON(data); //alert(data);
                
                // #3528 - display suggested email address
				if(data_parse.data.suggestion != '' && data_parse.data.suggestion != 'null' && data_parse.data.suggestion != null){
                    var content = "<label id='label_follow_email' for='follow_email' generated='true' class='error'>Do you mean '"+data_parse.data.suggestion+"'? <br/></label>";
                	if($("#label_follow_email").length == 0){
	                    $('input[id=follow_email_btn]').after(content);
					}else{
						$("#label_follow_email").html("Do you mean '"+data_parse.data.suggestion+"'? <br/>")
					}
                	$("#label_follow_email").css("display","block");
				}else{
					$("#label_follow_email").html('')
					$("#label_follow_email").css("display","none");
				}
                
                // #3506 - if emailgrade is F then allow to proceed
                var valid_grade = $("#valid_grade_follow").val();
							
                if(data_parse.data.checkEmail == 'F' &&  valid_grade == 0){
                        $("#valid_grade_follow").val(1);
                	if($("#label_follow_email").length == 0){                            
                            var content = '<label id="label_follow_email" for="follow_email" generated="true" class="error">Email address appears invalid please check. If OK Click Submit again.</label>';
	                    $('input[id=follow_email_btn]').after(content);
                        }else{
                                $("#label_follow_email").append('Email address appears invalid please check. If OK Click Submit again.');
                        }
                	$("#label_follow_email").css("display","block");
                }else{
                        $("#label_follow_email").html('')
                        $("#label_follow_email").css("display","none");
					
			                        
                        if (data_parse.status === 1 || data_parse.status === 2) {
                            
                            $('#auction_watchlist_status_' +data_parse.data.auction_id).val('1');
                            $('#follower_signup_status').val('1');
                            $('#favorite_icon,#favorite_icon_mobile').hide();            
                            $('#favorite_active_icon,#favorite_active_icon_mobile').show();                        
                            if($('#favorite_icon_'+data_parse.data.auction_id).length){
                                $('#favorite_icon_'+data_parse.data.auction_id).hide();            
                                $('#favorite_active_icon_'+data_parse.data.auction_id).show();                  
                            }
                            $('.mfp-close').trigger('click');
                                        
//	                    $('#form_follow').html('');
//	                    $('h4').html('');
//	                    var content = data_parse.data.error_message;
//	                    $('h4').html(content);

	                } else {
	                    //alert(data_parse.data.error_message);
	                    var content = '<br><label id="label_follow_email" for="follow_email" generated="true" class="error">'+data_parse.data.error_message+'</label>';
	                    $('input[id=follow_email_btn]').after(content);
	                }
                }
            },complete:function(){
		        _stopLoading();
			}
        });
    });
}

function init_auction_ended_search ()
{
    $('#ended_search_auction, #ended_search_auction_mobile').click(function(){ //alert('init_auction_ended_search');
        $(".auction_search_link" ).trigger( "click" );
    });
}

function hide_confirm_div(){
    $('.model-block__pricing_sub-title-txt').show();
    $('.model-block__sub-title-txt').show();                                
    $('.model-block__bid-input-container').show();
    $('#div_submit').show();			        
    $('.pure-u-1 model-block__content--last').attr("style",'overflow:scroll;');
    $('#confirm_modal_div').show();
}

function show_confirm_div() {
        var amt 	     = $('#bid_amt').val(); 
        var currency     = $('#hid_currency').val();
        var assetType    = $('#hid_asset_type').val();
        var auctiontypeid = $('#profile_auction_type_id').val(); //14 = lease
        var locale       = $('#hid_locale').val();
        var show_transaction_fee  = $('#show_transaction_fee').val();
        var transaction_fee       = $('#transaction_fee_value').val();
        
        var hideDecimal = 0;                            
        var lease_bid_format = $('#lease_bid_format').val();     
        if(lease_bid_format == 'M' || lease_bid_format == 'Y'){
            hideDecimal = 1;
        }
        
        if (amt != '') {
          var aURL     = base_url + 'bidding/get_float_val/'+ hideDecimal;
          var data_val = "amt="+amt+"&curr="+currency+"&asset_type="+assetType+"&auction_type_id="+auctiontypeid+"&locale="+locale;
          $.ajax({
              type: "GET",
              async: false,
              url: aURL,
              data: data_val, // serializes the form's elements.
              success: function(data) {
                  	amt = data;
                        $('#div_submit').attr('style', 'visibility: hidden');
                        $("#spinwheel1").attr("style", "visibility: hidden");
                        var new_bid = parseFloat($('#bid_amt').val());
                        if(auctiontypeid == 14 && $('#lease_square_foot_text').length > 0){ //lease
                            $('#new_amt').html('<span class="model-block__pricing-label offer-pricing-label">Your Offer: </span>' + '<span class="model-block__pricing-amount price_labels offer-pricing-amount">' + amt + '</span>' + '<span style="color:#fff;font-weight:500;"> '+$('#lease_square_foot_text').html()+'</span>');
                        } else {
                            $('#new_amt').html('<span class="model-block__pricing-label offer-pricing-label">Your Bid: </span>' + '<span class="model-block__pricing-amount price_labels offer-pricing-amount">' + amt + '</span>');
                        }                 
                        $('#new_amt').show();
                        
                        if(auctiontypeid != 14 && show_transaction_fee == '1' && transaction_fee > 0) {
                            $('#transaction_fee_container').hide();
                            
                            var transaction_fee_string       = $('#transaction_fee_string').val();
                            var bid_transaction_amt_text       = $('#bid_transaction_amt_text').val();
                            var transaction_fee_text       = $('#hid_transaction_fee_text').val();
                                                        
                            var transaction_fee_html =  '<span class="model-block__pricing-label offer-pricing-label">Transaction Fee:</span> <span class="model-block__pricing-amount price_labels offer-pricing-amount">' + transaction_fee_string + '</span><br>'
                            + '<span class="model-block__pricing-label offer-pricing-label">Total Sale Price:</span> <span class="model-block__pricing-amount price_labels offer-pricing-amount">' + bid_transaction_amt_text + '</span><br>';
                    
                            $('#new_amt').after(transaction_fee_html);
                            
                            $('#transaction_fee_container').hide();
                            $('#calculate_transaction_fee_btn').hide();
                            $('#transaction_fee_container .transaction_fee_popup').hide();
                            $('.transaction_fee_popup').css('display', 'none!important');
                        }                        
                        
                        if(auctiontypeid == 14 && assetType != 'LAND' /*&& $('#lease_square_foot_text').length > 0*/){ //lease                            
                            var sqft = $('#lease_square_foot').val();                                 
                            var newval_cal = new_bid;                            
                            if (sqft != '') {
                                newval_cal = sqft * new_bid;
                                var aURL     = base_url + 'bidding/get_float_val/'+hideDecimal;
                                var data_val = "amt="+(newval_cal)+"&curr="+currency+"&asset_type="+assetType+"&auction_type_id="+auctiontypeid+"&locale="+locale;
                                $.ajax({
                                    type: "GET",
                                    async: false,
                                    url: aURL,
                                    data: data_val, // serializes the form's elements.
                                    success: function(data) {          
                                        newval_cal = data;
                                    }
                                });
                            }
                            $('.lease_format').remove();
                            if(lease_bid_format == 'M' || lease_bid_format == 'Y'){
                                $('#new_amt_per_month').hide();
                            } else {
                                if(lease_bid_format == 'SF_M'){
                                    $('#new_amt_per_month').html('<span class="total-amount" style="color:#fff;font-weight:500;width: 262px;display: inline-block;">Total Offer per Month: </span>' + '<span class="price_labels" style="color:#6dbcec;">' + newval_cal + '</span>');   
                                } else {
                                    $('#new_amt_per_month').html('<span class="total-amount" style="color:#fff;font-weight:500;width: 262px;display: inline-block;">Total Offer per Year: </span>' + '<span class="price_labels" style="color:#6dbcec;">' + newval_cal + '</span>');
                                }                                
                                $('#new_amt_per_month').show();
                            }                            
                        } else {
                            $('.lease_format').remove();
                            $('#new_amt_per_month').hide();
                        }
                        
                        var title = "Offer Confirmation";
                        $('.model-block__title-txt').html(title);
                        $('.model-block__sub-title-txt').hide();                                
                        $('.model-block__bid-input-container').hide();
                        $('#div_submit').hide();			        
                        $('.pure-u-1 model-block__content--last').attr("style",'overflow:hidden;');
                        $('#confirm_modal_div').show();
                        $('#div_confirm').show();                  
              }
          });
        }
}

function show_bid_confirm_div() {
        var amt 	     = $('#amt').val(); 
        var currency     = $('#hid_currency').val();
        var assetType    = $('#hid_asset_type').val();
        var auctiontypeid = $('#profile_auction_type_id').val(); //14 = lease
        var locale       = $('#hid_locale').val();
        var show_transaction_fee  = $('#show_transaction_fee').val();
        var transaction_fee       = $('#transaction_fee_value').val();
        
        var hideDecimal = 0;
        if(auctiontypeid == 14){
            var lease_bid_format = $('#lease_bid_format').val();                                 
            if(lease_bid_format == 'M' || lease_bid_format == 'Y'){
                hideDecimal = 1;
            }
        } 
        
        if (amt != '') {
          var aURL     = base_url + 'bidding/get_float_val/'+hideDecimal;
          var data_val = "amt="+amt+"&curr="+currency+"&asset_type="+assetType+"&auction_type_id="+auctiontypeid+"&locale="+locale;
          $.ajax({
              type: "GET",
              async: false,
              url: aURL,
              data: data_val, // serializes the form's elements.
              success: function(data) {
                  	amt = data;
                        $('#div_submit').attr('style', 'visibility: hidden');
                        $("#spinwheel1").attr("style", "visibility: hidden");
                        var new_bid = parseFloat($('#amt').val());
                        if(auctiontypeid == 14 && $('#lease_square_foot_text').length > 0){ //lease
                            $('#new_amt').html('<span class="model-block__pricing-label bid-pricing-label">Your Offer: </span>' + '<span class="model-block__pricing-amount price_labels bid-pricing-amount">' + amt + '</span>' + '<span style="color:#fff;font-weight:500;"> '+$('#lease_square_foot_text').html()+'</span>');
                        } else {
                            $('#new_amt').html('<span class="model-block__pricing-label bid-pricing-label">Your Bid: </span>' + '<span class="model-block__pricing-amount price_labels bid-pricing-amount">' + amt + '</span>');
                        }                        
                        $('#new_amt').show();
                        
                        if(auctiontypeid != 14 && show_transaction_fee == '1' && transaction_fee > 0) {
                            $('#transaction_fee_container').hide();
                            
                            var transaction_fee_string       = $('#transaction_fee_string').val();
                            var bid_transaction_amt_text       = $('#bid_transaction_amt_text').val();
                            var transaction_fee_text       = $('#hid_transaction_fee_text').val();
                                                        
                            var transaction_fee_html = '<span class="model-block__pricing-label bid-pricing-label">Transaction Fee:</span> <span class="model-block__pricing-amount price_labels bid-pricing-amount">' + transaction_fee_string + '</span><br>'
                            + '<span class="model-block__pricing-label bid-pricing-label">Total Sale Price:</span> <span class="model-block__pricing-amount price_labels bid-pricing-amount">' + bid_transaction_amt_text + '</span><br>';
                    
                            $('#new_amt').after(transaction_fee_html);
                            
                            $('#transaction_fee_container').hide();
                            $('#calculate_transaction_fee_btn').hide();
                            $('#transaction_fee_container .transaction_fee_popup').hide();
                            $('.transaction_fee_popup').css('display', 'none!important');
                        }   
                                               
                        if(auctiontypeid == 14  && assetType != 'LAND' /*&& $('#lease_square_foot_text').length > 0*/){ //lease
                            var newval_cal = new_bid;
                            var sqft = $('#lease_square_foot').val();                                                                                    
                            if (sqft != '') {
                                newval_cal = sqft * new_bid;
                                var aURL     = base_url + 'bidding/get_float_val/'+hideDecimal;
                                var data_val = "amt="+(newval_cal)+"&curr="+currency+"&asset_type="+assetType+"&auction_type_id="+auctiontypeid+"&locale="+locale;
                                $.ajax({
                                    type: "GET",
                                    async: false,
                                    url: aURL,
                                    data: data_val, // serializes the form's elements.
                                    success: function(data) {          
                                        newval_cal = data;
                                    }
                                });
                            }
                            
                            if(lease_bid_format == 'M' || lease_bid_format == 'Y'){
                                $('#new_amt_per_month').hide();
                            } else {
                                if(lease_bid_format == 'SF_M'){
                                    $('#new_amt_per_month').html('<span class="total-amount" style="color:#fff;font-weight:500;width: 250px;display: inline-block;">Total Offer per Month: </span>' + '<span class="price_labels" style="color:#6dbcec;">' + newval_cal + '</span>'); 
                                } else {
                                    $('#new_amt_per_month').html('<span class="total-amount" style="color:#fff;font-weight:500;width: 250px;display: inline-block;">Total Offer per Year: </span>' + '<span class="price_labels" style="color:#6dbcec;">' + newval_cal + '</span>');
                                }   
                                $('#new_amt_per_month').show();
                            }
                        } else {
                            $('#new_amt_per_month').hide();
                        }
                        
                        var title = "Bid Confirmation";
                        $('.model-block__title-txt').html(title);
                        $('.model-block__sub-title-txt').hide();                                
                        $('.model-block__bid-input-container').hide();
                        $('#div_submit').hide();			        
                        $('.pure-u-1 model-block__content--last').attr("style",'overflow:hidden;');
                        $('#confirm_modal_div').show();
                        $('#div_confirm').show();                  
              }
          });
        }
}

$(function ()
{
    FRE_Global_JS.initTimer();
    init_auto_update();
    init_access_data_gate_gate();
    init_list_styles();
    init_total_purchase_price();
    init_magnificpopup_close();
    init_auction_ended_search();

    if ($('#form_bid').length) init_bid_form();
    if ($('#form_tender_offer').length) init_form_tender_offer();

    if ($('#form_financing').length) init_fin_form();
    if ($('#form_follow').length) init_form_follow();    

    if ($('#map_btn').length)
    {
        $('#map_btn').unbind();
        $('#map_btn').bind('click', function() {
                return toggle_map();
                //return false;
        });
    }
    if ($('#map_btn2').length) {
            $('#map_btn2').unbind();
            $('#map_btn2').bind('click', function () {
                    return toggle_map();
                    //return false;
            });
    }
    if ($('#map_btn3').length) {
            $('#map_btn3').unbind();
            $('#map_btn3').bind('click', function () {
                    return toggle_map();
                    //return false;
            });
    }
    if ($('#map_btn4').length) {
            $('#map_btn4').unbind();
            $('#map_btn4').bind('click', function () {
                    return toggle_map();
                    //return false;
            });
    }
});

$(function ()
{    
    var is_reit_asset = $('#is_reit_asset').val() | 0;
    var auction_type_id = $('#profile_auction_type_id').val(); //aucttype 14 = lease
    var noCommas = $('#bid_amt').val();

    if(noCommas != '' && noCommas != null && noCommas != undefined){
        noCommas = noCommas.replace(/[^0-9]+/gi, "")
    }    
    if(!is_reit_asset && auction_type_id != 14){
        $('#bid_amt').val(noCommas);
    }
    $('#bid_amt').on('keyup',function(){
        var is_reit_asset = $('#is_reit_asset').val() | 0;
        var auction_type_id = $('#profile_auction_type_id').val(); //aucttype 14 = lease
        var noCommas = $('#bid_amt').val();

        if(noCommas != '' && noCommas != null && noCommas != undefined){
            noCommas = noCommas.replace(/[^0-9]+/gi, "")
        }
        if(!is_reit_asset && auction_type_id != 14){
            $('#bid_amt').val(noCommas);
        }
    });
    


    var noCommas2 = $('#amt').val();
    if(noCommas2 != '' && noCommas2 != null && noCommas2 != undefined){
      noCommas2 = noCommas2.replace(/[^0-9]+/gi, "");
    }
    if(!is_reit_asset && auction_type_id != 14){
        $('#amt').val(noCommas2);
    }
    $('#amt').on('keyup',function(){
        var noCommas2 = $('#amt').val();
        var is_reit_asset = $('#is_reit_asset').val() | 0;
        var auction_type_id = $('#profile_auction_type_id').val(); //aucttype 14 = lease
        if(noCommas2 != '' && noCommas2 != null && noCommas2 != undefined){
            noCommas2 = noCommas2.replace(/[^0-9]+/gi, "")
        }
        if(!is_reit_asset && auction_type_id != 14){
            $('#amt').val(noCommas2);
        }
    });
    
    
    $('#due_diligence_period,#closing_period').on('keyup',function(){
        var nochar = $(this).val();
        if(nochar != '' && nochar != null && nochar != undefined){
            nochar = nochar.replace(/[^0-9]+/gi, "")
        }
        $(this).val(nochar);
    });          
});

function update_lease_format(fomatval)
{  
        var auction_id = $('#auction_id').val();
        if(auction_id == '' || auction_id == '0') {
            auction_id = $('input[name="auction_id"]').val();
        }
    
    	if (fomatval != '')
	{                
		$.get(base_url+'services/auctions/get_lease_bid_format/'+ auction_id + '/' + fomatval, function(r)
		{
			eval('var result = '+r);
			if (result.status == 1)
			{
                                $('select[name="lease_format"] option[value="'+fomatval+'"]').attr('selected', 'selected');
                                $('select[name="lease_format"]').select2("destroy");
                                $('select[name="lease_format"]').select2({width: '100%',minimumResultsForSearch: Infinity});
                                $('input[name="lease_bid_format"]').val(fomatval);
            
                                if(result.data.label_text != ''){
                                    $('#lease_sqft_label').html(result.data.label_text);
                                    $('#lease_square_foot_text').html(result.data.label_text);
                                }                                				
				if (result.data.minimum_bid != '')
				{
                                    $('#lease_mb,#lease_mb_mob,#lease_mb_popup').html(result.data.minimum_bid);
				}
				if (result.data.suggested_value != '')
				{
                                    $('#lease_sv,#lease_sv_mob,#lease_sv_popup').html(result.data.suggested_value);
				}
                                if (result.data.compare_min_bid != '')
				{
                                    $('#compare_min_bid').val(result.data.compare_min_bid);
				}  
                                if(result.data.min_bid_compare_error != ''){
                                    $('#min_bid_compare_error').html(result.data.min_bid_compare_error);
                                    init_form_tender_offer();
                                }                            
                                if($('#bid_amt').val() != '' && $('#bid_amt').val() < $('#compare_min_bid').val()){
                                    var content = '<label for="amt" generated="true" class="error minBidErrorText" style="display:inline-block;">'+$('#min_bid_compare_error').html()+'</label>';
                                    $('#min_bid_error').html( content );
                                }
                                $('#bid_amt').trigger('change');
			}
			else
			{
				// do nothing
			}
		});
	}
}


function calculate_cap_rate(bid_amt_field) {
    
    var amt = $('#'+bid_amt_field).val();
    
    var auction_id = $('#auction_id').val();
    if(auction_id == '' || auction_id == '0') {
        auction_id = $('input[name="auction_id"]').val();
    }
    
    $.get(base_url+'services/auctions/get_bid_cap_rate/'+ auction_id +'/' + amt, function(r)
    {
            eval('var result = '+r);
            if (result.status == 1)
            {
                    if (result.data.cap_rate != '')
                    {
                            $('.cap_rate_popup').fadeOut(100, function(){
                                    $('.cap_rate_popup').html(result.data.cap_rate);
                                    $('.cap_rate_popup').fadeIn(100);
                            });
                    }
            }
            else
            {
                    // do nothing
            }
    });
}


function calculate_transaction_fee(bid_amt_field, use_calculation, show_fees) {
    
    var amt = $('#'+bid_amt_field).val();
    if(amt == '') {
        amt = 0;
    }
    
    var auction_id = $('#auction_id').val();
    if(auction_id == '' || auction_id == '0') {
        auction_id = $('input[name="auction_id"]').val();
    }
    $.get(base_url+'services/auctions/get_transaction_fee/'+ auction_id +'/' + amt + '/' + use_calculation, function(r)
    {
            eval('var result = '+r);
            if (result.status == 1)
            {
                    if (result.data.transaction_fee != '')
                    {
                           // $('.transaction_fee_popup').fadeOut(100, function(){
                                    $('.transaction_fee_popup').html(result.data.transaction_fee_string); //+ ' ' + result.data.transaction_fee_text                                    
//                                    $('.transaction_fee_popup').fadeIn(100);
                                    
                                    $('#transaction_fee_value').val(result.data.transaction_fee);
                                    $('#transaction_fee_string').val(result.data.transaction_fee_string);
                                    $('#bid_transaction_amt_text').val(result.data.bid_transaction_amt_text);
                                    
                                    $('#transaction_fee_container').show();
//                                    if(show_fees == 1) {
//                                        $('.transaction_fee_popup').show();
//                                    } else {
//                                        $('.transaction_fee_popup').hide();
//                                    }
                            //});
                    }
            }
            else
            {
                    // do nothing
            }
    });
}