var lc_xmlhttpreq;
var sCurrPrefix="lw";

function initLocateWidget(locationID, fType, sPrefix)
{
    notebar_lid = locationID;
    nbfeatureType = fType;

    initFromToYear(sPrefix + "_from_yr", sPrefix + "_to_yr");
    initFromToMonth(sPrefix + "_from_month", sPrefix + "_to_month");

    setFeatureValuesByWidget(fType, sPrefix + "_activityInput2");
}

function initFromToYear(sFromYearId, sToYearId, sFromYearValue, sToYearValue)
{
    var from_year = document.getElementById(sFromYearId);
    var to_year = document.getElementById(sToYearId);

    if (from_year != null && to_year != null) {

        var d = new Date();
        var year = d.getFullYear();

        from_year.options.length = year - 1910;
        to_year.options.length = year - 1910;

        for (yr = year, j = 0; yr >= 1911; yr--, j++) {
            to_year.options[j].text = yr;
            to_year.options[j].value = yr;
            if (sToYearValue && sToYearValue.length > 0 && sToYearValue == yr)
            {
                to_year.options[j].selected = "1";
            }
            from_year.options[j].text = yr;
            from_year.options[j].value = yr;
            if (sFromYearValue && sFromYearValue.length > 0 && sFromYearValue == yr)
            {
                from_year.options[j].selected = "1";
            }
        }
    }
}

function initFromToMonth(sFromMonthId, sToMonthId, sFromMonthValue, sToMonthValue)
{
    var from_month = document.getElementById(sFromMonthId);
    var to_month = document.getElementById(sToMonthId);

    if (from_month != null && to_month != null) {

        from_month.options.length = 13;
        to_month.options.length = 13;

        for (j = 1; j <= 12; j++) {
            var sMonth = zeroPad(j, 2);
            from_month.options[j].text = sMonth;
            from_month.options[j].value = sMonth;
            if (sFromMonthValue && sFromMonthValue.length > 0 && sFromMonthValue == sMonth)
            {
                from_month.options[j].selected = "1";
            }
            to_month.options[j].text = sMonth;
            to_month.options[j].value = sMonth;
            if (sToMonthValue && sToMonthValue.length > 0 && sToMonthValue == sMonth)
            {
                to_month.options[j].selected = "1";
            }
        }
    }
}

function zeroPad(num, count)
{ 
    var numZeropad = num + '';

    while(numZeropad.length < count) {
        numZeropad = "0" + numZeropad; 
    }
    return numZeropad;
}

function postLocate(sPrefix)
{
    if (!loggedIn())
    {
       askToRegister();
    }
    else
    {
	// User IS logged in...but is he FB user?
	if (isFacebookUser())
	{
	    // Yes. FB users must opt-in for email
	    // Ask FB to call us back with the answer
	    FB.Facebook.apiClient.users_hasAppPermission('email', 
		function(result)
		{
		// The result is 0 for users who have not yet opted in, and 1 for those who have 
		if (result==0) 
		    { 
			// We will not post the note yet. Ask for opt-in
			fbconnect_optin_showdiv();
		    } 
		else
		    {
			// User HAS opted in...pop up the note widget immediately
			postLocateNow(sPrefix);
		    }
		} );
	    // Do nothing now. Wait for above callback to fire.
	    return;
	}

	// Not a facebook user. Just post the note
	postLocateNow(sPrefix);
    }
}

function postLocateNow(sPrefix)
{
    if (notebar_lid == 0)
    {
        // No LID, don't bother making the call
        alert("No location was specified.  Please enter the location that you wish to add.");
        return false;       
    }

    var message = "";
    var activity = "";
    var unencodedMessage="";
    var name = "";
    var birthinfo_operation = "";
    var birth_args = "";
    var fromYear = "";
    var toYear = "";
    var fromMonth = "";
    var toMonth = "";

    sCurrPrefix = sPrefix;

    var messageElement = document.getElementById(sPrefix + "_findmsg");
    if (messageElement != null) {
        unencodedMessage = messageElement.value;
        message  = encodeURIComponent(unencodedMessage);
    }

    var activityElement = document.getElementById(sPrefix + "_activityInput2");
    if (activityElement != null) {
       activity = activityElement.value; 
    }

    var nameElement = document.getElementById(sPrefix + "_lookingfor");
    if (nameElement != null) {
       name = nameElement.value;
    }

    var fromYearElement = document.getElementById(sPrefix + "_from_yr");
    if (fromYearElement != null) {
       fromYear = fromYearElement.value;
    }

    var toYearElement = document.getElementById(sPrefix + "_to_yr");
    if (toYearElement != null) {
       toYear = toYearElement.value;
    }

    var fromMonthElement = document.getElementById(sPrefix + "_from_month");
    if (fromMonthElement != null) {
       fromMonth = fromMonthElement.value;
    }

    var toMonthElement = document.getElementById(sPrefix + "_to_month");
    if (toMonthElement != null) {
       toMonth = toMonthElement.value;
    }

    var birthInfoElements = document.getElementsByName(sPrefix + "_birthinfo");
    if (birthInfoElements != null) {
       if (birthInfoElements[0].checked) {
           var bdmonthElement = document.getElementById(sPrefix + "_bdmonth");
           var bddayElement = document.getElementById(sPrefix + "_bdday");
           var bdyearElement = document.getElementById(sPrefix + "_bdyear");
           if (bdmonthElement != null && bddayElement != null && bdyearElement != null) {
               birth_args = "&bmonth=" + bdmonthElement.value + "&bday=" + bddayElement.value + "&byear=" + bdyearElement.value;
           } else if (bdyearElement != null) {
               birth_args = "&byear=" + bdyearElement.value;
           }
       } else if (birthInfoElements[1].checked) {
           var birthyearElement = document.getElementById(sPrefix + "_birthyear");
           if (birthyearElement != null) {
               birth_args = "&byear=" + birthyearElement.value;
           }
       } else if (birthInfoElements[2].checked) {
           var currAgeElement = document.getElementById(sPrefix + "_currage");
           if (currAgeElement != null) {
               var d = new Date();
               var curr_year = d.getFullYear();
               var approx_age = currAgeElement.value;
               var byear = curr_year - approx_age;
               birth_args = "&byear=" + byear;
           }
       }
    }

    lc_xmlhttpreq = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        lc_xmlhttpreq = new XMLHttpRequest();
        if (lc_xmlhttpreq.overrideMimeType) {
            lc_xmlhttpreq.overrideMimeType('text/html');
    	}
    } else if (window.ActiveXObject) { // IE
        try {
            lc_xmlhttpreq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                lc_xmlhttpreq = new ActiveXObject("Microsoft.XMLHTTP");
	    } catch (e) {}
	}
    }

    if (!lc_xmlhttpreq) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }

    // Above code doesn't work for FF. Use InfoBox xmlhttp object
    //lc_xmlhttpreq = xmlhttp;

    lc_xmlhttpreq.onreadystatechange = processPostedFind;

    var iZoom = getZoomLevel();

    var url="http://www.zoomatlas.com/NoteMan/NoteBar?op=find&lid=" + notebar_lid + 
       "&type=" + activity + "&msg=" + escape(message) + "&name=" + name + "&fy=" + fromYear + "&ty=" + toYear +
       "&fm=" + fromMonth + "&tm=" + toMonth + birth_args +
       "&long=" + ibFloatPanelLon + "&lat=" + ibFloatPanelLat + "&zoom=" + iZoom + "&ft=" + nbfeatureType;

    lc_xmlhttpreq.open('GET', url, true);
    lc_xmlhttpreq.send(null);

    return false;
}

function processPostedFind()
{
    if (lc_xmlhttpreq.readyState==4) {
        if (lc_xmlhttpreq.status==200) {
       	    var xmlDoc = lc_xmlhttpreq.responseXML; 
            if (true) {
                lc_xmlhttpreq.close;
                clearFind();
                updateFind();
                doRedrawMap(xmlDoc);
            } else {
                handleFindError();
            }
        } else {
            alert("processPostedFind: problem with request");
        }
    }
}

function clearFind()
{
    if (msgBoxPanel == null) {
        clearLocateFormElement("findmsg");
        resetLocateSelectElement("activityInput2");
        clearLocateFormElement("lookingfor");

        clearLocateFormElement("from_yr");
        clearLocateFormElement("to_yr");
        clearLocateFormElement("from_month");
        clearLocateFormElement("to_month");
        clearLocateBirthInfoRadioButtons("birthinfo");
        clearLocateFormElement("bdmonth");
        clearLocateFormElement("bdday");
        clearLocateFormElement("bdyear");
        clearLocateFormElement("birthyear");
        clearLocateFormElement("currage");
    } else {
        var successDisplay = "Your note was posted successfully.<br/><input type='button' value='OK' onclick='cancelPvtMsg();'>";
        msgBoxPanel.setBody(successDisplay);
    }
}

function clearLocateFormElement(sId)
{
    try {
        document.getElementById(sCurrPrefix + "_" + sId).value = "";
    } catch (e) {}
}

function resetLocateSelectElement(sId)
{
    try {
        var selectElement = document.getElementById(sCurrPrefix + "_" + sId);
        selectElement.selectedIndex = 0;
    } catch (e) {}
}

function clearLocateBirthInfoRadioButtons(sName)
{
    try {
        var radioButtonArray = document.getElementsByName(sCurrPrefix + "_" + sName);
        for (i=0; i<3; i++)
            radioButtonArray[i].checked = false;
    } catch (e) {}
}

function handleFindError()
{
    var sMsg = "Error posting your 'I'm looking for' item";

    if (msgBoxPanel == null) {
        alert(sMsg);
    } else {
        var errorDisplay = sMsg + "<br/><input type='button' value='OK' onclick='cancelPvtMsg();'>";
        msgBoxPanel.setBody(errorDisplay);
    }
}

function setBirthInfoRadioButton(sPrefix, iIndex)
{
    try {
        document.getElementsByName(sPrefix + "_birthinfo")[iIndex].checked = true;
    } catch (e) {}
}
