var popLayer = "popupoverlay";
var loadingLayer = "popuploading";
var contentLayer = "popupcontent";
var helpId = "help_intro";

function loadCalendar_js()
{
  if( typeof(def_calendar) == "undefined" ){ addScript("/js/calendar.js"); }
}
function loadJsCalendar_js()
{
  if( typeof(def_calendar) == "undefined" ){ addScript("/js/jsCalendar.js"); }
}
function loadBuddies_js()
{
  if( typeof(def_buddies) == "undefined" ){ addScript("/js/buddies.js"); }
}
function loadMembers_js()
{
  if( typeof(def_members) == "undefined" ){ addScript("/js/members.js"); }
}

function doPopup( locationId )
{
  var pop = initPopup();
  var loading = initLoading(pop,true);
  pop.style.display = "block";
  var content = initContent(pop,locationId);
  loading.style.display = "none";
  content.style.display = "block";
}

function switchLoading()
{
  var loading = document.getElementById( loadingLayer );
  var content = document.getElementById( contentLayer );
  loading.style.display = "none";
}

function hidePopup( )
{
  var pop = initPopup();
  pop.style.display = "none";
  var content = document.getElementById( contentLayer );
  pop.removeChild( content );
}

function hideOldContent()
{
  if ( popContentElement!="" )
  {
    var objWidth = getObjectWidth(popContentElement);
    var objHeight = getObjectHeight(popContentElement);
    popContentParent.appendChild( popContentElement );
    popContentElement.style.display = popContentDisplay;
    popContentElement.style.width = objWidth+"px";
    popContentElement.style.height = objHeight+"px";
    popContentElement = "";
  }
}

function initPopup()
{
  var el = document.getElementById(popLayer);
  if ( el==null || typeof(el)=="undefined" )
  {
    var htmlbody = document.getElementsByTagName("body").item(0);
    el = document.createElement("div");
    el.className = "overlay";
    el.style.background = "url('/art/popupmap/overlay.png')";
    el.setAttribute("id",popLayer);
    el.style.display = "none";
    el.style.position = "absolute";
    el.style.top = "0";
    el.style.left = "0";
    el.style.zIndex = "101";
    htmlbody.insertBefore(el, htmlbody.firstChild);
  }
  el.style.left = getDisplayScrollX() + "px";
  el.style.top = getDisplayScrollY() + "px";

  el.style.width = getDisplayWidth() + "px";
  el.style.height = getDisplayHeight() + "px";
  return el;
}

function initLoading( el, create )
{
  var loading = document.getElementById( loadingLayer );
  if ( create && (loading==null || typeof(loading)=="undefined") )
  {
    loading = document.createElement("div");
    loading.className = "loading";
    loading.setAttribute("id",loadingLayer);
    loading.style.display = "none";
    loading.style.background = "url(/art/popupmap/loading.gif) no-repeat center middle";
    loading.style.top = "0";
    loading.style.left = "0";
    loading.style.width = "126px";
    loading.style.height = "22px";
    loading.style.zIndex = "91";
    //el.appendChild( loading );
  }
  displayContent( el, loading );
  return loading;
}

function initContent( el, locationId )
{
  var content = document.createElement("div");
  content.className = "popupMap";
  content.setAttribute("id",contentLayer);
  content.style.display = "none";
  content.style.background = "#fff";
  content.style.top = "0";
  content.style.left = "0";
  content.style.width = "594px";
  content.style.height = "365px";
  content.style.zIndex = "91";

  var ifr = document.createElement("iframe");
  ifr.border = 0;
  ifr.frameBorder = 0;
  ifr.style.border = "0px";
  //ifr.onload = parent.switchLoading();
  ifr.setAttribute("scrolling","none");
  ifr.scrolling="no";
  ifr.width = 594;
  ifr.height = 335;
  ifr.src = "/members/locations/popupmap.jsp?locationId="+locationId;
  content.appendChild(ifr);

  var closelink = document.createElement("p");
  closelink.innerHTML = "<a href=\"#\" onclick=\"hidePopup();return false\">Close map</a>";
  closelink.style.padding = "10px";
  closelink.style.textAlign = "right";
  content.appendChild( closelink );

  displayContent( el, content );
  return content;
}

function displayContent( el, content )
{
  if ( content!=null && typeof(content)!="undefined" )
  {
    content.style.display = "block";
    content.style.position = "relative";
    var objWidth = getObjectWidth(content);
    var objHeight = getObjectHeight(content);
    el.appendChild( content );
    content.style.width = objWidth+"px";
    content.style.height = objHeight+"px";
    content.style.left = parseNumber((getObjectWidth( el )/2)-(getObjectWidth(content)/2))+"px";
    content.style.top = parseNumber((getObjectHeight( el )/2)-(getObjectHeight(content)/2))+"px";
    content.zIndex = el.zIndex+1;
  }
}

function getDisplayWidth()
{
  if( window.innerWidth )
  {
    return( window.innerWidth );
  }
  if( document.body && document.body.clientWidth )
  {
    return( document.body.clientWidth );
  }
  return( 0 );
}

function getDisplayHeight()
{
  if( window.innerHeight )
  {
    return( window.innerHeight );
  }
  if( document.body && document.body.clientHeight )
  {
    return( document.body.clientHeight );
  }
  return( 0 );
}

function getDisplayScrollX()
{
  if( window.pageXOffset )
  {
    return window.pageXOffset;
  }
  if( document.body && document.body.scrollLeft )
  {
    return document.body.scrollLeft;
  }
  return 0;
}

function getDisplayScrollY()
{
  if( window.pageYOffset )
  {
    return window.pageYOffset;
  }
  if( document.body && document.body.scrollTop )
  {
    return document.body.scrollTop;
  }
  return( 0 );
}

function getObjectWidth( obj )
{
  if( obj != null )
  {
    if( obj.style && obj.style.pixelWidth )
    {
      return obj.style.pixelWidth;
    }
    if( obj.style && obj.style.width )
    {
      return parseNumber(obj.style.width);
    }
    if( obj.offsetWidth )
    {
      return parseNumber( obj.offsetWidth );
    }
    if( obj.document && obj.document.width )
    {
      return obj.document.width;
    }
    if( obj.clip )
    {
      return obj.clip.right - obj.clip.left;
    }
  }

  return( 0 );
}

function getObjectHeight( obj )
{
  if( obj != null )
  {
    if( obj.style && obj.style.pixelHeight )
    {
      return obj.style.pixelHeight;
    }
    if( obj.style && obj.style.height )
    {
      return parseNumber(obj.style.height);
    }
    if( obj.offsetHeight )
    {
      return parseNumber( obj.offsetHeight );
    }
    if( obj.document && obj.document.height )
    {
      return obj.document.height;
    }
    if( obj.clip )
    {
      return obj.clip.bottom - obj.clip.top;
    }
  }
  return( 0 );
}

function parseNumber( s )
{
  return parseInt( ( '0' + s ), 10 );
}

function viewLocation()
{
  var locId = document.getElementById("cityLocationId").value;
  popLocation(locId);
}
function popLocation(locId)
{
  if ( locId != "" && !isNaN(locId) && (locId*1)>0 )
  {
    doPopup(locId);
  }
}
function showViewLink()
{
  var el = document.getElementById("viewLink");
  var locId = document.getElementById("cityLocationId").value;
  el.style.display = ( locId!="" && !isNaN(locId) && (locId*1)>0 ? "block" : "none" );

  refreshShadow( "entry1" );
}


function popUri( target, srcUri, position, title, postOpen, postClose )
{
  $.get( srcUri, function(data){popTmpl( target, data, position, title, postOpen, postClose, true );} );
  //callRemote( srcUri, function(data){ popTmpl( target, data, position, title, postOpen, postClose, true );} );
}

function popTmpl( target, templateSrcId, position, title, postOpen, postClose, ajax )
{
  closeTmpl( "info" ); // clear any tooltips
  closeTmpl( target ); // clear any panel info in use

  var pnl = getElt( target );
  var tmplFunc = null;
  if( typeof(templateSrcId) == "function" )
  {
    tmplFunc = templateSrcId;
    templateSrcId = "";
  }

  hidelayer(pnl);

  var template = null;
  var parentNodeId = "";

  if( ajax )
  {
    template = document.createElement("div");
    if( target == "info" )
    {
      templateSrcId += "<p><a href=\"#\" onclick=\"return closeTmpl('info')\">close</a></p>";
    }
    template.innerHTML = templateSrcId;
  }
  else if( templateSrcId != "" )
  {
    template = getElt( templateSrcId );
    if( template != null && template.parentNode.id != null && template.parentNode.id != "" )
    {
      parentNodeId = template.parentNode.id;
    }
  }

  if( templateSrcId != "" && template == null )
  {
    if(typeof(console)!="undefined"){console.log("template '"+templateSrcId+"' not found");}
    return;
  }

  if( target.indexOf("info") == -1 )
  {
    if( title != null )
    {
      getElt( target+"Title" ).innerHTML = title;
    }
    if( template != null )
    {
      getElt( target+"Body" ).appendChild(template);
    }
    else if( typeof(tmplFunc) == "function" )
    {
      tmplFunc( target+"Body" );
    }
    if( target.indexOf("hlp") == -1 )
    {
      showModalBlank( pnl, true );
    }
  }
  else
  {
    var shadChild = getElt( target+".shadowed" );
    if( shadChild != null )
    {
      shadChild.appendChild(template);
    }
    else
    {
      pnl.appendChild(template);
    }

    if( getlayerwidth(pnl) > 200 )
    {
      pnl.style.width = "200px";
    }
  }

  if( template != null )
  {
    template.style.display = "block";
  }

  if( position != null )
  {
    var viewBound = new Boundry(getpagescrolly(),getpagescrollx(),getwindowwidth(),getwindowheight());
    movelayer(pnl, 0,0);
    if( typeof(position.width) == "undefined" )
    {
      movelayer(pnl, ((viewBound.dimension.width/2)-(getlayerwidth(pnl)/2)), viewBound.top+100);
    }
    else
    {
      var overflow = viewBound.right - (position.width+getlayerwidth(pnl));
      movelayer(pnl, (overflow<0?position.width+overflow-18:position.width), position.height);
    }
  }

  getElt( target ).style.display="block";

  addShadow(pnl,'shad',20,5,0);

  pnl = getElt( target );
  if( ajax )
  {
    evalJS( templateSrcId );
  }
  else
  {
    pnl.setAttribute("contentId", templateSrcId);
    pnl.setAttribute("parentId", parentNodeId );
  }

  var closer = getElt( target+"Close" );
  if( typeof(closer) != "undefined" )
  {
    addEvent( closer, "click", true, function(){closeTmpl( target, postClose );} );
  }

  showlayer(target);

  if( typeof(postOpen) != "undefined" && postOpen != null )
  {
    postOpen( target+"Body" );
  }
}

function closeTmpl( target, postClose )
{
  var bodyContainer = getElt( target+"Body" );
  if( bodyContainer == null || bodyContainer == "undefined" )
  {
    bodyContainer = getElt( target+".shadowed");
    if( bodyContainer == null )// only if now shadowed version is found...
    {
      bodyContainer = getElt( target );
    }
  }

  if( target == "entry1" && typeof( hideResults ) != "undefined" ) //close ajaxsearch
  {
    hideResults();
  }

  var pnl = getElt( target );
  var revertId = pnl.getAttribute("contentId");
  var parentId = pnl.getAttribute("parentId");
  pnl.removeAttribute("contentId");
  pnl.removeAttribute("parentId");

  if( target == "info" )
  {
    pnl.style.width = "";
  }

  /* move template back out to body */
  var children = bodyContainer.childNodes;
  for( var i = 0; children != null && i < children.length; i++ )
  {
    children[i].style.display = "none";
    if( children[i].id == revertId ) // only put back on the body if it came from there
    {
      if( parentId != "" && parentId != null )
      {
        getElt(parentId).appendChild(children[i]);
      }
      else
      {
        document.getElementsByTagName("body")[0].appendChild(children[i]);
      }
    }
    else
    {
      bodyContainer.removeChild(children[i]);
    }
  }

  if( typeof(postClose) != "undefined" && postClose != null )
  {
    postClose();
  }

  hidelayer(target);
  //getElt( target ).style.display="none";
  hideModalBlank( target );
}


function showModalBlank( behindLayer, obscureBG )
{
  behindLayer = getElt(behindLayer);
  if( behindLayer == null )
  {
    return null;
  }

  var blankLayer = getElt("blank_"+behindLayer.id);
  var zi = behindLayer.style.zIndex;

  behindStyle = getlayerstyle( behindLayer );

  if( zi == "" && typeof(behindStyle) != "undefined" )
  {
    zi = behindStyle.zIndex;
  }


  if( isNaN(parseInt(zi,10)) || zi == 0 )
  {
    zi = 50;
  }

  behindLayer.style.zIndex = parseInt(zi,10)+1;

  if( blankLayer == null )
  {
    blankLayer = document.createElement( "div" );

    blankLayer.setAttribute( "id", "blank_"+behindLayer.id );
    if( obscureBG )
    {
      blankLayer.className = "modalBlank";
    }
    blankLayer.style.zIndex = zi;

    document.body.appendChild( blankLayer );
  }

  movelayer( blankLayer, 0, 0 );
  sizelayer( blankLayer, getpagewidth(), getpageheight() );

  backLayer( blankLayer );
  blankLayer.style.display = "block";

  return blankLayer;
}

function hideModalBlank( behindLayer )
{
  behindLayer = getElt(behindLayer);
  var blankLayer = getElt("blank_"+behindLayer.id);
  if( blankLayer != null )
  {
    blankLayer.style.display = "none";
    unbackLayer( blankLayer );
  }
}

function showUserSearch()
{
  popUri( 'entry1', '/members/tracking.jsp?targetId=locator_list', true, 'Search New Contacts', null );
  return false;
}

function openInvite()
{
  popUri( 'entry1', '/members/invite.jsp', true, 'Invite a Friend', null );
  return false;
}

function editLocation(locationId)
{
  var panelTitle = "Edit Location";
  if( typeof(locationId) == "undefined" )
  {
    locationId = "";
    panelTitle = "Add New Location";
  }
  popUri( 'entry1', '/members/locations/edit.jsp?locationId='+locationId, true, panelTitle, null );
  return false;
}

function deleteLocation(locationName, locationId)
{
  if(
     confirm("Are you sure you want to permanently delete the '" + locationName + "' location?\nAny calendar events that are set against this location will be re-set to an unknow location.")
    )
  {
    if( !testAjax() )
    {
      return true;
    }
    linkLoader(null, "/members/locations/database.jsp?mode=delete&locationId="+locationId, "locator_list", false );
  }
  return false;
}

function addCalendarEvent( trgElt )
{
  popUri( 'entry1', '/members/eventForm.jsp', true, 'New Calendar Event',  function(){addCalendarItem(trgElt);} );
  return false;
}

function openCalendarWidget( formId, formElementStub, ev )
{
  var clicked = ( ( ev.target ) ? ev.target : ev.srcElement );
  popTmpl( 'entry2', function(targetElt){openJSCalendar(targetElt, formId, formElementStub, ev);}, new Dimension(getlayerleft( clicked ) + getlayerwidth( clicked ),getlayertop( clicked ) + getlayerheight( clicked ) ), 'Calendar' );
  return false;
}

function openJSCalendar( targetElt, formId, formElementStub, eventId )
{
  loadJsCalendar_js();
  var target = getElt(targetElt);
  var el = document.createElement("div");
  el.id = target.id + "_js";

  target.appendChild( el );

  var d = new Date();
  var f = document.forms[formId];
  if( f != null )
  {
    d = new Date(f.elements[formElementStub+"Year" ].options[f.elements[formElementStub+"Year" ].selectedIndex].text,
        parseInt(f.elements[formElementStub+"Month"].options[f.elements[formElementStub+"Month"].selectedIndex].value,10)-1,
                 f.elements[formElementStub+"Day"  ].options[f.elements[formElementStub+"Day"  ].selectedIndex].text
                );
  }
  var cal = getJsCalendar( formElementStub, d );
  cal.formId = formId;
  cal.canCloseValue=false;
  cal.create( el,null,clickJSCalendar,null,null,null );
  cal.draw();
  cal.display();
}

function clickJSCalendar( data )
{
  loadCalendar_js();
  var f = getElt(this.formId);
  var selYear = new String((this.selected[0].getYear()<1900)?(this.selected[0].getYear()+1900):(this.selected[0].getYear()));

  f.elements[ this.name + "Day"].selectedIndex   = this.selected[0].getDate()-1;

  f.elements[ this.name + "Month"].selectedIndex = this.selected[0].getMonth();

  for( var i = 0; i < f.elements[ this.name + "Year"].options.length; i++ )
  {
    if( f.elements[ this.name + "Year"].options[i].text == selYear )
    {
      f.elements[ this.name + "Year"].selectedIndex = i;
      break;
    }
  }
  closeTmpl( "entry2" );
  validateDates(f.elements[ this.name + "Day"], this.name);
}

function editCalendarEvent(eventId)
{
  loadCalendar_js();
  if( typeof(calendarItems) == "undefined" || typeof(calendarItems[eventId]) == "undefined" )
  {
    loadItem( eventId, function(){popUri( 'entry1', '/members/eventForm.jsp', true, "Edit Calendar Event", function(){editItem(eventId);} );} );
  }
  else
  {
    popUri( 'entry1', '/members/eventForm.jsp', true, "Edit Calendar Event", function(){editItem(eventId);} );
  }
  return false;
}


function openHelp( forceId, e )
{ /* helpId is a global var set in loaded elements */
  var showId = (typeof(forceId)=="undefined"||forceId==null)?helpId:forceId;
  var pos = (typeof(e)=="undefined")?(null):(new Dimension(mousePageX(e),mousePageY(e)));
  if( typeof(helpText) == "undefined" )
  {
    helpText = [];
  }
  if( helpText[showId] == null )
  {
    $.get( "/ajax/help.jsp", {id:showId}, function(data){loadHelp(data,pos);} );
    //callRemote( "/ajax/help.jsp?id="+showId, function(data){loadHelp(data,pos);} );
    return false;
  }
  if( typeof(e) != "undefined" )
  {
    popTmpl( "info", helpText[showId], pos, null, null, null, true );
  }
  else
  {
    popTmpl( "hlp", helpText[showId], null, null, null, null, true );
  }
  return false;
}

function loadHelp( data, pos )
{
  var parser = new DOMImplementation();

  var results = data.childNodes;

  helpText[ results.item(0).getAttribute("id") ] = results.item(0).textContent;//getItemValue( results.item(0) );

  popTmpl( (pos==null?"hlp":"info"), helpText[results.item(0).getAttribute("id")], pos, null, null, null, true );
}


function injectThrobber(target)
{
  var targ = $( target );
  if( targ.length==0 || targ.children(".throbber").length !=0)
  {
    return;
  }

  if( targ.parent().css("position") == "" || targ.parent().css("position") == "static" )
  {
    targ.parent().css("position","relative");
  }

  targ.append('<div class="throbber" style="top:0px;left:0px;width:' + targ.outerWidth({margin:true}) + 'px;height:' + targ.outerHeight({margin:true}) + 'px"><br/></div>');
  return targ.children(".throbber");
}

function removeThrobber(target)
{
  ($(target).hasClass("throbber") ? $(target) : $(target).find(".throbber")).remove();
}

var Invite =
{
  toggleAll: function(elmnt)
  {
    var throb = injectThrobber(".inviteList");
    window.setTimeout(function(){$(".inviteContacts tr:not(.invDone) :checkbox").each(function(i){this.click()}); removeThrobber(throb); }, 5 );
  },
  highlight: function(elmnt)
  {
    (elmnt.checked) ? $(elmnt).parents("tr").addClass("active") : $(elmnt).parents("tr").removeClass("active");
  },
  sendCheck: function(elmnt)
  {
    if( $(".inviteContacts :checkbox:checked").length == 0 )
    {
      alert("Please select contacts to receive the invitation.");
      return false;
    }
    return true;
  }
}