var gEntry = 0;
var gGetAttempts = 0;
var gfInd = false;
var gfSignup = false;
var gsLocName = "";
var gLat;
var gLong;
var gAddress="";
var objectCover;
var objectFrame;
var objectPicFrame;
var objectPhotoSlide;
var objectName;
var objectAddress;
var objectEmail;
var objectQuote;
var map;
var sid;
var my_accuracy;
var ipa;
var longitude;
var lat;
var my_evt;
var email;
var lat_array;
var lng_array;
var t_array;
var link;

try{
	var RunTimes = parseInt(document.getElementById('RunTimes').value);
} catch(err){}


$(document).ready(function(){
   InitPrettyPhoto();
   $('form').highlight();
   $.featureList(
      $("#tabs li a"),
      $("#output li"), {
      transition_interval: 60000
   });
});

$.fn.preload = function() {
   // Usage:   $(['img1.jpg','img2.jpg','img3.jpg']).preload();
   this.each(function(){
       $('<img/>')[0].src = this;
   });
}

function InitPrettyPhoto(){
   $(".slidemap").prettyPhoto({
      custom_markup: '<div id="map_canvas" style="width:260px; height:265px"></div>',
      changepicturecallback: 
         function(){ 
            InitMap(); 
         }
      }
   );
   $().prettyPhoto({
      custom_markup: '',
      changepicturecallback: 
         function(){}
      }
   );
}

try{
   var baseIcon = new GIcon(G_DEFAULT_ICON);
   baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
   baseIcon.iconSize = new GSize(20, 34);
   baseIcon.shadowSize = new GSize(37, 34);
   baseIcon.iconAnchor = new GPoint(9, 34);
   baseIcon.infoWindowAnchor = new GPoint(9, 2);
} catch(err){}

Array.prototype.max = function() {
   var i;
   var max = this[0];
   var len = this.length;
   for (i = 1; i < len; i++){
      if (this[i] > max){
         max = this[i];
      }
   }
   return max;
};

Array.prototype.min = function() {
    var i;
    var min = this[0];
    var len = this.length;
    for (i = 1; i < len; i++){
        if (this[i] < min){
            min = this[i];
        }
    }
    return min;
};

function alertContentsAjax(result, return_fn) {
   switch(return_fn){
      case "alert":
         alert("result: "+result);
         break;      
      case "block":
         ShowGoodOrBad("all", result);
         break;
      case "CheckPwd":
         CheckPwd(result);
         break;
      case "email_blocked":
         ShowGoodOrBad("email", result);
         break;
      case "fr_update_get":
         GetIndMsgSettingsReturn(result);
         break;
      case "fr_update_settings":
         UpdateFriendSettingsReturn(result);
         break;
      case "GetPostResponse":
         GetPostResponse(result);
         break;
      case "get_row":
         RowFound(result);
         break;
      case "IsUniqueEmail":
         IsUniqueEmail(result);
         break;      
      case "IsUniqueLocName":
         IsUniqueLocName(result);
         break;
      case "IsUniqueLocNameIndividual":
         IsUniqueLocNameIndividual(result);
         break;
      case "loc_search":
         showSearchResults(result);
         ShowLocationFriends(result);
         break;     
      case "remove_from_loc":
         ShowLocationFriends(result);
         break;
      case "ReqLoc":
         ReqLocReturn(result);
         break;
      case "slide":
         ShowSlideInfo(result);
         break;   
      case "SubmitComment":
         SubmitCommentReturn(result);
         break; 
      case "web_blocked":
         ShowGoodOrBad("web", result);
         break;
      case "":
         break;
      default:
         document.body.style.cursor="default";
         alert("There was a problem with the request");
   }
   ChangeIconToPointer();
   return false;
}

function GetPressedKeyNum(evt){
   var pressed = (window.event)?event.keyCode:evt.which;
   return pressed;
}

function IfEnterSubmit(evt){
   if (GetPressedKeyNum(evt) == 13){
      SignIn();
   }
   return false;
}

function setGlobalLatLong(latitude, longitude, address){
   gLat = latitude;
   gLong = longitude;
   gAddress = address;
   if (gLat==="" || gLong===""){
      geocoder = new google.maps.Geocoder();
      geocoder.geocode( { 'address': address}, function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
            var point = results[0].geometry.location;
            gLat = point.lat();
            gLong = point.lng();
         } else {
             //alert("Geocode was not successful for the following reason: " + status);
         }
      });
   }
}

function FadeButton(sFade, sShow){
   document.getElementById(sFade).style.display='block';
   $("#"+sFade).animate({
      opacity:.2}, "slow");
   $("#"+sShow).animate({
      opacity:.8}, "slow");
   document.body.style.cursor="pointer";
}

function UnfadeButton(sMain, sOther){
   document.getElementById(sMain).style.display='block';
   $("#"+sMain).animate({
      opacity:1}, "slow");
   $("#"+sOther).animate({
      opacity:0}, "slow");
   document.body.style.cursor="default";
}
function IsIPad(){
   return navigator.userAgent.match(/iPad/i) != null;
}

function SignIn(){
    if (document.getElementById("email").value==="" || document.getElementById("password").value===""){
       alert("Please enter your email and password.");
       return false;
    } else {
       document.signin.submit();
    }
}

function UpdateShownPic(){
   document.getElementById("my_pic").style.display='none';
   document.getElementById("updated_pic").style.display='block';
}

function initSlides(){
   initCover();
   objectFrame=document.getElementById('frame_bg');
   objectPicFrame=document.getElementById('slideFrame');
   objectPhotoSlide=document.getElementById('frame_pic');
   objectName = document.getElementById("frame_name");
   objectAddress = document.getElementById("frame_address");
   objectEmail = document.getElementById("frame_email");
   objectQuote = document.getElementById("frame_quote");
}

function initCover(){
   objectCover=document.getElementById('cover');
}
function createSmallMarker(point, color) {
   var f = new GIcon();
   f.image = "http://labs.google.com/ridefinder/images/mm_20_" + color + ".png";
   f.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
   f.iconSize = new GSize(12,20);
   f.shadowSize = new GSize(22,20);
   f.iconAnchor = new GPoint(6,20);
   f.infoWindowAnchor = new GPoint(6,1);
   f.infoShadowAnchor = new GPoint(13,13);
   var newMarker = new GMarker(point,
      {icon: f,
      draggable: false});
 
   return newMarker;
}

// Creates a marker representing a point in the polyline.
function createPointMarker(point, time_string) {
   var point_marker = createSmallMarker(point, "blue");
   GEvent.addListener(point_marker, "click", function() {
      point_marker.openInfoWindowHtml("<b>" + time_string + "</b>");
   });
   return point_marker;
}

function createMarker(point, index, time_string) {
    // Create a lettered icon for this point using our icon class
   var letter = String.fromCharCode("A".charCodeAt(0) + index-1);
   var letteredIcon = new GIcon(baseIcon);
   letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

    // Set up our GMarkerOptions object
   markerOptions = { icon:letteredIcon };
   var marker = new GMarker(point, markerOptions);
   if (time_string!==""){
      GEvent.addListener(marker, "click", function() {
         marker.openInfoWindowHtml("<b>" + time_string + "</b>");
      });
   }
   return marker;
}

function InitMap(){
   var lat = gLat;
   var longitude = gLong;
   var myPoint = new google.maps.LatLng(lat, longitude);
   document.getElementById("frame_pic").zindex = 900;
   var myOptions = {
      zoom: 15,
      center: myPoint,
      navigationControl: true,
      scaleControl: true,
      backgroundColor: "#FFFFFF",
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };
   var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions); 
   if (lat_array){
      var south = lng_array.min();
      var north = lng_array.max();
      var east = lat_array.max();
      var west = lat_array.min();
      var south_east = new google.maps.LatLng(west, south);
      var north_west = new google.maps.LatLng(east, north);
      if (!south_east.equals(north_west)){
         var my_bounds = new google.maps.LatLngBounds(south_east, north_west);
         if (my_bounds<15){
            my_bounds = 15;
         }
         map.fitBounds(my_bounds);
      }
      if (lat_array.length<=6){
         var new_point = new google.maps.LatLng(lat, longitude);
         var new_marker = new google.maps.Marker({
            position: new_point,
            title: t_array[0]
         });
         new_marker.setMap(map);
            for (i=1;i<lat_array.length;i++){
               new_point = new google.maps.LatLng(lat_array[i], lng_array[i]);
               new_marker = new google.maps.Marker({
               position: new_point,
               title: t_array[i]
            });
            new_marker.setMap(map);
         }
      } else { //use polylines
         var new_points = [];
         for (i=0;i<lat_array.length;i++){
            new_points[i] = new google.maps.LatLng(lat_array[i], lng_array[i]);
            new_point = new google.maps.LatLng(lat_array[i], lng_array[i]);
            new_marker = new google.maps.Marker({
               position: new_point,
               title: t_array[i]
            });
            new_marker.setMap(map);
         } 
         var myPath = new google.maps.Polyline({
            path: new_points,
            strokeColor: "#FF0000",
            strokeOpacity: 1.0,
            strokeWeight: 2
         });
         myPath.setMap(map);
      }
   } else {
      var marker = new google.maps.Marker({
         position: myPoint,
         title:""
      });
      marker.setMap(map);
   }
   google.maps.event.trigger(map, 'resize');
   lat_array = null;
   lng_array = null;
   t_array = null;
}

function hideSlide(){
   //alert("hide slide");
   objectPhotoSlide.style.overflow="hidden";
   document.body.style.cursor='auto';
   $("#slideFrame").hide("slow");
   $("#frame_bg").hide("slow", function(){
      hideObjectFrame();
   });
}

function hideObjectFrame(){
   objectName.innerHTML = '';
   objectAddress.innerHTML = '';
   objectEmail.innerHTML = '';
   objectQuote.innerHTML = '';
   lightenCover();
}

function initSlidesAndFindLocation(ip_address, id_code){
    ipa = ip_address;
    //idc = id_code;
    try{
       var time_dst=calculate_time_zone();
       var time_array=time_dst.split(",");
       document.getElementById("gmt_offset").value = time_array[0];
       document.getElementById("dst").value = time_array[1];
    }catch(e){}
    initSlides();
    findLocation(ip_address, id_code);
}

function makePOSTRequest(ajax_url, params, callback_arg){
   $.ajax({
      url: ajax_url,
      dataType: "text",
      type: "POST",
      data: params,
      success: function(sResp){
         alertContentsAjax(sResp, callback_arg);
      }
   });      
}

function insertRows(session, f_you){
   var last_date;
   try{
      last_date = document.getElementById("date0").innerHTML;
   } catch(e) {
      last_date = "0";
   }
   if (gGetAttempts<10){
      gGetAttempts += 1;
      makePOSTRequest("/getnewrow", "id="+session+"&last_date="+last_date+"&f_you="+f_you, "get_row");
   }
}

function initSlidesAndFindLocationAndInsertRows(ip_address, id_code, f_you){
    initSlidesAndFindLocation(ip_address, id_code);
    my_id = id_code;
    var fn = "insertRows('"+id_code+"', "+f_you+")";
    setTimeout(fn, 4000);
}

function ParseXML(sXML, sTag){
//the tags should not have the angle brackets
   try{
      var array1 = sXML.split("<"+sTag+">");
      var array2 = array1[1].split("</"+sTag+">");
      return array2[0];
   } catch(e){
      //alert("Error: "+e.description);
      return "";
   }
}

function GetLatestRow(response){
   return ParseXML(response, "new_row");
}

function GetRowID(sResult){
   var sid = ParseXML(sResult, "table_id");
   return sid;
}

function RowAlreadyExists(row_id){
   var curr_row_id = "";
   var i;
   try{
      for (i=1;i<20; i++){
         curr_row_id = document.getElementById("table_id"+i).value;
         //alert("comparing "+curr_row_id+" to "+row_id);
         if (curr_row_id==row_id){
            return i;
         }
      }
      return false;
   } catch (e){
      //alert("error: "+e.description+" i="+i);
      return false;
   }
}

function RemoveRow(row_id){
   $("#blank_row"+row_id).animate({height:0}, "slow");
   $("#plus_line"+row_id).html("");
   $("#cell_table"+row_id).animate({opacity:0}, "fast", 
      function(){
         $("#cell_table"+row_id).html("");
         $("#cell_table"+row_id).animate({height:0}, "slow");
         $("#comment_message"+row_id).animate({opacity:0}, "fast",
            function(){
               $("#comment_message"+row_id).html("");
               $("#comment_message"+row_id).animate({height:0}, "slow");
               $("#plus_line"+row_id).animate({height:0}, "slow");
               $("#blank_tr"+row_id).animate({height:0}, "slow");
            }
         );
      }
   );
}

function PercentEncode(sText){
   var sTxt = sText;
   try{
      if (sTxt.length()!==0){
         sTxt = sTxt.replace("%","%25");
         sTxt = sTxt.replace("!","%21");
         sTxt = sTxt.replace("*","%2A");
         sTxt = sTxt.replace("'","%27");
         sTxt = sTxt.replace("(","%28");
         sTxt = sTxt.replace(")","%29");
         sTxt = sTxt.replace(";","%3B");
         sTxt = sTxt.replace(":","%3A");
         //sTxt = sTxt.replace("@","%40");
         sTxt = sTxt.replace("&","%26");
         //sTxt = sTxt.replace("=","%3D");
         sTxt = sTxt.replace("+","%2B");
         sTxt = sTxt.replace("$","%24");
         sTxt = sTxt.replace(",","%2C");
         sTxt = sTxt.replace("/","%2F");
         sTxt = sTxt.replace("?","%3F");
         sTxt = sTxt.replace("#","%23");
         sTxt = sTxt.replace("[","%5B");
         sTxt = sTxt.replace("]","%5D");
         sTxt = sTxt.replace("<","%3C");
         sTxt = sTxt.replace(">","%3E");
         sTxt = sTxt.replace("~","%7E");
         sTxt = sTxt.replace(".","%2E");
         sTxt = sTxt.replace("\"","%22");
         sTxt = sTxt.replace("{","%7B");
         sTxt = sTxt.replace("}","%7D");
         sTxt = sTxt.replace("|","%7C");
         sTxt = sTxt.replace("\\","%5C");
         sTxt = sTxt.replace("-","%2D");
         sTxt = sTxt.replace("`","%60");
         sTxt = sTxt.replace("_","%5F");
         sTxt = sTxt.replace("^","%5E");
         sTxt = sTxt.replace(" ","%20");
      }
   } catch(err){}
   return sTxt;
}

function mouseX(my_evt) {
	if (!my_evt){
		my_evt = document.event;
	}
	try{
		if (my_evt.pageX){
			return my_evt.pageX;
		}
	} catch (err) {}
	try{
		if (my_evt.clientX){
			return my_evt.clientX + (document.documentElement.scrollLeft + document.body.scrollLeft);
		} else {
			return null;
		}
	} catch (err1){
		return null;
	}
}

function mouseY(my_evt) {
	if (!my_evt){
		my_evt = document.event;
	}
	try{
		if (my_evt.pageY){ 
			return my_evt.pageY;
		}
	} catch (err) {}
	try{
		if (my_evt.clientY){
			return my_evt.clientY + (document.documentElement.scrollTop + document.body.scrollTop);
		} else {
			return null;
		}
	} catch (err1){
		return null;
	}
}   
      
function MapSlide(event, location, my_time, lat, longitude, address){
    if (lat==="" || longitude===""){
       geocoder = new google.maps.Geocoder();
       geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
             MapSlideByPoint(event, location, my_time, address, results[0].geometry.location);
          } else {
             //alert("Geocode was not successful for the following reason: " + status);
          }
       });
    }
    if (lat && longitude){
        initMap(lat,longitude);
    }
}

function MapSlideByPoint(my_evt, location, my_time, address, point){
    if (point){
        var lat = point.lat();
        var longitude = point.lng();
        if (lat && longitude){
            MapSlide(my_evt, location, my_time, lat, longitude, address);
        }
    }
}

function MapSlideArray(event, location, time_array, latitude_array, longitude_array, address){
   if ((latitude_array.length)!==0){
      //place the first point
	  lat_array = latitude_array;
	  lng_array = longitude_array;
	  t_array = time_array;
      MapSlide(event, location, time_array[0], latitude_array[0], longitude_array[0], address);
   }
}

function ShowSlideInfo(html){
   var picture = ParseXML(html,"picture");
   //alert("pic="+picture);
   var address1 = ParseXML(html,"address1");
   var address2 = ParseXML(html,"address2");
   var city = ParseXML(html,"city");
   var state = ParseXML(html,"state");
   var country = ParseXML(html,"country");
   var quote = ParseXML(html,"quote");
   var name = ParseXML(html,"name");
   var address = "";
   if (address1!=="None" && address1!==""){
      address = address1;
   }
   if (address2!=="None" && address2!==""){
      if (address!==""){
         address = address+"<br>"+address2;
      } else {
         address = address2;
      }
   } 
   if (city!=="None" && city!==""){
      if (address!==""){
         address = address+"<br>"+city;
      } else {
         address = city;
      }
   }
   if (state!=="None" && state!==""){
      if (city!=="None" && city!==""){
         address = address+", "+state;
      } else {
         address = address+"<br>"+state;
      }
   }
   if (country!=="None" && country!==""){
      address = address+" "+country;
   }
   if (quote!="None" && quote!==""){
      address = address+"<br/><span style='font-weight:bold'>Quote: </span>"+quote;
   }
   $.prettyPhoto.open(picture,name,address);
}

function showSearchResults(result){
	var k;
	var page_no = ParseXML(result, "page_no");
	var count = parseInt(ParseXML(result, "count"),10);
	var loc_link = parseInt(ParseXML(result, "loc_link"),10);
	var next = ParseXML(result, "next");
	if (count == 21){
		next = true;
		count = 20;
	}
	var html_str = "<table style='width:300px;'>";
	if (count===0){
		html_str += "<tr><td>There weren't any matches. <div style='font-weight:light'>If you're having trouble finding " +
					"someone, it could be because they haven't registered a Bluetooth " +
					"ID.</div></td></tr>";
	}
	for (k=1;k<=count;k++){
		var i_str = k;
		var name = ParseXML(result, "name"+i_str);
		var image = ParseXML(result, "image"+i_str);
		var ind_link = ParseXML(result, "link"+i_str);
		html_str += "<tr style='width:100%'><td style='width:55px'>"+image+"</td>";
		html_str += "<td>"+name+"</td>";
		html_str += "<td style='text-align:right'><input type='button' value='Add' "+
					"onClick='AddPersonToLoc("+ind_link+", "+loc_link+", "+page_no+")' >"+
					"</td></tr>";
	}
	if (next=="yes"){
		html_str += "<tr><td style='text-align:center'><a href='' onClick='LocSearchPeople("+(page_no+1)+", "+loc_link+")' />more</a>";
	}
	html_str += "</table>";
	document.getElementById("search_space").innerHTML = html_str;
}

function ShowBlock(fBlock){
	var sHTML = "<td>";
    var show_emailYes;
	var show_emailNo;
    if (fBlock){
       show_emailYes = "value='True' checked";
       show_emailNo="value='False' onClick='BlockOrUnblock(\"False\",\""+link+"\")'";
    } else {
       show_emailYes="value='True' onClick='BlockOrUnblock(\"True\",\""+link+"\")'";
       show_emailNo="value='False' checked";
    }
    sHTML += "<input type='radio' name='block' "+show_emailYes+" >"+
              "</td><td><input type='radio' name='block' "+show_emailNo+" >";
    sHTML+= "</td><td>";
    sHTML+= "Block all my locations";
    sHTML+= "</td>";
    //alert("block email4");
    document.getElementById("block").innerHTML=sHTML;
    //alert(sHTML);
    alert("Done.");
    document.body.style.cursor="default";
}

function BlockOrUnblockWeb(block, mylink){
	document.body.style.cursor="wait";
    link = mylink;
	return_str = "web_blocked";
    makePOSTRequest("/block_web", "block="+block+"&link="+link, "web_blocked");
}

function ShowGoodOrBad(sContext, result){
	var this_resp = ParseXML(result, "response");
	if (this_resp=="True"){
		var block = ParseXML(result, "block");
		result = "";
		var fBlock=false;
		if (block=="Yes"){
			fBlock=true;
		}
		try{
			if (sContext=="all"){
				ShowBlock(fBlock);
			}
			if (sContext=="web"){
				ShowBlockWeb(fBlock);
			}
			if (sContext=="email"){
				ShowBlockEmail(fBlock);
			}
		}catch(e){
		    document.body.style.cursor="default";
			alert("There was a problem with the request.");
		}
	} else {
	    document.body.style.cursor="default";
		alert("There was a problem with the request.");
	}	
}

function ShowLocationFriends(result){
    var i;
	var loc_link = parseInt(ParseXML(result, "loc_id"),10);
	var count = ParseXML(result, "countf");
	var html_str = "<table style='width:300px'>";
	for (i=1;i<=count;i++){
		var i_str = i;
		var name = ParseXML(result, "namef"+i_str);
		var image = ParseXML(result, "imagef"+i_str);
		var link = ParseXML(result, "linkf"+i_str);
		html_str += "<tr style='width:100%'><td style='width:55px'>"+image+"</td>";
		html_str += "<td>"+name+"</td>";
		html_str += "<td style='text-align:right'><input type='button' value='Remove' "+
					"onClick='RemoveFromLocation("+link+", "+loc_link+")' style='text-align:right'>"+
					"</td></tr>";
	}
	html_str += "</table>";
	document.getElementById("location_friends").innerHTML = html_str;
}


function AddPersonToLoc(ind_link, loc_link, sPage){
	return_str = "loc_search";
	var sSearch = document.getElementById('people_search').value;
	makePOSTRequest("/add_to_loc", "search=" + sSearch + "&page_no=" + sPage + "&loc_link=" + loc_link+
								"&ind_link="+ind_link, "loc_search");
}

function LocSearchPeople(sPage, loc_link){
	return_str = "loc_search";
	//alert('searching');
	var sSearch = document.getElementById('people_search').value;
	if (sSearch !== ""){
		makePOSTRequest("/search_loc", "search=" + sSearch + "&page_no=" + sPage + "&loc_link=" + loc_link, "loc_search");
	}
	return false;
}


function GetSlideHTML(id, event){
    var iMouseX = mouseX(event);
    var iMouseY = mouseY(event);
	return_str = "slide";
	var html = makePOSTRequest("/internal_lookup", "lid="+id+"&mouseY="+iMouseY+"&mouseX="+iMouseX, "slide");
	return html;
}

function GetMapSlideHTML(id){
	return_str = "map_slide";
	var html = makePOSTRequest("/internal_map_lookup", "lid="+id, "map_slide");
	return html;
}


function showSlide(event, id){
   //$.prettyPhoto.open("/images/prettyPhoto/facebook/loader.gif", "", "");
   var html = makePOSTRequest("/internal_lookup", "lid="+id, "slide");
} 

function showLocSlide(event, id){
    makePOSTRequest("/internal_loc_lookup", "lid="+id,"slide");
}

function showMapSlide(event, id){
    my_evt = event;
    return_str = "slide";
    GetMapSlideHTML(id);
    return false;
}
function ShowTextMsgSettings(my_id, fr_id){
   $("#text_msg_box").top();
   $("#text_msg_box").left();
   DarkenScreen();
   
   $("#text_msg_box").show();
}

function BlockOrUnblock(block, mylink){
	document.body.style.cursor="wait";
	link = mylink;
	return_str = "block";
    makePOSTRequest("/block", "block="+block+"&link="+link, "block");
}

function ShowBlockWeb(fBlock){
	try{
		//alert("fBlock: "+fBlock);
		var sHTML = "<td>";
		var show_emailYes;
		var show_emailNo;
	    if (fBlock){
	       show_emailYes = "value='True' checked";
	       show_emailNo="value='False' onClick='BlockOrUnblockWeb(\"False\",\""+link+"\")'";
	    } else {
	       show_emailYes="value='True' onClick='BlockOrUnblockWeb(\"True\",\""+link+"\")'";
	       show_emailNo="value='False' checked";
	    }
	    //alert("block email3");
	    sHTML += "<input type='radio' name='web_blocked' "+show_emailYes+" >"+
	              "</td><td><input type='radio' name='web_blocked' "+show_emailNo+" >";
	    sHTML+= "</td><td>";
	    sHTML+= "Block my location when I visit the site";
	    sHTML+= "</td>";
	    //alert("block email4");
	    document.getElementById("web_blocked").innerHTML=sHTML;
	    //alert(sHTML);
	    alert("Updated");
		document.body.style.cursor="default";
	}catch(e){
		//alert("ShowBlockWeb:"+e);
	}
}

function BlockOrUnblockEmail(block, mylink){
	//alert("block email");
	document.body.style.cursor="wait";
    link = mylink;
	return_str = "email_blocked";
    makePOSTRequest("/block_email", "block="+block+"&link="+link,"email_blocked");
}

function ShowBlockEmail(fBlock){
	var sHTML = "<td>";
	var show_emailYes="";
	var show_emailNo="";
	//alert("fBlock: "+fBlock);
    if (fBlock===true){
       //alert("fBlock is true");
       show_emailYes = "value='True' checked";
       show_emailNo="value='False' onClick='BlockOrUnblockEmail(\"False\",\""+link+"\")'";
    } else {
       //alert("fBlock is false");
       show_emailYes="value='True' onClick='BlockOrUnblockEmail(\"True\",\""+link+"\")'";
       show_emailNo="value='False' checked";
    }
    sHTML += "<input type='radio' name='email_blocked' "+show_emailYes+" >"+
              "</td><td><input type='radio' name='email_blocked' "+show_emailNo+" >";
    sHTML+= "</td><td>";
    sHTML+= "Hide my email address";
    sHTML+= "</td>";
    document.getElementById("email_blocked").innerHTML=sHTML;
    //alert(sHTML);
	alert("Okay");
	document.body.style.cursor="default";
}

function BTIDTool(){
    var box = document.getElementById('btid_box');
    //var instruct = document.getElementById('bt_instructions');
    SetToBlankAndShrink("#bt_instructions");
    $("#btid_box").animate({height:400}, "slow",
       function(){
          box.innerHTML = "<applet code='findID.BTApplet.class' CODEBASE='applet/' "+
				"ARCHIVE='bluecove-2.1.0.jar,WhoAmI.jar' width='200px' height='400px'></applet>";
	      box.style.zindex=10;
	   }
	);
}


function BTcheck(BTval){
    var msg = "The BLUETOOTH ID that you entered isn't valid. "+  
        " Entering an invalid ID will disable some features.";
    //alert("BTVal="+BTval);
    if (BTval.length!=12) {
        var goon=confirm(msg);
        if (goon){
            return true;
        } else {
            return false;
        }
    } else {
        return true;
    }
}

function friendAccept(link, num){
    //alert("in friendAccept");
	var count = parseInt(document.getElementById('req_count').value,10);
	document.getElementById('req_count').value = count - 1;
	//alert ("count="+count);
    document.getElementById('row'+num).style.display = 'none';
    makePOSTRequest("/fr_accept", "link="+link+"&val=Accept", "");
    if (count==1 || count=="1"){
        document.getElementById("main_requests").style.display = 'none';
		location.href = ("/if");
    }    
}

function friendDecline(link, num){
	var count = parseInt(document.getElementById('req_count').value,10);
	document.getElementById('req_count').value = count - 1;
    document.getElementById('row'+num).style.display = 'none';
    makePOSTRequest("/fr_accept", "link="+link+"&val=Decline","");
    if (count==1 || count=="1"){
        document.getElementById("main_requests").style.display = 'none';
		location.href = ("/if");
    }
}

function AddDevice(){
    if (document.getElementById("loc_user_name").value===""){
          document.getElementById("loc_user_name").style.background = 'Yellow';
          alert("Please enter a location email.");
          return false;
    }
    if (document.getElementById("loc_password").value.length===0){
          document.getElementById("loc_password").style.background = 'Yellow';
          alert("Please enter a password.");
          return false;
    }
    document.add_device.submit();
}

function Notify(sess){
   makePOSTRequest("/send_signup_emails", "id="+sess, "");
}

function UpdateComment(){
   try{
      document.getElementById("comment_key").value = "xyzzy";
      document.new_comment.comment.value='';
      document.getElementById("comment").value = "";
   } catch(err){
      //alert("error");
   }
}



function GoToLoc(loc){
	document.location.href = loc;
}

function setCookie(c_name,value,expiredays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +value+((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function HideLocator(){
	document.getElementById('loc_id').style.display = 'none';
	setCookie('browserid', "notSet", 10);
}

function InsertBTID(my_bt){
    //alert("InsertBTID");
    var bt_array = my_bt.split("--");
    document.getElementById('BTID').value = bt_array[1];
    var loc_cookie_val;
    try{
	    try{
	        loc_cookie_val = GetCookie("lsid");
	    } catch(e) {
	        loc_cookie_val = null;
	    }
	    if (loc_cookie_val===null){
	        try{
	            if (document.getElementById('java_ver').value > 4){
	                $("#LocationNameDiv").show("slow");
		        }
	        } catch(es){}
	    }else{
	       //alert("??");
	    }
	}catch(e){
	   alert("error1: "+e.description);
	}
}


function JSPhone1(){
    var phone1 = document.update_ind.phone1.value;
	if (phone1.length==3){
		document.update_ind.phone2.focus();
	}
}

function JSPhone2(){
    var phone1 = document.update_ind.phone2.value;
	if (phone1.length==3){
		document.update_ind.phone3.focus();
	}
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function MyBTCheck(){
    var box = document.getElementById('bt_check');
    box.style.width = '100%'; 
    box.innerHTML = "<applet code='btExists.BTCheck.class' codebase='applet/' "+
		"archive='BTEnabled.jar,bluecove-2.1.0.jar'></applet>";
}

function PressDownloadButton(){
	document.getElementById('button1').style.display='none';
	document.getElementById('button2').style.display='block';
}

function RemoveFriend(link, fr_link, row_name){
    var answer = confirm("Are you sure you want to delete this person from your friends?");
    if (answer){
		document.getElementById(row_name).style.display = 'none';
		makePOSTRequest("/unfriend", "link="+link+"&fr_link="+fr_link,"");
    }
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}  

function showAlpha(){
    var alpha_light = document.getElementById("liquid_tab_alpha_light");
    var alpha_dark = document.getElementById("liquid_tab_alpha_dark");
    var calender_light = document.getElementById("liquid_tab_calender_light");
    var calender_dark = document.getElementById("liquid_tab_calender_dark");
    
    document.cookie='ift=locations; path = /';
    alpha_light.style.display = 'block';
    alpha_dark.style.display = 'none';
    alpha_light.style.zIndex = 10;
    alpha_dark.style.zIndex = 10;
    calender_light.style.zIndex = 9;
    calender_dark.style.zIndex = 9;
    calender_light.style.display = 'none';
    calender_dark.style.display = 'block';

    document.getElementById('center_table').style.display='block';
    document.getElementById('alpha_table').style.display='none';
}


function showCalender(){
    var alpha_light = document.getElementById("liquid_tab_alpha_light");
    var alpha_dark = document.getElementById("liquid_tab_alpha_dark");
    var calender_light = document.getElementById("liquid_tab_calender_light");
    var calender_dark = document.getElementById("liquid_tab_calender_dark");
    
    document.cookie='ift=settings; path = /';
    alpha_light.style.display = 'none';
    alpha_dark.style.display = 'block';
    calender_light.style.display = 'block';
    calender_dark.style.display = 'none';
    alpha_light.style.zIndex = 9;
    alpha_dark.style.zIndex = 9;
    calender_light.style.zIndex = 10;
    calender_dark.style.zIndex = 10;
 
    document.getElementById('center_table').style.display='none';
    document.getElementById('alpha_table').style.display='block';
}

function showHistory(){
   var history_light = document.getElementById("liquid_tab_history_light");
    var history_dark = document.getElementById("liquid_tab_history_dark");
    var favorite_light = document.getElementById("liquid_tab_favorite_light");
    var favorite_dark = document.getElementById("liquid_tab_favorite_dark");
    
    document.cookie='iht=history; path = /';
    history_light.style.display = 'block';
    history_dark.style.display = 'none';
    favorite_light.style.display = 'none';
    favorite_dark.style.display = 'block';
    history_light.style.zIndex = 10;
    history_dark.style.zIndex = 10;
    favorite_light.style.zIndex = 8;
    favorite_dark.style.zIndex = 8;

    document.getElementById('favorite_table').style.display='none';
    document.getElementById('history_table').style.display='block';
}

function showFavorites(){
   var history_light = document.getElementById("liquid_tab_history_light");
    var history_dark = document.getElementById("liquid_tab_history_dark");
    var favorite_light = document.getElementById("liquid_tab_favorite_light");
    var favorite_dark = document.getElementById("liquid_tab_favorite_dark");
    
    document.cookie='iht=favorites; path = /';
    history_light.style.display = 'none';
    history_dark.style.display = 'block';
    favorite_light.style.display = 'block';
    favorite_dark.style.display = 'none';

    history_light.style.zIndex = 8;
    history_dark.style.zIndex = 8;
    favorite_light.style.zIndex = 10;
    favorite_dark.style.zIndex = 10;
   
    document.getElementById('favorite_table').style.display='block';
    document.getElementById('history_table').style.display='none';
}

function ShowFriends(){
    if (document.getElementById('friend_select').value=='alphabetically'){
        document.getElementById('center_table').style.display='none';
        document.getElementById('alpha_table').style.display='block';
    } else {
        document.getElementById('center_table').style.display='block';
        document.getElementById('alpha_table').style.display='none';
    }
}

function SwitchLongButton(x){
    if (x==1){
        document.getElementById('button3').style.display='none';
        document.getElementById('button4').style.display='block';
    }
}

function SwitchUpAllButtons(){
   SwitchOutButton("button1", "button2", 0);
   SwitchOutButton("button3", "button4", 0);
   SwitchOutButton("button5", "button6", 0);
}

function SwitchOutButton(top, bottom, x){
   if (x==1){
      document.getElementById(bottom).style.display='block';
      try{
         document.getElementById(bottom).style.opacity = 1;
      }catch(ope1){}
      try{
         document.getElementById(bottom).style.filter = 'alpha(opacity=100)';
      }catch(ope2){}
      document.getElementById(top).style.display='none';
   } else {
      document.getElementById(top).style.display='block';
      try{
         document.getElementById(bottom).style.opacity = 0;
         document.getElementById(top).style.opacity = 1;
      }catch(ope1){}
      try{
         document.getElementById(bottom).style.filter = 'alpha(opacity=0)';
         document.getElementById(top).style.opacity = 'alpha(opacity=100)';
      }catch(ope2){}
      document.getElementById(bottom).style.display='block';
   }
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function UnixTime(){
	var now_time = new Date(); // Generic JS date object
	var unixtime_ms = now_time.getTime(); // Returns milliseconds since the epoch
	return unixtime_ms;
}

function UnpressDownloadButton(){
	document.getElementById('button2').style.display='none';
	document.getElementById('button1').style.display='block';
}

function GetOSName(){
	var OSName="Unknown OS";
	if (navigator.appVersion.indexOf("Win")!=-1){OSName="Windows";}
	if (navigator.appVersion.indexOf("Mac")!=-1) {OSName="MacOS";}
	if (navigator.appVersion.indexOf("X11")!=-1) {OSName="UNIX";}
	if (navigator.appVersion.indexOf("Linux")!=-1) {OSName="Linux";}
	return OSName;
}

function InsertVersionInd(ver){
   document.getElementById('java_ver').value = ver;
}

function InsertVersion(ver){
	//alert("in InsertVersion");
	if (ver<5){
		var my_confirm = confirm("For your computer to be a locator, you must have "+
		     "Java version 1.5 or greater installed.  Currently, you don't.  Would you like to "+
		     "go to the install page now.");
		if (my_confirm){
			var OS = GetOSName();
			if (OS=="MacOS"){
				window.open("http://support.apple.com/kb/DL972", "Java Download",
							"height=500, width=400");
			} else {
				//location.href = "http://java.com/en/download/manual.jsp";
				window.open("http://java.com/en/download/manual.jsp", "Java Download", 
							"height=500, width=400");
			}
		} else {
		    history.go(-1); 
		}
	}
}

function RemoveFromLocation(iid, loc_id){
	return_str = "remove_from_loc";
	makePOSTRequest("/remove_from_loc", "iid="+iid+"&loc_id="+loc_id, "");	
}



function VerifyComment(){
	var comment = document.new_comment.comment.value;
	if (comment.substring(0,15)!="Leave a comment"){
		return true;
	} else {
		return false;
	}
}	

function ShowTextMsgTimes(evt, name, MyLink, FrLink){
   var xval = mouseX(evt);
   var yval = mouseY(evt)-100;
   document.getElementById("link").value = MyLink;
   document.getElementById("fr_link").value = FrLink;
   $("#txt_name").html(name);
   $("#cover").show();
   $("#text_msg_box").show();
   $("#text_msg_box").css("left", xval+"px");
   $("#text_msg_box").css("top", yval+"px");
   $("#cover").animate({opacity:.7}, "slow");
   ChangeIconToWait();
   $("#text_msg_box").animate({opacity:1}, "slow");   
   GetIndMsgSettings(MyLink, FrLink);
   ChangeIconToPointer();
}

function GetIndMsgSettings(MyLink, FrLink){
   var params = "my_link="+MyLink+"&fr_link="+FrLink;
   makePOSTRequest("/fr_update_get", params, "fr_update_get");
}

function GetIndMsgSettingsReturn(resp){
   var str = ParseXML(resp, "GetIndMsgSettings");
   var start = ParseXML(resp, "SMSStart");
   if (start==""){
      start = "12:00 AM";
   }
   var end = ParseXML(resp, "SMSEnd");
   if (end==""){
      end = "12:00 AM";
   }
   document.getElementById("start_time").value = start;
   document.getElementById("end_time").value = end;
   var setting = ParseXML(resp, "SendSMS");
   if (setting=="Less" || setting=="More"){
      document.getElementById("start_time").disabled = false;
      document.getElementById("end_time").disabled = false;
      if (setting=="Less"){
         document.getElementById("txt_settings_select").selectedIndex=1;
      } else {
         document.getElementById("txt_settings_select").selectedIndex=2;
      }
   } else {
      document.getElementById("txt_settings_select").selectedIndex=0;
      document.getElementById("start_time").disabled = true;
      document.getElementById("end_time").disabled = true;
   }  
}

function DisableTextTimes(){
   if (document.getElementById("txt_settings_select").selectedIndex==0){
      document.getElementById("start_time").disabled = true;
      document.getElementById("end_time").disabled = true;
   } else {
      document.getElementById("start_time").disabled = false;
      document.getElementById("end_time").disabled = false;
   }
}

function UpdateFriendSettingsReturn(resp){
   if (ParseXML(resp, "UpdateFriendSettings")!="true"){
      alert("An error occured and your settings could not be changed.");
   }
}

function UpdTxtSettings(){
   var start = document.getElementById("start_time").value;
   var end = document.getElementById("end_time").value;
   var fr_link = document.getElementById("fr_link").value;
   var my_link = document.getElementById("link").value;
   var ind = document.getElementById("txt_settings_select").selectedIndex;
   var setting = document.getElementById("txt_settings_select").options[ind].value;
   if (phone==="" && (setting=="Less detailed" || setting=="More detailed")){
       answer = confirm("To be alerted by SMS you need to enter phone number and carrier.  "+
							"Would you like to do this now?");
       if (answer){
          location.href = ("/my_account?iid="+id.toString()); 
       } else {
          document.getElementById("txt_settings_select").selectIndex = 0
       }
   } else {
	   if (setting=="Less detailed"){
	      setting = "Less";
	   } else {
	      if (setting=="More detailed"){
	         setting = "More";
	      } else {
	         setting = "False";
	      }
	   }
   }
   var params = "start_time="+start+"&end_time="+end+"&fr_link="+fr_link+"&my_link="+my_link+"&settings="+setting;
   makePOSTRequest("/fr_update_settings", params, "fr_update_settings");
}

function SaveTextMsgSettings(fSave){
   $("#text_msg_box").animate({opacity:0}, "fast");
   $("#text_msg_box").hide();
   $("#cover").animate({opacity:0}, "slow");
   $("#cover").hide();
   if (fSave){
      ChangeIconToWait();
      UpdTxtSettings();
   }
}

function ChangeIconToFinger(){
   document.body.style.cursor="pointer";
}

function ChangeIconToPointer(){
   document.body.style.cursor="default";
}

function ChangeIconToWait(){
   document.body.style.cursor="wait";
}

function Sleep(iMil){
   var sleeping = true;
   var start = new Date();
   var startTime = start.getTime();
   while (sleeping){
      var current = new Date();
      var newTime = current.getTime();
      if (newTime - startTime > iMil){
         sleeping = false;
      }
   }
}



function ClearTextArea(){
	document.getElementById("comment").style.background= "url(/img_files/shoutnotxt.jpg)";
}

function SwitchFbButton(){
	document.getElementById("fbconn").style.display = "none";
	document.getElementById("fbconndown").style.display = "block";
}

function HideBTID(){
	document.getElementById('btid_msg').style.display='none';
	setCookie('btid_msg',"False",10);
}

function GetCookie(check_name) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false;
	for (i = 0; i < a_all_cookies.length; i++){
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if ( cookie_name == check_name ){
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 ){
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			return cookie_value;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found){
		return null;
	}
}



function findLivePageHeight(){
   if(window.innerHeight){
      return window.innerHeight;
   }
   if(document.body.clientHeight){
      return document.body.clientHeight;
   } 
   return null;
}

function findLivePageWidth(){
   if(window.innerWidth){
      return window.innerWidth;
   }
   if(document.body.clientWidth){
      return document.body.clientWidth;
   }
   return null;
}

function darkenCover(fInitMap,event, location, my_time, lat, longitude, address){
   try{
      objectCover.style.display = "block";
      objectCover.style.height = $(document).height()+"px";
      $("#cover").animate({
         opacity:.65}, "slow", function(){
            InitGoogMap(fInitMap,event, location, my_time, lat, longitude, address);
         }
      );
   }catch(e){}
}

function xWindowHeight(){
var b=0,c=document,a=window;
  if((!c.compatMode||c.compatMode=="CSS1Compat") && c.documentElement && c.documentElement.clientHeight){
     b=c.documentElement.clientHeight;
  } else {
     if(c.body&&c.body.clientHeight){
        b=c.body.clientHeight;
     } else {
        if(xDef(a.innerWidth,a.innerHeight,c.width)){
           b=a.innerHeight;
           if(c.width>a.innerWidth){
              b-=16;
           }
        }
     }
  }
  return b;
}


function xDef(){
   var a;
   for(a=0;a<arguments.length;++a){
      if(typeof(arguments[a])=="undefined"){
         return false;
      }
   }
   return true;
}

function InitGoogMap(fInitMap,event, location, my_time, lat, longitude, address){
   
   if (fInitMap){
      $("#frame_bg").show("slow");
      $("#slideFrame").show("show");
      $("#frame_pic").show("show", 
         function(){
            InitMap(lat, longitude);
         }
      );
      google.maps.event.trigger(map, 'resize');
   }
   return false;
}

function loadjsfile(filename){ 
   var fileref=document.createElement('script');
   fileref.setAttribute("type","text/javascript");
   fileref.setAttribute("src",filename);
}

function initCover(){
   objectCover=document.getElementById('cover');
}

function findGeoProvider(){
   if(navigator.geolocation){
      return navigator.geolocation;
   }
   try{
      var geo=google.gears.factory.create('beta.geolocation');
      if(geo){
         return geo;
      }
   }catch(err){

   }
   if(typeof GearsFactory!='undefined'){
      factory=new GearsFactory();
   }return null;
}

function useOtherIPService(sid,ipa,lat,longitude){
   var browserid=GetCookie("browserid");
   var time_dst=calculate_time_zone();
   var time_array=time_dst.split(",");
   if (gEntry<10){
      gEntry += 1;
      makePOSTRequest("/ajax_lat_entry","sid="+sid+"&ip_address="+ipa+"&lat="+
      					lat+"&long="+longitude+"&browserid="+browserid+"&gmt_offset="+
      					time_array[0]+"&dst="+time_array[1],"");
   }
}

function enterMyLatLong(ipa,lat,longitude,address,city,state,country,accuracy,serv_level){
   try{
      var browserid=GetCookie("browserid");
      var time_dst=calculate_time_zone();
      var time_array=time_dst.split(",");
	  if (gEntry<10){
	  	 gEntry += 1;
         makePOSTRequest("/ajax_lat_entry","sid="+sid+"&ip_address="+ipa+"&lat="+lat+
         				   "&long="+longitude+"&address="+address+"&city="+city+"&state="+
         				   state+"&country="+country+"&accuracy="+accuracy+"&service_level="+
         				   serv_level+"&browserid="+browserid+"&gmt_offset="+time_array[0]+
         				   "&dst="+time_array[1],"");
      }
   }catch(e){}
}

function getAddress(latlng, address, city, state, country, my_accuracy){
   if(latlng!==null){
      lat=latlng.coords.latitude;
      longitude=latlng.coords.longitude;
      try{
         //var geocoder=new GClientGeocoder();
         enterMyLatLong(ipa,lat,longitude,address,city,state,country,my_accuracy,"1");
      }catch(err){
         try{
            enterMyLatLong(ipa,lat,longitude,address,city,state,country,my_accuracy,"1");
         }catch(err2){
            //useOtherIPService(sid,ipa,"","");
         }
      }
   }else{
      //useOtherIPService(sid,ipa,"","");
   }
}

function foundLocation(position){
   lat=position.coords.latitude;
   longitude=position.coords.longitude;
   try{
      document.getElementById("longitude").value = longitude;
      document.getElementById("lat").value = lat;
   }catch(e){}
   my_accuracy=position.coords.accuracy;
   try{
      address=position.gearsAddress.streetNumber+" "+position.gearsAddress.street;
   }catch(err1){
      address="";
   }try{
      city=position.gearsAddress.city;
   }catch(err2){
      city="";
   }try{
      state=position.gearsAddress.region;
   }catch(err3){
      state="";
   }try{
      country=position.gearsAddress.country;
   }catch(err4){
      country="";
   }
   time_zone=calculate_time_zone();
   tz_array=time_zone.split(",");
   getAddress(position, address, city, state, country, my_accuracy); 
}

function noLocation(){
   useOtherIPService(sid,ipa,"","");
}

function RunOnce(){
   if(RunTimes == 1){
      //alert("first time");
   	  RunTimes++;
      return true;
   } else if(RunTimes==undefined) {
      RunTimes = 2;
      return true;
   } else {
      //alert("not first time: "+RunTimes);
      RunTimes++;
      return false;
   } 
}

function findLocation(ip_address,id_code){
   sid=id_code;
   ipa=ip_address;
   if (RunOnce()){
	   var mygeo=findGeoProvider();
	   if(mygeo){
	      try{
	         //alert("watching position");
	         mygeo.getCurrentPosition(foundLocation,noLocation,{enableHighAccuracy:true,gearsRequestAddress:true});
	         //mygeo.watchPosition(foundLocation,noLocation,{enableHighAccuracy:true,gearsRequestAddress:true});
	      }catch(err){
	         //alert("getting current position");
	         mygeo.getCurrentPosition(foundLocation,noLocation,{enableHighAccuracy:true,gearsRequestAddress:true});
	      }
	   }else{
	      if (ipa!=""){
	         useOtherIPService(sid,ip_address,"","");
	      }
	   }
   }
}

function LoadSignup(){
   //document.signup.email.focus();
   try{
      document.signup.file.value="";
   }catch(e){}
   initCover();
   SetMyTZ();
}

function LoadFBSignup(){
   SetMyTZ();
}

function isWindows(){
   if(GetOSName()=="Windows"){
      return true;
   }else{
      return false;
   }
}

function LoadSignupLoc(){ 
   if (isWindows()){
      try{
         document.loc_signup.loc_name.focus();
         document.loc_signup.img_name.value="";
      }catch(e){}
      initCover();
   }else{
      alert("Currently, being an OlderSibling locator is only fully tested on "+
      		"Windows computers. While it should work on Linux and Mac, "+
      		"it may still contain bugs.  Procede at your discretion.");
   }
}

function lightenCover(){
   $("#cover").animate({
      opacity:0}, "fast", function(){
         hideCover();
      }
   );
}

function hideCover(){
   objectCover.style.display = "none";
}

function initialize(point){
   var map_area=document.getElementById("map_canvas");
   var map_cell=document.getElementById("map_cell");
   map_cell.style.height='300px';
   map_cell.style.width='500px';
   map_area.style.height='300px';
   map_area.style.width='500px';
   var latlng = new google.maps.LatLng(point.lat(), point.lng());
   var myOptions = {
      zoom: 17,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };
   var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
   var marker = new google.maps.Marker({
       position: latlng, 
       map: map
   }); 
}

function GetCoord(address){
   var geocoder1 = new google.maps.Geocoder();
   geocoder1.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
         var point = results[0].geometry.location;
         initialize(point);
       }
   });
}

function initializeMobile(lat,longitude){
   var map_area=document.getElementById("map_canvas");
   var map_cell=document.getElementById("map_cell");
   map_cell.style.height='300px';
   map_cell.style.width='500px';
   map_area.style.height='300px';
   map_area.style.width='500px';
   if(GBrowserIsCompatible()){
      var map=new GMap2(map_area);
      map.setMapType(G_NORMAL_MAP);
      map.addControl(new GLargeMapControl());
      map.setCenter(new GLatLng(lat,longitude),12);
      var point=new GLatLng(lat,longitude);
      var marker=new GMarker(point);
      map.addOverlay(marker);
      var accuracy=document.getElementById("accuracy");
      accuracy.innerHTML="<b>*This location was determined by the user's last IP Address which may"+
                         " not be accurate.</b>";
   }
}

function downloadLoc(){
	//the only difference should be the "start as service" call
	var ostype = GetOSName();
	switch(ostype){
		case "":
			reNavigate("http://oldersibling.com/OSInstaller.exe");
			break;
		case "Windows":
			reNavigate("http://oldersibling.com/OSInstaller.exe");
			break;	
		case "MacOS":
			reNavigate("http://oldersibling.com/OSInstallerMac.app");
			break;
		case "Linux":
			reNavigate("http://oldersibling.com/OSInstaller.exe");
			break;
		default:
			reNavigate("http://oldersibling.com/OSInstallerLinux.exe");
			break;
	}
}

function reNavigate(url){
	document.location.href = url;
	setTimeout('delayer()',6000);
}

function delayer(){
	//alert("in delayer");
	document.getElementById('location2').style.display = 'none';
	document.getElementById('location3').style.display = 'block';
}

function GetFileType(filename){
	var name_len = filename.length;
	var ext = filename.substring(name_len-4);
	var ext4 = filename.substring(name_len-5);
	if (ext4==".jpeg"){
		ext = ".jpg";
	}	
	//alert("filetype = "+ext);
	return ext;
}

function BuildFormList(fInd, fSignin){
	// put all the information in an array so it can be POSTed
	var my_email;
	var my_first;
	var my_last;
	var btid;
	var tz;
	var postArray = new Array();
	if (fInd){
		if (fSignin){
			my_email = document.getElementById("email").value;
			my_first = document.getElementById("first").value;
			my_last = document.getElementById("last").value;
			var pwd = document.getElementById("pwd").value;
			btid = document.getElementById("BTID").value;
			tz = document.getElementById("timezone").value;
			var loc_name = document.getElementById("loc_name").value;
		    postArray[0] = "email="+my_email;
		    postArray[1] = "first="+my_first;
		    postArray[2] = "last="+my_last;
		    postArray[3] = "pwd="+pwd;
		    postArray[4] = "BTID="+btid;
		    postArray[5] = "loc="+loc_name;
		    postArray[6] = "timezone="+tz;
		    return postArray;
		} else {
			//alert("buildFormList");
			my_email = document.getElementById("email").value;
			my_first = document.getElementById("first").value;
			my_last = document.getElementById("last").value;
			//var pwd = document.getElementById("pwd").value;
			btid = document.getElementById("BTID").value;
		    postArray[0] = "email="+my_email;
		    postArray[1] = "first="+my_first;
		    postArray[2] = "last="+my_last;
		    postArray[3] = "session="+document.getElementById("session").value;
		    //postArray[3] = "pwd="+pwd;
		    postArray[4] = "btid="+btid;
		    postArray[5] = "address1="+document.getElementById("address1").value;
		    postArray[6] = "address2="+document.getElementById("address2").value;
		    postArray[7] = "city="+document.getElementById("city").value;
		    postArray[8] = "state="+document.getElementById("state").value;
		    postArray[9] = "zip="+document.getElementById("zip").value;
		    postArray[10] = "country="+document.getElementById("country").value;
		    postArray[11] = "phone1="+document.getElementById("phone1").value;
		    postArray[12] = "phone2="+document.getElementById("phone2").value;
		    postArray[13] = "phone3="+document.getElementById("phone3").value;
		    postArray[14] = "carrier="+document.getElementById("carrier").value;
		    postArray[15] = "quote="+document.getElementById("quote").value;
		    //alert("Exiting build form list");
		    return postArray;
		}
	} else {//location
		if (fSignin){
			//alert("location signin");
			postArray[0] = "loc_name="+document.getElementById("loc_name").value;
			postArray[1] = "loc_password="+document.getElementById("loc_password").value;
			postArray[2] = "address1="+document.getElementById("address1").value;
			//postArray[3] = "address2="+document.getElementById("address2").value;
		    postArray[3] = "city="+document.getElementById("city").value;
		    postArray[4] = "state="+document.getElementById("state").value;
		    //postArray[5] = "zip="+document.getElementById("zip").value;
		    postArray[5] = "country="+document.getElementById("country").value;
		    postArray[6] = "loc_type="+document.getElementById("loc_type").value;
		    postArray[7] = "loc_device_type="+document.getElementById("loc_device_type").value;
		    //postArray[10] = "os_type="+document.getElementById("os_type").value;
		    postArray[8] = "timezone="+document.getElementById("timezone").value;
		    
		    //alert("return");
		    return postArray;
		} else {
			//alert("Updating your location");
			postArray[0] = "loc_name="+document.getElementById("loc_name").value;
			postArray[1] = "email="+document.getElementById("email").value;
			postArray[2] = "address1="+document.getElementById("address1").value;
		    postArray[3] = "address2="+document.getElementById("address2").value;
		    postArray[4] = "city="+document.getElementById("city").value;
		    postArray[5] = "state="+document.getElementById("state").value;
		    postArray[6] = "zip="+document.getElementById("zip").value;
		    postArray[7] = "country="+document.getElementById("country").value;
		    postArray[8] = "loc_type="+document.getElementById("loc_type").value;
		
			try{
			    postArray[9] = "loc_device_type="+document.getElementById("loc_device_type1").value;
			}catch(err){
				
			}
			try{
			    postArray[10] = "timezone="+document.getElementById("timezone").value;
			}catch(err1){

			}
		    postArray[11] = "update=true";
		    postArray[12] = "session="+document.getElementById("session").value;
		    postArray[13] = "comment="+document.getElementById("comment").value;
			
		    return postArray;
		}
	}
	//alert("exiting BuildList");
}

function LimitPwCharacters(sTest, sName, element){
    var i;
	var lLen = sTest.length;
	var sChars = new RegExp("[a-zA-Z0-9_!@#$%^*().,]");
	for (i=0;i<lLen;i++){
		if (sChars.test(sTest.substring(i,i+1))){
			
		} else {
			alert("Sorry, but your "+sName+" contains an illegal character. You can only "+
					"use letters, numbers, _, !, @, #, $, %, ^, *, (, ), ., and commas.");
			document.getElementById(element).style.background = "Yellow";
			document.getElementById(element).focus();
			return false;
		}
	}
	return true;
}

function verify() {
	//alert("verifying");
	var form = document.signup;
	if (LimitPwCharacters(form.pwd.value, "password", "pwd")){
	    if (form.first.value+" "+form.last.value!=" "){
			if (form.pwd.value!=form.pwd2.value) {
		        form.pwd.style.background = 'Yellow';
		        form.pwd2.style.background = 'Yellow';
		        form.pwd.focus();
		        alert("Your passwords do not match.");
		        return false;
		    } else {
		        if (form.pwd.value.length<6){
		            form.pwd.style.background = 'Yellow';
		            form.pwd2.style.background = 'Yellow';
		            form.pwd.focus();
		            alert("Your password must be at least 6 characters long.");
		            return false;
		        } else {
		        	try{
		        		form.BTID.value = form.BTID.value.replace(/:/g,"");
		        		//alert("replace");
		            } catch (err){}
		            if (BTcheck(form.BTID.value)){
		                if (form.agree.checked==1){
		                    return true;
		                } else {
		                    alert("You must agree to the terms of service to sign up for OlderSibling.");
		                    return false;
		                }
		            } else {
		                return false;
		            }
		        }
		    }
	    } else {
	    	alert("Please enter a name.");
	    	form.first.style.background = "Yellow";
	    	form.last.style.background = "Yellow";
	    	form.first.focus();
	    	return false;
	    }
	}
	return false;
}

function ShowLocAddress(){
	var disp = "";
	if (document.loc_signup.loc_device_type.value == "stationary"){
		disp = "block";
	} else {
		disp = "none";
	}
	document.getElementById('address1').style.display = disp;
	document.getElementById('city').style.display = disp;
	document.getElementById('state').style.display = disp;
	document.getElementById('country').style.display = disp;
	
	document.getElementById('street_label').style.display = disp;
	document.getElementById('city_label').style.display = disp;
	document.getElementById('state_label').style.display = disp;
	document.getElementById('country_label').style.display = disp;
}

function LimitCharacters(sTest, sName, element){
	var i;
	var lLen = sTest.length;
	var sChars =new RegExp("[a-zA-Z0-9_ \']");
	for (i=0;i<lLen;i++){
		if (sChars.test(sTest.substring(i,i+1))){
			
		} else {
			alert("Sorry, but your "+sName+" contains an illegal character. You can only "+
					"use letters, numbers, underscores, single quotes, and spaces.");
			document.getElementById(element).style.background = "Yellow";
			document.getElementById(element).focus();
			return false;
		}
	}
	return true;
}

function GetPostResponse(response){
	//alert("response="+response);
	//alert("gfInd="+gfInd+", gfSignup="+gfSignup);
	var date = new Date();
	date.setTime(date.getTime()+(30*24*60*60*1000*61)); //5 years
	//var expires = "; expires="+date.toGMTString();
	if (gfInd){
		if (gfSignup){
			var cookie=ParseXML(response,"cookie");
			var lid = ParseXML(response,"lid");
			if (lid==""){
				document.location.href="/load_welcome?sid="+cookie;
			}else{
				document.location.href="/location_download?sid="+cookie+"&lid="+lid;
			}
		} else {
			document.location.href="/ih";
		}
	} else {
		if (gfSignup){
			//alert("right path");
			var lsid = ParseXML(response, "lsid");
			document.location.href="/location_download?lid="+lsid;
		} else {
			//alert("done");
			var link = ParseXML(response, "link");
			if (link!="" || link!="None"){
			   document.location.href="/loc?loc="+link;
			} else {
			   document.location.href="/ih";
			}
		}
	}
}

function GetDataUrl(fInd, fSignup){
	if (fInd){
		if (fSignup){
			//alert("url=http://oldersibling.appspot.com/welcome");
			return "/welcome";
		} else {
			return "/my_accountUpd";
		}	
	} else {
		if (fSignup){
			return "/location_data_entered";
		} else {
			//alert("/location_data_entry");
			return "/location_data_entry";
		}
	}	
}

function ReqLoc(btid, loc_id){
    makePOSTRequest("/loc_req", "btid="+btid+"&loc_id="+loc_id, "ReqLoc");
}

function ReqLocReturn(response){
	alert("Done");
	if (ParseXML(response, "loc_req")=="true"){
       $("#request").animate({
          opacity:0}, "slow"
       );
    }
}

function submitDataNoPic(my_element_array) {
    var parameters="";
    for (x=0;x< my_element_array.length;x++){
    	parameters+=PercentEncode(my_element_array[x])+"&";
    }
    var input_url = GetDataUrl(gfInd, gfSignup);
    makePOSTRequest(input_url, parameters, "GetPostResponse");
    return true;
}

function GetForm(fInd, fSignup){
	//alert("in GetForm find="+fInd+", fSignup="+fSignup);
	if (fInd){
		if (fSignup){
			//alert("GetForm: document.signup");
			return document.signup;
		} else {
			return document.update_ind;
		}	
	} else {
		if (fSignup){
			return document.loc_signup;
		} else {
			return document.loc_upd;
		}
	}
}

function pleaseWait(fInd, fSignup){
	//alert("PleaseWait");
	try{
	    darkenCover(false);
	} catch(cover_err){}
	try{
		gfInd = fInd;
		gfSignup = fSignup;
		document.body.style.cursor="auto";
		document.getElementById('btid_box').style.display = 'none';
    } catch (err) {
    	//alert("pleaseWait error1"+err.message);
    }
    try{
	    var objectWait = document.getElementById('please_wait');
	    var objectWaitFrame = document.getElementById('please_wait_frame');
	    var scrollTop = $(window).scrollTop();
		var win_height = $(window).height();
		var str_top = (scrollTop + (win_height - 131)/2)+'px';
		//alert("scrollTop: "+scrollTop+"; win_height: "+win_height+"; str_top: "+str_top);
	    var str_left = (((findLivePageWidth()/2))-101)+'px';
	    objectWaitFrame.style.verticalAlign="top";
	    objectWaitFrame.style.left=str_left;
	    objectWaitFrame.style.top=str_top;
	    objectWaitFrame.style.display='block';
	    objectWaitFrame.style.zIndex = 110;
	    try{
	       objectWaitFrame.style.opacity = 1;
	    }catch(e){}
	    try{
	       objectWaitFrame.style.filter = 'alpha(opacity='+100+')';
	    }catch(e){}
	    objectWait.style.width='203px';
	    objectWait.style.height='131px';
	    objectWait.style.display='block';
	    objectWait.style.zIndex = 110;
	    try{
	       objectWait.style.opacity = 1;
	    }catch(e){}
	    try{
	       objectWait.style.filter = 'alpha(opacity=100)';
	    }catch(e){}
	} catch (err1){
		//alert("pleaseWait error2"+err1.message);
	}
	try{
		var my_form = GetForm(fInd, fSignup);
		var blob_name = "";
		try{
			blob_name = my_form.file.value;
		} catch(bloberr){}
		try{
			my_form.submit();
		} catch(errh){
			my_form.submit.click();
		}
    } catch (err2){
    	alert("pleaseWait error3"+err2.message);
    }
}

function IsUniqueLocName(result){
	var fContinue = false;
	var fContinue2 = false;
            var unique = ParseXML(result, "unique");
            if (unique == "Yes"){
            	   fContinue = true;
            } else {
            	   fContinue2 = true;
            }
	if (fContinue){
		//alert("email is unique");
		pleaseWait(gfInd,gfSignup);
	} else {
		if (fContinue2){
			document.getElementById("loc_name").style.background = 'Yellow';
			var loc_name = ParseXML(result, "loc_name");
			alert("The location with the name \""+loc_name+"\" has already been signed up to OlderSibling.");
		}
	}	
}

function CheckLocName(name) {
   makePOSTRequest("/check_loc_name", "name="+name, "IsUniqueLocName");
}

function ValidateLoc(){
    //var form = document.loc_signup;
    //alert("timezone"+document.loc_signup.timezone.value);
	if (document.getElementById("not_unique").innerHTML!="okay"){
	    alert("Please select a different location name.");
	    return false;
	}
    if (LimitCharacters(document.getElementById("loc_name").value,"location name","loc_name")){
    	if (LimitPwCharacters(document.getElementById("loc_password").value, "password", "loc_password")){
	
		    if (document.loc_signup.loc_name.value.length<4){
		        document.loc_signup.loc_name.style.background = 'Yellow';
		        document.loc_signup.loc_name.focus();
		        alert("Please enter a location name that is at least 4 characters long.");
		        return false;
		    }
		    if (document.loc_signup.loc_password.value!=document.loc_signup.confirm_loc_password.value) {
		        document.loc_signup.loc_password.style.background = 'Yellow';
		        document.loc_signup.confirm_loc_password.style.background = 'Yellow';
		        document.loc_signup.loc_password.focus();
		        alert("Your passwords do not match.");
		        return false;
		    }
		    if (document.loc_signup.loc_password.value.length<6){
		        document.loc_signup.loc_password.style.background = 'Yellow';
		        document.loc_signup.loc_password.focus();
		        alert("Your password must be at least 6 characters long.");
		        return false;
		    }
		    if (document.loc_signup.loc_type.value===""){
		        document.loc_signup.loc_type.style.background = 'Yellow';
		        document.loc_signup.loc_type.focus();
		        alert("Please choose a location type.");
		        return false;
		    }
		    if (document.loc_signup.loc_device_type.value===""){
		        document.loc_signup.loc_device_type.style.background = 'Yellow';
		        document.loc_signup.loc_device_type.focus();
		        alert("Please choose a device type.");
		        return false;
		    }
		    if (document.loc_signup.agree.checked!=1){
		        alert("You must agree to the terms of service.");
		        return false;
		    }
		    gfInd = false;
		    gfSignup = true;
		    CheckLocName(document.loc_signup.loc_name.value);
    	}
    }
}

function ValidateLocUpd(){
    pleaseWait(false, false);
}

function IsUniqueEmail(result){
	var fContinue = false;
	var fContinue2 = false;
            var unique = ParseXML(result, "unique");
            if (unique == "Yes"){
            	   fContinue = true;
            } else {
            	   fContinue2 = true;
            }
	if (fContinue){
		//alert("email is unique");
		if (verify()){
			pleaseWait(gfInd,gfSignup);
		}
	} else {
		if (fContinue2){
			document.signup.email.style.background = 'Yellow';
			var email = ParseXML(result, "email");
			alert("The email \""+email+"\" has already been signed up to OlderSibling.");
		}
	}	
}

function checkEmail(email) {
   makePOSTRequest("/check_email", "email="+email, "IsUniqueEmail");
}

function verifyFBSignin(){
	var form = document.signup;
	var myLocName = document.getElementById('loc_name').value;
	//alert("locname="+myLocName);
	if (trim(myLocName)!=""){
	   	if (document.getElementById('not_unique').innerHTML!= "okay"){
	   	   alert("Please select a unique location name that is at least "+
	   	         "4 letters long, or leave the Location Name blank.");
	   	   return false;
	   	} else {
	   	    if (LimitPwCharacters(document.getElementById("pwd").value, "password", "pwd")){
		   	    if (document.getElementById("pwd").value!=document.getElementById("pwd2").value){
		   			alert("Your passwords do not match.");
		   			document.getElementById("pwd").focus();
		   			return false;
		   		} else {
		   		   if (document.getElementById("pwd").value.length<6){
		   		      alert("Your password must be at lease 6 characters long.");
		   		      document.getElementById("pwd").focus();
		   		      return false;
		   		   }
		   		}
		   	}else{
		   	   return false;
		   	}
	   	}
	}
    try{
		form.BTID.value = form.BTID.value.replace(/:/g,"");
    } catch (err){}
    if (BTcheck(form.BTID.value)){
        if (form.agree.checked==1){
            
        } else {
            alert("You must agree to the terms of service to sign up for OlderSibling.");
            return false;
        }
    } else {
        return false;
    }
    form.submit();
}

function verifyEmail() {
	gfInd=true;
	gfSignup = true;
	var myLocName = document.getElementById('loc_name').value;
	if (trim(myLocName)!=""){
	   	if (document.getElementById('not_unique').innerHTML!= "okay"){
	   	   alert("Please select a unique location name that is at least 4 letters long, or leave the Location Name blank.");
	   	   return false;
	   	} else {}
	}
	document.body.style.cursor="wait";
	var email = document.getElementById("email").value;
    var emailmsg = "Please enter a valid email.";
    var elec = email.split("@");
    try{
	    if (elec.length!=2){
	        alert(emailmsg);
	        return false;
	    }
	    else{
	        if ((elec[0].length<1) || (elec[1].length<1)){
	            alert(emailmsg);
	            return false;
	        }
	    }
	    var edot = elec[1].split(".");
	    if ((edot[0].length<1) || (edot[1].length<1)){
	        alert(emailmsg);
	        return false;
	    }else{
			gfInd = true;
			gfSignup = true;
			checkEmail(email);
	    }
	} catch(err){
	   alert(err.name + ": "+err.message);
	   return false;
	}
}

function VerifyAccount() {
	//alert("Verify Account");
	document.body.style.cursor="wait";
	//var form = document.update_ind;
	pleaseWait(true, false);
}

function CheckPwd(result){
   var check = ParseXML(result, "check");
   if (check=="checked"){
      pleaseWait(true, false);
   } else {
      alert("There was an error verifying your email and password.");
   }
}

function IsUniqueLocNameIndividual(result){
	var fContinue = false;
	var fContinue2 = false;
	try{
	            var unique = ParseXML(result, "unique");
	            if (unique == "Yes"){
	            	   fContinue = true;
	            } else {
	            	   fContinue2 = true;
		}
		var locName="";
		if (fContinue){
			locName = ParseXML(result, "loc_name");
			if (locName == gsLocName){
				document.getElementById("spinner").style.display = "none";
				document.getElementById("not_unique").style.display = "block";
				document.getElementById("not_unique").innerHTML = "okay";
			}
		} else {
			if (fContinue2){
				locName = ParseXML(result, "loc_name");
				if (locName == gsLocName){
					document.getElementById("spinner").style.display = "none";
					document.getElementById("not_unique").style.display = "block";
					document.getElementById("not_unique").innerHTML = "This location name has already been registered.";
				}
			}
		}
	}catch(e){
	   	alert("error: "+e.description);
	}
}



function CheckLocNameIndividual(name) {
   makePOSTRequest("check_loc_name", "name="+name, "IsUniqueLocNameIndividual")
}

function CheckUniqueLocName(){
	var locName = document.getElementById('loc_name').value;
	gsLocName = locName;
	if (trim(locName).length>=4){
		//alert("loc name="+locName);
		document.getElementById('spinner').style.display = "block";
		document.getElementById('not_unique').style.display = "none";
		CheckLocNameIndividual(locName);
	} else {
		document.getElementById('not_unique').innerHTML = "Please select a unique location name "+
			"(that is at least 4 letters long).";
		document.getElementById('spinner').style.display = "none";
		document.getElementById('not_unique').style.display = "block";
		
	}
}

function checkEmailPwd(email, pwd){
   makePOSTRequest("/check_email_pwd", "email="+email+"&pwd="+pwd, "CheckPwd");	
}

function calculate_time_zone() {
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
	var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	temp = june1.toGMTString();
	var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
	var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
	var dst;
	if (std_time_offset == daylight_time_offset) {
		dst = "0"; // daylight savings time is NOT observed
	} else {
		// positive is southern, negative is northern hemisphere
		var hemisphere = std_time_offset - daylight_time_offset;
		if (hemisphere >= 0){
			std_time_offset = daylight_time_offset;
		}
		dst = "1"; // daylight savings time is observed
	}
	var i;
	// check just to avoid error messages
	return convert(std_time_offset)+","+dst;
}

function SetMyTZ(){
	var tz = calculate_time_zone();
	document.getElementById("timezone").value = tz;
}
	
function GetTimeZone(gmt_offset, dst){
	var i;
	var time_val = "";
	if (gmt_offset!=-1){   
		//its already been set
		time_val = gmt_offset+","+dst;
	} else {
		time_val = calculate_time_zone();
	}
	for (i = 0; i < document.getElementById('timezone').options.length; i++) {
		if (document.getElementById('timezone').options[i].value == time_val) {
			document.getElementById('timezone').selectedIndex = i;
			break;
		}
	}
}

function convert(value) {
	var hours = parseInt(value,10);
   	value -= parseInt(value,10);
	value *= 60;
	var mins = parseInt(value,10);
   	return hours + (mins/60);
}

function changeSort(){
   var sortby = document.getElementById("sortby").value;
   setCookie("alpha_sort", sortby, 10);
   location.href = ("/if"); 
}

function ShowCommentForm(parent_id, str_count){
   ShrinkCommentForms();
   $('#comment_message'+str_count).hide("slow");
   $('#message_inner_div'+str_count).show("fast");
   if (str_count=="0"){
      var new_height;
      if ($("#new_table_row").height()!=0){
         new_height = $("#new_table_row").height()+89; 
         $("#new_table_row").animate({
               height:new_height
            }, "slow"
         );
      } else {
         new_height = $("#new_table_row_today").height()+89; 
         $("#new_table_row_today").animate({
               height:new_height
            }, "slow"
         );
      }
   }
   $('#message_inner_div'+str_count).animate({
         height: 89,
         opacity:0
      }, "slow", function(){
         ShowTextArea(parent_id, str_count);
      }
   );
} 

function ShowTextArea(parent_id, str_count){
   var new_comment_html = "<div id='message_inner_div"+str_count+"'>";
   new_comment_html += "<form name='new_comment"+parent_id+"' action='/shout'"+
                               " method='post'>";
   new_comment_html += "<table border='0' width='100%'>";
   new_comment_html += "<tr><td width='100%' style='width:100%;'>";
   new_comment_html += "<textarea name='comment' id='comment"+parent_id+"' class='shout_area' "+
                            "rows='3' style='width:98%;' onFocus='this.className=\"no_text\";'>";
   new_comment_html += "</textarea></td></tr>"; 
   new_comment_html += "<tr><td style='text-align:right;width:100%;'>"+
                            "<input type='button' value='Submit' "+
                            "onClick='SubmitComment("+str_count+",\""+parent_id+"\")'/>";
   new_comment_html += "</td></tr>";
   new_comment_html += "<tr><td style='height:5px'></td></tr>";
   new_comment_html += "</table></form>";
   new_comment_html += "</div><br/>";	
   try{
      document.getElementById('#message_inner_div'+str_count).style.opacity = (0);
   }catch(e){}
   try{
      document.getElementById('message_inner_div'+str_count).style.filter = 'alpha(opacity=0)';
   }catch(e){}
   document.getElementById('message_inner_div'+str_count).innerHTML= new_comment_html;
   $('#message_inner_div'+str_count).animate({
             opacity:1}, "slow");
}

function ShrinkCommentForms(){
//find out if there is a comment form open
//if there is, then shrink it
   var i;
   var element_height;
   $(".plus").show("slow");
   for (i=-1;i<20;i++){
      try{
         try{
            element_height = $("#message_inner_div"+i).height();
         } catch(eh){
            element_height = 0;
         }
         if (element_height!=0 && element_height!=null){
            break;
         }    
      } catch (e) {
         alert("shrinkCommentForms error: "+e.description);
      }
   }
   var j = i;
   try{
      if (j==0){
         var new_height;
         if ($("#new_table_row").height()!=0){
            new_height = $("#new_table_row").height() - 89;
            $("#new_table_row").animate({height:new_height}, "slow");
         } else {
            new_height = $("#new_table_row_today").height() - 89;
            $("#new_table_row_today").animate({height:new_height}, "slow");
         }
      }
      $("#message_inner_div"+j).animate({opacity:0},"slow",
         function(){
            SetToBlankAndShrink("#message_inner_div"+j);
         }
      );
   }catch (e){
      SetToBlankAndShrink("#message_inner_div"+j);
   }
}

function SetToBlankAndShrink(shr_element){
   $(shr_element).html("");
   $(shr_element).animate({
      height:0},"slow"
   );
}

function SubmitComment(str_count, parent_id){
   // this will enter the new comment in the db as a child of the parent
   // the return function will show the statement, along with the picture
   // and map star(if it's available).
   var new_comment = document.getElementById("comment"+parent_id).value;
   var ind_id = GetCookie("pmgps_session_id");
   var loc_rand_id = GetCookie("lsid");
   var latitude = document.getElementById("lat").value;
   var longitude = document.getElementById("longitude").value;
   var gmt_offset = document.getElementById("gmt_offset").value;
   var dst = document.getElementById("dst").value;
   if (new_comment){
      document.body.style.cursor = "wait";
      new_comment = PercentEncode(new_comment);
      $('#message_inner_div'+str_count).hide("slow", function(){
         PostNewComment('#message_inner_div'+str_count, str_count, parent_id, 
         		latitude, longitude, gmt_offset, dst, new_comment, 
         		loc_rand_id, ind_id);
      });
   }
}
function PostNewComment(shr_element, str_count, parent_id, latitude, longitude,
						gmt_offset, dst, new_comment, loc_rand_id, ind_id){
   makePOSTRequest("/enter_ajax_comment", 
           "count="+str_count+"&parent_id="+parent_id+"&latitude="+latitude+
           "&longitude="+longitude+"&gmt_offset="+gmt_offset+"&dst="+dst+
           "&comment="+new_comment+"&loc_rand_id="+loc_rand_id+"&ind_id="+ind_id,
           "SubmitComment");
   SetToBlankAndShrink(shr_element);
}

function SubmitCommentReturn(response){
   document.body.style.cursor = "default";
   var str_count = ParseXML(response, "str_count");
   var myhtml = trim(ParseXML(response, "comment_html"));
   var old_html = document.getElementById('new_comment'+str_count).innerHTML;
   var my_new_html = (old_html+"<br>"+myhtml).replace(/XXX/g, '"');
   try{
      document.getElementById('new_comment'+str_count).style.opacity = (0);
   }catch(e){}
   try{
      document.getElementById('new_comment'+str_count).style.filter = 'alpha(opacity=0)';
   }catch(e){}
   var new_height = $('#new_comment'+str_count).height()+89;
   try{
      $("#comment_message"+str_count).show("slow");
      $('#new_comment'+str_count).animate({
          height: new_height}, 900, function(){
               ShowNewComment(str_count, my_new_html);
           });
   } catch(e) {
      alert("error SubmitCommentReturn: "+e.description);
   }
}

function ShowNewComment(str_count, new_html){
   $('#new_comment'+str_count).html(new_html);
   $('#new_comment'+str_count).animate({
                opacity:1}, "slow");
}

function ChangeRow(row, new_text){
   //alert("change row: row: "+row+"; new_text:"+new_text);
   $("#"+row).animate({
      opacity:0},"slow",
      function(){
         SwapAndShow(row, new_text);
      }
   );
}

function SwapAndShow(row, new_text){
   $("#"+row).html(new_text);
   $("#"+row).animate({
      opacity:1}, "slow"
   );
}

function RowFound(response){
   if (ParseXML(response, "title")!="500 Server Error"){ 
      var first_row_id = document.getElementById("table_id1").value;
      var new_row = GetLatestRow(response);
      var new_row_id = GetRowID(response);
      return_row = ParseXML(response, "new_row");
      if (new_row_id!=""){
         InitPrettyPhoto();
         if (new_row_id==first_row_id){
            var last_time = document.getElementById("end_time1").value;
            var new_last_time = ParseXML(response, "end_time");
            if (last_time != new_last_time){
               var new_text = ParseXML(response, "td");
               new_text = new_text.replace(/\n/g,"");
               ChangeRow("text_cell_1", new_text);
            }else if(last_time!="the Present"){
               var id_code = GetCookie("pmgps_session_id");
               var fn = "insertRows('"+id_code+"', true)";
               findLocation("", id_code);
               setTimeout(fn, 4000);
            }
         } else {
            var ret_date = ParseXML(response, "new_date");
            ExpandNewRow(ret_date, new_row, new_row_id);
         }
      }
   }
}

function ExpandNewRow(new_date, new_text, row_id){
   var most_recent_date = document.getElementById("date1").innerHTML;
   var f_new_date = false;
   if (new_date!=most_recent_date){
      f_new_date = true;
   }
   if (!f_new_date){ //same day
      $("#new_table_row_today").animate({
         height:89},"slow",
         function(){
            InsertRow("new_table_row_today", new_text);
         }
      );
      var del_row = RowAlreadyExists(row_id);
      if (del_row){
         //alert("remove row: "+row_id);
         RemoveRow(del_row,100);
      }else{
         //alert("not row");
      }
   } else {
      $("#new_table_row").animate({
         height: 80},"slow",
         function(){
            InsertNewDayRow(new_date, new_text);
         }
      );
      $("#my_top_line").animate({opacity:1}, "fast");
   }
}

function InsertNewDayRow(new_date, new_text){
   $("#new_date").animate({
      height:40}, "slow",
      function(){
          InsertRow("new_date", new_date);
      }
   );
   InsertRow("new_table_row", new_text);
   SetOpacity("new_date_row", 0);
   $("#new_date_row").animate({opacity:1}, "slow");
}

function InsertRow(new_row, new_text){
   SetOpacity(new_row,0);
   //alert("inserting row: "+new_text+" into "+new_row);
   $("#"+new_row).html(new_text);
   $("#"+new_row).animate({opacity:1}, "fast");
}

function SetOpacity(my_elm, new_op){
   try{
      document.getElementById(my_elm).style.filter = 'alpha(opacity=' + new_op + ')';
   }catch(e){}
   try{
      document.getElementById(my_elm).style.opacity=new_op/100;
   }catch(e1){}
}

jQuery.fn.highlight = function(selector, className, eventStart, eventEnd){
   var className = className || 'highlight';
   if(eventStart == undefined && eventEnd == undefined){
      var eventStart = 'mouseover';
      var eventEnd = 'mouseout';
   } else if(eventStart == eventEnd || eventStart != undefined && eventEnd == undefined){
      var toggle = true;
   }
   this.each(
      function(){
         var tagName;
         try{
            tagName = this.tagName.toLowerCase();
         }catch(e){
            tagName = '';
         }
            if(tagName == 'form'){
               selector	= selector || 'li';
               var elements = jQuery("textarea, select, multi-select, :text, :image, :password, :radio, :checkbox, :file", this);
               elements.bind('focus', 
                  function(){
                     var parents = jQuery(this).parents(selector);
                     var parent	= jQuery(parents.get(0));
                     parent.addClass(className);
                  }
               );
               elements.bind(
                  'blur', 
                  function(){
                     var parents = jQuery(this).parents(selector);
                     var parent = jQuery(parents.get(0));
                     parent.removeClass(className);
                  }
               );
            } else {
               if(tagName.match(/^(table|tbody)$/) != null){
                  selector = selector || 'tr';
               } else if(tagName.match(/^(ul|ol)$/) != null){
                  selector = selector || 'li';
               } else {
                  selector = '*';
               }
               var elements = jQuery(selector, this);
               if(toggle){
                  elements.bind(
                     eventStart, 
                     function(){
                        if($(this).hasClass(className)){
                           $(this).removeClass(className);
                        } else {
                           $(this).addClass(className);
                        }
                     }
                  );
               } else {
                  elements.bind (
                     eventStart, 
                     function(){
                        $(this).addClass(className);
                     }
                  );
                  elements.bind(
                     eventEnd, 
                     function(){
                        $(this).removeClass(className);
                     }
                  );
               }
            }
         }
      );
   return this;
}

;(function($) {
	$.fn.featureList = function(options) {
		var tabs	= $(this);
		var output	= $(options.output);

		new jQuery.featureList(tabs, output, options);

		return this;	
	};

	$.featureList = function(tabs, output, options) {
		function slide(nr) {
			if (typeof nr == "undefined") {
				nr = visible_item + 1;
				nr = nr >= total_items ? 0 : nr;
			}

			tabs.removeClass('current').filter(":eq(" + nr + ")").addClass('current');

			output.stop(true, true).filter(":visible").fadeOut();
			output.filter(":eq(" + nr + ")").fadeIn(function() {
				visible_item = nr;	
			});
		}

		var options			= options || {}; 
		var total_items		= tabs.length;
		var visible_item	= options.start_item || 0;

		options.pause_on_hover		= options.pause_on_hover		|| true;
		options.transition_interval	= options.transition_interval	|| 5000;

		output.hide().eq( visible_item ).show();
		tabs.eq( visible_item ).addClass('current');

		tabs.click(function() {
			if ($(this).hasClass('current')) {
				return false;	
			}

			slide( tabs.index( this) );
		});

		if (options.transition_interval > 0) {
			var timer = setInterval(function () {
				slide();
			}, options.transition_interval);

			if (options.pause_on_hover) {
				tabs.mouseenter(function() {
					clearInterval( timer );

				}).mouseleave(function() {
					clearInterval( timer );
					timer = setInterval(function () {
						slide();
					}, options.transition_interval);
				});
			}
		}
	};
})(jQuery);
