// JavaScript Document
//name space for search Results = psui.searchResults
YAHOO.namespace("ps.searchResults");
//global alias for root namespace defined in ps	-ui.js
var psui = YAHOO.ps;
var pslog = YAHOO.log;
psui.globals['reserveUnitCount'] =0;
//Get the reservation days
var strMaxReservationDays="";
var MaxReservationDays = "";
//global object to hold the calendar button
psui.calendarButton = null;
//page configuration object
psui.searchResults.pageConfig = {};
psui.searchResults.helpDivRendered = false;
//array to hold the accordion Panal Ids
psui.searchResults.arrAccordionPanelId = new Array;

//array Marketing Codes for content display
psui.searchResults.arrLookupSizeCode = new Array;
/****************************
psui.searchResults.arrLookupSizeCode['FiveByFive'] = "<img class=\"sizeIcon\" src=\"images/icon_5x5.gif\"><span class=\"sizeText\">5'x5'</span><span class=\"displayNone\">area:25sqft</span>";
psui.searchResults.arrLookupSizeCode['FiveByTen'] = "<img class=\"sizeIcon\" src=\"images/icon_10x5.gif\"><span class=\"sizeText\">5'x10'</span><span class=\"displayNone\">area:50sqft</span>";
psui.searchResults.arrLookupSizeCode['FiveByFifteen'] = "<img class=\"sizeIcon\" src=\"images/icon_10x5.gif\"><span class=\"sizeText\">5'x15'</span><span class=\"displayNone\">area:75sqft</span>";
psui.searchResults.arrLookupSizeCode['TenByTen'] = "<img class=\"sizeIcon\" src=\"images/icon_10x10.gif\"><span class=\"sizeText\">10'x10'</span><span class=\"displayNone\">area:100sqft</span>";
psui.searchResults.arrLookupSizeCode['TenByFifteen'] = "<img class=\"sizeIcon\" src=\"images/icon_10x10.gif\"><span class=\"sizeText\">10'x15'</span><span class=\"displayNone\">area:150sqft</span>";
psui.searchResults.arrLookupSizeCode['TenByTwenty'] = "<img class=\"sizeIcon\" src=\"images/icon_10x20.gif\"><span class=\"sizeText\">10'x20'</span><span class=\"displayNone\">area:200sqft</span>";
psui.searchResults.arrLookupSizeCode['TenByTwentyFive'] = "<img class=\"sizeIcon\" src=\"images/icon_10x25.gif\"><span class=\"sizeText\">10'x25'</span><span class=\"displayNone\">area:250sqft</span>";
psui.searchResults.arrLookupSizeCode['TenByThirty'] = "<img class=\"sizeIcon\" src=\"images/icon_10x30.gif\"><span class=\"sizeText\">10'x30'</span><span class=\"displayNone\">area:300sqft</span>";
****************************/
psui.searchResults.arrWeekdayCode = new Array;
psui.searchResults.arrWeekdayCode[0] = 'M-F: ';
psui.searchResults.arrWeekdayCode[1] = 'Sat: ';
psui.searchResults.arrWeekdayCode[2] = 'Sun: ';
//current implementation has the backend rendering the JSON string into a variable 	psui.searchResults.JSONResponseString 
//future modification would allow for asychronous request of psui.searchResults.JSONResponseString from backend.
psui.searchResults.init = function() {
	if(psui.searchResults.JSONResponseString.length > 0) {
		psui.searchResults.queryResultData = YAHOO.lang.JSON.parse(psui.searchResults.JSONResponseString );
		psui.searchResults.queryResponse = psui.searchResults.queryResultData.SearchResponse;
		psui.searchResults.queryMessage = psui.searchResults.queryResultData.Message;
		psui.searchResults.queryType = psui.searchResults.queryResultData.SearchType;
		if(psui.searchResults.queryResponse.toUpperCase() == 'FAILURE') {
			psui.searchResults.strErrorMessage = psui.searchResults.queryMessage;
			if(!(psui.searchResults.strErrorMessage=='')) {
				//display error only if the error message is not blank
				psui.searchResults.errorMessage();
			}
		} else {
			psui.searchResults.renderPage();
		}
	} else {
 	    //response string not populate
	    // These lines should remain commented out as these error messages are in the backend code.
		// psui.searchResults.strErrorMessage = 'No Data Available';
		// psui.searchResults.errorMessage();
}

};

//function to render error Message
psui.searchResults.errorMessage = function() {
	(document.getElementById('my-dl')).innerHTML = '<div class="error">'+psui.searchResults.strErrorMessage+'</div>';
}

//initialize all objects needed for the search results page
psui.searchResults.renderPage = function() {
    //alert('render page');
    psui.searchResults.queryResultData = YAHOO.lang.JSON.parse(psui.searchResults.JSONResponseString);
    psui.searchResults.queryResponse = psui.searchResults.queryResultData.SearchResponse;
    var singleSite;
    if (psui.searchResults.queryType == "Site") {
        singleSite = true;
    } else if (psui.searchResults.queryType == "All") {
        singleSite = false;
    }
    //retrieve the unique Distance Segments from the data structure
    psui.searchResults.arrDistanceSegments = new Array();
    //retrieve the unique SiteIds from the data structure;
    psui.searchResults.arrSiteIds = new Array();

    var indexDistanceSegments = 0;
    var iter = 0;
    //this loop retrieves all distance from origin values into an array arrDistanceSegments
    //variables used within the body of the while loop
    var strMoreInfoLink = "";
    var strFeatures = "";
    var strSpecialOffers = "";
    while (iter < psui.searchResults.queryResultData.Sizes.length) {

        psui.searchResults.arrDistanceSegments[psui.searchResults.arrDistanceSegments.length] = parseFloat(psui.searchResults.queryResultData.Sizes[iter].DistanceFromOrigin);
        //populate SiteIds
        psui.searchResults.arrSiteIds[psui.searchResults.arrSiteIds.length] = psui.searchResults.queryResultData.Sizes[iter].SiteId;
        //format the features object for presentation
        strMoreInfoLink = "storage-details.aspx?";
        strMoreInfoLink += "SiteNumber=" + psui.searchResults.queryResultData.Sizes[iter].SiteNumber + "&SiteId=" + psui.searchResults.queryResultData.Sizes[iter].SiteId + "&SizeId=" + psui.searchResults.queryResultData.Sizes[iter].SizeId + "&WidthxLength=" + psui.searchResults.queryResultData.Sizes[iter].WidthxLength;

        strMaxReservationDays = psui.searchResults.queryResultData.Sizes[iter].MaxReservationDays;

        var hasLongTermRentDiscount = false;
        //format the Special Offers
        strSpecialOffers = '<ul class="featuresBullets">';
        for (offerIter = 0; offerIter < psui.searchResults.queryResultData.Sizes[iter].Promotions.length; offerIter++) {

            if (psui.searchResults.queryResultData.Sizes[iter].Promotions[offerIter] == 'Long Term Rent Discount') {
                hasLongTermRentDiscount = true;
                strSpecialOffers = strSpecialOffers + '<li style="color:#ff6600">Stay 3 Mo. Or More - Save $$</li>';
            }
            else {
                strSpecialOffers = strSpecialOffers + '<li>' + psui.searchResults.queryResultData.Sizes[iter].Promotions[offerIter] + '</li>';
            }
        }
        strSpecialOffers += '</ul>';
        psui.searchResults.queryResultData.Sizes[iter].Promotions = strSpecialOffers;

        strFeatures = '<table class="search_results_features" cellpadding="0" cellspacing="0"><tr><td nowrap>';
        strFeatures += '<ul class="featuresBullets">';  //<div class="tableCellFeatures"><div class="featuresListContainer">
        for (featIter = 0; featIter < psui.searchResults.queryResultData.Sizes[iter].Features.length; featIter++) {
            strFeatures = strFeatures + '<li>' + psui.searchResults.queryResultData.Sizes[iter].Features[featIter] + '</li>';
        }
        //strFeatures += '</ul><div style="padding-bottom:6px;"><a href="' + strMoreInfoLink + '">Show Details</a>'; //</div></div>
        strFeatures += '</ul><div style="padding-bottom:6px;padding-left:25px;"><a href="javascript:;" id="showhideMoreLink_' + psui.searchResults.queryResultData.Sizes[iter].SiteId + '_' + psui.searchResults.queryResultData.Sizes[iter].SizeId + '" onclick="location_details_info_toggle(' + psui.searchResults.queryResultData.Sizes[iter].SiteId + ', ' + psui.searchResults.queryResultData.Sizes[iter].SizeId + ', this)">Show Details</a>'; //</div></div>

        var navigateTo = 'checkout.aspx';

        strFeatures += '</td><td>';

        strFeatures += '<table class="search_results_button_group"><tr><td><a href="' + navigateTo + '" onclick="saveState(psui.searchResults.arrSiteIds[' + iter + '], psui.searchResults.queryResultData.Sizes[' + iter + '].SizeId); return addUnit(psui.searchResults.queryResultData.Sizes[' + iter + ']);"><img src="images/spacer.gif" alt="Rent Now" class="searchBtnRentNow"></a></td><td><a class="showRentHelpLink"><img src="images/spacer.gif" title="What is this?"  onclick="rentHelpClick(this);" class="searchBtnQuestion searchBtnQuestion_rent" /></a></td></tr><tr><td align="center" colspan="2" style="padding-bottom:4px;"><span style="font-size:7pt;">or</span></td></tr><tr><td><a href="' + navigateTo + '" onclick="saveState(psui.searchResults.arrSiteIds[' + iter + '], psui.searchResults.queryResultData.Sizes[' + iter + '].SizeId); return holdForLater(psui.searchResults.queryResultData.Sizes[' + iter + '])"><img src="images/spacer.gif" alt="Hold" class="searchBtnHold" /></a></td><td><a class="showReserveHelpLink"><img src="images/spacer.gif" title="What is this?" onclick="reserveHelpClick(this);" class="searchBtnQuestion searchBtnQuestion_hold" /></a></td></tr></table>';

        strFeatures += '</td></tr>';
        strFeatures += '</table>';
        psui.searchResults.queryResultData.Sizes[iter].Features = strFeatures;
        //format Monthly Rate
        if (hasLongTermRentDiscount) {
            //var discountedPrice = psui.searchResults.queryResultData.Sizes[iter].OriginalRent * 0.95;
            psui.searchResults.queryResultData.Sizes[iter].MonthlyRent = '<font style="color:black">' + '<strike>$' + psui.searchResults.queryResultData.Sizes[iter].OriginalRent.toFixed(2) + '</strike>' + '</font>' + '<BR/><font style="color:#ff6600">$' + psui.searchResults.queryResultData.Sizes[iter].MonthlyRent.toFixed(2) + '</font>';
        }
        else {
            psui.searchResults.queryResultData.Sizes[iter].MonthlyRent = '<font style="color:black">' + '$' + psui.searchResults.queryResultData.Sizes[iter].MonthlyRent.toFixed(2) + '</font>';
        }

        //format width x length
        var strWidthxLength = psui.searchResults.arrLookupSizeCode[psui.searchResults.queryResultData.Sizes[iter].WidthxLength];

        var strIn = psui.searchResults.queryResultData.Sizes[iter].WidthxLength;
        //alert('string to parse: ' + strIn);
        //replace all occurances of "\u0027" globally ( that is the /g option in the regexp
        //we are applying a regular expression to search for all occurances of the target string with an empty string.
        var strIn = strIn.replace(/\u0027/g, "")
        //you can reuse this to remove different string patterns.
        //alert('string with apostrophe characters removed: ' + strIn);

        //now we want to split the string into the length and width parts....
        //we are expecting an "x" to delimit the two parts so we split the string at the x
        // the split method returns an array of string parts split by the x.
        var arrStringTokens = strIn.split("x");
        //alert('first part of string split at "x" = : ' + arrStringTokens[0]);
        //alert('second part of string split at "x" = : ' + arrStringTokens[1]);
        var width = parseInt(arrStringTokens[0]);
        var length = parseInt(arrStringTokens[1]);
        //alert('the parsed width and length are: width='+width+' length='+length);
        var area = width * length;
        //alert('the area calculated = '+area);

        var availableIcons = ['5x5', '5x10', '5x15', '10x10', '10x15', '10x20', '10x25', '10x30'];
        var iconSize = psui.searchResults.queryResultData.Sizes[iter].WidthxLength.replaceAll("'", "").replaceAll(" ", "").toLowerCase();
        var iconFile = "5x15"; //default
        for (var iter2 = 0; iter2 < availableIcons.length; iter2++) {
            if (availableIcons[iter2] == iconSize) {
                iconFile = iconSize;
                break;
            }
        }
        strWidthxLength = '<img class=\"sizeIcon\" src=\"images/icon_' + iconFile + '.gif\"><div style="clear:both;text-align:center"><span class=\"sizeText\">' + psui.searchResults.queryResultData.Sizes[iter].WidthxLength + '</span>' + '<span class=\"displayNone\">area:' + area + 'sqft</span></div>';
        if (typeof (strWidthxLength) != 'undefined') {
            psui.searchResults.queryResultData.Sizes[iter].WidthxLength = strWidthxLength;
        }
        iter = iter + 1;
    };
    //alert('end while');
    //important to sort array first so that we can remove duplicates
    //commenting sort function because json result data will always be returned in the correct sort order
    //psui.searchResults.arrDistanceSegments.sort();
    // arrDistanceSegments now contains a unique and sorted list of the distance segments
    // the .unique method is a non standard extension of the array object..it is defined at the top of this script
    psui.searchResults.arrDistanceSegments = psui.searchResults.arrDistanceSegments.unique();
    psui.searchResults.arrSiteIds = psui.searchResults.arrSiteIds.unique();
    //alert(psui.searchResults.arrSiteIds);
    //we now know how many segment panels we have to create
    //each segment panel is going to need its own datatable object
    //column definition that all datatables share

    psui.searchResults.sortBySize = function(a, b, desc) {
        //alert('sort by size');
        if (!YAHOO.lang.isValue(a)) {
            return (!YAHOO.lang.isValue(b)) ? 0 : 1;
        }
        else if (!YAHOO.lang.isValue(b)) {
            return -1;
        }

        var nodeA = a.getData("WidthxLength");
        nodeA = parseInt(nodeA.slice(nodeA.indexOf('area:') + 5, nodeA.indexOf('sqft')));

        var nodeB = b.getData("WidthxLength");
        nodeB = parseInt(nodeB.slice(nodeB.indexOf('area:') + 5, nodeB.indexOf('sqft')));

        var compareResult = YAHOO.util.Sort.compare(nodeA, nodeB, desc);
        //alert('A: '+nodeA+' B: '+nodeB+' result: '+compareResult);
        return compareResult;
    }

    psui.searchResults.sortByMonthlyRent = function(a, b, desc) {
        //alert('sort by size');
        if (!YAHOO.lang.isValue(a)) {
            return (!YAHOO.lang.isValue(b)) ? 0 : 1;
        }
        else if (!YAHOO.lang.isValue(b)) {
            return -1;
        }

        var nodeA = a.getData("MonthlyRent");
        nodeA = nodeA.match(/\$[0-9.]*<\/font/ig) + '';
        nodeA = parseFloat(nodeA.replace(/<\/font/ig, '').replace(/\$/ig, ''));

        var nodeB = b.getData("MonthlyRent");
        nodeB = nodeB.match(/\$[0-9.]*<\/font/ig) + '';
        nodeB = parseFloat(nodeB.replace(/<\/font/ig, '').replace(/\$/ig, ''));

        var compareResult = YAHOO.util.Sort.compare(nodeA, nodeB, desc);
        //alert('A: '+nodeA+' B: '+nodeB+' result: '+compareResult);
        return compareResult;
    }

    var myColumnDefs = [
		{ key: "WidthxLength", label: "Size", sortable: true, resizeable: false, sortOptions: { sortFunction: psui.searchResults.sortBySize} },
        { key: "MonthlyRent", label: "Monthly Rate", sortable: true, resizeable: false, sortOptions: { sortFunction: psui.searchResults.sortByMonthlyRent} },
    //{ key: "MonthlyRent", label: "Monthly Rate", sortable: true, resizeable: false, formatter: YAHOO.widget.DataTable.formatCurrency },
		{key: "Promotions", label: "Special Offer", sortable: true, resizeable: false },
		{ key: "Features", label: "Features", sortable: false, resizeable: false }
	];
    var myConfigs = {
        paginated: false, // Enables built-in client-side pagination
        paginator: { // Configurable options
            containers: null, // Create container DIVs dynamically
            currentPage: 1, // Show page 1
            dropdownOptions: [10, 25, 50], // Show these in the rows-per-page dropdown
            pageLinks: 0, // Show links to all pages
            rowsPerPage: 10 // Show up to 500 rows per page
        },
        sortedBy: { key: "WidthxLength", dir: "asc" }
    };
    //array to hold all data table objects
    var arrDataTableObjects = new Array;
    //array to hold all our dataSource objects which are subsets of the larger data segmented by distance
    var arrDataSources = new Array;
    //array to hold JS Array which is subest of larger JS array segmented by distance
    // the JS Array will be the basis for the dataSource objects to be created hele by the array above
    var arrDataArray = new Array;

    //this loop segments the Large JSON data array into subsets based on the unique distance segments.
    //future...this loop can be revisited to make more efficient.  currently looping N * M times
    // N = number of unique distance
    // M = size of complete JSON dataset
    //possibly can change to loop M times with conditionals for assignments to data arrays

    /*for(indexIter=0;indexIter<psui.searchResults.arrDistanceSegments.length;indexIter++) {
    arrDataArray[indexIter] = new Array;
    var iter=0;
    while(iter<psui.searchResults.queryResultData.Sizes.length) {
			
    if(psui.searchResults.arrDistanceSegments[indexIter] == psui.searchResults.queryResultData.Sizes[iter].DistanceFromOrigin)
    {
    arrDataArray[indexIter][arrDataArray[indexIter].length] = psui.searchResults.queryResultData.Sizes[iter];
    }
    iter=iter+1;
    };
    }*/

    for (indexIter = 0; indexIter < psui.searchResults.arrSiteIds.length; indexIter++) {
        //alert('forloop');
        
        arrDataArray[indexIter] = new Array;
        var iter = 0;
        while (iter < psui.searchResults.queryResultData.Sizes.length) {

            if (psui.searchResults.arrSiteIds[indexIter] == psui.searchResults.queryResultData.Sizes[iter].SiteId) {
                arrDataArray[indexIter][arrDataArray[indexIter].length] = psui.searchResults.queryResultData.Sizes[iter];
            }
            iter = iter + 1;
        };
    }
    //we are building the accordian sections dynamically. for maintanbility, this variable holds a html snippet template with
    //place holders for elements to be populated later.
    //if there is a need to change html for the accordian segments, developer can maintain here in one place
    var htmlDt = '<dt class="a-m-t" id="#DT_ID#"><div style="display:inline;float:left;"><div class="results-location"><strong id="distance2">#DISTANCE# mi</strong><span class="addressText">#ADDRESS_TEXT#</span><!--<span class="viewMapOverlay"> | <a href="#VIEW_MAP_LINK#" id="#TT_ID#" onmouseover="showMap(this, #LAT#,#LONG#,\'#MAP_DIV_ID#\');" onmouseout="hideMap(this);">View Map &amp; Hours</a></span>--></div></div><div style="float:right;padding-top:10px;display:inline;font-size:.9em;"><img src="images/search_details_show_orange.gif" onclick="location_details_toggle(#SITE_ID#);" id="location_details_#SITE_ID#" class="location_details_#RESULT_INDEX#"/><img src="images/search_units_show_orange.gif" onclick="location_units_toggle(\'#DT_ID#\',\'#RESULT_INDEX#\');" id="location_units_#RESULT_INDEX#" class="location_units_click site_id_#SITE_ID#" /></div></dt>';
    htmlDt += '<dd class="a-m-d-details placeHolder" id="dd_details_#SITE_ID#" style="display:none"><div>INFO</div></dd>';
    var htmlPrintView = '<div class="locationHours printMedia"><table border="0"><tr><td>#OFFICE_HOURS#</td><td>#ACCESS_HOURS#</td></tr></table></div>';

    var htmlMoreResultsLink = '';
    if (!singleSite) {
        //htmlMoreResultsLink ='<div class="moreResultsLink"><a href="storage-search.aspx?SearchType=Site&SiteId=#SITE_ID#&Lat=#QUERY_LAT#&Long=#QUERY_LONG#&Location=#QUERY_LOCATION#&Radius=0">Display More Results</a></div>'; 
        htmlMoreResultsLink = '<div class="moreResultsLink"><a onmouseover="psui.searchResults.reCreateQuery(this)" href=""><form name="siteUrl" class="hidden"> <input type="hidden" name="siteUrlInput"  value="storage-search.aspx?SearchType=Site&SiteId=#SITE_ID#&Location=#QUERY_LOCATION#&Radius=0" /></form>Display More Results</a></div>';
    }

    var htmlDd = '<dd class="a-m-d" id="#DD_ID#">' + htmlPrintView + '<div id="#DATATABLE_ID#"></div>' + htmlMoreResultsLink + '</dd>';
    var htmlAccordianDivTemplate = htmlDt + htmlDd;
    var htmlDdWithOutDisplayLink = '<dd class="a-m-d" id="#DD_ID#">' + htmlPrintView + '<div id="#DATATABLE_ID#"></div></dd>';
    var htmlAccordianDivTemplateWithOutDisplayLink = htmlDt + htmlDdWithOutDisplayLink;
    var htmlMapToolTipTemplate = '<div class="mapOverlayContainer"><div class="mapImage" id="#MAP_ID#">#MAP#</div><div class="officeHours">#OFFICE_HOURS#</div><div class="accessHours">#ACCESS_HOURS#</div></div>';

    //variable to hold the innerHTML of the accordian div
    var accordianInnerHtml = "";
    var accordianInnerHtmlWithOutDisplayLink = "";

    //array of the panel Ids.
    var arrToolTipObjects = new Array;
    psui.searchResults.arrToolTipContent = new Array;
    //for loop to build accordian menu sections in the DOM
    for (indexIter = 0; indexIter < psui.searchResults.arrSiteIds.length; indexIter++) {
        setTimeout('myShowFunction()', 100); setTimeout('myShowFunction()', 600);
        var strDtId = "dt" + indexIter;
        var strTtId = "tt" + indexIter;
        var strLat = arrDataArray[indexIter][0].Address[5];
        var strLong = arrDataArray[indexIter][0].Address[6];
        var strSiteId = arrDataArray[indexIter][0].SiteId;
        if (indexIter == 0) {
            psui.searchResults.firstSiteId = strSiteId;
        }
        psui.searchResults.arrAccordionPanelId[psui.searchResults.arrAccordionPanelId.length] = strDtId;
        var strDdId = "dd" + indexIter;

        if (arrDataArray[indexIter][0].HasMoreResults == true) {
            var strTemp = htmlAccordianDivTemplate;
        }
        else {
            var strTemp = htmlAccordianDivTemplateWithOutDisplayLink;
        }

        //convert distance to fixed 2 decimal point places
        var strDistance = (arrDataArray[indexIter][0].DistanceFromOrigin).toFixed(2);
        var strOfficeHours = '<span class="officeHoursHdr">Office Hours:</span><br />';
        for (iterOH = 0; iterOH < arrDataArray[indexIter][0].OfficeHours.length; iterOH++) {
            strOfficeHours = strOfficeHours + psui.searchResults.arrWeekdayCode[iterOH] + arrDataArray[indexIter][0].OfficeHours[iterOH] + '<br />';
        }
        var strAccessHours = '<span class="accessHoursHdr">Tenant Access Hours:</span><br />';
        for (iterOH = 0; iterOH < arrDataArray[indexIter][0].GateHours.length; iterOH++) {
            strAccessHours = strAccessHours + psui.searchResults.arrWeekdayCode[iterOH] + arrDataArray[indexIter][0].GateHours[iterOH] + '<br />';
        }
        var strMap = "";
        var strMapId = "map" + indexIter;
        var strAddress = arrDataArray[indexIter][0].Address[0] + arrDataArray[indexIter][0].Address[1] + ", " + arrDataArray[indexIter][0].Address[2] + ", " + arrDataArray[indexIter][0].Address[3] + " " + arrDataArray[indexIter][0].Address[4];
        var strDataTableId = "dataTable" + indexIter;

        //replace the template placeholders with the correct strings and IDs
        strTemp = strTemp.replace('#INDEX#', indexIter);
        strTemp = strTemp.replace('#INDEX#', indexIter);
        strTemp = strTemp.replaceAll('#DT_ID#', strDtId);
        strTemp = strTemp.replace('#TT_ID#', strTtId);
        strTemp = strTemp.replace('#DD_ID#', strDdId);
        strTemp = strTemp.replace('#DISTANCE#', strDistance);
        strTemp = strTemp.replace('#ADDRESS_TEXT#', initial_caps(strAddress));
        strTemp = strTemp.replace('#DATATABLE_ID#', strDataTableId);
        strTemp = strTemp.replace('#MAP_DIV_ID#', strMapId);
        strTemp = strTemp.replace('#LAT#', strLat);
        strTemp = strTemp.replace('#LONG#', strLong);
        strTemp = strTemp.replaceAll('#SITE_ID#', strSiteId);
        strTemp = strTemp.replace('#QUERY_LAT#', strLat);
        strTemp = strTemp.replace('#QUERY_LONG#', strLong);
        strTemp = strTemp.replace('#QUERY_LOCATION#', strAddress);
        strTemp = strTemp.replace('#OFFICE_HOURS#', strOfficeHours);
        strTemp = strTemp.replace('#ACCESS_HOURS#', strAccessHours);
        strTemp = strTemp.replaceAll('#RESULT_INDEX#', indexIter); // JPL

        accordianInnerHtml = accordianInnerHtml + strTemp;

        strTemp = htmlMapToolTipTemplate;
        strTemp = strTemp.replace('#MAP_ID#', strMapId);
        strTemp = strTemp.replace('#MAP#', strMap);
        strTemp = strTemp.replace('#OFFICE_HOURS#', strOfficeHours);
        strTemp = strTemp.replace('#ACCESS_HOURS#', strAccessHours);
        psui.searchResults.arrToolTipContent[indexIter] = strTemp;

    }
    //populate the DOM with accordian menu
    //IMPORTANT this sequence must happen first,
    //DOM must be updated before we assign datatable objects into their containing divs.
    (document.getElementById('my-dl')).innerHTML = accordianInnerHtml;

    YAHOO.util.Event.onDOMReady(function() {
        //create datatable objects when the Dom is ready
        //and associate them with their data sources and display divs in the DOM.
        for (indexIter = 0; indexIter < psui.searchResults.arrSiteIds.length; indexIter++) {
            var strTtId = "tt" + indexIter;
            var strDataTableId = "dataTable" + indexIter;
            arrDataSources[indexIter] = new YAHOO.util.DataSource(arrDataArray[indexIter]);
            arrDataSources[indexIter].responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
            arrDataSources[indexIter].responseSchema = { fields: ["WidthxLength", "MonthlyRent", "Promotions", "Features"] };
            arrDataTableObjects[indexIter] = new YAHOO.widget.DataTable(strDataTableId, myColumnDefs, arrDataSources[indexIter], myConfigs);
        }
        if (psui.searchResults.arrSiteIds.length == 1) {
            // lastly we expand the first section of the accordian
            //YAHOO.util.Dom.addClass("dt0", "a-m-t-expand");
            //YAHOO.util.Dom.addClass("dd0", "a-m-d-expand");
            location_units_toggle('dt0', '0');
        }
        if (getURLParam('ra') == '1') {
            restoreAccordionCache();
        }

        // JPL
        //var location_details = YAHOO.util.Dom.get('location_details_' + psui.searchResults.firstSiteId);
        //var location_details = YAHOO.util.Dom.getElementsByClassName('location_details_0')[0];
        //location_details.src = 'images/search_details_show_white.png';
        //var location_units = YAHOO.util.Dom.get('location_units_0');
        //location_units.src = 'images/search_units_hide_white.png';

    });
    psui.searchResults.renderDropDowns();
}

function expandAllPanels() {
	//for(indexIter=0;indexIter<psui.searchResults.arrAccordionPanelId.length;indexIter++) {
	//	//explicitly setting the class vs using the animated opening.
	//	YAHOO.util.Dom.addClass("dt"+indexIter,"a-m-t-expand");
	//	YAHOO.util.Dom.addClass("dd"+indexIter,"a-m-d-expand");
    //}
    var items = YAHOO.util.Dom.getElementsByClassName('location_units_click');
    for (var i = 0; i < items.length; i++) {
        if (items[i].src.indexOf('show') > -1) {
            location_units_toggle('dt' + i, i + '');
        }
    }
};
function closeAllPanels() {
	//for(indexIter=0;indexIter<psui.searchResults.arrAccordionPanelId.length;indexIter++) {
	//	YAHOO.util.Dom.removeClass("dt"+indexIter,"a-m-t-expand");
	//	YAHOO.util.Dom.removeClass("dd"+indexIter,"a-m-d-expand");
    //}
    var items = YAHOO.util.Dom.getElementsByClassName('location_units_click');
    for (var i = 0; i < items.length; i++) {
        if (items[i].src.indexOf('hide') > -1) {
            location_units_toggle('dt' + i, i + '');
        }
    }
};

function openPanelById(panelId) {
	closeAllPanels();
	AccordionMenu.openDtById(panelId);
};
function showMap(obj, lat, long, divId) {
	var grandParentNodeId = obj.parentNode.parentNode.parentNode.id;
	YAHOO.util.Dom.removeClass(grandParentNodeId,"a-m-t");
	YAHOO.util.Dom.addClass(grandParentNodeId,"a-m-t-atr");
	psui.searchResults.mapOverlay = new YAHOO.widget.Overlay("mapToolTip");
	var mapOverlay = psui.searchResults.mapOverlay;
	var coordinates = YAHOO.util.Dom.getXY(obj);
	coordinates[0] = coordinates[0] + 100;
	coordinates[1] = coordinates[1] - 20;
	var indexContent = parseInt((obj.id).replace('tt',''));
	mapOverlay.cfg.setProperty("xy", coordinates);
	mapOverlay.setHeader("");
	mapOverlay.setBody(psui.searchResults.arrToolTipContent[indexContent]);
	mapOverlay.setFooter("");
	mapOverlay.render(document.body);
	mapOverlay.hide();
	mapOverlay.cfg.setProperty("xy", coordinates);
	mapOverlay.showEvent.subscribe(function() {psui.searchResults.drawMap(lat,long,divId);});
	mapOverlay.show();
//	YAHOO.util.Event.addListener('mapToolTip','mouseover',mapOverlay.show,mapOverlay);
};
function hideMap(obj) {
	var grandParentNodeId = obj.parentNode.parentNode.parentNode.id;
	psui.searchResults.mapOverlay.hide();
	YAHOO.util.Dom.removeClass(grandParentNodeId,"a-m-t-atr");
	YAHOO.util.Dom.addClass(grandParentNodeId,"a-m-t");
	
};
// default date population on add unit
function defaultInputDate(){
	//if ((YAHOO.util.Dom.get('reserveDate')).value==''){
			 var today_Date = new Date();
			 var fillTodayDate = (today_Date.getMonth()+1)+'/'+today_Date.getDate()+'/'+today_Date.getFullYear();
		  (YAHOO.util.Dom.get('reserveDate')).value =fillTodayDate;
		  document.forms['rentReserveDialog'].StartDate.value = fillTodayDate;
		  document.forms['rentReserveDialog'].TransactionType.value='Reserve'
		  document.forms['rentReserveDialog'].rentDateSelect.disabled='true';
		  document.forms['rentReserveDialog'].reserveDate.disabled='';
		  document.forms['rentReserveDialog'].reserveDate.selectedIndex=1;
		  (YAHOO.util.Dom.get('holdStorageUnit')).checked=true;
		  (YAHOO.util.Dom.get('rentStorageUnit')).checked=false;
		  document.forms['rentReserveDialog'].reserveDate.focus;
		  return fillTodayDate
			// } 
		 }
		 
function holdForLater(obj) {
//debugger;
	var objUnit = new psui.order.objUnit;
	objUnit.SizeId = obj.SizeId;
	objUnit.TransactionType = 'Reserve';    //rent
	objUnit.Description = obj.Address[0] + obj.Address[1] + ", " + obj.Address[2] + obj.Address[3] + " " + obj.Address[4];
	objUnit.ProductName = sanitizeProductName(obj.WidthxLengthWL); //SC//
	objUnit.Price = parseHTMLPrice(obj.MonthlyRent); //SC//

	//var startDate = new Date(); 
	//startDate.setDate(startDate.getDate() + 3);//making a reasonable guess here
	
	// ARBITRARY VALUE
	var startDate = new Date('1/1/2222');
	
	objUnit.StartDate = (startDate.getMonth()+1) + '/' + startDate.getDate() + '/' + startDate.getFullYear();
	objUnit.ByPassRentReserveDialog = true;
	//limit the user to a maximum of three reservations
	if (objUnit.TransactionType =='Reserve'){
		psui.globals['reserveUnitCount']++;
		}
	//if(psui.globals['reserveUnitCount']>3){ // Commented by Manmohan Pal on 05/03/2009
	if(psui.globals['reserveUnitCount']>1){
		//actual no. of added items
		psui.globals['reserveUnitCount'] = psui.globals['reserveUnitCount']-1;
		YAHOO.util.Dom.setStyle('dialogAddUnit_c', "visibility", "");
		//psui.searchResults.dialogAddUnit.hide();
		//(YAHOO.util.Dom.get('overlay9')).innerHTML = ""; //Commented by Manmohan Pal on 12/03/2009 
		(YAHOO.util.Dom.get('overlay9')).innerHTML = reserveLimitMsg;
		var reserveLimitMsg = "";
			reserveLimitMsg +='<div id="reserveUnitMsg"><p>There is a limit of 3 unit reservations per customer. Please remove a reservation from your order, or contact customer service at 1-800-688-8057</p></div>\n';
			reserveLimitMsg +='<div class="reserveUnitContinue"><img onclick="showHideSelectListIE6(\'reserveUnit\')" alt="Continue Shopping" src="images/btn_continue_shopping.jpg"/></div>\n';
		(YAHOO.util.Dom.get('overlay9')).innerHTML = reserveLimitMsg;
		//YAHOO.publicStorage.container.overlay9.setBody(reserveLimitMsg);
		YAHOO.publicStorage.container.overlay9.setFooter("");
		//YAHOO.publicStorage.container.overlay9.render();
		YAHOO.publicStorage.container.overlay9.show();
		//YAHOO.publicStorage.container.overlay9();
		return false;
	    }
	pslog(YAHOO.lang.JSON.stringify(objUnit));
	//add the item
	return psui.order.addItem('storageUnit',objUnit);
    //return true;
}
function addUnit(obj) {
	var objUnit = new psui.order.objUnit;
	objUnit.SizeId = obj.SizeId;
	objUnit.TransactionType = 'Rent';
	objUnit.Description = obj.Address[0] + obj.Address[1] + ", " + obj.Address[2] + obj.Address[3] + " " + obj.Address[4];
	objUnit.ProductName = sanitizeProductName(obj.WidthxLengthWL); //SC//
	objUnit.Price = parseHTMLPrice(obj.MonthlyRent); //SC//

	//var startDate = new Date(); 
	//startDate.setDate(startDate.getDate() + 3);//making a reasonable guess here
	
	// ARBITRARY VALUE
	var startDate = new Date('1/1/2222');
	objUnit.StartDate = (startDate.getMonth()+1) + '/' + startDate.getDate() + '/' + startDate.getFullYear();
	objUnit.ByPassRentReserveDialog = true;
	
	pslog(YAHOO.lang.JSON.stringify(objUnit));
	//add the item
	return psui.order.addItem('storageUnit',objUnit);
	
    return;
	//pslog(obj);
	//THis function takes in a complete size unit object / record
	//set the form fields for the dialog with the unit data.
	 defaultInputDate();
	
	YAHOO.util.Dom.setStyle('dialogAddUnit','display','block');
	psui.searchResults.dialogAddUnit.show();
	document.forms['rentReserveDialog'].SiteNumber.value = obj.SiteNumber;
	document.forms['rentReserveDialog'].SiteId.value = obj.SiteId;
	document.forms['rentReserveDialog'].SizeId.value = obj.SizeId;
	document.forms['rentReserveDialog'].rentDateSelect.value='';
	document.forms['rentReserveDialog'].StartDate.value='';
	document.forms['rentReserveDialog'].TransactionType.value='Reserve';	

	strMaxReservationDays = obj.MaxReservationDays;	
	//alert(strMaxReservationDays);
	psui.searchResults.renderDropDowns();	
	psui.errorMessage('dialogAddUnitError','');
};
var loadDialog = function() {	
	var handleSubmit = function() {
		this.submit();
	};
	var handleCancel = function() {
		this.cancel();
	};
	// Define various event handlers for Dialog
	var handleSuccess = function(o) {
		var response = o.responseText;
		//response = response.split("<!")[0];
		//document.getElementById("resp").innerHTML = response;
	};
	var handleFailure = function(o) {
		pslog("Submission failed: " + o.status);
	};
	callback = { success: handleSuccess, failure: handleFailure };
	// Instantiate the Dialog
	psui.searchResults.dialogAddUnit = new YAHOO.widget.Dialog("dialogAddUnit",
	            { width : "690px",
	              fixedcenter : true,
	              visible : false,
				  iframe:false,
				  modal:true,
	              constraintoviewport : true,
	              buttons : [
					{ type:"link",name:"btnCancelDialog",text:"<img src=\"images/btn_cancel.gif\" border=\"0\">",
					handler:handleCancel } ,
					{ type:"link",name:"btnAddOrderDialog",text:"<img src=\"images/btn_add_to_my_order.gif\" border=\"0\">",
					handler:handleSubmit, isDefault:true }]
	             } );
	psui.searchResults.dialogAddUnit.render();
	//functions to call when this overlay is shown
	psui.searchResults.dialogAddUnit.showEvent = function() {
		//clear error message
		pslog('show');
		psui.errorMessage('dialogAddUnitError','');
	};
	psui.searchResults.dialogAddUnit.validate = function() {
		//clear the error messages
		psui.errorMessage('dialogAddUnitError','');
		var formValid = true;
		var formData = this.getData();
		//validation procedures here
		//check SizeId
		pslog(formData.StartDate);
		if(formData.TransactionType=='') {
			psui.errorMessage('dialogAddUnitError','Please Choose an option');
			formValid=false;
			return false;
		}
		if(formData.StartDate=='') {
			psui.errorMessage('dialogAddUnitError','No Date Entered');
			formValid=false;
			return false;
		}
		//if(formData.rentDateSelect=='') {
		//	psui.errorMessage('dialogAddUnitError','No Date Entered');
		//	formValid=false;
		//	return false;
		//}
		if(!(psui.arrRegExp['dateFormat'].test(formData.StartDate))) {
			psui.errorMessage('dialogAddUnitError','Invalid Date Format');
			formValid=false;
			return false;
		};
		if(formData.SizeId=='') {
			//empty
			formValid=false;
		} else if(!(psui.arrRegExp['alphaNumeric'].test(formData.SizeId))) {
			//non alphaNumeric
			formValid=false;
		};
		if(formValid) {
			//alert('form valid');
			psui.searchResults.dialogAddUnit.hide();
			var objUnit = new psui.order.objUnit;
			objUnit.SizeId = formData.SizeId;
			objUnit.TransactionType = formData.TransactionType;
			objUnit.StartDate = formData.StartDate;
			//limit the user to a maximum of three reservations
			if (objUnit.TransactionType =='Reserve'){
				psui.globals['reserveUnitCount']++;
					}
			//if(psui.globals['reserveUnitCount']>3){  // Commented from Manmohan Pal on 05/06/2009
			if(psui.globals['reserveUnitCount']>1){
			
				//actual no. of added items
				psui.globals['reserveUnitCount'] = psui.globals['reserveUnitCount']-1;
				YAHOO.util.Dom.setStyle('dialogAddUnit_c', "visibility", "");
						//psui.searchResults.dialogAddUnit.hide();
						(YAHOO.util.Dom.get('overlay9')).innerHTML = "";
						var reserveLimitMsg = "";
							reserveLimitMsg +='<div id="reserveUnitMsg"><p>There is a limit of 3 unit reservations per customer. Please remove a reservation from your order, or contact customer service at 1-800-688-8057</p></div>\n';
							reserveLimitMsg +='<div class="reserveUnitContinue"><img onclick="showHideSelectListIE6(\'reserveUnit\')" alt="Continue Shopping" src="images/btn_continue_shopping.jpg"/></div>\n';
						(YAHOO.util.Dom.get('overlay9')).innerHTML = reserveLimitMsg;
						//YAHOO.publicStorage.container.overlay9.setBody(reserveLimitMsg);
						YAHOO.publicStorage.container.overlay9.setFooter("");
						//YAHOO.publicStorage.container.overlay9.render();
						YAHOO.publicStorage.container.overlay9.show();
						YAHOO.publicStorage.container.overlay9();
						
						}
		
			pslog(YAHOO.lang.JSON.stringify(objUnit));
			//add the item
			return psui.order.addItem('storageUnit',objUnit);
			//alert('close dialog');
			//return true;
		} else {
			return false;
		}
	};
}
//initialize the overlay dialog for add_unit
YAHOO.util.Event.onDOMReady(loadDialog);

psui.searchResults.renderDropDowns = function () {
	//clear all options
	YAHOO.util.Dom.get('reserveDate').innerHTML ="";
	

	
	var htmlHoldtxt ="";
	var optionMax = 31;
	if (strMaxReservationDays == "7") {
		htmlHoldtxt ="Place a no-commitment hold on unit size, price and promotion for up to 7 days. Choose your move-in (hold until) date and complete your rental at the property."
		optionMax=8;
	} else {
		htmlHoldtxt ="Place a no-commitment hold on unit size, price and promotion for up to 30 days. Choose your move-in (hold until) date and complete your rental at the property."
	}
	(document.getElementById('hold_context')).innerHTML = htmlHoldtxt;
	
	
   //set the form fields for reserve drop down options
   

	var arrThirtyDays = new Array;
	//todays Date
	arrThirtyDays[1]=new Date();
	var mon = arrThirtyDays[1].getMonth();
	var day = arrThirtyDays[1].getDate();
	var fullYear = arrThirtyDays[1].getFullYear();
	mon=mon+1;
	var dateString = mon+'/'+day+'/'+fullYear; 
	document.forms['rentReserveDialog'].reserveDate.options[0] = new Option('Hold Until','');
	document.forms['rentReserveDialog'].reserveDate.options[1] = new Option(dateString,dateString);
		
	//pslog(dateString);
	for(dateSelectIter=2;dateSelectIter<optionMax;dateSelectIter++) {
		arrThirtyDays[dateSelectIter]=new Date(arrThirtyDays[dateSelectIter-1]);		
		arrThirtyDays[dateSelectIter].setDate(arrThirtyDays[dateSelectIter-1].getDate()+1);	
		mon = arrThirtyDays[dateSelectIter].getMonth();
		day = arrThirtyDays[dateSelectIter].getDate();
		fullYear = arrThirtyDays[dateSelectIter].getFullYear();
		mon=mon+1;
		dateString = mon+'/'+day+'/'+fullYear; 
		document.forms['rentReserveDialog'].reserveDate.options[dateSelectIter] = new Option(dateString,dateString);
		}
		
	var arrCollegeSevenDays = new Array;
	//todays Date
	arrCollegeSevenDays[1]=new Date();
	var mon = arrCollegeSevenDays[1].getMonth();
	var day = arrCollegeSevenDays[1].getDate();
	var fullYear = arrCollegeSevenDays[1].getFullYear();
	mon=mon+1;
	var dateString = mon+'/'+day+'/'+fullYear;
	document.forms['rentReserveDialog'].rentDateSelect.options[0] = new Option('Move In Date','');
	document.forms['rentReserveDialog'].rentDateSelect.options[1] = new Option(dateString,dateString);
	//pslog(dateString);
	for(dateSelectIter=2;dateSelectIter<8;dateSelectIter++) {
		arrCollegeSevenDays[dateSelectIter]=new Date(arrCollegeSevenDays[dateSelectIter-1]);
		arrCollegeSevenDays[dateSelectIter].setDate(arrCollegeSevenDays[dateSelectIter-1].getDate()+1);
		mon = arrCollegeSevenDays[dateSelectIter].getMonth();
		day = arrCollegeSevenDays[dateSelectIter].getDate();
		fullYear = arrCollegeSevenDays[dateSelectIter].getFullYear();
		mon=mon+1;
		dateString = mon+'/'+day+'/'+fullYear;
		document.forms['rentReserveDialog'].rentDateSelect.options[dateSelectIter] = new Option(dateString,dateString);
		}
};

//draw Map using google api
psui.searchResults.drawMap = function(lat,long,divId) {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById(divId));
		//create a latlng point object
        var latlng = new GLatLng(lat, long);
		//center the map on the coordinates
		map.setCenter(latlng, 13);
								var baseIcon = new GIcon();
                baseIcon.iconSize = new GSize(40, 47);
                baseIcon.iconAnchor = new GPoint(20, 47);
                var icon = new GIcon(baseIcon);
				icon.image = "images/icon_map_flag.gif";
                marker = new GMarker(latlng,icon);
		//add a markert overlay on the coordinate
		map.addOverlay(marker);
      }
	}

psui.searchResults.printPage = function() {
	//psui.searchResults.updatePrintContent(document.forms['aspnetForm']);
	psui.searchResults.updatePrintContent(document.forms['frmlocate']);
	window.print();
	};

psui.searchResults.updatePrintContent = function() {
	var objForm = arguments[0];
	if(typeof(objForm)=='undefined') {
		//objForm = document.forms['aspnetForm'];
		objForm = document.forms['frmlocate'];
	}
	//psui.updatePrintView('zipCodeView',objForm.locationZip.value);
	psui.updatePrintView('zipCodeView',objForm.location.value);
	if (objForm.distanceRadius != null){
	    psui.updatePrintView('ctl00_PublicStoragePageContent_distance',objForm.distanceRadius.value);
	}
	if (objForm.specialOffersSelect != null){
	    psui.updatePrintView('offersPrintView',objForm.specialOffersSelect.options[objForm.specialOffersSelect.selectedIndex].value);
	}
	//psui.updatePrintViewCheckBox(objForm.size,'sizesPrintView');
	//psui.updatePrintViewCheckBox(objForm.features,'featuresPrintView')
	//return true;
	}

psui.searchResults.refineSearchObj = function() {
	//this.locationZip = '';
	this.location = '';
	this.distanceRadius = '';
	this.specialOffersSelect = '';
	this.sizes = new Array;
}

psui.searchResults.validateForm = function() {
	var objForm = arguments[0];
	var valid = true;
	psui.searchResults.updatePrintContent(objForm);
	 
	//if(objForm.locationZip.value=='') 
	if(objForm.location.value=='') 
	{
		valid = false;
		psui.errorMessage('locationError','Please enter a search location');
		}
	return valid;
	};
	
psui.searchResults.reCreateQuery = function(Obj){
	var originalUrl=(YAHOO.util.Dom.get(Obj)).getElementsByTagName('form')[0].siteUrlInput.value;
	
	//objForm =document.forms['aspnetForm'];
	objForm =document.forms['frmlocate'];
	var specialOffer = objForm.special_offers.options[objForm.special_offers.selectedIndex].value;
	var sizeStringIn = escape(psui.generateCheckBoxQueryStringSize(objForm.size));
	var featuresStringIn = escape(psui.generateCheckBoxQueryStringFeature(objForm.features));
	Obj.href = originalUrl+'&special_offers='+specialOffer+'&marketingtype='+sizeStringIn+'&features='+featuresStringIn;
	
	}
	
	
function sanitizeProductName(product_name){
	product_name = product_name.replace(' (W x L)','');
	product_name = product_name.replace('*','');
	return product_name;
}