﻿// JScript File
//const Natrual = 0;
//const Cultural = 1;
//const Historical = 2;
var DestinationList;
var DestinationObj;
var DestinationIndex;
var callbackFNC;
var marker;
var map;
var SelectedCategory = "";
var SelectedActivity = "";
var CurrentOpenCalendarView = "";
var ddlActivityObjName;
var markers = new Array();

//function DrawYahooMap(){
//    try{
//        var myPoint = new YGeoPoint(41.6,-82);
//        var mapContainer = document.getElementById('mapContainer')
//        map = new YMap(mapContainer);
//        
//        map.drawZoomAndCenter(myPoint, 10);
//        //Add Control
//        map.addPanControl(); 
//        map.addZoomLong();  
//        map.addZoomScale();
//        map.addTypeControl();       
//        
//    }
//    catch(e){
//            alert('The following exception was thrown by the script : Error name :'+e.name+' Error message :'+e.message);
//    }

//}

function DrawGoogleMap()
{
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("mapContainer"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(41.6, -82), 8);
        
      }
}

function AddDestinationToMap(dest){
  
    
    var Icon = new GIcon();
    
    switch (dest.Category)
    {
        case "0": Icon.image = '/images/natural-icon.gif'; break;
        case "1": Icon.image = '/images/cultural-icon.gif'; break;
        case "2": Icon.image = '/images/historical-icon.gif'; break;
    }

    Icon.iconSize = new GSize(13, 13);
    Icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    Icon.shadowSize = new GSize(0, 0);
    Icon.iconAnchor = new GPoint(0, 0);
    Icon.infoWindowAnchor = new GPoint(5, 1);
    
    markerOptions = {title:dest.DestinationName, icon:Icon};
    var point = new GLatLng(dest.Latitude, dest.Longitude*-1);
    var gmarker = new GMarker(point , markerOptions);
    
    GEvent.addListener(gmarker, "click", function() {
        gmarker.openInfoWindowHtml(getSmartWinDesc(dest));
        });
    
    
   
 
    if (SelectedCategory != "")
    {
        if (dest.Category != SelectedCategory) {marker.hide();}
    }
    
    if ( (SelectedActivity != "") && (!marker.isHidden()) )
    {
        var k;
        var hide = true;
        for(k = 0; k < dest.Activities.length; k++)
        {
            if (dest.Activities[k] == SelectedActivity) {hide = false;}
        }
        if (hide) {marker.hide();}
    }

    map.addOverlay(gmarker);
    markers.push(gmarker);
}


function getSmartWinDesc(dest){
    var desc = "";
    desc += "<div id='DestinationTitle'>" + dest.DestinationName + "</div>";
    desc += "<div id='DestinationShortDesc'>" + dest.ShortDesc + "</div>";
    //desc += "lat:" + dest.Latitude + "  long:" + dest.Longitude + "<br/>";
    //desc += dest.Activities.length + "<br>";
//    for (var k = 0; k < dest.Activities.length; k++)
//    {
//        desc += dest.Activities[k] + "; ";
//    }
//    desc += "<br/>";
    desc += "<a href='javascript:ShowDestinationDetails(" + dest.DestinationID + ");'>View Details</a><br/>";
    desc += "<a href='javascript:AddtoItinerary(" + dest.DestinationID + ", true)'>Add to Itinerary</a>";
    
    return desc;
}

function ClearMap()
{
//        var mapContainer = document.getElementById('mapContainer');
//        map = new YMap(mapContainer);
//YEvent.ClearAll();
    map.removeMarkersAll();
//   for (j = 0; j < DestinationObj.length; j++)
//   {
//        marker = map.getMarkerObject(DestinationObj[j].DestinationID);
//        YEvent.ClearAll(marker);
//        YEvent.Remove(marker);
//    }
}

function StartActivityOptionsDownload()
{
        var objActivity = document.getElementById(ddlActivityObjName);
        if (!objActivity) {alert('an error occured "'  + ddlActivityObjName + '"');return;}
        objActivity.length=0;
        objActivity.disabled = true;
        var option = document.createElement('OPTION');
        option.value = '';
        option.innerHTML = 'Please Wait...';
        objActivity.appendChild(option);

        if (SelectedCategory != "")
        {
            CoastalWebServices.GetActivities(SelectedCategory, ReceiveActivityOptions);
        }
        else
        {
            CoastalWebServices.GetActivities("", ReceiveActivityOptions);
        }
}

function ReceiveActivityOptions(Options)
{
       //alert(Options);
        var objActivity = document.getElementById(ddlActivityObjName);
        if (!Options){
            objActivity.length = 0;
            var option = document.createElement('OPTION');
            option.innerHTML = 'No Activities Found';
            objActivity.appendChild(option);
            return;
        }
        
        objActivity.length = 0;
        var rows = Options.split('|'); 
        
        var option = document.createElement('OPTION');
        option.value = "";
        option.innerHTML = "Activities";
        objActivity.appendChild(option);        
        
        var selectedIndex = 0;
        for (var k = 0; k < rows.length -1; ++k)
        {
            var option = document.createElement('OPTION');
            var values = rows[k].split('^');
            option.value = values[0];
            option.innerHTML = values[1];
            if (values[0] == SelectedActivity) {selectedIndex = k+1}
            objActivity.appendChild(option);
        }
        objActivity.disabled = false;
        if (selectedIndex != 0) 
        {
            objActivity.options[selectedIndex].selected = true;
        }
        else
        {
            SelectedActivity = "";
            RenderDestinationFilter();
        }
           
        
        
}

function StartDestinationDownload(callback, ddlactivity)
{
    callbackFNC = callback;
    ddlActivityObjName = ddlactivity;
    //CoastalWebServices.GetDestinationArray(ReceiveDestinationArray);
    DestinationIndex = 0;
    DestinationObj = CreateCollection("DestinationCollection");    
    //GetAllDestinations();
}

function ReceiveDestinationArray(ArrayStr)
{
   //alert(ArrayStr);
    DestinationIndex = 0;
    DestinationObj = CreateCollection("DestinationCollection");
    if ((ArrayStr.length > 0) && (ArrayStr.indexOf(",") == -1))
    { 
        eval("DestinationList = new Array('" + ArrayStr + "')");
    }
    else
    {
      eval("DestinationList = new Array(" + ArrayStr + ")");
    }
    //DestinationList = ArrayStr.split(",");
      
    if (DestinationIndex < DestinationList.length) {GetNextDestinationItem();}
}

function GetNextDestinationItem()
{
    //alert(DestinationIndex);
    //alert(DestinationList[DestinationIndex]);
    CoastalWebServices.GetDestinationItem(DestinationList[DestinationIndex] ,ReceiveDestinationItem);
}

function GetAllDestinations()
{
    CoastalWebServices.GetAllDestinations(ReceiveAllDestinations);
}

function ReceiveAllDestinations(items)
{
    //add destination to collection
    //try{
        var AllDestinations = items.split("$$?");
        for (var k = 0; k < AllDestinations.length; k++)
        {
            var values =  AllDestinations[k].split(",");
            var siteactivities = values[8].split("|");
            DestinationObj.Add(new Destination(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], siteactivities, values[9], values[10], values[11]))
        
            AddDestinationToMap(DestinationObj[DestinationObj.length-1]);
        
            DestinationIndex++;
        }
        //alert("done!");
        //GetDestinationDetails(callbackFNC);
        //if (DestinationIndex < DestinationList.length) { GetNextDestinationItem();}
        CoastalWebServices.GetSimpleItinerary(true,ReceiveItineraryList);
//    }
//    catch(e){
//        alert(e);
//    }

}

function ReceiveDestinationItem(item)
{
    //add destination to collection
    try{
        var values =  item.split(",");
        var siteactivities = values[8].split("|");
        DestinationObj.Add(new Destination(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], siteactivities, values[9], values[10], values[11]))
    
        AddDestinationToMap(DestinationObj[DestinationObj.length-1]);
    
        DestinationIndex++;

        //GetDestinationDetails(callbackFNC);
        if (DestinationIndex < DestinationList.length) 
        { GetNextDestinationItem();}
        else
        {
         //ReceiveItineraryList(DestinationList.join(","));
         CoastalWebServices.GetSimpleItinerary(true,ReceiveItineraryList);
         }
    }
    catch(e){
        //alert(item);
    }
        
}

function SwitchThemeCategory(category)
{
    SelectedCategory = category;
    RenderDestinationFilter();
    StartActivityOptionsDownload();
//    var j;
//    for (j = 0; j < DestinationObj.length; j++)
//   {
//        marker = map.getMarkerObject(DestinationObj[j].DestinationID);
//        if (DestinationObj[j].Category != category)
//        {  
//            marker.hide();
//        }
//        else
//        {
//            marker.unhide();
//        }
//    }
}

function SelectActivity(nActId)
{
    SelectedActivity = nActId;
    RenderDestinationFilter();
//    var j;
//    for (j = 0; j < DestinationObj.length; j++)
//   {
//        marker = map.getMarkerObject(DestinationObj[j].DestinationID);
//        if (SelectedCategory != "")
//        {
//            if (DestinationObj[j].Category == SelectedCategory)
//            {
//                var k;
//                var hide = true;
//                for (k = 0; k < DestinationObj[j].Activities.length; k++)
//                {
//                    if (DestinationObj[j].Activities[k] == nActId) {hide = false;}
//                }
//                if (hide) {
//                    marker.hide();
//                 }
//                 else
//                 {
//                    marker.unhide();
//                 }  
//            }

//        }
//        else
//        {
//               var k;
//                var hide = true;
//                for (k = 0; k < DestinationObj[j].Activities.length; k++)
//                {
//                    if (DestinationObj[j].Activities[k] == nActId) {hide = false;}
//                }
//                if (hide) {
//                    marker.hide();
//                 }
//                 else
//                 {
//                    marker.unhide();
//                 }   
//        }
//                 
//    }    
}

function RenderDestinationFilter()
{
    if ((SelectedCategory == "") && (SelectedActivity == "")) {
        ShowAllDestinations();
        return;
    }
    var j;
    for(j = 0; j < DestinationObj.length; j++)
    {
        var dest = DestinationObj[j];
        var k;
        var hide = true;
        
        if ((SelectedCategory == "") || ((SelectedCategory != "") && (dest.Category == SelectedCategory)))
        {
            if (SelectedActivity == "")
            {
                hide = false;
            }
            else
            {
                var h;
                for(h = 0; h < dest.Activities.length; h++)
                {
                    if (dest.Activities[h] == SelectedActivity) {hide = false;}
                }
            }
        }
        
        marker = markers[j];
        if (hide) 
        {
            marker.hide();
        }
        else
        {
            marker.show();
        }
            
    }  
}

function ShowAllDestinations()
{
    var j;
    SelectedCategory = "";
    SelectedActivity = "";
    for (j = 0; j < DestinationObj.length; j++)
   {
        markers[j].show();
    }
    //StartActivityOptionsDownload();
}


//Destination Collection
function DestinationCollection()
{
    this.Container="";
    this.Add=function(obj)
    {
        this.push(obj);
    }
    this.Display=function()
    {
//        str="<Table border=1 width=200 ><tr><td>" + 
//            "<b>Name</b></td><td><b>" + 
//            "Age</b></td><tr>";
//        for( = 0;i<this.length;i++)
//            str+="<Tr><Td>"+this[i].ShortDesc+ 
//                 "</Td><Td>"+this[i].CategoryName+
//                 "</Td></Tr>";
//        str+="</Table>";
        this.Container.innerHTML=str;
    }
}
    
function Destination(DestinationID, DestinationName, ShortDesc, CategoryID, CategoryName, Latitude, Longitude, Category, Activities, Street, Town, Phone)
{
    this.DestinationID = DestinationID;
    this.DestinationName = DestinationName;
    this.ShortDesc = ShortDesc;
    this.CategoryID = CategoryID;
    this.CategoryName = CategoryName;
    this.Latitude = Latitude;
    this.Longitude = Longitude;
    this.Category = Category;
    this.Activities = Activities;
    this.Street = Street;
    this.Town = Town;
    this.Phone = Phone;

}

//Itinerary
function LoadMyItinerary()
{        
    DestinationIndex = 0;
    DestinationObj = CreateCollection("DestinationCollection");  
    CoastalWebServices.GetSimpleItinerary(false, ReceiveDestinationArray);
    
}


function AddtoItinerary(DestinationID, UpdateList)
{
    
    //var details = $find("DetailsModal");
    //details.hide();
    if (UpdateList) {
        CoastalWebServices.AddToItinerary(DestinationID, true, ReceiveItineraryList);
    }
    else
    {
        CoastalWebServices.AddToItinerary(DestinationID, false, ConfirmDestinationAdded);
    }
}

function ConfirmDestinationAdded(emptystring)
{
    alert("Destination added to your itinerary");
}

function ReceiveItineraryList(ItineraryList)
{
    if (ItineraryList =="-1") 
    {
        alert("Destination is already in your itinerary");
        return;
    }
    var ItineraryHTML = "";
    var ItineraryName = "";
    var ItineraryContainer = document.getElementById("ItineraryContainer");
    ItineraryContainer.innerHTML = "";
    
    if (ItineraryList != "")
    {
        var j;
        var k;
        
        var ItineraryArray = ItineraryList.split(",");
        for(k = 0; k < ItineraryArray.length; k++)
        {
            if (ItineraryArray[k].indexOf("^^") != -1 )
            {
                ItineraryName = ItineraryArray[k].substring(2, ItineraryArray[k].length);
            }
            else
            {
            for(j = 0; j < DestinationObj.length; j++)
            {
                var dest = DestinationObj[j];
                        
                if (dest.DestinationID == ItineraryArray[k])
                {
                    ItineraryHTML += "<div class='ItineraryRemoveBtn' onclick='RemoveItineraryItem("+ dest.DestinationID + ")'>&nbsp;</div><li onclick='ShowDestinationDetails(" + dest.DestinationID + ")'>" + dest.DestinationName + "<div class='ItineraryStreet'>" + dest.Street + "</div><div class='ItineraryTown'>" + dest.Town + "</div><div class='ItineraryPhone'>" + dest.Phone + "</div></li>"
                    break;
                }
            }
            }
        }
        
        if (ItineraryHTML != "")
        {   
            if (ItineraryName != "") {ItineraryName = " [" + ItineraryName + "]"};
            ItineraryHTML = "<div id='ItineraryTitle'>My Itinerary" + ItineraryName + "</div><ul>" + ItineraryHTML + "</ul>"
            ItineraryContainer.innerHTML = ItineraryHTML;
        }
            
    }

}

function RemoveItineraryItem(nSiteId)
{
     if (confirm("Are you sure you want to remove this destination from your itinerary?")){ CoastalWebServices.RemoveFromItinerary(nSiteId, ReceiveItineraryList)};
}

function ShowDestinationDetails(DestinationID)
{
    var details = $find("DetailsModal");
    //details._dropShadowBehavior._shadowDiv.style.zIndex =1;
    details._backgroundElement.style.zIndex =2;
    details._foregroundElement.style.zIndex =3;
    $get("DestinationDetails").innerHTML = "loading, please wait...";
    details.show();
    CoastalWebServices.GetDestinationDetailControl(DestinationID, ReceiveDestinationDetails);
}

  
function ReceiveDestinationDetails(result) 
{
    $get("DestinationDetails").innerHTML = result;
}

function GetDestination(arg, callback, context)
{
    eval(callback);
}

function DestinationCallbackError(result, context){alert(result);}


function LoadCalendarEvents(nSiteId)
{
    var Year = document.getElementById("CalendarYear").value;
    var Month = document.getElementById("CalendarMonth").value;
    CoastalWebServices.GetCalendarEventNews(Year,Month, nSiteId, ReceiveCalendarEventNews);
}

function ReceiveCalendarEventNews(itemStr)
{
    //alert(itemStr);

    var items = itemStr.split("$$?");
    var Year = document.getElementById("CalendarYear").value;
    var Month = document.getElementById("CalendarMonth").value;
    
    
    
    for (var j = 0; j < items.length; j++)
    {
        var item = items[j].split(",");


        for (var DayOffset = 0; DayOffset < item[10]; DayOffset++)
        {
            
            var DateObjName = (Number(item[3]) + DayOffset)  + Month + Year;
            
            var cell = document.getElementById(DateObjName);
            cell.onmouseover = function(ev) {
                var cell_view = document.getElementById(this.id + "_view");
                if (cell_view.style.display != "block")
                {
                    ev = ev || window.event;
                    var mousePos = mouseCoords(ev);
                    //cell_view.style.left = event.clientX - 100 + document.body.scrollLeft;
                    //cell_view.style.top = event.clientY - 20 + document.body.scrollTop;
                    cell_view.style.left = mousePos.x - 100;
                    cell_view.style.top = mousePos.y - 20;
                    
                    //***cell_view.style.display = "block";
                    
                    //alert(document.body.scrollTop);
                    //alert(document.documentElement.scrollTop);
                    
                    if (CurrentOpenCalendarView != "") 
                    {
                    //alert(CurrentOpenCalendarView);
                        document.getElementById(CurrentOpenCalendarView).style.display = "none";
                       
                    }
                     CurrentOpenCalendarView = cell_view.id;
                     
                    //clearTimeout(this.timeout);
                    //this.timeout = setTimeout(function(){new Effect.BlindDown('rollit', {duration:.3, fps:40})},400);                             
                    
                }
             cell.onmouseout = function() {
                    if (CurrentOpenCalendarView != "") 
                    {
                        document.getElementById(CurrentOpenCalendarView).style.display = "none";  
                        CurrentOpenCalendarView = "";
                    }
             }
                //cell_view.innerHTML += event
            }
            cell.innerHTML += "<div id='CalendarDayItem' onclick='GetCalendarEvent(" + item[9] + ")' >" + item[1] + "<div id='CalendarDayItemSite'>" + item[7] + "</div>" + "</div>";
            //id='" + item[0] + "'
            
            var cell_view = document.getElementById(DateObjName + "_view");
            
                //timeout : null;
                cell_view.onmouseout = function() {
                this.style.display = "none";
                CurrentOpenCalendarView = "";
                }    
                cell_view.onmouseover = function() {
                this.style.display = "block";
                CurrentOpenCalendarView = this.id;
                }
                          
            cell_view.innerHTML += "<div class='CalendarDayViewItem' onclick='GetCalendarEvent(" + item[9] + ")'>" + item[1] + "<div class='CalendarDayViewSite'>" + item[7] + "</div></div>";
        }
    }
}



function mouseMove(){
	var ev       = ev || window.event;
	var mousePos = mouseCoords(ev);
}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
//	
	    if (document.documentElement && !document.documentElement.scrollTop)
	    {		
	        return {
		    x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		    y:ev.clientY + document.body.scrollTop  - document.body.clientTop		    
		    };

		}
		else
		{
	        return {
		    x:ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft,
		    y:ev.clientY + document.documentElement.scrollTop  - document.documentElement.clientTop
		    };
		}
	
}

function GetCalendarEvent(EventId)
{
    CoastalWebServices.GetCalendarEventByEventId(EventId, ReceiveSiteEventNews);
}

function GetNewsSightingPopOver(EventId)
{
    CoastalWebServices.GetNewsSightingBySugestionId(EventId, ReceiveSiteEventNews);
}

function GetEvent()
{
    //showPopWin("test test test", 600, 500, null);
    GetSiteDetailItems(1,"News");
}

function GetSiteDetailItems(nSiteId, Type)
{
    CoastalWebServices.GetCalendarEventNewsBySiteAndType(nSiteId, Type, ReceiveSiteEventNews);
}

function ReceiveSiteEventNews(control)
{
    //showPopWin(control, 600, 600, null);
    showPopWin(control, 600, 600);
}


//ADD SIGHTINGS AND NEWS
var UserID;
var AddNSsiteId;
var AddNStype;


function AddNewsSighting(nSiteId, type)
{
    if ((nSiteId != "") && ((type != "") || (type == "0")))
    {
        AddNSsiteId = nSiteId;
        AddNStype = type;
        CoastalWebServices.CheckUserLoggedIn(ReceiveUserIdStatus);
     }
}


function ReceiveUserIdStatus(UserIDStatus)
{
   UserID = UserIDStatus;
   
   if (UserID == "-1")
   {
        alert("An Error Occurred.  Please try again later");
   }
   else if (UserID == "")
   {
        window.location = "../login/Default.aspx?ReturnURL=%2fexplore%2fdetail.asp%3fid=" + AddNSsiteId + "%26type=" + AddNStype;
   }
   else
   {
        //CoastalWebServices.GetAddNSControl(AddNSsiteId, ReceiveAddNSControl);
       OpenNSPopOver();
   }
}

function OpenNSPopOver()
{
    //var NSPopOverControl = document.getElementById("AddNSPopOver");      
    
    //var btnSaveNS = document.getElementById("btnSaveNS");
    //var btnCancelNS = document.getElementById("btnCancelNS");
    
    //btnSaveNS.disabled = false;
    //btnCancelNS.disabled = false;
        
    //var AddNewsItemSubject = document.getElementById("AddNewsItemSubject");
    //var AddNewsItemDescription = document.getElementById("AddNewsItemDescription");
    
    //AddNewsItemSubject.value = "";
    //AddNewsItemDescription.value = "";
    
    //var NSPopOverControlString = NSPopOverControl.innerHTML;
    //NSPopOverControlString.replace("AddNewsItemSubject", "AddNewsItemSubjectControl");
    //NSPopOverControlString.replace("AddNewsItemDescription", "AddNewsItemDescriptionControl");
    //alert(NSPopOverControlString);
    //ReceiveAddNSControl(NSPopOverControlString);
    
    CoastalWebServices.GetAddNSControl(AddNSsiteId, ReceiveAddNSControl);
}

function ReceiveAddNSControl(control)
{
    showPopWin(control, 400, 330, null);

    if (AddNStype == 1)
    {setPopTitle("Add News");}
    else
    {setPopTitle("Add Recent Sighting");} 
}

function SaveNSItem()
{
    var btnSaveNS = document.getElementById("btnSaveNS");
    var btnCancelNS = document.getElementById("btnCancelNS");
    
    btnSaveNS.disabled = true;
    btnCancelNS.disabled = true;
        
    var AddNewsItemSubject = document.getElementById("AddNewsItemSubject");
    var AddNewsItemDescription = document.getElementById("AddNewsItemDescription");
      
    var btnSaveNS = document.getElementById("btnSaveNS");
    var btnCancelNS = document.getElementById("btnCancelNS");
    
    btnSaveNS.disabled = true;
    btnCancelNS.disabled = true;
    
    CoastalWebServices.SaveNS(UserID,AddNSsiteId, AddNStype, AddNewsItemSubject.value,AddNewsItemDescription.value,ReceiveNSSaveConfirmation);
    //CoastalWebServices.SaveNS(UserID, ReceiveNSSaveConfirmation);
}

function ReceiveNSSaveConfirmation(errorStatus)
{
    if (errorStatus == "-1")
    {
        alert("An error occurred.  Your item could not be saved.  Please try again later");
    }
    else
    {
        alert("Your item has been successfully saved.  Thank you for your submission.")
    }
    
    hidePopWin(null);
}

function CancelNSItem()
{
    hidePopWin(null);
}

//Helping Hands
function CreateCollection(ClassName)    
{
    var obj=new Array();
    eval("var t=new "+ClassName+"()");
    for(_item in t)
        {
            eval("obj."+_item+"=t."+_item);
        }
    return obj;
}
