function remove_xy(btn_id)
{
   document.getElementById(btn_id).disabled = true;
}

function hide(element_id)
{
   target = document.getElementById(element_id);
   target.style.visibility = "hidden";
}

function show(element_id)
{
   target = document.getElementById(element_id);
   target.style.visibility = "visible";
}

function toggle(element_id)
{
   target = document.getElementById(element_id);
   if(target.style.visibility == "hidden")
   {
      target.style.visibility = "visible";
   } 
   else 
   {
      target.style.visibility = "hidden";
   }
}

function toggleDisplay(element_id)
{
   target = document.getElementById(element_id);
   if(target.style.display == "none")
   {
      target.style.display = "";
   }
   else 
   {
      target.style.display = "none";
   }
}

function toggleCategoryBranch(needle, img_id_name)
{
   var all = document.getElementsByTagName('dl');
   for(var i = 0; i < all.length; i++)
   {
      var idname = all[i].id;
      if(idname.match(needle) != null)
      {
         toggleDisplay(idname);
      }
   }
   
   var uri = "http://www.poifriend.com/img/cat_list_menu/";
   
   if(document.getElementById(img_id_name).src == uri + "plus_sign.gif")
   {
      document.getElementById(img_id_name).src = uri + "minus_sign.gif";
   }
   else if(document.getElementById(img_id_name).src == uri + "minus_sign.gif")
   {
      document.getElementById(img_id_name).src = uri + "plus_sign.gif";
   }
}

function toggleMultiCategoryBranches(parents_list)
{
   parents_list_arr = parents_list.split('|');
   for(i = 0; i < parents_list_arr.length; i++)
   {
      toggleCategoryBranch('cat' + parents_list_arr[i] + 'child', 'cat' + parents_list_arr[i] + 'img');
   }  
}

function toggleMsgBox(element_id, img_id_name)
{
   if(document.getElementById(element_id) != null)
   {
      $("#" + element_id).toggle("fast");
   }
   
   var uri = "/img/forum/";
   var plus_img = new Image();
   plus_img.src = uri + "plus_sign.gif";
   var minus_img = new Image();
   minus_img.src = uri + "minus_sign.gif";

   if(document.getElementById(img_id_name).src == plus_img.src)
   {
      document.getElementById(img_id_name).src = minus_img.src;
      document.getElementById('msg_box_text').innerHTML = 'Close message box';
   }
   else if(document.getElementById(img_id_name).src == minus_img.src)
   {
      document.getElementById(img_id_name).src = plus_img.src;
      document.getElementById('msg_box_text').innerHTML = 'Post your topic';
   }
}

function shiftOpacity(id, millisec)
{
   target1 = document.getElementById(id);
   if(target1.style.opacity == 0)
   {
      opacity(id, 0, 100, millisec);
   }
   else
   {
      opacity(id, 100, 0, millisec);
   }
   if(target1.style.opacity == 0)
   {
      target1.style.zIndex = 10;
   }
   else
   {
      target1.style.zIndex = -10;  
   }
}

function opacity(id, opacStart, opacEnd, millisec)
{
   var speed = Math.round(millisec / 100);
   var timer = 0;

   if(opacStart > opacEnd)
   {
      for(i = opacStart; i >= opacEnd; i--)
      {
         setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
         timer++;
      }
   }
   else if(opacStart < opacEnd)
   {
      for(i = opacStart; i <= opacEnd; i++)
      {
         setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
         timer++;
      }
   }
} 

function changeOpac(opacity, id)
{
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}


function showAddr(element_id)
{
   target = document.getElementById(element_id);
   if(target.style.display == "none")
   {
      target.style.display = "";
   } 
}

function popGetCoordinates(form_name, field_name, lat, lng, zoom_level)
{
   if(form_name.length == 0)
   {
      popWin = window.open('/scripts/get_coordinates.php', 'popGetCoordinates', 'width=360, height=360');
   }
   else
   {
      popWin = window.open('/scripts/get_coordinates.php?form_name='+form_name+'&field_name='+field_name+'&lat='+lat+'&lng='+lng+'&zoom_level='+zoom_level, 'popGetCoordinates', 'width=360, height=360');  
   }
   popWin.focus();
}

function confirmDelete()
{
   var agree = confirm("Are you sure you want to delete this?");
   if(agree)
      return true;
   else
      return false;
}

function toggleGMap(obj, elementId, adjustTop, adjustLeft, target_field_id_name)
{
   arr = getPosition(obj);

   hide(elementId);
   show(elementId);
	
	document.gmap_coordinates.target_field_id.value = target_field_id_name;
	document.getElementById(elementId).style.top = (arr[0] + adjustTop) + "px";
	document.getElementById(elementId).style.left = (arr[1] + adjustLeft) + "px";
}

function showRepos(obj, elementId, adjustTop, adjustLeft)
{
   arr = getPosition(obj);

   hide(elementId);
   show(elementId);

   setPosition(elementId, arr[0] + adjustTop, arr[1] + adjustLeft);
}

function getPosition(obj)
{
   var curleft = curtop = 0;
   if (obj.offsetParent) 
	{
	   curtop = obj.offsetTop
      curleft = obj.offsetLeft
      while(obj = obj.offsetParent)
      {
         curtop += obj.offsetTop
         curleft += obj.offsetLeft
      }
   }
   return [curtop,curleft];
}

function setPosition(element_id, t, l)
{
   var x = document.getElementById(element_id);
   x.style.top = t + 'px';
   x.style.left = l + 'px';
}

function getAddressFields(pref, i)
{
   str = document.getElementById('poi_address'+pref+i).value + ' ' + document.getElementById('poi_city'+pref+i).value + ' ' + document.getElementById('poi_provstate'+pref+i).value + ' ' + document.getElementById('poi_postal'+pref+i).value;
   return str;  
}

function flip(imgPath, imgName)
{
   if(document.images)
      document.images[imgName].src = imgPath;
}

function confirmDel()
{
   return confirm("Are you sure you want to delete this?");
}

function isNumeric(sText)
{
   var ValidChars = "0123456789.-";
   var IsNumber=true;
   var Char;
 
   for(i = 0; i < sText.length && IsNumber == true; i++) 
   { 
      Char = sText.charAt(i); 
      if(ValidChars.indexOf(Char) == -1) 
      {
         IsNumber = false;
      }
   }
   return IsNumber;
}

function showCoordinates(coordinates, target_field_id, custom_icon)
{
   lat = 0;
   lng = 0;
   zoom = 0;
   
   if(coordinates.length > 0 && coordinates.indexOf(",") > 0)
   {
      arr = coordinates.split(",");
      lat = trim(arr[0]);
      lng = trim(arr[1]);
      zoom = 15;
   }
   
   if(!isNumeric(lat) || !isNumeric(lng) || Math.abs(lat) > 90 || Math.abs(lng) > 180)
   {
      alert('Coordinates are wrong!');
   }
   else
   {
      map.clearOverlays();
      
      map.setCenter(new GLatLng(lat, lng), zoom);
      var point = new GLatLng(lat, lng);
      if(custom_icon.length > 0)
      {
         var icon = get_gmap_icon(custom_icon);
      }
      else
      {
         var icon = get_gmap_icon();
      }
      if(target_field_id.length > 0)
      {
         var marker = new GMarker(point, { icon: icon, draggable: true});
         
         GEvent.addListener(marker, "dragstart", 
            function()
            {
               map.closeInfoWindow();
            }
         );
   		
         GEvent.addListener(marker, "dragend", 
            function()
            {
               var lat = Math.round((marker.getPoint().lat())*1000000)/1000000
               var lng = Math.round((marker.getPoint().lng())*1000000)/1000000
               coordinates_string = lat + "," + lng;
               document.getElementById(target_field_id).value = coordinates_string;
            }
         );  
      }
      else
      {
         var marker = new GMarker(point, icon);
      }
      
      map.addOverlay(marker);
      map.enableScrollWheelZoom();
   }
}

function trim(str)
{
   var trimmed = str.replace(/^\s+|\s+$/g, '');
   return trimmed;
}

function stars_over(f, s)
{
   ratings = "ratings_" + f;
   rating0 = "Not at all";
   rating1 = "Somewhat";
   rating2 = "Moderately";
   rating3 = "Highly";
   rating4 = "Very highly";
   
   document.getElementById(ratings).innerHTML = eval('rating' + s);

   for(i = 0; i <= s; i++)
   {
      document['star'+f+i].src = '/img/poi_list/star_on.gif';
   }
}

function stars_out(f, n, v, o)
{
   votes = "votes";
   if(v == 1)
   {
      votes = "vote";
   }
   document.getElementById(ratings).innerHTML = o + n + " (" + v + " " + votes + ")";

   for(i = 0; i < 5; i++)
   {
      if(i < n)
      {
         document['star'+f+i].src = '/img/poi_list/star.gif';
      }
      else
      {
         document['star'+f+i].src = '/img/poi_list/star_gray.gif';
      }
   }
}

function createXmlHttpRequestObject()
{
   var xmlHttp;
   try
   {
      xmlHttp = new XMLHttpRequest();
   }
   catch(e)
   {
      var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
                                      'MSXML2.XMLHTTP.5.0',
                                      'MSXML2.XMLHTTP.4.0',
                                      'MSXML2.XMLHTTP.3.0',
                                      'MSXML2.XMLHTTP',
                                      'Microsoft.XMLHTTP');
      for(var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
      {
         try
         {
            xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
         }
         catch (e) {}
      }
   }
   if(!xmlHttp)
   {
      alert("Error creating the XMLHttpRequest object.");
   }
   else
   {
      return xmlHttp;
   }
}

function processXmlHttpRequest(url, obj, func)
{
   xmlHttp = createXmlHttpRequestObject();
   if(xmlHttp)
   {
      try
      {
         xmlHttp.open("GET", url, true);
         xmlHttp.onreadystatechange = function()
                                      {
                                         eval('func(obj)');
                                      }
         xmlHttp.send(null);
      }
      catch(e)
      {
         alert("Can't connect to server:\n" + e.toString());
      }
   }
}

function sendXmlHttp(url)
{
   xmlHttp = createXmlHttpRequestObject();
   if(xmlHttp)
   {
      try
      {
         xmlHttp.open("GET", url, true);
         xmlHttp.send(null);
      }
      catch(e)
      {
         alert("Can't connect to server:\n" + e.toString());
      }
   }
}

function getResponse(obj)
{
   myDiv = document.getElementById(obj);
   if(xmlHttp.readyState >= 1 && xmlHttp.readyState <= 3)
   {
      myDiv.innerHTML = "<img src=\"/img/loading.gif\" alt=\"\" /> Processing...";
   }
   else if(xmlHttp.readyState == 4)
   {
      if(xmlHttp.status == 200)
      {
         try
         {
            response = xmlHttp.responseText;
            myDiv.innerHTML = response;
         }
         catch(e)
         {
            alert("Error: " + e.toString());
         }
      }
      else
      {
         alert("There was a problem retrieving the data:\n" +
         xmlHttp.statusText);
      }
   }
}

function getResponse2(obj)
{
   myDiv = document.getElementById(obj);
   if(xmlHttp.readyState == 4)
   {
      if(xmlHttp.status == 200)
      {
         try
         {
            response = xmlHttp.responseText;
            myDiv.innerHTML = response;
         }
         catch(e)
         {
            alert("Error: " + e.toString());
         }
      }
      else
      {
         alert("There was a problem retrieving the data:\n" +
         xmlHttp.statusText);
      }
   }
}

function getResponse3(obj)
{
   myDiv = document.getElementById(obj);
   if(xmlHttp.readyState >= 1 && xmlHttp.readyState <= 3)
   {
      myDiv.innerHTML = "<img src=\"/img/loading_tiny.gif\" alt=\"\" />";
   }
   else if(xmlHttp.readyState == 4)
   {
      if(xmlHttp.status == 200)
      {
         try
         {
            response = xmlHttp.responseText;
            myDiv.innerHTML = response;
         }
         catch(e)
         {
            alert("Error: " + e.toString());
         }
      }
      else
      {
         alert("There was a problem retrieving the data:\n" +
         xmlHttp.statusText);
      }
   }
}

function stopRKey(evt)
{
   var evt = (evt) ? evt : ((event) ? event : null);
   var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
   if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}

function create_pois_list_warning()
{
   add_pois_max_allowed = 20;
   poi_data_entered = false;
   for(i = 0; i < add_pois_max_allowed; i++)
   {
      var_poi_name = 'poi_name_insert_' + i;
      var_poi_coordinates = 'poi_coordinates_insert_' + i;
      if(document.getElementById(var_poi_name) && document.getElementById(var_poi_coordinates))
      {
         if(
            document.getElementById(var_poi_name).value.length > 0 ||
            document.getElementById(var_poi_coordinates).value.length > 0
           )
         {
            poi_data_entered = true;
            break;
         }
      }
   }
   return poi_data_entered;
}

function get_pois_list()
{
   num = document.getElementById('numPois').value;
	
   warn = create_pois_list_warning();
   if(warn)
   {
      if(confirm('This will clear all POIs you have entered. Are you sure?')) 
      { 
         processXmlHttpRequest('/scripts/create_pois_list.php?numPois=' + num, 'pois_to_edit', getResponse); return false;
      }
   }
   else
   {
      processXmlHttpRequest('/scripts/create_pois_list.php?numPois=' + num, 'pois_to_edit', getResponse); return false;
   }
}

function poigroup_level_infos(selectedValue)
{
   if(selectedValue == 'public')
   {
      document.getElementById('poigroup_level_info').innerHTML=" - visible to everyone";
   }
   else if(selectedValue == 'personal')
   {
      document.getElementById('poigroup_level_info').innerHTML=" - visible only to you or friends you choose to share with";
   }
}

function hideGMapOnFocus()
{
   if(!document.getElementsByTagName)
   {
      return;
   }
   var allfields = document.getElementsByTagName("input");

   for(var i = 0; i < allfields.length; i++)
   {
      var field = allfields[i];
      var field_name = field.name;
      if(field_name == 'address' || field_name == 'getcoord' || field_name == 'get_btn' || field_name == 'ok_btn')
      {
         // do nothing
      }
      else if(field_name == 'user_coordinates' || field_name == 'user_coordinates_0' || field_name == 'user_coordinates_1' || field_name == 'user_coordinates_2')
      {
         field.onfocus = function() { toggleGMap(this, 'floating_map', 23, 0, this.name); };
      }
      else
      {
         field.onfocus = function() { hide('floating_map'); };
      }
   }
}

function get_poi_info_short(poi_id)
{
    processXmlHttpRequest('/scripts/show_poi_info.php?poi_id=' + poi_id, 'poi_info_short', getResponse); return false;
}

function get_suggested_poi_info_short(poi_id)
{
    processXmlHttpRequest('/scripts/show_suggested_poi_info.php?poi_id=' + poi_id, 'poi_info_short', getResponse); return false;
}

function get_google_map_directions(poi_id)
{
   sendXmlHttp('/scripts/pois_directionmap_counts.php?poi_id=' + poi_id);
   document.directions_form.submit();
}

function show_bubble_msg(msg_text, pos_target_field_id, adjustTop, adjustLeft)
{
   arr = getPosition(document.getElementById(pos_target_field_id));
   $('#floating_msg').show("fast");
   setPosition('floating_msg', arr[0] - adjustTop, arr[1] - adjustLeft);
   document.getElementById('floating_msg_text').innerHTML = msg_text;  
}

function uncheckAll(chk)
{
   chk = document.getElementsByName(chk);
   for(i = 0; i < chk.length; i++)
   {
      chk[i].checked = false;
   }
}

var currLink = null;
function toggleNewsNav(elm) 
{  
   document.getElementById('news_nl').className = '';
   if(elm == 'news_nl')
   {
      $("#forum_box").hide();
      $("#comments_box").hide();
      $("#news_box").fadeIn("fast");
   }
   if(elm == 'news_fl')
   {
      $("#news_box").hide();
      $("#comments_box").hide();
      $("#forum_box").fadeIn("fast");
   }
   if(elm == 'news_cl')
   {
      $("#news_box").hide();
      $("#forum_box").hide();
      $("#comments_box").fadeIn("fast");
   }
   createCookie('newsnav',elm,7);
   if(currLink)
   {
      currLink.className = currLink.className.replace(/\bon\b/,'');
      currLink.blur();
   }
   currLink = document.getElementById(elm);  
   currLink.className = "on"; 
}
function rememberNewsNav()
{
   var elm = readCookie('newsnav');
   if(elm)
   {
      toggleNewsNav(elm);  
   }
}

var currApprBrdLink = null;
function toggleApprBrdNav(elm) 
{  
   document.getElementById('apprbrd1').className = '';
   if(elm == 'apprbrd1')
   {
      $('#groupers').fadeOut("fast");
      $('#posters').fadeOut("fast");
      $('#suggers').fadeIn("fast");
   }
   if(elm == 'apprbrd2')
   {
      $('#suggers').fadeOut("fast");
      $('#posters').fadeOut("fast");
      $('#groupers').fadeIn("fast");
   }
   if(elm == 'apprbrd3')
   {
      $('#suggers').fadeOut("fast");
      $('#groupers').fadeOut("fast");
      $('#posters').fadeIn("fast");
   }
   createCookie('apprbrdnav',elm,7);
   if(currApprBrdLink)
   {
      currApprBrdLink.className = currApprBrdLink.className.replace(/\bon\b/,'');
      currApprBrdLink.blur();
   }
   currApprBrdLink = document.getElementById(elm);  
   currApprBrdLink.className = "on"; 
}
function rememberApprBrdNav()
{
   var elm = readCookie('apprbrdnav');
   if(elm)
   {
      toggleApprBrdNav(elm);  
   }
}

var currShareLink = null;
function toggleShareNav(elm) 
{  
   document.getElementById('already_shared_tab').className = '';
   if(elm == 'already_shared_tab')
   {
      $('#not_shared_yet').hide();
      $('#non_users').hide();
      $('#already_shared').fadeIn("fast");
   }
   if(elm == 'not_shared_yet_tab')
   {
      $('#already_shared').hide();
      $('#non_users').hide();
      $('#not_shared_yet').fadeIn("fast");
   }
   if(elm == 'non_users_tab')
   {
      $('#already_shared').hide();
      $('#not_shared_yet').hide();
      $('#non_users').fadeIn("fast");
   }
   createCookie('sharenav',elm,7);
   if(currShareLink)
   {
      currShareLink.className = currShareLink.className.replace(/\bon\b/,'');
      currShareLink.blur();
   }
   currShareLink = document.getElementById(elm);  
   currShareLink.className = "on"; 
}
function rememberShareNav()
{
   var elm = readCookie('sharenav');
   if(elm)
   {
      toggleShareNav(elm);  
   }
}


function createCookie(name,value,days)
{
   if(days) 
   {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
   }
   else var expires = "";
   document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++)
   {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
   }
   return null;
}

function eraseCookie(name)
{
   createCookie(name,"",-1);
}

function get_gmap_icon()
{
   var icon = new GIcon();
   if(arguments.length > 0)
   {
      icon.image = "/img/markers/" + arguments[0] + ".png";
   }
   else
   {
      icon.image = "/img/pf_marker.png";
   }
   icon.shadow = "/img/pf_marker_shadow.png";
   icon.iconSize = new GSize(32, 32);
   icon.shadowSize = new GSize(52, 32);
   icon.iconAnchor = new GPoint(16, 32);
   icon.infoWindowAnchor = new GPoint(16, 14);  
   
   return icon;
}

function show_file_type_options(pid)
{
   email = '';
   if(document.getElementById('email_' + pid))
   {
      if(document.getElementById('email_' + pid).value.length > 0)
      {
         email = document.getElementById('email_' + pid).value;
      }
   }
   if(document.getElementById('file_type_' + pid).value == "garmin_direct")
   {
      document.getElementById('garmin_placeholder_' + pid).innerHTML = '<a href="/scripts/garmin_direct.php?poigroup_id='+pid+'&email='+email+'" rel="lyteframe" title="POIfriend.com" id="pop_garmin_direct_' + pid + '" rev="showClose:true width:542 height:340"></a>';
      fb.tagAnchors(document);
      fb.start(document.getElementById('pop_garmin_direct_' + pid));
      $('#file_type_common_' + pid).fadeOut("fast");
   }
   else if(document.getElementById('file_type_' + pid).value == "tomtom_direct")
   {
      document.getElementById('tomtom_placeholder_' + pid).innerHTML = '<a href="/scripts/tomtom_direct.php?poigroup_id='+pid+'&email='+email+'" rel="floatbox" title="POIfriend.com" id="pop_tomtom_direct_' + pid + '" rev="showClose:true width:620 height:420"></a>';
      fb.tagAnchors(document);
      fb.start(document.getElementById('pop_tomtom_direct_' + pid));
      $('#file_type_common_' + pid).fadeOut("fast");
   }
   else if(document.getElementById('file_type_' + pid).value == "gearthkmz")
   {
      $('#zip_with_icon_layer_' + pid).fadeOut("fast");
   }
   else
   {
      $('#file_type_common_' + pid).show("fast");
      $('#zip_with_icon_layer_' + pid).show("fast");
   }
}

function manage_pois(mode, act, unique_id)
{
   if(act == 'get_coordinates')
   {
      showRepos(document.getElementById('coordinates_img_' + mode + '_' + unique_id), 'floating_map2', 30, 42); 
      showAddress(getAddressFields('_' + mode + '_', unique_id), 'poi_coordinates_' + mode + '_' + unique_id, 130, 200); 
      showCoordinates(document.getElementById('poi_coordinates_' + mode + '_' + unique_id, 'poi_coordinates_' + mode + '_' + unique_id), '', ''); 
      $('refresh_map_' + unique_id).fadeOut("fast"); 
      return false;
   }
   else if(act == 'refresh_map')
   {
      showRepos(document.getElementById('coordinates_img_' + mode + '_' + unique_id), 'floating_map2', 30, 42); 
      showCoordinates(document.getElementById('poi_coordinates_' + mode + '_' + unique_id).value, 'poi_coordinates_' + mode + '_' + unique_id, '', ''); 
      return false;
   }
   else if(act == 'onkeyup')
   {
      showRepos(document.getElementById('coordinates_img_' + mode + '_' + unique_id), 'floating_map2', 30, 42); 
      showCoordinates(document.getElementById('poi_coordinates_' + mode + '_' + unique_id).value, 'poi_coordinates_' + mode + '_' + unique_id, '', ''); 
      $('refresh_map_' + unique_id).fadeOut("fast"); 
      return false;
   }
}

function validate_download_form()
{
   emailVal = document.getElementById('email').value;
   processXmlHttpRequest('/scripts/create_pois_list.php?numPois=' + num, 'pois_to_edit', getResponse); return false;
}
