

jQuery.fn.extend({everyTime:function(b,c,d,e,a){return this.each(function(){jQuery.timer.add(this,b,c,d,e,a)})},oneTime:function(a,b,c){return this.each(function(){jQuery.timer.add(this,a,b,c,1)})},stopTime:function(a,b){return this.each(function(){jQuery.timer.remove(this,a,b)})}});jQuery.event.special;jQuery.extend({timer:{global:[],guid:1,dataKey:"jQuery.timer",regex:/^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,powers:{ms:1,cs:10,ds:100,s:1000,das:10000,hs:100000,ks:1000000},timeParse:function(c){if(c==undefined||c==null){return null}var a=this.regex.exec(jQuery.trim(c.toString()));if(a[2]){var b=parseFloat(a[1]);var d=this.powers[a[2]]||1;return b*d}else{return c}},add:function(e,c,h,g,b,f){var a=0;if(jQuery.isFunction(h)){if(!b){b=g}g=h;h=c}c=jQuery.timer.timeParse(c);if(typeof c!="number"||isNaN(c)||c<=0){return}if(b&&b.constructor!=Number){f=!!b;b=0}b=b||0;f=f||false;var d=jQuery.data(e,this.dataKey)||jQuery.data(e,this.dataKey,{});if(!d[h]){d[h]={}}g.timerID=g.timerID||this.guid++;var i=function(){if(f&&this.inProgress){return}this.inProgress=true;if((++a>b&&b!==0)||g.call(e,a)===false){jQuery.timer.remove(e,h,g)}this.inProgress=false};i.timerID=g.timerID;if(!d[h][g.timerID]){d[h][g.timerID]=window.setInterval(i,c)}this.global.push(e)},remove:function(c,b,d){var e=jQuery.data(c,this.dataKey),a;if(e){if(!b){for(b in e){this.remove(c,b,d)}}else{if(e[b]){if(d){if(d.timerID){window.clearInterval(e[b][d.timerID]);delete e[b][d.timerID]}}else{for(var d in e[b]){window.clearInterval(e[b][d]);delete e[b][d]}}for(a in e[b]){break}if(!a){a=null;delete e[b]}}}for(a in e){break}if(!a){jQuery.removeData(c,this.dataKey)}}}}});jQuery(window).bind("unload",function(){jQuery.each(jQuery.timer.global,function(a,b){jQuery.timer.remove(b)})});

var currIcon = "friendly";
var route_data = [];
var curr_step = 1;
var recordon = true; 
var pointset = false; 

// ICONS ---------------------------------------
var iconwayPoint = new GIcon();
iconwayPoint.image = 'http://farmerdane.ca/hushcrush.ca/_img/orange_smiley.png';
iconwayPoint.iconSize = new GSize(12, 20);
//iconwayPoint.shadowSize = new GSize(6, 6);
iconwayPoint.iconAnchor = new GPoint(6, 20);
iconwayPoint.infoWindowAnchor = new GPoint(5, 1);

var iconStart = new GIcon();
iconStart.image = 'http://farmerdane.ca/hushcrush.ca/_img/red_smiley.png';
iconStart.iconSize = new GSize(12, 20);
//iconwayPoint.shadowSize = new GSize(6, 6);
iconStart.iconAnchor = new GPoint(6, 20);
iconStart.infoWindowAnchor = new GPoint(5, 1);

var iconPoop = new GIcon();
iconPoop.image = 'http://pooptheworld.com/_img/iphone_map/pointer-poop.png';
iconPoop.iconSize = new GSize(30, 26);
//iconwayPoint.shadowSize = new GSize(6, 6);
iconPoop.iconAnchor = new GPoint(6, 20);
iconPoop.infoWindowAnchor = new GPoint(12,0);

var customIcons = [];
customIcons["poop"] = iconPoop;


// ******************************************************
// START OF PAGE LOADING FUNCTIONS ----------------------
// ******************************************************

var sel = 0;
$().ready(function() {
 load();
});

function loadListener(){
 mainmap.disableDoubleClickZoom();
 GEvent.bind(mainmap, "click", this, this.addPoint);
};

function load() {

 if (GBrowserIsCompatible()) {
 mainmap = new GMap2(document.getElementById("map"), {draggableCursor:"auto", draggingCursor:"move"});
 //mainmap.addControl(new GLargeMapControl()); // Zoom control
 //mainmap.addControl(new GMapTypeControl()); // Toggle between map types
 //mainmap.addControl(new GScaleControl()); // Scale bar
 mainmap.setCenter(new GLatLng(49.270, -123.135), 13);
 //mainmap.disableDragging();
 //mainmap.setMapType(G_SATELLITE_TYPE);
 //loadListener();
 /*makeTooltip();*/
 }



};
var addsightings = [];
var ret_findloc;
function resetForm(){
 $("#form-findloc").resetForm();
};


function getGAddress(response){
 
 ret_findloc = $("#form-findloc").validate().form();
 if(ret_findloc){
 if (!response || response.Status.code != 200) {
 alert("Sorry, we were unable to geocode that address");
 } else {
 place = response.Placemark[0];
 
 try{
 var curr_countrycode = place.AddressDetails.Country.CountryNameCode;
 var curr_country = place.AddressDetails.Country.CountryName;
 var curr_province = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
 var curr_city = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
 var curr_tf = place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
 var curr_postal = place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
 }catch(err){ 
 alert(place.address); 
 //alert(curr_countrycode + " - " + curr_country+ " - " + curr_province+ " - " + curr_city+ " - " + curr_tf+ " - " + curr_postal);
 }
 
 
 point = new GLatLng(place.Point.coordinates[1],
 place.Point.coordinates[0]);
 marker = new GMarker(point, {icon: customIcons[currIcon], draggable:true, bouncy:true });
 var s = new Sighting(marker);
 
 checkUnsetPoint(); 
 addsightings.push(s);
 mainmap.addOverlay(s.marker); 
 setDragListeners(s.marker);
 
 /* If clicked disable the point addition */
 recordon = false;
 marker.openInfoWindowHtml('<div class="pwindow">'+place.address + '<br>' +
 '<b>Country code:</b> ' + curr_countrycode+'<br/><br/><div>Do you want to add your sighting here?</div><div><a href="javascript:void(0)" onclick="setPoint()">Yes</a> &nbsp; <a href="javascript:void(0)" onclick="checkUnsetPoint()">No</a></div></div>');
 
 marker.disableDragging()
 
 GEvent.addListener(marker, "click", function() {
 mainmap.removeOverlay(marker);
 });
 
 mainmap.setCenter(point, 15);
 
 }
 }
};

function findLocation() {
 var geocoder = new GClientGeocoder();
 address = $("#addressloc").val();
 geocoder.getLocations(address, getGAddress);
};

function setDragListeners(marker){
 
 GEvent.addListener(marker, "dragstart", function() {
 /* re-enable the point addition */
 recordon = true;
 });

 GEvent.addListener(marker, "dragend", function() {
 
 });
};

function changeStepImg(num, img){
 $('#step-icon').attr('src',sitebase+'_img/'+img+"_"+num+".gif");
 $('#step-icon').attr('alt',"Step " + num + " of 3");
}

function prevStep(num){
 //if there is a marker show step 2
 if(addsightings.length > 0){
 $("#step-"+(num+1)).hide();
 $("#step-"+num).fadeIn();
 redrawSIFR();
 changeStepImg(num,"circles_step");
 }
};

function enableButton(num){ 
 $('#butnext-'+num).attr('src',sitebase+"_img/button_next.gif");
};

function disableButton(num){
 $('#butnext-'+num).attr('src',sitebase+"_img/button_next_disabled.gif");
};

function changeIcon(icontype){
 currIcon = icontype;
 if(addsightings.length > 0){
 var m = addsightings.pop();
 var marker = new GMarker(m.marker.getPoint(), {icon: customIcons[currIcon], draggable:true, bouncy:true });
 var s = new Sighting(marker);
 setDragListeners(s.marker);
 mainmap.removeOverlay(m.marker)
 mainmap.addOverlay(s.marker)
 addsightings.push(s);
 }
};

function showStep(num){
 //if there is a marker show step 2
 if(addsightings.length > 0){
 resetForm();
 $("#step-"+(num-1)).hide();
 $("#step-"+num).fadeIn();
 redrawSIFR();
 changeStepImg(num,"circles_step");
 }
};

function hideStep(num){
 $("#step-"+num).hide();
};


function showBusyRight(){
 $('#right-loading-content').show();
};

function hideBusyRight(){
 $('#right-loading-content').hide();
};

function checkUnsetPoint() {
 /* re-enable the point addition */
 recordon = true;
 if(addsightings.length > 0){
 addsightings[0].marker.enableDragging();
 }
 
 var curradd = addsightings.pop(); 
 if(curradd !== undefined){
 mainmap.removeOverlay(curradd.marker); 
 pointset = false;
 disableButton(1);
 }
 
 return curradd;
};

function setPoint() {
 /* re-enable the point addition and dragging */
 recordon = true; 
 
 
 if(addsightings.length > 0){
 addsightings[0].marker.enableDragging();
 mainmap.closeInfoWindow();
 pointset = true;
 enableButton(1);
 } 

};



function changeIcon(icontype){
 currIcon = icontype;
 if(addsightings.length > 0){
 var m = addsightings.pop();
 var marker = new GMarker(m.marker.getPoint(), {icon: customIcons[currIcon], draggable:true, bouncy:true });
 var s = new Sighting(marker);
 setDragListeners(s.marker);
 mainmap.removeOverlay(m.marker)
 mainmap.addOverlay(s.marker)
 addsightings.push(s);
 }
};


function addPoint(overlay, point){

 if(recordon){
 addWayPoint(point);
 }
};

function addWayPoint(point){
 
 if(point){ 
 checkUnsetPoint();
 var marker = new GMarker(point, {icon: customIcons[currIcon], draggable:true, bouncy:true }); 
 var s = new Sighting(marker);
 setDragListeners(s.marker);
 addsightings.push(s);
 mainmap.addOverlay(s.marker);
 pointset = true;
 enableButton(1);
 
 }
 

};

function Sighting(m, title, descrip, intersection){
 this.marker = (m === undefined)? null : m;
 this.description = (descrip === undefined)? "" : descrip;
 this.title = (title === undefined)? "" : title;
 this.intersection = (intersection === undefined)? "" : intersection;
};
 
 

var MapScroll = {
 innerCall : 'innerfunc_ms',
 mappoints : [],
 currData : [],
 refreshMap : false,
 gmap : null,
 showbubble : false,
 userview : false,

 _getData : function (speed, uname){
 
 var req_url = (MapScroll.userview === false) ? "/getPoops/" : "/getPoops/userid/" + MapScroll.userview;
 
 $.getJSON(req_url,
 function(data){
 $.each(data, function(i,item){
 MapScroll.currData.push(item);
 }); 
 //reverse the order to get most recent first
 MapScroll.currData.reverse();
 
 //MapScroll.intID = setInterval("MapScroll._addPoint()", speed);
 if(!MapScroll.refreshMap){
 MapScroll._addPoint();
 $(document).everyTime(speed, MapScroll.innerCall, function() {
 MapScroll._addPoint();
 });
 MapScroll.refreshMap = true;
 }

 });
 },

 stopUpdate: function(uname){
 $(document).stopTime(uname);
 $(document).stopTime(MapScroll.innerCall);
 MapScroll.refreshMap = false;
 },
 update: function(amap, uname, speed, ajaxgrabspeed, showbubble, userview){
 if(showbubble === true){
 MapScroll.showbubble = showbubble;
 }
 
 if(userview !== undefined){
 MapScroll.userview = userview;
 }
 
 MapScroll._getData(speed, uname);
 MapScroll._gMap = amap; 

 $(document).everyTime(ajaxgrabspeed, uname, function() {
 MapScroll._getData(speed, uname);
 });

 },

 _addPoint: function(){ 

 var cdat = MapScroll.currData.pop();
 if(cdat !== undefined){
 
 var old = MapScroll.mappoints.pop();
 if(old !== undefined){
 MapScroll._gMap.removeOverlay(old);
 }
 
 var point = new GLatLng(cdat.latitude, cdat.longitude);
 var marker = new GMarker(point, {icon: customIcons['poop'], draggable:false, bouncy:true });
 MapScroll.mappoints.push(marker);
 MapScroll._gMap.addOverlay(marker);
 
 
 var html ='<div class="crush-box clearfix" style="width: 265px; height: 70px; overflow: hidden;"><div class="cb-left"><img src="_img/poops/'+cdat.image_id+'_sm.jpg" /></div><div class="cb-right"><div class="top-row"><div class="clearfix first"><p><a href="map/'+cdat.user_id+'">'+cdat.sUsername+'</a></p></div><h2 id="poopname">'+cdat.name+'</h2></div><p class="key">'+cdat.dateadded_abbr+'</p><p><span id="smellslike">Smells Like:&nbsp;</span>'+cdat.fname+'</p></div></div>';
 
 if(MapScroll.showbubble)
 marker.openInfoWindowHtml(html);
 
 //marker.openInfoWindowHtml(html);
 this._drawText(cdat)
 MapScroll._gMap.setZoom(10);
 MapScroll._gMap.panTo(point);

 }

 
 },
 
 _drawText: function (cdat){
 var html ='\
 <div id="content-frame">\
 <p><a href="map/'+cdat.user_id+'">'+cdat.sUsername+'</a></p>\
 <h2>'+cdat.name+'</h2>\
 <p class="key">'+cdat.dateadded_abbr+'</p>\
 <p><span id="smellslike">Smells Like:</span><br />'+cdat.fname+'</p>\
 </div>\
 ';
 $('#ib-right').html(html);
 $('#poop-image').attr('src', 'http://pooptheworld.com/_img/poops/'+cdat.image_id+'.jpg');
 }

};

var UserPoops = {
 innerCall : 'innerfunc_ms',
 mappoints : [],
 currData : [],
 refreshMap : false,
 gmap : null,
 showbubble : false,

 update: function(map, uid){
 UserPoops._gMap = map;
 UserPoops._gMap.addControl(new GLargeMapControl()); // Zoom control
 UserPoops._gMap.setCenter(new GLatLng(0,0),1);
 var bounds = new GLatLngBounds();
 
 // If something isn't working, it is the following code.
 // Delete the block below, and the map will work fine!
 ///*
 if(uid === 0) {
 var point = new GLatLng(0,0);
 var marker = new GMarker(point, {icon: customIcons['poop'], draggable:false, bouncy:true });
 UserPoops._gMap.addOverlay(marker);
 //bounds.extend(point);
 //UserPoops._gMap.setZoom(UserPoops._gMap.getBoundsZoomLevel(bounds));
 //UserPoops._gMap.setCenter(bounds.getCenter());
 
 UserPoops._gMap.setZoom(1);
 
 GEvent.addListener(marker, "click", function() {
 var html ='<div class="crush-box clearfix" style="width: 265px; height: 70px; overflow: hidden;"><div class="cb-right"><div class="top-row"><div class="clearfix first"><p style="font-size: 14px; font-weight: 800; color: #2c729a;">Click a username below to view their trail of destruction!</p></div></div></div></div>'; 
 marker.openInfoWindowHtml(html);
 }); 
 
 var html ='<div class="crush-box clearfix" style="width: 265px; height: 70px; overflow: hidden;"><div class="cb-right"><div class="top-row"><div class="clearfix first"><p style="font-size: 14px; font-weight: 800; color: #2c729a;">Click a username below to view their trail of destruction!</p></div></div></div></div>'; 
 marker.openInfoWindowHtml(html);
 }
 else {
 //*/
 // End block, which is probably broken
 
 $.getJSON(sitebase+"getUserPoops/"+uid,
 function(data){
 //alert(data);
 $.each(data, function(i,item){
 var point = new GLatLng(item.latitude, item.longitude);
 var marker = new GMarker(point, {icon: customIcons['poop'], draggable:false, bouncy:true });
 marker.fname = item.fname;
 marker.sUsername = item.sUsername;
 marker.dateadded_abbr = item.dateadded_abbr;
 marker.image_id = item.image_id;
 marker.name = item.name;
 UserPoops._gMap.addOverlay(marker); 
 bounds.extend(point); 
 UserPoops._gMap.setZoom(UserPoops._gMap.getBoundsZoomLevel(bounds));
 UserPoops._gMap.setCenter(bounds.getCenter());
 
 GEvent.addListener(marker, "click", function() {
 var html ='<div class="crush-box clearfix" style="width: 265px; height: 70px; overflow: hidden;"><div class="cb-left"><img src="'+sitebase+'_img/poops/'+marker.image_id+'_sm.jpg" /></div><div class="cb-right"><div class="top-row"><div class="clearfix first"><p>'+marker.sUsername+'</p></div><h2 id="poopname">'+marker.name+'</h2></div><p class="key">'+marker.dateadded_abbr+'</p><p><span id="smellslike">Smells Like:&nbsp;</span>'+marker.fname+'</p></div></div>';
 
 marker.openInfoWindowHtml(html);
 }); 
 
 }); 
 
 });

 } // Danger
 }
};