﻿function ChurchSearch(varname,map)
{
    this.isInMapControl = false;
    this.varname = varname;
    this.map = map;
    this.resultDiv = "resultDiv";
    
    this.searchCount = 0;
    this.pageMax = 5;
    this.pageIdx = 0;
    
    this.originalCenter = 0;
    this.name = "";
    this.address = "";
    this.country = "";
    this.state = "";
    this.city = "";
    this.language = "";
    this.timeStart = "0";
    this.timeEnd = "0";

    this.FireSearch = function(name, country, state, city, language, timeStart, timeEnd,
                    upperLeftLatitude, upperLeftLongitude, lowerRightLatitude, lowerRightLongitude,
                    centerLat, centerLong, pIdx, pMax, searchCount, handlerPlotMap)
    {
        var params = {
            upperLeftLat : upperLeftLatitude,
            upperLeftLong : upperLeftLongitude,
            lowerRightLat : lowerRightLatitude,
            lowerRightLong : lowerRightLongitude,
            centerLat : centerLat,
            centerLong : centerLong,
            churchCountry : country,
            churchState : state,
            churchCity : city,
            churchName : name,
            occurLanguage : language,
            occurTimeStart : timeStart,
            occurTimeEnd : timeEnd,
            MatchFrom : pIdx * pMax,
            MatchTo : pMax,
            ajax : 1
        };

        //$.post("finder.aspx?ajax=1", params, handlerPlotMap);
        $.get("finder.aspx", params, handlerPlotMap);
    }
    
    this.SearchCity = function()
    {
        var me = this;
        this.FireSearch(me.name, me.country, me.state, me.city, me.language, me.timeStart, me.timeEnd, 
                          0, 0, 0, 0,
                          0, 0, me.pageIdx, me.pageMax, (++me.searchCount), me.PlotMap);
    }
    
    this.SearchByLocation = function(loc)
    {
        var me = this;
        me.pageIdx = 0;
        me.map.FindLocation(loc, 
            function(e)
            {
                me.originalCenter = me.map.map.GetCenter();
                me.Search();
            }
        ); 
    }

    this.MoveNext = function()
    {
        this.pageIdx++;
        if ( this.address != "" )
            this.Search();
        else
            this.SearchCity();
        return false;
    }
    
    this.MoveBack = function()
    {
        this.pageIdx--;
        if ( this.address != "" )
            this.Search();
        else
            this.SearchCity();
        return false;
    }

    this.Search = function(isOnChanged)
    {
        var me = this;
        var upperLeft = me.map.GetUpperLeft();
        var lowerRight = me.map.GetLowerRight();
        var resultList = "";
        var centerLat = 0;
        var centerLong = 0;
        
        if ( me.originalCenter == 0 )
        {
            centerLat = me.map.map.GetCenter().Latitude;
            centerLong = me.map.map.GetCenter().Longitude;
        }
        else
        {
            centerLat = me.originalCenter.Latitude;
            centerLong = me.originalCenter.Longitude;
        }
        this.FireSearch(me.name, "", "", "", me.language, me.timeStart, me.timeEnd, 
                      upperLeft.Latitude, upperLeft.Longitude, lowerRight.Latitude, lowerRight.Longitude,
                      centerLat, centerLong, me.pageIdx, me.pageMax, (++me.searchCount), me.PlotMap);
    }

    this.PlotMap = function (res) 
    {
        eval("res = { value: " + res + " }");
        ShowResult();
        
        var me = churchSearcher;
        me.map.map.DeleteAllPushpins();
        me.map.pinID = 1;
        
        //document.getElementById("debug").innerHTML = "";
        if ( res != null && res.value != null && res.value.Messages != null && res.value.Messages.length > 0 ) 
        {
            for ( m = 0; m < res.value.Messages.length; m ++ )
                document.getElementById("debug").innerHTML += res.value.Messages[m] + "<hr>";
        }
        else
        {
            document.getElementById("debug").innerHTML += "no debug messages!<br>";
        }

        if ( res != null && res.value != null && res.value.TotalMatched > 0 ) 
        {
            // stop auto search
            jMap.repeatSearch = 0;
            
            document.getElementById("searchBtn").value = "Search!";
            document.getElementById("searchBtn").disabled = false;

            var resultList = "";
            var resultNav = "";
            resultList = "<br><div class=\"bodybold\">" + res.value.TotalMatched + " church" 
                            + ( res.value.TotalCount > 1 ? "es" : "" ) + " found</div>";

            resultNav += "<table border='0' cellpadding='0' cellspacing='0'><tr>";
            
            resultNav += "<td class=\"bodytext\">";
            
            if ( me.pageIdx == 0 )
                resultNav += "back";
            else
                resultNav += "<a href=\"#\" class=\"bodytext\" onclick=\"return churchSearcher.MoveBack();\">back</a>";
            
            resultNav += "</td><td>&nbsp;</td><td class=\"bodytext\">&nbsp;";
            
            //resultNav += (me.pageIdx*me.pageMax+1) + " - ";
            
            //if ( me.pageMax*(me.pageIdx+1) >= res.value.TotalMatched )
            //    resultNav += res.value.TotalMatched;
            //else
            //    resultNav += me.pageMax*(me.pageIdx+1);
                
            resultNav += "</td><td class=\"bodytext\">&nbsp;</td><td class=\"bodytext\">";
            
            if ( me.pageMax*(me.pageIdx+1) >= res.value.TotalMatched )
                resultNav += "no more";
            else
                resultNav += "<a href=\"#\" class=\"bodytext\" onclick=\"return churchSearcher.MoveNext();\">" 
                            + ( res.value.TotalMatched - (me.pageMax*(me.pageIdx+1)) ) + " more</a>";
            
            resultNav += "<td>&nbsp;</td></tr></table>";
            
            resultList += "<table cellpadding='0' cellspacing='0' border='0' width='100%'>";

            var churchBox = new jgn.Transformer();
            churchBox.compile("element", "tplChurchBox");
            
            var churchLink = new jgn.Transformer();
            churchLink.compile("element", "tplChurchLink");

            var timeStarted = new Date();
            for (idx = 0; idx < res.value.Houses.length; idx++)
            {
                var leftlink = "";
                var boxinfo = "";
                var church = res.value.Houses[idx];
                
                church.idx = idx + 1;
                church.searcher = me;
                church.pushpin = (me.pageIdx*me.pageMax) + idx + 1;
                church.staffs = onlyStaff(church.staffs);
                church.occurs = onlyWorship(church.meetings);
                
                leftlink = churchLink.getString(church);
                boxinfo = churchBox.getString(church);
            
                me.map.AddPushpin("", boxinfo, church.latitude, church.longitude);
                resultList += leftlink;
            }
            var timeEnded = new Date();
            
            resultList += "</table><br>";
            resultList += "<table width='100%'><tr><td align='right'>" + resultNav + "</td></tr></table><br>";

            document.getElementById(me.resultDiv).innerHTML = resultList;
        }
        else
        {
            document.getElementById("searchBtn").value = "Search!";
            document.getElementById("searchBtn").disabled = false;
            document.getElementById(me.resultDiv).innerHTML = "<br><br><center><div class=\"bodybold\" style=\"color:red;\">no church found<br>on the map</div><br><a href='#' onclick='return ShowSearch();' class='bodytext'>Try to zoom out<br>or change search</a></center><br><br>";
        }
        
        if ( me.address != "" )
        {
            if ( me.originalCenter == 0 )
            {
                me.map.map.AddPushpin(new VEPushpin(
                       me.map.pinID, 
                       me.map.map.GetCenter(), 
                       '/map/btn_solo.png',
                       "Map Center", 
                       ""
                       ));
            }
            else
            {
                me.map.map.AddPushpin(new VEPushpin(
                       me.map.pinID, 
                       me.originalCenter, 
                       '/map/btn_solo.png',
                       me.address, 
                       ""
                       ));
            }
        }
        
        /*if ( jMap.repeatSearch >= 1 )
        {
            var upperLeft = jMap.GetUpperLeft();
            var lowerRight = jMap.GetLowerRight();
            
            x = Math.sqrt( Math.pow( (69.1 * (lowerRight.Latitude - upperLeft.Latitude)), 2) );
            y = Math.sqrt( Math.pow( (53 * (lowerRight.Longitude - upperLeft.Longitude)), 2) );
            
            html = "";
            
            html += "<br><font color='blue'>looking for <b>" + page.request.name + "</b><br>from <b>" + page.request.address + "</b></font><br><br>";
            
            html += "<font color='red'><b>no church found<br>in " + Math.round(x*y) + " square miles.<br><br>";

            if ( jMap.repeatSearch > 1 )
            {
                html += "expanding search area ...</b></font><br><br>";
                setTimeout('jMap.map.ZoomOut();SearchMap();', 3000);
            }
            else
            {
                html += "search terminated.</b></font><br><br><a href=\"#\" class='bodytext' onclick=\"return ShowSearch();\" style='font-size:18px;'>try again</a><br><br>";
                document.getElementById("searchBtn").value = "Search!";
                document.getElementById("searchBtn").disabled = false;
            }

            document.getElementById(me.resultDiv).innerHTML = html;
            
            jMap.repeatSearch --;
        }*/

        if ( me.address == "" )
        {
            jMap.map.SetMapView(jMap.latLongArray);
        }
    }
}




var churches = new Array();
var jMap = null;
var churchSearcher = null;

function onLoad()
{
    jMap = new JGospelMap("jMap");
    jMap.GetMap();
    
    churchSearcher = new ChurchSearch("churchSearcher", jMap);
    
    jMap.map.AttachEvent("onmouseover", function(e) {
        churchSearcher.isInMapControl = true;
    });
    
    jMap.map.AttachEvent("onmouseout", function(e) {
        churchSearcher.isInMapControl = false;
    });
    
    jMap.map.AttachEvent("onchangeview", function(e) {
    
        if ( churchSearcher.isInMapControl && churchSearcher.address != "" )
        {
            churchSearcher.pageIdx = 0;
            churchSearcher.Search(true);
        }
    });
}

function getChurch(sel)
{
    churches[sel.selectedIndex].ShowDetail("detailDiv");
    jMap.AddPushpin(churches[sel.selectedIndex]);
}

function onlyStaff(staffs)
{
    if ( staffs == null || staffs.length == 0 )
        return staffs;
    return [ staffs[0] ];
}

function onlyWorship(meetings)
{
    var occurs = new Array();
    
    for ( var i = 0; i < meetings.length; i ++ )
    {
        if ( meetings[i].engType.toLowerCase() != "worship" )
            continue;

        for ( var j = 0; j < meetings[i].Occurs.length; j ++ )
            occurs[ occurs.length ] = meetings[i].Occurs[j];
    }
    
    return occurs;
}

function displayTime(o)
{
    if ( !o || !o.timeStart )
        return "";
    
    var from = formatTime(o.timeStart);
    var to = "";
    if ( o.timeEnd )
        to = formatTime(o.timeEnd);

    if ( from != "" && to != "" )
        return from + " - " + to;
    else if ( from != "" )
        return from;

    return "";
}

function formatTime(s)
{
    s = s+""; // int to string
    if ( !s || s.length != 5 || s == "10000" )
        return "";

    s = s.substring(1, 5);
    var hour = s.substring(0, 2);
    var min = s.substring(2, 4);
    
    hour = parseInt(hour, 10);
    
    s = "";
    if ( hour >= 12 )
    {
        hour -= 12;
        s = "pm";
        if ( hour == 0 )
            hour = 12;
    }
    else
    {
        s = "am";
    }
        
    s = hour + ":" + min + s;
    return s;
}

function pickLangauge(lang)
{
    if ( lang.engName.length > 0 && lang.engName.charAt(0) == "+" )
        return lang.engName.substring(1);

    if ( lang.traName.length > 0 && lang.traName.charAt(0) == "+" )
        return lang.traName.substring(1);
    
    return ( lang.engName != "" ? lang.engName : lang.traName );
}