var isOK = false;
var map_type = 1;
var map
var icon_y = new GIcon();
var icon_r = new GIcon();
var tooltip;
var PIPE = '|';
var ptypes = {
	'ear':'Early Childhood',
	'ele':'Elementary',
	'mid':'Middle School',
	'hig':'High School',
	'oth':'Other Grade Ranges',
	'col':'College/University',
	'alt':'Alternative',
	'unk':'Unknown',
	'frm':'Firm'
	};
var atypes = {
	'1':'Honor',
	'2':'Merit',
	'3':'Citation',
	'4':'Recognized Value',
	'6':'Reviewer Recognition',
	'5':'No Award'
	};
var roletypes = {
	'1000':'Submitter',
	'1001':'Lead Architect',
	'1002':'Planner',
	'1003':'Associate'
	};

var firmurl = "http://www.designshare.com/index.php/profiles/";
var projurl = "http://www.designshare.com/index.php/projects/";

var siteurl = "http://www.designshare.com";
var mapdir = "/map4/";
var xmlfile = mapdir + "awardsxml.php";
var prjxmlfile = mapdir + "projectxml.php";
var frmxmlfile = mapdir + "firmxml.php";

formhtml = 'This profile is inactive. To activate your  profile, contact us.'
formhtml += '<form name="frmcontact" id="frmcontact" action="/map4/contact.php" method="post" onSubmit="return cs_checkContact()">'
formhtml += '<div class="subcol">'
formhtml += '<label for="name">Your Name</label>'
formhtml += '<input id="name" name="name" maxlength="30"><br>'
formhtml += '<label for="email">Email</label>'
formhtml += '<input id="email" name="email"  maxlength="30"><br>'
formhtml += '<label for="comments">Comments</label>'
formhtml += '<textarea id="comments" name="comments"  maxlength="255" cols="20" rows="6"></textarea><br>'
formhtml += '<input type="submit" value="Send"><br>'
formhtml += '<label id="errormsg" style="display:none;color:red;width:200px">Please fill all the fields.</label>'	
formhtml += '<input type="hidden" id="orgs_id" name="orgs_id" value="$orgs_id"><br>'
formhtml += '</div>'
formhtml += '</form>'


function cs_showAdvanced(){
	var el = document.getElementById('advanced').style;
	if ('none'==el.display) {
		el.display = '';
		document.getElementById('advancedlink').innerHTML = 'Advanced\&nbsp;\&laquo;';
	} else {
		el.display = 'none'
		document.getElementById('advancedlink').innerHTML = 'Advanced\&nbsp;\&raquo;';
	}
}
function cs_clickByRole(){
	var ShowAllFirms = (document.getElementById('FirmsAll').checked)
	for (var i = 1; i < 4; i++) {
		document.sform['Role100' + i].disabled = ShowAllFirms;
	}
}

function cs_showPrjFrm(optValue){
	if ('Projects'==optValue) {
		document.getElementById('f_proj').style.display='';
		document.getElementById('f_firms').style.display='none';
	} else if ('Firms'==optValue) {
		document.getElementById('f_proj').style.display='none';
		document.getElementById('f_firms').style.display='';
	} else if ('Both'==optValue) {
		document.getElementById('f_proj').style.display='';
		document.getElementById('f_firms').style.display='';
	}
}

function cs_showProjectInfo (id, marker){
	var request = GXmlHttp.create();
	request.open("GET", prjxmlfile + '?id=' + id, true);
	request.onreadystatechange = function() {
    if (request.readyState == 4) {
    	var xmlDoc = request.responseXML;
    	var projects = xmlDoc.documentElement.getElementsByTagName("project");
    	if (projects.length) {
    	  var i = 0;
    	  var name = projects[i].getAttribute("name");
				var state = projects[i].getAttribute("stateprov");
				if (''!=state) {
					state += ', ';
				}
				var html = projects[i].getAttribute("city") + ', ' + state + projects[i].getAttribute("country");
				var award = projects[i].getAttribute("award");
				if ((award>=1 && award <=4) || 6==award){
					html += ('<br />' + atypes[award] + ' Award');
				}
				html = '<div><a href="' + projurl + projects[i].getAttribute("id") + '" target="_blank">' + name + '</a><br />' + html;
				var img = siteurl + projects[i].getAttribute("img");
				html +=  '</div>'
				html += '<img src="' + img + '" width=150 height=100><br />';
			  var frms = projects[i].getElementsByTagName("frm");
			  if (frms.length) {
			    html +=  '<div>';// style="text-align:left;margin-bottom:15px;">';
			    for (var j = 0; j < frms.length; j++) {
			    //roletypes
			     html += roletypes[frms[j].getAttribute("role")] + ': <a href="' + firmurl + frms[j].getAttribute("id") + '/about" target="_blank">' + frms[j].getAttribute("name") + '</a>' + "<br />";
			    }
        }
        html +=  '</div>';//&nbsp;<br />&nbsp;<br />';
    		marker.openInfoWindowHtml(html);
        tooltip.style.visibility="hidden";
    	}
  	}
	}
	request.send(null);
}

function cs_showFirmInfo (id, marker){
	var request = GXmlHttp.create();
	request.open("GET", frmxmlfile + '?id=' + id, true);
	request.onreadystatechange = function() {
	if (request.readyState == 4) {
    	var xmlDoc = request.responseXML;
    	var projects = xmlDoc.documentElement.getElementsByTagName("firm");
    	if (projects.length) {
			var i = 0;
			var name = projects[i].getAttribute("name");
			var state = projects[i].getAttribute("stateprov");
			if (''!=state) {
				state += ', ';
			}
			//Profile is inactive
			if (0 == projects[i].getAttribute("ShowLevel")) {
				html = '<strong>' + name + '</strong><br />';
				tst='<input type="hidden" id="orgs_id" name="orgs_id" value="$orgs_id"><br>';
				html += formhtml.replace(/\$orgs_id/, id);
    		} else {
  				var html = projects[i].getAttribute("city") + ', ' + state + projects[i].getAttribute("country");
  				//html = '<div style="white-space:nowrap;"><a href="' + firmurl + id + '" target="_blank">' + name + '</a><br />' + html + '</div>';
  				html = '<a href="' + firmurl + projects[i].getAttribute("id") + '/about" target="_blank">' + name + '</a><br />' + html ;//'<div><a href="' + firmurl + id + '" target="_blank">' + name + '</a><br />' + html ;
  
				var prjs = projects[i].getElementsByTagName("prj");
				if (prjs.length) {
					html += "<ul>Projects:"
					for (var j = 0; j < prjs.length; j++) {
						html += '<li /><a href="' + projurl + prjs[j].getAttribute("id") + '" target="_blank">' + prjs[j].getAttribute("name") + '</a>';// + "<br />";
					}
					html +=  '</ul>';// &nbsp; <br /><br />';
				}
				//html +=  '</div>'
			}
			marker.openInfoWindowHtml(html);
			tooltip.style.visibility="hidden";
    	}
  	}
	}
	request.send(null);
}

function cs_showstatus(statust) {
	lbl = document.getElementById('showstatus');
  if(typeof(lbl.textContent) != "undefined"){
      //alert (lbl.innerText);
      lbl.textContent = statust;
  } else{
      lbl.innerText = statust;
      //window.setTimeout('',10);
  }
}

function showTooltip(marker) {
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}

function cs_showLocales(){

	if (!isOK) {
		return;
	}
	// A function to create the marker and set up the event window
	function createMarker(point,id,isfirm) {
		var marker;
		if (isfirm){
			marker = new GMarker(point, icon_r);
		  GEvent.addListener(marker, "click", function() {
		    showTooltip(marker);
        cs_showFirmInfo(id, marker);
		  });
		} else {
			marker = new GMarker(point, icon_y);
      GEvent.addListener(marker, "click", function() {
		    showTooltip(marker);
        cs_showProjectInfo(id, marker);
		  });
		}
		return marker;
	}
	
	var args = cs_getArgs();
	if (0==args.length){
		return;
	}

	cs_showstatus('Searching...');
	// Read the data from xml
	var request = GXmlHttp.create();
	request.open("GET", xmlfile + '?' + args, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			// obtain the array of projects and loop through it
			var projects = xmlDoc.documentElement.getElementsByTagName("project");

			cs_showstatus('Displaying...');

			cs_removeProjects();

			for (var i = 0; i < projects.length; i++) {
			// obtain the attribues of each project
				var lat = parseFloat(projects[i].getAttribute("lat"));
				var lng = parseFloat(projects[i].getAttribute("lng"));
				if (Math.abs(lat)+Math.abs(lng) > 0.00001) {
					var point = new GLatLng(lat, lng);
					var pid = projects[i].getAttribute("id");
					var isfirm = ("1"==projects[i].getAttribute("isfirm"));
					// create the marker
					var marker = createMarker(point, pid, isfirm);
					map.addOverlay(marker);
				}
			}
			cs_showstatus('Done.');
			window.setTimeout("cs_showstatus('');",2000);
		}
	}
	request.send(null);

}

function cs_removeProjects(){
	map.clearOverlays();
}

function CSLoadMap() {
	if (GBrowserIsCompatible()) {

    var el_map = document.getElementById("map");
		map = new GMap2(el_map);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(30.0, 0.0), 2);

		isOK = true;

		//red marker
		icon_r.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
		icon_r.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		icon_r.iconSize = new GSize(12, 20);
		icon_r.shadowSize = new GSize(22, 20);
		icon_r.iconAnchor = new GPoint(6, 20);
		icon_r.infoWindowAnchor = new GPoint(5, 1);
		//yellow marker
		icon_y.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
		icon_y.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		icon_y.iconSize = new GSize(12, 20);
		icon_y.shadowSize = new GSize(22, 20);
		icon_y.iconAnchor = new GPoint(6, 20);
		icon_y.infoWindowAnchor = new GPoint(5, 1);

    tooltip = document.createElement("div");
    tooltip.innerHTML = '<div class="tooltip">Loading...</div>';
    tooltip.style.visibility="hidden";
    el_map.appendChild(tooltip);

		cs_showLocales();

	}
    else {
		  alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}

function cs_getArgs() {
	var result = 'show=';
	var show = 3;
	var sval = 0;
	var ival = 0;

	if(2==map_type){
		result += 'firms';
		show = 2;

			sval = document.sform.f_city.value;
			if (sval!='') {
				result += '&f_city=' + escape(sval);
			}
			sval = document.sform.f_address.value;
			if (sval!='') {
				result += '&f_address=' + escape(sval);
			}

		} else {
		if (document.sform.ShowProjects.checked){
			result += 'projects';
			show = 1;
		} else if (document.sform.ShowFirms.checked){
			result += 'firms';
			show = 2;
		} else {
			result += 'both';
		}
	}

	if (show & 1) {	//Projects
		sval = document.sform.p_Country.value;
		if (sval!='All') {
			result += '&p_country=' + sval;
		}
		ival = document.sform.p_State.value;
		if (ival>0) {
			result += '&p_stateprov=' + ival;
		}
		sval = document.sform.p_AwardType.value;
		if (sval!=0) {
			result += '&p_award=' + sval;
		}
		sval = document.sform.p_Year.value;
		if (sval!='All') {
			result += '&p_year=' + sval;
		}
		sval = document.sform.p_School.value;
		if (sval!='All') {
			result += '&p_ptype=' + sval;
		}
		sval = document.sform.p_keyword.value;
		if (sval!='') {
			result += '&p_keyword=' + escape(sval);
		}
	}
	if (show & 2) {	//Firms
		sval = document.sform.f_Country.value;
		if (sval!='All') {
			result += '&f_country=' + sval;
		}
		ival = document.sform.f_State.value;
		if (ival>0) {
			result += '&f_stateprov=' + ival;
		}
	
		sval = document.sform.f_keyword.value;
		if (sval!='') {
			result += '&f_keyword=' + escape(sval);
		}
	}
	//alert ("result:"+result);
	return(result);
}

function clickShow() {
  cs_showstatus('');
	cs_showLocales();
}

String.prototype.LTrim = new Function("return this.replace(/^\\s+/,'')")
String.prototype.RTrim = new Function("return this.replace(/\\s+$/,'')")
String.prototype.Trim = new Function("return this.replace(/^\\s+|\\s+$/g,'')")

function valid_email(email) {
  if( email.match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/)){
    return true;
  }
  return false;
}

function cs_checkContact(){
  var message = '';
	if ("" == document.frmcontact.name.value.RTrim()){
	  message = 'Please enter your name';
	} else if (!valid_email(document.frmcontact.email.value)) {
	  message = 'Please enter valid email';
  } else if ("" == document.frmcontact.comments.value.RTrim()){
	  message = 'Please enter comments';
	}
	lbl = document.getElementById('errormsg');
	if (''==message){
	 lbl.style.display = 'none';
	 return true;
  }

  if(document.all){
       lbl.innerText = message;
  } else{
      lbl.textContent = message;
  }
  lbl.style.display = '';
  return false;
}

