// Footsmart Namespace
// RWilliams SomeTime/May/2008
// Create a namespace for the footsmart website
//-----------------------------------------------------------------------
var FootSmart = FootSmart ? FootSmart : function(){

    // Private variables here
    //***************************************************************************
    var domain = '';//'http://localhost/footsmart.web/';
    var searchHandler = 'controls/searchresults/Celebros.ashx?';
    var ajaxLoaderGif = "<img src='images/ajax-loader.gif' />";
    var searchPageName = window.location.pathname + "?"; //'SearchReturns.aspx?';
    var searchUrl = domain + searchPageName + 'SearchTerm=';
    var loadingHTML = '<img align="absmiddle" border="0" src="http://www.footsmart.com/Images/LoaderIcon.gif"><br /><img src="http://www.footsmart.com/images/space.gif" width="588px" height="1"><img src="http://www.footsmart.com/images/space.gif" width="1" height="100">';
    var loadingTEXT = 'Loading...';
    var moreOptionImage = 'http://www.footsmart.com/Images/more.jpg';
    var productsDisplayMode = 1; //1=Grid, 0=List
    var beginRow = '<tr>';
    var endRow = '</tr>';
    var searchHandleHidden = 'searchResults_iptSH';
    var cellsPerRow = 4;
    var questionsPerRow = 3;
    var minRefinementsForMoreOptions = 6; // How many refinements do we need to have before we can shoe more options
    var ajaxEnableSearchResultsRefinements = false;    
    var ajaxEnableSideBar = false;
    //var ajaxEnableRefinements = true;        
    var Celebros_Search = 0; // see FootSmart.Library.SearchManagement.Celebros.enmActions
    var Celebros_Answer_Question = 2; // see FootSmart.Library.SearchManagement.Celebros.enmActions
    var Celebros_SetAsFirst_Question = 7; // see FootSmart.Library.SearchManagement.Celebros.enmActionsvar
    var Celebros_Move_Page = 3; // see FootSmart.Library.SearchManagement.Celebros.enmActionsvar
    var topPageSizeSelectorCellName = 'TopPageSizeSelectorContent';    
    var topNavigationBarCellName = 'TopNavigationBarContent';
    var bottomPageSizeSelectorCellName = 'BottomPageSizeSelectorContent';
    var bottomNavigationBarCellName = 'BottomNavigationBarContent';
    var topSortingSelectorCellName = 'TopSortingSelectorContent';
    var bottomSortingSelectorCellName = 'BottomSortingSelectorContent';    
    var moreOptionsImagebuttonCellName = 'MoreOptionsImagebutton';
    var clearOptionsImagebuttonCellName = 'ClearOptionsImagebutton';
    var pageSizeText = 'Products per page: ';
    var homePageLink = '<a href="default.aspx" class="searchPath">Home</a> &gt; ';
    var searchRefined = false; // Indicates whether the user has refined the his/her search
    var newSearch = false;
    var redirectOnSingleProduct = false;

    // Private functions
    //***************************************************************************
    function GetGridCell(item)
    {
        // Perform prototype template evaluation
        // returns the results of the evaluation
        //-----------------------------------------------------------------------    
        
        if(item == undefined)
        {
            // Return empty column
            return '<td align="center" valign="top" width="151px" class="productGridSpace">&nbsp</td>';            
        }
        else
        {
            // If we have a canadian price, then the user must have 
            // switched to canadian pricing
            var isCanadian = false;

            if(item.cnPrice != null && item.cnPrice.length > 0)
            {
                isCanadian = true;
            }

            // Build the cell
            var cell = '<td align="center" valign="top" width="25%" class="productGridSpace">';
            cell += '<table border="0" cellpadding="0" cellspacing="0">';
            cell += '<tr>';
            cell += '	<td align="center"><a title="#{tip}" href="#{url}"><img onerror="this.src=\'Images/nopic_new_white.gif\'" src="#{imageurl}" title="#{tip}" alt="#{tip}" border="0" style="width:100px;" /></a></td>';
            cell += '	<td valign="top">' + ((item.showNewFlag == 'true') ? '<img src="/images/new-icon2.gif" border="0" width="25" height="25" alt="" />' : '') + '</td>';
            cell += '</tr>';
            cell += '<tr><td align="center" colspan="2"><a title="#{tip}" href="#{url}"><span class="subproducthead2"><a title="#{tip}" href="#{url}">#{title}</a></span></td></tr>';
            cell += '<tr>';
            cell += '    <td colspan="2" align="center" nowrap="nowrap">';

            if(isCanadian == true)
            {
                // We don't show strikeout price for canadian
				cell += '<span class="subproductprice">Price: </span>';
                cell += '<span class="subproductprice">#{cnPrice}</span>';
            }
            else
            {
                if(item.rprice != null && item.rprice.length > 0)
                {
					// Show strikeout price if any
					cell += '<span class="productStrikeOutWasPriceSmall">Was: #{rprice}</span>&nbsp;';
                    cell += '<span class="productStrikeOutNowPriceSmall">Now: #{price}</span>';
                }
                else
                {
					// Show price
					cell += '<span class="subproductprice">Price: </span>';
                    cell += '<span class="subproductprice">#{price}</span>';
                }
            }

            cell += '    </td>';
            cell += '</tr>';
            cell += '<tr><td colspan="2" align="center" class="productPromoText">#{promoShipText}</td></tr>';
            cell += '<tr>';
            cell += '    <td colspan="2" align="center"><a href="#{url}">';
	        cell += '            <img id="imgRatings" src="#{bvimageurl}" border="0" width="85" height="30" onError="this.src=images/pixel.gif;" /></a>';
            cell += '    </td>';
            cell += '</tr>';
            cell += '</table>';
            cell += '</td>';
            
            // Init the template
            var myTemplate = new Template(cell);

            // Evaluate the template with the JSon object
            return myTemplate.evaluate(item);
        }            
    };
    
    function AddOptionToSelect(elem, text, value, selected){
        var option;
        if(Prototype.Browser.IE){
            option = new Element('option');
            option.text = text;
            option.value = value;
            option.innerHTML = text;
            if(selected != 'undefined') option.selected = selected;
            elem.options.insert(option);
        }else{
            option = new Element('option', {'value':value, 'label': text});
            option.innerHTML = text;
            if(selected != undefined) option.selected = selected;
            elem.appendChild(option);
        }    
    };
    
    function GetQuestionAnswerCellElement(question){
        // Performs a template evaluation on the given item
        // and returns a cell with the new question and answers
        //-----------------------------------------------------------------------
        if(question == undefined){
            //TODO: handle undefined items
            // Return empty column
            var td = new Element('td', {'align':'center', 'valign':'top', 'width' :'100%'});
            return td;
        }else{
            // Build the new url
            // SearchReturns.aspx?Action=7&amp;QuestionId=5151&amp;SH=QT1zaG9lc35CPXNob2VzfkQ9MTZ_ST1wcmljZX5LPTR_TD0xfk09Mzd_Tj0yfg&amp;SI=fe7df899-aca3-4b1f-b20a-a77cb9b28233
            var hashed = $H(BuildCelebrosSearchQuery(Celebros_SetAsFirst_Question, 0).toQueryParams());
            hashed.set('questionid', question.id);
            var url = 'SearchReturns.aspx?' + hashed.toQueryString();            
            
            // Build answers
            var drpList = new Element('select');
            drpList.update();
            question.answers.each(function(answer, index){                
                if(drpList.options.length <= 0){
                    AddOptionToSelect(drpList, "All", "All");
                }
                AddOptionToSelect(drpList, answer.text, answer.id);
            });
            
            // Lets build the rest of the html            
            var cell = new Element('td', {'valign' : 'top'});
            var body = new Element('tbody');
            var table, tr, td, a, sel;
            var cls =  question.sidetext.gsub(' ','');  //Applies a class to all the select boxes that equals name of refinement without space
            if(questionsPerRow > 1){
                table = new Element('table', {width: '100%', cellpadding: '0', cellspacing: '0', 'class':'NLQ', style: 'padding-right: 10px;'});
                table.appendChild(body);
                
                // Link Row
                var tr = new Element('tr');
                var td = new Element('td',{'class':'questionTitle'});
                //a = new Element('a', {'class':'questionTitle', href: url});
                //a.innerHTML = question.sidetext;
                td.innerHTML =  question.sidetext;
                //td.appendChild(a);
                tr.appendChild(td);
                body.appendChild(tr);
                
                // Select Row
                tr = new Element('tr');
                td = new Element('td');                
                td.innerHTML = '<select class="topNavRefine '+cls+'">'+drpList.innerHTML+'</select>';
                tr.appendChild(td);
                body.appendChild(tr);                
                table.appendChild(body);
            }else{
                // Left Nav
                table = new Element('table', {cellpadding: '0', cellspacing: '0', 'class':'NLQ'});
                
                // Link Row
                tr = new Element('tr');
                var td = new Element('td',{'class':'questionTitle'});
                //a = new Element('a', {'class':'questionTitle', href: url});
                //a.innerHTML = question.sidetext;
                td.innerHTML =  question.sidetext;
                //td.appendChild(a);
                tr.appendChild(td);
                body.appendChild(tr);
                
                // Select Row
                tr = new Element('tr');
                td = new Element('td');
                // changed because it generates JS error.  Hwa Son
                //td.innerHTML = '<select class="leftNav '+cls+'" onblur="this.style.width=155px">'+drpList.innerHTML+'</select>';
                td.innerHTML = "<select class=\"leftNav "+cls+"\" onblur=\"this.style.width='145px';\">"+drpList.innerHTML+"</select>";
                tr.appendChild(td); 
                body.appendChild(tr);                
                table.appendChild(body);
            }            
            // Spacer Row
            tr = new Element('tr');
            td = new Element('td', {height: '5'});
            tr.appendChild(td);
            body.appendChild(tr);                
            table.appendChild(body); 

            // Append the cell to the main table
            cell.appendChild(table);
            return cell;            
        } ;       
    };
    
    function AddPageSizeSelectorCell(elementName, pageSizes, currentPageSize){
        // Grabs the page size selector cell and stick it in
        // Example:
        //<select name="searchResults:pssPageSizeSelector:ddlDisplayedProducts" id="searchResults_pssPageSizeSelector_ddlDisplayedProducts" OnChange="Javascript:SubmitData(this.value)">
        //    <option selected="selected" value="Action=13&amp;PageSize=16">16</option>
        //    <option value="Action=13&amp;PageSize=32">32</option>
        //    <option value="Action=13&amp;PageSize=48">48</option>
        //    <option value="Action=13&amp;PageSize=64">64</option>
        //    <option value="Action=13&amp;PageSize=80">80</option>
        //    <option value="Action=13&amp;PageSize=96">96</option>
        //</select>        
        //---------------------------------------------------------------------------
        if(pageSizes.length <= 1){
            $(topPageSizeSelectorCellName).update();
            $(bottomPageSizeSelectorCellName).update();
        }else{
            var drpList = $(elementName).getElementsBySelector('select')[0];
            drpList.update();
            pageSizes.each(function(pagesize, index){
                var isSelected = (pagesize==currentPageSize);
                var val = 'Action=13&PageSize=' + pagesize;
                AddOptionToSelect(drpList, pagesize, val, isSelected);
            });
        };
    };
    
    function AddPageSortingSelectorCell(elementName, pageSort){
        // Creates the result sorting cell and stick it in the table
        //--------------------------------------------------------------------------
        var drpList = $(elementName).getElementsBySelector('select')[0];
        drpList.update();
        pageSort.each(function(pagesortOption, index){
            var so = pagesortOption[0].evalJSON(true);
            AddOptionToSelect(drpList, so.title, so.value, so.selected);         
        });        
    };
    
    function IsBeginRow(index, cellsPerRow){
        // Determine if this should be a start of row
        //-----------------------------------------------------------------------
        if(index == 0 || (index % cellsPerRow) == 0) {
            return true;
        }
        
        return false;
    };
    
    function IsEndRow(index, cellsPerRow, recordCount){
        // Determine if this should be a end of a row
        //-----------------------------------------------------------------------
        if( ((index+1) % cellsPerRow) == 0
            || (index+1) == recordCount) {
            return true;
        }     
        
        return false;
    };
    
    function GetHTMLHref(link, text, suffix, cssclass){
        var link;
        if(cssclass != undefined){
            link = '<a href='+searchPageName + link+' class='+cssclass+'>'+text+'</a>';
        }else{
            link = '<a href='+searchPageName + link+'>'+text+'</a>';
        }
            
        if(suffix != undefined){
            link += suffix;
        }

        return link;
    };
    
    function SetNavOrientation(useLeftNav){
        // Sets the orientation of the refinements navigation
        // ------------------------------------------------------------------------
        if(useLeftNav == true){
            questionsPerRow = 1;
        }else{
            questionsPerRow = 3;
        }        
    };
    
    function GetNavigationLinks(pageSize, currentPage, productsOnThisPage, totalPages, totalProductsCount, span)
    {
        if(totalPages != undefined && totalPages > 1){
            // Creates the navigation bar at the top and bottom
            //-----------------------------------------------------------------------
	        var firstProdInPage = (currentPage * pageSize + 1);
		    var lastProdInPage = (productsOnThisPage + firstProdInPage - 1);
		    var startText = ((currentPage * pageSize) + 1) + " - " + ((currentPage * pageSize) + productsOnThisPage) + " of " + totalProductsCount;
		    var navigationBar = ''; //startText + '';
		    var hashed = $H(BuildCelebrosSearchQuery(Celebros_Move_Page).toQueryParams());
		    var selectedPageIndex = (currentPage + 1);
		    var spacer = '&nbsp;|&nbsp;';
    		
            // calculate start and end indexes
            var startIndex = Math.max(0, currentPage-(Math.floor(span/2)));
            if (startIndex + span >= totalPages) {startIndex = Math.max(totalPages - span, 0);}
            var endIndex = Math.min(totalPages - 1, (startIndex + span));

            // Remove other unwanted params
            hashed.unset('searchterm');
            hashed.unset('Page');
            hashed.unset('page');
            
            // re-assigning SH and SI
            // Hwa Son 9/17/2008
            hashed.unset('SH');
            hashed.unset('SI');
            
            hashed.set('SH', $F(searchHandleHidden));
            hashed.set('SI', $F('searchResults_iptSI'));
           
	        // if this is not the beginning then add prev
            if(currentPage > 0){
                hashed.set('Page', (currentPage-1));
                navigationBar += GetHTMLHref(hashed.toQueryString(), '&lt;&nbsp;Previous', spacer, 'PrevNext');
            }
    		
		    // Begin looping
		    for(var i=startIndex; i<=endIndex;i++)
		    {
		        var pageText = (i+1);
		        if(i == currentPage){
		            navigationBar += '<font  style="text-decoration: underline;">'+pageText+'</font>'+spacer;
		        }else{
		            hashed.set('Page', i);
		            navigationBar += GetHTMLHref(hashed.toQueryString(),pageText, spacer, 'PrevNext');
		        }
		    }
    		
	        // next link
		    if ((currentPage + 1) != totalPages){
                hashed.set('Page', (currentPage+1));
                navigationBar += GetHTMLHref(hashed.toQueryString(), 'Next&nbsp;&gt;', null, 'PrevNext');
            }
                    
            // Return it
            return navigationBar;
        }else{
            //$$('table#topnavbar tr')[0].hide();
            return '';
        }
    };
        
    function BuildCelebrosSearchQuery(action, answerId){
        // use the neccessary information to build a celebros search query string
        // a somewhat complete string will contain, sh("search handle"), si("session id")
        //  an action tag, answer id, etc...
        //-----------------------------------------------------------------------      
        try{
            var hashed =  $H(window.location.href.toQueryParams());                
            hashed.set('SH', $F(searchHandleHidden));
            hashed.set('SI', $F('searchResults_iptSI'));
            hashed.set('LAP', $F('searchResults_iptLAP'));
            
            if(action != undefined){
                hashed.set('Action', action);
            }
            
            if(hashed.get('Action') == undefined) {
                hashed.set('Action', '2'); // 2=Celebros_Answer_Question
            }
            
            if(answerId != undefined && answerId != null && answerId != 0){
                hashed.set('AnswerId', answerId);
            }
        }
        catch(err){
            // this is defintely not good, prob someone change the name of a control or param
            // its current defaulting to a shoe search. 
            // TODO: Adam how do we handle this? Redirect to home page or what?
            //return (domain + searchHandler + 'searchTerm=shoes');
            return '';
        }

        return (domain + searchHandler + hashed.toQueryString());
    };
    
    function BeginAJAXWaitProcess(){
        // Indicate that the ajax process has started by showing a loading gif
        //-----------------------------------------------------------------------
        var table = $('ProductsTable').update();
        if(table){
            if(Prototype.Browser.IE){
                var row = new Element('tr');
                var cell = new Element('td', {'class': 'LoadingImage'});                
                cell.innerHTML = loadingHTML;
                row.appendChild(cell);                
                table.tBodies[0].appendChild(row);
            }else{
                table.innerHTML = '<tr><td class="LoadingImage">' + loadingHTML + '</td></tr>';
            }
        }
    };

    function EndAJAXWaitProcess(){
        // Indicate that the ajax processing is completed and end
        //----------------------------------------------------------------------- 
        var table = $('ProductsTable');
        var t = '';
    };
    
    function ChangeMoreOptionsHref(currentPage)
    {       
        // To change more options url
        // Hwa Son 7/1/2008  
        // Hwa Son 9/17/2008       
        //----------------------------------------------------------------------- 
        var si = $F('searchResults_iptSI');
        var sh = $F(searchHandleHidden);
        var moreOptions;
        if (ajaxEnableSearchResultsRefinements)
        {
            moreOptions = document.getElementById("searchResults_bodyRefinements_anMoreOptions");
            var sHref = searchPageName + "Action=3&page=" + currentPage + "&SH=" + sh + "&SI=" + si + "&MoreOptions=true";
            if (moreOptions != null)
            {
                moreOptions.href = sHref;
            }
            
            moreOptions = document.getElementById("searchResults_lnRefinements_anMoreOptions");
            if (moreOptions != null)
            {
                moreOptions.href = sHref;
            }
        }
    };    
    
    function RemoveSpecialChars(url){
		//url = url.replace(/%u2019/g, "%27");  // replace a fancy apostrophe from MS-WORD with a regular apostrophe.
		//url = url.replace(/%5C/g, ""); // remove all '\'
		//url = url.replace(/\//g, "");   // remove all '/'
		url = url.replace(/\*/g, "");  // remove all * 
		url = url.replace(/%5E/g, "");  // remove all ^    
		return url;
    };
    
    function HideResultMessage()
    {
        if ($$('div#CustomMessageDiv')[0].innerHTML.length > 0)
        {
            $$('div#resultsMessage')[0].hide();
        }
    };
    
    // Public functions
    //***************************************************************************
    return {
        Destroy: function(){
            /* Destroy the framework here */
            if(ajaxEnableSearchResultsRefinements == true){ 
                if(newSearch != true){
                    SetCookie('CelebrosDestroyed', '1');
                }
            }                 
        },
        Init: function(){  
            //  if windows safari, disable AJAX back.
            //  Hwa Son 7/21/2008
            var isSafari=(ua.indexOf('webkit')!=-1);
            var isMac=(ua.indexOf('mac')!=-1);
            if (isSafari && !isMac)
            {
               ajaxEnableSearchResultsRefinements = false; 
            }
            
            /* Initialize the framework here */            
            if(ajaxEnableSearchResultsRefinements == true){            
                var hashed =  $H(window.location.href.toLowerCase().toQueryParams());
                var sh = hashed.get('sh');
                var st = hashed.get('searchterm');
                
                // If there is no search handle, force the init search
                if(sh != undefined){
                    DeleteCookie('CelebrosDestroyed');
                }
                
                // The user most likely did something to cause a postback
                // such as sort or link click, which means no searchterm but sh
                if(sh != undefined && st == undefined){
                    FootSmart.PerformQwiserSearch(null, null, null);
                }
                
                // if there is a cookie, then force a reload of the last search, after
                // deleting the cookie
                if(GetCookie('CelebrosDestroyed') != null)
                {
                    DeleteCookie('CelebrosDestroyed');
                    if(st!=null){                        
                        var url = (domain + searchHandler + 'searchterm=' + st);
                        FootSmart.PerformQwiserSearch(null, null, url);
                    }
                }
                else{
                    // Prefore the questions for AJAX refinements
                    FootSmart.PrepareForRefinementsOnChange();
                }
            }
            
        },
        
        // Prepare for a new search
        //-----------------------------------------------------------------------        
        PrepareNewSearch: function(){
            /*Run some tests here*/       
            newSearch = true;  
            DeleteCookie('CelebrosDestroyed');
        },

        // Test the framework
        //-----------------------------------------------------------------------        
        TestFramework: function(){
            /*Run some tests here*/   
        },

        // Looks for all the refinement controls and modify the onchange events
        //-----------------------------------------------------------------------        
        PrepareForRefinementsOnChange: function (){
            HideResultMessage();
            
            // Apply bulk event listening to all select boxes with this table
            if(ajaxEnableSearchResultsRefinements == true){
                // Do not show "More Options" & "Clear Options" if there is only one refinement
                var refinementCount = $$('table#SearchResultsRefinementsBody select').length;
                var optionsTable = $('OptionsTable');
                if(optionsTable){
                    if(refinementCount < 6){
                        $(moreOptionsImagebuttonCellName).hide();
                    }else{
                        $(moreOptionsImagebuttonCellName).show();
                    }
                }
                
                // Refinements
                $$('table#SearchResultsRefinementsBody select').each(function(element, index){                      
                    // Disable post back for now.
                    element.writeAttribute('onchange', ''); // null works in firefox but not IE so use ''
                    
                    // Monitor question change events
                    element.observe('change', function(evnt){                                    
                        var drpList = Event.element(evnt);
                        searchRefined = true;                        
                       
                        // Perform the search
                        FootSmart.PerformQwiserSearch(Celebros_Answer_Question, drpList);
                        
                        // Show the clear options button if the user refines
                        if($(clearOptionsImagebuttonCellName)){
                            $(clearOptionsImagebuttonCellName).firstDescendant().setStyle({visibility:'visible'});
                        }                        
                    });
                });
                
               
            }
        },
        
        // Perform an ajax lookup to Celebros
        // controls/searchresults/Celebros.ashx?qry=shoes
        // actionId, Id of action to be performed
        // element, the element that triggered the action
        //-----------------------------------------------------------------------        
        PerformQwiserSearch: function(actionId, element, url){ 
            // Get the search term.
            //var url; 
            if(url == null || url == 'undefined' || url == '' || url == undefined){
                if(element != null && element != 'undefined'){
                    url = BuildCelebrosSearchQuery(actionId, element.value);
                }else{
                    // New Search
                    url = BuildCelebrosSearchQuery(actionId, null);
                }
            }

            // Perform Ajax lookup
            if(!url.blank()){                
                new Ajax.Request(url, {
                    method: 'get',
                    onLoading: function(){
                            // Begin the ajax loading indicator
                            //BeginAJAXWaitProcess();
                            
                            // Show progress bar here
                            if(ajaxEnableSideBar == true){
                                $('RelatedProductsContent').innerHTML = loadingTEXT;
                                $('RelatedConditionsContent').innerHTML = loadingTEXT;                                
                            }
                            
                            HideResultMessage();
                        },
                    onSuccess: function(transport){   
                            if(transport.responseText.isJSON()){
                                var data = transport.responseText.evalJSON(true);                          
                               
                                // If its just a single product, don't bother doing anything
                                // just redirect to the product page as per the url specified
                                //-----------------------------------------------------------
                                // RWilliams - Disable redirect to product page on single product
                                //-----------------------------------------------------------
                                if(data.Products && redirectOnSingleProduct == true){
                                    if(data.Products.length == 1){
                                        var thisProd = data.Products[0][0].evalJSON(true);
                                        window.location.href = thisProd.url;
                                        return;
                                    };
                                };
                                
                                // REFINEMENTS: Do we need to ajaxify the refinements list
                                //----------------------------------------------------------
                                if(ajaxEnableSearchResultsRefinements == true){                                    
                                    // SearchHandle - set the hidden control with 
                                    // the most recent Qwiser search handle
                                    $(searchHandleHidden).value = data.SH;
                                    SetCookie('SH', data.SH);
                                    
                                    if(data.Navigation){
                                        var navInfo2 = data.Navigation[0].evalJSON(true);
                                        SetNavOrientation(navInfo2.useleftnav);
                                    }
                                    
                                    // Refinements
                                    var questionsRow;
                                    var questionCellsOnRow = 0;      
                                    var refineBody = $$('#SearchResultsRefinementsBody tbody')[0];
                                    refineBody.update();
                                    //alert(data.Questions.length);
                                    data.Questions.each(function(item, index){
                                        var question = item[0].evalJSON(true); // id, sidetext, title, etc..
                                        
                                        // Begin
                                        if(IsBeginRow(index, questionsPerRow) == true){
                                            questionsRow = new Element('tr');
                                            questionCellsOnRow = 0;
                                        }
                                        
                                        // Cell
                                        questionsRow.appendChild(GetQuestionAnswerCellElement(question));
                                        questionCellsOnRow++;
                                        
                                        // End
                                        if(IsEndRow(index, questionsPerRow, data.Questions.length) == true){
                                            if(questionCellsOnRow != questionsPerRow){
                                                // We have an incomplete row, patch it up - add empty rows
                                                //---------------------------------------------------------
                                                for(var i=0;i<(questionsPerRow-questionCellsOnRow);i++){
                                                    questionsRow.appendChild(GetQuestionAnswerCellElement());
                                                }
                                            };
                                            refineBody.appendChild(questionsRow);
                                        };                                                                               
                                    });
                                    
                                    // Update the search path & dynamically add classes to it
                                    // removed "homePageLink"  Hwa Son 6/30/2008
                                    if($('searchPath')){
                                        if (data.SearchPath.toLowerCase().indexOf(searchHandler.toLowerCase()) > -1)
                                        {
                                            // for a virtual site site.
                                            // Hwa Son 7/8/2008
                                            var pathName = "";
                                            if (window.location.pathname.toLowerCase().indexOf("footsmart.web") > -1)
                                            {
                                                pathName = window.location.pathname.substring(0, window.location.pathname.indexOf("/", 1));
                                            }

                                            data.SearchPath = data.SearchPath.replace(/\/controls\/searchresults\/Celebros.ashx?/g, window.location.pathname.replace(pathName, ""));
                                            
                                            var hashed =  $H(window.location.href.toQueryParams());
                                            
                                            var cmParam = "";
                                            if (hashed.get('cm_sp')) cmParam = cmParam + "&cm_sp=" + hashed.get('cm_sp');
                                            if (hashed.get('cm_re')) cmParam = cmParam + "&cm_re=" + hashed.get('cm_re');
                                            data.SearchPath = data.SearchPath.replace(/Action=4/g, "Action=4" + cmParam);
                                            
                                            // re-assigning SH and SI
                                            // Hwa Son 9/17/2008
                                            var sSH = data.SearchPath.indexOf('SH=')+3;
                                            var sSI = data.SearchPath.indexOf('SI=')+3;
                                            
                                            var reSH = new RegExp(data.SearchPath.substring(sSH, data.SearchPath.indexOf('&SI=')), "g");
                                            var reSI = new RegExp(data.SearchPath.substring(sSI, data.SearchPath.indexOf('">', sSI)), "g");
                                            data.SearchPath = data.SearchPath.replace(reSH, $F(searchHandleHidden));
                                            data.SearchPath = data.SearchPath.replace(reSI, $F('searchResults_iptSI'));
                                        }
                                        $('searchPath').innerHTML = data.SearchPath;
                                        $('searchPath').up().addClassName('searchPathCell');
                                        $$('#searchPath a').each(function(link, index){
                                            link.addClassName('searchPath');
                                        });
                                    };  
                                                                        
                                    // Lets add all the questions to the table
                                    if(questionsRow && !questionsRow.empty()){ 
                                        // hook up the on change events again
                                        FootSmart.PrepareForRefinementsOnChange();
                                    }
                                    
                                    // Lets build the navigation bar at the top and bottom
                                    // looks like 1 - 12 of 456 <Previous 1,2,3,4,5 Next >
                                    var pageSize;
                                    if(data.Navigation){
                                        var navInfo = data.Navigation[0].evalJSON(true);
                                        var navLinks = GetNavigationLinks(navInfo.pagesize, navInfo.currentpage, navInfo.productsonthispage, navInfo.totalpages, navInfo.totalproductscount, navInfo.span);
                                        pageSize = navInfo.pagesize;
                                        
                                        // Page navigation
                                        $(topNavigationBarCellName).innerHTML = navLinks;                                        
                                        $(bottomNavigationBarCellName).innerHTML = navLinks;
                                        
                                        // Display the message text
                                        // your search for BLACK produced 123 items...
                                        if($$('font#TotalProdsCount')[0]){
                                            $$('font#TotalProdsCount')[0].innerHTML = navInfo.totalproductscount;
                                        }
                                        
                                        // Hide custom message text
                                        // Because if the user is refining the we don't want to show error or null message
                                        if($$('CustomMessageCell')[0]){
                                            $$('CustomMessageCell').hide();
                                        }
                                        
                                        // more options link
                                        // Hwa Son 7/8/2008
                                        ChangeMoreOptionsHref(navInfo.currentpage);
                                    }
                                    
                                    // highlight the page size selected and sort controls
                                    if(data.PageSizes){
                                        AddPageSizeSelectorCell(topPageSizeSelectorCellName, data.PageSizes, pageSize);
                                        AddPageSizeSelectorCell(bottomPageSizeSelectorCellName, data.PageSizes, pageSize);
                                    }
                                    
                                    // Page sorting
                                    if(data.PageSortOptions){
                                        AddPageSortingSelectorCell(topSortingSelectorCellName, data.PageSortOptions);
                                        AddPageSortingSelectorCell(bottomSortingSelectorCellName, data.PageSortOptions);
                                    }
                                                                        
                                    // Analytics
                                    if(data.Anlx){
                                        //$('AnalyticsImageCell').innerHTML = data.Anlx;
                                        var qwiserImage = $('AnalyticsImageCell').down();
                                        if(qwiserImage){
                                            var src = data.Anlx.substring(data.Anlx.indexOf("SRC='")+5, data.Anlx.indexOf("'", data.Anlx.indexOf("SRC='")+5));
                                            qwiserImage.src = src;
                                        }
                                    }
                                    
                                    // switch the message in the narrow your search box
                                    // Hwa Son 7/9/2008
                                    if (data.NarrowSearchMessage)
                                    {
                                        $('NarrowSearchMessageCell').innerHTML = data.NarrowSearchMessage;
                                    }
                                    
                                    // no drop down message.
                                    // Hwa Son 7/10/2008
                                    if (data.NoDropDownMessage && !questionsRow)
                                    {
                                        $('NoDropDownMessageCell').innerHTML = data.NoDropDownMessage;
                                        $('NarrowSearchMessageCell').innerHTML = "";
                                    }
                                }         
                                
                                // switch search result message
                                // Hwa Son 7/9/2008
                                if (actionId)
                                {
                                    $$('div#resultsMessage')[0].show();
                                    if ($$('div#CustomMessageDiv')[0].innerHTML.length > 0)
                                    {
                                        $$('div#CustomMessageDiv')[0].hide();
                                    }
                                }
                                else
                                {
                                    HideResultMessage();
                                } 
                                                                
                                // SIDEBAR: Do we want to ajaxify the side bar?
                                //----------------------------------------------------------
                                if(ajaxEnableSideBar == true){
                                    // Related Products  
                                    // modified by Hwa Son 9/24/2008                                    
                                    if(data.RelatedSearches && data.RelatedSearchesAll && $('RelatedProductsContent')){
                                        $('RelatedProductsContent').update();
                                        
                                        var innerHtml = '<div id="divRelatedProductsMore" style="visibility:hidden;position:absolute;">';
                                        innerHtml += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"relatedBox\">";
			                
                                        data.RelatedSearchesAll.each(function(item, index){
                                            innerHtml += "<tr><td height=\"5\"></td></tr>";
                                            innerHtml += "<tr><td><a href='" + searchPageName + "Searchterm=" + item + "'>" + item + "</a></td></tr>";
                                        });
                                        
                                        innerHtml += "<tr><td height=\"5\"></td></tr>";
                                        innerHtml += "<tr><td style=\"font-weight:bold; padding-bottom:10px;\"><a href=\"Javascript: ContentSwitch('divRelatedProductsLess', 'divRelatedProductsMore', 'RelatedProductsContent');\">< Less</a></td></tr>";
                                        innerHtml += "</table></div>";
                                        
                                        innerHtml += '<div id="divRelatedProductsLess" style="visibility:visible;">';                                     
                                        innerHtml += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"relatedBox\">";
			                
                                        data.RelatedSearches.each(function(item, index){
                                            innerHtml += "<tr><td height=\"5\"></td></tr>";
                                            innerHtml += "<tr><td><a href='" + searchPageName + "Searchterm=" + item + "'>" + item + "</a></td></tr>";
                                        });
                                        
                                        innerHtml += "<tr><td height=\"5\"></td></tr>";
                                        if (data.RelatedSearchesAll.length != data.RelatedSearches.length)
                                        {
                                            innerHtml += "<tr><td style=\"font-weight:bold; padding-bottom:10px;\"><a id=\"hlRelatedProducts\" href=\"Javascript: ContentSwitch('divRelatedProductsMore', 'divRelatedProductsLess', 'RelatedProductsContent');\">More ></a></td></tr>";
                                        }
                                        innerHtml += "</table></div>";
                                        
                                        $('RelatedProductsContent').innerHTML = innerHtml;
                                        
                                        if (data.RelatedSearchesAll.length == 0)
                                        {
                                            if ($('tdRelatedProductsLeft')) $('tdRelatedProductsLeft').hide();
                                            if ($('tdRelatedProductsRight')) $('tdRelatedProductsRight').hide();
                                        }
                                    };
                                    
                                    // Related Conditions
                                    // modified by Hwa Son 9/24/2008                                
                                    if(data.RelatedConditions && data.RelatedConditionsSorted && $('RelatedConditionsContent')){
                                        $('RelatedConditionsContent').update();
                                        
                                        var innerHtml = '<div id="divRelatedConditionsMore" style="visibility:hidden;position:absolute;">';
                                        innerHtml += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"relatedBox\">";
			                
                                        data.RelatedConditionsSorted.each(function(item, index){
                                            innerHtml += "<tr><td height=\"5\"></td></tr>";
                                            innerHtml += "<tr><td>" + item + "</td></tr>";
                                        });
                                        
                                        innerHtml += "<tr><td height=\"5\"></td></tr>";
                                        innerHtml += "<tr><td style=\"font-weight:bold; padding-bottom:10px;\"><a href=\"Javascript: ContentSwitch('divRelatedConditionsLess', 'divRelatedConditionsMore', 'RelatedConditionsContent');\">< Less</a></td></tr>";
                                        innerHtml += "</table></div>";
                                        
                                        innerHtml += '<div id="divRelatedConditionsLess" style="visibility:visible;">';                                     
                                        innerHtml += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"relatedBox\">";
			                
                                        data.RelatedConditions.each(function(item, index){
                                            innerHtml += "<tr><td height=\"5\"></td></tr>";
                                            innerHtml += "<tr><td>" + item + "</td></tr>";
                                        });
                                        
                                        innerHtml += "<tr><td height=\"5\"></td></tr>";
                                        if (data.RelatedConditionsSorted.length != data.RelatedConditions.length)
                                        {
                                            innerHtml += "<tr><td style=\"font-weight:bold; padding-bottom:10px;\"><a id=\"hlRelatedConditions\" href=\"Javascript: ContentSwitch('divRelatedConditionsMore', 'divRelatedConditionsLess', 'RelatedConditionsContent');\">More ></a></td></tr>";
                                        }
                                        innerHtml += "</table></div>";
                                        
                                        $('RelatedConditionsContent').innerHTML = innerHtml;
                                        
                                        if (data.RelatedConditionsSorted.length == 0)
                                        {
                                            if ($('tdRelatedConditionsLeft')) $('tdRelatedConditionsLeft').hide();
                                            if ($('tdRelatedConditionsRight')) $('tdRelatedConditionsRight').hide();
                                        }
                                    };
                                };
				
                                // PRODUCTS: Get the products html for this page
                                //----------------------------------------------------------
                                if(data.Products){                                    
                                    var gridRow = '';
                                    var recordCount = data.Products.length;
                                    var cellsOnRow = 0;
                                    data.Products.each(function(itm, index){
                                        var thisItem = itm[0].evalJSON(true);
                                        
                                        // Grid View                                    
                                        if(productsDisplayMode == 1){       
                                            // Determine if its the start of a row
                                            if(IsBeginRow(index, cellsPerRow) == true)
                                            {
                                                gridRow += beginRow;
                                                cellsOnRow = 0;
                                            }
                                            
                                            // Add a grid cell
                                            gridRow += GetGridCell(thisItem);
                                            cellsOnRow++;

                                            // Determine if its the end of a row
                                            if(IsEndRow(index, cellsPerRow, data.Products.length) == true) 
                                            {
                                                // If its the end but not a complete row then add empty cells..neatified
                                                var remainder = cellsPerRow - cellsOnRow;
                                                for(var x = 1; x<=remainder; x++){
                                                    gridRow += GetGridCell(null);
                                                }
                                                gridRow += endRow;
                                            }                                        
                                        }                                   
                                    }); 
                                };
                                
                                // Insert the row into the products table
                                //----------------------------------------------------------                                    
                                if(!gridRow.empty()){        
                                    var table = $('ProductsTable').update();
                                    table.insert(gridRow);
                                    //$('ProductsTable').innerHTML = gridRow.length + $('ProductsTable').innerHTML;
                                }
                                
                                // Handle Coremetrics tags
                                if(actionId && data.CMValues && data.CMCount){
                                    var pageId = CM_Page;
                                    // for A/B test.
                                    if (GetCookie("SEARCH_NAV_POS") != null && GetCookie("SEARCH_NAV_POS").length > 0)
                                    {
                                        pageId += " " +  GetCookie("SEARCH_NAV_POS");
                                    }
                                    cmCreatePageviewTag(pageId, data.CMValues, CM_Cat, data.CMCount);     
                                }
                            }
                        },
                    // TODO: Handle error here, ADAM What should we do here????
                    onFailure: function(){EndAJAXWaitProcess();},
                    onException: function(){EndAJAXWaitProcess();},
                    onComplete: function(){EndAJAXWaitProcess();}
                });
            }
        }

    };
}();