//requires jquery

DEFAULT_STRAT_BY = 'q15'; // wish this were a mason page so we could reuse constant from perl
var schoolId;
var districtId;
var stratBy;
var stratGroup;
var level;
var runType;

/*
 * This function parses comma-separated name=value 
 * argument pairs from the query string of the URL. 
 * It stores the name=value pairs in 
 * properties of an object and returns that object.
 *
 * adapted from JavaScript, The Definitive Guide, by Daniel Flanagan 
 */
function getArgs(  ) {
    var args = new Object(  );
    var query = location.search.substring(1); // query string minus initial '?'
    var pairs = query.split("&"); // break at ampersand (was comma in original)
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
          // Look for "name=value"
        if (pos == -1) continue;
          // If not found, skip
        var argname = pairs[i].substring(0,pos);
          // Extract the name
        var value = pairs[i].substring(pos+1);
          // Extract the value
        args[argname] = unescape(value);
         // Store as a property
       // In JavaScript 1.5, use decodeURIComponent(  ) 
       // instead of escape(  )
    }
    return args;     // Return the object
}

var observerCallback = function(ev) {
	var args = getArgs();
	args.strat_by = stratBy || DEFAULT_STRAT_BY;
	args.strat_group = stratGroup || '';
	args.level = level || '';
	args.run_type = runType || 'all';
	if (!args.lang) args.lang = 'en';
	if (!args.school_id && schoolId) args.school_id = schoolId;	
	if (!args.district_id && districtId) args.district_id = districtId;
	
	switch (target = ev.target) {
		case $('level-selector'):
			args.level = target.value || '';
		break;
		case $('strat-group-selector'):
			args.strat_group = target.value || '';
		break;
		case $('run-selector'):
			args.district_id = getArgs().district_id || '';
			if (target.value != 'all') {
				args.run_type = '';
				args.school_id = target.value;
			}
		break;
		case $('run-type-selector'):
			args.run_type = target.value || 'all';
		break;
		case $('lang-selector'):
			args.lang = target.value || 'en';
		break;
	}
	
	href = window.location.pathname;
	if (href.indexOf('?') == -1) {
		window.location = href + "?" + jQuery.param(args);
	} else {
		window.location = href + "&" + jQuery.param(args);
	}
};

document.observe('dom:loaded', function() {
  jQuery.each(['strat-group', 'run', 'level', 'run-type', 'lang'], function() {
	  if (selector = $(this+'-selector')) {
	  	  selector.observe('change', observerCallback);
	  }
  });
});

/*****************************************************************************
 * school_id/district_id preservation logic follows:
 */

// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

var eraseCookie = function(name) {
	createCookie(name,"",-1);
};

// request parameter verification

var argsForRequest = function() {
  if (districtId) {
    return jQuery.param({
      district_id: districtId,
      school_id:   schoolId || '',
      level:       level || '',
      run_type:	   runType || 'all',
      strat_by:    stratBy || DEFAULT_STRAT_BY,
      strat_group: stratGroup || ''
    });
  } else {
		return jQuery.param({
			run_type:	   runType || 'all',
			school_id:   schoolId,
			strat_by:    stratBy || DEFAULT_STRAT_BY,
			strat_group: stratGroup || ''
		});
	}
};

// when we're in the results section, and viewing the html flavor, rewrite hrefs
if (window.location.pathname.match(/^\/(district\_)?results\b/) &&
    window.location.pathname.match(/\bhtml\b/)) {
  schoolId = getArgs().school_id;
  districtId = getArgs().district_id;
  level = getArgs().level;
  runType = getArgs().run_type;
  stratBy = getArgs().strat_by;
  stratGroup = getArgs().strat_group;
  if (!schoolId && !districtId) {
    // try to recover school id from session and redirect
    schoolId = readCookie('school_id');
    districtId = readCookie('district_id');
    level = readCookie('level');
    runType = readCookie('run_type');
    stratBy = readCookie('strat_by');
    stratGroup = readCookie('strat_group');
    if (schoolId || districtId) {
      href = window.location.pathname;
      if (href.indexOf('?') == -1) {
        window.location = href + "?" + argsForRequest();
      }
    } else {
      alert("Bad location: no school specified.\nPlease find your school.");
      // send them searching if they have no school id
      window.location = '/schools.html';
    }
  }
  if (schoolId) {
    createCookie('school_id', schoolId, 1);
  }
  if (districtId) {
    createCookie('district_id', districtId, 1);
  }
  createCookie('level', level || '', 1);
  createCookie('run_type', runType || 'all', 1);
  createCookie('strat_by', stratBy || DEFAULT_STRAT_BY, 1);
  createCookie('strat_group', stratGroup || '', 1);
  jQuery(document).ready(function() {
    jQuery('#content-cols')
    .find('a[href]').each(function(index, link) {
      if (link.href.indexOf('?') == -1) {
        link.href += "?" + argsForRequest();
      }
    });
  });
}

