/***************************************
*** JS code used throughout the site ***
***************************************/

var CURRENTYEAR = 2009;
var PAGE_ID = "";

PSession = {}
PSession.clear = function() {
	this.periods = null;
	this.indicatorIds = null;
	this.placeIds = null;
	this.overlaySetIds = null;
}
PSession.toURI = function() {
	var query = "?";
	if (this.indicatorIds) query += "i=" + this.indicatorIds;
	if (this.placeIds) query += "&p=" + this.placeIds;
	if (this.periods) query += "&period=" + this.periods;
	if (this.overlaySetIds) query += "&o=" + this.overlaySetIds;
	
	// chop ? if no params
	query = (query == '?') ? '' : query;
	return query;
}

PSession.fromURI = function(o) {
	this.placeIds = o['p'];
	this.indicatorIds = o['i'];
	this.periods = o['period'];
	this.overlaySetIds = o['o'];
}

PSession.setState = function(state) {
	this.clear();
	if (state.indicator) {
		this.indicatorIds = [state.indicator.id];
		this.periods = state.indicator.getPeriod();
		if (window.session2) {
//			console.log('(PSesssion.setState) i is now ' + session2.get('i'));
			session2.put('i', state.indicator.id);
			session2.put('period', state.indicator.getPeriod());
		}
	}
	if (state.place)
		this.setPlaces([state.place]);
	this.setOverlaySets(state.sets);
}

PSession.setPlaces = function(places) {
	var ids = [];
	var l = places.length;
	for (var i=0; i<l; i++) ids.push(places[i].id);
	this.placeIds = ids.join(',');
	if (window.session2) {
		session2.put('p', this.placeIds);
	}
}

PSession.setOverlaySets = function(sets) {
	if (sets) {
		var ids = [];
		var l = sets.length;
		for (var i=0; i<l; i++) ids.push(sets[i].id);
		this.overlaySetIds = ids.join(',');
		if (window.session2) {
			session2.put('o', this.overlaySetIds);
		}

		// save the filters
		var groups = {};
		var group;
		for (var i=0; i<l; i++) {
			group = sets[i].filtergroups;
			if (group) 
				groups[sets[i].id] = group;
		}

		if (window.session2) {
			session2.put('ofilters', groups);
		}
	}
}
PSession.setOverlaySet = function(set) {
	this.overlaySetIds = set.id;
	if (window.session2) {
		session2.put('o', set.id);
	}
}

function getMeasurementLabel(m, full) {
	var retVal = "&nbsp;";
	var TRANSLATE_TOGGLE = {
		"enum":"Type","count":"#","percent":"%","percent change":"%Ch","median":"Mdn","change":"Ch","rate":"Rt","currency":"$","average currency":"Av$",
		"total currency":"Tot$","% level 1":"%1","% level 2":"%2","% level 3":"%3","% level 4":"%4","% level 5":"%5","at or above proficient":"AOAP",
		"does not meet":"DNM","exceeds":"E","failed":"F","meets":"M","passedadvanced":"PA","passed":"PASS","partially meets":"PM","advanced":"ADV",
		"at or above proficient":"AOAP","basic":"B","below basic":"BB","proficient":"PROF","approaches":"APP","falls far below":"FB","meets":"M",
		"partially proficient":"PP","unsatisfactory":"U","below":"B","distinguished":"D","well below":"WB","not meeting":"NM","pass+":"P+","did not pass":"DNP",
		"undetermined":"U","approaches standard":"AS","academic warning":"AW","exemplary":"E","exceeds standard":"ES","meets standard":"MS","approaching basic":"AB",
		"mastery":"M","advanced/above proficient":"AP","needs improvement":"NI","warning/failing":"WF","does not meet":"DNM","apprentice":"APP",
		"exceeded expectations":"EE","met expectations":"ME","minimal":"M","novice":"N","nearing proficient":"NP","beginning":"B","progressing":"PROG",
		"achieved the standard":"AS","achieved the standard with honors":"AS+","below the standard":"BS","achievement level 1":"L1","achievement level 2":"L2",
		"achievement level 3":"L3","achievement level 4":"L4","little evidence of achievement":"LE","nearly achieved the standard":"NA","advanced proficient":"ADVP",
		"beginning step":"BS","approaches standard":"AS","emergent/developing":"ED","limited knowledge":"LK","satisfactory":"S","no score":"NS",
		"proficient with distinction":"PD","substantially below proficient":"SBP","below standard":"BS","met standard":"MS","well below standard":"WB",
		"far below basic":"FBB","exceeding":"E","failing":"F","meeting":"M","pass":"PASS","below proficient":"BP","near proficient":"NP","score":"Score",
		"average":"Av","degree days":"Degree Days","honors":"HON","not proficient":"NP","pct chg price from last year":"%Ch1YR$","pct chg price 2003-2006":"%Ch3YR$",
		"pct chg price 2001-2006":"%Ch5YR$","pct chg num sales from last year":"%Ch1YR#","pct chg price from last quarter":"%Ch1Q$",
		"pct chg num sales from last qtr":"%Ch1Q#","pct chg price from 4 qtrs previous":"%Ch4Q$","pct chg num sales from 4 qtrs previous":"%Ch4Q#",
		"pct chg vac units from last qtr":"%Ch1Q","pct chg vac units from 4 qtrs previous":"%Ch4Q","pct chg no-stat units from last qtr":"%Ch1Q",
		"pct chg no-stat units from 4 qtrs previous":"%Ch4Q","square foot":"Sq Ft","units":"Units"
	};
	if (m == "enum")
		retVal = "Type";
	else if (full) {
		if (m == "count")
			retVal = "Number";
		else
			retVal = m.substr(0,1).toUpperCase() + m.substr(1);
	} 
	else if (TRANSLATE_TOGGLE[m])
		retVal = TRANSLATE_TOGGLE[m];

	return retVal;
}

function saveEffect() {
	jQuery('#mypolicymap').fadeTo(2000, 0.2, function() { 
		jQuery('#mypolicymap').fadeTo(2000, 1);
	});
}

function teaseIndicators(extra) {
	var link = getContextPath() + ( isPublicUser() ? '/register.jsp?reg_type=sub': '/upgrade?reg_type=sub');

	var text = "Available to subscribers only.  If you're a subscriber, <a onclick='loginAlert(this)' class='pagelinks'>login</a> to access, or become a <a href='" + link + "' class='pagelinks'>subscriber</a>.";
	if (extra)
		text += "<br><br>" + extra;
 	var alerter = new PAlerter();
	var position = getAlertPosition(parseInt(alerter.box.style.width));
	
	alerter.popup(text,position[0],position[1],"OK");	
}

function comingIndicators () {
	var text = "Not yet available to PolicyMap  users. Stay tuned to our PolicyMap  email updates and blog for a release announcement about these data.";
 	var alerter = new PAlerter();
	alerter.popup(text, null, null, "OK");	
}

function naIndicators() {
	var text = "This data is not available.";

 	var alerter = new PAlerter();
	var position = getAlertPosition(parseInt(alerter.box.style.width));
	
	alerter.popup(text,position[0],position[1],"OK");	
}

PAlerter = function() {
	return new PAlerter2();
	this.box = document.createElement('div');
	this.box.className = "alertDialog";
	this.box.style.position = "absolute";
	this.box.style.width = "294px";	
}

PAlerter.prototype.popup = function(content, positionX, positionY, clabel, alabel, acallback, icon, ccallback ) {
	var fadeSpeed = 500;
	var box = this.box;
	this.box.style.top = positionY + "px";
	this.box.style.left = positionX + "px";
	
	this.icon = document.createElement('img');
	if (icon) {
		this.box.style.width = "336px";
		var imagesrc = "";
		if (icon == "exclamation")
			imagesrc = "images/alert_exclamation.gif";
		else if (icon == "info")
			imagesrc = "images/alert_info.gif";

		this.icon.src = imagesrc;
		this.icon.style.width = "66px";
		this.icon.style.height = "44px";
		
		var imageDiv = document.createElement('div');
		imageDiv.className = "alertImageHolder";
		
		imageDiv.appendChild(this.icon);
		this.box.appendChild(imageDiv);
	}
	var boxcontent = document.createElement('p');
	jQuery(boxcontent).append(content);
	
	var buttonsArea = document.createElement('div');
	buttonsArea.align = "center";
	
	if (alabel) {
		var button1div = document.createElement('span');

		button1div.box = this.box;
		button1div.onclick = function() { jQuery(this.box).fadeOut(fadeSpeed); };

		var actionbutton = document.createElement('input');
		actionbutton.type = "button";
		actionbutton.className = "alertButtons";
		actionbutton.value = alabel;
		jQuery(actionbutton).click( function() {
			jQuery(box).fadeOut(fadeSpeed, function() {
			if( acallback && acallback.constructor == Function ) {
					acallback();
				}
					});
		});
		button1div.appendChild(actionbutton);
		buttonsArea.appendChild(button1div);
	}
	var button2div = document.createElement('span');
	
	button2div.box = this.box;
	button2div.onclick = function() { 
		jQuery(this.box).fadeOut(fadeSpeed, function() {
			if (ccallback instanceof Function) {
				ccallback();
			}
		});
	}

	var cancel = document.createElement('input');
	cancel.type = "button";
	cancel.className = "alertButtons";
	if (clabel)
		cancel.value = clabel;
	else
		cancel.value = "Cancel";
	
	button2div.appendChild(cancel);
	buttonsArea.appendChild(button2div);

	// fix spacing when image is added
	if (icon) {
		boxcontent.style.paddingLeft = "88px";
		buttonsArea.style.paddingLeft = "72px";
	}
		
	this.box.appendChild(boxcontent);
	this.box.appendChild(buttonsArea);

	document.body.appendChild(this.box);

	jQuery(this.box).hide();
	jQuery(this.box).fadeIn(fadeSpeed);
}

function getElementPosition(elem) {
	var oleft, otop;
	if (elem.offsetLeft)
		oleft = elem.offsetLeft;
	else {
		while(!elem.offsetLeft) {
			elem = elem.offsetParent;
			if (elem.offsetLeft)
				oleft = elem.offsetLeft;
		}
	}
	if (elem.offsetTop)
		otop = elem.offsetTop;
	else {
		while(!elem.offsetTop) {
			elem = elem.offsetParent;
			if (elem.offsetTop)
				otop = elem.offsetTop;
		}
	}
	return [oleft,otop];
}

function getState(place) {
        var state = "";
        if (place.getState() && place.getType() != PPlaceType.CITIES && place.getType() != PPlaceType.STATE && place.getType() != PPlaceType.CDBG)
                state = ", " + place.getState();
        return state;
}

function sendMail(domain, account, subject) {
	var a = "mailto:" + account + domain + "?" + "subject=" + subject;
	location.href = a;
}

function setMenuScroll() {
	var scroll = jQuery(".scrollingDiv");
	for (var i=0; i<scroll.length; i++) {
		// Scrolling is buggy on ie6 so removing scrolling div
		if (version < 7) {
			var fragment = document.createDocumentFragment();
			while(scroll[i].firstChild) {
			    fragment.appendChild(scroll[i].firstChild);
			}
			scroll[i].parentNode.insertBefore(fragment, scroll[i]);
			scroll[i].parentNode.removeChild(scroll[i]);
		}
		else {	// this initialises the scrolling with custom scrollbar for the menu
			jQuery(scroll[i]).jScrollPane({showArrows:true,scrollbarWidth:10});
			// added css for when scroll bar goes on the left side
			if (scroll[i].className == "scrollingDiv leftSide") {
				var par = jQuery(scroll[i]).parent()[0];
				jQuery(par).find('.jScrollPaneTrack').css('left','0')
				jQuery(par).find('.jScrollPaneDrag').css('padding','0')
				jQuery(par).find('.jScrollArrowUp').css('left','0')
				jQuery(par).find('.jScrollArrowDown').css('left','0')
				jQuery(scroll[i]).css({'margin' : '0 9px', 'width' : '167px'});
			}
		}
	}
}

// will get overwritten if certain pages need it
function onLoad() {}

// expiry alert is shown only once.
function showExpiryAlertFunction() {
	var shown = false;
        return function() {
        	if( !shown && isExpiredSubscription() && showExpNoteCount() ) {
                	var alerter = new PAlerter();
                        var pos = getAlertPosition(parseInt(alerter.box.style.width));
                        var content = "Your PolicyMap subscription has expired; however, you may continue to use your account to access the site as a registered user." 
                        alerter.popup(content,pos[0],pos[1],"OK");
                        shown = true;
                }
        };
}

// When user clicks login alert in subscriber/register alerts no need to redirect to login page
// This alert takes the login form from the top right of the app and displays it in an alert
function loginAlert(elem) {
	var log = document.getElementById('login');
	var div = document.createElement('div');
	div.appendChild(log);
	var text = div.innerHTML;
	var alerter = new PAlerter();

	// get position from alert the login link was triggered from
	var box = elem.parentNode.parentNode;
	var posY = parseFloat(box.style.top);
	var posX = parseFloat(box.style.left);
	alerter.popup(text,posX,posY,"Cancel", "Submit", function() {validateAndLogin()}, null, function() {loginAlertCancel()});
}

function loginAlertCancel(elem) {
	jQuery("#login").insertBefore(".helpLabel")[0];
}
