var ssh={};
var GLOBALS={};
GLOBALS.lang=null;


$(document).ready(function(){colorText();initMap();miscSetup();});
//$map= the map
$("ul#category ul li").live("click",subcatClick);
$("ul#category div").live("click",catClick).click();

function _t(token, lib){
	return GLOBALS.lang?lib.langs[GLOBALS.lang][token] || lib[token] : lib[token];
}

function catClick(){
	// Toggle display of subs
	$(this).toggleClass("opened").next().slideToggle();
	
}

function subcatClick(){
	// check if data exists else load
	var id=$(this).attr("id");
	if(GLOBALS.emd[id]){
		// loaded ... so show or hide
		if($(this).hasClass("active")){
			// hide them
			var idl=GLOBALS.master[id];
			for(i in idl){
				idl[i].setMap(null);
			}
			$(this).removeClass("active");
			GLOBALS.visibles[id]=false;
		}else{
			//show them
			var idl=GLOBALS.master[id];
			for(i in idl){
				idl[i].setMap(GLOBALS.$mapO);
			}
			$(this).addClass("active");
			GLOBALS.visibles[i]=true;
		}
	}else{
		//load data and show
		addLoad();
		$.ajax({ url: "/mapData/cat_"+id.substr(1)+".json", dataType: "json", context: this, success: function(data){createMarkers(data);$(this).addClass("active").parent().parent().addClass("active");removeLoad();GLOBALS.emd[id]=1;}, error:function(){removeLoad();
			GLOBALS.$map.block({
			 message: _t('NOCATS', notifications), 
                css: { border: '3px solid #a00' },
                timeout: 2000
              }
			//{ overlayCSS: { backgroundColor: '#00f' } }
			); 

			
			
			}});
	}
	if($(this).parent().find(".active").length){
		$(this).parent().parent().addClass("active");
	}else{
		$(this).parent().parent().removeClass("active");
	}
}
GLOBALS.loadQueueCount=0;
function addLoad(){
	GLOBALS.loadQueueCount++;
	
	GLOBALS.$map.block(loadingMessage());
}
function removeLoad(){
	GLOBALS.loadQueueCount--;
	if(GLOBALS.loadQueueCount==0){
		GLOBALS.$map.unblock();
	}else{
		GLOBALS.$map.block(loadingMessage());
	}
}
function loadingMessage(){
	return { 
		message: //"Please wait as I process your " + (GLOBALS.loadQueueCount>1 ? GLOBALS.loadQueueCount + " requests.": "request.") 
		_t('PLEASEWAIT', notifications)
		}
}
function createMarkers(data){
	var idl=[];
	var idx="d"+data[0][2];
	GLOBALS.visibles[idx]=true;
	var parts=data[0][2].split(".");
	var image=GLOBALS.images[data[0][2]] || GLOBALS.images[parts[0]];
	//var image="/images/" + $("#c" + parseInt(data[0][2],10) + " div").css("background-image").replace(/^.*\/|\.p.*$/g,"") + ".png";
	for (i in data){
		var r=data[i];
		var mll = new google.maps.LatLng(r[10], r[9]);
		var m = new google.maps.Marker({
      		position: mll,
      		map: GLOBALS.$mapO,
      		icon: image,
      		eid:r[0],
      		edata:r
  		});
  		idl.push(m);
	}
	GLOBALS.master[idx]=idl;
	for(i in idl){
		
		google.maps.event.addListener(idl[i], 'click', function() {
  			showWindow(this);
  		});
  	}
  
}
function showWindow(ma){
	var d={};
	for(i in GLOBALS.fields){
		d[GLOBALS.fields[i]]=ma.edata[i];
	}
	//if(d['url']!="" && d['url']."")
	var temp=$.tmpl("ssh.templates.iw.standard",d);
	GLOBALS.iw.setContent(temp.html());
	GLOBALS.iw.open(GLOBALS.$mapO,ma);
}
ssh.templates={
	"iw": {"standard": "<div><div id='iw'><h2>${name}</h2>{{if othercat}}<h3>${othercat}</h3>{{/if}}${address}<br/>Chicago, IL ${zip}<hr/>{{if phone}}Phone: ${phone}<br/>{{/if}}{{if url}}Web: ${url}<br/>{{/if}}<a class='iwp' id='r${id}'>more info</a></div></div>"},
	"pin": {"standard": "<div><div class='pi'><span class='close'>x</span><div class='col1'><img src='${img}' rel='${cat_long}'/></div><div class='col2'><h2>${OrgName}</h2>{{if othercat}}<h3>${othercat}</h3>{{/if}}${Addnum}${Fraction} ${Street} ${Unit}<br/>Chicago, IL ${zip}<hr/>{{if Phone}}Phone: ${Phone}${Extension}<br/>{{/if}}{{if URL}}Web: ${URL}<br/>{{/if}}</div><div class='col3'><h3>Hours:</h3>${q004}<br/>{{if q005=='Yes'}}	<img src='/images/icons_handicap.png' rel='Wheelchair accessible' /> {{/if}}{{if q006=='Yes'}}	<img src='/images/icons_parking.png' rel='Off-street parking available' /> {{/if}}{{if q007=='Yes'}}	<img src='/images/icons_delivery.png' rel='Delivers goods' /> {{/if}}{{if q009=='Yes'}}	<img src='/images/icons_language.png' rel='Multiple Languages spoken' /> {{/if}}</div><div class='col4'><h3>Services:</h3>	\
<ul> \
{{if qs01=='Yes'}}	<li rel='Food (prepared or ingredients)'>Food</li>	{{/if}} \
{{if qs02=='Yes'}}	<li rel='Clothing (including outerwear and shoes)'>Clothing</li>	{{/if}} \
{{if qs03=='Yes'}}	<li rel='Housing or housing search (or weatherizing programs or materials, home repairs or repair materials, utility payment assistance, mortgage assistance, or warming or cooling centers)'>Housing</li>	{{/if}} \
{{if qs04=='Yes'}}	<li rel='Childcare or youth activities'>Childcare or youth activities</li>	{{/if}} \
{{if qs05=='Yes'}}	<li rel='Physical fitness products or services'>Physical fitness products or services</li>	{{/if}} \
{{if qs06=='Yes'}}	<li rel='Health goods or services'>Health goods or services</li>	{{/if}} \
{{if qs07=='Yes'}}	<li rel='Mental health services'>Mental health services</li>	{{/if}} \
{{if qs08=='Yes'}}	<li rel='Transportation'>Transportation</li>	{{/if}} \
{{if qs09=='Yes'}}	<li rel='Employment, placement, or training services including basic adult education'>Employment, placement, or training services</li>	{{/if}} \
{{if qs10=='Yes'}}	<li rel='Social services'>Social services</li>	{{/if}} \
{{if qs11=='Yes'}}	<li rel='Internet access'>Internet access</li>	{{/if}} \
{{if qs12=='Yes'}}	<li rel='Antiviolence and Community services'>Antiviolence and Community services</li>	{{/if}} \
</ul> \
	</div></div></div>"}

};
/*

{{if qs02=='Yes'}}	<img src='/images/icons_clothing.png' rel='Clothing (including outerwear and shoes)' /> {{/if}} \
	{{if qs03=='Yes'}}	<img src='/images/icons_shelter.png' rel='Housing or housing search (or weatherizing programs or materials, home repairs or repair materials, utility payment assistance, mortgage assistance, or warming or coolingcenters)' /> {{/if}} \
	{{if qs11=='Yes'}}	<img src='/images/icons_wireless.png' rel='Internet Access' /> {{/if}} \
	
	*/
/*

**********************
NEED TO CHANGE templates for Spanish site

*/
GLOBALS.fields=["id","name","cate","othercat","phone","url","comm","address","zip","long","lat"];



function searchBox(){
	
	
	
}
GLOBALS.$mapO='';
GLOBALS.visibles={},GLOBALS.emd={},GLOBALS.master={};
GLOBALS.iw=new google.maps.InfoWindow();
GLOBALS.$map=$("#sshmap");
$.template("ssh.templates.iw.standard",ssh.templates.iw.standard);
$.template("ssh.templates.pin.standard",ssh.templates.pin.standard);
GLOBALS.geoXml;
function initMap(){
	GLOBALS.$mapO = new google.maps.Map(document.getElementById("sshmap"), { zoom: 10, center: new google.maps.LatLng(41.8,-87.6), mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: false });
	GLOBALS.$mapO.enableKeyDragZoom({
		visualEnabled: true,
		visualPosition: google.maps.ControlPosition.LEFT,
		visualPositionOffset: new google.maps.Size(35, 0),
		visualPositionIndex: null,
		visualSprite: "http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png",
		visualSize: new google.maps.Size(20, 20),
		visualTips: {
			off: "Turn on",
			on: "Turn off"
		}
	});

//	google.maps.event.addListener($mapO, 'click', function(event) {
//		console.log(event);
//	});
	GLOBALS.geoXml = new google.maps.KmlLayer("http://www.southsidehealth.org/community_outlines.kmz");
	GLOBALS.geoXml.setMap(GLOBALS.$mapO);
	GLOBALS.geoXmlOFP = new google.maps.KmlLayer("http://www.southsidehealth.org/test.kmz");
	GLOBALS.geoXmlOFP.setMap(GLOBALS.$mapO);
}

function zoomTo(){
	
}


GLOBALS.images={"1":"/images/icons_dining_color.png",
"2":"/images/icons_retail_color.png",
"3":"/images/icons_tradeservice_color.png",
"4":"/images/icons_personalservice_color.png",
"5":"/images/icons_financial_color.png",
"6":"/images/icons_healthservice_color.png",
"7":"/images/icons_political_color.png",
"8":"/images/icons_transportation_color.png",
"9":"/images/icons_industrial_color.png",
"10":"/images/icons_religious_color1.png",
"11":"/images/icons_childcare_color.png",
"12":"/images/icons_housing_color.png",
"13":"/images/icons_publicservice_color.png",
"14":"/images/icons_entertainment_color.png",
"15":"/images/icons_fitness_color.png",
"16":"/images/icons_other_color.png"};
GLOBALS.colors=["#f36a18", "#c3b6a0", "#243dfd", "#474646", "#64a17e", "#8b7f31", "#e25050", "#737ca1", "#812163", "#613e3e", "#000000", "#55b848", "#2aaedd", "#a16e4d", "#8c9b85", "#c18c31"];
function colorText(){
	$("ul#category div").each( function(i,item){if (i<GLOBALS.colors.length) {$(this).css("color",GLOBALS.colors[i]);}});
	$("ul#category ul").each( function(i,item){if (i<GLOBALS.colors.length) {$(this).css("color",GLOBALS.colors[i]);}});
}
GLOBALS.known={};
function miscSetup(){
	$("#iw a.iwp").live("click",function(){
		// Pin
		var item=$(this).attr("id").substr(1);
		//Get record and post it
		if(GLOBALS.known[item]){
			//just append it
			pin(GLOBALS.known[item]);
		}else{
			$.ajax({ url: "/services/getCase.php?CID="+item, dataType: "json", context: this, success: function(data){pin(data);}});
		}
		return false;
	});
	$("#map_pin").corner();
	$("#map_pin div.pi span.close").live("click",function(){$(this).parent().parent().remove();});
	
	$("#map_dd select").change(function(){
		var val=$(this).val();
		GLOBALS.$mapO.setCenter(GLOBALS.zoomloc[val][0]);
		GLOBALS.$mapO.setZoom(GLOBALS.zoomloc[val][1]);
	});
	
	
	$("#expsurv").hide();
	$("#maplink").click(function(){$("#expsurv").slideToggle("slow")});
	$("#expsurv button").click(function(){window.location='http://www.southsidehealth.org/edit-place/' + $('#expsurv input').val();});
	$("#map_dd select").customStyle();
	
}
function pin(data){
	var c=data['OrgTypeCombined'];
	var parts=c.split(".");
	data['img']=GLOBALS.images[parts[0]];
	data['cat_long']=$("#c"+parts[0] + " div").text() + "/" + $(("#d"+c).replace(".","\\.")).text();
	var temp=$.tmpl("ssh.templates.pin.standard",data);
	temp.appendTo($("#map_pin"));
	$('<div class="clear"></div>').appendTo($("#map_pin"));
	GLOBALS.known[data['CaseID']]=data;
	$("#map_pin .pi:last img[rel], #map_pin .pi:last li[rel]").tinyTips('ssh', 'rel');
	$( "#iw" ).effect("transfer", { to: temp, className: "ui-effects-transfer" },2000);
}



GLOBALS.zoomloc={
	"South Side Communities": [new google.maps.LatLng(41.8,-87.6),11],
	"Auburn Gresham":  [new google.maps.LatLng(41.7421317115985, -87.65458831787107),14],
	//"Chatham":  [new google.maps.LatLng(41.8,-87.6),11],
	//"Douglas":  [new google.maps.LatLng(41.8,-87.6),11],
	"Englewood":  [new google.maps.LatLng(41.77465704241093, -87.64085540771482),13],
	//"Greater Grand Crossing":  [new google.maps.LatLng(41.8,-87.6),11],
	"South Chicago":  [new google.maps.LatLng(41.73880141699834, -87.55468139648436),14],
	"South Shore":  [new google.maps.LatLng(41.76287811799253, -87.56832847595213), 14],
	"West Englewood":  [new google.maps.LatLng(41.775617185473024, -87.66600379943846),13],
	"Hyde Park": [new google.maps.LatLng(41.794804,-87.589273),14],
	"Washington Park": [new google.maps.LatLng(41.791028,-87.617254),14],
	"Kenwood": [new google.maps.LatLng(41.809452,-87.59378),14],
	"Grand Boulevard": [new google.maps.LatLng(41.812942,-87.617769),14],
	"Woodlawn": [new google.maps.LatLng(41.77666,-87.587299),14],
	"East Side": [new google.maps.LatLng(41.70455,-87.5348),13],
	"Oakland": [new google.maps.LatLng(41.82505,-87.60039),15],
	"Fuller Park": [new google.maps.LatLng(41.81, -87.626667),14]
};

(function($){
 $.fn.extend({
 
 	customStyle : function(options) {
	  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
	  return this.each(function() {
	  
			var currentSelected = $(this).find(':selected');
			$(this).after('<span class="customStyleSelectBox"><span class="customStyleSelectBoxInner">'+currentSelected.text()+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
			var selectBoxSpan = $(this).next();
			var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right'));			
			var selectBoxSpanInner = selectBoxSpan.find(':first-child');
			selectBoxSpan.css({display:'inline-block'});
			selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
			var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
			$(this).height(selectBoxHeight).change(function(){
				// selectBoxSpanInner.text($(this).val()).parent().addClass('changed');   This was not ideal
			selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
				// Thanks to Juarez Filho & PaddyMurphy
			});
			
	  });
	  }
	}
 });
})(jQuery);

