﻿// Functionality for World Planner
var hist=new Array();
var histsize=10;
var slot=-1;
var current=-1;
var reload=0;
var pan = 0;
var pinId = 0;
var map = null;
var pinDataList = new Array();
var polylinesDataList = new Array();

var pinspercycle=10
var pinIconUrl = null;// "../images/map/pushpin.png";
var mWidth=950
var mHeight=500
var PopupPrefix="VPOP"
var CloseBox="<div class=\"PopupClose\" onclick=\"HidePopup();\">X</div>"
//var newPinContent=CloseBox+"<span class=\"ClusterTitle\">New Photo Location</span><br /><br />This will be the location of your photo on the map. Click 'Add Photo' to continue.<br /><br /><div class=\"PinActions\"><div class=\"PopupAddImageButton\" onclick=\"javascript:HidePhotoPin(true);\"></div><br/><a href=\"#\" onclick=\"javascript:AddPhotoPin();\">Move me</a><br/><a href=\"#\" onclick=\"javascript:HidePhotoPin(false);\">Cancel</a></div>"
var PinContentEvent=CloseBox+"<b>Area:</b> [AREA]<br /><b>Venue:</b> [EVENTVENUE]<br /><b>Time:</b> [TIME]<br /><hr /><b>Description:</b><br />[EVENTDESCRIPTION]<br />[URL]<br /><br /><div class=\"PinActions\"><a href=\"#\" onclick=\"Zoom2Fit('[ENCODEDLOCATION]',[ZOOMLEVEL]);\">Zoom to street level</a><br /><a href=\"mailto:?subject=Check%20out%20this%20Australia%20Day%20event%20-%20[EVENTVENUE]&body=Hi,%0A%0AI%20found%20this%20Australia%20Day%20event%20on%20the%20Look%20Up%20and%20Smile%20website%20and%20thought%20you%20might%20like%20to%20check%20it%20out.%0A%0AClick%20here%20to%20view%20the%20event%20map:%0A[WEBSERVERPATH]/what_map.aspx?ID=[ENCODEDLOCATIONEMAIL]%0AVenue:%20[EVENTVENUE]%0ATime:%20[TIME]%0ADescription:%0A[EVENTDESCRIPTION]%0A%0AVisit%20http://www.lookupandsmile.com.au%20to%20enter%20the%20Australia%20Day%20Photo%20Competition%20and%20you%20could%20win%20a%20$100,000%20Australian%20Travel%20Pass%20for%20your%20family%20and%20great%20runner-up%20prizes%20simply%20for%20voting%20for%20your%20favourite!\">Send link in e-mail</a><br /><div onclick=\"AddImageatLocation(new VELatLong([LAT],[LON]));\" class=\"PopupAddImageButton\"></div></div>"
var PinContentPhoto=CloseBox+"<img id=\"PopupPhotoImage\" src=\"[PHOTOURL]\" alt=\"Look up and Smile User Summitted Photo\" height=\"[PHOTOHEIGHT]\" width=\"[PHOTOWIDTH]\" hspace=\"5\" align=\"left\" onload=\"SelectRatingStars([AVERAGERATING]);\" /><b>Photographer</b><br />[LIVEIDENTITYFIRSTNAME] [LIVEIDENTITYLASTNAME]<br /><br /><br /><br /><br /><br /><div onclick=\"window.location='/about_flip.aspx?ImageGUID=[PHOTOGUID]';\" class=\"LaunchFlashButton\"></div><br /><div class=\"RatingLabel\">Rating&nbsp;&nbsp;</div>"
for(var x=1;x<11;x++){
PinContentPhoto+="<div id=\"RatingStar"+x+"\" onclick=\"RatePhoto('[PHOTOGUID]',"+x+");\" onmouseover=\"SelectRatingStars("+x+");\" onmouseout=\"SelectRatingStars([AVERAGERATING]);\" class=\"[IE6MODE]RatingStar\"></div>"}
PinContentPhoto+="<br /><b>Description</b><br />[PHOTODESCRIPTION]<br /><br /><div class=\"PinActions\"><div style=\"float:left; position:relative;\"><a href=\"#\" onclick=\"Zoom2Fit('[ENCODEDLOCATION]',[ZOOMLEVEL]);\">Zoom to street level</a><br /><a href=\"mailto:?subject=Check%20out%20this%20shot%20taken%20on%20Australia%20Day&body=Hi,%0A%0AI%20found%20this%20photo%20taken%20on%20Australia%20Day%20on%20the%20Look%20Up%20and%20Smile%20website%20and%20thought%20you%20might%20like%20to%20check%20it%20out.%0A%0AClick%20here%20to%20view%20the%20image:%0A[WEBSERVERPATH]/what_map.aspx?ID=[ENCODEDLOCATIONEMAIL]%0A%0AVisit%20http://www.lookupandsmile.com.au%20to%20enter%20the%20Australia%20Day%20Photo%20Competition%20and%20you%20could%20win%20a%20$100,000%20Australian%20Travel%20Pass%20for%20your%20family%20and%20great%20runner-up%20prizes%20simply%20for%20voting%20for%20your%20favourite!\">Send link in e-mail</a></div><div id=\"ReportPhotoDiv\" class=\"ReportPhoto\" onclick=\"ReportPhoto('[PHOTOGUID]');\"></div><br /><br /><div onclick=\"AddImageatLocation(new VELatLong([PHOTOLATITUDE],[PHOTOLONGITUDE]));\" class=\"PopupAddImageButton\"></div></div>"

var map=null
var pins=new Array()
var processorIndex=0
var IE6mode=false
var popupMasterDiv
var popupPointerDiv
var popupContentDiv
var popupLoadingDiv
var LocationToPopup
var popupAddButtonDiv
var imgAddButton
var addPinMode = 0;
var canEdit = false;

function pinData(id, lat, lng, cityId, city, region, country, desc, cityOpts){
    this.id = id;
    this.lng = lng;
    this.lat = lat;
    this.cityId = cityId;
    this.city = city;
    this.region = region;
    this.country = country;
    this.desc = desc;
    this.cityOpts = cityOpts;
}

function polylinesData(fromId, toId, startLat, startLng, endLat, endLng)
{
    this.fromId = fromId;
    this.toId = toId;
    this.startLat = startLat;
    this.startLng = startLng;
    this.endLat = endLat;
    this.endLng = endLng;
}
      
function addPinClick()
{
    if(map!=null){
        if (addPinMode==0){
            addPinMode=1;
            document.getElementById("map").childNodes[0].style.cursor="crosshair"
            document.getElementById("AddPhotoInstructions").style.display="block"
            document.getElementById("btnAddPin").className = "CancelAddImageButton";
            
        }
        else
        {
            addPinMode=0;
            document.getElementById("map").childNodes[0].style.cursor="default"
            document.getElementById("AddPhotoInstructions").style.display="none"
            document.getElementById("btnAddPin").className = "AddImageButton";
        }
    }
}

function saveSteps(){
    var wpID;
    
    var ddd = document.getElementsByName("WorldPlannerID").value;

    if (document.getElementsByName("WorldPlannerID").value==""){
        wpID = 0;
    }
    else{
        wpID = document.getElementsByName("WorldPlannerID").value;
    }
        
    var e = WorldPlanner_TravelPlanner.SaveSteps(wpID, pinDataList);
    if (e.value!=0){

        document.location.href = "Members/TravelPlanner_Add.aspx?wpID=" + e.value;
        //document.write(location.href);
    }
    else{
        alert("Error saving plan to database");
    }
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
    else
    {
        return "0";
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}

function loadSteps(){
    var wp = WorldPlanner_TravelPlannerReadOnly.GetSteps(getQueryVariable("id") );
    if (wp.error != null){
        alert(wp.error.Message);
    }
    else
    {
        var wps = wp.value;
        for (var i = 0; i < wps.length; i++) {
            //Create a new pin data object
            var pd = new pinData(pinId, wps[i].Latitude, wps[i].Longitude, wps[i].CityId, wps[i].City, wps[i].Region, wps[i].Country, wps[i].Description, null);
            pinId++;

            //Add pin to the list of pins
            pinDataList[pinDataList.length] = pd;

            //Add pin to the map
            AddClickablePin(pd.id,wps[i].Latitude, wps[i].Longitude,true)
            document.getElementById("map").childNodes[0].style.cursor=""
            
            //Draw the lines
            if (pinDataList.length > 1)
            {
                var pl = new polylinesData(pinDataList[pinDataList.length-2].id, pd.id, pinDataList[pinDataList.length-2].lat,pinDataList[pinDataList.length-2].lng, pinDataList[pinDataList.length-1].lat, pinDataList[pinDataList.length-1].lng);
                polylinesDataList[polylinesDataList.length] = pl;
                DrawPoly(pd.id-1, [new VELatLong(pinDataList[pinDataList.length-2].lat,pinDataList[pinDataList.length-2].lng), new VELatLong(pinDataList[pinDataList.length-1].lat, pinDataList[pinDataList.length-1].lng)], 1, new VEColor(0,0,255,1));
            }
        }
    }
}

function loadEditSteps(){
    var wp = WorldPlanner_TravelPlanner.GetSteps(getQueryVariable("id") );
    if (wp.error != null){
        alert(wp.error.Message);
    }
    else
    {
        var wps = wp.value;
        for (var i = 0; i < wps.length; i++) {
            //Create a new pin data object
            var pd = new pinData(pinId, wps[i].Latitude, wps[i].Longitude, wps[i].CityId, wps[i].City, wps[i].Region, wps[i].Country, wps[i].Description, null);
            pd.cityOpts = WorldPlanner_TravelPlanner.GetLongLatLookup(wps[i].Longitude, wps[i].Latitude).value;
            pinId++;

            //Add pin to the list of pins
            pinDataList[pinDataList.length] = pd;

            //Add pin to the map
            AddClickablePin(pd.id,wps[i].Latitude, wps[i].Longitude,true)
            document.getElementById("map").childNodes[0].style.cursor=""
            
            //Draw the lines
            if (pinDataList.length > 1)
            {
                var pl = new polylinesData(pinDataList[pinDataList.length-2].id, pd.id, pinDataList[pinDataList.length-2].lat,pinDataList[pinDataList.length-2].lng, pinDataList[pinDataList.length-1].lat, pinDataList[pinDataList.length-1].lng);
                polylinesDataList[polylinesDataList.length] = pl;
                DrawPoly(pd.id-1, [new VELatLong(pinDataList[pinDataList.length-2].lat,pinDataList[pinDataList.length-2].lng), new VELatLong(pinDataList[pinDataList.length-1].lat, pinDataList[pinDataList.length-1].lng)], 1, new VEColor(0,0,255,1));
            }
        }
    }
}

function createPin(cityData) {
    if (addPinMode == 1){
        //Create a new pin data object
        var pd = new pinData(pinId, cityData[0].Latitude, cityData[0].Longitude, cityData[0].CityId, cityData[0].City, cityData[0].Region, cityData[0].Country, "", cityData);
        pinId++;
        
        //Add pin to the list of pins
        pinDataList[pinDataList.length] = pd;

        //Add pin to the map
        AddClickablePin(pd.id,cityData[0].Latitude, cityData[0].Longitude,true)
        document.getElementById("map").childNodes[0].style.cursor=""
        
        //Draw the lines
        if (pinDataList.length > 1)
        {
            var pl = new polylinesData(pinDataList[pinDataList.length-2].id, pd.id, pinDataList[pinDataList.length-2].lat,pinDataList[pinDataList.length-2].lng, pinDataList[pinDataList.length-1].lat, pinDataList[pinDataList.length-1].lng);
            polylinesDataList[polylinesDataList.length] = pl;
            DrawPoly(pd.id-1, [new VELatLong(pinDataList[pinDataList.length-2].lat,pinDataList[pinDataList.length-2].lng), new VELatLong(pinDataList[pinDataList.length-1].lat, pinDataList[pinDataList.length-1].lng)], 1, new VEColor(0,0,255,1));
        }
        
        addPinMode = 0;
        document.getElementById("btnAddPin").className = "AddImageButton";
        document.getElementById("AddPhotoInstructions").style.display="none";
    }
    
    return true;
}

function AddClickablePin(pinID,lat, lon, activatepopup){
    //if(IE6mode&&icon_url.substring(icon_url.length-4)==".png"){
    //iconStyle="IE6"+iconStyle
    //icon_url="images/map/Blank.gif"}
    //var pin=new VEPushpin(pinID,latlon,icon_url,"",pinID+"",iconStyle)
    var pin=new VEPushpin(pinID,new VELatLong(lat, lon),pinIconUrl,"",pinID+"",null)
    VEPushpin.ShowDetailOnMouseOver=false
    VEPushpin.OnMouseOverCallback=PinHover
    map.AddPushpin(pin)
    var element=document.getElementById(pinID)
    element.onclick=EventHandlerOnClick
    if(canEdit && activatepopup){
        document.getElementById(pinID+"_"+map.GUID).onmouseover()
    }
}

function createPinPopUp(pd)
{
    var strPinHTML = "";
    strPinHTML=CloseBox;

    strPinHTML += "City:<br /> <select name='city" + pd.id + "' id='city" + pd.id + "'>" 
    for (var i = 0; i < pd.cityOpts.length; i++) {
        if (pd.city == pd.cityOpts[i].City)
            strPinHTML += "<option value='" + pd.cityOpts[i].CityId + "' selected='true'>" + pd.cityOpts[i].City + "</option>";
        else
            strPinHTML += "<option value='" + pd.cityOpts[i].CityId + "'>" + pd.cityOpts[i].City + "</option>";
    }
    strPinHTML += "</select><br/>" + pd.region + ", " + pd.country + "<br/><textarea cols='17' rows='5' id='txtDesc" + pd.id + "'>" + pd.desc + "</textarea><br><a href=\"javascript:DeletePin(" + pd.id + ");\">Delete</a> | <a href=\"javascript:SavePin(" + pd.id + ");\">Save</a>";
    
    return strPinHTML;
}

function createReadOnlyPinPopUp(pd)
{
    var strPinHTML = "";
    strPinHTML=CloseBox;

    strPinHTML += "City:" + pd.city 
    strPinHTML += "<br/>" + pd.region + ", " + pd.country + "<br/><br/>" + pd.desc + "<br>";
    
    return strPinHTML;
}

      
function CheckIEVersion(){
    var version=0
    if(navigator.appVersion.indexOf("MSIE")!=-1){
        temp=navigator.appVersion.split("MSIE")
        version=parseFloat(temp[1])}
    if(version>=5.5&&version<7){
        IE6mode=true}
}

function MapDispose(){
    pins=null
    popupMasterDiv=null
    popupPointerDiv=null
    popupContentDiv=null
    popupLoadingDiv=null
    LocationToPopup=null
    newPin=null
    if(map!=null){
        map.Dispose()}
    map=null
}

function loadPlanner()
{
        //try{
            var ffv=0;
            var ffn="Firefox/";
            var ffp=navigator.userAgent.indexOf(ffn);
            if(ffp !=-1)
                ffv=parseFloat(navigator.userAgent.substring(ffp+ffn.length));
                // If we're using Firefox 1.5 or above override the Virtual Earth drawing functions to use SVG
                if(ffv>=1.5){
                    Msn.Drawing.Graphic.CreateGraphic=function(f,b){return new Msn.Drawing.SVGGraphic(f,b);
                }
            }
            CheckIEVersion();
            map=new VEMap('map');
            map.LoadMap(new VELatLong(50,5),4,'h', false);
            map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
            

            if (canEdit)
            {
                map.AttachEvent("onmouseup", function(e){onClickEvent(e)});
                onClickEvent = function (e)
                {
                    var x = e.mapX;
                    var y = e.mapY;
                    var pixel = new VEPixel(x, y);
                    var latlong = map.PixelToLatLong(pixel);

                    //Round the coordinates to 5 decimal places
                    var latitude = Math.round(10000*latlong.Latitude)/10000;
                    var longitude = Math.round(10000*latlong.Longitude)/10000;

                    var cv = WorldPlanner_TravelPlanner.GetLongLatLookup(longitude, latitude).value;
	                if (cv != null)
	                {
	                    createPin(cv);
	                }
                }

                CreateCustomPopup();
            
                //Add the photo button
                var divAddPhoto=document.getElementById("AddPhotoPane");
                divAddPhoto.style.display="block";
                divAddPhoto.style.left=map.GetLeft()+805+"px";
                divAddPhoto.style.top=map.GetTop()+5+"px";
                
                loadEditSteps();
            }
            else{
                CreateCustomPopup();
                
                loadSteps();
            }

}


function PinHover(x,y,title,details){
    PhotoPopupGUIDs=new Array()
    var ID=details
    var DivID=PopupPrefix+ID
    var classPrefix=""
    if(IE6mode){
        classPrefix="IE6"}
    var classSuffix=""
    var PopupWidth=161
    var PopupHeight=150
    var PopupPointerWidth=21
    var PopupPointerHeight=31
    var PopupLoadingWidth=64
    var PopupLoadingHeight=64
    var mapX=x - map.GetLeft();
    var mapY=y - map.GetTop();
    x = x + document.getElementById("site_container").offsetLeft  - map.GetLeft();
    y = y + document.getElementById("site_container").offsetTop + 235 - map.GetTop();
    
    if(mapY<=(mHeight/2)){
        classSuffix="T"
        popupContentDiv.style.top=0+"px"
        popupMasterDiv.style.top=(y-PopupPointerHeight)+"px"
        popupLoadingDiv.style.top=(PopupHeight-PopupLoadingHeight)/2+"px"
    }else{
        classSuffix="B"
        popupContentDiv.style.top=PopupPointerHeight+"px"
        popupMasterDiv.style.top=(y-PopupHeight)+"px"
        popupLoadingDiv.style.top=(PopupHeight-PopupLoadingHeight)/2+"px"
    }
    if(mapX<=(mWidth/2)){
        classSuffix+="L"
        popupContentDiv.style.left=PopupPointerWidth+"px"
        popupMasterDiv.style.left=x+"px"
        popupLoadingDiv.style.left=(((PopupWidth-PopupPointerWidth)-PopupLoadingWidth)/2+PopupPointerWidth)+"px"
    }else{
        classSuffix+="R"
        popupContentDiv.style.left=0+"px"
        popupMasterDiv.style.left=(x-PopupWidth)+"px"
        popupLoadingDiv.style.left=((PopupWidth-PopupPointerWidth)-PopupLoadingWidth)/2+"px"
    }
    popupPointerDiv.className=classPrefix+"PopupPointer"+classSuffix

    popupLoadingDiv.style.display="none"
        
    var pd = getPinData(ID);
    if (pd != null)
        if (canEdit){
            popupContentDiv.innerHTML=createPinPopUp(pd);
        }
        else
        {
            popupContentDiv.innerHTML=createReadOnlyPinPopUp(pd);
        }
            
    popupMasterDiv.style.display="block"
}

function getPinData(id){
    var pd = null;
    for (var i = 0; i < pinDataList.length; i++) {
        if (pinDataList[i].id == id)
            pd = pinDataList[i]
    }
    return pd;
}

function EventHandlerOnClick(e){
    if(e!=null){
        document.getElementById(e.currentTarget.id+"_"+map.GUID).onmouseover()
    }else{
        document.getElementById(window.event.srcElement.id).onmouseover()}
}

function HidePopup(){
    if(popupMasterDiv!=null){
    popupMasterDiv.style.display="none"}
}

function CreateCustomPopup(){
    popupMasterDiv=document.createElement("div");
    popupMasterDiv.id="myCustomPopup";
    popupMasterDiv.style.display="none";
    popupMasterDiv.className="PopupMaster";
    map.AddControl(popupMasterDiv);
   
    popupPointerDiv=document.createElement("div");
    popupPointerDiv.id="myCustomPopupPointer";
    popupPointerDiv.className="PopupPointerTL";
   
    popupMasterDiv.appendChild(popupPointerDiv);
    popupContentDiv=document.createElement("div");
    popupContentDiv.id="myCustomPopupContent";
    popupContentDiv.className="PopupContent";
    popupMasterDiv.appendChild(popupContentDiv);
    
    popupLoadingDiv=document.createElement("div");
    popupLoadingDiv.id="myCustomPopupLoading";
    popupLoadingDiv.className="PopupLoading";
    popupMasterDiv.appendChild(popupLoadingDiv);
}

function DrawPoly(id,points,width,color)         
{            
    poly = new VEPolyline(id,points);            
    poly.SetWidth(width);            
    poly.SetColor(color);
    map.AddPolyline(poly);            
}

function DeletePin(id)         
{              
    //try            
    //{                 
        if (id!=null)                
        {     
        
            var newLineStartId = 0;
            var newLineEndId = 0;
            var newLineStartLat = 0;
            var newLineStartLng = 0;
            var newLineEndLat = 0;
            var newLineEndLng = 0;
            
            // loop through and check which lines need to go
            for (var i = 0; i < polylinesDataList.length; i++) {
                   if (polylinesDataList[i].fromId==id)
                   {
                        map.DeletePolyline(polylinesDataList[i].fromId);
                        // add the co-ordinates so we can draw a line between the remaining push pins
                        newLineEndLat = polylinesDataList[i].endLat;
                        newLineEndLng = polylinesDataList[i].endLng;
                        newLineEndId = i
                   }
                   
                   if (polylinesDataList[i].toId==id)
                   {
                        map.DeletePolyline(polylinesDataList[i].fromId);
                        newLineStartLat = polylinesDataList[i].startLat;
                        newLineStartLng = polylinesDataList[i].startLng;
                        newLineStartId = i
                   }
            }
            if (newLineStartId !=0) {polylinesDataList.splice(newLineStartId,1)}
            if (newLineEndId !=0) {polylinesDataList.splice(newLineEndId,1)}

            //remove pushpin from array
            pinDataList.splice(id, 1);

            //remove from map
            map.DeletePushpin(id); 
            
            if (newLineStartLat != 0 && newLineEndLat != 0){
                //draw the new line
                DrawPoly(newLineStartId, [new VELatLong(newLineStartLat,newLineStartLng), new VELatLong(newLineEndLat, newLineEndLng)], 1, new VEColor(0,0,255,1));                
            }
            
            HidePopup();
        }                
        else                
        {                
            map.DeleteAllPushpins(); 
            map.DeleteAllPolylines();               
        }    
    //}            
    //catch (err)            
    //{                
    //    alert(err.message);            
    //}
}   

function SavePin(id)         
{              
    //try            
    //{                 
        if (id!=null)                
        {   
            //retieve details
            var pd = getPinData(id);
            pd.desc = document.getElementById("txtDesc" + id).innerText;
            pd.cityId = document.getElementById("city" + id).options[document.getElementById("city" + id).selectedIndex].value;
            pd.city = document.getElementById("city" + id).options[document.getElementById("city" + id).selectedIndex].text;
            HidePopup();
        }                
    //}            
    //catch (err)            
    //{                
    //    alert(err.message);            
   // }
}   


function switch_region(region) {
	switch(region) {
		case 'Africa': 	 map.SetCenterAndZoom(new VELatLong(2.0, 17.0), 3);
		break;
		case 'Australasia': 	map.SetCenterAndZoom(new VELatLong(-9.0,146.16),3);
		break;
		case 'East_Asia': 	map.SetCenterAndZoom(new VELatLong(34.0, 115.224),3); 
		break;
		case 'Europe': map.SetCenterAndZoom(new VELatLong(56.365, 10.459), 3);
		break;
        case 'Middle_East': map.SetCenterAndZoom(new VELatLong(34.0, 39.0), 4);
		break;
		case 'North_America': map.SetCenterAndZoom(new VELatLong(44.21, -99.756), 3);
		break;
		case 'South_America': map.SetCenterAndZoom(new VELatLong(-24.367, -66.357), 3);
		break;
		case 'West_Asia': map.SetCenterAndZoom(new VELatLong(38.548, 69.521), 3);
		break;
	}
}

function set_region(region) {
	var regions=['Africa', 'Australasia', 'East_Asia', 'Europe', 'Middle_East', 'North_America', 'South_America', 'West_Asia'];
	for (var i=0; i<regions.length; i++) {
		$(regions[i]).style['background'] = '#ffea8d';
		$(regions[i]).style['color'] = '#1E1D57';
	}
	$(region).style['background'] = '#c0540b';
	$(region).style['color'] = '#FFFFFF';
	$('message').innerHTML='<div style="text-align: center"><br><br><\
br><br>Click on a region to start.</div>';
	var func=sprintf('switch_region("%s")',region);
	ajax('/ajax_log','msg='+func,null);
	setTimeout(func,10);	
}

