$(function () {
	/*
	$(".gridprop .readmore").each(function() {
		var href = $(this).parent().find(".displayaddress a").attr("href");
		$(this).attr("href",href);
	});
	*/

    // add change event for new propind select
    $('input[name="propind"]').change(function () {
        changePriceList();
        if ($(this).val() === "S") {
            $("#excludelabel").text("Hide Sold / SSTC");
            $(".newhomes-container").show();
        } else {
            $("#excludelabel").text("Hide Let / Let Agreed");
            $(".newhomes-container").hide();
        }
    });

    changePriceList();

    setBusinessCategoryToggle($("#businessCategoryId").val());

    // Update text of 0 bedroom search option
    $('.beds option[value="0"]').text("Studio");

    // and for the business category select
    $("#businessCategoryId").change(function () {
        setBusinessCategoryToggle($(this).val());
    });

    //$("#newhomescheck").change(function() {
    //	setSearchFilters();
    //});

    //$("#excludecheck").change(function() {
    //	setSearchFilters();
    //});

    if ($("#propsearch div").length > 0) {
        changePriceList();
        setBusinessCategoryToggle($("#businessCategoryId").val());
        $("#MinPrice").appendTo("#minPriceWrapper");
        $("#MaxPrice").appendTo("#maxPriceWrapper");
    }

    if ($(".status").length > 0) {
        $(".status").each(function (index) {
            // unwrap and rewrap link around status
            $(this).parent().find("a").prepend(this);
        });
    }

    if ($('body .venobox').length > 0) {
        $('.venobox').venobox();
    }

    // update the top search hidden fields
    setTopSearchHiddenValues();

    // toggle open class for dropdown on hover
    $(".dropdown-menu").hover(
        function () {
            if (!$(this).parent().hasClass("open")) {
                $(this).parent().addClass("open");
            }
        }, function () {
            // maybe remove it ?
            if ($(this).parent().hasClass("open")) {
                $(this).parent().removeClass("open");
            }
        }
    );

    $(".scrollTo").click(function (event) {
        event.preventDefault();
        if ($(this).attr("href").length > 0) {
            var elemId = '#' + $(this).attr("href").replace('#', '');
            if ($(elemId).length > 0) {
                var topPixel = $(elemId).offset().top;
                // take banner height into account
                var bannerHeight = $("#header").height() + 15;
                topPixel = topPixel - bannerHeight;
                $('html, body').animate({
                    scrollTop: topPixel
                }, 500);
            }
        }
    });

    if ($("#search").length > 0 && !$("#search").hasClass("map")) {
        $(window).scroll(function () {
            if ($(window).width() > 991) {
                if ($(window).scrollTop() > 147) {
                    $("#search").addClass("fix-search");
                } else {
                    $("#search").removeClass("fix-search");
                }
                if ($(window).scrollTop() >= $(".paging").position().top - $("#search").height() - 30) {
                    $("#search").addClass("raise-search");
                    $("#search").css('top', $(".paging").position().top - $("#search").height() - 30);
                } else {
                    $("#search").removeClass("raise-search");
                    $("#search").css('top', '75px');
                }
            }
            else {
                $("#search").css('top', '0px');
            }
        });
    }

    $(window).resize(function () {
        if ($(window).width() < 992) {
            $("#search").removeClass("fix-search");
            $("#search").removeClass("raise-search");
        }
    });

	$(".scrollToTop").click(function(event) {
		event.preventDefault();
		$('html, body').animate({
			scrollTop: 0
		}, 250);
	});

	// auto scroll to viewingform
    // No longer works due to initialisation of the slideshow, so just allow browser to handle it

	if($(".propertydet div").length > 0){
        if (location.href.indexOf("#viewingformanchor") > 0) {
			//$("#viewinglinkwrap a").trigger("click");
		}
	}

	// add clears to blog
	/*
	if($(".bloglist .clearfix").length < 1) {
		$(".bloglist .blogitem:nth-child(3)").each(function( i ) {
			$('<div class="clearfix">&nbsp;</div>').insertAfter($(this));
		});
	}
	*/

	if($('.bloglist .row').length < 1) {
		$('.bloglist .blogitem').wrapMatch(3,'row');
	}

	if($(".features .twocolfeaturelist ul").length > 0) {
		$(".features .twocolfeaturelist").append('<div class="clearboth">&nbsp;</div>');
	}

	if($(".listprop").length > 0) {
		$(".listprop .summary p").each(function( index ) {
			var thisText = $(this).html();
			// strip out carriage returns
			thisText = thisText.replace(/[\n\r]+/g, '');
			thisText = thisText.replace('<br><br>',' ');
			thisText = thisText.replace('<br>',' ');
			$(this).html(thisText);
		});
	}

	if($(".propertydet #vtourlinkwrap a").length > 0) {
		$(".propertydet #vtourlinkwrap a").text("Virtual Tour");
	} else {
		$(".propertydet #vtourlinkwrap").hide();
	}

	$(window).trigger('resize');
});

$("#sortBy").change(function() {
	setSearchFilters();
	$("#propsearch").trigger("submit");
});

function setSearchFilters() {
	setTopSearchHiddenValues();
	$("#propsearch").trigger("submit");
}

function setTopSearchHiddenValues() {
	if($('input[name="exclude"]:checked').length > 0) {
		$("#hiddenHideProps").attr("value",$("#excludecheck").attr("value"));
	} else {
		$("#hiddenHideProps").attr("value","");
	}
	if($('input[name="salesClassificationRefId"]:checked').length > 0) {
		$("#hiddenSalesClassificationRefId").attr("value",$("#newhomescheck").attr("value"));
	} else {
		$("#hiddenSalesClassificationRefId").attr("value","");
	}
	$("#hiddenSortBy").attr("value",$("#sortBy").val());
}

function changePriceList() {
    changeV2minPriceList();
    changeV2maxPriceList();
}

function changeV2minPriceList() {
    var elems, propind, priceList, optionList, listStr, pArr, currSel, isSelected;

    currSel = $("#MinPrice").val();
    isSelected = false;

    $("#MinPrice option").remove();
    $("#MinPrice").append('<option value="">No Min.</option>');

    propind = $("input:radio[name=propind]:checked").val();
	// uses select boxes now
    //propind = $("#propind").val();

    if(propind === "L") {
        listStr = new String($("#RentPricelist").val());
        optionList = listStr.split(";");
		$("#MinPriceWrap label").text("Rent From PCM:");
		$(".sstc-container label").text("Hide Let Agreed");
        $(".newhomes-container").hide();
    } else {
        listStr = new String($("#SalesPricelist").val());
        optionList = listStr.split(";");
        $("#MinPriceWrap label").text("Buy Price From:");
        $(".sstc-container label").text("Hide SSTC and Sold");
        $(".newhomes-container").show();
    }
    for (i = 0; i < optionList.length; i++) {
        if(currSel === optionList[i]) {
			isSelected = true;
		} else {
			isSelected = false;
		}
        pArr = optionList[i].split("-");
        if (pArr[1] === "") {
            $("#MinPrice").append(new Option(String.fromCharCode(163) + addCommas(pArr[0]) + "+", optionList[i],false,isSelected));

        } else {
            if(optionList[i].length > 0) {
            	$("#MinPrice").append(new Option(String.fromCharCode(163) + addCommas(optionList[i]), optionList[i],false,isSelected));
            }
        }
    }
}
function changeV2maxPriceList() {
    var elems, propind, priceList, optionList, listStr, pArr, currSel, isSelected;
    // get the current selected option
    currSel = $("#MaxPrice").val();
    isSelected = false;

    $("#MaxPrice option").remove();
    $("#MaxPrice").append('<option value="">No Max.</option>');

    propind = $("input:radio[name=propind]:checked").val();
	// uses select boxes now
    //propind = $("#propind").val();

    if(propind === "L") {
        listStr = new String($("#RentPricelist").val());
        optionList = listStr.split(";");
		$("#MaxPriceWrap label").text("Rent To PCM:");
		$(".sstc-container label").text("Hide Let Agreed");
        $(".newhomes-container").hide();
    } else {
        listStr = new String($("#SalesPricelist").val());
        optionList = listStr.split(";");
        $("#MaxPriceWrap label").text("Buy Price To:");
        $(".sstc-container label").text("Hide SSTC and Sold");
        $(".newhomes-container").show();
    }
    for (i = 0; i < optionList.length; i++) {
        if(currSel === optionList[i]) {
			isSelected = true;
		} else {
			isSelected = false;
		}
        pArr = optionList[i].split("-");
        if (pArr[1] === "") {
            $("#MaxPrice").append(new Option(String.fromCharCode(163) + addCommas(pArr[0]) + "+", optionList[i],false,isSelected));

        } else {
            if(optionList[i].length > 0) {
            	$("#MaxPrice").append(new Option(String.fromCharCode(163) + addCommas(optionList[i]), optionList[i],false,isSelected));
            }
        }
    }
}

function setBusinessCategoryToggle(busCat) {
	// hide some fields on commercial
    if (busCat === "2") {
        $("#bedfieldrow").hide();
        $("#newhomesfieldrow").hide();
		//$("#BedsEqual").prop( "disabled", true );
		$("#propsearch").attr("action","commercial/properties/");
		console.log("COMM: " + busCat);
	} else {
        $("#bedfieldrow").show();
        $("#newhomesfieldrow").show();
		//$("#BedsEqual").prop( "disabled", false );
		$("#propsearch").attr("action","properties/");
	}

}

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;
}

var map;
function loadGoogleMapv3(lat, long, addressStr, prmGoogleMapKey) {
	var mapQuery = '';
	if(addressStr.length > 0)  {
		mapQuery = addressStr;
	} else if (eval(lat) && eval(long)) {
		mapQuery = lat + "," + long;
	}
	$(".contactmap #map").html('<iframe width="100%" height="100%" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q=' + mapQuery + '&amp;key=' + prmGoogleMapKey + '"></iframe>');
}

function addErrClass(prmSelector) {
	if($(prmSelector).length > 0) {
		if(! $(prmSelector).hasClass("errform")) {
			$(prmSelector).addClass("errform");
		}
	}
}
function removeErrClass(prmSelector) {
	if($(prmSelector).length > 0) {
		if($(prmSelector).hasClass("errform")) {
			$(prmSelector).removeClass("errform");
		}
	}
}

function validateNumericCaptcha(prmSelector) {
	var result;
	result = ( parseInt($(prmSelector + ' #firstbox').val()) + parseInt($(prmSelector + ' #secondbox').val()) == parseInt($(prmSelector + ' #result').val()) ) ;
	return result;
}

(function($){
  $.fn.wrapMatch = function(count, className) {
    var length = this.length;
    for(var i = 0; i < length ; i+=count) {
      this.slice(i, i+count).wrapAll('<div '+((typeof className == 'string')?'class="'+className+'"':'')+'/>');
    }
    return this;
  };
})(jQuery);

(function($) {

$.fn.randomise = function(childElem) {
  return this.each(function() {
      var $this = $(this);
      var elems = $this.children(childElem);

      elems.sort(function() { return (Math.round(Math.random())-0.5); });

      $this.detach(childElem);

      for(var i=0; i < elems.length; i++)
        $this.append(elems[i]);

  });
}
})(jQuery);