var map;
var centerPoint;
var centerMarker;
var mapOptions;

String.prototype.trim = function ()
{
    return this.replace(/^\s+|\s+$/g, '');
}
function CheckForm(form)
{
	if (form.search_zip.value != "")
	{
		var validZipCode = (/\d{5}(-\d{4})?/);
		var gotIt = validZipCode.test(form.search_zip.value); 
		
		if(!gotIt)
		{
			alert('\"' + form.search_zip.value + "\" is not a valid zip code");                  
			form.search_zip.focus();
			return false;
		}
	}
	else
	{
		if (form.search_city.value == "")
		{
			alert("Please enter a city or zip code!");
			form.search_zip.focus();
			return false;
		}
		if(form.search_state.value== "")
		{
			alert("Please select a state!");
			form.search_state.focus();
			return false;
		}
	}
	return true;
}
function showhide(id)
{
	if (document.getElementById)
	{
		obj = document.getElementById(id);
		if (obj.style.display == "none")
		{
			obj.style.display = "";
		} 
		else
		{
			obj.style.display = "none";

		}
	}
}
function hideinfo() {
    if (!document.getElementsByTagName && !document.createElement && !document.createTextNode) return;
    var nodes = document.getElementsByTagName("span");
    for (var i = nodes.length - 1; i >= 0; i--) {
        if (nodes[i].className == "render_info") {
            var at = / at /;
            var dot = / dot /g;
            var node = document.createElement("a");
            var address = nodes[i].firstChild.nodeValue;

            address = address.replace(at, "@");
            address = address.replace(dot, ".");

            address = address.replace(at, "@");
            address = address.replace(dot, ".");
            node.setAttribute("href", "mailto:" + address);
            node.appendChild(document.createTextNode(address));

            node.setAttribute("class", "render_info");
            node.setAttribute("className", "render_info");

            var prnt = nodes[i].parentNode;
            for (var j = 0; j < prnt.childNodes.length; j++)
                if (prnt.childNodes[j] == nodes[i]) {
                    if (!prnt.replaceChild) return;
                    prnt.replaceChild(node, prnt.childNodes[j]);
                    break;
                }
        }
    }
}
function validateDate(fld) {

    var RegExPattern = "/^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/";
 //   var errorMessage = 'Please enter valid date as month, day, and four digit year.\nYou may use a slash, hyphen or period to separate the values.\nThe date must be a real date. 2-30-2000 would not be accepted.\nFormay mm/dd/yyyy.';
    if ((fld.value.match(RegExPattern)) && (fld.value!=''))
    {
        //alert('Date is OK'); 
        return true;
    }
    else
    {
        //alert(errorMessage);
        //fld.focus();
        return false;
    }
}

function toggleVehicleSearch() {
    $('#unit-sizes').hide();
    $('#sort-units').hide();
    $('#search-amenities').hide();
    $('#sort-vehicle-units').show();
}
function toggleUnitSearch() {
    $('#unit-sizes').show();
    $('#sort-units').show();
    $('#search-amenities').show();
    $('#sort-vehicle-units').hide();
}
function updateSearchText() {
    if (searchLocation != null && searchLocation.length > 0) {
        $('input#search_text').val(searchLocation);
    }
}
function updateSearchFields() {
    if (searchLocation != null && searchLocation.length > 0) {
        $('input#search_text').val(searchLocation);
    }
    if (searchType != null && searchType == "vehicle") {
        $('#radioUnit').attr('checked', false);
        $('#radioVehicle').attr('checked', true);

        if (orderVehicle != null) {
            var idVal = '#order_vehicle' + order;
            $(idVal).attr('checked', true);
        }

        toggleVehicleSearch();
    }
    else {

        $('#radioUnit').attr('checked', true);
        $('#radioVehicle').attr('checked', false);

        if (order != null) {
            var idVal = '#order_' + order;
            $(idVal).attr('checked', true);
        }

        if (sqft != null) {
            var sizes = [25, 50, 75, 100, 150, 200, 300];
            for (var i = 0; i < sizes.length; i++) {
                if (sqft == sizes[i]) {
                    var sizeName = '#size' + sqft;
                    $(sizeName).click();
                    break;
                }
            }
        }

        if (amenities != null && amenities.length > 0) {
            for (var i = 0; i < amenities.length; i++) {
                var curVal = amenities[i];
                idVal = '#amenities_' + curVal;
                $(idVal).click();
            }
        }

        toggleUnitSearch();
    }
}
function initializeQtips() {
    $('#amenities_climate_controlled').qtip({
        content: '<span class="qtip_bold">Climate Controlled Storage</span><br /><br />Heated and cooled storage units. Best for long-term storage or storing sensitive items such as musical instruments or electronics.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });
    $('#amenities_drive_up').qtip({
        content: '<span class="qtip_bold">Drive Up Access</span><br /><br />Units with exterior doors. These allow you to back your vehicle up to the unit for easier unloading when you move in.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });

    $('#amenities_twenty_four_hour_access').qtip({
        content: '<span class="qtip_bold">24 Hour Access</span><br /><br />These locations allow you to access your storage unit 24 hours a day, even when the office is closed.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });

    $('#size0').qtip({
        content: '<span class="qtip_bold">All Unit Sizes</span><br /><br />Search for all unit sizes. Recommended default search.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });

    $('#size25').qtip({
        content: '<span class="qtip_bold">5\' x 5\' Unit (25 ft&#178;).</span><br /><br />Small furniture &amp; boxes<br /><br />Size of small closet.<br />Good for chairs, cabinets, electronics, boxes.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });

    $('#size50').qtip({
        content: '<span class="qtip_bold">5\' x 10\' Unit (50 ft&#178;).</span><br /><br />1 bedroom apartment or studio<br /><br />Size of large walk-in closet.<br />Good for mattress set, couch, dining room tables, chairs, boxes.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });

    $('#size75').qtip({
        content: '<span class="qtip_bold">5\' x 15\' Unit (75 ft&#178;).</span><br /><br />1 bedroom apartment<br /><br />Size of small bedroom.<br />Good for large dining sets, desks, bainets, mattress set, washer/dryder.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });

    $('#size100').qtip({
        content: '<span class="qtip_bold">10\' x 10\' Unit (100 ft&#178;).</span><br /><br />2 bedroom apartment<br /><br />Size of a large bedroom.<br />Good for bedroom sets, refrigerator, large drawers, multiple boxes.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });

    $('#size150').qtip({
        content: '<span class="qtip_bold">10\' x 15\' Unit (150 ft&#178;).</span><br /><br />2-3 bedroom house or large apartment<br /><br />Size of small one car garage. Good for multiple bedroom sets, large appliances, smaller cars, boats, other vehicles, patio sets.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });

    $('#size200').qtip({
        content: '<span class="qtip_bold">10\' x 20\' Unit (200 ft&#178;).</span><br /><br />4 bedroom house or full garage<br /><br />Size of standard one car garage. Good for multiple bedroom sets, trucks, trailers, large furniture items, mid-size vehicles, misellaneous items.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });

    $('#size300').qtip({
        content: '<span class="qtip_bold">10\' x 30\' Unit (300 ft&#178;).</span><br /><br />5 bedroom house, large items<br /><br />Size of two car garages. Good for multiple bedroom sets, appliances, large furniture, patio sets, seasonal items.',
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            },
            adjust: { x: 3 }
        },
        style: {
            border: {
                width: 4,
                color: '#b85555'
            },
            padding: 10,
            background: '#F2F2F2',
            lineHeight: '16px',
            fontSize: '13px'
        }
    });
}

function initializeSearch() {

    initializeQtips();

    if (initializeMap != undefined && initializeMap == true) {
        jQuery('#map-container').show();
        $('.sf_facility_listings tr').click(function () {
            var href = $(this).find("a").attr("href");
            if (href) {
                window.location = href;
            }
        });

        initGoogleMap();
    }
    else {
        jQuery('#map-container').hide();
    }

    jQuery('#search-preloader').hide();
}

function initializeSearchNoQtip() {
    if (initializeMap != undefined && initializeMap == true) {
        jQuery('#map-container').show();
        $('.sf_facility_listings tr').click(function () {
            var href = $(this).find("a").attr("href");
            if (href) {
                window.location = href;
            }
        });

        initGoogleMap();
    }
    else {
        jQuery('#map-container').hide();
    }

    jQuery('#search-preloader').hide();
}
function initGoogleMap() {

    mapOptions = {
        zoom: 8,
        scrollwheel: false,
        mapTypeControl: false,
        navigationControl: { style: google.maps.NavigationControlStyle.DEFAULT },
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    centerPoint = new google.maps.LatLng(centerLatitude, centerLongitude);
    map.setCenter(centerPoint);

    var centerIcon = new google.maps.MarkerImage(CONFIG.baseUri + "/images/global/map-markers/location-marker.png", new google.maps.Size(19, 19), new google.maps.Point(0, 0), new google.maps.Point(0, 0));

    centerMarker = new google.maps.Marker({
        position: centerPoint,
        icon: centerIcon,
        map: map,
        title: searchLocation,
        zIndex: 100
    });

    var points = [];

    if (listings != null) {
        for (var i = 0; i < listings.length; i++) {
            points[i] = new google.maps.LatLng(listings[i].latitude, listings[i].longitude);
            markers[i] = createGoogleMapMarker(points[i], i);
            markers[i].setMap(map);
        }

        if (points.length > 0) {
            map.fitBounds(getBoundsForLatLngsSF(points, centerPoint));
        }
    }

    google.maps.event.addListener(map, 'bounds_changed', function () {
        $('#infobox').remove();
    });

}

function createGoogleMapMarker(point, index, markerTitle) {
    var baseImage = CONFIG.baseUri + "/images/global/map-markers/red-pin.png";
    var hoverImage = CONFIG.baseUri + "/images/global/map-markers/green-pin.png";
    var shadowIcon = new google.maps.MarkerImage(CONFIG.baseUri + "/images/global/map-markers/marker-shadow.png", new google.maps.Size(30, 24), new google.maps.Point(0, 0), new google.maps.Point(5, 23));

    var marker = new google.maps.Marker({
        position: point,
        icon: createMarkerIconSF(false, index),
        shadow: shadowIcon,
        zIndex: 200 - index
    });

    google.maps.event.addListener(marker, 'click', function () {
        for (var i = 0; i < listings.length; i++) {
            //infoWindows[i].close();
            markers[i].setZIndex(200 - index);
            markers[i].setIcon(createMarkerIconSF(false, i));
        }
        $(".search-listing-facility-details").removeClass("selected");
        $("div[id='" + (index + 1) + "'] .search-listing-facility-details").addClass("selected");
        //infoWindows[index].open(map,marker);
        marker.setZIndex(210 + index);
        marker.setIcon(this, createMarkerIconSF(true, index));
        //$('div.info-window-container-'+index).parent().css('overflow-y','hidden');

        $('#infobox').remove();
        showInfoBoxSF(marker, index);
    });

    google.maps.event.addListener(marker, 'mouseover', function () {
        if (!$("div[id='" + (index + 1) + "'] .search-listing-facility-details").hasClass("selected")) {
            marker.setZIndex(200 + index);
            marker.setIcon(createMarkerIconSF(true, index));
        }
        //swap the image in the search listing
        $("#" + (index + 1) + " img.search-listing-map-marker").attr("src", hoverImage);

    });

    google.maps.event.addListener(marker, 'mouseout', function () {
        if (!$("div[id='" + (index + 1) + "'] .search-listing-facility-details").hasClass("selected")) {
            marker.setZIndex(200 - index);
            marker.setIcon(createMarkerIconSF(false, index));
        }
        //swap the image in the search listing
        $("#" + (index + 1) + " img.search-listing-map-marker").attr("src", baseImage);
    });

    return marker;
}

function getBoundsForLatLngsSF(latLngs, centerLatLng) {

    var bounds = new google.maps.LatLngBounds;
    for (var i = 0; i < latLngs.length; i++) {
        bounds.extend(latLngs[i]);
    }
    bounds.extend(centerLatLng);
    return bounds;
}
function createMarkerIconSF(hover, index) {

    var image;

    if (hover) {
        image = CONFIG.baseUri + "/images/global/map-markers/green-pin.png";
    } else {
        image = CONFIG.baseUri + "/images/global/map-markers/red-pin.png";
    }

    var icon = new google.maps.MarkerImage(image, new google.maps.Size(30, 42), new google.maps.Point(0, 0), new google.maps.Point(15, 42));

    return icon;
}
function showInfoBoxSF(marker, index) {
    var map = marker.getMap();
    var bounds = map.getBounds();
    if (!bounds) return;

    // The degrees per pixel
    var mapDiv = map.getDiv();
    var mapWidth = mapDiv.offsetWidth;
    var mapHeight = mapDiv.offsetHeight;
    var boundsSpan = bounds.toSpan();
    var longSpan = boundsSpan.lng();
    var latSpan = boundsSpan.lat();
    var degPixelX = longSpan / mapWidth;
    var degPixelY = latSpan / mapHeight;

    // find the difference between the marker and the top of the map (in pixels)
    var diffPixelY = (bounds.getNorthEast().lat() - marker.getPosition().lat()) / degPixelY;

    // find the difference between the marker and the left side of the map (in pixels)
    var diffPixelX = (marker.getPosition().lng() - bounds.getSouthWest().lng()) / degPixelX;

    var div = document.createElement("div");
    $(div).css('top', (diffPixelY - 20) + 'px');
    $(div).css('margin-left', (diffPixelX - 20) + 'px');
    $(div).attr('id', 'infobox');

    $(div).append('<img src="http://www.google.com/intl/en_us/mapfiles/close.gif" class="close-button" />');
    $(div).append($('#infowindow-' + index).clone());

    $('#map-container').append(div);

    $('#infobox img.close-button').click(function () {
        $('#infobox').remove();
    });
}
