var map;
var geocoder;
function Gload(){
		       geocoder = new GClientGeocoder();
                       }
    
function addToMap(response){
		       if (!response || response.Status.code != 200) {
					      alert("Sorry, we were unable to geocode that address");
		       } else {
					      // Retrieve the object
					      place = response.Placemark[0];
					       // Retrieve the latitude and longitude
					      point = new GLatLng(place.Point.coordinates[1],
					      place.Point.coordinates[0]);
					      longitud= place.Point.coordinates[0];
					      latitud= place.Point.coordinates[1];
					      //alert(latitud);
                                              document.getElementById('latitud').value=latitud;
                                               document.getElementById('longitud').value=longitud;
		       }
}
                       
								 
function showLocation(){
		       //var address = "821 Mohawk Street, Columbus OH";
		       Gload();
		       var address = document.getElementById('address1').value +", "+ document.getElementById('city').value + " " + document.getElementById('state').value ;
		       geocoder.getLocations(address, addToMap);
                       //alert(address);
}
                        

function searchLocations(text){
                       var product = document.getElementById('product_input').value;
                       var nid = document.getElementById('product_id').value;
                       var type = document.getElementById('product_type').value;
                       var location = document.getElementById('location').value;
                       var locationname = text;
                       var zip = document.getElementById('zip').value; 
                       var within = document.getElementById('within').value;
                       //var filter = document.getElementById('location').value;
                       window.location="index.php?action=map&str="+product+"&nid="+nid+"&type="+type+"&zip="+zip+"&within="+within+"&loca="+location+"&locaname="+locationname+"&origin=other";
                       // window.location="map/"+product+"/"+nid+"/"+type+"/"+zip+"/"+within+"/"+location+"/other";
}

function searchLocationsSub(text){
                       var product = document.getElementById('product_input').value;
                       var nid = document.getElementById('product_id').value;
                       var type = document.getElementById('product_type').value;
                       var location = document.getElementById('location').value;
                       var locationname = text;
                       var zip = document.getElementById('zip').value; 
                       var within = document.getElementById('within').value;
                       //var filter = document.getElementById('location').value;
                       window.location="http://buyctgrown.com/index.php?action=map&str="+product+"&nid="+nid+"&type="+type+"&zip="+zip+"&within="+within+"&loca="+location+"&locaname="+locationname+"&origin=other";
                       //window.location="../map/"+product+"/"+nid+"/"+type+"/"+zip+"/"+within+"/"+location+"/other";
}


function searchall(product,location,locationname, zip,within,nid,type){
                       if(nid==""){
                                              nid='none';
                       }
                       var radius=within;
                       if(zip==""){
                                              var address='06511';
                       }else{
                                              var address=zip;            
                       }
                       geocoder = new GClientGeocoder();
                       geocoder.getLatLng(address, function(latlng) {
                                              if (!latlng) {
                                                                     //alert(address + ' not found');
                                                                     var  lat='41.327197';
                                                                     var lng='-72.919693';
                                              }else{
                                                                     searchLocationsNear(latlng,location,locationname,radius,product,nid,type);
                                              }
                       });
}

function searchLocationsNear(center,location,locationname,radius,valueprod,nid,type) {
                       var searchUrl = 'includes/utils/genxml.php?num=distance&lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius +'&valueprod=' +valueprod  +'&location=' +location+'&nid=' +nid+'&type=' +type;
                       GDownloadUrl(searchUrl, function(data) {
                                              var xml = GXml.parse(data);
                                              var markers = xml.documentElement.getElementsByTagName('marker');
                                              map.clearOverlays();
                                              var sidebar = document.getElementById('sidebar');
                                              sidebar.innerHTML = '';
                                              if (markers.length == 0) {
                                                                     sidebar.innerHTML = 'No results found.';
                                                                     //map.setCenter(new GLatLng(40, -100), 4);
                                                                     return;
                                              }
                                              var bounds = new GLatLngBounds();
                                              for (var i = 0; i < markers.length; i++) {
                                                                     var nid = markers[i].getAttribute('eid');
                                                                     var name = markers[i].getAttribute('title');
                                                                     var urlname = markers[i].getAttribute('urlname');
                                                                     var address = markers[i].getAttribute('address');
                                                                     var city = markers[i].getAttribute('city');
                                                                     var zip = markers[i].getAttribute('zip');
                                                                     var distance = parseFloat(markers[i].getAttribute('distance'));
                                                                     var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                                                     parseFloat(markers[i].getAttribute('lng')));
                                                                     var marker = createMarker(point, nid, name, urlname, address, city, zip);
                                                                     map.addOverlay(marker);
                                                                     var sidebarEntry = createSidebarEntry(nid, marker, name, urlname, address, distance, city, zip);
                                                                     sidebar.appendChild(sidebarEntry);
                                                                     bounds.extend(point);
                                              }
                       });
                       $('product_input').value="";
                       $('product_id').value="";
                       if(location!=''){
                                var displaysearch=valueprod+" "+locationname;              
                       }else{
                              var displaysearch=valueprod;                
                       }
                       document.getElementById('searched').innerHTML = displaysearch;
}

function createMarker(point, nid, name, urlname, address, city, zip) {
                       var marker = new GMarker(point);
                       var str=name;
                       if(str.length>30){
                            str=str.substr(0,30);            
                       }
                       var html = '<span class=orangetext>' + str + '</span> <br/>' + address +'<br/>' + city +' CT ' + zip +'<br /><a href="'+urlname+'" class="profile">view profile</a> | <a href="#" onclick="emailfarm('+nid+')" class="profile">contact</a>';
                       GEvent.addListener(marker, 'click', function() {
                       marker.openInfoWindowHtml(html);
                       });
                       GEvent.addDomListener(marker, 'mouseover', function() {
                       marker.openInfoWindowHtml(html);
                       });
                       return marker;
                       }
    
function createSidebarEntry(nid, marker, name, urlname, address, distance, city, zip) {
                       var div = document.createElement('div');
                       var str=name;
                       if(str.length>30){
                            str=str.substr(0,30);            
                       }
                       if(distance == distance){
                                              var miles='<span=ligth> (' + distance.toFixed(1) + ') mi.</span>';
                       }else {
                                              var miles='';          
                       }
     
                       var line =  name + miles +'<br/>' ;
                       var html = '<span class=orangetext>' + str + '</span> <br/>' + address +'<br/>' + city +' CT ' + zip +'<br /><a href="'+urlname+'" class="profile">view profile</a> | <a href="#" onclick="emailfarm('+nid+')" class="profile">contact</a>';
                       div.innerHTML = line;
                       div.style.cursor = 'pointer';
                       div.style.marginBottom = '5px'; 
                       GEvent.addDomListener(div, 'click', function() {
                                              //cleanURL version
                                              window.location = ""+urlname+"";
                       });
                       GEvent.addDomListener(div, 'mouseover', function() {
                                              div.style.color='#cb4c00';
                                              div.style.backgroundColor = '#e6f9ff';
                                              marker.openInfoWindowHtml(html);
                       });
                       GEvent.addDomListener(div, 'mouseout', function() {
                                              div.style.color='#333';
                                              div.style.backgroundColor = '#fff';
                       });
                       return div;
}
    
    
/* came from home page */
function getSelectedId(text, li) {
                       $('product_id').value=li.id;
                       $('product_type').value=li.title;
}


/* seach for network in small map organization profile */
function searchsmall(datos){
                       var xml = GXml.parse(datos);
                       var markers = xml.documentElement.getElementsByTagName('marker');
                       map.clearOverlays();
                       var bounds = new GLatLngBounds();
                       for (var i = 0; i < markers.length; i++) {
                                              var nid = markers[i].getAttribute('lid');
                                              var name = markers[i].getAttribute('title');
                                              var address = markers[i].getAttribute('address');
                                              var city = markers[i].getAttribute('city');
                                              var zip = markers[i].getAttribute('zip');
                                              var urlname = markers[i].getAttribute('urlname');
                                              var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                              parseFloat(markers[i].getAttribute('lng')));
                                              var marker = createMarker(point, nid, name,urlname, address, city, zip);
                                              map.addOverlay(marker);
                                              bounds.extend(point);
                       }
                       map.setCenter(bounds.getCenter());
}

/* send email to organization*/
function emailfarm(nid){
                       var divTag = document.createElement("div");
       
                       divTag.id = "div1";
       
                       divTag.setAttribute("align","center");
       
                       divTag.style.margin = "0px auto";
       
                       divTag.className ="dynamicDiv";
       
                       divTag.innerHTML = "<img src='images/bubble_close.png' onClick='closemailbox()' class='closemail'><h1>Send Email</h1><div id='response'>	</div><form name='formail'  onsubmit='sendemail("+nid+"); return false;'>Your email:<br /><label><input type='text' name='youremail' class='youremail'></label><br />Body:<br /><textarea name='text' rows='15' id='text' class='youremail'></textarea><input type='submit' value='send mail' id='sendmail' name='sendmail'></form>";
        
                       document.getElementById("sideLeft").appendChild(divTag);
 
}
function closemailbox(){
                       var elm = document.getElementById('div1');
                       elm.parentNode.removeChild(elm);
}

////send email
function sendemail(nid){
                       var youremail=document.formail.youremail.value;
                       var text=document.formail.text.value;
                       var valid = '';
                       var isr = ' is required.';
                       if (youremail.length<1) {
                                              valid += '<br />Your email'+isr;
                       }
                       if (text.length<1) {
                                              valid += '<br />Text'+isr;
                       }
                       if (valid!='') {
                                              document.getElementById('response').style.display= "block";
                                              document.getElementById('response').innerHTML="Error:"+valid;
                       }else {
                                              var datastr =text;
                                              document.getElementById('response').style.display= "block";
                                              document.getElementById('response').innerHTML="Sending message .... ";
                                              send(nid, youremail, text);
                       }  
}
function send(nid,youremail, text){
                       var xmlHttp = getXMLHttp();
                       xmlHttp.onreadystatechange = function(){
                                              if(xmlHttp.readyState == 4){
                                                                     ShowResponse(xmlHttp.responseText); 
                                              }
                       }
                       var fileName='includes/utils/mail.php?nid='+nid+'&text='+text+'&youremail='+youremail;
                       xmlHttp.open("GET", fileName, true);
                       xmlHttp.send(null);
}

function ShowResponse(resp){
                       if(resp == 1) {
                                              var elm = document.getElementById('div1');              
                                              elm.parentNode.removeChild(elm);
                                              alert("Congratulations! Your email has been sent.");
                       } else if(resp == 2) {
                                              var elm = document.getElementById('div1');
                                              elm.parentNode.removeChild(elm);
                                              alert("there's some errors to send the mail, verify your server options.");
                       } 
}

var interval = 215; //Move 10px every initialization

function moveImageLeft() {
                       //get slider position
                       var x=document.getElementById('imgslider').offsetLeft;
                       //Keep on moving the image till the target is achieved
                       if(x<0){x = x+418;} 
                       //Move the image to the new location
                       document.getElementById("imgslider").style.left = x+'px';
}

function moveImageRight() {
                       //get slider position
                       var x=document.getElementById('imgslider').offsetLeft;
                       //Keep on moving the image till the target is achieved
                       if((x<=0)&&(x>-1200)){ x = x-418;}
                       //Move the image to the new location
                       document.getElementById("imgslider").style.left = x+'px';
                       ///change title of profile featured
}
function plus(){
		       var jumi = document.getElementById("aValue");
                       //alert(jumi.value);
                       if(jumi.value<3){
                                              var jum = (document.getElementById("aValue").value -1)+ 2;
                                              jumi.value = jum;                              
                                              if (document.getElementById){
                                                                     //document.getElementById("profeatured").href= "?action=profile&nid="+Lnks[jumi.value];
                                                                     //cleanURL version
                                                                     document.getElementById("profeatured").href= URL[jumi.value];
                                                                     document.getElementById("profeatured").innerHTML= Caption[jumi.value];
                                              }
                       }	
}

function minus(){
		       var jumi = document.getElementById("aValue");
                       //alert(jumi.value);
                       if(jumi.value>0){
                                              var jum = (document.getElementById("aValue").value )- 1;
                                              jumi.value = jum;
                                              if (document.getElementById){
                                                                     document.getElementById("profeatured").href=URL[jumi.value];
                                                                     document.getElementById("profeatured").innerHTML= Caption[jumi.value];
                                              }
                       }	
}
                        
function upss(jss){
		       if (document.getElementById){
                                              jss = jss + 1;
                                              document.getElementById("profeatured").href= "profile.php?nid="+Lnks[jss];
                                              document.getElementById("profeatured").innerHTML= Caption[jss];
		       }					
}
/////Register: display div with products for each catyegory to pick our products

///check if any products are selected and if so prevent the user from closing it
function anyselected(){
                      alert(products.lenght); 
}


function selectproducts(nid){
                       var catid=nid;
                       var ni = document.getElementById('prodbox');
                       ni.style.visibility='visible';
                       var numi = document.getElementById('theValue');
                       var num = (document.getElementById('theValue').value -1)+ 2;
                       numi.value = num;
                       var myProd='p'+nid;
                       if(document.getElementById(myProd).checked==true){

                                              var newdiv = document.createElement('div');
                                              newdiv.id='myDiv'+nid;
                                              newdiv.className='selector';
                                              ///call the file to show product list under category
                                              var searchUrl = 'includes/utils/gencat.php?cat='+nid;
                                              GDownloadUrl(searchUrl, function(data) {
                                                                     var xml = GXml.parse(data);
                                                                     var products = xml.documentElement.getElementsByTagName('product');
                                                                     newdiv.innerHTML = '';
                                                                     if (products.length == 0) {
                                                                                            newdiv.innerHTML = 'No results found.';
                                                                                            //map.setCenter(new GLatLng(40, -100), 4);
                                                                                            return;
                                                                     }
                                                                     var prods='';
                                                                     for (var i = 0; i < products.length; i++) {
                                                                                            var nid = products[i].getAttribute('nid');
                                                                                            var title = products[i].getAttribute('title');
                                                                                            var prods= prods+'<label class="eachproduct2"><input type="checkbox" name="produs[]" value="'+nid+'" id="'+nid+'" class="eachproduct2">'+title+' </label>';
                                                                     }
                                                                     var append=prods+'<a href="javascript:;" onclick="removeElement(this.id);" class="removebox" id="'+catid+'"><img src="images/collapse.gif" title="close" alt="close" /></a>';
                                                                     newdiv.innerHTML =append;
                                              });
                                              ni.appendChild(newdiv);
                       }else{
                            var divToRemove='myDiv'+nid;
                            var element = document.getElementById(divToRemove);
                            element.parentNode.removeChild(element);                 
                       }
}
function selectedproducts(tid,nid){
                       var catid=tid;
                       var ni = document.getElementById('prodbox');
                       ni.style.visibility='visible';
                       var numi = document.getElementById('theValue');
                       var num = (document.getElementById('theValue').value -1)+ 2;
                       numi.value = num;
                       
                       var newdiv = document.createElement('div');
                       newdiv.id='myDiv'+nid;
                       newdiv.className='selector';
                       ///call the file to show product list under category
                       var searchUrl = 'includes/utils/genselcat.php?cat='+tid+'&nid='+nid;
                       GDownloadUrl(searchUrl, function(data) {
                                              var xml = GXml.parse(data);
                                              var products = xml.documentElement.getElementsByTagName('product');
                                              newdiv.innerHTML = '';
                                              if (products.length == 0) {
                                                                     newdiv.innerHTML = 'No results found.';
                                                                     //map.setCenter(new GLatLng(40, -100), 4);
                                                                     return;
                                              }
                                              var prods='';
                                              for (var i = 0; i < products.length; i++) {
                                                                     var nid = products[i].getAttribute('nid');
                                                                     var title = products[i].getAttribute('title');
                                                                      var status = products[i].getAttribute('status');
                                                                     var prods= prods+'<label class="eachproduct2"><input type="checkbox" name="produs[]" value="'+nid+'" id="'+nid+'" class="eachproduct2" '+status+'>'+title+' </label>';
                                              }
                                              var append=prods+'<a href="javascript:;" onclick="removeElement(this.id);" class="removebox" id="'+catid+'"><img src="images/collapse.gif" title="close" alt="close" /></a>';
                                              newdiv.innerHTML =append;
                       });
                       ni.appendChild(newdiv);
                   
}


function removeElement(divNum) {                      
                       var collection = document.getElementById('myDiv').getElementsByTagName('INPUT');
                       for (var x=0; x<collection.length; x++) {
                                              if (collection[x].checked==true){
                                                                     alert("You selected products from this box. If you close it the selections will be lost.");
                                                                     return false;
                                              }else{
                                                                     var empty='yes';
                                              }
                       }
                       if(empty=='yes'){
                                              var d1=document.getElementById('myDiv').parentNode ;
                                              d1.style.visibility='hidden';
                                              var olddiv = document.getElementById('myDiv');
                                              d1.removeChild(olddiv);
                                              document.getElementById(divNum).checked = false;
                       }
}

function getXMLHttp(){
                       var xmlHttp
                       try{
                                              //Firefox, Opera 8.0+, Safari
                                              xmlHttp = new XMLHttpRequest();
                       }
                       catch(e){
                                              //Internet Explorer
                                              try{
                                                                     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                                              }
                       catch(e){
                                              try{
                                                                     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                                              }
                       catch(e){
                                              alert("Your browser does not support AJAX!")
                                              return false;
                       }
}
}
                       return xmlHttp;
}

function addtofollow(nid){
                       var xmlHttp = getXMLHttp();
                       xmlHttp.onreadystatechange = function(){
                                              if(xmlHttp.readyState == 4){
                                                                     HandleResponse(xmlHttp.responseText); 
                                              }
                       }
                       var fileName = 'includes/utils/follow.php?nid='+nid;
                       xmlHttp.open("GET", fileName, true);
                       xmlHttp.send(null);
}

function HandleResponse(resp){
                       if(resp == 1) {
                                              alert("Congratulations! the listing has been added to your account.");
                       } else if(resp == 2) {
                                              alert("We are sorry, there was some problem with your request.");
                       } else if(resp == 3){
                                              alert("You need to log in in order to add listings to your account.");
                       } else if(resp == 5){
                                              alert("You are already following this listing.");          
                       }
}


/*delete picture from Manage Listing */
function HandleDeleted(resp){
                       if(resp == 1) {
                                              alert("Your picture has been deleted.");
                       } else if(resp == 2) {
                                              alert("We are sorry, there was some problem with your request.");
                       } else if(resp == 3){
                                              alert("You need to log in in order to delete pictures.");
                       }
}


function deletepic(nid){
                       var xmlHttp = getXMLHttp();
                       xmlHttp.onreadystatechange = function(){
                                              if(xmlHttp.readyState == 4){
                                                                     HandleDeleted(xmlHttp.responseText); 
                                              }
                       }
                       var fileName = 'includes/utils/deletepic.php?nid='+nid;
                       xmlHttp.open("GET", fileName, true);
                       xmlHttp.send(null);
}

/*check if user accepted terms and conditions in register */
function checkaccept(theForm){
                       if(theForm.acceptterms.checked == false){
                                              alert ('You must accept the terms and conditions in order to register.');
                                              return false;
                       } else { 	
                                              return true;
                       }
}

/* forms back to manage*/
function goback(){
                       window.location = "manage";              
}



/* Forms validation */
//////validate email
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

function validate_CheckBoxes(field,alerttxt){
    with(field){
        if (field[0].checked == false && field[1].checked == false){
            alert(alerttxt);return false;
        }else{
            return true;
        }
    }
}

function validate_required(field,alerttxt){
    with (field){
        if (value==null||value==""){
            alert(alerttxt);return false;
        }else{
            return true;
        }
    }
}

function validate_length(field, alerttxt){
    with (field){
        if (value.length<6){
             alert(alerttxt);return false;              
        }else{
             return true;          
        }
    }
}


function validate_email(emailStr) {
         with(emailStr){              
                       /* The following variable tells the rest of the function whether or not
                       to verify that the address ends in a two-letter country or well-known
                       TLD.  1 means check it, 0 means don't. */
                       var checkTLD=1;
                       /* The following is the list of known TLDs that an e-mail address must end with. */
                       var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
                       /* The following pattern is used to check if the entered e-mail address
                       fits the user@domain format.  It also is used to separate the username
                       from the domain. */
                       var emailPat=/^(.+)@(.+)$/;
                       /* The following string represents the pattern for matching all special
                       characters.  We don't want to allow special characters in the address. 
                       These characters include ( ) < > @ , ; : \ " . [ ] */
                       var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
                       /* The following string represents the range of characters allowed in a 
                       username or domainname.  It really states which chars aren't allowed.*/
                       var validChars="\[^\\s" + specialChars + "\]";
                       /* The following pattern applies if the "user" is a quoted string (in
                       which case, there are no rules about which characters are allowed
                       and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
                       is a legal e-mail address. */
                       var quotedUser="(\"[^\"]*\")";
                       /* The following pattern applies for domains that are IP addresses,
                       rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
                       e-mail address. NOTE: The square brackets are required. */
                       var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
                       /* The following string represents an atom (basically a series of non-special characters.) */
                       var atom=validChars + '+';
                       /* The following string represents one word in the typical username.
                       For example, in john.doe@somewhere.com, john and doe are words.
                       Basically, a word is either an atom or quoted string. */
                       var word="(" + atom + "|" + quotedUser + ")";
                       // The following pattern describes the structure of the user
                       var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
                       /* The following pattern describes the structure of a normal symbolic
                       domain, as opposed to ipDomainPat, shown above. */
                       var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
                       /* Finally, let's start trying to figure out if the supplied address is valid. */
                       /* Begin with the coarse pattern to simply break up user@domain into
                       different pieces that are easy to analyze. */
                       var matchArray=value.match(emailPat);
                       if (matchArray==null) {
                                              /* Too many/few @'s or something; basically, this address doesn't
                                              even fit the general mould of a valid e-mail address. */
                                              alert("Email address seems incorrect (check @ and .'s)");
                                              return false;
                       }
                       var user=matchArray[1];
                       var domain=matchArray[2];
                       // Start by checking that only basic ASCII characters are in the strings (0-127).
                       for (i=0; i<user.length; i++) {
                                              if (user.charCodeAt(i)>127) {
                                                                     alert("Ths username contains invalid characters.");
                                                                     return false;
                                              }
                       }
                       for (i=0; i<domain.length; i++) {
                                              if (domain.charCodeAt(i)>127) {
                                                                     alert("Ths domain name contains invalid characters.");
                                                                     return false;
                                              }
                       }
                       // See if "user" is valid 
                       if (user.match(userPat)==null) {
                                              // user is not valid
                                              alert("The username doesn't seem to be valid.");
                                              return false;
                       }
                       /* if the e-mail address is at an IP address (as opposed to a symbolic
                       host name) make sure the IP address is valid. */
                       var IPArray=domain.match(ipDomainPat);
                       if (IPArray!=null) {
                                              // this is an IP address
                                              for (var i=1;i<=4;i++) {
                                                                     if (IPArray[i]>255) {
                                                                                            alert("Destination IP address is invalid!");
                                                                                            return false;
                                                                     }
                                              }
                                              return true;
                       }
                       // Domain is symbolic name.  Check if it's valid.
                       var atomPat=new RegExp("^" + atom + "$");
                       var domArr=domain.split(".");
                       var len=domArr.length;
                       for (i=0;i<len;i++) {
                                              if (domArr[i].search(atomPat)==-1) {
                                                                     alert("The domain name does not seem to be valid.");
                                                                     return false;
                                              }
                       }
                       /* domain name seems valid, but now make sure that it ends in a
                       known top-level domain (like com, edu, gov) or a two-letter word,
                       representing country (uk, nl), and that there's a hostname preceding 
                       the domain or country. */
                       if (checkTLD && domArr[domArr.length-1].length!=2 && 
                                              domArr[domArr.length-1].search(knownDomsPat)==-1) {
                                              alert("The email address must end in a well-known domain or two letter " + "country.");
                                              return false;
                       }
                       // Make sure there's a host name preceding the domain.
                       if (len<2) {
                                              alert("This address is missing a hostname!");
                       return false;
                       }                    
                       // If we've gotten this far, everything's valid!
                       return true;
         }
}

//  End -->
////////////////////////////////////////////////////////////////////////////////////////

////validate numeric value
function validate_zip(field,alerttxt){
   with(field){
                       var valid = "0123456789-";
                       var hyphencount = 0;
                       if (value.length!=5 && value.length!=10) {
                       alert("Please enter your 5 digit or 5 digit+4 zip code.");
                       return false;
                       }
                       for (var i=0; i < value.length; i++) {
                       temp = "" + value.substring(i, i+1);
                       if (temp == "-") hyphencount++;
                       if (valid.indexOf(temp) == "-1") {
                       alert("Invalid characters in your zip code.  Please try again.");
                       return false;
                       }
                       if ((hyphencount > 1) || ((value.length==10) && ""+value.charAt(5)!="-")) {
                       alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
                       return false;
                          }
                       }
                       return true;
   }
}

function validate_web(field,alerttxt){
                       with(field){
                                              if (value!=null&&value!=""){
                                                                     var v = new RegExp();
                                                                     v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
                                                                     if (!v.test(value)) {
                                                                         alert(alerttxt);
                                                                         return false;
                                                                     } 
                                              }else{
                                                                     return true;
                                              }
                                              return true;
                       }
}

function validate_characters(field,alerttxt){
                       with(field){
                                              var iChars = "!@#$%^&*()+=-[]\;,./{}|\":<>?";   
                                              for(var i = 0; i < value.length; i++){   
                                                                     if(iChars.indexOf(value.charAt(i)) != -1){   	
                                                                                            alert(alerttxt);  
                                                                                            return false;  
                                                                     }  
                                              }
                                              return true;
                       }
}

function validate_onlytext(field,alerttxt){
                       with(field){
                                               var regExp = /^[A-Za-z\s*]$/;
                                              for(var i = 0; i < value.length; i++){   
                                                                     if(!value.charAt(i).match(regExp)){   	
                                                                                            alert(alerttxt);  
                                                                                            return false;  
                                                                     }  
                                              }
                                              return true;
                       }
}

function validate_onlynumbers(field,alerttxt){
                       with(field){
                                              if (value!=null&&value!=""){
                                                                     var regExp = /^[0-9\s*]$/;
                                                                     for(var i = 0; i < value.length; i++){   
                                                                                            if(!value.charAt(i).match(regExp)){   	
                                                                                                                   alert(alerttxt);  
                                                                                                                   return false;  
                                                                                            }  
                                                                     }
                                              }
                                              return true;        
                       }
}
///////VALIDATE PHONE NUMBER
                       // Declaring required variables
                       var digits = "0123456789";
                       // non-digit characters which are allowed in phone numbers
                       var phoneNumberDelimiters = "()- ";
                       // characters which are allowed in international phone numbers
                       // (a leading + is OK)
                       var validWorldPhoneChars = phoneNumberDelimiters + "+";
                       // Minimum no of digits in an international phone no.
                       var minDigitsInIPhoneNumber = 10;
                       
                       function isInteger(s)
                       {   var i;
                           for (i = 0; i < s.length; i++)
                           {   
                               // Check that current character is number.
                               var c = s.charAt(i);
                               if (((c < "0") || (c > "9"))) return false;
                           }
                           // All characters are numbers.
                           return true;
                       }
                       function trim(s)
                       {   var i;
                           var returnString = "";
                           // Search through string's characters one by one.
                           // If character is not a whitespace, append to returnString.
                           for (i = 0; i < s.length; i++)
                           {   
                               // Check that current character isn't whitespace.
                               var c = s.charAt(i);
                               if (c != " ") returnString += c;
                           }
                           return returnString;
                       }
                       function stripCharsInBag(s, bag)
                       {   var i;
                           var returnString = "";
                           // Search through string's characters one by one.
                           // If character is not in bag, append to returnString.
                           for (i = 0; i < s.length; i++)
                           {   
                               // Check that current character isn't whitespace.
                               var c = s.charAt(i);
                               if (bag.indexOf(c) == -1) returnString += c;
                           }
                           return returnString;
                       }
                       
                       function checkInternationalPhone(strPhone){
                                          
                                                                     var bracket=3
                                                                     strPhone=trim(strPhone)
                                                                     if(strPhone.indexOf("+")>1) return false
                                                                     if(strPhone.indexOf("-")!=-1)bracket=bracket+1
                                                                     if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
                                                                     var brchr=strPhone.indexOf("(")
                                                                     if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
                                                                     if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
                                                                     s=stripCharsInBag(strPhone,validWorldPhoneChars);
                                                                     return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);                   
                                         
                     
                       }


function validate_select(field, alerttxt){
                    with(field){
                                              if(field.selectedIndex==0){
                                                                     alert(alerttxt);
                                                                     return false;
                                              }
                                              return true;
                    }
}

function checifexistingemail(field){
                       var xmlHttp = getXMLHttp();
                       xmlHttp.onreadystatechange = function(){
                                              if(xmlHttp.readyState == 4){
                       
                                                                     ReturnResponse(xmlHttp.responseText);
                                                                     
                                              }
                       }
                       var fileName='includes/utils/checkemail.php?email='+field.value;
                       xmlHttp.open("GET", fileName, true);
                       xmlHttp.send(null);
}
function ReturnResponse(resp){
                       if(resp == 1) {
                                             
                                              alert("This email is already in use. Please try with a different one.");
                                              return false;
                                              
                       } else if(resp == 2) {
                                              return true;
                       }
                      
}

////register general user
function validate_form1(thisform){
    with(thisform){
        if(validate_required(fname,"First Name must be filled out!")==false){
                fname.focus();return false;
        }
        if(validate_characters(fname,"First Name contains special characters. Please remove them and try again.")==false){
                fname.focus();return false;
        }
        if(validate_onlytext(fname,"First Name  must contain only letters")==false){
                fname.focus();return false;       
        }
        if(validate_required(lname,"Last Name must be filled out!")==false){
                lname.focus();return false;
        }
        if(validate_onlytext(lname,"Last Name  must contain only letters")==false){
                lname.focus();return false;       
        }
        if(validate_characters(lname,"Last Name contains special characters. Please remove them and try again.")==false){
                lname.focus();return false;
        }
        if(validate_required(email,"Email must be filled out!")==false){
                email.focus();return false;
        }
        if(validate_email(email)==false){
                email.focus();return false;
        }
        if(validate_required(zip,"Zip Code must be filled out!")==false){
                zip.focus();return false;
        }
        if(validate_zip(zip,"Zip Code must contain only numbers")==false){
                 zip.focus(); return false;      
        }
        if(validate_required(email,"Email must be filled out!")==false){
                email.focus();return false;
        }
        if(validate_required(pass1,"Password must be filled out!")==false){
                pass1.focus();return false;
        }
        if(validate_required(pass2,"Password must be filled out!")==false){
                pass2.focus();return false;
        }
        if(validate_length(pass1,"Password must contain at least six characters!")==false){
                pass1.focus();return false;
        }
        if(validate_length(pass2,"Confirm Password must contain at least six characters!")==false){
                pass1.focus();return false;
        }
        if(thisform.pass1.value != thisform.pass2.value){
                alert("Error: Passwords that you've entered don't match!");
                thisform.pass1.focus();
                return false;        
        }
    }
}
///register premium user
function validate_form2(thisform){
    with(thisform){
        if(validate_required(fname,"First Name must be filled out!")==false){
                fname.focus();return false;
        }
        if(validate_characters(fname,"First Name contains special characters. Please remove them and try again.")==false){
                fname.focus();return false;
        }
       if(validate_onlytext(fname,"First Name  must contain only letters")==false){
                fname.focus();return false;       
        }
        if(validate_required(lname,"Last Name must be filled out!")==false){
                lname.focus();return false;
        }
        if(validate_characters(lname,"Last Name contains special characters. Please remove them and try again.")==false){
                lname.focus();return false;
        }
        if(validate_onlytext(lname,"Last Name  must contain only letters")==false){
                lname.focus();return false;       
        }
        if(validate_required(email,"Email must be filled out!")==false){
                email.focus();return false;
        }
        if(validate_email(email)==false){
                email.focus();return false;
        }
        if(validate_required(pass1,"Password must be filled out!")==false){
                pass1.focus();return false;
        }
        if(validate_required(pass2,"Password must be filled out!")==false){
                pass2.focus();return false;
        }
        if(validate_length(pass1,"Password must contain at least six characters!")==false){
                pass1.focus();return false;
        }
        if(validate_length(pass2,"Confirm Password must contain at least six characters!")==false){
                pass1.focus();return false;
        }
        if(thisform.pass1.value != thisform.pass2.value){
                alert("Error: Passwords that you've entered don't match!");
                thisform.pass1.focus();
                return false;        
        }
        if(validate_required(org_name,"Organization name must be filled out!")==false){
                org_name.focus();return false;
        }
        /////org name safe characters
        if(validate_characters(org_name,"Organization Name contains special characters. Please remove them and try again.")==false){
                org_name.focus();return false;
        }
        ///valid website
        if(validate_web(web,"Website address is not a valid URL")==false){
                       web.focus(); return false;
        }
        if(validate_required(street,"Street must be filled out!")==false){
                street.focus();return false;
        }
        if(validate_required(city,"City must be filled out!")==false){
                city.focus();return false;
        }       
        if(validate_required(zip,"Zip Code must be filled out!")==false){
                zip.focus();return false;
        }
        if(validate_zip(zip,"Zip Code must contain only numbers")==false){
                 zip.focus(); return false;      
        }
        if(validate_select(filter1, "You must make a selection to define your organization!")==false){
                  filter1.focus(); return false;     
        }
        /////other certification
        if(validate_characters(othercertification,"Growing Methods and Certifications field contains special characters. Please remove them and try again.")==false){
                othercertification.focus();return false;       
        }
        //////other organization
        if(validate_characters(otherbelong,"Organization you Belong to field contains special characters. Please remove them and try again.")==false){
                othercertification.focus();return false;       
        }
        ////contact fname empty - only letters
        if(validate_required(cfname,"Contact First Name must be filled out!")==false){
                cfname.focus();return false;
        }
        if(validate_onlytext(cfname,"Contact First Name  must contain only letters")==false){
                cfname.focus();return false;       
        }
        ////contact lname empty - only letters
        if(validate_required(clname,"Contact Last Name must be filled out!")==false){
                clname.focus();return false;
        }
        if(validate_onlytext(clname,"Contact Last Name  must contain only letters")==false){
                clname.focus();return false;       
        }
        ///cotnact email
        if(validate_required(cemail,"Contact Email must be filled out!")==false){
                cemail.focus();return false;
        }
        if(validate_email(cemail)==false){
                cemail.focus();return false;
        }
        ///validate phone

	if (checkInternationalPhone(phone.value)==false){
		alert("Please Enter a Valid Phone Number")
		phone.value="";
		phone.focus();
		return false;
	}/*
        if (checkInternationalPhone(fax.value)==false){
		alert("Please Enter a Valid Fax Number")
		fax.value="";
		fax.focus();
		return false;
	}*/
       
    }
}
////register non premium user
function validate_form3(thisform){
    with(thisform){
        if(validate_required(fname,"First Name must be filled out!")==false){
                fname.focus();return false;
        }
        if(validate_characters(fname,"First Name contains special characters. Please remove them and try again.")==false){
                fname.focus();return false;
        }
       if(validate_onlytext(fname,"First Name  must contain only letters")==false){
                fname.focus();return false;       
        }
        if(validate_required(lname,"Last Name must be filled out!")==false){
                lname.focus();return false;
        }
        if(validate_characters(lname,"Last Name contains special characters. Please remove them and try again.")==false){
                lname.focus();return false;
        }
        if(validate_onlytext(lname,"Last Name  must contain only letters")==false){
                lname.focus();return false;       
        }
        if(validate_required(email,"Email must be filled out!")==false){
                email.focus();return false;
        }
        if(validate_email(email)==false){
                email.focus();return false;
        }
        if(checifexistingemail(email)==false){
                email.focus();return false;       
        }
        if(validate_required(pass1,"Password must be filled out!")==false){
                pass1.focus();return false;
        }
        if(validate_required(pass2,"Password must be filled out!")==false){
                pass2.focus();return false;
        }
        if(validate_length(pass1,"Password must contain at least six characters!")==false){
                pass1.focus();return false;
        }
        if(validate_length(pass2,"Confirm Password must contain at least six characters!")==false){
                pass1.focus();return false;
        }
        if(thisform.pass1.value != thisform.pass2.value){
                alert("Error: Passwords that you've entered don't match!");
                thisform.pass1.focus();
                return false;        
        }
        if(validate_required(org_name,"Organization name must be filled out!")==false){
                org_name.focus();return false;
        }
        /////org name safe characters
        if(validate_characters(org_name,"Organization Name contains special characters. Please remove them and try again.")==false){
                org_name.focus();return false;
        }
        ///valid website
        if(validate_web(web,"Website address is not a valid URL")==false){
                       web.focus(); return false;
        }
        if(validate_required(street,"Street must be filled out!")==false){
                street.focus();return false;
        }
        if(validate_required(city,"City must be filled out!")==false){
                city.focus();return false;
        }       
        if(validate_required(zip,"Zip Code must be filled out!")==false){
                zip.focus();return false;
        }
        if(validate_zip(zip,"Zip Code must contain only numbers")==false){
                 zip.focus(); return false;      
        }
        if(validate_select(filter1, "You must make a selection to define your organization!")==false){
                  filter1.focus(); return false;     
        }
        ////contact fname empty - only letters
        if(validate_required(cfname,"Contact First Name must be filled out!")==false){
                cfname.focus();return false;
        }
        if(validate_onlytext(cfname,"Contact First Name  must contain only letters")==false){
                cfname.focus();return false;       
        }
        ////contact lname empty - only letters
        if(validate_required(clname,"Contact Last Name must be filled out!")==false){
                clname.focus();return false;
        }
        if(validate_onlytext(clname,"Contact Last Name  must contain only letters")==false){
                clname.focus();return false;       
        }
        ///cotnact email
        if(validate_required(cemail,"Contact Email must be filled out!")==false){
                cemail.focus();return false;
        }
        if(validate_email(cemail)==false){
                cemail.focus();return false;
        }       
        ////contact phone empty - only numbers
        if (checkInternationalPhone(phone.value)==false){
		alert("Please Enter a Valid Phone Number")
		phone.value="";
		phone.focus();
		return false;
	}
        ////contact fax  only numbers
        /*
        if (checkInternationalPhone(fax.value)==false){
		alert("Please Enter a Valid Fax Number")
		fax.value="";
		fax.focus();
		return false;
	}*/
    }
}

function validate_forgot(thisform){
                       with(thisform){
                                      if(validate_required(pass1,"Password must be filled out!")==false){
                                              pass1.focus();return false;
                                      }
                                      if(validate_required(pass2,"Password must be filled out!")==false){
                                              pass2.focus();return false;
                                      }
                                      if(validate_length(pass1,"Password must contain at least six characters!")==false){
                                              pass1.focus();return false;
                                      }
                                      if(validate_length(pass2,"Confirm Password must contain at least six characters!")==false){
                                              pass1.focus();return false;
                                      }
                                      if(thisform.pass1.value != thisform.pass2.value){
                                              alert("Error: Passwords that you've entered don't match!");
                                              thisform.pass1.focus();
                                              return false;        
                                      }                
                       }
}

function validate_locations(thisform){
                       with(thisform){
                                              for (i=0; i<thisform.childNodes.length; i++){
                                                                    if(thisform.childNodes[i].className=="bussiness"){
                                                                                            if(thisform.childNodes[i].childNodes[1].value==''||thisform.childNodes[i].childNodes[1].value==null){
                                                                                                                   alert("Bussiness Name must be filled out");return false;
                                                                                            }                 
                                                                     }
                                                                     if(thisform.childNodes[i].className=="street"){
                                                                                            if(thisform.childNodes[i].childNodes[1].value==''||thisform.childNodes[i].childNodes[1].value==null){
                                                                                                                   alert("Street must be filled out");return false;
                                                                                            }                 
                                                                     }
                                                                     if(thisform.childNodes[i].className=="city"){
                                                                                            if(thisform.childNodes[i].childNodes[1].value==''||thisform.childNodes[i].childNodes[1].value==null){
                                                                                                                   alert("City must be filled out");return false;
                                                                                            }                 
                                                                     }
                                                                     if(thisform.childNodes[i].className=="zip"){
                                                                                            if(thisform.childNodes[i].childNodes[1].value==''||thisform.childNodes[i].childNodes[1].value==null){
                                                                                                                   alert("Zip code must be filled out");return false;
                                                                                            }                
                                                                     }
                                                                     if(thisform.childNodes[i].className=="lname"){
                                                                                            if(thisform.childNodes[i].childNodes[1].value==''||thisform.childNodes[i].childNodes[1].value==null){
                                                                                                                   alert("Contact first name must be filled out");return false;
                                                                                            }                  
                                                                     }
                                                                     if(thisform.childNodes[i].className=="fname"){
                                                                                            if(thisform.childNodes[i].childNodes[1].value==''||thisform.childNodes[i].childNodes[1].value==null){
                                                                                                                   alert("Contact last name must be filled out");return false;
                                                                                            }                 
                                                                     }
                                                                     if(thisform.childNodes[i].className=="phone"){
                                                                                            if(thisform.childNodes[i].childNodes[1].value==''||thisform.childNodes[i].childNodes[1].value==null){
                                                                                                                   alert("Contact Phone must be filled out");return false;
                                                                                            } else{
                                                                                                                   return true;
                                                                                            }
                                                                     }
                                                                     
                                                                     
                                              }
                                               return false;
                       }
}


function validate_mod_user(thisform){
                        with(thisform){
                                     if(thisform.key.value != thisform.key2.value){
                                              alert("Error: Passwords that you've entered don't match!");
                                              thisform.pass1.focus();
                                              return false;        
                                      }                    
                        }
}
//////////////////////////////////////////////////////////////////////////////////////////
 
 ///show/hidde message for restaurants in registration page
 function doShowDiv(filter1Val){
                       if (filter1Val=="21"){
					      document.getElementById("restaurantDiv").style.visibility = "visible";
		       }else{
					      document.getElementById("restaurantDiv").style.visibility = "hidden"; 
		       }
}


 
 function getXMLHTTP(){ //fuction to return the xml http object
 var xmlhttp=false;	
 try{
  xmlhttp=new XMLHttpRequest();
 }
 catch(e){		
  try{			
   xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
  }
  catch(e){
   try{
     xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   }
   catch(e1){
    xmlhttp=false;
   }
  }
 }
 return xmlhttp;
}
function changePrevalence(pre,nid){
  var strURL="includes/utils/changePrevalence.php?pre="+pre+"&nid="+nid;
  var req = getXMLHTTP();
  if (req){
    req.onreadystatechange = function(){
      if (req.readyState == 4){
          // only if "OK"
          if (req.status == 200){
              alert(req.responseText)
          } else {
              alert("There was a problem while using XMLHTTP:\n" + req.statusText);
          }
      }
    }
   }
   req.open("GET", strURL, true);
   req.send(null);
                       
}
