/* !Map */
function resizeViewPort() {
  var viewportWidth = $(window).width()+'px';
  var viewportHeight = $(window).height()+'px';
  $("#viewport").css({'width' : viewportWidth, 'height' : viewportHeight});
}

function filterArray(tileAttributes) {
  var tileInformation = new Array();
  for (i=0;i<tileAttributes.length;i++) {
    if (tileAttributes[i] != 'special' && tileAttributes[i] != 'editable') {
      tileInformation.push(tileAttributes[i]);
    }
  }
  return tileInformation;
}

function dragMap() {
  var map = $(".neighbourhoods");
  if (map.length !== 0) {
    map.draggable();
  }
}

function centerOnNeighbourhood() {
  var neighbourhoods = $(".neighbourhoods");
  if (neighbourhoods.length != 0) {
    var neighbourhoodId = neighbourhoods.attr('id').replace("currentlySelected ", "");
    var neighbourhood = $("div[id*='neighbourhood"+neighbourhoodId+"']");
    if (neighbourhood.length != 0) {
      var neighbourhoodsPosition = neighbourhood.attr('id').split(" ");
      var neighbourhoodsPosition = neighbourhoodsPosition[1].split(",");
      $(".neighbourhoods").css("left", -neighbourhoodsPosition[0])
      $(".neighbourhoods").css("top", -neighbourhoodsPosition[1]);
    }
  }
}

function chookATrain() {
  var neighbourhood = $(".map");
  if (neighbourhood.attr('id')) {
    var neighbourhoodsPosition = neighbourhood.attr('id').split(" ");
    var neighbourhoodsPosition = neighbourhoodsPosition[1].split(",");
    var neighbourhoodX = parseInt(neighbourhoodsPosition[0]);
    var neighbourhoodY = parseInt(neighbourhoodsPosition[1]);
    $(".trainTile").each(function(index) {
      var trainId = $(this).attr("id").split(" ");
      var trainCoordinates = trainId[1].split("-");
      var trainsArray = new Array("boemeltreintje.png", "boemeltreintje2.png", "Express_Trein.png", "goederentrein.png");
      var sizesArray = new Array("214", "214", "505", "414");
      var randomTrain = Math.floor(Math.random()*trainsArray.length);
      if (randomTrain != 0) {
        var randomTrain = randomTrain-1;
      }
      switch (trainId[0]) {
        case 'trainSouth':
          var trainSchedule = Math.floor(Math.random()*2);
/*           if (trainSchedule == 1) { */
            var xCoordinate = (trainCoordinates[1]*50)-50;
            var yCoordinate = (trainCoordinates[0]*50)-50;
            $(".map").append('<div id="trainSouth" title="I\'m a chook-a train yeah" style="background: url(\''+SITE_URL+'/images/planestrainsautomobiles/'+trainsArray[randomTrain]+'\') no-repeat; left: '+xCoordinate+'px; top:'+yCoordinate+'px; width: 24px; height: '+sizesArray[randomTrain]+'px; position: absolute; z-index: 10000000000;"></div>');
            $("#trainSouth").animate({ 
              marginTop: neighbourhoodY+1500,
              easing: 'linear'
            }, 20000, function(){
              $("#trainSouth").remove();
            });
/*           } */
        break;
        case 'trainNorth':
          var trainSchedule = Math.floor(Math.random()*2);
/*           if (trainSchedule == 1) { */
            var xCoordinate = (trainCoordinates[1]*50)-27;
            var yCoordinate = (trainCoordinates[0]*50);
            $(".map").append('<div id="trainNorth" title="I\'m a chook-a train yeah" style="background: url(\''+SITE_URL+'/images/planestrainsautomobiles/'+trainsArray[randomTrain]+'\') no-repeat; left: '+xCoordinate+'px; top:'+yCoordinate+'px; width: 24px; height: '+sizesArray[randomTrain]+'px; position: absolute; z-index: 10000000000;"></div>');
            var marginTop = neighbourhoodY+parseInt(sizesArray[randomTrain]);
            $("#trainNorth").animate({ 
              marginTop: "-"+marginTop,
              easing: 'linear'
            }, 20000, function(){
              $("#trainNorth").remove();
            });
/*           } */
        break;
        case 'trainWest':
        break;
        case 'trainEast':
        break;
      }
    });
  }
}

function deployPlanes() {
  var neighbourhood = $(".map");
  if (neighbourhood.length != 0) {
    var neighbourhoodsPosition = neighbourhood.attr('id').split(" ");
    var neighbourhoodsPosition = neighbourhoodsPosition[1].split(",");
    var neighbourhoodX = parseInt(neighbourhoodsPosition[0]);
    var neighbourhoodY = parseInt(neighbourhoodsPosition[1]);
    var planePosition = neighbourhoodY+Math.floor(Math.random()*1500); 
    var planes = new Array('T-84-THENDERJET.png', 'F-16.png', 'F-16_duo_flight.png');
    var index = Math.round((Math.random()*planes.length));
    if (index != 0) {
      var index = index-1;
    }
    var plane = planes[index];
    if (plane != 'undefined') {
      $(".map").append('<div id="flyingPlane" title="A plane!" style="background: url(\''+SITE_URL+'/images/planestrainsautomobiles/'+plane+'\') no-repeat; top:'+planePosition+'px; left: -621px; width: 621px; height: 125px; position: absolute; z-index: 10000000000;"></div>');
      $("#flyingPlane").animate({ 
        marginLeft: neighbourhoodX+1900,
        easing: 'linear'
      }, 10000, function(){
        $("#flyingPlane").remove();
      });    
    }
  }
}

/* !Tiles */
var selectedTiles = new Array();

function drawTileBorder(tileId) {
  var selectedTileImg = $("#"+tileId+" span img[class!='infoIcon']");
  var selectedTileSpan = $("#"+tileId+" span, #"+tileId+" img.grassTile, #"+tileId+" img.regularTile");
  $(selectedTileImg).css({'width':'48px', 'height':'48px'});   
  $(selectedTileSpan).css({'border':'1px solid #fff', 'width':'48px', 'height':'48px'});
}

function removeTileBorder(tileId) {
  var selectedTileImg = $("#"+tileId+" span img[class!='infoIcon']");
  var selectedTileSpan = $("#"+tileId+" span, #"+tileId+" img.grassTile, #"+tileId+" img.regularTile");
  $(selectedTileImg).css({'width':'50px', 'height':'50px'});   
  $(selectedTileSpan).css({'border':'none', 'width':'50px', 'height':'50px'});
}

function showWindow() {
  $(".special, .editable, .special editable").live('click', function(event) {
    $("#customTile, #infoWindow").remove();
    var tile = $(this);
    var tileClass = tile.attr('class');
    var tileId = tile.attr('id');
    var tileAttributes = filterArray(tileClass.split(" "));
    if (tile.hasClass('special')) {
      var tileType = 'special';
    } else {
      var tileType = 'regular';
    }
    var tileCoordinates = tileAttributes[1];
    var tileInfo = tileAttributes[0];
    var neighbourhoodId = $(".neighbourhoods").attr("id").replace("currentlySelected ","");    
    var year = '';

    if ($("#frentzen")) {
      var year = $("#frentzen").text();
    } else {
      var year = "0";
    }

    //Start multitile option, limit is a selection of 10 tiles
    if (selectedTiles.length > 9 || $("#multiTile:checked").val() != 1) {
      selectedTiles = new Array();
      selectedTiles.push(tileId+" "+tileClass);
      var previouslySelected = $("img[style*='width: 48px'], span[style*='width: 48px']");
      if (previouslySelected[0] !="") {
        previouslySelected.css({'border':'none', 'width':'50px', 'height':'50px'});
      }
      drawTileBorder(tileId);
    } else {
      selectedTiles.push(tileId+" "+tileClass);
      drawTileBorder(tileId);
    }
    
    $("#viewport").append('<div id="infoWindow"><span id="dragHandle"></span><a href="" id="'+tileId+'" class="closeInfoWindow"></a><br class="clear" /><div id="infoWindowContent"></div></div>');
 
    $("#infoWindow").fadeIn(500, function() {
      $('#infoWindow').draggable({ handle: '#dragHandle' });
      if (tile.hasClass('special') && !tile.hasClass('special editable')) {
        var data = {tileId:tileId, infoId:tileInfo, neighbourhoodId:neighbourhoodId, year:year};
        sendRequest('info', data);
      } else {
        var tileUrl = $('img:not(.infoIcon)', tile).attr('src');
        tileCoordinates = tileCoordinates.split("-");
        var data = {row:tileCoordinates[0], column:tileCoordinates[1], info:tileInfo, tileId:tileId, neighbourhoodId:neighbourhoodId, year:year, tileUrl:tileUrl, type:tileType};          
        sendRequest('edit', data);
      }
    });
    event.preventDefault();
  });  
}

function sendRequest(type, data) {
  if (request) {
    request.abort();
  }
  var contentContainer = $('#infoWindowContent');
  if (contentContainer) {
    if (type === 'edit') {
      var request = '/maps/editwindow';
    } else if(type === 'add') {
      var request = '/maps/add';
    } else {
      var request = '/maps/infowindow';
    }
    request = $.ajax({
      url: SITE_URL+request,
      type : 'POST',
      data : data,
      beforeSend: function() {
        contentContainer.children().fadeOut('fast');
        contentContainer.animate({height: '100px'}, 'fast').addClass('loading');
      },
      success : function(response) {
        contentContainer.removeClass('loading').css({opacity : '0'}).html(response).animate({height: '100%', opacity: '1'}, 'fast');
      }
    });
  }
  if (request) {
    return true;
  }
  return false;
}

function closeWindow() {
  $(".closeInfoWindow").live("click", function(event) {
    $('#infoWindowContent').animate({height: '50px', opacity: '0'}, 'fast', function() {
      $("#infoWindow").fadeOut(500, function() {
        var tileId = $(this).attr("id");        
        removeTileBorder(tileId);
        $(this).remove();
      });    
    });
    event.preventDefault();
  });
}

function showTile(tileId, neighbourhoodId) {
  $.ajax({
    'url' : SITE_URL+"/maps/show_tile",
    'type' : 'POST',
    'data' : {'tileId' : tileId, 'neighbourhoodId' : neighbourhoodId},
    'success' : function(response) {
  	  var tileObject = $(".map a[id="+tileId+"]");
      tileObject.replaceWith(response);
    }
  }); 
}

function removeInfoWindow(tileId) {
  $("#infoWindow").delay(2000).fadeOut(500, function() {
    removeTileBorder(tileId);
    $(this).remove();
  });
}

function uploadTile(data) {
  tileId = data.tileId;
  neighbourhoodId = data.neighbourhood;
  $("button#tileBack").removeAttr('disabled');
  $.get(SITE_URL+'maps/get_session', function(response) {
  	$("input#file_upload").uploadify({
      'langFile'       : SITE_URL+'/scripts/nl.uploadify.js',
  	  'id'             : $(this).attr('id'),
  		'swf'            : SITE_URL+'/images/uploadify.swf',
  		'uploader'       : SITE_URL+'maps/add/key:'+response,
  		'cancelImage'    : SITE_URL+'/images/cancel.png',
  		'debug'          : false,
  		'checkExisting'  : '',
  		'postData'       : data,
  		'queueID'        : 'fileQueue',
  		'method'         : 'POST',
  		'buttonText'     : 'Kies bestand',
  		'auto'           : false,
  		'multi'          : false,
  		'queueSizeLimit' : 1,
  		'onUploadSuccess' : function(file,data,response) {
  		  $("#infoWindowContent").fadeOut('fast').html('<div class="buildSuccess">Aannemersbedrijf Van Meri&euml;nboer-Tak heeft de constructiewerkzaamheden op dit kavel afgerond.</div>').fadeIn('fast', function() {
    		  //Show the tile on the map
    		  showTile(tileId, neighbourhoodId);
    		  removeInfoWindow(tileId);
  		  });
  		}
  	});
  
    $("input#tileSubmit").click(function(event) {
      $('#file_upload').uploadifyUpload();
      event.preventDefault();
    });
  });
}

function buildSpecialTile() {
  $("#tileSubmit").live('click', function(event) {
    //$(this).attr("disabled","disabled");  
    $('.error').hide();
	  var tileName = $("input#tileName").val();
		var tileDescription = $("textarea#tileDescription").val();

		if (tileName == "") {
      $("label#tileNameError").css({display:'block'});
      $("input#tileName").focus();
    }
    
    if (tileDescription == "") {
      $("label#tileDescriptionError").css({display:'block'});
      $("textarea#tileDescription").focus();
    }
    
    if (tileName != "" && tileDescription != "") {
      var neighbourhoodId = $("input#neighbourhoodId").val();
      var tileRow = $("input#tileRow").val();
      var tileColumn = $("input#tileColumn").val();
      var tileInfo = $("input#tileInfo").val();
      var tileId = $("input#tileId").val();
      var tileCreator = $("input#tileCreator").val();
      var tileMonth = $("select#tileDateMonth option:selected").text();
      var tileYear = $("select#tileDateYear").val();
      var tileDate = tileMonth+' '+tileYear;
      var currentTile = $("input#currentTile").val();
      var tileName = tileName.replace("&", "\&amp;");
      var tileDescription = tileDescription.replace("&", "\&amp;");

      if ($(this).hasClass('upload')) {
        $(".tileData").fadeOut(500, function() {
          $(this).hide();
          $("input#tileSubmit").val("Bouwen");
          $("input#tileName, textarea#tileDescription, select#tileDateMonth, select#tileDateYear, input#tileCreator").attr("disabled","disabled");
          $(".tileUpload").fadeIn(500, function() {
            $("input#tileBack").removeAttr("disabled");
          });
        });
      }

      if ($("input#tileDemolish:checked, input#tileDemolish[type='hidden']").val() == 1) {
        //The tile should be demolished and uploaded again
        var type = 'upload';
      } else {
        //Just update the information already present
        var type = 'update';
      }
      var data = {type:type, tileName:tileName, tileDescription:tileDescription, tileId:tileId, currentTile:currentTile, tileRow:tileRow, tileColumn:tileColumn, tileInfo:tileInfo, neighbourhood:neighbourhoodId, tileCreator:tileCreator, tileDate:tileDate};
      if (type === 'update') {
        if (sendRequest('add', data)) {
          showTile(tileId, neighbourhoodId);
          removeInfoWindow(tileId);
        }
      } else if (type === 'upload')  {
        uploadTile(data);
      }
    }
    event.preventDefault();
  });
  
  $('button#tileBack').live('click', function(event) {
    $(".tileUpload").fadeOut(500, function() {
      $(this).hide();
      $("input#tileSubmit").val('Volgende →').fadeIn('fast');
      $("input#tileName, textarea#tileDescription, select#tileDateMonth, select#tileDateYear, input#tileCreator").removeAttr("disabled");
      $(".tileData").fadeIn(500, function() {
        $("input#tileBack").attr({"disabled":"disabled"});
      });
    });
    event.preventDefault();
  });
}

function tileToggle() {
  $(".tileToggle").live('click', function(event) {
    var tileToggle = $(this);
    //When the standardTiles are visible, show the special ones
    if ($("#standardTile").is(":visible")) {
      selectedTiles = new Array();    
      var visibleElement = $("#standardTile");
      var hiddenElement = $("#customTile");
      var toggleLabel = "Standaard kavel";
      var tileId = $("input#tileId").val();
      var previouslySelected = $("img[style*='width: 48px'], span[style*='width: 48px']");
      if (previouslySelected[0] !="") {
        previouslySelected.css({'border':'none', 'width':'50px', 'height':'50px'});
      }
      drawTileBorder(tileId);
    } else {
      var visibleElement = $("#customTile");
      var hiddenElement = $("#standardTile");
      var toggleLabel = "Speciaal kavel";
    }
    $(visibleElement).slideUp(500, function() {
      $(visibleElement).hide();
      tileToggle.text(toggleLabel);
      $(hiddenElement).slideDown(500, function() {
        $("#customTile *").removeAttr("disabled");
      });
    });
    event.preventDefault();        
  });
  
  $('input#tileDemolish').live('change', function(event) {
    if ($(this).is(':checked')) {
      $("#tileSubmit").toggleClass('upload').val('Volgende →'); 
    } else {
      $("#tileSubmit").toggleClass('upload').val('Bouwen'); 
    }
  });
}

function selectStandardTile() {
  $(".standardTile").live("click", function(event) {
    //Set the border of the selected tile and unset others
    $("#standardTiles ul li ul li.subGroup ul li[style*=black]").css({"border-color":"white"});
    $(this).parent().css({"border-color":"black"});
    $("#standardTiles ul li ul li.subGroup ul li").removeAttr("id", "selected");
    $(this).parent().attr("id", "selected");
    $("#standardTiles ul li ul li.subGroup ul li").hover(
      function () {
        if ($(this).attr("id") != "selected") {
          $(this).css({"border-color":"#888"});
        }
      }, 
      function () {
        if ($(this).attr("id") != "selected") {
          $(this).css({"border-color":"white"});
        }
      }
    );
    //Get the img element
    var tileUrl = $('img', this).attr("src");
    $("input#tileUrl").val(tileUrl);
    $('#standardTileSubmit').removeAttr('disabled').fadeIn('fast');
    event.preventDefault();
  });
}

function buildStandardTile() {
  $("#standardTileSubmit").live("click", function(event) {
    $(this).attr("disabled","disabled");
    var neighbourhoodId = $("input#neighbourhoodId").val();
    var tileMetaData = new Array();
    var tileIds = "";
    var tileRows = "";
    var tileColumns = "";
    var tileUrls = "";
    var tileInformation = "";

    for (var i=0;i<selectedTiles.length;i++) {
      var tileAttributes = filterArray(selectedTiles[i].split(" "));
      var tileCoordinates = tileAttributes[2].split("-");
      var tileId = tileAttributes[0];
      var tileUrl = $("input#tileUrl").val();
      var tileRow = tileCoordinates[0];
      var tileInfo = tileAttributes[1];
      var tileColumn = tileCoordinates[1];
      var tileMeta = tileAttributes;
      tileMeta[tileMeta.length-2] = 0;
      var tileMeta = tileMeta.join(" ");
      tileMetaData.push(tileMeta);
      if (selectedTiles.length == 1) {
        var tileIds= tileId;
        var tileUrls = tileUrl;
        var tileRows = tileRow;
        var tileColumns = tileColumn;
        var tileInformation = tileInfo;
      } else {         
        var tileIds= tileIds+"-"+tileId;
        var tileUrls = tileUrls+"-"+tileUrl;
        var tileRows = tileRows+"-"+tileRow;
        var tileColumns = tileColumns+"-"+tileColumn;
        var tileInformation = tileInformation+"-"+tileInfo;
      }
    }
    
    var data = {type:'standard', url:tileUrls, tileId:tileIds, tileRow:tileRows, tileColumn:tileColumns, tileInfo:tileInformation, neighbourhood:neighbourhoodId};
    if (sendRequest('add', data)) {
	    //Show the tile on the map
      showTile(tileId, neighbourhoodId);
      selectedTiles = new Array();
		  $("#infoWindow").delay('2000').fadeOut(500);
    }
    event.preventDefault();
  });
}

function multiTileToggle() {
  $("input#multiTile").click(function(event) {
    if (!$(this).attr("checked")) {
      var tileId = $("input#tileId").val();
      var previouslySelected = $("img[style*='width: 48px'], span[style*='width: 48px']");
      if (previouslySelected[0] !="") {
        previouslySelected.css({'border':'none', 'width':'50px', 'height':'50px'});
      }
      drawTileBorder(tileId);
      var lastTile = selectedTiles[selectedTiles.length-1];
      selectedTiles = new Array();
      selectedTiles.push(lastTile);
    }
  });
}

/* !Neighbourhoods */
function submitNeighbourhoodForm() {
  $("#neighbourhoodFormContent form").submit(function() {
    $(this).attr("disabled","disabled");
		var neighbourhoodName = $("input#neighbourhoodName").val();
		var neighbourhoodX = $("input#neighbourhoodX").val();
		var neighbourhoodY = $("input#neighbourhoodY").val();

		if (neighbourhoodName == "") {
      $("label#neighbourhoodNameError").show();
      $("input#neighbourhoodName").focus();
      return false;
    } else if (neighbourhoodX == "" || neighbourhoodY == "") {
      $("label#neighbourhoodPositionsError").show();
      $("object#neighbourhoodPositions").focus();
      return false;
    } else {
      return true;
    }
  });
}

function setNeighbourhoodPosition() {
  $(".neighbourhoodPosition").click(function(event) {
    //Reset possible other neighbourhood positions
    var oldSelection = $("span[style*=background]");
    oldSelection.css({'background':'#fff', 'color':'#000'});
    oldSelection.html("New neighbourhood");
    oldSelection.hover(function() {
      $(this).css({'background':'#666', 'color':'#fff'});
    },
    function() {
      $(this).css({'background':'#fff', 'color':'#000'});
    });
    
    $(this).css({'background':'#333', 'color':'#fff'});
    $(this).html($('input#neighbourhoodName', window.parent.document).val());
    var neighbourhoodPositions = $(this).attr("id").split("|");
    //Set the x and y values from the object
    $('input#neighbourhoodX', window.parent.document).val(neighbourhoodPositions[0]);
    $('input#neighbourhoodY', window.parent.document).val(neighbourhoodPositions[1]);
    event.preventDefault();
  });
}

function toggleWelstand() {
  $("a.welstandsItem").click(function(event) {
    var welstandsId = $(this).attr("id").substr(9);
    $("p.welstandsBody:visible").toggle();
    $("p#welstandsBody"+welstandsId).toggle();
    event.preventDefault();
  });
}

function showInfoIcons() {
  $("#showInfoIcons").click(function(event) {
    $("img.infoIcon").toggle();
    if ($("img.infoIcon:hidden").length != 0) {
      $(this).html("Toon info iconen");
    } else {
      $(this).html("Verberg info iconen");
    }
    event.preventDefault();
  });
}

function fancyBox() {
  $("div.citizenPhoto a, div.historyPhoto a, ul.albumList li a").fancybox({
    'transitionIn'		: 'none',
    'transitionOut'		: 'none',
    'titlePosition' 	: 'inside'
  });
}

function searchField() {
  $("#search").focus(function() {
  	if( this.value == this.defaultValue ) {
  		this.value = "";
  	}
  }).blur(function() {
  	if( !this.value.length ) {
  		this.value = this.defaultValue;
  	}
  });
}

function toggleTools() {
  $("ul li.utilityHeader a:not(#rssLink)").click(function(event) {
    $(this).toggleClass('active');
    var parentObject = $(this).parent().parent();
    $(parentObject.children()).each(function(index) {
      if (!$(this).attr("class")) {
        $(this).slideToggle();
      }
    });
    event.preventDefault();
  });
  $("a#showMore").click(function (event) {
    if ($(this).text() == 'Toon meer') {
      $(this).text('Toon minder').toggleClass('more');
      $("ul#activityList li:hidden").each(function(index) {
        $(this).slideToggle().attr({'class':'overflow'});
      });
    } else {
      $(this).text('Toon meer').toggleClass('more');
      $("ul#activityList li.overflow").each(function(index) {
        $(this).slideToggle();
      });
    }
    event.preventDefault();
  });}

function toggleTileGroups() {
  $("li.tileGroup a").live('click', function (event) {
    var subGroups = $(this).parent().parent();
    var subGroups = $('li.subGroup', subGroups);
    subGroups.each(function(index) {
      if ($(this).hasClass('subGroup')) {
        $(this).slideToggle();
      }
    });
    event.preventDefault();
  });
}

function goToYear() {
  $("form#FrentzenForm .submit").hide();
  $("select#frentzenSelect").change(function() {
    $('form#FrentzenForm').submit();
  });
}

function handleNotifications() {
/*
  $("#notifications .notice, #notifications .error").delay('4000').slideUp('fast', function() {
    $(this).remove();
  });
*/
}

function timeline() {
  var containerWidth = $("#timelineContainer").width();
  var dragElement = $("ul#timeline");
  var dragWidth = dragElement.width();
  dragElement.draggable({
    axis: 'x',
    stop : function(event, ui) {
      var dragLeft = ui.position.left;
      var dragPercentage = -dragLeft/dragWidth * 100;
      $(".slider .ui-slider-handle").css({'left':dragPercentage+'%'});
      if (dragLeft > 0) {
        $(this).animate({'left':'0px'}, 'fast');
      } else {
        if ((dragWidth + dragLeft) < 100) {
          $(this).animate({'left':'-61960px'}, 'fast');
        }
      }
    }
  });
  $( ".slider" ).slider({
    max : dragWidth-(containerWidth/2),
    create : function(event, ui) {
      $(".ui-slider-handle").css({'left':'100%'});
    },
    slide : function(event, ui) {
      var dragValue = -ui.value;
      dragElement.css({'left': dragValue+'px'});
    },
    stop : function(event, ui) {
      var sliderOffset = $(ui.handle).attr('style');
      var sliderOffset = sliderOffset.substr(sliderOffset.indexOf('left: ')+6).replace(/;/, '');
      $(".ui-slider-handle").css({'left':sliderOffset});
    }
  });
  
  $("ul#timelineLegend li a").click(function(event) {
    var element = $(this).parent();
    element.toggleClass('inactive');
    var linkClass = element.attr('class').split(" ");
    var linkClass = linkClass[0];
    switch(linkClass) {
      case 'citizen':
        var linkClass = 'citizen';
      break;
      case 'history':
        var linkClass = 'history';
      break;
      case 'tile':
        var linkClass = 'tile';
      break;
    }
    $("ul#timeline li ul.events").each(function(mainIndex, list) {
      var count = 0;
      $(list).children().each(function(index, element) {
        var element = $(element);
        if (element.hasClass(linkClass)) {
          if (element.hasClass('hidden')) {
            var margin = count*32;
            element.removeClass('hidden');
            element.css({'margin-top':margin+'px'});
            count++;
          } else {
            element.addClass('hidden');
            element.css({'margin-top':'0px'});
          }
        } else if (!element.hasClass('hidden')) {
          var margin = count*32;
          element.css({'margin-top':margin+'px'});
          count++;
        }
      });
    });
    event.preventDefault();
  });
}

$(document).ready(function() { 
  dragMap();
  showWindow();
  closeWindow();
  resizeViewPort();
  setNeighbourhoodPosition();
  submitNeighbourhoodForm();
  centerOnNeighbourhood();
  showInfoIcons();
  fancyBox();
  multiTileToggle();
  toggleWelstand();
  chookATrain();
  deployPlanes();
  toggleTools();
  goToYear();
  searchField();
  handleNotifications();
  toggleTileGroups();
  selectStandardTile();
  buildStandardTile();
  buildSpecialTile();
  tileToggle();
  timeline();
});

$(window).resize(function() { 
  resizeViewPort();
});
