﻿var parseLocations;
var parseLocationValidator;
var redirectToResultsIfValid;

function onSliderChanged(val)
{
    var ageMin = parseInt(val[0]);
    var ageMax = parseInt(val[1]);
    $(hdnMin).value = ageMin;
    $(hdnMax).value = ageMax;
    
    renderInputs();
}
function onSliderSlides(val)
{
    var ageMin = parseInt(val[0]);
    var ageMax = parseInt(val[1]);
    $(hdnMin).value = ageMin;
    $(hdnMax).value = ageMax;
    
    renderInputs();
}

function renderInputs()
{
    $('highlighter').style.left = parseInt($('sliderHandle1').style.left) + "px";
    $('highlighter').style.width = (parseInt($('sliderHandle2').style.left) - parseInt($('sliderHandle1').style.left))  + "px";
    
    $('lblAgeRange').innerHTML  = $(hdnMin).value + "-" + $(hdnMax).value;
}

function SetGender(value, hdnValue, imgMaleOnID, imgMaleOffID, imgFemaleOnID, imgFemaleOffID)
{
    $(hdnValue).value = value;
    
    if (value == 'male')
    {
        $(imgMaleOnID).style.display = 'block';
        $(imgMaleOffID).style.display = 'none';
        $(imgFemaleOnID).style.display = 'none';
        $(imgFemaleOffID).style.display = 'block';
    }
    
    if (value == 'female')
    {
        $(imgMaleOnID).style.display = 'none';
        $(imgMaleOffID).style.display = 'block';
        $(imgFemaleOnID).style.display = 'block';
        $(imgFemaleOffID).style.display = 'none';
    }
    
    if ((value != 'male') && (value != 'female'))
    {
        $(imgMaleOnID).style.display = 'none';
        $(imgMaleOffID).style.display = 'block';
        $(imgFemaleOnID).style.display = 'none';
        $(imgFemaleOffID).style.display = 'block';
    }
    
    setLookingForGender();
}

function setLookingForGender()
{
    var gender = $(hdnLookingFor).value;
    if (gender == "male")
    {
        $("ageMale").style.display = 'block';
        $("ageFemale").style.display = 'none';
    }
    else
    {
        $("ageMale").style.display = 'none';
        $("ageFemale").style.display = 'block';
    }
}

function toggleSearchMode()
{
    var showSearchBoxValue = $(hdnShowSearchBox).value.toLowerCase();
    if (showSearchBoxValue != 'true')
    {
        showMe(true); 
    }
    else
    {
        showMe(false); 
    }

    if ($(hdnAdvancedSearch).value == 'true')
    {
        $(hdnAdvancedSearch).value = 'false';
    }
    else
    {
        $(hdnAdvancedSearch).value = 'true';
    }
    refreshSearchControls();    
}

function refreshSearchControls()
{
    if ($(hdnAdvancedSearch).value != 'false')
    {
        $('tblAdvancedSearch').style.display = 'block';
        $('trNickname').style.visibility = 'visible';
        $('btnSearchMode').innerHTML = 'Less Search Options';
        //$('spnSaveSearch').style.display = 'block';
    }
    else
    {
        $('tblAdvancedSearch').style.display = 'none';
        $('trNickname').style.visibility = 'hidden';
        $('btnSearchMode').innerHTML = 'More Search Options';
        //$('spnSaveSearch').style.display = 'none';
    }
    
    setLookingForGender();
}

function redirectToSearchResults()
{
    var url = redirectUrl;
    var keywords = encodeURI( $(txtKeywords).value.replace(/^\s+|\s+$/g, '') );
    var locatedNear = $(txtLocatedNear).value;
    var nickname = encodeURI( $(txtNickname).value.replace(/^\s+|\s+$/g, '') );
    var distance;
    
    if (locatedNear == initialLocationValue)
    {
        locatedNear = '';
        distance = '';
    }
    else
    {
        locatedNear = encodeURI( locatedNear.replace(/^\s+|\s+$/g, '') );
        
        var objDdlDistance = $(ddlDistance);
        
        if (objDdlDistance.value == "0")
        {
            distance = encodeURI( defaultDistance )
        }
        else
        {
            distance = encodeURI( objDdlDistance.value );
        }
    }
    
    
    
    if ($(hdnGender).value=='male')
    {
        url += 'gender=1&'
    }
    else
    {
        url += 'gender=2&'
    }
    
    if ($(hdnLookingFor).value=='male')
    {
        url += 'lookingfor=1&'
    }
    else
    {
        url += 'lookingfor=2&'
    }
    
    url += 'ageMin=' + $(hdnMin).value;
    url += '&ageMax=' + $(hdnMax).value;
    
    if ((keywords.length > 0) && ($(txtKeywords).value != initialKeywordsValue))
    {
        url += '&keywords=';
        url += keywords;
    }
    
    if (locatedNear.length > 0)
    {
        url += '&locatednear=';
        url += locatedNear;
    }
    
    if (distance.length > 0)
    {
        url += '&distance=';
        url += distance;
    }
    
    if (nickname.length > 0)
    {
        url += '&nickname=';
        url += nickname;
    }
    
    if ($(hdnAdvancedSearch).value == 'true')
    {
        maritalStatus = $(ddlMaritalStatus).value;
        if (maritalStatus != '0')
        {
            url += '&maritalstatus=';
            url += maritalStatus;
        }
        
        religion = $(ddlReligion).value;
        if (religion != '0')
        {
            url += '&religion=';
            url += religion;
        }
        
        ethnicity = $(ddlEthnicity).value;
        if (ethnicity != '0')
        {
            url += '&ethnicity=';
            url += ethnicity;
        }
        
        bodyType = $(ddlBodyType).value;
        if (bodyType != '0')
        {
            url += '&bodytype=';
            url += bodyType;
        }
        
        heightMin = $(ddlHeightMin).value;
        if (heightMin != '0')
        {
            url += '&heightMin=';
            url += heightMin;
        }
        
        heightMax = $(ddlHeightMax).value;
        if (heightMax != '0')
        {
            url += '&heightMax=';
            url += heightMax;
        }   
    }
    
    selectedSites = getSelectedSites();
    if (selectedSites.length > 0)
    {
        url += '&selectedSites=';
        url += selectedSites;
    }  
    
    if ($(chkSaveSearch).checked)
    {
        url += '&savesearch=1';
    }       
    
    if ($(chkSearchSafeOnly).checked)
    {
        url += '&searchsafe=1';
    }  
    
    url += '&advancedsearch=';
    if ($(hdnAdvancedSearch).value != 'true')
    {
        url += '0';
    }
    else
    {
        url += '1';
    }
    
    url += '&showSearchBox=';
    url += $(hdnShowSearchBox).value;
    
    location.href = url;
}

function hideMe(useAnimation)
{
    if (useAnimation)
    {
        //$('searchBoxContents').style.visibility = 'hidden';
        new Effect.SlideUp($('searchBoxContents'), {duration:0.5});
    }
    else
    {
        $('searchBoxContents').style.display = 'none';
    }
    $('anchorHideSearchContents').style.display = 'none';
    $('anchorShowSearchContents').style.display = 'block';     
    $(hdnShowSearchBox).value = 'false';  

    updatePagesLinks(); 
}

function showMe(useAnimation)
{
    if (useAnimation)
    {
        //$('searchBoxContents').style.visibility = 'visible';
        new Effect.SlideDown($('searchBoxContents'), {duration:0.5});
    }
    else
    {
        $('searchBoxContents').style.display = 'block';
    }
    $('anchorHideSearchContents').style.display = 'block';
    $('anchorShowSearchContents').style.display = 'none'; 
    
    $(hdnShowSearchBox).value = 'true';
    
    updatePagesLinks();
}

function locationCheckPressedKey(e)
{
    var key = e.keyCode;
    
    if (key == 38)
    {
        if (selectedLocationSuggestion > 0)
        {
            selectedLocationSuggestion--;
            updateSelectedLocation();
        }
        return false;
    }
    if (key == 40)
    {
        if (selectedLocationSuggestion < (totalSuggestedLocations - 1))
        {
            selectedLocationSuggestion++;
            updateSelectedLocation();
        }
        return false;
    }
    if (key == 13)
    {
        if (selectedLocationSuggestion >= 0)
        {
            $(txtLocatedNear).value = getSelectedLocation();
            hideLocationSuggestions();
        }
        
        return false;
    }
    if (key == 27)
    {
        if (selectedLocationSuggestion >= 0)
        {
            hideLocationSuggestions();
        }
        
        return false;
    }
    
    return true;
}

function Location(zip, name)
{
    this.zip = zip;
    this.name = name;
    
    this.toString = function()
    {
        return this.name;
    }
}

function locationCheckRequery()
{
    var currentValue = ($(txtLocatedNear).value);
    if (currentValue != prevLocationValue)
    {
        prevLocationValue = currentValue;
        
        if (prevLocationValue.length >= 3)
        {
            requeryLocations(prevLocationValue);
        }
        else
        {
            hideLocationSuggestions();
        }
        
        if (prevLocationValue.length == 0)
        {
            SetDropDownListValue($(ddlDistance), '');
        }
        else
        {
            SetDropDownListValue($(ddlDistance), defaultDistance);
        }
    }
}

function requeryLocations(str)
{
    getMatchingLocations(str);
}

parseLocations = function(xhr)
{
    locationsXml = xhr.responseText;
    var xmlLocations;
    if (window.ActiveXObject)
    {
        xmlLocations = new ActiveXObject("msxml.DOMDocument");
        xmlLocations.loadXML(locationsXml);
    } else if (document.implementation && document.implementation.createDocument)
    {
        parser = new DOMParser();
        xmlLocations = parser.parseFromString(locationsXml, "text/xml");
    }
    
    var locationsArray = new Array();
	var items = xmlLocations.selectNodes("/locations/location");
	var loc = null;
	var obj = null;
	for (i=0; i<items.length; i++)
	{
	    obj = items[i];
	    loc = new Location(obj.attributes[0].value, obj.attributes[1].value);
	    locationsArray[i] = loc;
	}
	
	bindLocations(locationsArray);
}

function bindLocations(locations)
{
    if (locations.length == 0)
    {
        hideLocationSuggestions();
        return;
    }
    
    if ((locations.length == 1) && (locations[0].name == prevLocationValue))
    {
        hideLocationSuggestions();
        return;
    }
    
    var divSuggestion = $(divLocationSuggestions);
    selectedLocationSuggestion = -1;
    totalSuggestedLocations = locations.length;
    
    while (divSuggestion.childNodes.length > 0)
    {
        divSuggestion.removeChild(divSuggestion.childNodes[0]);
    }
    
    for(i=0; i<locations.length;i++)
    {
        var locDiv = document.createElement("DIV");
		locDiv.id = locationPrefix + i;
		locDiv.className = suggestionStyle;
		locDiv.innerHTML = locations[i].toString();
		locDiv.onclick = function()
		{
		    setLocationValue(this.innerHTML);
		    hideLocationSuggestions();
		}
		divSuggestion.appendChild(locDiv);
    }
    
    updateSelectedLocation();
    divSuggestion.scrollTop = 0;
    
    divSuggestion.style.display = 'block';
}

function setLocationValue(str)
{
    $(txtLocatedNear).value = str;
    prevLocationValue = str;
}

function updateSelectedLocation()
{
    var divSuggestion = $(divLocationSuggestions);
    var objLoc;
    
    for (i=0; i<divSuggestion.childNodes.length;i++)
    {
        objLoc = divSuggestion.childNodes[i];
        if (objLoc.id == locationPrefix + selectedLocationSuggestion)
        {
            objLoc.className = suggestionSelectedStyle;
            if (divSuggestion.scrollTop > (i) * suggestionItemHeight)
            {
                divSuggestion.scrollTop = i*suggestionItemHeight;
            }
            
            if (divSuggestion.scrollTop+(suggestionScrollItems-1)*suggestionItemHeight < (i) * suggestionItemHeight)
            {
                divSuggestion.scrollTop = (i-(suggestionScrollItems-1))*suggestionItemHeight;
            }
        }
        else
        {
            objLoc.className = suggestionStyle;
        }
    }
}

function getSelectedLocation()
{
    var divSuggestion = $(divLocationSuggestions);
    var objLoc;
    
    for (i=0; i<divSuggestion.childNodes.length;i++)
    {
        objLoc = divSuggestion.childNodes[i];
        if (objLoc.className == suggestionSelectedStyle)
        {
            return objLoc.innerHTML;
        }
    }
}

function hideLocationSuggestions()
{
    if (!locationSuggestionsHasFocus)
    {
        var divSuggestion = $(divLocationSuggestions);
        selectedLocationSuggestion = -1;
        totalSuggestedLocations = 0;
        
        while (divSuggestion.childNodes.length > 0)
        {
           divSuggestion.removeChild(divSuggestion.childNodes[0]);
        }
        
        updateSelectedLocation();
        
        divSuggestion.style.display = 'none';
    }
}

function locationLostFocus()
{
    locationTextboxHasFocus = false;
    prevLocationValue = $(txtLocatedNear).value;
    var t = setTimeout("locationLostFocus2()", 100);
}

function keywordsLostFocus()
{
    keywordsTextboxHasFocus = false;
    
    if ($(txtKeywords).value == '')
    {
        setInitialKeywordsValue(true);
    }
}

function locationLostFocus2()
{
    if (!locationSuggestionsHasFocus)
    {
        var t = setTimeout("hideLocationSuggestions()", 100);
        prevLocationValue = $(txtLocatedNear).value;
        validateZipOrCityState(prevLocationValue);
        
        if ($(txtLocatedNear).value == '')
        {
            setInitialLocationValue(true);
        }
    }
}

function locationSuggestionLostFocus()
{
    locationSuggestionsHasFocus = false;
    prevLocationValue = $(txtLocatedNear).value;
    var t = setTimeout("locationSuggestionLostFocus2()", 100);
}

function locationSuggestionLostFocus2()
{
    if (locationTextboxHasFocus != true)
    {
        var t = setTimeout("hideLocationSuggestions()", 100);
        prevLocationValue = $(txtLocatedNear).value;
        validateZipOrCityState(prevLocationValue);
    }
}

function getMatchingLocations(str)
{
    getXMLdoc(locationSuggestionsXML + str, parseLocations);
}

function validateZipOrCityState(str)
{
    str = encodeURI(str);
    
    if (str.length > 0)
    {
        getXMLdoc(locationValidationXML + str, parseLocationValidator);
    }
    else
    {
        showInvalidZipOrCityStateMessage(false);
    }
}

parseLocationValidator = function(xhr)
{
    var xmlAnswer = xhr.responseText;
    bResult = !checkLocationValidatorAnswer(xmlAnswer);
    showInvalidZipOrCityStateMessage(bResult);
}

function checkLocationValidatorAnswer(xmlAnswer)
{
    var xmlLocations;
    if (window.ActiveXObject)
    {
        xmlLocations = new ActiveXObject("msxml.DOMDocument");
        xmlLocations.loadXML(xmlAnswer);
    } else if (document.implementation && document.implementation.createDocument)
    {
        parser = new DOMParser();
        xmlLocations = parser.parseFromString(xmlAnswer, "text/xml");
    }
    
	var answer = xmlLocations.selectSingleNode("/locations/response");
	var zip = answer.attributes[0].value;
	var input = answer.attributes[1].value;
	if (input == prevLocationValue)
	{
	    return (zip.length > 0);
	}
	else
	{
	    return false;
	}
}

function showInvalidZipOrCityStateMessage(show)
{
    $(divInvalidZipOrCityState).style.display = show ? 'block' : 'none';    
}

function distanceChanged(obj)
{
    if ($(ddlDistance).value == '0')
    {
        showInvalidZipOrCityStateMessage(false);
    }
}

function locationGotFocus()
{
    locationTextboxHasFocus=true;
    showInvalidZipOrCityStateMessage(false);
    if ($(txtLocatedNear).value == initialLocationValue)
    {
        setInitialLocationValue(false);
    }
}

function keywordsGotFocus()
{
    keywordsTextboxHasFocus=true;
    if ($(txtKeywords).value == initialKeywordsValue)
    {
        setInitialKeywordsValue(false);
    }
}

function setInitialLocationValue(isInitial)
{
    if (isInitial)
    {
        $(txtLocatedNear).value = initialLocationValue;
        $(txtLocatedNear).style.color = 'gray';
    }
    else
    {
        $(txtLocatedNear).value = '';
        $(txtLocatedNear).style.color = '#000000';
    }
}

function setInitialKeywordsValue(isInitial)
{
    if (isInitial)
    {
        $(txtKeywords).value = initialKeywordsValue;
        $(txtKeywords).style.color = 'gray';
    }
    else
    {
        $(txtKeywords).value = '';
        $(txtKeywords).style.color = '#000000';
    }
}

function setLocationStyle()
{
    if (($(txtLocatedNear).value == '') || ($(txtLocatedNear).value == initialLocationValue))
    {
        $(txtLocatedNear).style.color = 'gray';
        $(txtLocatedNear).value = initialLocationValue;
    }
    else
    {
        $(txtLocatedNear).style.color = '#000000';
    }
}

function setKeywordsStyle()
{
    if (($(txtKeywords).value == '') || ($(txtKeywords).value == initialKeywordsValue))
    {
        $(txtKeywords).style.color = 'gray';
        $(txtKeywords).value = initialKeywordsValue;
    }
    else
    {
        $(txtKeywords).style.color = '#000000';
    }
}

function validateForm()
{
    if (($(txtLocatedNear).value.length > 0) && ($(txtLocatedNear).value != initialLocationValue))
    {
        getXMLdoc(locationValidationXML + encodeURI($(txtLocatedNear).value), redirectToResultsIfValid);
    }
    else
    {
        redirectToSearchResults();
    }
}

redirectToResultsIfValid = function(xhr)
{
    var txtAnswer = xhr.responseText;
    
    if (checkLocationValidatorAnswer(txtAnswer))
    {
        redirectToSearchResults();
    }  
    else
    {
        showInvalidZipOrCityStateMessage(true);
    }      
}

function updatePagesLinks()
{
    var links = document.getElementsByName('pageLink');
    var link;
    var href;
    var showSearchBoxValue = $(hdnShowSearchBox).value.toLowerCase();
    var isAdvancedSearch = $(hdnAdvancedSearch).value.toLowerCase();
    
    for (i=0; i<links.length; i++)
    {
        link = links[i];
        href = link.href.toLowerCase();
        
        if (href.indexOf('&showsearchbox=') < 0)
        {
            href = href + '&showsearchbox=';
            href = href + showSearchBoxValue;
        }
        else
        {
            if (showSearchBoxValue != 'true')
            {
                href = href.replace('&showsearchbox=true', '&showsearchbox=false');
            }
            else
            {
                href = href.replace('&showsearchbox=false', '&showsearchbox=true');
            }
        }
        
        if (isAdvancedSearch != 'true')
        {
            href = href.replace('&advancedsearch=1', '');
        }
        else
        {
            if (href.indexOf('&advancedsearch=') > 0)
            {
                href = href.replace('&advancedsearch=0', '&advancedsearch=1');
            }
            else
            {
                href = href + '&advancedsearch=1';
            }
        }
        
        link.href = href;
    }
}

function showSitesList(show)
{
    var obj = $('divSitesList');
    
    if (show)
    {
        new Effect.Appear(obj, {duration:0.3});
    }
    else
    {
        new Effect.Fade(obj, {duration:0.3});
    }
}

function getSelectedSites()
{
    return encodeURI(selectBoxGetValue(sbSitesID));
}