// Run after page is loaded
function onload_script() {
	focus_on_first();
	add_auth_nav();
	add_breadcrumbs();
	
	// Loads a users's candidate choices
	var selections = {};  
	get_selections_from_cookie();
	chooser_load_status();
	preload_images();
	
	// Add searches
	if ( typeof(searches) != 'undefined' ) {
		for (div in searches)  { 
    	get_google_search(div, searches[div], document.getElementById(div));
  	}
	}
	
	// Add geocoder
	initialize_geocoder();
}

// Focuses on the page's first search field (with blinking cursor)
function focus_on_first() {
	x = document.getElementsByTagName('input');
	profile = document.getElementById('candidate-comment-form');
	if (profile == null && x != null && x[0] != null) x[0].focus();
}

// Adds authentication links at top of every page (create account, login etc.)
function add_auth_nav () {
	
	name = get_cookie('name');
	if ( name ) {
		auth_nav='<li class="login"><a href="auth/logout">logout</a></li>'+
        '<li class="login"><a href="auth/edit_account">account</a></li>'+
				'<li class="login"><div id="welcome-message">hi '+name+'!</div></li>';
	}
	else   {
		auth_nav='<li class="login"><a href="auth/login">log in</a></li>';
		//auth_nav='<li class="login"><a href="auth/login">log in</a></li>'+
        //'<li class="login"><a href="auth/create_account">create account</a></li>';
	}
	
	document.getElementById('auth_nav').innerHTML=auth_nav;
}

function add_breadcrumbs() {
	
	// Determine if breadcrumbs are called for
	ul_element = document.getElementById('breadcrumbs');
	if (ul_element) {
		
		// Find breadcrumbs passed by page
		breadcrumb_link = location.pathname;

		// Read history from cookie
		var myArray = new Array();
		var myCookie = get_cookie('breadcrumb');
		if (myCookie) {
			myArray = myCookie.split(',');
			
			// Remove values less than or equal to breadcrumb_index
			for (i=0;i<myArray.length;) {
				if ( myArray[i] >= breadcrumb_index ) {
					myArray.splice(i,3);
				}
				else {
					i = i+3;
				}
			}
		}
		
		// Add current breadcrumb
		myArray.push(breadcrumb_index);
		myArray.push(breadcrumb_link);
		myArray.push(breadcrumb_title);
		
		// Write breadcrumb
		breadcrumbs  = '<li><a href="">Home</a></li>';
		for (i=0;i<myArray.length;i=i+3) {
			var last_element = '';
			if ( i+3 >= myArray.length) {
				last_element = ' class="last"';
			}
			if ( myArray[i+1] == breadcrumb_link ) {
				breadcrumbs += '<li'+last_element+'>'+myArray[i+2]+'</li>';
			} else {
				breadcrumbs += '<li'+last_element+'><a href="'+myArray[i+1]+'">'+myArray[i+2]+'</a></li>';
			}
		} 
		ul_element.innerHTML = breadcrumbs;
			
		// Write new cookie
		set_cookie("breadcrumb",myArray.join(','));
	}
}

function get_google_search(query_type, search_query, infodiv) {
	
	if (infodiv.id=='google-web') {
		var searcher = new google.search.WebSearch();
		searcher.setResultSetSize('4');
	}
	else if (infodiv.id=='google-news') {
  	var searcher = new google.search.NewsSearch();
		searcher.setResultSetSize('4');
	}
	searcher.setNoHtmlGeneration();
	searcher.setSearchCompleteCallback(document, 
		function(infodiv) { 
			infodiv.innerHTML = '';
			for ( i in searcher.results ) {
				var entry = searcher.results[i];
				var div = document.createElement("div");
				div.setAttribute('class', 'feed-entry-div');

				var mylink = document.createElement('a');
				if (infodiv.id=='google-blogs') {
					mylink.setAttribute('href', entry.postUrl);
				}
				else {
					mylink.setAttribute('href', entry.unescapedUrl);
					mylink.setAttribute('target', '_blank');
				}				
				mylink.innerHTML = entry.title;
				var header = document.createElement('div');
				header.setAttribute('class', 'feed-entry-title');
				header.appendChild(mylink);
				
				if (infodiv.id=='google-news') {
					var publisher = document.createElement('div');
					publisher.innerHTML = entry.publisher;
					publisher.setAttribute('class', 'feed-entry-publisher')
					header.appendChild(publisher);
				}

				var content = document.createElement('div');
				content.innerHTML = entry.content;
				content.setAttribute('class', 'feed-entry-content')
				
				div.appendChild(header);
				div.appendChild(content);
				infodiv.appendChild(div);

			}
			var sourcelink = document.createElement("a");
			sourcelink.setAttribute('href', searcher.cursor.moreResultsUrl);
			sourcelink.setAttribute('target', '_blank');	
			if (infodiv.id=='google-web') {
				sourcelink.innerHTML = 'Google Search';
			}
			else if (infodiv.id=='google-news') {
				sourcelink.innerHTML = 'Google News';
			}
			else if (infodiv.id=='google-blogs') {
				sourcelink.innerHTML = 'Google Blogs';
			}
			
			var source = document.createElement("p");
			source.setAttribute('class', 'source');
			source.innerHTML = 'More from ';
			source.appendChild(sourcelink);
			infodiv.appendChild(source);
			
		}, new Array(infodiv) );
	searcher.execute(search_query);
	
}

// Initializes geocoder for use in address search
function initialize_geocoder() {
	if ( typeof(geocoder) != 'undefined') {
		geocoder = new GClientGeocoder();
	}
}

// When geocoder returns an answer, sets cookie appropriately and redirects
function setCookiesAndRedirect(response) {

	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	} else {
		place = response.Placemark[0];

		set_cookie("address",place.address);
		set_cookie("lat",place.Point.coordinates[1]);
		set_cookie("lng",place.Point.coordinates[0]);
		
		window.location="./browse/address/"+place.address;
	}
}

// Processes search form submission - parses, geocodes if necessary, redirects
function submitSearchForm(searchstring) {
	
	// Regular Expressions
	zipRegExp = new RegExp(/^([0-9]{5})[0-9\-\s]*$/);
	addrRegExp = new RegExp(/^[0-9]+\s+[A-Za-z]+/);
	
	// Is it only a zip code?
	if ( mymatch = zipRegExp.exec(searchstring) ) {
		zip = mymatch[1];
		
		// Delete addr, lat, lng cookies
		set_cookie("lat","");
		set_cookie("lng","");
		set_cookie("address","");
		
		// Set zip code cookie
		set_cookie("zip",zip);
		
		// Redirect to search page
		window.location="./browse/zip/"+zip;
	}
	
	// Is it an address?
	else if ( mymatch = addrRegExp.exec(searchstring) ) {
		address = searchstring;
		
		// Append zip information if available
		if ( zip = get_cookie("zip") ) {
			address = address+" "+zip;
		}
		
		// Geocode, set cookies and redirect to search page
		geocoder.getLocations(address, setCookiesAndRedirect);
	}
	
	// If not zip code or address, recipient page will decode
	else {
		set_cookie("address","");
		set_cookie("lat","");
		set_cookie("lng","");
		set_cookie("zip","");
		
		window.location="./search/index/"+searchstring;
	}
}

// Helper function
function getElementsByClassName( strClassName, obj ) {
    var ar = arguments[2] || new Array();
    var re = new RegExp("\\b" + strClassName + "\\b", "g");

    if ( re.test(obj.className) ) {
        ar.push( obj );
    }
    for ( var i = 0; i < obj.childNodes.length; i++ )
        getElementsByClassName( strClassName, obj.childNodes[i], ar );
    
    return ar;
}

// Candidate chooser functionality
function chooser_update_status(obj) {
  var id_vals   = obj.id.split("-");
  var office_id = parseInt(id_vals[0]); 
  var id        = parseInt(id_vals[1]); 
  var holders   = parseInt(id_vals[2]);
  if (selections[office_id]) {
    for (var i in selections[office_id]) {
      if (id == selections[office_id][i]) {
        selections[office_id].splice(i,1);
        if (selections[office_id].length == 0) {
          delete selections[office_id];
        }
        chooser_load_status();
        return;
      }
    }
    if (selections[office_id].length == holders) {
      selections[office_id].shift();
    }
    selections[office_id].push(id);
  } else {
    selections[office_id] = [id];
  }
  chooser_load_status();
}

function chooser_load_status() {
  var worklist = document.getElementsByTagName("img");
  for (var i=0; i < worklist.length; i++) {
    if (worklist[i].className != "checkbox") {
      continue;
    }
    var id_vals   = worklist[i].id.split("-");
    var office_id = parseInt(id_vals[0]); 
    var id        = parseInt(id_vals[1]); 
    if (!worklist[i].src.match("empty")) {
      worklist[i].src = worklist[i].src.replace('_on','_empty_on');
      worklist[i].src = worklist[i].src.replace('_off','_empty_off');
    }
    for (var j in selections) {
      if (j == office_id) {
        for (var k=0; k < selections[j].length; k++) {
          if (selections[j][k] == id) {
            worklist[i].src = worklist[i].src.replace('_empty_','_');
          }
        }
      }
    }
  }
  set_selections_to_cookie();
}

function get_selections_from_cookie() {
  selections = {};
  var cookie = get_cookie("selections");
  if (!cookie) {
    return;
  }
  var offices = get_cookie("selections").split(",");
  for (var i=0; i < offices.length; i++) {
    var j = offices[i].split(".");
    office = j.shift();
    selections[office] = j;
  }
}

function set_selections_to_cookie() {
  var out = "";
  for (var i in selections) {
    out += "," + i + "." + selections[i].join(".");
  }
  out = out.substring(1); // Trim leading comma
  set_cookie("selections",out);
}

function rollover(obj,status) {
	if (status=='on') {
		obj.src = obj.src.replace('_off','_on');
	}
	else {
		obj.src = obj.src.replace('_on','_off');
	}
}

// Preload checkmark images
function preload_images() {
	img1 = new Image();
	img2 = new Image();
	img3 = new Image();
	img4 = new Image();

	img1.src = "http://imageelection.com/check_off.gif";
	img2.src = "http://imageelection.com/check_on.gif";
	img3.src = "http://imageelection.com/check_empty_off.gif";
	img4.src = "http://imageelection.com/check_empty_on.gif";
}


// Helper functions for cookies
function set_cookie ( cookie_name, cookie_value ) {
	document.cookie = cookie_name+"="+cookie_value+";path=/";
}

function get_cookie ( cookie_name ) {
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

	if ( results ) {
		return ( unescape ( results[2] ) );
	}
	else {
		return '';
	}
}

function delete_cookie ( cookie_name ) {
	var cookie_date = new Date ( );  // current date & time
	cookie_date.setTime ( cookie_date.getTime() - 1 );
	document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}