/*
Created by Todd Dzur for opshop.org
Google Map Christmas lights. 2008

*/


/*
 Gives directions between a series of points within a given radius.
*/
//if (typeof(GIcon()) != "undefined")  {
	/*
var GEARTH_ICON = new GIcon(); GEARTH_ICON.iconSize=new GSize(32,32); GEARTH_ICON.shadowSize=new GSize(56,32); GEARTH_ICON.iconAnchor=new GPoint(16,32); GEARTH_ICON.infoWindowAnchor=new GPoint(16,0);

   
  var icons = {"start":new GIcon(G_DEFAULT_ICON, 'http://maps.google.com/mapfiles/dd-start.png'),
    "end":new GIcon(G_DEFAULT_ICON, 'http://maps.google.com/mapfiles/dd-end.png'),
    "caution": new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/kml/pal3/icon41.png'),
    "other":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/ltblue-dot.png'),
    "check":new GIcon(GEARTH_ICON, 'http://opshop.org/gmap/question.gif'),
    "tree":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/kml/pal2/icon12.png'),
    "street":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/ylw-pushpin.png'),
    "topstreet":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/grn-pushpin.png'),  
    "topstreetpic":new GIcon(GEARTH_ICON, 'http://opshop.org/christmas/grn-pushpin-dot.png'),  
    "lowstreet":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/red-pushpin.png'),  
    "checkstreet":new GIcon(GEARTH_ICON, 'http://opshop.org/gmap/question.gif'),
    "house":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/yellow.png'),
    "tophouse":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/green.png'),
    "lowhouse":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/red.png'),
    "housepic":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/yellow-dot.png'),
    "tophousepic":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/green-dot.png'),
    "check":new GIcon(GEARTH_ICON, 'http://opshop.org/christmas/question.gif'),
    "lowcheck":new GIcon(GEARTH_ICON, 'http://opshop.org/christmas/question.gif'),
    "topcheck":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/green.png')
    };
     */
//}
   
function closestMarkerSearch(map, markers, zoom, address,within) {
	
	  within = within * 1000
    if (markers.length == 0) {
        throw new Exception('No markers given');
    }
    var mymarkers = markers.slice();
    new GClientGeocoder().getLatLng(address, function(latLng) {
        if (latLng === null) {
            alert('Please enter an address');
        } else {
            var distance;
            var homedistnace;
            var closestDistance = null;
            var closestMarker = null;
            var drive = [];
            var tmpmarkers = new Array();
           if (pmarker) {
            	map.removeControl(pmarker);
            	pmarker.hide();
            }
            
            pmarker = createMarkerIcon(latLng,address,'',"start");
            map.addOverlay(pmarker);
            drive.push(pmarker.getLatLng());
            
            var cm;
            var c = 0;
            var stops = 15;
            //var debug = "<pre>Debug\n";
            for (var m = 0; m < stops;m++){
	            closestDistance = null;
              closestMarker = null;
              tmpmarkers = new Array();
              //debug += 'Stop ' + m + '\n';
	            for (var i = 0; i < mymarkers.length; i++) {
		              //debug += 'Marker ' + i + ' of ' + mymarkers.length;
		              if (latLng == mymarkers[i].getLatLng()) {
		              } else {
			              
		                distance = latLng.distanceFrom(mymarkers[i].getLatLng());
		                homedistance = pmarker.getLatLng().distanceFrom(mymarkers[i].getLatLng());
		                c++;
		                //if (distance>within && m == 0) {
			              if (homedistance>within) {
			                  farMarker = mymarkers[i];
			               	  farMarker.hide();
		                } else if (mymarkers[i].getIcon().image.match(/red/)) {
			                //alert("Low rated");
		                } else { 	
			            	closeMarker = mymarkers[i];
			                closeMarker.show();
			                if (closestDistance === null || distance < closestDistance ) {
		                    	closestDistance = distance;
		                    	closestMarker = mymarkers[i];
		                    	cm = i;
		                	}
		                	tmpmarkers.push(mymarkers[i]);
		                	 
	                  } 
	               }
	               if (mymarkers.length <= i) {i=mymarkers.length;}
	            }
	           
	           if (closestMarker == null) {
		           // alert ("No Closest Marker:" + cm);
	           }else{
		            //Add marker to route and remove the marker from array.
								
		            drive.push(closestMarker.getLatLng());
								latLng = closestMarker.getLatLng();
								
								var isNotSame = function(x) {
			   						if (x.getLatLng() == latLng) { return false; } else { return true; }
								}
				
								mymarkers = tmpmarkers.filter(isNotSame);
				
				  	}
			  
			  /* Work here */
			  
			  	if (m >= 10) { 
				  	within = latLng.distanceFrom(pmarker.getLatLng());
			  	 //alert (within);
			  	 }
			  
			  	 
			  /*End here */
			  
				if (mymarkers < 1) { m = stops; }
		    }//End Loops
					  
            if (closestDistance < 2000) { zoom = 14; } else if (closestDistance< 4000) { zoom = 12;} else { zoom = 10;}
            map.setZoom(zoom);
            map.setCenter(latLng);

            
			document.getElementById("route").innerHTML = "";
            directions.clear();
            directions = new GDirections(map,directionsPanel);
            directions.loadFromWaypoints(drive);

        		GEvent.addListener(directions, 'load', function(){ // Listnener for directions on load 
        			   	document.getElementById('dist').innerHTML = (directions.getDistance().meters / 1000).toPrecision(4) + ' km, not including return travel';   // Fill kilometers  
        		}); 
        }
    });
}

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}

//******************************
function closestList2(map, markers, zoom, address,within) {

	  //directions.clear();
	  var debug = "";
	  within = within * 1000
	  
    if (markers.length == 0) {
	  
        throw new Exception('No markers given');
    }
  
    var mymarkers = markers.slice();

    new GClientGeocoder().getLatLng(address, function(latLng) {

        if (latLng === null) {
            alert('Please enter an address - or address not found');
        } else {
           var distance;
           if (pmarker) {
            	map.removeControl(pmarker);
            	pmarker.hide();
            }
            
            pmarker = createMarkerIcon(latLng,address,'',"start");
            map.addOverlay(pmarker);
                        
            var c = 0;
						var hidden = false;
            var listmarkers = [];
            for (var i = 0; i < mymarkers.length; i++) {
	             if (mymarkers[i] != null){
			           if (latLng == mymarkers[i].getLatLng()) {
				              
			           } else {
				              distance = latLng.distanceFrom(mymarkers[i].getLatLng());
				              
			                //debug += mymarkers[i].getTitle() + ',' + i + ',' + (distance / 1000).toPrecision(4) + ',' +  mymarkers[i].getLatLng() +  '<br />';
			                if (latLng.distanceFrom(mymarkers[i].getLatLng())>within) {
				                  farMarker = mymarkers[i];
				               	  farMarker.hide();
											} else if (mymarkers[i].getIcon().image.match(/red/)) {
			                //alert("Low rated");
			                } else { 	
				                 closeMarker = mymarkers[i];
				                 closeMarker.show();
				                 listmarkers.push(mymarkers[i]);
				                 //debug += mymarkers[i].getTitle() + ',' + i + ',' + (distance / 1000).toPrecision(4) + ',' +  mymarkers[i].getLatLng() + ',' + (latLng.distanceFrom(mymarkers[i].getLatLng()) / 1000).toPrecision(4) + '<br />';	 
			                }
		                } 

	         			}       

		         }

	           

            zoom = 12;
            map.setZoom(zoom);
            map.setCenter(latLng);
            listmarkers.sort(sortLatLng);
             
            var msg = "";
            for (var i=0;i < listmarkers.length; i++){
	           	msg += listmarkers[i].getTitle() + '<br /><br />';
            }     
						document.getElementById("rightlist").innerHTML = msg;
						document.getElementById("debug").innerHTML = debug;
      
        }
    });
}
function sortLatLng(a, b){
//Compare "a" and "b" in some fashion, and return -1, 0, or 1
  return  (b.getLatLng().lat() - a.getLatLng().lat());
}
//******************************

// Creates a marker whose info window displays the given number
function createMarker(point, number, sid)
{
var marker = new GMarker(point, {title: number});
// Show this markers index in the info window when it is clicked
var html = number;
GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html); storeDetails(sid);});
//storeDetails
return marker;
};


function createMarkerIcon(point, mtitle, name, icon) {
  //alert(icon);
  
  var GEARTH_ICON = new GIcon(); GEARTH_ICON.iconSize=new GSize(32,32); GEARTH_ICON.shadowSize=new GSize(56,32); GEARTH_ICON.iconAnchor=new GPoint(16,32); GEARTH_ICON.infoWindowAnchor=new GPoint(16,0);

   
  var icons = {"start":new GIcon(G_DEFAULT_ICON, 'http://maps.google.com/mapfiles/dd-start.png'),
    "end":new GIcon(G_DEFAULT_ICON, 'http://maps.google.com/mapfiles/dd-end.png'),
    "caution": new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/kml/pal3/icon41.png'),
    "other":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/ltblue-dot.png'),
    "check":new GIcon(GEARTH_ICON, 'http://opshop.org/gmap/question.gif'),
    "tree":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/kml/pal2/icon12.png'),
    "street":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/ylw-pushpin.png'),
    "topstreet":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/grn-pushpin.png'),  
    "topstreetpic":new GIcon(GEARTH_ICON, 'http://opshop.org/christmas/grn-pushpin-dot.png'),  
    "lowstreet":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/red-pushpin.png'),  
    "checkstreet":new GIcon(GEARTH_ICON, 'http://opshop.org/gmap/question.gif'),
    "house":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/yellow.png'),
    "tophouse":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/green.png'),
    "lowhouse":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/red.png'),
    "housepic":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/yellow-dot.png'),
    "tophousepic":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/green-dot.png'),
    "check":new GIcon(GEARTH_ICON, 'http://opshop.org/christmas/question.gif'),
    "lowcheck":new GIcon(GEARTH_ICON, 'http://opshop.org/christmas/question.gif'),
    "topcheck":new GIcon(GEARTH_ICON, 'http://maps.google.com/mapfiles/ms/micons/green.png')
    };
    
  if (icon) {
  	var marker = new GMarker(point, {
    icon: icons[icon],
    draggable: false,
    bouncy: false,
    title:mtitle
  });
  }else{
  	var marker = new GMarker(point);
  }
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(mtitle + '<br />' + name);
  });

  return marker;
}
// Creates a marker whose info window displays the given number
function createMarkers(point,stitle, mtitle, sid)
{
var marker = new GMarker(point, {title: stitle});
// Show this markers index in the info window when it is clicked
var html = mtitle;
GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html); storeDetails(sid);});
//storeDetails
return marker;
};

function vote(id,r) {
	
	
   if (r < 1 || r > 5) {
	     alert ("Voting error");
   } else {
	    //popUp('christmas_vote.php?id=' + id + '&rank=' + r + '&by=')
      
      var url = "/phpsql_vote.php?id=" + id + "&rank=" + r + "&by=";
      GDownloadUrl(url, function(data, responseCode) {
        if (responseCode == 200 && data.length <= 2) {
          marker.closeInfoWindow();
          document.getElementById("message").innerHTML = "Ranking added. Page will need to be reloaded to see any changes";
         
        } else {
        	document.getElementById("message").innerHTML = "<img src='http://maps.google.com/mapfiles/ms/micons/caution.png' /> Ranking error. " + data;
      	}
      });
      
    }
}

function votelist(id,r) {
	
	
   if (r < 1 || r > 5) {
	     alert ("Voting error");
   } else {
	    //popUp('christmas_vote.php?id=' + id + '&rank=' + r + '&by=')
      
      var url = "/phpsql_vote.php?id=" + id + "&rank=" + r + "&by=";
      GDownloadUrl(url, function(data, responseCode) {
        if (responseCode == 200 && data.length <= 2) {
          document.getElementById("message").innerHTML = "Ranking added. Page will need to be reloaded to see any changes";
         
        } else {
        	document.getElementById("message").innerHTML = "<img src='http://maps.google.com/mapfiles/ms/micons/caution.png' /> Ranking error. " + data;
      	}
      });
      
    }
}

function votelistc(id,r,com,chk) {
	
//alert("Test votelistc:1");
   if (r < 1 || r > 5) {
	     alert ("Voting error");
   } else {
      var url = "/phpsql_votecomment.php?id=" + id + "&rank=" + r + "&comment=" + com + "&chk=" + chk;
      GDownloadUrl(url, function(data, responseCode) {
        if (responseCode == 200 && data.length <= 2) {
          document.getElementById("message").innerHTML = "Ranking added. Page will need to be reloaded to see any changes";
          if (marker) {marker.closeInfoWindow()};
        } else {
        	document.getElementById("message").innerHTML = data;
      	}
      });
      
    }
}


function login(e) {
	  document.getElementById("message").innerHTML = "Trying to Login";
	  var url = "/login.php?email=" + e;
      GDownloadUrl(url, function(data, responseCode) {
        if (responseCode == 200 && data.length <= 2) {
          document.getElementById("message").innerHTML = "Email Registred OK.";
          //document.getElementById("login").innerHTML = "";
          if (marker) {marker.closeInfoWindow()};
         
        } else {
        	document.getElementById("message").innerHTML = "<img src='http://maps.google.com/mapfiles/ms/micons/caution.png' /> Login Error. " + data;
      	}
      });
      
}

function showlogin() {
	document.getElementById("login").innerHTML = "<form onsubmit=\"login2(document.getElementById('email').value); return false\">Email:<input type='text' id='email' /> <input type=submit value='Login' /></form><br />";
}
function login2(e) {
	  document.getElementById("message").innerHTML = "Trying to Login";
	  var url = "/login2.php?email=" + e;
      GDownloadUrl(url, function(data, responseCode) {
		
        if (responseCode == 200 && Left(data,4) == "user") {
	        
	      document.getElementById("message").innerHTML = "";
          document.getElementById("userdetails").innerHTML = "<b>" + Mid(data,5,50) + "</b>";
          document.getElementById("login").innerHTML = "";
          if (typeof(marker) != "undefined") {marker.closeInfoWindow()};
         
        } else {
        	document.getElementById("message").innerHTML = "<img src='http://maps.google.com/mapfiles/ms/micons/caution.png' /> Login Error. " + data;
      	}
      });
      
}

function login2a(e) {
	  document.getElementById("message").innerHTML = "Trying to Login";
	  var url = "/login2.php?email=" + e;
      GDownloadUrl(url, function(data, responseCode) {
		
        if (responseCode == 200 && Left(data,4) == "user") {
	        
	      document.getElementById("message").innerHTML = "";
          document.getElementById("userdetails").innerHTML = "<b>" + Mid(data,5,50) + "</b>";
          document.getElementById("login").innerHTML = "";
          document.getElementById('mainpage').style.display = 'block'; 
          if (typeof(marker) != "undefined") {marker.closeInfoWindow()};
         
        } else {
        	document.getElementById("message").innerHTML = "<img src='http://maps.google.com/mapfiles/ms/micons/caution.png' /> Login Error. " + data;
      	}
      });
      
}

function login_faceb() {
	  document.getElementById("message").innerHTML = "Trying to Login";
	  var url = "/connectAccount.php";
      GDownloadUrl(url, function(data, responseCode) {
		
        if (responseCode == 200 && Left(data,4) == "user") {
	        
	      document.getElementById("message").innerHTML = "";
          document.getElementById("userdetails").innerHTML = "<b>" + Mid(data,5,50) + "</b>";
          document.getElementById("login").innerHTML = "";
          document.getElementById('mainpage').style.display = 'block'; 
          if (typeof(marker) != "undefined") {marker.closeInfoWindow()};
         
        } else {
        	document.getElementById("message").innerHTML = "<img src='http://maps.google.com/mapfiles/ms/micons/caution.png' /> Login Error. " + data;
      	}
      });
      
}




function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=400,height=200,left = 440,top = 412');");
}

function loadDetail(id) {
	  // var oVDiv=document.getElementById('ID'+id);
      //alert("The content of the first DIV element is " + "\"" + oVDiv.innerHTML + "\".");
    $('#ID'+id).toggleClass('hide');
	if (document.getElementById('ID'+id).innerHTML == "" || document.getElementById('ID'+id).innerHTML == "&nbsp;") {
	   //document.getElementById('ID'+id).innerHTML == "Loading..."
	   $('#ID'+id).empty().html('<img src="/images/loader.gif" />');
	   $('#ID'+id).load('/phpsql_storedetailsNew.php?id='+id);
	 }
     
}
function loadDetailH(id) {
	  // var oVDiv=document.getElementById('ID'+id);
      //alert("The content of the first DIV element is " + "\"" + oVDiv.innerHTML + "\".");
   $('#ID'+id).toggleClass('hide');
	if (document.getElementById('ID'+id).innerHTML == "") {
	   //document.getElementById('ID'+id).innerHTML == "Loading..."
	   $('#ID'+id).empty().html('<img src="/images/loader.gif" />');
	   $('#ID'+id).load('/phpsql_storedetailsNew.php?h=true&id='+id);
	 }
      
}


function votelistajax(id,r,com,chk) {
	
   if (r < 1 || r > 5) {
	     alert ("Voting error");
   } else {
      var url = "/phpsql_votecommentajax.php?id=" + id + "&rank=" + r + "&comment=" + com + "&chk=" + chk;
      $('#message').load(url);
      
      
    }
}


function storeDetails2(id, map) {
	if (id < 1) {
	     alert ("Store id error");
   } else {
	    //popUp('phpsql_storedetails.php?id=' + id);
      
      var url = "/phpsql_storedetails.php?id=" + id + "&showmap=" + map;
      GDownloadUrl(url, function(data, responseCode) {
        if (responseCode == 200) {
          document.getElementById("rightlist").innerHTML = data;
        } else {
        	document.getElementById("message").innerHTML = "Error retriving store details" & data & "<br />";
      	}
      });
      
    }
}
function storeDetails(id) {
	
	storeDetails2(id, "false");
	 /*if (id < 1) {
	     alert ("Store id error");
   } else {
	    //popUp('phpsql_storedetails.php?id=' + id);
      
      var url = "/phpsql_storedetails.php?id=" + id;
      GDownloadUrl(url, function(data, responseCode) {
        if (responseCode == 200) {
          document.getElementById("rightlist").innerHTML = data;
        } else {
        	document.getElementById("message").innerHTML = "Error retriving store details" & data & "<br />";
      	}
      });
      
    }*/
}

   function Right(str, n)
        /***
                IN: str - the string we are RIGHTing
                    n - the number of characters we want to return

                RETVAL: n characters from the right side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                   return "";
                else if (n > String(str).length)   // Invalid bound, return
                   return str;                     // entire string
                else { // Valid bound, return appropriate substring
                   var iLen = String(str).length;
                   return String(str).substring(iLen, iLen - n);
                }
        }
        
               function Mid(str, start, len)
        /***
                IN: str - the string we are LEFTing
                    start - our string's starting position (0 based!!)
                    len - how many characters from start we want to get

                RETVAL: The substring from start to start+len
        ***/
        {
                // Make sure start and len are within proper bounds
                if (start < 0 || len < 0) return "";

                var iEnd, iLen = String(str).length;
                if (start + len > iLen)
                        iEnd = iLen;
                else
                        iEnd = start + len;

                return String(str).substring(start,iEnd);
        }
        
               function Left(str, n)
        /***
                IN: str - the string we are LEFTing
                    n - the number of characters we want to return

                RETVAL: n characters from the left side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                        return "";
                else if (n > String(str).length)   // Invalid bound, return
                        return str;                // entire string
                else // Valid bound, return appropriate substring
                        return String(str).substring(0,n);
        }