var postcardApp;   

function windowHeight(){
  var alto = 0;
  if (typeof(window.innerHeight) == 'number') {
    alto = window.innerHeight;
  } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
    alto = document.documentElement.clientHeight;
  } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
    alto = document.body.clientHeight;
  }
  return alto;
}

function windowWidth(){
  var alto = 0;
  if (typeof(window.innerWidth) == 'number') {
    alto = window.innerWidth;
  } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
    alto = document.documentElement.clientWidth;
  } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
    alto = document.body.clientWidth;
  }
  return alto;
}

function fillthescreen(sub){
  winH = windowHeight(); //This returns the screen heigth
  heightNeeded = winH - sub; //We need to substract the footer height
  if (typeof(window.innerWidth) != 'number') { //Explorer doesn't recognize minHeight
    document.getElementById('map_div').style.height = heightNeeded + 'px'; //So, we use height (and explroer bug)
  }
  document.getElementById('map_div').style.minHeight = heightNeeded + 'px'; //For every other browser, we use minHeight
}

/*
 * Load all the icons - they're embedded in a hidden part of the HTML which is sent at load-time.
 */
function loadIcons(){

  $('#icons .icon').each(function(){
  
    var icon_id = $(this).find('.icon_id').text();
    var icon_file = $(this).find('.icon_file').text();
    
    var icon = new GIcon(G_DEFAULT_ICON);
    icon.image = icon_file;
    
    icons[icon_id] = icon;
  });
}

function show_people_grid(html){
  $('#people_grid_contents').html(html);
  
  var grid = $('#people_grid')
  
  grid[0].style.left = 100 + 'px';
  grid[0].style.width = (windowWidth() - 200) + 'px';
  
  $('#close_link')[0].style.left = (windowWidth() - 230) + 'px';
  
  grid.show();
  
}

function hide_people_grid() {
  $('#people_grid').hide();
}

function select_person(person_id){
  setHashValue("person", person_id);
	setHashValue("country", null);
}

function select_country(country_code){
  setHashValue("country", country_code);
	setHashValue("person", null);
}


var lat_lng_match = /\s[-\d\.]+,[-\d\.]+\s/g;

function show_card() {
	
	var postcard_id = postcardApp.propertyValue('postcard');
	
	// the id might be null/undefined
	if(!postcard_id) return;
	
  var url = '/view/postcard/' + postcard_id + '?windowHeight=' + windowHeight();
  
  jQuery.get(url, function(data){
    // the lat and lng is encoded in a comment at the top of the response... 
    var latlng_array = data.match(lat_lng_match)[0].split(",")
    var lat_lng = new GLatLng(latlng_array[0], latlng_array[1]);
    
    map.openInfoWindowHtml(lat_lng, data, {
      onCloseFn : function() {           
        // when the info window is closed, we need to clear out any postcard id from the hash
        setHashValue('postcard', null);
      }
    });
  });
}


function newPostcardApp() {

  var oldVals = new Array();
	
  /*
   * 
   */
  this.hashChanged = function(){
		var vals = decomposeHash();
		
		var person_changed = propertyChanged('person', vals);
		var country_changed = propertyChanged('country', vals);
		
		if (person_changed || country_changed) {
			//alert("person_changed="+person_changed+ " country_changed="+country_changed);
  		loadPostcards();
	  }
		
		var postcard_changed = propertyChanged('postcard', vals);
    if (postcard_changed) {
      show_card();
    }
  }
	
	/*
	 * detect changes in a property 
	 */
	this.propertyChanged = function(property, vals) {
    if(!(oldVals[property] === vals[property])) {
			oldVals[property] = vals[property];
			if (vals[property]) {
				return vals[property];
			} else {
			 	return true;
			}
    }
		return false;
	}
	
	 /*
   * get a property value 
   */
  this.propertyValue = function(property) {
		return oldVals[property];
  }
	
	// initialize
  setupHashMonitor(this.hashChanged);
  loadPostcards();  
	
	// end constructor
  return this;
}


function setupHashMonitor(callback){

  // don't call it at the start - we can do that ourselves
  var old_hash = window.location.hash.toString();
  
  setInterval(function(){
    var new_hash = window.location.hash.toString();
    
    if (!(new_hash === old_hash)) {
      callback();
      old_hash = new_hash;
    }
  }, 250);
}

/*
 * Decompose a hash like #foo-bar&boo-123  into:
 * foo: bar
 * boo: 123
 */
function decomposeHash() {
  var hash = window.location.hash.substring(1); // remove the # char
  
  var parts = hash.split('&');
  
  var result = new Array();
  
  var matches;
  for(var idx = 0; idx < parts.length; idx++) {
    matches = parts[idx].match(/(\w+)-(\w+)/);
    if(matches) {
      var name = matches[1];
      var value = matches[2];
      result[name] = value;
    }
  }
  
  return result;
}

function rebuildHash(array) {
  
  var hash = "#";
  
  for (var key in array) {
    var pair = key + "-" + array[key];
     
    if(hash === "#") {
      hash = hash + pair;
    } else {
      hash = hash + "&" + pair;
    }
  }
  
  window.location.hash = hash;
}

function setHashValue(name, value) {
  var vals = decomposeHash();
	
	if(value) {
		// add or update the entry
	  vals[name] = value;	
	} else {
		// remove the entry
		var new_vals = new Array();
		
	  for (var item in vals) {
			if(!(item === name)) {
				new_vals[item] = vals[item];
			}
		}
		vals = new_vals;
	}
  
  rebuildHash(vals);
}

function joinStrings(array, separator) {
	var first = true;
	var result = "";
	
	for (var item in array) {
	  if(!first) {
			result += separator;
		} 
		result += array[item];
		first = false;
	}
	return result;
}

