﻿var botDaysOut = 4;    //The number of days from today to set end date to.  Change this to alter the default date/time
                        //window for the initial search.  If <= 0, the code will not load any default date/times and it
                        //will not do an initial search if there are no cookies.

var botDebug = false;   //The debug mode of the page, if debug is set to true, the program will create an alert with each
                        //JSON call.

var botResponseSearch;
var botResponseGenres;
var botResponseNeighborhoods;
var botCurrentPosition;

function BOTLoadGenres(obj)
{
    botResponseGenres = obj;
}

function BOTLoadNeighborhoods(obj)
{
    botResponseNeighborhoods = obj;
}

function BOTLoadResults(obj)
{
    botResponseSearch = obj;
    var iCount = botResponseSearch.results.length;
    var botSearchResults;

    if (iCount == 0)
        botSearchResults = "No results found. Please search again.";
    else
        botSearchResults = '<div class="BOTSearchDefaultText"><h4>' + iCount + ' results</h4></div>';

    var sCurrent = '';

    for(var i=0; i < iCount; i++)
    {
        if (botResponseSearch.results[i].date != sCurrent)
        {
            sCurrent = botResponseSearch.results[i].date;
            botSearchResults += '<h2 class="BOTSearchResultsMonthStart">' + botResponseSearch.results[i].dayOfWeekToString + ', ' + botResponseSearch.results[i].monthOfYearToString + ' ' + botResponseSearch.results[i].dayOfMonth + ', ' + botResponseSearch.results[i].yearOfCommonEra + '</h2>';
        }

        botSearchResults += BOTGetResultCode(i);
        if (i != iCount-1)
            botSearchResults += '<hr />';
    }

    document.getElementById('BOTSearchResults').innerHTML = botSearchResults;
    document.getElementById('BOTSearchOptionsLoader').innerHTML = '<a href="javascript:BOTSearch();"><img src="images/search.jpg" alt="search" class="BOTImageLink" /></a>';
}

function BOTGetResultCode(index)
{
    var botSearchResult = ''
        + '<div class="BOTSearchResult">'
        + '  <a name="anchor' + index + '"></a>'
        + '  <table class="BOTSearchResultTable">'
        + '    <tr>'
        + '      <td class="BOTSearchResultDateTimes">'
        + '        <div class="BOTTextLarge">' + botResponseSearch.results[index].dayOfWeekToString + '</div>'
        + '        <div class="BOTTextLarge">' + botResponseSearch.results[index].dayOfMonth + " " + botResponseSearch.results[index].monthOfYearToStringShort + " " + botResponseSearch.results[index].yearOfCommonEra + '</div>'
        + '        <div class="BOTTextMedium">' + botResponseSearch.results[index].time + '</div>'
        + '      </td>'
        + '      <td class="BOTSearchResultGenre"><img src="http://resource.boxofficetickets.com/BOT/UI/Genre/' + botResponseSearch.results[index].program.genre + '/32.png" /></td>'
        + '      <td class="BOTSearchResultDetails">'
        + '        <div class="BOTTextXLarge">' + botResponseSearch.results[index].fullName + '</div>'
        + '        <div class="BOTTextLarge">' + botResponseSearch.results[index].program.presentingPartner.toString + '</div>'
        + '        <div class="BOTTextMedium">' + botResponseSearch.results[index].venue.toString + ', ' + botResponseSearch.results[index].venue.facility.cityState + '</div>'
        + '        <div class="BOTTextSmall">' + botResponseSearch.results[index].detailsShort + '</div>'
        + '      </td>'
        + '      <td class="BOTSearchResultMoreInfo"><a href="javascript:BOTMoreInfo(' + index + ');" class="BOTImageLink"><img src="images/moreInfoSq.jpg" class="BOTImageLink" /></a></td>'
        + '    </tr>'
        + '  </table>'
        + '</div>';
    return botSearchResult;
}

function BOTMoreInfo(index)
{
    //check to make sure there is a venu before displaying venue information
    if (botResponseSearch.results[index].venue.src != '')
    {
        document.getElementById('BOTInspectResultVenueMap').style.display = 'block';
        document.getElementById('BOTInspectResultVenueText').style.display = 'block';

        BOTLoadMap(botResponseSearch.results[index].venue.facility.address.toString);
        document.getElementById('BOTInspectResultVenueText').innerHTML = '<div class="BOTTextSmall">Venue:</div><a href="' + botResponseSearch.results[index].venue.src + '" target="_blank">' + botResponseSearch.results[index].venue.toString + '</a><br />'
            + '<a href="' + botResponseSearch.results[index].venue.facility.src + '" target="_blank">' + botResponseSearch.results[index].venue.facility.address.toString + '</a>';
    }
    else
    {
        document.getElementById('BOTInspectResultVenueMap').style.display = 'none';
        document.getElementById('BOTInspectResultVenueText').style.display = 'none';
    }

    botCurrentPosition = 'anchor' + index;

    document.getElementById('BOTInspectResultPoster').innerHTML = '<img id="BOTInspectResultPosterImage" src="' + botResponseSearch.results[index].srcForIcon + '" />';

    document.getElementById('BOTInspectResultGenreTableImage').innerHTML = '<img src="http://resource.boxofficetickets.com/BOT/UI/Genre/' + botResponseSearch.results[index].program.genre + '/64.png" />';

    document.getElementById('BOTInspectResultGenreTableText').innerHTML = botResponseSearch.results[index].program.genres;

    if (!botResponseSearch.results[index].freeOfCharge)
        document.getElementById('BOTInspectResultBuy').innerHTML = '<a href="' + botResponseSearch.results[index].src + '" target="_blank"><img src="images/ordernow.jpg" class="BOTImageLink" /></a>';
    else
        document.getElementById('BOTInspectResultBuy').innerHTML = '';

    document.getElementById('BOTInspectResultMoreInfo').innerHTML = '<a href="' + botResponseSearch.results[index].srcForOfficialWebsite + '" target="_blank"><img src="images/moreinfo.jpg" class="BOTImageLink" /></a>';

    document.getElementById('BOTInspectResultProgram').innerHTML = '<div class="BOTTextXLarge">' + botResponseSearch.results[index].program.toString + '</div>' + '<br />' + botResponseSearch.results[index].date + '<br />' + botResponseSearch.results[index].time + '<br />' + botResponseSearch.results[index].runTime + '<br /><div class="BOTInspectResultDetailsDateRange BOTTextSmall">' + botResponseSearch.results[index].program.dateRange + '</div>';
    
    if (botResponseSearch.results[index].priceRange != 'Unknown')
        document.getElementById('BOTInspectResultProgram').innerHTML += '<div class="BOTTextSmall">' + botResponseSearch.results[index].priceRange + '</div>';

    if (botResponseSearch.results[index].program.fundingMiceTypeHTML != '')
        document.getElementById('BOTInspectResultProgram').innerHTML += '<div class="BOTFundingMiceType">' + botResponseSearch.results[index].program.fundingMiceTypeHTML + '</div>';

    document.getElementById('BOTInspectResultPartner').innerHTML = '<div class="BOTTextSmall">Presented By:</div><a href="' + botResponseSearch.results[index].program.presentingPartner.src + '" target="_blank">' + botResponseSearch.results[index].program.presentingPartner.toString + '</a>';

    if (botResponseSearch.results[index].program.presentingPartner.fundingMiceTypeHTML != '')
        document.getElementById('BOTInspectResultPartner').innerHTML += '<div class="BOTFundingMiceType">' + botResponseSearch.results[index].program.presentingPartner.fundingMiceTypeHTML + '</div>';

    if (botResponseSearch.results[index].details == '')
        document.getElementById('BOTInspectResultDetails').style.display = 'none';
    else
    {
        document.getElementById('BOTInspectResultDetails').style.display = 'block';
        document.getElementById('BOTInspectResultDetails').innerHTML = botResponseSearch.results[index].details;
    }

    document.getElementById('BOTSearch').style.display = 'none';

    document.getElementById('BOTInspect').style.display = 'block';
}

function BOTBackToResults()
{
    document.getElementById('BOTSearch').style.display = 'block';
    document.getElementById('BOTInspect').style.display = 'none';
    window.location.hash = botCurrentPosition;
}

function BOTSearch()
{
    if (BOTValidateInputs())
    {
        document.getElementById('BOTSearchOptionsLoader').innerHTML = '<img src="images/loader.gif" id="BOTSearchOptionsTableLoadGif" />';
        BOTDoSearch();
    }
}

function BOTDoSearch()
{   
    var genre = document.getElementById('BOTSearchOptionsGenre').value;
    var dateFrom = document.getElementById('BOTSearchOptionsStartDate').value;
    var dateTo = document.getElementById('BOTSearchOptionsEndDate').value;
    var neighborhood = document.getElementById('BOTSearchOptionsNeighborhood').value;
    var keyWord = document.getElementById('BOTSearchOptionsKeyword').value;

    var uri = 'https://robot.boxofficetickets.com/800-494-TIXS/WebObjects/RoBOTWebAPI.woa/wa/DAForRoBOTWebAPI/subProgramsForTag?idForTag=9011&passKeyForTag=fa4bc27467&objectGraphDepth=2&callback=BOTLoadResults';

    if (genre != "0")
    {
        BOTCreateCookie('botgenre', genre);
        uri += '&genre=' + genre;
    }
    else
        BOTClearCookie('botgenre');

    if (dateFrom != '')
    {
        BOTCreateCookie('botdateFrom', dateFrom);
        uri += '&dateFrom=' + dateFrom;
    }
    else
        BOTClearCookie('botdateFrom');

    if (dateTo != '')
    {
        BOTCreateCookie('botdateTo', dateTo);
        uri += '&dateTo=' + dateTo;
    }
    else
        BOTClearCookie('botdateTo');

    if (neighborhood != "0")
    {
        BOTCreateCookie('botneighborhood', neighborhood);
        uri += '&neighborhood=' + neighborhood;
    }
    else
        BOTClearCookie('botneighborhood');

    if (keyWord != '')
    {
        BOTCreateCookie('botkeyWord', keyWord);
        uri += '&keyWord=' + keyWord;
    }
    else
        BOTClearCookie('botkeyWord');

    if (botDebug)
        alert(uri);

    var botJsonCall = document.createElement('script');
    botJsonCall.setAttribute('type', 'text/javascript');
    botJsonCall.setAttribute('src', uri);
    document.getElementsByTagName('head')[0].appendChild(botJsonCall);
}

function ClearDate(sDateInput, sDateCookie)
{
    document.getElementById(sDateInput).value = '';
}

//Google Maps code
function BOTLoadMap(address)
{
    var map = new google.maps.Map2(document.getElementById("BOTInspectResultVenueMap"),{size:new google.maps.Size(532,200)});
    var geocoder = new google.maps.ClientGeocoder();

    if (geocoder)
    {
        geocoder.getLatLng(address,
            function(point)
            {
                if (!point)
                {
                    if (botDebug)
                        alert(address + " not found");
                }
                else
                {
                    map.setCenter(point, 13);
                    var marker = new google.maps.Marker(point);
                    map.addOverlay(marker);
                    //marker.openInfoWindowHtml(address);
                }
            }
        );
    }
}

function Initialize()
{
    var bCookies = false;

    var genre = BOTReadCookie('botgenre');
    if (genre != null && genre != '')
    {
        bCookies = true;
        document.getElementById('BOTSearchOptionsGenre' + genre).selected = true;
    }

    var dateFrom = BOTReadCookie('botdateFrom');
    if (dateFrom != null && dateFrom != '')
    {
        bCookies = true;
        document.getElementById('BOTSearchOptionsStartDate').value = dateFrom;
    }
    else if (botDaysOut > 0)
    {
        var d = new Date();
        document.getElementById('BOTSearchOptionsStartDate').value = (d.getMonth() + 1) + '-' + d.getDate() + '-' + getTrueYear(d);
    }

    var dateTo = BOTReadCookie('botdateTo');
    if (dateTo != null && dateTo != '')
    {
        bCookies = true;
        document.getElementById('BOTSearchOptionsEndDate').value = dateTo;
    }
    else if (botDaysOut > 0)
    {
        var d = new Date();
        d.setTime(d.getTime() + (botDaysOut * 24 * 60 * 60 * 1000));
        document.getElementById('BOTSearchOptionsEndDate').value = (d.getMonth() + 1) + '-' + d.getDate() + '-' + getTrueYear(d);
    }

    var neighborhood = BOTReadCookie('botneighborhood');
    if (neighborhood != null && neighborhood != '')
    {
        bCookies = true;
        document.getElementById('BOTSearchOptionsNeighborhood' + neighborhood).selected = true;
    }
    
    var keyWord = BOTReadCookie('botkeyWord');
    if (keyWord != null && keyWord != '')
    {
        bCookies = true;
        document.getElementById('BOTSearchOptionsKeyword').value = keyWord;
    }

    if (bCookies || botDaysOut > 0)
        BOTSearch();
}

//Cookie Management code, these scripts are modified versions of the ones found at http://www.quirksmode.org/js/cookies.html
function BOTCreateCookie(name, value)
{
    var date = new Date();
	date.setTime(date.getTime() + (15 * 60 * 1000));
	var expires = "; expires=" + date.toGMTString();
	document.cookie = name + "=" + value + expires + "; path=/";
}

function BOTReadCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i = 0; i < ca.length; i++)
	{
        var c = ca[i];
		while (c.charAt(0)==' ')
		    c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0)
		    return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function BOTClearCookie(name)
{
    var date = new Date();
	date.setTime(date.getTime() - 1);
	var expires = "; expires=" + date.toGMTString();
	document.cookie = name + "=" + expires + "; path=/";
}

function getTrueYear(theDate)
{
	x = theDate.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}


function isEmpty(object)
{
    for(var i in object)
        return true;
    return false;
}

//currently not working when the dateTo is in the next calendar year.
function BOTValidateInputs()
{
    return true;

    var bIsValid = true;
    var dateFrom = document.getElementById('BOTSearchOptionsStartDate').value;
    var dateTo = document.getElementById('BOTSearchOptionsEndDate').value;

    if (dateTo != '' && dateFrom != '')
    {
        var dFrom = Date.parse(dateFrom);
        var dTo = Date.parse(dateTo);

        if (dateFrom > dateTo)
        {
            alert('The end date must occur after the start date, please adjust the dates you have selected.');
            bIsValid = false;
        }
    }
    
    return bIsValid;
}