﻿///<reference path="VeJavaScriptIntellisenseHelper.js" />

var map = null;
var mapData = null;    
var panToLat = null;
var panToLong = null;
var mStyle = null;
var ycywuid = null;

function startGetMap()
{
    setToken ();
}

function getMap(token) {
    mapData = $.parseJSON($('#mapXml').html());
    // firefox Hack
    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) }
    }

    map = new VEMap('YCYWMap');
    map.SetClientToken(token);
    // Check to see if we are here to view the Local traffic (map data was not set)     
    var LocalTaffic;

    if (mapData.length == 0) {
        LocalTaffic = true;
        var latlong = new VELatLong(parseFloat(TLat), parseFloat(TLon), 20, VEAltitudeMode.RelativeToGround);
        map.LoadMap(latlong);
    } else {
        LocalTaffic = false;
    }
    //var pinHTML = "<div class='pinStyle'>{0}</div>";

    for (var i = 0; i < mapData.length; i++) {
        var current = mapData[i];
        var latlong = new VELatLong(parseFloat(current.Latitude), parseFloat(current.Longitude), 10, VEAltitudeMode.RelativeToGround);
        if (i == 0) { map.LoadMap(latlong); }
        // Attach the event handlers to the mouse 
        // map.AttachEvent ("onmouseover", mouseOverHandler);
        // map.AttachEvent ("onmouseout", mouseOutHandler);

        //var icon = "<div style=\"text-align:center;background-image:url(" + imgPushPin + ");\">1<img style=\"float:left;display:inline\" src=\"" + imgPushPin + "\" alt=\"" + current.BusinessName + "\" title=\"" + current.BusinessName + "\" /></div>";
        var icon = "<div id=\"msMapDiv\" style=\"cursor:pointer;cursor:hand;color:#FFF;font-weight:bold;height:27px;width:23px;text-align:center;background-image:url(" + imgPushPin + ");\">" + current.DisplayIndex + "</div>";
        var shape = new VEShape(VEShapeType.Pushpin, latlong);
        // set currentPin HTML
        // var currentPinHTML = pinHTML.replace('{0}', i);
        shape.SetDescription(getPopupHtml(current, i));
        shape.SetCustomIcon(icon);
        if (current.Heading.length > 0)
            shape.SetTitle(current.Heading);
        else
            shape.SetTitle(current.BusinessName);
        map.AddShape(shape);
        current.ShapeID = shape.GetID();
        // only allow in IE
       if (ffv == '0') {
            changeGridviewID_IE(current.GridviewDivID, current.ShapeID);
        } else {
            changeGridviewID_FF(current.GridviewDivID, current.ShapeID);
        }
      
        if (current.HasFocus) {
            map.SetCenter(latlong);
        }
       
    }
    if (LocalTaffic) {
        map.SetZoomLevel(11);
    }
    else {
        map.SetZoomLevel(14);
    }
   
    setMapSytle(); 
   // alert(largermap);
    if(largermap == 'no')
    ShowTraffic();
    if((largermap != null) && (largermap == 'yes'))
       ShowTrafficLargerMap();
    map.AttachEvent("onendpan", endEvent);
    map.AttachEvent("onchangeview", endEvent);
    map.AttachEvent("onchangemapstyle", changeMapStyle);
    
            document.getElementById('MSVE_obliqueNotification').innerHTML = "";
     map.SetZoomLevel (14); 
    
    
}


 function ShowTraffic()
 {
    map.LoadTraffic(true);
    map.ShowTrafficLegend(283,330);
    map.SetTrafficLegendText("Traffic");
 }
 function ShowTrafficLargerMap()
 {
    map.LoadTraffic(true);
    map.ShowTrafficLegend(463,530);
    map.SetTrafficLegendText("Traffic");
 }
  function SetLargerMapFlag()
 {
   ClearTraffic();
   largermap ='yes';
 }
 function ClearTraffic()
 {
    map.ClearTraffic();
 }


 function getOuter(ele) {
     var parent = ele.parentNode;
     var el = document.createElement(parent.tagName);
     el.appendChild(ele);
     var shtml = el.innerHTML;
     parent.appendChild(ele);
     return shtml;
 }

// var d = elem.ownerDocument.createElement("body");
// d.innerHTML = h;
// elem.parentNode.replaceChild(d.firstChild, elem);


 function changeGridviewID_FF(i, PushPinID) {
     var elem = document.getElementById(i);
     if (elem) {
         //        //alert( strInnerHTML);
         //Build out sidebar
         var itemHTML = '';
         var strouterHTML = getOuter(elem);
         var d = elem.ownerDocument.createElement("body");
         itemHTML = ' onmouseover="mouseOverSidebarItem(\'' + PushPinID + '\');"';
         d.innerHTML = strouterHTML.replace('<table width=\"100%\"', '<table width=\"100%\"' + itemHTML);
         elem.parentNode.replaceChild(d.firstChild, elem);

     }
 }



function changeGridviewID_IE (i, PushPinID)
{
    var elem = document.getElementById(i);
    if (elem) {
//        //alert( strInnerHTML);
        //Build out sidebar
        var itemHTML = '';
        var strouterHTML = elem.outerHTML;
        itemHTML += ' onmouseover="mouseOverSidebarItem(\'' + PushPinID + '\');"';
        // onmouseout="mouseOutSidebarItem(\'' + PushPinID + '\');"';
        elem.outerHTML = strouterHTML.replace('<TABLE width=\"100%\"', '<TABLE width=\"100%\"' + itemHTML)
    }
}

function changeMapStyle(e)
{
    $.ajax({
        type: 'POST',
        url: ycywbase + '/ajax.ashx?t=map&m=SetVEView&v=' + map.GetMapStyle()        
    });
}

function setMapSytle ()
{    
    if (mStyle)
    {
        if (mStyle == 'Road')
        {
           map.SetMapStyle(VEMapStyle.Road);
        }
        else if (mStyle == 'Hybrid')
        {
            map.SetMapStyle(VEMapStyle.Hybrid);        
        }
        else if (mStyle == 'Aerial')
        {
            map.SetMapStyle(VEMapStyle.Aerial);
        }
        else if (mStyle == 'Birdseye' || mStyle == 'BirdseyeHybrid' || mStyle == 'Oblique')
        {
            map.SetMapStyle(VEMapStyle.Birdseye);
        }    
    }
}

function endEvent()
{
    if (panToLat && panToLong)
    {
        setTimeout (showInfoBox, 500);
    }
}

function showInfoBox()
{
    jumpToLocation (panToLat, panToLong);
    panToLat = panToLong = null;
}

function getPopupHtml(business, idx)
{
      var desc = "";
    if (business.Address.length > 0)
        var busAddress = business.Address;
        desc += "<div>" + busAddress.replace(/\,\,/g,","); + "</div>";
    if (business.PhoneNumber.length > 0)
        desc += "<div>Phone: " + business.PhoneNumber + "</div>";
    if (business.FaxNumber.length > 0)
        desc += "<div>Fax: " + business.FaxNumber + "</div>";  
    if (business.DisplayAdUrl.length > 0)
        desc += "<div>"+ business.DisplayAdUrl + "</div>"; 
    if (business.EmailAddress.length > 0)
        desc += "<div>E-mail: " + business.EmailAddress + "</div>";            
    if (business.Website.length > 0)
        desc += "<div><a target=\"_blank\" href=\"" + "http://" + business.Website + "\">Web Site</a></div>";
    if (business.Description.length > 0)
        desc += "<div style=\"padding: 5px 0 5px 0;\">" + business.Description + "</div>"; 
    if (business.CouponsUrl.length > 0)
        desc += "<div><a target=\"_blank\" href=\"" + business.CouponsUrl + "\">Coupons for this business</a></div>";       
    desc += "<div><a href='../GetDirections.aspx?La=" + business.Latitude + "&Lo=" + business.Longitude + "&Bi=" + escape(business.BusinessName) + "&Ad=" + escape(business.Address) + "' target='GetDirections' title=\"Directions to this location\">Directions to this location</a></div>";           
    desc += "<div><a href=\"javascript:sendToFriendOpen(" + idx + ");\" title=\"Send map to friend\">Send map to friend</a></div>";
//    if (ycywuid){
   //     desc += "<div><a href=\"javascript:addToContacts(" + idx + ");\" title=\"Save this business to my network\">Save this business to my network</a></div>";//}

    return desc;                  
}


function launchDirectionsModal(idx)
{
    var data = $.parseJSON( $('#mapXml').html());     
    var business = data[idx];
    $('#msgDirections').html('Directions to ' + business.BusinessName);
    $('#btnGoDirections').bind('click', function(){ getDirections (idx); });
    $('#directionsModal').jqmShow(); 
}

function jumpToLocation(latitude, longitude)
{   
    for (var i = 0; i < mapData.length; i++)
    {
        var current = mapData[i];
        if (current.Latitude == latitude && current.Longitude == longitude)
        {
            map.HideInfoBox();
            var shape = map.GetShapeByID(current.ShapeID);            
            map.ShowInfoBox (shape, new VELatLong (Number(latitude), Number(longitude)));
            return;
        }
    }
}

function addToContacts(idx)
{
//    var data = $.parseJSON( $('#mapXml').html());     
//    var business = data[idx];
//   window.open(ycywroot + '/Registered/Contacts.aspx?l=1&BusinessName=' + escape(business.BusinessName) + '&ServiceType= ' + escape(business.ServiceType) + '&WorkPhone= ' + escape(business.PhoneNumber) +
//        '&EmailAddress=' + escape(business.EmailAddress) + '&Website=' + escape(business.Website) + '&Fax=' + escape(business.FaxNumber) + '&Street=' + escape(business.BldAddr) + '&City=' + escape(business.City) + '&State=' + escape(business.State) + '&ZipCode=' + escape(business.ZipCode),'Contacts');
////    $.ajax({
//        type: 'POST',
//        dataType: 'json',
//        data: $.toJSON(business),        
//        url:  ycywroot + '/ajax.ashx?t=map&m=AddToContacts&userID=' + ycywuid,
//        success: function(result) { alert(result.Message); }
//    });
}

function setCenter(latitude, longitude)
{
    var latlong = new VELatLong (Number(latitude), Number(longitude)); 
    map.SetCenter(latlong);       
    panToLat = latitude;
    panToLong = longitude;
}

function setToken()
{

     $.ajax({
        type: 'POST',
        url: ycywbase + '/ajax.ashx?t=map&m=GetToken',
        data: "{}",
        success: function(result) { getMap(result) }
    });
}

function sendToFriendOpen(idx)
{
    $('#friendModal').jqmShow();
    $('#btnSendToFriend').bind('click', function(){ sendToFriendComplete (idx); });
}

function sendToFriendComplete(idx)
{
    var data = $.parseJSON( $('#mapXml').html());     
    var business = data[idx];
    var obj = new Object();
    obj.To = $('#mapToAddress').val();
    obj.From = $('#mapFromAddress').val();
    obj.Comments = $('#mapComments').val();
    obj.Business = business;
    $.ajax({
        type: 'POST',
        dataType: 'json',
        data: $.toJSON(obj),        
        url: ycywbase + '/ajax.ashx?t=map&m=SendToFriend',
        success: function(result) {alert(result.Message); if (!result.HasError) { $('#friendModal').jqmHide();$('#btnSendToFriend').unbind('click'); } }
    });

        
}

var popupTimeout;

function mouseOverSidebarItem(markerId){
    //center map on current pushpin
    currentShape = map.GetShapeByID(markerId);
    var latlong = new VELatLong (parseFloat(currentShape.Latitude), parseFloat(currentShape.Longitude), 10, VEAltitudeMode.RelativeToGround);  
    map.SetCenter ( latlong );
}


$(function() {
    // This is what's called when the genericmap usercontrol  property displayMap = true
    if (displayMapFlag) {
        $('#YCYWMap').attr('style', mapStyle);
        
             mapData = $.parseJSON($('#mapXml').html());
            //if there is no map data
              if (mapData.length == 0) {
                  $('#YCYWMap').hide();
                 $('.largermapJQ').hide();
                  
                 }
                 else
                 {        startGetMap();
                 }
       // $('#directionsModal').jqm(
       // { modal: true }
      //  );
      $('#directionsModal').hide();
    } else {
    // hide these DIV ID's when genericmap usercontrol property displayMap = false
        $('#largerMap,#YCYWMap').hide();
    }

    $('#btnCancelSendToFriend').bind('click', function() {
        $('#friendModal').jqmHide();
        $('#mapToAddress,#mapFromAddress,#mapComments').val('');
    });
    $('#friendModal').jqm(
        { modal: true }
    );
      
});


function sendToFriendOpen(idx)
{
    $('#friendModal').jqmShow();
    $('#btnSendToFriend').bind('click', function(){ sendToFriendComplete (idx); });
}
function sendToFriendComplete(idx)
{

    var data = $.parseJSON( $('#mapXml').html());     
    var business = data[idx];
    var obj = new Object();
    obj.To = $('#mapToAddress').val();
    obj.From = $('#mapFromAddress').val();
    obj.Comments = $('#mapComments').val();
    obj.Business = business;
    $.ajax({
        type: 'POST',
        dataType: 'json',
        data: $.toJSON(obj),        
        url: ycywbase + '/ajax.ashx?t=map&m=SendToFriend',
        success: function(result) {alert(result.Message); if (!result.HasError) { $('#friendModal').jqmHide();$('#btnSendToFriend').unbind('click'); } }
    });

        
}