
var methodurl;
var prePlayedHikeId;
var player = new SWFObject("monoslideshow.swf", "mss", 700, 600, "7", "#FFFFFF");
var months = 0;
var top_method;
var selectedInput = null;


function statsSelected(selectedValue, elemid)
{
  
  var customAdd = document.getElementById(elemid);

  if (selectedValue == 'yes')  {
    customAdd.style.display = "none";
  } else  {
    customAdd.style.display = "block";
  }
 }

function toggle(elemid)
{

  var customAdd = document.getElementById(elemid);

  if (customAdd.style.display == 'block')  {
    customAdd.style.display = "none";
  } else  {
    customAdd.style.display = "block";
  }
 }


function deleteHike(hikeid, accessHash, referrer) {
    //alert("referrer: " + referrer);
    closeMsg();

    var answer = confirm ("Do you want to delete this report?");
    if (answer) {
        location.href='index.php?deleteReport=1&hikeid=' + hikeid + "&access_hash=" + accessHash + "&referrer=" + referrer;
    }

}

function deleteSignup(sectionid, url) {
    var answer = confirm ("Do you want to unregister from this event?");
    if (answer) {
        window.location = url;
    }
}


function deleteComment(sectionid, url) {
  jdeleteObject(sectionid, url, "comment")
}

function jdeleteObject(sectionid, url, label) {
    var answer = confirm ("Do you want to delete this " + label + "?");

    if (answer) {
        jget(sectionid, url, "true");
    }
}

function deleteObject(url, label) {
    var answer = confirm ("Do you want to delete this " + label + "?");

    if (answer) {
      window.location = url;
    }
}



function getReports(trailKey, trailname, trailid, roundtrip, elevation, album)
{
    //alert("trailKey: " + trailKey + ", " + methodurl);
    closeMsg();
    
    var customAdd = document.getElementById(trailKey);

    var url= "index.php?tr&trailname="+trailname+"&trailid="
          +trailid+"&roundtrip="+roundtrip+"&elevation="+elevation+"&album="+album
          +"&closeFlag=true";



    if (customAdd.style.display == "block" && url == methodurl)
    {
        customAdd.style.display = "none";
        return;
    }

    methodurl = url;


    jget(trailKey, url, "true");

}



function addTrail(url, elemid)
{
    closeMsg();

    var customAdd = document.getElementById(elemid);

    if (customAdd.style.display == "block")
    {
        customAdd.style.display = "none";
        return;
    }

    jget(elemid, url);

}


function changeHike(hikeid, trailname,version,uid,offset,cols)
{
      closeMsg();

    var customAdd = document.getElementById("hike"+hikeid);

    if (customAdd.style.display == "block")
    {
        customAdd.style.display = "none";
        return;
    }



    var url2 = "index.php?changeHike&hikeid="+hikeid+"&trailname="+trailname+"&version="+version+"&uid="+uid+"&offset="+offset+"&cols="+cols;

    jget("hike"+hikeid, url2);

}

function showHikes(fb_uid)  {
      closeMsg();

    var customAdd = document.getElementById("friend"+fb_uid);

    if (customAdd.style.display == "block")
    {
        customAdd.style.display = "none";
        return;
    }

    url = "showHikes.php";

    var url2=url + "?fb_uid="+fb_uid;

    jget("friend"+fb_uid, url2);

}


function updateTrailNoFB(url, trailkey, trailname, trailid, roundtrip, elevation)
{
    closeMsg();

    var customAdd = document.getElementById(trailkey);

    if (customAdd.style.display == "block" && url == methodurl)
    {
        customAdd.style.display = "none";
        return;
    }


    methodurl = url;

    var url2= "index?" + url + "&trailkey="+trailkey+"&trailname="+trailname+"&trailid="+trailid+"&roundtrip="+roundtrip+"&elevation="+elevation;

    jget(trailkey, url2);

}


function closeMsg() {
   var customAdd = document.getElementById("headermsg");

    if (customAdd != null)
    {
        customAdd.style.display = "none";
    }
}

function closeWindow(winid)  {
    //alert("closewindow: " + winid);

    var customAdd = document.getElementById(winid);

    //alert("display: " + customAdd.style.display);

    if (customAdd)
    {
        customAdd.style.display = "none";
    }

}

function ajax2()
{
    var xmlHttp=null;
    try
    {
          // Firefox, Opera 8.0+, Safari
          xmlHttp=new XMLHttpRequest();
    } catch (e)
    {
      // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e)
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    }     
    
    
    return xmlHttp;
}

function showSpinner()  {
  //alert("showapinner");
  var spinner =  document.getElementById("uploadSpinner");
	spinner.style.position = "absolute";
  //alert("showapinner1");

  if (mousePos != null) {

    var newTop = mousePos.y - spinner.clientHeight - 50;
    var newLeft = mousePos.x - ( spinner.clientWidth / 2 );

    if( newTop < 0 )
      newTop = mousePos.y + 20;
    if( newLeft < 0 )
      newLeft = 0;
    //alert("showapinner2");
    var elem = document.getElementById("page");
    //alert("showapinner3");

    spinner.style.top = newTop + "px";
    spinner.style.left = (newLeft - elem.offsetLeft) + "px";
    
    //alert("showapinner4: " + spinner.style.top + ", " + spinner.style.left);
    
    spinner.style.display = "block";
  }
}

function hideSpinner() {
    document.getElementById("uploadSpinner").style.display = "none";
}



function selectPhotoHost(selectedValue, trailid, cols) {
  //selectedValue = document.getElementById("album").value;

  //alert("selectedValue: " + selectedValue);
  
  albumCertify = document.getElementById('album_certify');

  //alert("albumCertify: " + albumCertify.value);
  albumCertify.value = '';



  flickrid = "flickr" + trailid;
  picasaid = "picasa" + trailid;
  pictureid = "albums" + trailid;

  document.getElementById(pictureid).style.display = "none";

  if (selectedValue == "no")  {
    document.getElementById(flickrid).style.display = "none";
    document.getElementById(picasaid).style.display = "none";
  } else if (selectedValue == "flickr") {
    document.getElementById(flickrid).style.display = "block";
    document.getElementById(picasaid).style.display = "none";

  } else if (selectedValue == "picasa") {
    document.getElementById(flickrid).style.display = "none";
    document.getElementById(picasaid).style.display = "block";
  } else if (selectedValue == "facebook")  {
    document.getElementById(flickrid).style.display = "none";
    document.getElementById(picasaid).style.display = "none";
    url = "index.php?getAlbumsFacebook&sid="+Math.random() + "&cols=" + cols;
    jget(pictureid, url);
  } else if (selectedValue == "nochange") {
    document.getElementById(flickrid).style.display = "none";
    document.getElementById(picasaid).style.display = "none";
  }
}

function getAlbums(pictureid, url, flickrDiv) {
   //alert("getFacebookAlbums " + pictureid);

  var customAdd = document.getElementById(pictureid);

  showSpinner();

  xmlHttp=ajax2();

  xmlHttp.onreadystatechange= function()
  {
      if (xmlHttp.readyState==4)
      {
          //alert("response: " + xmlHttp.responseText);
          customAdd.innerHTML=xmlHttp.responseText;
          customAdd.style.display = "block";

          if (flickrDiv)  {
            flickrDiv.style.display = "none";
          }


          hideSpinner();
      }
  }


  xmlHttp.open("get",url,true);
  xmlHttp.send(null);


}



function getFlickrAlbums(screenname, trailid, pictureid, cols) {
   //alert(screenname + ", " + trailid + ", " + pictureid);

  if (screenname)  {
    url = "index.php?getAlbumsFlickr&sid="+Math.random()+"&username="+screenname+"&trailid="+trailid + "&cols=" + cols;

    jget(pictureid, url);
  }
}

function getPicasaAlbums(screenname, trailid, pictureid, cols) {
   //alert("getPicasaAlbums: " + screenname + ", " + trailid + ", " + pictureid);

  if (screenname)  {
    url = "index.php?getAlbumsPicasa=1&sid="+Math.random()+"&username="+screenname+"&trailid="+trailid + "&cols=" + cols;

    jget(pictureid, url);
  }
}


  function openSlideShow(dataFile, hikeid)  {
      //alert("dataFile: " + dataFile + ", " + hikeid);

      centerElement("slideshowwindow");


      player.addVariable("showLogo", "false");
      player.addVariable("dataFile", dataFile + "?hikeid=" + hikeid);
      player.write("slideshow");
  }

  function showPicture(photoid)  {
    //alert("showPicture: " + photoid);
    url = "index.php?showPicture&photoid="+photoid;
    jget("pictureholder", url);
  }



  function centerElement(elemid)  {
    var elem = document.getElementById(elemid);
    elem.style.display = "block";

    //var newTop = mousePos.y - slideshowwindow.clientHeight - 50;
   // if (newTop < 50) newTop = 50;
     windowResize();
     //alert("size: " + winSize.y + ", " + slideshowwindow.clientHeight + ", " + getScrollXY().y);
     //alert("x size: " + winSize.x + ", " + slideshowwindow.clientWidth);



     var newTop = (winSize.y / 2) - elem.clientHeight / 2 + getScrollXY().y;
     var newLeft = (winSize.x / 2) - elem.clientWidth / 2;

     if (newTop < 0)  newTop = 0;

     var pageElem = document.getElementById("page");



      //slideshowwindow.style.position = "absolute";
      elem.style.top = newTop + "px";
      elem.style.left = (newLeft - pageElem.offsetLeft) + "px";
  }


  function openSlideShow2(dataFile, hikeid)  {
    //alert("openSlide: " + dataFile + ", " + hikeid);

    var customAdd = document.getElementById("slideshowwindow");


    showSpinner();
    url = " ";

    xmlHttp=ajax2();


    //var url2=url + "?sid="+Math.random()+"&hikeid="+hikeid;

    var url2 = dataFile + "?hikeid=" + hikeid;

    xmlHttp.onreadystatechange= function()
    {
        if (xmlHttp.readyState==4)
        {
            //alert(xmlHttp.responseText);
            customAdd.innerHTML=xmlHttp.responseText;
            customAdd.style.display = "block";
            customAdd.style.position = "absolute";
            var newTop = mousePos.y - customAdd.clientHeight + 50;
            if (newTop < 50) newTop = 50;
            customAdd.style.top = newTop + "px";

            hideSpinner();
        }

    }


    xmlHttp.open("get",url2,true);
    xmlHttp.send(null);


}

function noEnter(e){
var characterCode
	 if(e && e.which){
	 e = e
	 characterCode = e.which
	 }
	 else{
	 e = event
	 characterCode = e.keyCode
	 }
	 if(characterCode == 13){
 	 return false
	 }
	 else{
	 return true
	 }
}


function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return  {
		x: scrOfX,
		y: scrOfY
	};

}

function openLink(hikeid, trailid, province, region)  {
  //alert("openlink: " + hikeid + ", " + trailid);

  id = "link" + hikeid
  link = getBaseURL() + "/index.php?hikeid="+hikeid+"&trailid="+trailid+
        "&province="+province+"&region="+region+"#t";


  html = '<div style="border:1px solid #B2CBCE;padding: 3px;">';
  html += '<a href="#" style="float: right;padding: 0 3px;" onclick="closeWindow(\''+id+'\'); return false;">';
  html += '<img style="border: none;" src="http://hike101.com/welcome_files/x_to_hide.gif" alt="Close Section" />';
  html += '</a>';

  html += "<div class='add_form' style='padding: 3px;'>";
  html += '<div class="editor_value">';
  html += '<input class="inputtext" value="'+link+'" type="text" size="75" maxlength="75" /> ';
  html += '<span class="dev_explanation">Copy and paste the link into your browser or IM and share it with your friends</span></div>';
  html += '</div>';
  html += '</div>';

  var customAdd = document.getElementById(id);
  customAdd.style.display = "block";

  customAdd.innerHTML=html;
}


function getBaseURL()
{
  documentBasePath = document.location.href;
  if (documentBasePath.indexOf('?') != -1)  {
    documentBasePath = documentBasePath.substring(0, documentBasePath.indexOf('?'));
  }

  documentBasePath = documentBasePath.substring(0, documentBasePath.lastIndexOf('/'));

  return documentBasePath;
}

function prevDate(url)
{
    months--;
    getListByDate(url);
}
function nextDate(url)
{
    months++;
    getListByDate(url);
}

function getListByDate(url)  {
    var myDate=new Date()
    myDate.setMonth(myDate.getMonth()+months);

    var todayDate = document.getElementById("today_date");
    date = formatDate(myDate);

    todayDate.innerHTML = date;


    url += "&month=" + (myDate.getMonth() + 1)
          + "&year=" + myDate.getFullYear();



    jget("TOP_DATE_LIST_SECTION", url, "true");

}

function getTopReports(method)  {

    var customAdd = document.getElementById("top_report_order");

    customAdd.className = method;

    url = "index?getTopReports=1&noheader=1&list=" + method;

    jget("REPORT_LIST_SECTION", url, "true");

}



function formatDate(myDate)
{
   var months = new Array(12);
   months[0]  = "January";
   months[1]  = "February";
   months[2]  = "March";
   months[3]  = "April";
   months[4]  = "May";
   months[5]  = "June";
   months[6]  = "July";
   months[7]  = "August";
   months[8]  = "September";
   months[9]  = "October";
   months[10] = "November";
   months[11] = "December";
  

    var month = months[myDate.getMonth()];
    //var year = myDate.getFullYear();
    //var date = month + " "  + year;
    return month;
}



function jgetScript(url) {
  //alert("jget " + sectionid + ", " + url + ", " + fbml + ", " + center);
  closeMsg();

  showSpinner();

  url += "&sid="+Math.random();
  xmlHttp=ajax2();

  xmlHttp.onreadystatechange= function()
  {
      if (xmlHttp.readyState==4)
      {
          //alert("response: " + xmlHttp.responseText);
          hideSpinner();
          eval(xmlHttp.responseText);
      }
  }


  xmlHttp.open("get",url,true);
  xmlHttp.send(null);
}


function jget(sectionid, url) {
  jget(sectionid, url, null, null, "block");
}


function jget(sectionid, url, fbml) {
  jget(sectionid, url, fbml, null, "block");
}

function jget(sectionid, url, fbml, center) {
  jget(sectionid, url, fbml, center, "block");
}
function jget(sectionid, url, fbml, center, displayMode) {
  //alert("jget " + sectionid + ", " + url + ", " + fbml + ", " + center);
  closeMsg();

  if (sectionid)  {
    var customAdd = document.getElementById(sectionid);
  }

  showSpinner();

  url += "&sid="+Math.random();
  xmlHttp=ajax2();

  xmlHttp.onreadystatechange= function()
  {
      if (xmlHttp.readyState==4)
      {
          //alert("response: " + xmlHttp.responseText);
          if (sectionid)  {
            customAdd.innerHTML=xmlHttp.responseText;

            if (displayMode == "block") {
              customAdd.style.display = "block";
            } else  {
              customAdd.style.display = "inline";
            }



            if (center) {
              centerElement(sectionid);
            }
          }

          if (fbml) {
            //alert("fbml");
            FB.XFBML.Host.parseDomTree();
          }

          hideSpinner();
      }
  }


  xmlHttp.open("get",url,true);
  xmlHttp.send(null);
}


function promoteH(oid, obj, score) {

    var url ="index.php?promoteObj&oid="+oid+"&obj="+obj+"&score="+score;

    jget("scoreH"+obj+oid, url);

}

function promoteP(hikeid, pid, provider, picIndex, score) {


    var url ="index.php?promotePicture&pid="+pid+"&provider="+provider+"&score="+score+"&hikeid="+hikeid;

    scorePicture("scoreP"+pid, url, picIndex, score);

}

function scorePicture(sectionid, url, picIndex, score) {
  closeMsg();


  var customAdd = document.getElementById(sectionid);

  showSpinner();

  url += "&sid="+Math.random();
  xmlHttp=ajax2();

  xmlHttp.onreadystatechange= function()
  {
      if (xmlHttp.readyState==4)
      {
          //alert("response: " + xmlHttp.responseText);
          var j = xmlHttp.responseText;
          if (j != customAdd.innerHTML) {
            customAdd.innerHTML = j;
            album.images[picIndex].score += score;
            //alert("new score: " + album.images[picIndex].score + ", " + score);
          }
          hideSpinner();
      }
  }


  xmlHttp.open("get",url,true);
  xmlHttp.send(null);
}




function openFriendInvitation() {
  var url ="index.php?openFriendSelection=1";


  jget("slideshowwindow", url, "true", "true");
}

function openComment(areaid)  {
  var customAdd = document.getElementById("comment_area"+areaid);

    if (customAdd.style.display == "block")
    {
      customAdd.style.display = "none";
    } else  {
      customAdd.style.display = "block";
    }
}

function jsubmit(formObj, sectionid, url, fbml) {
  var getstr = formGetString(formObj);

  jget(sectionid, url + "&" + getstr, fbml);
}

function comment(textObj, selectId, sectionid, formSectionid, url) {
  //alert("comment");
  var comment="";
  var attachSelect="";
  if(document.all){
       comment = textObj.innerHTML;
       textObj.innerHTML = "";
  } else{
      comment = textObj.value;
      textObj.value = "";
  }

  var selectObj = null;
  if (selectId) selectObj = document.getElementById(selectId);

  //selectObj can be mood or gift
  if (selectObj) {
    //alert("comment" + selectObj.name + "=" + selectObj.options[selectObj.selectedIndex].value);
    attachSelect = "&" + selectObj.name + "=" + selectObj.options[selectObj.selectedIndex].value;
    selectObj.selectedIndex = 0;
    document.getElementById("image" + selectId).innerHTML = "";

  }

  //alert("comment: " + comment + ", " + sectionid + ", " + url);
  url += "&" + textObj.name + "=" + escape(comment) + attachSelect;

  //alert("comment: " + comment + ", " + sectionid + ", " + url);

  closeMsg();



  showSpinner();

  url += "&sid="+Math.random();


  //alert("comment");

  xmlHttp2=ajax2();



  xmlHttp2.onreadystatechange= function()
  {
      if (xmlHttp2.readyState==4)
      {
          //alert("response: " + xmlHttp2.responseText);
          var customAdd2 = document.getElementById(sectionid);

          //this condition needs to be clarified: When formSectionid is null,
          //content will not be reset. Instead the received response will be
          //added. This is required in adding message as we don't want to refresh
          //all the news
          if (formSectionid)  {
            customAdd2.innerHTML = xmlHttp2.responseText;
          } else {
            customAdd2.innerHTML = xmlHttp2.responseText + customAdd2.innerHTML;
           }



          customAdd2.style.display = "block";

          if (formSectionid)  {
            customAdd2 = document.getElementById(formSectionid);
            customAdd2.style.display = "none";
          }

          FB.XFBML.Host.parseDomTree();

          hideSpinner();
      }
  }


  xmlHttp2.open("get",url,true);
  xmlHttp2.send(null);

  
  applyForPermission('email');
}



function formGetString(formObj) {
  //safety measure in case the form is defected so we don't get stuck in this method
  var getstr = "";
  for (i=0; i<formObj.childNodes.length; i++) {
     //alert("tag: " + formObj.childNodes[i].tagName);
     if (formObj.childNodes[i].tagName == "INPUT") {
        if (formObj.childNodes[i].type == "text") {
           getstr += formObj.childNodes[i].name + "=" + formObj.childNodes[i].value + "&";
        } else if (formObj.childNodes[i].type == "checkbox") {
           if (formObj.childNodes[i].checked) {
              getstr += formObj.childNodes[i].name + "=" + formObj.childNodes[i].value + "&";
           } else {
              getstr += formObj.childNodes[i].name + "=&";
           }
        } else if (formObj.childNodes[i].type == "radio") {
           if (formObj.childNodes[i].checked) {
              getstr += formObj.childNodes[i].name + "=" + formObj.childNodes[i].value + "&";
           }
        }
     } else if (formObj.childNodes[i].tagName == "SELECT") {
        var sel = formObj.childNodes[i];
        getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
     } else if (formObj.childNodes[i].tagName == "TEXTAREA") {
        if(document.all){
             getstr += formObj.childNodes[i].name + "=" + formObj.childNodes[i].innerHTML + "&";
             formObj.childNodes[i].innerHTML = "";
        } else{
            getstr += formObj.childNodes[i].name + "=" + formObj.childNodes[i].value + "&";
            formObj.childNodes[i].value = "";
        }
        //alert("getstr: " + getstr);
     }

     if (formObj != null && formObj.firstChild != null && formObj.childNodes[i].childNodes != null && formObj.childNodes[i].childNodes.length > 0)  {
       //alert("children");
       getstr += formGetString(formObj.childNodes[i]);
    }

  }

  return getstr;
}

function changeGeo(url, province,region)  {
  window.location="index.php?" + url + "&province="+province+"&region="+region;
}

function changeRegions(province)  {
  //alert("changeREgions: " + province);
  url = "index.php?getRegions&province=" + province;
  jget("regionselect", url,null,null);
}

function changeRegions2(country, province, type)  {
  //alert("changeREgions: " + province + ", " + country);
  url = "index.php?getTrailRegions="+type+"&trailcountry="+country+"&trailprovince="+province;
  jget("regionselect", url,null,null);
}

function changeProvinces(country, type)  {
  //alert("changeProvinces: " + ", " + type);

  url = "index.php?getTrailProvinces="+type+"&trailcountry="+country;

  var customAdd = document.getElementById("provinceselect");

  showSpinner();

  url += "&sid="+Math.random();
  xmlHttp=ajax2();

  xmlHttp.onreadystatechange= function()
  {
      if (xmlHttp.readyState==4)
      {
          //alert("response: " + xmlHttp.responseText);
          hideSpinner();

          customAdd.innerHTML=xmlHttp.responseText;
          //alert("step 1");
          var trailprov = document.getElementById("trailprovince");
          //alert("step 2: " + trailprov);

          if (trailprov)  {
            changeRegions2(country, trailprov.value, type);
          } else  {
            changeRegions2(country, "", type);
          }

      }
  }


  xmlHttp.open("get",url,true);
  xmlHttp.send(null);




}

function prevPicture()
{
    if (album.images.length <= 1) return;


    if (typeof(prevBaseLink) != "undefined" && prevBaseLink) {
      if (albumIndex == 0)  {
          window.location = prevBaseLink;
          return;
      }
    }

    unhighlightPictureIndex(albumIndex);

    albumIndex = albumIndex - 1 >= 0 ? albumIndex - 1 : album.images.length - 1;


    displayPicture();
    updatepicTracker();
    



    updateNextThumbnails();
    updatePreviousThumnails();

}
function nextPicture()
{
    if (album.images.length <= 1) return;

    if (isDrag) {
      isDrag = false;
      return;
    }

    if (typeof(nextBaseLink) != "undefined" && nextBaseLink) {
      if (albumIndex == album.images.length - 1)  {
          window.location = nextBaseLink;
          return;
      }
    }

    unhighlightPictureIndex(albumIndex);

    //alert("albumIndex1: " + albumIndex);
    albumIndex = (albumIndex + 1) % (album.images.length);
    //alert("albumIndex2: " + albumIndex + ", " + album.images.length);

    displayPicture();

    updatepicTracker();
    updateNextThumbnails();
    updatePreviousThumnails();


}

function gotoPicture(newPicIndex) {
  cancelPhotoLocation();
  unhighlightPictureIndex(albumIndex);
  albumIndex = parseInt(newPicIndex);
  displayPicture();
  updatepicTracker();
  updateNextThumbnails();
  updatePreviousThumnails();
}


function prevThumbnail()
{
    if (album.images.length <= 2) return;

    albumIndex = albumIndex - 1 >= 0 ? albumIndex - 1 : album.images.length - 1;

    updatepicTracker();
    updateNextThumbnails();
    updatePreviousThumnails();

}
function nextThumbnail()
{
    if (album.images.length <= 1) return;

    albumIndex = (albumIndex + 1) % (album.images.length);

    updatepicTracker();
    updateNextThumbnails();
    updatePreviousThumnails();

}


function unhighlightPictureIndex(index)  {
  var picElem = document.getElementById('pic'+index);
  if (picElem)  {
    var picgeotag = document.getElementById("picgeotag");
    if (picgeotag && album.images[index].score > 0)  {
      picElem.style.border = '2px solid  #D9D919';
    } else  {
      picElem.style.border = '2px solid  #ffffff';
    }
    //alert("unhighlightPictureIndex: " + albumIndex);
    
  }
}

function highlightPictureIndex()  {
  var picElem = document.getElementById('pic'+albumIndex);
  if (picElem)  {
    //alert("highlightPictureIndex: " + albumIndex);
    picElem.style.border = '2px solid  #f67766';
  }
}

function unhighlightAll() {
  if (hasAlbum()) {
    for (i = 0; i < album.images.length; i++) {
      unhighlightPictureIndex(i);
    }

  }
}


function displayPicture()  {
    //alert("picture: " + album.images[albumIndex].src);

    var mainPicture = document.getElementById("pictureholder");


    //html = "<a href='"+album.images[albumIndex].link+"'>";
    //html = "<a href='#' onClick='nextPicture();return false;'>";
    if (album.images[albumIndex].width > 0 && album.images[albumIndex].height > 0)  {
      html = "<img style='border:2px solid #ffffff' src='"+album.images[albumIndex].src+"' width='"+album.images[albumIndex].width+"' height='"+album.images[albumIndex].height+"'/>";
    } else  {
      html = "<img style='border:2px solid #ffffff' src='"+album.images[albumIndex].src+"'/>";
    }

    
    //html += "</a>";
    mainPicture.innerHTML = html;

    renderPictureControl();




    if (album.images[albumIndex].provider == "K") {
      provider = 'Flickr';
    } else if (album.images[albumIndex].provider == "P") {
      provider = 'Picasa';
    } else if (album.images[albumIndex].provider == "B")  {
      provider = 'Facebook';
    }

    var picturefooter = document.getElementById("picturefooter");

    html = "<b>Trail</b>: ";
    html += "<a href='index.php?viewTrail=1&trailid="+album.images[albumIndex].trailid+"'>";
    html += album.images[albumIndex].trailname;
    html += "</a><br/>";
    html += "<b>Report</b>: ";
    html += "<a href='index.php?viewHike&hikeid="+album.images[albumIndex].hikeid+"'>";
    html += "Check it out";
    html += "</a><br/>";
    html += "<b>Region</b>: ";
    html += album.images[albumIndex].region + "<br/>";
    html += "<b>Province</b>: ";
    html += album.images[albumIndex].province + "<br/>";
    html += "<b>Country</b>: ";
    html += album.images[albumIndex].country + "<br/>";
    html += "<b>Date</b>: ";
    html += album.images[albumIndex].date + "<br/>";
    html += "<b>Source</b>: ";
    html += "<a href='"+album.images[albumIndex].link+"'>"+provider+"</a>" + "<br/>";


  picturefooter.innerHTML = html;

  var picturecaption = document.getElementById("picturecaption");
  picturecaption.innerHTML = "";

  var picturetitle = document.getElementById("picturetitle");

  if (album.images[albumIndex].cache == 1 || album.images[albumIndex].provider == 'P') {

    if (picturetitle) {
      picturetitle.innerHTML = album.images[albumIndex].title;
    }

    picturecaption.innerHTML = album.images[albumIndex].desc;
  } else if (album.images[albumIndex].provider == 'B' || album.images[albumIndex].provider == 'K') {
    url = "index.php?getPicInfo&pid=" + album.images[albumIndex].id + "&fb_uid=" + album.images[albumIndex].fb_uid + "&hikeid=" + album.images[albumIndex].hikeid
        + "&provider="+album.images[albumIndex].provider + "&user_name=" + album.images[albumIndex].user_name + "&picIndex=" + album.images[albumIndex].picIndex + "&picSize=" + album.images.length;

    renderPictureDetails(url, albumIndex);
  //picasa picture has title and description so we don't need to make another request to fetch them.
  }


  if (typeof(album.images[albumIndex].marker) != "undefined" && album.images[albumIndex].marker) {
    bounce(albumIndex);
  } else  {
    hidePointer();
  }


   updatePicGeoTag();


  if (mapType=="bestphoto" && typeof(nearbyTrails) != "undefined" && nearbyTrails && nearbyTrails.trails.length > 0) {
    if (prePictureTrailId != album.images[albumIndex].trailid)  {
      showTrailLocation(album.images[albumIndex].trailid);
      prePictureTrailId = album.images[albumIndex].trailid;
    }

  }



  highlightPictureIndex();

  //photographer
  if (typeof(topAlbumPage) != "undefined" && topAlbumPage && photoFb_uid != album.images[albumIndex].fb_uid) {
    setTimeout("updatePhotographer();", 1);
  }

}

function updatePhotographer() {
  html = "<a href='index.php?viewUser=1&uid="+album.images[albumIndex].fb_uid+"' style='font-weight:plain;'>";
  html += "<fb:name uid='"+album.images[albumIndex].fb_uid+"' firstnameonly='true' useyou='false' linked='false'/>";
  html += "</a>";

  var photographer = document.getElementById("photographer");
  photographer.innerHTML = html;
  FB.XFBML.Host.parseDomTree();
  photoFb_uid = album.images[albumIndex].fb_uid;

}

function renderPictureControl()  {

  var hikeid = album.images[albumIndex].hikeid;
  var id = album.images[albumIndex].id;
  var score = album.images[albumIndex].score;
  var provider = album.images[albumIndex].provider;
  var picIndex = albumIndex;
  var publishLink = album.images[albumIndex].pubish_link



  html = '<table><tr><td>';

  var picgeotag = document.getElementById("picgeotag");
  if (picgeotag)  {
    html += '<a href="#" onclick="bounce('+albumIndex+'); return false;">';
    html += "<b>Photo:</b></a>";
    html += (picIndex+1) + "/" + album.images.length;
    html += "&nbsp;&nbsp;&nbsp;&nbsp;";
  } else  {
  }




  //html += "&nbsp;&nbsp;&nbsp;";
  
  //html += '<a href="#" onClick="prevPicture();return false;"><b>Previous</b></a>';
  //html += '&nbsp;&nbsp;<a href="#" onClick="nextPicture();return false;"><b>Next</b></a>';



  if (provider == "P" || provider == "K") {
    html += '<span style="font-weight:bold;">';
    html += '<img src="http://static.ak.fbcdn.net/images/icons/favicon.gif" alt="" style="vertical-align:middle;margin-right:2px;margin-bottom:2px;" />';
    if (publishLink)  {
      html += '<a href="#" onclick="jgetScript(\''+publishLink+'\');return false;">Share it</a>';
    } else  {
      html += '<a href="#" onclick="userlogin();return false;">Share it</a>';
    }
    html += "</span>";

  }

  html += "&nbsp;&nbsp;&nbsp;&nbsp;";


  html += '<b>Do you like this photo?&nbsp;</b>';
  html += "</td><td>";

  html += '<div class="voteArea">';
  html += '<div class="promote">';
  html += '<a href="#" onclick="promoteP(\''+hikeid+'\',\''+id+'\',\''+provider+'\','+picIndex+',1); return false;" title="Like this photo">';
  html += '</a>';
  html += '</div>';

  html += '<div class="demote">';
  html += '<a href="#" onclick="promoteP(\''+hikeid+'\',\''+id+'\',\''+provider+'\','+picIndex+',-1); return false;" title="Dislike this photo">';
  html += '</a>';
  html += '</div>';

  html += '<div class="score">';
  scoreid = 'scoreP' +id;
  html += "<span id='"+scoreid+"'>";
  html += score;
  html += '</span>';
  html += '</div>';

  html += '</div>';

  html += '</td></tr>';
  html += "</table>";


  var pictureControl = document.getElementById("pictureControl");
  pictureControl.innerHTML = html;
}

function updatePicGeoTag()  {
    var lat = "Unknown";
    var lng = "Unknown";
    var distance = "Unknown";
    var elevation = "Unknown";

    if (editFlag && editMarker)  {
      lat = editMarker.getLatLng().lat();
      lng = editMarker.getLatLng().lng();
      lat = formatNum(lat,6);
      lng = formatNum(lng,6);
    } else if (album.images[albumIndex].marker) {
      lat = album.images[albumIndex].piclat;
      lng = album.images[albumIndex].piclng;
      lat = formatNum(lat,6);
      lng = formatNum(lng,6);
      if (album.images[albumIndex].gpsType == 0)  {
        distance = album.images[albumIndex].picdist + "Km";
        elevation = album.images[albumIndex].picalt + "m";
      }
    }



    var picgeotag = document.getElementById("picgeotag");
    if (picgeotag)  {
      html = "&nbsp;&nbsp;";
      html += "<b>Distance</b>:";
      html += distance;
      html += "&nbsp;&nbsp;";
      html += "<b>Elevation</b>:";
      html += elevation;
      html += "&nbsp;&nbsp;";
      html += "<b>Lat</b>:";
      html += lat;
      html += "&nbsp;&nbsp;";
      html += "<b>Lng</b>:";
      html += lng;
      picgeotag.innerHTML = html;
    }
}


function formatNum(num, precision) {
    var s = num.toString();
    var n = parseFloat(s);
    return n.toFixed(precision);
}


function updateNextThumbnails()  {

    nextIndex = (albumIndex + 1) % (album.images.length);
    nextnextIndex = (albumIndex + 2) % (album.images.length);

    var nextPicture = document.getElementById("nextPicture");
    html = "<img src='" + album.images[nextIndex].src + "' width='80' height='65' alt='Next Picture' title='Next Picture'/>"
    nextPicture.innerHTML = html;
    

    var nextnextPicture = document.getElementById("nextnextPicture");
    html = "<img src='" + album.images[nextnextIndex].src + "' width='80' height='65' alt='Next Picture'/>"
    nextnextPicture.innerHTML = html;
}

function updatePreviousThumnails()  {
    if (album.images.length <= 2) return;

    prevIndex = albumIndex - 1 >= 0 ? albumIndex - 1 : album.images.length - 1;
    prevprevIndex = prevIndex - 1 >= 0 ? prevIndex - 1 : album.images.length - 1;

    var prevPicture = document.getElementById("prevPicture");
    html = "<img src='" + album.images[prevIndex].src + "' width='80' height='65' alt='Previous Picture' title='Previous Picture'/>"
    prevPicture.innerHTML = html;

    var prevprevPicture = document.getElementById("prevprevPicture");
    html = "<img src='" + album.images[prevprevIndex].src + "' width='80' height='65' alt='Previous Picture'/>"
    prevprevPicture.innerHTML = html;

}

function updatepicTracker() {
    var pictracker = document.getElementById("pictracker");
    pictracker.innerHTML = (albumIndex + 1) + "/" + album.images.length;
}

function renderPictureDetails(url, picIndex) {

  //alert("renderPictureDetails: " + picIndex + ", " + album.images[picIndex].cache);
  showSpinner();
  xmlHttp=ajax2();

  xmlHttp.onreadystatechange= function()
  {
      if (xmlHttp.readyState==4)
      {
          hideSpinner();
          //alert("response: " + xmlHttp.responseText);
          var j =xmlHttp.responseText;
          pictureDetails = eval('(' + j + ')');

          var picturecaption = document.getElementById("picturecaption");
          picturecaption.innerHTML = pictureDetails.desc;

          if (picIndex == albumIndex) {
            album.images[picIndex].desc = pictureDetails.desc;
            album.images[picIndex].cache = 1;
          }
          //alert("renderPictureDetails: " + album.images[picIndex].cache);
      }
  }

  xmlHttp.open("get",url,true);
  xmlHttp.send(null);

}






var fastSearchTimer;
var noresult = null;
var existingElem = null
function findTrailsWrapperSearch(evt)
{
  var keyCode =
    document.layers ? evt.which :
    document.all ? event.keyCode :
    document.getElementById ? evt.keyCode : 0;

  elemkeywordValue = document.getElementById("trailkeyword").value;  
  url = "index.php?findTrails=1&trailname="+elemkeywordValue;

  findTrailsWrapper(evt, "trail", url, "findTrailsWrapperSearch", null);

  if (keyCode == 13 || evt.type=='dblclick')  {
     select = document.getElementById('trailselect');
     if (select)  {
       trailid = select.options[select.selectedIndex].value;
       window.location="index.php?viewTrail=1&trailid=" + trailid;
    }
  }

}



function findTrailsWrapperAddNewReport(evt)
{
  var keyCode =
    document.layers ? evt.which :
    document.all ? event.keyCode :
    document.getElementById ? evt.keyCode : 0;

  elemkeywordValue = document.getElementById("trailkeyword").value;
  url = "index.php?findTrails=1&trailname="+elemkeywordValue;

  findTrailsWrapper(evt, "trail", url, "findTrailsWrapperAddNewReport", null);

  if (keyCode == 13 || evt.type=='dblclick')  {
     select = document.getElementById('trailselect');
     //select.style.display = "none";

     roundtrip = document.getElementById('default_roundtrip');
     elevation = document.getElementById('default_elevation');
     trailid = document.getElementById('trailid');


     if (select && select.options.length > 0 && selectedResults)  {

       roundtrip.innerHTML = selectedResults.objects[select.selectedIndex].roundtrip;
       elevation.innerHTML = selectedResults.objects[select.selectedIndex].elevation;
       trailid.value = selectedResults.objects[select.selectedIndex].id;
       //alert("trailid: " + selectedResults.objects[select.selectedIndex].trailid);

    } else  {
       roundtrip.innerHTML = "";
       elevation.innerHTML = "";
       trailid.value = "";
       select.style.display = "none";

    }
  }

}



function findTrailsWrapperCallout(evt)
{
  var keyCode =
    document.layers ? evt.which :
    document.all ? event.keyCode :
    document.getElementById ? evt.keyCode : 0;

  elemkeywordValue = document.getElementById("trailkeyword").value;
  url = "index.php?findTrails=1&trailname="+elemkeywordValue;

  findTrailsWrapper(evt, "trail", url, "findTrailsWrapperCallout", null);

  if (keyCode == 13 || evt.type=='dblclick')  {
     select = document.getElementById('trailselect');
     //select.style.display = "none";
     
     //roundtrip = document.getElementById('roundtrip');
     //elevation = document.getElementById('elevation');
     //highpoint = document.getElementById('highpoint');
     trailid = document.getElementById('trailid');
     //greenresult = document.getElementById('greenresult');
     //redresult = document.getElementById('redresult');
     //noresult = document.getElementById('noresult');


     if (select && select.options.length > 0 && selectedResults)  {

       //roundtrip.value = selectedResults.objects[select.selectedIndex].roundtrip;
       //elevation.value = selectedResults.objects[select.selectedIndex].elevation;
       //highpoint.value = selectedResults.objects[select.selectedIndex].highpoint;
       trailid.value = selectedResults.objects[select.selectedIndex].id;

/*
      if (selectedResults.objects[select.selectedIndex].status == 'yes') {
        greenresult.style.display = "inline";
        noresult.style.display = "none";
        redresult.style.display = "none";
      } else if (selectedResults.objects[select.selectedIndex].status == 'no')   {
        greenresult.style.display = "none";
        noresult.style.display = "none";
        redresult.style.display = "inline";
      } else  {
        greenresult.style.display = "none";
        noresult.style.display = "inline";
        redresult.style.display = "none";
      }
*/
    } else  {
       //roundtrip.value = "";
       //elevation.value = "";
       //highpoint.value = "";
       trailid.value = "";
       //greenresult.style.display = "none";
       //noresult.style.display = "inline";
       //redresult.style.display = "none";
       select.style.display = "none";

    }
  }

}


function findTrailsWrapperAdd(evt)
{
  elemkeywordValue = document.getElementById("trailkeyword").value;
  url = "index.php?findTrails=1&trailname="+elemkeywordValue;
  findTrailsWrapper(evt, "trail", url, null, "close");

}

function findTrailsWrapper(evt, elemName, url, handlerFunction, closeFlag)
{
    elemSelect = elemName + "select";
    elemkeyword = elemName + "keyword";
    elemSelectArea = elemName + "selectarea";

    var keyCode =
      document.layers ? evt.which :
      document.all ? event.keyCode :
      document.getElementById ? evt.keyCode : 0;


   if (keyCode == 40) {
     select = document.getElementById(elemSelect);
     select.focus();
     if (select && select.options.length > 0 && select.options[select.selectedIndex])  {
      select.selectedIndex = 1;
     }
     return;
     
   } else if (keyCode == 13)  {
     key = document.getElementById(elemkeyword);
     select = document.getElementById(elemSelect);
     if (select && select.options.length > select.selectedIndex && select.options.length > 0)  {
       name = select.options[select.selectedIndex].text;

       if (name.indexOf('[') > 0) {
        name = name.substring(0, name.indexOf('[') - 1);
        existingElem = true;
       } else {
         existingElem = false;
       }

       key.value = name;

       select.style.display = "none";
     }
     return;
   } else if (keyCode == 8)  {
     key = document.getElementById(elemkeyword);
     if (key.value.length < 1)  {
       key.value = ''
      customAdd = document.getElementById(elemSelectArea);
      customAdd.innerHTML = render_empty_dhx_combo(elemName);
      return;
     }

   } else if (keyCode == 27)  {
      customAdd = document.getElementById(elemSelectArea);
      customAdd.innerHTML = render_empty_dhx_combo(elemName);

       return
   } else if (evt.type=='dblclick') {
     return;
   }


    if (fastSearchTimer)
    {
        clearTimeout(fastSearchTimer);
    }

    elemkeywordValue = document.getElementById(elemkeyword).value;

    if (elemkeywordValue.length > 0)  {
       //alert("no rsult 1: " + noresult + ", " + elemkeywordValue);
      if (noresult != null && elemkeywordValue.indexOf(noresult) == 0)  {
        return;
      }


      caller = "findResults('"+elemName+"','"+url+"','"+handlerFunction +"',"+closeFlag+")";
      //alert("called: " + caller);
      fastSearchTimer = setTimeout(caller, 300);

    }


}

var selectedResults;

function findResults(elemName,url, handlerFunction,closeFlag) {

  elemSelect = elemName + "select";
  elemkeyword = elemName + "keyword";
  elemSelectArea = elemName + "selectarea";

  //alert("findResults: " + handlerFunction);

  var elemkeywordValue =document.getElementById(elemkeyword).value;
  //alert("find Trail: " + trailname);
  select = document.getElementById(elemSelect);
  select.style.display = "block";

  showSpinner();

  country = '';
  if (document.getElementById('trailcountry'))  {
    country = document.getElementById('trailcountry').value;
  }
  province = '';
  if (document.getElementById('trailprovince'))  {
    province = document.getElementById('trailprovince').value;
  }
  region = '';
  if (document.getElementById('trailregion'))  {
    region = document.getElementById('trailregion').value;
  }
  
  if (country == "")  {
    province = "";
  }
  if (province == "") {
    region = "";
  }


  url = url+"&trailcountry="+country+"&trailprovince="+province+"&trailregion="+region+"&sid="+Math.random();
  //alert("findtrails: " + url);
  xmlHttp=ajax2();

  xmlHttp.onreadystatechange= function()
  {
      if (xmlHttp.readyState==4)
      {
          //alert("response: " + xmlHttp.responseText);
          var j =xmlHttp.responseText;

          if (j) {
            selectedResults = eval('(' + j + ')');
          } else  {
            selectedResults = null;
          }

         //alert("selectedResults: " + selectedResults);

          
          html = render_dhx_combo("block", elemName, handlerFunction);
            for (i = 0; selectedResults && i < selectedResults.objects.length; i++)  {
              html += "<option ";

              if (selectedResults.objects[i].status == "yes") {
                html += "style='color: #0FB947' ";
              } else if (selectedResults.objects[i].status == "no")  {
                html += "style='color: #E20C16' ";
              } else if (selectedResults.objects[i].status == "maybe")  {
                html += "style='color: #F4B802' ";
              }

              html += "value='" + selectedResults.objects[i].id + "'";
              if (i == 0) html += " selected";
              html += ">" + selectedResults.objects[i].name + " [" + selectedResults.objects[i].hiked + "]</option>";
            }

          html += "</select>";
          
          //alert("html: " + html);

          if (!selectedResults || selectedResults.objects.length == 0) {
            noresult = elemkeywordValue;
          } else  {
            noresult = null;
          }
          //alert("no rsult 2: " + noresult);

          var customAdd = document.getElementById(elemSelectArea);
          customAdd.innerHTML = html;

          select = document.getElementById(elemSelect);
          if ((!selectedResults || selectedResults.objects.length == 0) && closeFlag) {
            select.style.display = "none";
          } else  {
            select.style.display = "inline";
          }

          hideSpinner();
      } 
  }


  xmlHttp.open("get",url,true);
  xmlHttp.send(null);


}

function selectKeyup(evt, elemName, handlerFunction) {
  //alert("selectKeyup: " + evt.type + ", " + handlerFunction);
  elemSelect = elemName + "select";
  elemkeyword = elemName + "keyword";
  elemSelectArea = elemName + "selectarea";


   var keyCode =
      document.layers ? evt.which :
      document.all ? event.keyCode :
      document.getElementById ? evt.keyCode : 0;
    
   select = document.getElementById(elemSelect);

   if (keyCode == 38 && select.selectedIndex == 0)
   {
     key = document.getElementById(elemkeyword);
     key.focus();
   } else if (keyCode == 13 || evt.type=='dblclick')  {
     key = document.getElementById(elemkeyword);

     var selIndex = select.selectedIndex;

     name = select.options[selIndex].text;
     //alert("name: " + name);
     if (name.indexOf('[') > 0) {
      name = name.substring(0, name.indexOf('[') - 1);
      //alert("name without []" + name);
     }


     key.value = name;
     select.style.display = "none";

     if (handlerFunction)
      handlerFunction(evt);
   } else if (keyCode == 27)  {
      customAdd = document.getElementById(elemSelectArea);
      customAdd.innerHTML = render_empty_dhx_combo(elemName);
   }
}


function blurTrailSearch(ev)  {

  key = document.getElementById('trailkeyword');

  if (key.value == '')  {
    key.value = "Find Trail";
   // key.style.color = "#000000";
  }


}

function focusTrailSearch(ev)  {
    key = document.getElementById('trailkeyword');

  if (key.value == 'Find Trail')  {
    key.value = "";
    //key.style.color = "black";
  }
}




function render_dhx_combo(display, elemName, handlerFunction)  {
  //alert("render_dhx_combo: " + elemName + ", " + handlerFunction);
  keyup = "selectKeyup(event,\""+elemName+"\","+handlerFunction+");";
  html = "<select id='"+elemName+"select' class='dhx_combo_list' style='display:"+display+";width:306px;' size='7' ondblclick='"+keyup+"' onkeyup='"+keyup+"'>";
 return html;
}

function render_empty_dhx_combo(elemName) {
  html = render_dhx_combo("none", elemName, "");
  html += "<option value''></option>";
  html += "</select>";
  return html;
}






/*
 * Prompts the user to grant a permission to the application.
 */
function facebook_prompt_permission(permission, acknowledgeDialog, callbackFunc) {
    //alert("facebook_prompt_permission");
  //FB.ensureInit(function() {
    //check is user already granted for this permission or not

    FB.Facebook.apiClient.users_hasAppPermission(permission,
     function(result) {
        // prompt offline permission
        if (result == 0) {
          //alert("facebook_prompt_permission 2");
          showEmailPermissionDialog(permission, callbackFunc);
  
        } else {
            // permission already granted.
          if (acknowledgeDialog)  {
            alert(permission + " permission has been granted before");
          }

          callbackFunc(true);
            //alert("was granted");
        }
    });

  //});
}

function applyForPermission(permission) {
    //alert("applyForPermission");

    // this checks current status of permission and if not granted it will display an ajax box for user to give permission.
    facebook_prompt_permission(permission, false, function(accepted) {
      if(accepted) {
        //alert("permission has been granted before");

        var url ="index.php?updateEmailPermission=1&permission=1";
        showEmailDialog = 1;
        jget(null, url);

      } else  {
        url ="index.php?updateEmailPermission=1&permission=0";
        showEmailDialog = 0;
        jget(null, url);
      }

    });
}

function applyAndAcknowledgeForPermission(permission) {
    //alert("applyForPermission");
    // this checks current status of permission and if not granted it will display an ajax box for user to give permission.
    facebook_prompt_permission(permission, true, function(accepted) {
      if(accepted) {


        var url ="index.php?updateEmailPermission=1&permission=1";
        jget(null, url);




      } else  {
        url ="index.php?updateEmailPermission=1&permission=0";
        jget(null, url);
      }

    });
}



function showEmailPermissionDialog(permission, callbackFunc)  {
  //alert("showEmailPermissionDialog");

  if (showEmailDialog == "1" || showEmailDialog == 1) {
    showFBPermission(permission, callbackFunc);
  }
}

function showFBPermission(permission, callbackFunc) {
    FB.ensureInit ( function () {
      FB.Connect.showPermissionDialog(permission, callbackFunc);
    });
}

var friendMessage = "";
var firstFriendMessage = true;
function messageBlurHandler() {
  textObj = document.getElementById("friendMessageText");

  if(document.all){
    if (textObj.innerHTML == "")  {
      textObj.innerHTML = friendMessage;
      //textObj.className = "messagetextblur";
    }

  } else{
    if (textObj.value == "")  {
      textObj.value = friendMessage;
      //textObj.className = "messagetextblur";
    }
  }
}

function messageFocusHandler()  {

  textObj = document.getElementById("friendMessageText");

  //textObj.className = "messagetextfocus";

  if(document.all){
     if (firstFriendMessage || textObj.innerHTML == friendMessage)
       if (firstFriendMessage)  {
         firstFriendMessage = false;
         friendMessage = textObj.innerHTML;
       }
       textObj.innerHTML = "";
  } else{
     if (firstFriendMessage || textObj.value == friendMessage)
       if (firstFriendMessage)  {
         firstFriendMessage = false;
         friendMessage = textObj.value;
       }
       textObj.value = "";
  }
}

function checkRows(textArea, minRowCount){
  //alert("checkRows: " + textArea);
  while (
    textArea.rows > minRowCount &&
    textArea.scrollHeight < textArea.offsetHeight
  ){
    textArea.rows--;
  }

  while (textArea.scrollHeight > textArea.offsetHeight)
  {
  textArea.rows++;
  }
}


function selectNewFile(selectedValue) {
  //alert('select 1');
  var gpsfilechange = document.getElementById('gpsfilechange');
  //alert('select 2');

  if (selectedValue == 'no')  {
    gpsfilechange.style.display = 'none';
  } else if (selectedValue == 'yes')  {
    gpsfilechange.style.display = 'block';
  } else if (selectedValue == 'delete') {
    var answer = confirm ('Are you sure of selecting the delete option?');
    if (!answer) {
      document.getElementById('fileChange').value = 'no';
    }

  }
}

function addFeedback(textObj, url) {
  //alert("addFeedback " + url);
  showSpinner();

  var comment="";
  if(document.all){
    comment = textObj.name + "=" + textObj.innerHTML;
  } else{
    comment = textObj.name + "=" + textObj.value;
  }

  url += "&" + encodeURI(comment);


  url += "&sid="+Math.random();

  //alert("url: " + url);

  xmlHttp2=ajax2();
  xmlHttp2.onreadystatechange= function()
  {
      if (xmlHttp2.readyState==4)
      {
          //alert("response: " + xmlHttp2.responseText);
          var feedback_action = document.getElementById('send_feedback_action');
          var feedback_thankyou = document.getElementById('send_thank_you_feedback');

          feedback_action.style.display = "none";
          feedback_thankyou.style.display = "block";

          if(document.all){
            textObj.innerHTML = "";
          } else{
            textObj.value = "";
          }


          FB.XFBML.Host.parseDomTree();

          hideSpinner();
      }
  }


  xmlHttp2.open("get",url,true);
  xmlHttp2.send(null);
}

function freshImagePeriodically() {
  //alert("charged");
  setTimeout('jtimeget("home_image", "index.php?refreshHomePageImage=1")', 20000);
}


function jtimeget(sectionid, url) {


  var customAdd = document.getElementById(sectionid);

  url += "&sid="+Math.random();
  xmlHttp=ajax2();

  xmlHttp.onreadystatechange= function()
  {
      if (xmlHttp.readyState==4)
      {
          //alert("response: " + xmlHttp.responseText);
          customAdd.innerHTML=xmlHttp.responseText;
          freshImagePeriodically();
      }
  }


  xmlHttp.open("get",url,true);
  xmlHttp.send(null);
}

function jgetTextField(textObj, sectionid, url) {
  //alert("addFeedback " + url);
  showSpinner();

  var textQuery="";
  if(document.all){
    textQuery = textObj.name + "=" + textObj.innerHTML;
  } else{
    textQuery = textObj.name + "=" + textObj.value;
  }

  url += "&" + encodeURI(textQuery);


  url += "&sid="+Math.random();

  //alert("url: " + url);

  jget(sectionid, url);
}

function swipe(first, second) {
  //alert("swipe");
  var i = 0;
  var lastSelected = -1;
  while(i < first.options.length) {
    if (first.options[i].selected) {
      var newOpt = new Option(first.options[i].text, first.options[i].text);//first.options[i].value, first.options[i].value);
      second.options[second.options.length] = newOpt;
      //second.options.add(newOpt, second.options.length);
      second.selectedIndex = second.options.length - 1;
      first.options[i] = null;
      lastSelected = i;
    } else  {
      i++;
    }
  }
  //alert("lastSelected: " + lastSelected);
  if (lastSelected >= first.options.length)
    lastSelected = first.options.length - 1;


  if (lastSelected >= 0) {
    //alert("selected: " + lastSelected);
    first.selectedIndex = lastSelected;
  }


}

function postReport(trailid)
{
  window.location = "index.php?addReport=1&trailid="+trailid;
}

function hasAlbum() {
  //alert("hasAlbum2");
  var hasAlbum = (typeof(album)!= "undefined" && album && album.images && album.images.length > 0);


  return hasAlbum;
}

function saveTagForm() {
  var select = document.getElementById('selectedTags');

  var tagList = "";
  if (select) {
    for (var i = 0; i < select.options.length; i++) {
      if (select.options[i].text > "") {
        tagList += select.options[i].text + ",";
      }
    }


    tag_list = document.getElementById('tag_list');
    tag_list.value = tagList;
  }

  var editForm = document.getElementById('editform');
  editForm.submit();
}

var loginAttempts = 0;
function userlogin()  {

  //alert("userlogin: " + loginAttempts);
  loginAttempts ++;

  if (loginAttempts > 1)  {
    loginAttempts = 0;
    refreshPage();
    return;
  }

  FB.Connect.requireSession(function() {
    refreshPage();
  });
}

function refreshPage()  {
    var loc = window.location;
    window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
}
function userlogout() {
  FB.Connect.logoutAndRedirect('http://www.livetrails.com');
}

function showNavigationButtons()  {
document.getElementById('previousContainer').className='previousContainerHover';
document.getElementById('nextContainer').className='nextContainerHover';
}

function findOrganization(evt,rnum)
{
  var keyCode =
    document.layers ? evt.which :
    document.all ? event.keyCode :
    document.getElementById ? evt.keyCode : 0;

  elemkeywordValue = document.getElementById("organization"+rnum+"keyword").value;
  url = "index.php?findOrganizations=1&name="+elemkeywordValue;
  findTrailsWrapper(evt, "organization"+rnum, url, "findOrganization", "close");

  if (keyCode == 13 || evt.type=='dblclick')  {
     select = document.getElementById('organization'+rnum+'type');
     if (select)  {
       if (existingElem == true)  {
        select.style.display = "none";
       } else {
         select.style.display = "block";
       }
    }
  }

}

function addOrganizationMember(rid, context) {
  alert("rid: " + rid);

 FB.ensureInit(function() {
        var dialog = new FB.UI.FBMLPopupDialog('XXXXXXX', '');

        fbml = "<form action='index.php?test=1' method='get'>"
        fbml += "<select name='test' size='1'>";
        fbml += "<option value='3'>test</option>";
        fbml += "</select>";
        fbml += "<input class='inputsubmit' type='button' value='Save' onClick='submit();' />";
        fbml += "</form>";
        dialog.setFBMLContent(fbml);
        dialog.setContentWidth(200);
        dialog.setContentHeight(200);
        dialog.show();
    });


}

