
var methodurl;
var prePlayedHikeId;
var player = new SWFObject("monoslideshow.swf", "mss", 700, 600, "7", "#FFFFFF");
var months = 0;
var albumIndex = 0;
var top_method;

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) {
    closeMsg();

    var answer = confirm ("Do you want to delete this report?");
    if (answer) {
        location.href='index.php?method=deleteHike&hikeid=' + hikeid + "&access_hash=" + accessHash;
    }

}

function deleteSignup(sectionid, url) {
    var answer = confirm ("Do you want to unregister from this callout?");
    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);

    if (customAdd.style.display == "block")
    {
        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()  {
  var spinner =  document.getElementById("uploadSpinner");
	spinner.style.position = "absolute";

  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;

    var elem = document.getElementById("page");


    spinner.style.top = newTop + "px";
    spinner.style.left = (newLeft - elem.offsetLeft) + "px";
    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);

  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(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()
{
    months--;
    getTopUsers(top_method);
}
function nextDate()
{
    months++;
    getTopUsers(top_method);
}

function getTopUsers(method)  {
    var myDate=new Date()
    myDate.setMonth(myDate.getMonth()+months);

    var todayDate = document.getElementById("today_date");
    date = formatDate(myDate);

    todayDate.innerHTML = date;

    var customAdd = document.getElementById("top_order");
    
    customAdd.className = method;
    

    top_method = method;

    url = "index?hbs&mt=" + top_method + "&month=" + (myDate.getMonth() + 1)
          + "&year=" + myDate.getFullYear();



    jget("TOP_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 date;
}


function jget(sectionid, url) {
  jget(sectionid, url, null, null);
}


function jget(sectionid, url, fbml) {
  jget(sectionid, url, fbml, null);
}

function jget(sectionid, url, fbml, center) {
  jget(sectionid, url, fbml, center);
}
function jget(sectionid, url, fbml, center) {
  //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;


            customAdd.style.display = "block";

            if (center) {
              centerElement(sectionid);
            }
          }

          if (fbml) {
            //alert("fbml");
            FB.XFBML.Host.parseDomTree();
          }

          hideSpinner();
      }
  }


  xmlHttp.open("get",url,true);
  xmlHttp.send(null);
}


function promoteH(hikeid, score) {

    var url ="index.php?promoteHike&hikeid="+hikeid+"&score="+score;

    jget("scoreH"+hikeid, url);

}

function promoteP(hikeid, pid, provider, score) {

    var url ="index.php?promotePicture&pid="+pid+"&provider="+provider+"&score="+score+"&hikeid="+hikeid;

    jget("scoreP"+pid, url);

}



function openFriendInvitation() {
  var url ="inviteFriends.php?if";


  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, sectionid, formSectionid, url) {
  var comment="";
  if(document.all){
       comment = textObj.name + "=" + textObj.innerHTML;
       textObj.innerHTML = "";
  } else{
      comment = textObj.name + "=" + textObj.value;
      textObj.value = "";
  }

  //alert("comment: " + comment + ", " + sectionid);
  url += "&" + encodeURI(comment);


  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(province,region)  {
  window.location="index.php?province="+province+"&region="+region;
}

function changeRegions(province)  {
  //alert("changeREgions: " + province);
  url = "index.php?getRegions&province=" + province;
  jget("regionselect", url,null,null);
}

function changeRegions2(province)  {
  //alert("changeREgions: " + province);
  url = "index.php?getRegions2&province="+province;
  jget("regionselect", url,null,null);
}

function prevPicture()
{
    if (album.images.length <= 1) return;

    albumIndex = albumIndex - 1 >= 0 ? albumIndex - 1 : album.images.length - 1;


    displayPicture();
    updatepicTracker();
    


    updateNextThumbnails();
    updatePreviousThumnails();

}
function nextPicture()
{
    if (album.images.length <= 1) return;

    albumIndex = (albumIndex + 1) % (album.images.length);


    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 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;'>";
    html += "<img src='"+album.images[albumIndex].src+"' />";
    html += "</a>";

   
    mainPicture.innerHTML = html;


    var picturefooter = document.getElementById("picturefooter");


    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';
    }

    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>Hike</b>: ";
    html += "<a href='index.php?viewHike&hikeid="+album.images[albumIndex].hikeid+"'>";
    html += "See report";
    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>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;



  if (album.images[albumIndex].provider == 'B' || album.images[albumIndex].provider == 'K') {
    $url = "index.php?getVotePicInfo&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;
    jget("votepictureinfoarea", $url, "true");
  //picasa picture has title and description so we don't need to make another request to fetch them.
  } else if (album.images[albumIndex].provider == 'P')  {
    $url = "index.php?getPicVoteArea&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;

    jget("picturevotearea", $url, "true");
    var pictureinfoarea = document.getElementById("pictureinfoarea");
    html = "<b>Title</b>: ";
    html += album.images[albumIndex].title + "<br/>";
    html += "<b>Detail</b>: ";
    html += album.images[albumIndex].desc;
    pictureinfoarea.innerHTML = html;

  }
}

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;
}





var fastSearchTimer;
var noresult = null;
function findTrailsWrapperSearch(evt)
{
  var keyCode =
    document.layers ? evt.which :
    document.all ? event.keyCode :
    document.getElementById ? evt.keyCode : 0;


  findTrailsWrapper(evt, "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 findTrailsWrapperCallout(evt)
{
  var keyCode =
    document.layers ? evt.which :
    document.all ? event.keyCode :
    document.getElementById ? evt.keyCode : 0;


  findTrailsWrapper(evt, "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 && selectedTrails)  {

       //roundtrip.value = selectedTrails.trails[select.selectedIndex].roundtrip;
       //elevation.value = selectedTrails.trails[select.selectedIndex].elevation;
       //highpoint.value = selectedTrails.trails[select.selectedIndex].highpoint;
       trailid.value = selectedTrails.trails[select.selectedIndex].trailid;

/*
      if (selectedTrails.trails[select.selectedIndex].last_report_status == 'yes') {
        greenresult.style.display = "inline";
        noresult.style.display = "none";
        redresult.style.display = "none";
      } else if (selectedTrails.trails[select.selectedIndex].last_report_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)
{
  findTrailsWrapper(evt, null, "close");

}

function findTrailsWrapper(evt, handlerFunction, closeFlag)
{

    var keyCode =
      document.layers ? evt.which :
      document.all ? event.keyCode :
      document.getElementById ? evt.keyCode : 0;


   if (keyCode == 40) {
     select = document.getElementById('trailselect');
     select.focus();
     if (select && select.options.length > 0 && select.options[select.selectedIndex])  {
      select.selectedIndex = 1;
     }
     return;
     
   } else if (keyCode == 13)  {
     key = document.getElementById('trailkeyword');
     select = document.getElementById('trailselect');
     if (select && select.options.length > select.selectedIndex && select.options.length > 0)  {
       key.value = select.options[select.selectedIndex].text;
       select.style.display = "none";
     }
     return;
   } else if (keyCode == 8)  {
     key = document.getElementById('trailkeyword');
     if (key.value.length < 1)  {
       key.value = ''
      customAdd = document.getElementById("trailselectarea");
      customAdd.innerHTML = render_empty_dhx_combo();
      return;
     }

   } else if (keyCode == 27)  {
      customAdd = document.getElementById("trailselectarea");
      customAdd.innerHTML = render_empty_dhx_combo();

       return
   } else if (evt.type=='dblclick') {
     return;
   }


    if (fastSearchTimer)
    {
        clearTimeout(fastSearchTimer);
    }

    streetName = document.getElementById('trailkeyword').value;

    if (streetName.length > 0)  {
       //alert("no rsult 1: " + noresult + ", " + streetName);
      if (noresult != null && streetName.indexOf(noresult) == 0)  {
        return;
      }

      caller = "findTrails('trailkeyword','"+handlerFunction +"',"+closeFlag+")";
      //alert("called: " + caller);
      fastSearchTimer = setTimeout(caller, 300);

    }


}

var selectedTrails;

function findTrails(elemid,handlerFunction,closeFlag) {
  //alert("findTrails: " + handlerFunction);
  //alert("findTrailsWrapper");
  var trailname=document.getElementById(elemid).value;
  //alert("find Trail: " + trailname);
  select = document.getElementById('trailselect');
  select.style.display = "block";

  showSpinner();

  province = '';
  if (document.getElementById('province'))  {
    province = document.getElementById('province').value;
  }
  region = '';
  if (document.getElementById('region'))  {
    region = document.getElementById('region').value;
  }
  url = "index.php?findTrails&trailname="+trailname+"&province="+province+"&region="+region+"&sid="+Math.random();
  xmlHttp=ajax2();

  xmlHttp.onreadystatechange= function()
  {
      if (xmlHttp.readyState==4)
      {
          //alert("response: " + xmlHttp.responseText);
          var j =xmlHttp.responseText;
          selectedTrails = eval('(' + j + ')');

          
          html = render_dhx_combo("block", handlerFunction);
            for (i = 0; i < selectedTrails.trails.length; i++)  {
              html += "<option ";

              if (selectedTrails.trails[i].last_report_status == "yes") {
                html += "style='color: #0FB947' ";
              } else if (selectedTrails.trails[i].last_report_status == "no")  {
                html += "style='color: #E20C16' ";
              } else if (selectedTrails.trails[i].last_report_status == "maybe")  {
                html += "style='color: #F4B802' ";
              }

              html += "value='" + selectedTrails.trails[i].trailid + "'";
              if (i == 0) html += " selected";
              html += ">" + selectedTrails.trails[i].trailname + "</option>";
            }

          html += "</select>";
          
          //alert("html: " + html);

          if (selectedTrails.trails.length == 0) {
            noresult = trailname;
          } else  {
            noresult = null;
          }
          //alert("no rsult 2: " + noresult);

          var customAdd = document.getElementById("trailselectarea");
          customAdd.innerHTML = html;

          select = document.getElementById('trailselect');
          if (selectedTrails.trails.length == 0 && closeFlag) {
            select.style.display = "none";
          } else  {
            select.style.display = "inline";
          }

          hideSpinner();
      }
  }


  xmlHttp.open("get",url,true);
  xmlHttp.send(null);


}

function trailselectKeyup(evt, handlerFunction) {
  //alert("trailselectKeyup: " + evt.type + ", " + handlerFunction);
   var keyCode =
      document.layers ? evt.which :
      document.all ? event.keyCode :
      document.getElementById ? evt.keyCode : 0;
    
   select = document.getElementById('trailselect');

   if (keyCode == 38 && select.selectedIndex == 0)
   {
     key = document.getElementById('trailkeyword');
     key.focus();
   } else if (keyCode == 13 || evt.type=='dblclick')  {
     key = document.getElementById('trailkeyword');

     var selIndex = select.selectedIndex;


     key.value = select.options[selIndex].text;
     select.style.display = "none";

     if (handlerFunction)
      handlerFunction(evt);
   } else if (keyCode == 27)  {
      customAdd = document.getElementById("trailselectarea");
      customAdd.innerHTML = render_empty_dhx_combo();
   }
}


function render_dhx_combo(display,handlerFunction)  {
  //alert("render_dhx_combo: " + handlerFunction);
  keyup = "trailselectKeyup(event,"+handlerFunction+");";
  html = "<select id='trailselect' class='dhx_combo_list' style='display:"+display+";width:356px;' size='5' ondblclick='"+keyup+"' onkeyup='"+keyup+"'>";
 return html;
}

function render_empty_dhx_combo() {
  html = render_dhx_combo("none","");
  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 = "Write a message to your friends";
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 (textObj.innerHTML == friendMessage)
       textObj.innerHTML = "";
  } else{
     if (textObj.value == friendMessage)
       textObj.value = "";
  }
}



