// ----------------------------------------------------------------------------------------------------
/*

   Version: DVF v2.26.120103

   Program: vnd_general.js

   Author:  James Whitfield
   Date:    11 August 2007

   Description:
   General functionality.

   Amendments:

   07/12/08  Included 'ViewVideoTour' function.
   14/12/08  Included 'ConfirmAction' function.
   28/03/09  Included 'trim' function.
   28/05/09  Amended 'OrderListByNearestTo' to recognise filter parameters.
   28/06/09  Removed requirements filtering and nearest to separate file.  Added 'GotoAnchor'.
   01/05/10  Recognise specific browsers - not just generic names.
   21/08/10  Added in Property Basket cookie functionality.
   28/08/10  Included 'GetBrowser'.
   29/08/10  Included 'grayOut'.
   06/09/10  Included 'GetPropertyRefFromURL'.
   10/09/10  Amended 'SetBrowserSpecific' to reference 'noautoresize' hidden field.
   24/10/10  Renamed 'basket' to 'shortlist'.
   18/11/10  Included 'LoadPage'.
   01/01/11  Check for column widths of 150 characters in 'SetBrowserSpecific'.
   11/02/11  Included 'ViewCalendar' function.
   25/02/11  Expanded IE (33 cols) from 40 cols to 48 cols.
   13/03/11  Correct CR/LF issue with Firefox for mandatory fields.
   08/04/11  Included widest textarea widths.
   12/04/11  Included 'ManageUserLoginDetails'.
   21/05/11  Included 'IsValidEmailAddress'.
   23/09/11  Included 'PreloadImages'.
   15/10/11  Included 'h2' tags in 'LoadPage'.
   31/10/11  Amend 'ManagePropertyShortlist'
   12/11/11  Included 'ManageRequestDetails'.
   30/12/11  Included 'ShowCommunityMap'.
   03/01/12  Included 'LikeFacebook'.

*/
// ----------------------------------------------------------------------------------------------------



// ====================================================================================================

function chr(ascii) { return String.fromCharCode(ascii) };

function trim(string1) { return string1.replace(/(^\s*)|(\s*$)/gi,"") };

// ====================================================================================================

function GetBrowser() {
  var browserName=  navigator.appName; 
  var browserAgent= navigator.userAgent;

  if ( browserName == 'Microsoft Internet Explorer') { browserIs= 'IE' }
   else if (browserAgent.indexOf('Chrome')  != -1 )  { browserIs= 'Chrome' }
   else if (browserAgent.indexOf('Firefox') != -1 )  { browserIs= 'Firefox' }
   else if (browserAgent.indexOf('Safari')  != -1 )  { browserIs= 'Safari' }
   else { browserIs= 'Other' }; // no change

  return(browserIs);

}

// ====================================================================================================

function SetBrowserSpecific(whichform, addextralines) {

  browserIs= GetBrowser();
//window.alert(browserIs);

// Set number of columns and rows in textareas for different browsers and field contents
// Set textarea property 'autoresize="no"' to stop auto-resizing

  if (addextralines == null) { addextralines= "Y"; }
  var formelems = document.getElementById(whichform).elements;
  var noautoresizeid= document.getElementById("noautoresize");
  for (i=0; i< formelems.length; i++) { 

     if (formelems[i].type == 'textarea') { 

        if ( browserIs == 'IE' ) {
           if (formelems[i].cols == 84) { formelems[i].cols= 116 }
            else if (formelems[i].cols == 33)  { formelems[i].cols= 48 }
            else if (formelems[i].cols == 110) { formelems[i].cols= 156 }
        } else if ( browserIs == 'Firefox' ) {
           if (formelems[i].cols == 84) { formelems[i].cols= 112 }
            else if (formelems[i].cols == 33)  { formelems[i].cols= 42 }
            else if (formelems[i].cols == 110) { formelems[i].cols= 150 }
        } else if ( browserIs == 'Chrome' ) {
           if (formelems[i].cols == 84) { formelems[i].cols= 116 }
            else if (formelems[i].cols == 33)  { formelems[i].cols= 47 }
            else if (formelems[i].cols == 110) { formelems[i].cols= 155 }
        } else if ( browserIs == 'Safari' ) { 
           if (formelems[i].cols == 84) { formelems[i].cols= 84 }
            else if (formelems[i].cols == 33)  { formelems[i].cols= 35 }
            else if (formelems[i].cols == 110) { formelems[i].cols= 110 }
        };

        var autoresize = -1;
        if ( noautoresizeid ) { autoresize= noautoresizeid.value.indexOf(formelems[i].name) };
       
        var noofrows;
        if ( autoresize == -1 ) { 

           if (formelems[i].value == "") { formelems[i].rows= 8; }
            else {
              var noofcr = formelems[i].value.split(/\n/g).length;
              noofrows= Math.floor((noofcr -1) /2);
              var textstring= formelems[i].value;
              for (var icr=0; icr < noofcr; icr++) { 
                  var crpos= textstring.indexOf(chr(10));
                  if (crpos < 0) { crpos= textstring.length }; 
                  noofrows = noofrows + Math.floor((crpos -1) / formelems[i].cols) +1;
                  textstring= textstring.substr(crpos +2, 9999);
                  if (( noofrows > 24 ) || ( textstring.length == 0 )) { break};
              };
           
             if (addextralines == "Y") {
                if (noofrows < 6) { noofrows= 6 };
                formelems[i].rows= noofrows +6;
              } else {
                formelems[i].rows= noofrows +2;
              };

             var countfieldid= document.getElementById(formelems[i].name + "count");
             if (countfieldid) { countfieldid.innerHTML = formelems[i].value.length };

          };
        };
     };
  };
}

// ====================================================================================================


function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if ( aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
} 

// ====================================================================================================


function BookmarkWhat(page, propertyid, description) {

  if (page == 'Home')
      var strTitle="disneyvillasflorida.com - Luxury Villas in Florida";
   else
   if (page == 'Owners')
      var strTitle="disneyvillasflorida.com - Owner Login";
    else
    if (page == 'Admin')
       var strTitle="disneyvillasflorida.com - Admin Login";
     else
     if (page == 'Specials')
       var strTitle="disneyvillasflorida.com - Special Promotions & Late Deals";
      else
      if (page == 'Location')
         var strTitle="disneyvillasflorida.com - " + description;
       else
       var strTitle="disneyvillasflorida.com - " + description + " (#" + propertyid + ")";

  window.external.AddFavorite(location.href,strTitle);
}

// ====================================================================================================


function CheckOwnersLockedOut(lockedout) {
  if ( lockedout == "Y" ) { 
     alert("No owner logins allowed at present.\n\nRefer to Noticeboard alongside for details.");
     return false;
  };
}

// ====================================================================================================

function ShowOrHideObject(divid, showorhide) {
  id = document.getElementById(divid);
  if (id) {
     if ((showorhide == "show") && (id.style.display == "none")) { id.style.display= "" }
      else if ((showorhide == "hide") && (id.style.display != "none")) { id.style.display= "none" };
  };
}

function ShowOrHideDiv(divid) {
  id = document.getElementById(divid);
  if (id) {
     if (id.style.display == "none") { id.style.display= "" }
      else if (id.style.display != "none") { id.style.display= "none" };
  };
}




function ShowObject(divid) {
  id = document.getElementById(divid);
  if (id) {
     if (id.style.display == "none") { id.style.display="" };
  };
}


function HideObject(divid) {
  id = document.getElementById(divid);
  if (id) {
     if (id.style.display != "none") { id.style.display="none" };
  };
}

// ====================================================================================================


function ShowAndExpandArea(divid, fieldid, expand) {

  var textareaid= document.getElementByID(fieldid);
  if (expand == "N") {
     if (textareaid.rows == 30) { textareaid.rows= 8 }
      else { textareaid.rows= 1;
             ShowOrHideObject(divid, "none") }; 
   } 
  else 
  if (expand == "Y") {
     ShowOrHideObject(divid, "");
     if (textareaid.rows == 1) { textareaid.rows= 8 }
      else { textareaid.rows= 30 };
   };
};


// ====================================================================================================

function ShowOwnersLoginMessage(lockedout) {
// VND v1.0.101031

  var strReply = getURLParam("reply");
  var userid= document.getElementById("username");

  if ( userid ) {

     if ( lockedout == "Y" ) 
        { strMessage = "No owner logins allowed at present.";
          document.getElementById("cellLoginMessage").innerHTML = strMessage }
      else
      if ( strReply != "" ) {

         var strUsername = getURLParam("user");
         var strMessage = "";

         switch(strReply) {
           case "noadmin" :
                strMessage = "This administrator username does not exist";
                break;
           case "nouser" :
                strMessage = "This username does not exist on disneyvillasflorida.com";
                break;
           case "nopass" :
                strMessage = "Incorrect password entered - note, this is case-sensitive!";
                break;
           case "prompt" :
                strMessage = "Click forgotten password button to have your password e-mailed to you";
                break;
           case "pass" :
                strMessage = "";
                break;
         };

         document.getElementById("cellLoginMessage").innerHTML = strMessage;
         userid.value = strUsername;
         userid.select();
     };
     userid.focus();
  };
};

// ====================================================================================================
// Preview property add in 'safe' window.
//'directories=no,status=no,copyhistory=no'
// ====================================================================================================

function ViewProperty(adurl, whatmode, withstats) {
  adurl= "./view_property.pl?rhid=" + adurl;
  if ( withstats == 'N' ) { adurl= adurl + "&fp=preview" };
  if ( whatmode  == "preview" ) { propad= window.open(adurl,'_blank','toolbar=no,location=no,scrollbars=yes,status=yes,directories=no,resizable=yes') }
   else if ( whatmode == "new" ) { propad= window.open(adurl,'_blank','') }
    else { propad= window.location.assign(adurl) };
};

// ====================================================================================================


function ViewVideoTour(hasvideo, videourl) {
  if (( hasvideo == 'N' ) || ( videourl == '' )) {
     window.alert('There is no video or 360 tour available for this property.');
   } else { 
     if ( videourl.substring(0,3) == 'www' ) { videourl= "http://" + videourl; }
     videotourad= window.open(videourl,'videotour','menubar=no,toolbar=no,titlebar=no,directories=no,location=no,scrollbars=yes,status=no,directories=no,resizable=no') }
};


// ====================================================================================================


function ViewCalendar(hascalendar, calendarurl, propertyid) {
  if (( hascalendar == 'N' ) || ( calendarurl == '' )) {
     window.alert('Unfortunately there is no availability calendar for this property.  Please contact the owner.');
   } else { 
     calendarurl='view_calendar.pl?rhid=' + propertyid;
     calendarad= window.open(calendarurl,'calendar','width=630,height=720,menubar=no,toolbar=no,titlebar=no,directories=no,location=no,scrollbars=no,status=no,directories=no,resizable=no') }
};


// ====================================================================================================

function OpenPage(newurl, openmode) {
  if ( openmode == "new" ) { newpage= window.open(newurl,'_newtab') }
   else
   if ( openmode == "asurl" ) { 
      urlparms= location.search.substring(1,99).replace("compare=y",'');
      if (( urlparms.substring(0,1) == "&" ) && ( newurl.indexOf("?") == -1 )) { urlparms= "?" + urlparms.substring(1,99) }
       else if ( urlparms != "" ) { urlparms= "&" + urlparms };
      newpage= window.location.assign(newurl + urlparms) }
    else
    { newpage= window.location.assign(newurl) };
//  return false;
};

// ====================================================================================================

function GetPropertyRefFromURL() {
  parms=location.href.split("?");
  if (parms.length > 1) {
     id=parms[1].split("=");
     parmid= id[0];
     if (( parmid == "ref" ) || (parmid == "id")) {
        villaid= id[1];
        if ((villaid >= 101) && (villaid < 999)) { OpenPage("./cgi-bin/view_property.pl?rhid=" + villaid + "&fp=2") }
     };
  };
}

// ====================================================================================================

function GotoAnchor(anchorhash) {self.location.hash = anchorhash};

// ====================================================================================================


function HoverOn(id) {
  if (id) { id.className= id.className + "hover"; };
}

// ====================================================================================================

function HoverOff(id) {
  if (id) { id.className= id.className.replace("hover","") };
}

// ====================================================================================================

function AllMandatoryFieldsEntered(thisform) {

  var mandmsg = "";

  for ( var i=0; i < thisform.elements.length; i++) {
        var elementid= thisform.elements[i];
        if ((elementid.getAttribute("mandatory")) && (elementid.value == "")) { 
           mandmsg= mandmsg + "* " + elementid.getAttribute("mandatory") + chr(13) + chr(10) };
  };

  if ( mandmsg != "" ) {
     mandmsg= "The following fields are mandatory and must have details entered:" + 
               chr(13) + chr(10) + chr(13) + chr(10) + mandmsg + chr(13) + chr(10) + "Please enter details then re-try.";
     window.alert(mandmsg);
     return (false);
   } else {
     return (true);
  };

};

// ====================================================================================================

function ShowNoOfChars(fieldid) {
// Shows how many characters entered
 countfieldid= document.getElementById(fieldid.name + "count");
 if (countfieldid) { countfieldid.innerHTML = fieldid.value.length }
}

// ====================================================================================================

function ConfirmDelete(title, gotourl) {
// Confirm deletion of a record
  if (confirm("Delete '" + title + "'?")) { return OpenPage(gotourl,'') };
}

// ====================================================================================================

function ConfirmAction(action, actiondata, gotourl) {
// Confirm action
  if (confirm(action + " '" + actiondata + "'?")) { return OpenPage(gotourl,'') };
}

// ====================================================================================================

function CheckSpelling(textareatocheck) {
  var textareaid = document.getElementById(textareatocheck);
  var speller = new spellChecker(textareaid);
  speller.openChecker();
//  var speller = new spellChecker();
//  speller.spellCheckAll();
}

// ====================================================================================================
// Slide and hide div
// ====================================================================================================

function SlideAndHide(divname, heightCurrent, heightTarget, modeRun) {

  var divid= document.getElementById(divname);
  var rerun= "N";
  var heightIncrement= 20;
  var timedelayms= 0;

  if ( heightCurrent == 0 ) {
     if ( divid.style.display == "none" ) { modeRun= "S"; window.status= "Opening..."; }
      else { modeRun= "X" };
   };

  if (( modeRun == "S" ) && ( heightCurrent <= heightTarget )) {
     divid.style.visibility= 'visible';
     divid.style.display= 'block';
     heightCurrent= heightCurrent + heightIncrement;
     rerun= "Y";
   } else if (( modeRun == "H" ) || ( modeRun == 'X' )) {

        if ( modeRun == "X" ) {
           modeRun= "H";
           heightCurrent= divid.style.height.replace(/px/g,'');
        };

        if ( heightCurrent <= heightIncrement )  {
           divid.style.height= 0;
           divid.style.display= 'none';
         } else {
           heightCurrent= heightCurrent - heightIncrement;
           rerun= "Y";
        };

     };

  if ( rerun == "Y" ) {
     divid.style.height= heightCurrent + "px";
     setTimeout('SlideAndHide("' + divname + '",' + heightCurrent + ',' + heightTarget + ',"' + modeRun + '")', timedelayms);
  };

}

// ====================================================================================================
// Property Shortlist cookies
// ====================================================================================================


function setCookie(cookieName, cookieContent)
{
 var ExpiryDate=new Date();
 var cookieExpiresAfter= 180;
 ExpiryDate.setDate(ExpiryDate.getDate() + cookieExpiresAfter);
 document.cookie.domain = 'disneyvillasflorida.com';
 document.cookie = cookieName+ "=" + escape(cookieContent) + ";path=/" + 
                  ((cookieExpiresAfter == null) ? "" : ";expires="+ExpiryDate.toUTCString());
};

// ====================================================================================================

function getCookie(cookieName)
{
 if (document.cookie.length>0) {
     c_start=document.cookie.indexOf(cookieName + "=");
     if (c_start != -1) {
         c_start= c_start + cookieName.length +1;
         c_end=   document.cookie.indexOf(";", c_start);
         if (c_end == -1) { c_end=document.cookie.length };
         return unescape(document.cookie.substring(c_start,c_end));
     };
 };
 return "";
};

// ====================================================================================================

function ManagePropertyShortlist(actionToDo, propertyID)
{

 shortlistNoOf = 0;
 shortlistMyProperties = getCookie('property_shortlist');

 if (actionToDo == 'remove') { 
    if (confirm('Do you wish to remove property #' + propertyID + ' from shortlist?') == true) {
       shortlistMyProperties= shortlistMyProperties.replace(propertyID + ",","");
       ShowOrHideDiv('divProperty' + propertyID)
    }
  }
  else
  if (actionToDo == 'add') {
     if (propertyID != 0) {
         if (shortlistMyProperties.indexOf(propertyID) == -1) {
             shortlistMyProperties = shortlistMyProperties + propertyID + ",";  
             window.alert('Property #' + propertyID + ' has been added to your shortlist'); 
          } else {
            window.alert('Property #' + propertyID + ' is already in your shortlist');
         }; 
     }; 
  }; 

 if (propertyID != 0) { setCookie('property_shortlist', shortlistMyProperties) };

    shortlistNoOf = shortlistMyProperties.split(",").length -1;
    document.getElementById('idPropertyShortlist').innerHTML = '<a href="' +
             ((location.pathname.indexOf('cgi-bin') == -1) ? "cgi-bin/" : "") + 
             'property_shortlist.pl" class="h100shortlist">Shortlist (' + shortlistNoOf  + ')</a>';
};

// ====================================================================================================

function ManageUserLoginDetails(cookieName, actionToDo)
{

 cookieUserLogin = getCookie(cookieName);

 username=    document.getElementById('username');
 userpass=    document.getElementById('password');
 savedetails= document.getElementById('savedetails');

 if (( actionToDo == 'save' ) || ( actionToDo == 'autosave' )) {
    if ( savedetails.checked == true ) { cookieUserLogin = username.value + ',' + userpass.value + ',' + savedetails.value }
     else { cookieUserLogin = ',,' } ;
    setCookie(cookieName, cookieUserLogin);
    if (( actionToDo == 'save' ) && ( savedetails.checked == true )) { window.alert('Your login details have been saved.') };
  }
  else
  if ( actionToDo == 'read' ) {
     loginField = cookieUserLogin.split(",");
     if (loginField[2] == 'saved' ) {
        username.value=       loginField[0];
        userpass.value=       loginField[1];
        savedetails.value=    loginField[2];
        savedetails.checked = true;
     };
  };

};

// ====================================================================================================

function GetListIndex(idList, strMatchTo) {
 var idx=0;
 while ((idList.options[idx].value != strMatchTo) && (idx < idList.options.length)) {idx++;}
 return(idx);
};


function ManageRequestDetails(cookieName, frmName, actionToDo)
{

 cookieRequest      = getCookie(cookieName); 
 frmId              = document.getElementById(frmName);

 var contactName    = document.getElementById('contactname');
 var contactEMail   = frmId.contactemail;
 var arrivalDay     = document.getElementById('arrival_day');
 var arrivalMonth   = document.getElementById('arrival_month');
 var arrivalYear    = document.getElementById('arrival_year');
 var departureDay   = document.getElementById('departure_day');
 var departureMonth = document.getElementById('departure_month');
 var departureYear  = document.getElementById('departure_year');
 var flexibleBy     = document.getElementById('flexibleby');
 var noofAdults     = document.getElementById('noofadults');
 var noofChildren   = document.getElementById('noofchildren');
 var residingIn     = document.getElementById('residingin');
 var anythingElse   = document.getElementById('anythingelse');

 if ( actionToDo == 'save' )  {
    cookieRequest = 'saved||' + contactName.value + '||' + contactEMail.value           + '||' + 
                    arrivalDay.selectedIndex      + '||' + arrivalMonth.selectedIndex   + '||' + arrivalYear.selectedIndex   + '||' +
                    departureDay.selectedIndex    + '||' + departureMonth.selectedIndex + '||' + departureYear.selectedIndex + '||' + 
                    flexibleBy.selectedIndex      + '||' + 
                    noofAdults.selectedIndex      + '||' + noofChildren.selectedIndex   + '||' + residingIn.selectedIndex    + '||' + 
                    anythingElse.value;

    setCookie(cookieName, cookieRequest);
  }
  else
  if ( actionToDo == 'read' ) {
     requestDetails = cookieRequest.split("||");
     if (requestDetails[0] == 'saved' ) {
        contactName.value            = requestDetails[1];
        contactEMail.value           = requestDetails[2];
        arrivalDay.selectedIndex     = requestDetails[3];
        arrivalMonth.selectedIndex   = requestDetails[4];
        arrivalYear.selectedIndex    = requestDetails[5];
        departureDay.selectedIndex   = requestDetails[6];
        departureMonth.selectedIndex = requestDetails[7];
        departureYear.selectedIndex  = requestDetails[8];
        flexibleBy.selectedIndex     = requestDetails[9];
        noofAdults.selectedIndex     = requestDetails[10];
        noofChildren.selectedIndex   = requestDetails[11];
        residingIn.selectedIndex     = requestDetails[12];
        anythingElse.value           = requestDetails[13];
     };
  };

};

// ====================================================================================================

function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 34;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }   
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';                          
  } else {
     dark.style.display='none';
  }
}

// ====================================================================================================

function LoadPage(pageTitle, pageTop, pageURL) {
  var divLoad= document.getElementById('divLoadPage');
  if (divLoad) {
     divLoad.style.top= pageTop + 'px';
     var pageTitleLoading = '<h1>Loading ' + pageTitle + '...</h1>';
     document.getElementById('idLoadPageTitle').innerHTML = pageTitleLoading;
     ShowObject('divLoadPage');
     grayOut(true, {'opacity':'25'});
     setTimeout("HideObject('divLoadPage'); grayOut(false);", 2500);
  };
  OpenPage(pageURL); 
};

// ====================================================================================================

function IsValidEmailAddress(email) { 
  var isvalid = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
  return email.match(isvalid) 
};

// ====================================================================================================

function PreloadImages(images) {
    if (document.images) {
        var i = 0;
        var imageArray = new Array();
        imageArray = images.split(',');
        var imageObj = new Image();
        for(i=0; i<=imageArray.length-1; i++) {
            imageObj.src=images[i];
        }
    }
};

// ====================================================================================================

function InitializeGoogleMap(mapName, latitude, longitude) {
  if (GBrowserIsCompatible()) {
     var map = new GMap2(document.getElementById(mapName));
     var mapOptions = { googleBarOptions : { style : "new" }};
     map.addControl(new GSmallZoomControl3D ());
     var locCoords = new GLatLng(latitude,longitude);
     var locMarker = new GMarker(locCoords);
     map.addOverlay(locMarker);
     map.setCenter(new GLatLng(latitude,longitude), 11);
  };
};

// ====================================================================================================


function ShowCommunityMap(mapName, latitude, longitude, communityName) {

  if (GBrowserIsCompatible()) {

     var map = new GMap2(document.getElementById(mapName));
     var mapOptions = { googleBarOptions : { style : "new" }};
     map.addControl(new GSmallZoomControl3D ());
//     map.addControl(new GMapTypeControl ());
//     map.addControl(new GScaleControl());

     var bounds;
     bounds = new GLatLngBounds();

     // Community

     var markerIcon    = new GIcon(G_DEFAULT_ICON);
     markerOptions     = { icon:markerIcon };
     markerIcon.image  = "../images/maps/marker_red.gif";

     var locCoords  = new GLatLng(latitude,longitude);
     var locMarker  = new GMarker(locCoords, markerOptions);
     var locTooltip = new Tooltip(locMarker, communityName, 4);
     locMarker.tooltip = locTooltip;
     map.addOverlay(locTooltip);
     GEvent.addListener(locMarker, 'mouseover',function() { this.tooltip.show(); });
     GEvent.addListener(locMarker, 'mouseout', function() { this.tooltip.hide(); });

     bounds.extend(locCoords);
     map.addOverlay(locMarker);

     // Walt Disney World

     markerIcon.image  = "../images/maps/marker_teal.gif";
     var locCoords  = new GLatLng(28.377506,-81.565247);
     var locMarker  = new GMarker(locCoords, markerOptions);
     var locTooltip = new Tooltip(locMarker, "Walt Disney World", 4);
     locMarker.tooltip = locTooltip;
     map.addOverlay(locTooltip);
     GEvent.addListener(locMarker, 'mouseover',function() { this.tooltip.show(); });
     GEvent.addListener(locMarker, 'mouseout', function() { this.tooltip.hide(); });

     bounds.extend(locCoords);
     map.addOverlay(locMarker);

     map.setCenter(bounds.getCenter());
     map.setZoom(map.getBoundsZoomLevel(bounds));

  };
};

// ====================================================================================================

function LikeFacebook(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
};

