/*  © 2001 WeightWatchers.com, Inc. All rights reserved.
    Author: Calvin C. Beloy
    March 25, 2008
    Release: WW.COM/8.2
    An include javascript file of uctr_MeetingFinder.ascx.
    Handles javascripts events to hide/unhide More Options panel and use to handle javascript postback to location_results.aspx page.
*/
var TIMES_CRITERIA = 'Times';
var DAYS_CRITERIA = 'Days';
var CRITERIA_PANEL = 'mfOptionPanel';
var IMG_COLLAPSE_EXPAND = 'imgCollapseExpand';
var LNK_COLLAPSE_EXPAND = 'lnkCollapseExpand';
var RESULT_PAGE = 'location_results.aspx';
var FULL_VIEW = 'FullView';
var ZIP_SEARCH_TYPE = 'ZIP';

/* Variables declared in code behind uctr_MeetingFinder.ascx.
    1. MFCtl - associative array of client IDs of server controls.
    2. COLLAPSE_IMAGE = 'm_footPrint/images/m_locID/css//btn_arrowclose.gif';
    3. EXPAND_IMAGE = 'm_footPrint/images/m_locID/css/mtf/btn_arrowdown.gif';
    4. ZIP_WATERMARK
    5. CITY_WATERMARK
    6. ZIP_ERR_MSG - localized Zip Code required error message.
    7. CITYSTATE_ERR_MSG - localized City and State required error message.
    8. MORE_OPT_COLLAPSE_TEXT - Text to show when time/day/meeting type filter criteria panel is collapse.
    9. MORE_OPT_EXPAND_TEXT - Text to show when time/day/meeting type filter criteria panel is expanded.
    10. ALL_DAY - the All DayOfWeek value.
    11. ALL_TIMES = the All TimesOfDay value.
    12. elSearchType
    13. elDisplayMode
    14. ZIP_INVALID_ERR_MSG - Error message if zip code has invalid characters
    15. ZIP_REGEX - Regular expression to check zip 	
*/

function ToggleOptionPanel(doExpand, toggleLink)
{
    var optionPanel = YAHOO.util.Dom.get(CRITERIA_PANEL);
    // doExpand will not be null when the page is from a postback and need to 
    // preserve the previous expand state of the search criteria option panel.
    if(null != doExpand || undefined != doExpand)
    {
        HidePanel(optionPanel, !doExpand); //
        ToogleOptionLnk(toggleLink,!doExpand);

    }else
    {
       // When the user just clicks on the toggle link or image.
       TooglePanel(optionPanel, toggleLink);
    }
}

function TooglePanel(optionPanel, toggleLink)
{    
    //If it is previously hidden then make it visible and vise versa.
    var doHide = optionPanel.style.display == "none" ? false: true
    HidePanel(optionPanel, doHide);
    ToogleOptionLnk(toggleLink, doHide);
}

function HidePanel(oEl, blnHide)
{    
    if(blnHide)
    {   
        oEl.style.display = "none";              
    }    
    else
    {    
        oEl.style.display = "";
    }
}
//Use to change the text of the link when its in collapse or expanded state.
function ToogleOptionLnk(elLink,blnHide)
{
    // elLink will be null when the calling function is not due to user clicking the link or image 
    // but coming from javascript call to preserve previous toggle state during postback.
    // Expand and collapse link will only be available in FullView mode.
    if( elLink == undefined || elLink == null )
    {
       elLink = YAHOO.util.Dom.get(LNK_COLLAPSE_EXPAND); 
    }        

    var srcImage ="";
    var lnkText = "";
    
    if(blnHide)
    {
        srcImage = COLLAPSE_IMAGE;
        lnkText = MORE_OPT_COLLAPSE_TEXT;
    }else{
        srcImage = EXPAND_IMAGE;
        lnkText =  MORE_OPT_EXPAND_TEXT;
    }
    //Change both the image and the link text.    
    if(elLink.firstChild.tagName == 'IMG')
    {
        elLink.firstChild.src = srcImage;
        var lnk = YAHOO.util.Dom.get(LNK_COLLAPSE_EXPAND)
        lnk.firstChild.firstChild.innerHTML = lnkText;
    }else
    {
        elLink.firstChild.firstChild.innerHTML = lnkText;
        var img = YAHOO.util.Dom.get(IMG_COLLAPSE_EXPAND);
        if(img != undefined && img != null)
        {
            img.src = srcImage;
        }
    }
}

// This function is use to unselect and select the checkboxes of Times and Days search criteria.
function SetSelected(oChkb, criteriaType)
{    
    // Check if the Times is All Times = 7 or All Days = 8, and if it is checked, then 
    // all other TimesCriteria checkboxes should be unchecked.    
        
    var selectAll 
    if(criteriaType == DAYS_CRITERIA)
    {
        selectAll = ALL_DAY;
    }else
    {
        selectAll = ALL_TIMES;
    }
    // If click checkbox is the Any Day or Any Time checkbox, then uncheck the other checkboxes.
    if(oChkb.value == selectAll && oChkb.checked)
    {   
        var allChkBoxes = YAHOO.util.Dom.getElementsBy (
                    function(el){if(el.name.indexOf(criteriaType) != -1){return true;}},'INPUT');
        
        for(ctr = 0; ctr < allChkBoxes.length; ctr++)
        {
            if(allChkBoxes[ctr].value != selectAll) // Exclude the All day/All Times checkbox
            {
                allChkBoxes[ctr].checked = false;
            }
        }
    }else
    {
        // Should test if all times criteria are already selected, 
        // if it is, should checked AllTimes/Days checkbox and unchecked the others.
       if(oChkb.checked) 
       {
            TestSelected(criteriaType);
       }
    }
}

// If AllDay or Any Time is selected then unselect other checkboxes.
// If have selected all days or all times then select All Day/Any time and the unselect the others
function TestSelected(criteriaType)
{   
    var isAllSelected = true; 
    var selectAll 
    if(criteriaType == DAYS_CRITERIA)
    {
        selectAll = ALL_DAY;
    }else
    {
        selectAll = ALL_TIMES;
    }
    
    var allChkBoxes = YAHOO.util.Dom.getElementsBy (
                function(el){if(el.name.indexOf(criteriaType) != -1){return true;}},'INPUT');
    
    // Iterate the checkboxes to determine if all have been checked which need to 
    // check the All Day/Any Time checkbox and then uncheck the others.
    for(ctr=0 ; ctr < allChkBoxes.length; ctr++)
    {
        if(allChkBoxes[ctr].value != selectAll) // Exclude the All day/All times checkbox
        {
            if(!allChkBoxes[ctr].checked)
            {
                isAllSelected = false;
                break;
            }            
        }else
        {
            allChkBoxes[ctr].checked = false;
        }
    }
    if(isAllSelected)
    {
        for(ctr=0; ctr <allChkBoxes.length; ctr++)
        {
            var isAllCheckBox = allChkBoxes[ctr].value == selectAll;
            allChkBoxes[ctr].checked = isAllCheckBox;
        }    
    }
}

// Sets back the selected Days from a postback.
// daysOfWeek is a comma delimited string of the 
function SetSelectedDays(daysOfWeek)
{    
    var allChkBoxes = YAHOO.util.Dom.getElementsBy (
                function(el){if(el.name.indexOf(DAYS_CRITERIA) != -1){return true;}},'INPUT');
    
     //If selected all 7 days, select All Day checkbox.
    if(daysOfWeek != "")
    {
        // When query string has d=1,2,3,4,5,6,7 - means AllDays, then select only AllDay checkbox.
        if(daysOfWeek.split(',').length	== 7) // Check AllDay 
        {
            allChkBoxes[0].checked = true;
        }else
        {
            for(ctr=0 ; ctr < allChkBoxes.length; ctr++)
            {
                var reSelect = daysOfWeek.indexOf(allChkBoxes[ctr].value) >= 0;
                allChkBoxes[ctr].checked = reSelect;
            }
        }
    }else //Set default to AllDay selected.
    {
        allChkBoxes[0].checked = true;
    }
}

// Sets back the selected Times from a postback.
function SetSelectedTimes(timesOfDay)
{   
    var allChkBoxes = YAHOO.util.Dom.getElementsBy (
                function(el){if(el.name.indexOf(TIMES_CRITERIA) != -1){return true;}},'INPUT');
    
    if(timesOfDay != "")
    {
        for(ctr=0 ; ctr < allChkBoxes.length; ctr++)
        {
            var reSelect = timesOfDay.indexOf(allChkBoxes[ctr].value) >= 0 ;
            allChkBoxes[ctr].checked = reSelect;
        }
    }else
    {
        //Set default to All Times 
        allChkBoxes[0].checked = true;
    }
    
        
}

// This method is use on all buttons/linkbuttons in MF user control.
// This where the url query string is build and form submitted.
function MFSubmit(pageForm)
{
    if(!ValidateMFForm())
    {
        return;
    }
    var currentUrl = top.location.href;
    if (currentUrl.indexOf("#") != -1)
    {
        currentUrl = currentUrl.substring(0,currentUrl.indexOf("#"));
    }

    var newUrl = '';
    var MFMgr = new SeachCriteriaMgr(); // Helper to get the search criteria from the form's input fields.
    var searchCriteria = MFMgr.GetSearchCriteria();
    //Check if the current url is the location_results.aspx, if it is just the current url, when its not use
    // the locatin_results.aspx url as the postback url.
    if(currentUrl.indexOf(RESULT_PAGE) >= 0)
    {        
        newUrl = currentUrl;
        if(currentUrl.indexOf("?") == -1)
        {
            newUrl +="?";
        }
        
    }else //Should preserve the query string to make sure other parts of the page that use some parameters in the query string will work fine. 
    {        
        newUrl += RESULT_PAGE;
        
        var index = currentUrl.indexOf("?");        
        var currentQS = index >=0 ? currentUrl.substr(index) : "?";
        newUrl += currentQS;        
    }
   //remove existing parameter to avoid duplicate
    newUrl = newUrl.replace(/((&|)(pg)=[\d]*)+/,'');
    newUrl = newUrl.replace(/((&|)(ref)=[\w\%\s]*)+/,''); //remove ref QS when in SimpleView or user control in pricingWrapper.aspx.
    newUrl = newUrl.replace(/((&|)(locationid|locationId)=[\d]*)+/,''); //remove also location id.   
    newUrl = newUrl.replace(/((&|)(stn)=[(\w\.\%\+\s)]*)+/,'');    
    newUrl = newUrl.replace(/((&|)(st)=[\w\+]*)+/,'');
    newUrl = newUrl.replace(/((&|)(s)=[\w]*)+/,'');
    newUrl = newUrl.replace(/((&|)(d)=[(\d)(\,)]*)+/,'');    
    newUrl = newUrl.replace(/((&|)(mt)=[-\d]*)+/,'');
    newUrl = newUrl.replace(/((&|)(t)=[(\d)(\,)]*)+/,'');
    newUrl = newUrl.replace(/((&|)(c)=[\w\s\%\+]*)+/,'');    
    newUrl = newUrl.replace(/((&|)(z)=[\d]*)+/,'');
    
    newUrl += searchCriteria != undefined ? searchCriteria.ToQueryString() : "";
    
    var oForm = document.forms[0];
    oForm.target="_top"
    oForm.action = newUrl;
    oForm.submit();
}

function ValidateMFForm()
{     
     // Validate ZipCode input field     
     var elCity;
     var elZipCode;
     var elState;
     
     // Get input appropriate input fields base on DisplayMode
     if(elDisplayMode.value == FULL_VIEW)
     {
        elZipCode = YAHOO.util.Dom.get(MFCtl.txtZipCodeFlvw);
        elCity = YAHOO.util.Dom.get(MFCtl.txtCityFlvw);
        elState = YAHOO.util.Dom.get(MFCtl.ctlStatesDropDownFlvw);
     }else
     {
        elZipCode = YAHOO.util.Dom.get(MFCtl.txtZipCodeCmpvw);
        elCity =  YAHOO.util.Dom.get(MFCtl.txtCityCmpvw);
        elState = YAHOO.util.Dom.get(MFCtl.ctlStatesDropDownCmpvw);
     }
      
     if(elSearchType.value == ZIP_SEARCH_TYPE)
     {  
       if(elZipCode.value == "" || elZipCode.value == ZIP_WATERMARK)

       {
            alert(ZIP_ERR_MSG);
            return false;
       }
	    if(!elZipCode.value.match(ZIP_REGEX))
       {
            //only show alert in full view(index page), since results page handles
            //validation on server side
            if (elDisplayMode.value == FULL_VIEW)
            {
                elZipCode.focus();
                alert(ZIP_INVALID_ERR_MSG);
                return false;
            }
       }
     }else // Validate city and state; they are mandatory
     {
        if(elCity.value == "" || elCity.value == CITY_WATERMARK_F || elCity.value == CITY_WATERMARK_C) 
        {
            alert(CITY_ERR_MSG);
            return false; 
        }
        else 
        {
            if(elState.selectedIndex == 0)
            {
                alert(CITYSTATE_ERR_MSG);
                return false;
            }
        }
     }
     if (elCity.value == CITY_WATERMARK_F || elCity.value == CITY_WATERMARK_C)
     {
        elCity.value= "";
     }
     return true;   
}

function SetWaterMark(elTextBox,txtType)
{
    var waterMark = "";
    if(elDisplayMode.value == FULL_VIEW)
    {
        if(txtType == "city")
        {
            waterMark = CITY_WATERMARK_F;
        }else
        {
            waterMark = ZIP_WATERMARK;        
        }        
    }else
    {
        if(txtType == "city")
        {
            waterMark = CITY_WATERMARK_C;
        }
    }
    if(elTextBox.value =="")
        elTextBox.value = waterMark;
}

function ClearWaterMark(elTextBox, txtType)
{
    if(txtType == "city")
    {
        if (elTextBox.value == CITY_WATERMARK_F || elTextBox.value == CITY_WATERMARK_C )
            elTextBox.value = "";
    }
    if(txtType == "zip")
    {
        if (elTextBox.value == ZIP_WATERMARK)
            elTextBox.value = "";
    }
}
// Contains objects to parse form input fields and create a SearchCriteria to be used as a query string in a postback to location_results.aspx page.
// Warning: The objects in this file are tightly coupled to the meeting finder usercontrol (uctr_MeetingFinder.ascx).
(function() 
{
    // This is a helper object for getting the user selected criteria.
    SeachCriteriaMgr = function(){};

    var proto= SeachCriteriaMgr.prototype;    
    
    // Returns the SearchCriteria object.   
    proto.GetSearchCriteria = function()
    {
        var searchCriteria = new SearchCriteria();
        
        //Need to know on what DisplayMode the control is, since forn input control Id's is different between FullView and CompactView.
        //While CompactView and SimpleView share the same form input controls.
        searchCriteria.SearchType = elSearchType.value;
            
        if(elDisplayMode != undefined && elDisplayMode != null )
        {
            //Gets the ZipCode, City and State, and MeetingType criteria.
            this.GetMainSearchCriteria(searchCriteria, elDisplayMode.value);
        }
        searchCriteria.TimeOfDays = this.GetTimeOfDay();
        searchCriteria.DaysOfWeek = this.GetDaysOfWeek(false);
        return searchCriteria;
    };
    
    
    proto.GetMainSearchCriteria = function(oSearchCriteria, displayMode)
    {
        var elZipCode;
        var elCity;
        var elStates;
        var elMeetingType;
        // Get appropriate input fields base on display mode.
        if(displayMode == FULL_VIEW )
        {
            elZipCode = YAHOO.util.Dom.get(MFCtl.txtZipCodeFlvw);
            elCity = YAHOO.util.Dom.get(MFCtl.txtCityFlvw);
            elStates = YAHOO.util.Dom.get(MFCtl.ctlStatesDropDownFlvw);
            elMeetingType =  YAHOO.util.Dom.get(MFCtl.ddlMeetingTypesFlvw)
               
        }else
        {
            elZipCode = YAHOO.util.Dom.get(MFCtl.txtZipCodeCmpvw);
            elCity = YAHOO.util.Dom.get(MFCtl.txtCityCmpvw);
            elStates = YAHOO.util.Dom.get(MFCtl.ctlStatesDropDownCmpvw);
            elMeetingType =  YAHOO.util.Dom.get(MFCtl.ddlMeetingTypesCmpvw);
        }
        //Get Meeting Type
        if(elMeetingType != undefined && elMeetingType != null)
        {
            oSearchCriteria.MeetingType = elMeetingType.options[elMeetingType.selectedIndex].value;
        } 
        //Get Zip Code        
        if(oSearchCriteria.SearchType == ZIP_SEARCH_TYPE)
        {           
            if(elZipCode != undefined && elZipCode != null)
            {
                oSearchCriteria.ZipCode = elZipCode.value;
            }
        }else // Get City and State
        {            
            if(elCity != undefined && elCity != null)
            {
                oSearchCriteria.City = elCity.value;
            }            
            if(elStates != undefined && elStates != null)
            {
                oSearchCriteria.StateID = elStates.options[elStates.selectedIndex].value;
                oSearchCriteria.StateName = elStates.options[elStates.selectedIndex].text;
            }
        }
    };    
    // Gets the selected TimeOfDay from the input checkboxes
    proto.GetTimeOfDay = function()
    {        
        var times = new Array();
        var selectedTimeOfDay = YAHOO.util.Dom.getElementsBy (
        function(el){if(el.name.indexOf(TIMES_CRITERIA) != -1)
                {
                    if(el.checked)
                        return true;
                }
            },'INPUT');
            
        for(ctr = 0; ctr < selectedTimeOfDay.length; ctr++)
        {
            times[ctr] = selectedTimeOfDay[ctr].value;
        }
        return times;
    
    };
    // Gets the selected DaysOfWeek from the input checkboxes
    // If blnAllDay = true, it gets all DaysOfWeek checkbox except the AllDay checkbox.
    // if false, then just get the DaysOfWeek from whatever selected checkboxes.
    proto.GetDaysOfWeek = function(blnAllDay)
    {
        var days = new Array();
        var selDaysOfWeek = YAHOO.util.Dom.getElementsBy (
        function(el){if(el.name.indexOf(DAYS_CRITERIA) != -1)
                {
                    if(!blnAllDay) 
                    {
                        if(el.checked)
                            return true;
                    }else //if its All Day then select all checkboxes except the all day checkbox.
                    {
                        if(el.value != ALL_DAY)
                            return true;
                    }
                }
            },'INPUT');
            
        for(ctr = 0; ctr < selDaysOfWeek.length; ctr++)
        {
            days[ctr] = selDaysOfWeek[ctr].value;
        }
        
        //  If it's All Day then return all other checkbox values except the AllDay checkbox.
        if(days.length == 1 && days[0] == ALL_DAY) 
        {
            return this.GetDaysOfWeek(true);            
        }else
        {
            return days;
        }
    };
 })();
 
 (function()
 {
    SearchCriteria = function(){};
    var proto = SearchCriteria.prototype;
    proto.City = "";
    proto.SearchType = "";
    proto.ZipCode = "";
    proto.StateID="";
    proto.StateName = "";
    proto.TimeOfDays=new Array();
    proto.DaysOfWeek = new Array();
    proto.MeetingType = "";
    proto.ToQueryString = function()
    {
        //Always add pg for paging control in location result page to work.
        var strQS="&pg=0";
        if(this.SearchType == ZIP_SEARCH_TYPE )
        {   
            strQS +="&s=ZIP";
            strQS +="&z=" + this.ZipCode;   
        }else
        {
            strQS +="&s=CS";
            strQS +="&c=" + this.City;
            strQS +="&st=" + this.StateID + "&stn=" + this.StateName;    
        }
        strQS +="&t=" + this.TimeOfDays.join();
        strQS +="&d=" + this.DaysOfWeek.join();
        strQS +="&mt=" + this.MeetingType;
        return strQS;
    };
 })();