// jQuery.ajaxSetup({ 
//   'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
// })
// 
// 
// THIS CODE RUNS THE SHOW.
// CREATED WITH LOVE BY INGRAM LABS, INC.
// www.ingramlabs.com

var map = null;

function CreateMap()
{
  map = new VEMap('myMap');
  map.LoadMap(null, 10, VEMapStyle.Aerial, false, VEMapMode.Mode2D, false, 0);

  // center on click
  map.AttachEvent("onclick", showCommunityForPin);
  map.AttachEvent("onchangeview", showPendingCommunity);
  map.AttachEvent("onendzoom", setBodyView);
  map.AttachEvent("onchangeview", setBodyView);
}

// set the zoom level and  as a body class 
function setBodyView(){
  var zoom = map.GetZoomLevel(zoom);
  var view = map.GetMapStyle(view);
  jQuery("body").removeClass();
  jQuery("body").addClass("zoom_" + zoom + " view_" + view + "");
}

function inboxCount(num){
	jQuery("#inboxCount a").html('('+ num +')'); 
}

// find location based on search
function FindLoc()
{
  try
  {
if ( jQuery("#catwPopup").length > 0 ) 
  	{
		jQuery('#catwPopup').hide();
	}
  	if (jQuery("input[@name='findtype']:checked").val() == 'map') 
	{
	  map.Find(null, jQuery("#txtWhere").val());
	}
	else
	{
	  FindGroup();
	}
  }
  catch(e)
  {
  alert(e.message);
  }
}

function FindGroup()
{
  try
  {
    if ( jQuery("#myMap_veplacelistpanel").length > 0 ) {
      jQuery('#myMap_veplacelistpanel').hide();
	  }
  	jQuery.ajax({
  	  url: "/services/map_search_groups/",
      data: "search_for=" + jQuery("#txtWhere").val(),
  	  type: 'GET',
  	  dataType: 'xml',
  	  timeout: 1000,
  	  error: function(){
        alert('Error loading XML document');
  	  },
  	  success: function(xml){
        // do something with xml
    		jQuery('#catwPopup').hide();
    		var _first = "";
    		var _count = 0;
    		var _css = "<div id=\"catwPopupBody\" class=\"catwPopupBody\" style=\"z-index: 300; height: 162px; width: 342px;\">";
    		jQuery(xml).find('group').each(function(){
    			_count += 1;
    			if(_first == "") {
            _first = jQuery(this).find('id').text();
    			}
    			_css += "<div id=\"veplacelistpanel_body_loc0\" class=\"VE_PlaceList_Location\" style=\"position: relative; z-index: 304;\">";
    			_css += "<a onclick=\"teleport('"+ jQuery(this).find('id').text() +"'); jQuery('#catwPopup').hide(); return false;\" href=\"#\">"+ jQuery(this).find('name').text() +"</a>";
    			_css += " <a onclick=\"jQuery('#catwPopupGroupDetails').toggle()\">info</a>";
    			_css += "<div id=\"catwPopupGroupDetails\" style=\"display: none;\">"+ jQuery(this).find('description').text() +"</div>";
    			_css += "</div>";
    		});
    		_css += "</div>"
        jQuery('#catwPopupBody').replaceWith(_css);
    		if(_first != '') {
    			teleport(_first);
    		}
    		if(_count > 1) {
          jQuery('#catwPopup').show();
    		}		
  	  }
  	});
  }
  catch(e)
  {
  alert(e.message);
  }
}

function loginRefresh(xml)
{
  var _user = jQuery(xml).find('user').text();
  var _user_id = jQuery(xml).find('user_id').text();
  var _circles = "<h3 class=\"head myCircles\"><a href=\"javascript:;\">My Rings</a></h3>";
  _circles += "<span class=\"topCirlcesBox\" style=\"display: none;\">";
  _circles += "<ul id=\"myCirlces\">";
  var _has_circles = false;
  jQuery(xml).find('group').each(function()
  {
    _has_circles = true;	
	_circles += "<li><a onclick=\"teleport('"+ jQuery(this).find('id').text() +"'); return false;\" href=\"#\">"+ jQuery(this).find('name').text() +"</a></li>";
  });
  
  _circles += "</ul>";
  _circles += "</span>";
  _circles += "</li>";
  
  if(_has_circles == true)
  {
  	_circles = "<li id=\"myCirclesNav\">" + _circles;
  }
  else
  {
  	_circles = "<li id=\"myCirclesNav\" style=\"display: none;\">" + _circles;
  }
  
  var _edit_profile_text = "(<a href=\"#\" onclick=\"loadPage('/users/"+ _user_id + "/')\">Profile</a>)";
  var _view_profile_text = "<a href=\"#\" onclick=\"loadPage('/users/"+ _user_id + "/')\">" + _user + "</a>";
  var _new_group_link = "<a href=\"#\" onclick=\"loadPage('/groups/new/')\">Add a Ring</a>";
  var _new_group_link2 = "<a href=\"#\" onclick=\"loadPage('/groups/new/')\">Add Your Ring Now!</a>";
  var _circle_description_link = "<a href=\"#\" onclick=\"loadPage('/groups/new/')\" >A Ring represents a place on earth where one or more people represent the Christian Church. RedRing provides an easy way for Rings to share what God is doing throughout the world.</a>";
  jQuery('#mainLogin').hide();
  jQuery('#password').val("");
  jQuery('#login').val("");
  jQuery('#loginMessage').html("");
  jQuery('#loggedOut').hide();
  jQuery('#userName').html(_view_profile_text);
  jQuery('#profileLink').html(_edit_profile_text);
  jQuery('#myCirclesNav').replaceWith(_circles);
  jQuery('#add_location').html(_new_group_link);
  jQuery('#add_circle_description').html(_circle_description_link);
  jQuery('#add_your_circle').html(_new_group_link2);
  
  if(_has_circles == true)
  {
    jQuery('#whatAreCirclesNav').hide();
  }
  else
  {
  	jQuery('#whatAreCirclesNav').show();
  }
  
  jQuery('#loggedIn').show();
}

function logoutRefresh()
{
  jQuery(jQuery.ajax({ url: '/logout',
    type: 'DELETE',
     dataType: 'script',
    // dataType: 'html',
    timeout: 1000,
    error: function() { 
      alert('Error loading document');
    }, 
    success: function(html){
      var _new_user_link = "<a href=\"#\" onclick=\"loadPage('/users/new/')\">Get on the map!</a>";
      var _new_user_link2 = "<a href=\"#\" onclick=\"loadPage('/users/new/')\">Add Your Ring Now!</a>";
      var _circle_description_link = "<a href=\"#\" onclick=\"loadPage('/users/new/')\" >A Ring represents a place on earth where one or more people represent the Christian Church. RedRing provides an easy way for Rings to share what God is doing throughout the world.</a>";
      jQuery('#loggedIn').hide();
      jQuery('#userName').html('');
      jQuery('#myCirclesNav').replaceWith("<li id='myCirclesNav' style='display: none;'><h3 class='head myCircles'></li>");
      jQuery('#loggedOut').show();
      jQuery('#add_location').html(_new_user_link);
      jQuery('#whatAreCirclesNav').show();
      jQuery('#add_circle_description').html(_circle_description_link);
      jQuery('#add_your_circle').html(_new_user_link2);
    }
  }));
}

function loadPage(url)
{
  unloadActiveCommunity();

  jQuery('#catwGeneralIFrame').html("<iframe width='550' scrolling='no' height='450' frameborder='0' src='" + url + "' allowtransparency='true' border='0' class='communityFrame' />"); 
  jQuery('#catwGeneralIFrame').show();
}

function unloadPopup()
{
	jQuery('#catwGeneralIFrame').hide();
}

// the current most popular video lat/long is inserted here
function DoCenterZoom(lat, lng, zoom)
{
   map.SetCenterAndZoom(new VELatLong(lat, lng), zoom);
}

// determine lat/long for center on click
// function CenterOnLatLong(mapX, mapY, offset) {
//   if (!offset) offset = {width: 0, height: 0};
// 
//    //Get the pixel coordinates from the click event, convert to LatLong value
//    pixel = new VEPixel(mapX + offset.width, mapY + offset.height);
//    latLong = map.PixelToLatLong(pixel);
//    map.SetCenter(latLong);
// }

//resize the map to fill the browser
function MapResize()
{
  if (map != null)
  {    
  if( typeof( window.innerWidth ) == 'number' )
  {
  //Non-IE
  map.Resize(window.innerWidth,window.innerHeight);
  } 
  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
  {
  //IE 6+ in 'standards compliant mode'
  map.Resize(document.documentElement.clientWidth,document.documentElement.clientHeight);
  }
  }
}

// pin data cache
// Key is community id. data is a map like this:
//   {
//     id: '1000',
//     name: 'The Rank 94',
//     rank: 94,
//     desc: 'This is a community with an average video popularity rank of 94 out of 100.',
//     thumb_url: '/images/pins/thumb.png',
//     lat: 47.65184677388794,
//     lon: -122.37588286399841
//     pin_id: <dynamic>
//     thumb_w: <dynamic>
//     thumb_h: <dynamic>
//     thumb_offset: <dynamic>
//     ve_element_id: <dynamic>
//     pin_container_node: <dynamic>
//   }
var PIN_DATA = {};

function injectCommunityPin(data) {
  // cache pin data.
  PIN_DATA[data.id] = data;

  // set pin_id
  data.pin_id = "community_pin_" + data.id;

  // inject pin
  var shape = new VEShape(VEShapeType.Pushpin,new VELatLong(data.lat, data.lon)); 
  shape.SetCustomIcon(pinThumbImg(data));
  shape.SetTitle(data.name);
  shape.SetDescription(data.desc + '');
  map.AddShape(shape);
}

// bulk pin loader
function injectCommunityPins(pin_data) {
  for (var i = pin_data.length - 1; i >= 0; i--){
    injectCommunityPin(pin_data[i]);
  };
}


// insert pin
function pinThumbImg(data){
  return "<div id='community_" + data.id + "' title='" + data.name + "' class='pinContainer thumbBack rank_" + Math.floor((data.rank + 5) / 10) + "' style='visibility:" + data.visibility + ";'><img class='thumbBack size_" + Math.floor((data.rank + 5) / 10) + "' src='/images/thumb_bg.png' /><img id='" + data.pin_id + "' class='communityID thumb rank_" + Math.floor((data.rank + 5) / 10) + "' src='" + data.thumb_url + "' /></div>";
}

// id: null,
// pin_container_node: null
var ACTIVE_COMMUNITY;
var SKIP_LATEST_MEDIA = false;

// Now called from onclick VE binding
function showCommunityForPin(event) {
  // VE calls this even when a pin is not clicked. Ignore that.
  if (!event.elementID) return true;

  // capture id
  var ve_element_id = event.elementID;

  // find community id and data for clicked pin.
  var pin_img = jQuery("#" + ve_element_id + " img.communityID");
  var community_id = pin_img.attr('id').replace(/community_pin_/, '');
  var data = PIN_DATA[community_id];
  data.ve_element_id = ve_element_id;

  // associate VE id with the pin data in cache.
  var parent_node = pin_img.parents(".VEAPI_Pushpin");

  // set active class
  parent_node.addClass("selectedPin");

  unloadActiveCommunity();

  // store new active community data.
  ACTIVE_COMMUNITY = {};
  ACTIVE_COMMUNITY.id = community_id;
  ACTIVE_COMMUNITY.pin_container_node = pin_img.parents(".pinContainer").get(0);

  // set thumb data for pin.
  var toff = data.thumb_offset = pin_img.offset();
  data.thumb_w = pin_img.width();
  data.thumb_h = pin_img.height();

  // overwrite pin data
  var url = "/groups/" + community_id
  if (SKIP_LATEST_MEDIA == false) {
    url += "/latest_media"; // location of video/album player
  }
  var ve_div = jQuery("#" + data.ve_element_id + " > div");
  ve_div.empty().append('<iframe class="communityFrame" border="0" frameborder="0" scrolling="no" allowtransparency="true" src="'+url+'" width="716" height="593"></iframe>');
  
  // find pin origin, compute offsets, and recenter
  centerOnCommunity(community_id, {x: 640/3, y: 530/2});
  SKIP_LATEST_MEDIA = false; // set this back to false if it was set to true

  // scale iframe
  //ve_div.find('iframe').animate({width: data.iframe_w, height: data.iframe_h}, 1000);
  //sizeToContent ();

  return false;
}

function unloadCommunity(community_hash, recenter) {
  var old_data = PIN_DATA[community_hash.id];
  jQuery("#" + old_data.ve_element_id).removeClass("selectedPin").children("div").empty().append(community_hash.pin_container_node);

  // compute offsets and recenter map
  centerOnCommunity(community_hash.id);

  return false;
}

function resizeActiveCommunity(width, height, recenter) {
  var data = PIN_DATA[ACTIVE_COMMUNITY.id];

  // scale iframe
  //var iframe = jQuery("#" + data.ve_element_id + " > div iframe");
  //iframe.animate({width: width, height: height}, 1000);

// TODO center properly
  // 
  // // compute offsets and recenter map
  // if (recenter){
  // wd = width - iframe.width();
  // hd = height - iframe.height();
  // CenterOnLatLong(data.map_x, data.map_y, {
  //   width: wd/2,
  //   height: hd/2
  // });
  // }
}

function unloadActiveCommunity(recenter) {
  // unload general iframe if there is one.
  unloadPopup();

  // and active community if there is one.
  if (ACTIVE_COMMUNITY && ACTIVE_COMMUNITY.id) {
    unloadCommunity(ACTIVE_COMMUNITY, recenter);
    ACTIVE_COMMUNITY = null;
  }
}

function centerOnCommunity(comm_id, offset) {
  if (!offset) offset = {x: 0, y: 0};

  data = PIN_DATA[comm_id];

  // find pin origin, compute offsets, and ...
  pin_pixel = map.LatLongToPixel(new VELatLong(data.lat, data.lon));
  pin_pixel.x += (offset.x || offset.width || 0);
  pin_pixel.y += (offset.y || offset.height || 0);

  // recenter map
  latLong = map.PixelToLatLong(pin_pixel);
  map.SetCenter(latLong);
}

// teleport
function teleport(community_id, skip_latest_media) {
  skip_latest_media = skip_latest_media ? true : false
  // no jumping to ourself
  if (ACTIVE_COMMUNITY && ACTIVE_COMMUNITY.id == community_id)
    return;

  // for viewchange callbacks
  PENDING_COMMUNITY=community_id;
  SKIP_LATEST_MEDIA=skip_latest_media;

  // we need to close any open communities before doing the next line
  var community = PIN_DATA[community_id];
  // alert(PENDING_COMMUNITY + "; " + (ACTIVE_COMMUNITY && ACTIVE_COMMUNITY.id) + "; " + community_id)
  unloadActiveCommunity();

  map.SetCenterAndZoom(new VELatLong(community.lat, community.lon), "11");

  // // this needs to be called in the function
  // var pushpin = jQuery('#' + click).parents('.VEAPI_Pushpin');
  // pushpin.addClass('clicked_' + click);
  // showCommunityForPin({elementID: pushpin.attr("id")});
  return false;
}

// Handler for VE callbacks. Find pin based on community_id in PENDING_COMMUNITY and load it.
var PENDING_COMMUNITY = null;
function showPendingCommunity(e, n) {
  if (PENDING_COMMUNITY) {
    var comm_id = PENDING_COMMUNITY;

    var veID = jQuery("#community_" + comm_id).parents(".VEAPI_Pushpin").attr('id');

    if (!veID) {
      if ((n||0) < 100) {
        // go into polling loop waiting for VE to drop pin with ID into place.
        setTimeout("showPendingCommunity(null, "+ ((n||0)+1) +")", 100);
      } else {
        // alert("Too many: " + n);
      }
      return;
    }

    PENDING_COMMUNITY = null;

    // alert(comm_id + "; " + veID + "; " + n);
    // jQuery("#" + veID + "> :first").trigger('click');
    showCommunityForPin({elementID: veID});
  }

  return true;
}


/* Mitigate VE hijacking; For at least Safari this is necessary.
 * Re-hijacks the prototype event handlers to ignore the occasional case where jQuery's 'fix'ed
 * event object leaks in and mangles VE.
 *
 * Most of this code is lifted out of VE itself, and is (c) Microsoft and all that.
 */
(function () {
  // if not Safari, leave.
  if (!/webkit/.test(navigator.userAgent.toLowerCase())) return;

  var a = function(a){window.event=a}

  var d = function (c,d,e){
    if(!d.slice) return;

    var b=d.slice(2);
    if(b!=="mouseenter"&&b!=="mouseleave")c.addEventListener(b,a,true);
    else{c.addEventListener("mouseover",a,true);
    c.addEventListener("mouseout",a,true)}
    c.addEventListener(b,e,false)
  }

  var c = function (d,b,c){
    if (!b.slice) return;

    var a=b.slice(2);
    if(b==="mousewheel")a="DOMMouseScroll";
    d.removeEventListener(a,c,false)
  }
  
  browser_version = navigator.appVersion.match(/^\d+\.\d+/)[0]-0;
  if (browser_version >= 5) return;

  Object.prototype.attachEvent=function(a,b){
    if(a==="onmousewheel")a="onmousewheel";
    if(a==="onclick")a="onmouseup";
    d(this,a,b)
  };

  Object.prototype.detachEvent=function(a,b){
    if(a==="onclick")a="onmouseup";
    c(this,a,b)
  };      
})();
