  var Application = function() {

   //Internal reference to self, circumvents 'this' keyword which is relative to current context, not root level class instance.
    _this = this;

    //Application title for Meta/Head[Title] 
    applicationTitle = 'iP Internet - Web Developers, Sydney. iPhone App Developers, HTML5 Experts, Intranet/Extranet Specialists. '

    //Reference to the projectHtml template
    projectHtml = $('div.project')[0];
    
    //Reference to the carouselHtml template
    carouselHtml = $('div.carouselImage')[0];
      
    //Private project filter variable
    projectFilter = 'date'; //Other options 'az', 'year', 'type', 'industry'  
    
    //A random project id (assigned in init())
    defaultProjectId = 0;   
    
    blnProjectsActive = false;    
    
    //Carousel Reference
    this.carousel = null;

    //Projects status 
    this.projectsOpen = false;

    /** Public - initialise application framework **/
    this.init = function() {
      //If Config has not been loaded, go and load 
      if (!Config._is_dataLoaded) { 
        //Initialise config
	Events.addEventListener(ConfigEvent.INIT, _this.onConfigInit, _this, 'ConfigInit');
        Config.init();
      } else {
        onConfigInit();
      }       
    };
    
    this.onConfigInit = function() {
      //Get random project
      defaultProjectId = _this.getRandomProject();	    
	    
      //Will not fire first time around
      SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onDeeplinkChange);
      
      //Manual fire for first time around
      SWFAddress.dispatchEvent(new SWFAddressEvent(SWFAddressEvent.CHANGE))
      
      Content.init();
      
      this.initFramework();
      
     //Set Offset and lowerYBound - both are used to calculate 
      var offset, lowerYBound;
      offset = setProjectsOffset(offset, lowerYBound).offset;
      lowerYBound = setProjectsOffset(offset, lowerYBound).lowerYBound;
  
      //Set window resize function
      $(window).bind("resize.Projects", function() {
        offset = setProjectsOffset(offset, lowerYBound).offset;
        lowerYBound = setProjectsOffset(offset, lowerYBound).lowerYBound;
      });
	
      //Set event for iPad / iPod orientation change
      $(window).bind("onorientationchange.Projects", function(){
        offset = setProjectsOffset(offset, lowerYBound).offset;
        lowerYBound = setProjectsOffset(offset, lowerYBound).lowerYBound;
      });
  
      //Attach filter click events
      $('#filters').find("img.projectsFilter").each(function() {
        $(this).bind('click', function() {           
          onFilterClick(this);
        }); 	
        $(this).bind('mouseover', function() {   
					   
	  if (!($(this).attr('src').indexOf('_s') > 0)) $(this).attr('src', $(this).attr('src').replace('.png', '_o.png'));					  
	});	
        $(this).bind('mouseout', function() {           
	  if (!($(this).attr('src').indexOf('_s') > 0)) $(this).attr('src', $(this).attr('src').replace('_o', ''));
	});		
      });  
            
      //Instruction/Keyboard shortcut animations
      $('#keyboard').bind('mouseover', function(e) {
	$('#instructions').fadeIn('fast');
        $('#siteControls').bind('mouseleave', function() {           
	  $('#instructions').stop(true, true).fadeOut('fast');
	});		
      });

      //This section handles view all projects click, binding the icon to the cursor, and the close of the projects container
      $('#buttonView:not(.locked)').live("click", function(e) {
        _this.projectsOpen = true;
        //Attach animation complete listener, then call showProjectContainer which will dispatch this event on complete.
	//onCarouselOpenComplete essentially then calls loadProjectContent
	//We wait to load the project content to avoid lag on animation.
	projectLoader_animateIn()
        Events.addEventListener(AnimationEvent.ANIMATION_COMPLETE, _this.onCarouselOpenComplete, _this)
        showProjectContainer(_this.carousel);

	//Mouse move function for close button
	$("html").bind("mousemove", function(e){    
          if((e.pageY < offset.top) || (e.pageY > lowerYBound)) {
            blnProjectsActive = true;
            showCloseButton(e);         	
          } else { 
            blnProjectsActive = false;      
            hideCloseButton();
          }
        }); 
	
	//Click event for closing project container
        $("html").bind("click", function(e) {
          if(blnProjectsActive) { 
            _this.projectsOpen = false;	  
            blnProjectsActive = false;      	
            $("html").unbind("mousemove");  	
            hideCloseButton();	
            hideProjectContainer(_this.carousel);   
          }
        });    
      });        
      
      //Memory Cleanup
      //blnProjectsActive = null;

    };
    
    /**Private - Handles a keyboard click event **/
    onKeyboardPress = function(e) { 
      //Listens for the keydown, then emulates (via .trigger()) various events, saves replicating code 
      switch(e.which) {
	case 32: //space
	  //alert('space pressed: ' + _this.projectsOpen);
          if(!_this.projectsOpen) {   
            $('#buttonView').stop(true, true).trigger("click");
          } else {		  
	    //Force projects active to true to get around if clause in html click
            //blnProjectsActive = true;
            $("html").stop(true, true).trigger("click");		
	  }
	  break;
	case 37: //left
	  $(_this.carousel.prevBtn).trigger("click");
	  break;
	case 39: //right
	  $(_this.carousel.nextBtn).trigger("click");
          break;	  
      }    
    }
    
    enableKeyboardEvents = function() {
      //alert('enable');
      $(document).bind("keydown", function(e) {						    
        onKeyboardPress(e);
      });  	    
    }
    
    disableKeyboardEvents = function() {
      //alert('disable');	    
      $(document).unbind("keydown");  	    
    }

    /**Public - Loads images in _this.carousel, then initialises _this.carousel **/          
    this.loadProjectInfo = function() {
      var currentProjectId = (isNaN(SWFAddress.getPathNames()[3])) ? defaultProjectId : SWFAddress.getPathNames()[3];
      var currentProject = null;	    
      var currentProjectUrl = 'www.ipinternet.com.au';
      var facebooklikeContent = '<iframe src="http://www.facebook.com/plugins/like.php?href=' + currentProjectUrl + '&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>'

      //Get current project
      $.each(Config._projects, function(index, objRef) {
        if (objRef.id == currentProjectId) currentProject = objRef;       
      });

      $('#projectTitle').text(currentProject.name);
      $('#projectType').text(currentProject.type);
      $('#projectDate').text(currentProject.dateString);
   
      $('#facebookLike').html(facebooklikeContent);
      $('#buttonLaunch').attr('href', currentProject.url);
      $('#buttonLaunch').text('View Website');      
    };

    /**Public - Gets a random project id based on a random index **/      
    this.getRandomProject = function() {
	  var RanIndex =  Math.floor((Config._projects.length)*Math.random());
	  return  Config._projects[RanIndex].id;
    };

    /**Public - Loads images in _this.carousel, then initialises _this.carousel **/      
    this.loadCarouselImages = function() {  
      var currentProjectId = (isNaN(SWFAddress.getPathNames()[3])) ? defaultProjectId : SWFAddress.getPathNames()[3];
      var currentProject = [];
      var container;
      
     // Events.removeEventListener(ConfigEvent.INIT, 'Config');
      $.each(Config._projects, function(index, objRef) {
        if (objRef.id == currentProjectId) currentProject = objRef;       
      });

      var carouselHtmlTemplate = $(carouselHtml).clone(); // We add a wrapper tag, since .html() is an innerHtml() call - nb: projectHtml is a class level property that stores the template on initial page load
      $('#carouselTop').empty();
      $.each(currentProject.images, function(index, value) {
        carouselHtmlTemplate = new $(carouselHtml).clone();
        $(carouselHtmlTemplate).find('.imgsrc').attr('value', value);	
        $(carouselHtmlTemplate).appendTo($('#carouselTop'));	
	carouselHtmlTemplate = null;	
      });  
      
      //To allow the carousel to function, we check to make sure 5 items are present. If not, stick duplicate items in to replace.
      var itmArray = $("#carouselTop").find("div[class^='carouselImage']");
      if(itmArray.length < 5) {
        var newItem = null;
	var len = itmArray.length;
	for(var i=0; i < len; i++)
	{
          newItem = $(itmArray[i]).clone();
	  $(itmArray[i]).parent().append(newItem);

          itmArray.push(newItem); 
	  //We essentially duplicate every item, if we still dont have enough, restart loop and add another set until we have enough.
	  //If we only populated up to 5 items, the loop could be out of synch. For example, under such logic, with 3 items it would only result 
	  //in items 1 and 2 being replicated. This would mean between replicated item 1 and original item 1 there would only be 1 click which
	  //may confuse the user as there is no intuitive logical pattern to the carousel. ie. 1, 2, 3, 1, 2, 1, 2, 3 etc
          if(i == len && itmArray.length < 5) i = 0; 		
	}
      };      
      
     //Variable declerations used in loop
      var img, imgSrc, imgContainer, hiddenSrc;     
      $("#carouselTop").find("div[class^='carouselImage']").each(function() {
        //Get the container and image, then remove the hidden field from DOM
        imgContainer = $(this);
        //Get the hidden field containing the image src
        hiddenSrc = imgContainer.find("input[class^='imgsrc']");
        //Set the image src
        imgSrc = hiddenSrc.val();
   
        //Remove the hidden field from DOM
        hiddenSrc.remove();	      
        //Show the image
        img = loadImage(imgSrc, imgContainer);
      });

      //Get all image elements, convert nodeList to array
      var itemsTop = toArray($("div#carouselTop > div.carouselImage"));
      var prevBtn = $('#buttonPrevious'), nextBtn = $('#buttonNext');

      //Create top instance of carousel, pass through next-previous buttons and nodelist.
      var _data = null;
      if(_this.carousel == null) _this.carousel = new Carousel();
      _this.carousel.init(_data, nextBtn, prevBtn, itemsTop);    

      //Memory Cleanup      
      _data = null;
      itemsTop = null;
      prevBtn = null;            
    };  

    /**Public - Basic function called once the animation of the carousel is complete, in turn loads the projects **/      
    this.onCarouselOpenComplete = function() {
      //We wait to load the project content to avoid lag on animation.
      blnProjectsActive = true;
      loadProjectContent(projectFilter);   
    };
    
    /**Public - Extensive code to be actioned once config has been initialised **/  
    this.configInitialised = function() { 
      var currentProjectId = (isNaN(SWFAddress.getPathNames()[3])) ? defaultProjectId : SWFAddress.getPathNames()[3];
      
      //Remove event listener
      Events.removeEventListener(ConfigEvent.INIT)

      var _data = '';
      var projectHtmlTemplate = $(projectHtml).clone(); 
      //sort array 
      switch(projectFilter.toLowerCase()) {
        case 'industry':
	  Config._projects.sort(function(a, b){
	    return (a.industry.toLowerCase() < b.industry.toLowerCase()) ? -1 : (a.industry.toLowerCase() == b.industry.toLowerCase()) ?  0 : 1;
	  });		
	break;
        case 'type':
	  Config._projects.sort(function(a, b){
	    return (a.type.toLowerCase() < b.type.toLowerCase()) ? -1 : (a.type.toLowerCase() == b.type.toLowerCase()) ?  0 : 1;
	  });		
	break;
        case 'date':
	  Config._projects.sort(function(a, b){				 
	    return (a.date > b.date) ? -1 : (a.date == b.date) ?  0 : 1;
	  });		
	break;	
        case 'az':
	  Config._projects.sort(function(a, b){
	    return (a.name.toLowerCase() < b.name.toLowerCase()) ? -1 : (a.name.toLowerCase() == b.name.toLowerCase()) ?  0 : 1;
	  });	
	break;		
      }
      
      for (var i=0; i<Config._projects.length; i++){
	//alert(Config._projects[i].name);   
      }
      
      //create html
      var currentHeader = '';
      //Clear html 
      $('#projectGallery').empty();
      $.each(Config._projects, function(index, objRef) {
        //Set header
        switch(projectFilter.toLowerCase()) {
          case 'industry':
            if(currentHeader != this.industry) _data += '<h3>' + this.industry + '</h3>'  
	  break;
          case 'type':
            if(currentHeader != this.type) _data += '<h3>' + this.type + '</h3>'	  		
	  break;
          case 'az':
            if(currentHeader != this.name) _data += '<h3>' + this.name.charAt(0).toUpperCase() + '</h3>'	  	
 	  break;		
        }

        projectHtmlTemplate = new $(projectHtml).clone();         
	$(projectHtmlTemplate).find('.projectImage').attr('id', 'Project' + this.id);
        $(projectHtmlTemplate).find('.imgsrc').attr('value', this.thumbnail);
        $(projectHtmlTemplate).find('.deeplink').attr('value', this.deeplink);	
        $(projectHtmlTemplate).find('h3.projectName').text(this.name);		
        $(projectHtmlTemplate).find('h4.projectType').text(this.type);			

	//Add html to _data variable
        $('#projectGallery').append($(projectHtmlTemplate)); 
	projectHtmlTemplate = null;
      });     
      
      //Set html to be equal to compounded html _data variable

      
      //Remove loader
      projectLoader_animateOut();
      //Variable declerations used in loop
      var img, imgSrc, imgContainer, hiddenSrc, overlay;
      //Find all thumnails & pre-load the image
      $("#contentProjects").find("div[class^='projectImage']").each(function() {
        //Get the container and image, then remove the hidden field from DOM
        imgContainer = $(this);
        //Get the hidden field containing the image src
        hiddenSrc = imgContainer.find("input[class^='imgsrc']");

        //Set the image src
        imgSrc = hiddenSrc.attr("value");
        //Remove the hidden field from DOM
        hiddenSrc.remove();	       

        //Show the image
        img = loadImage(imgSrc, imgContainer);
        
        //We pass both these parameters through since they may have changed or no longer be available when the click event is eventually fired.
        $(imgContainer).bind("click", { deeplink: imgContainer.find('.deeplink').attr('value') }, function(e){
          //Dispatch deeplink 	
	  SWFAddress.setValue(e.data.deeplink);   									 
          loadProjectContent(projectFilter);   	  
	});   

        //Add Frame - adds selectedProject class if current project
        overlay = (imgContainer.attr('id') == 'Project' + currentProjectId) ? $('<div class="projectImageOverlay selectedProject">') : $('<div class="projectImageOverlay">');	
	$(imgContainer).append(overlay);	  									 	
      });
      
      //Memory Cleanup
      _data = null;  
      projectHtmlTemplate = null;
      img = null;
      imgSrc = null; 
      imgContainer = null;
      hiddenSrc = null;          
    };
     
    /**Private - Load the project content and assign the filter images**/  
    loadProjectContent = function(filter) {
      //Set Filter styles
      
      $('#filters').find("img.projectsFilter").each(function() {
        var src = $(this).attr('src').replace('_o', '');
        if (filter == $(this).attr('id').split("filter_")[1]) {
          //Check to see if the clicked item is already selected, If not, add _o to filename
          src = (src.indexOf('_s') > 0) ? src : src.substring(0, src.lastIndexOf('.')) + '_s' + src.substring(src.lastIndexOf('.'));
          $(this).attr('src', src);
        } else {
          src = (src.indexOf('_s') == -1) ? src : src.substring(0, src.lastIndexOf('_s')) + src.substring(src.lastIndexOf('.'));
          $(this).attr('src', src);         
        }
      });    

       //If Config has not been loaded, go and load 
      if (!Config._is_dataLoaded) { 
        Events.addEventListener(ConfigEvent.INIT, _this.configInitialised, _this, 'Config');
        Config.init();
      } else {
        _this.configInitialised();
      }
      
      //Memory Cleanup
      loadingDiv = null;
      stylesObj = null;
      src = null;
    };    
    
    /**Private -Basic animation in function for projectLoader**/
    projectLoader_animateIn = function() {
      //Create loader, set it styles to match contentProjects
      var stylesObj = {
        'width' : $('#contentProjects').css('width'), 
        'height' : $('#contentProjects').css('height'), 
        'z-index' : $('#contentProjects').css('z-index') + 1,
        'position' : $('#contentProjects').css('position'),
        'marginTop' : $('#contentProjects').css('marginTop'),
        'top' : $('#contentProjects').css('top'),
        'left' : $('#contentProjects').css('left')
      };
      $('#loaderOverlay').css(stylesObj);  
      $('#projectContentLoader').fadeIn();
    };
   
    /**Private - Basic animation out function for projectLoader**/  
    projectLoader_animateOut = function() {  
      $('#projectContentLoader').fadeOut();
    };
    
    /**Private - onFilterClick**/  
    onFilterClick = function(filter) {  
      if (projectFilter != $(filter).attr('id').split("filter_")[1]) {	 	
        var src = $(filter).attr('src');
        //Check to see if the clicked item is already selected.
        //If not, add _s to filename
        src = (src.indexOf('_s') > 0) ? src : src.substring(0, src.lastIndexOf('.')) + '_s' + src.substring(src.lastIndexOf('.'));
        $(filter).attr('src', src);
        projectFilter = $(filter).attr('id').split("filter_")[1];
        projectLoader_animateIn();
        loadProjectContent(projectFilter);       
      }
    };     
    
    /**Public - Loads config (normally fired on an animation complete) **/      
    this.initProject = function() {     
     //Events.removeEventListener(AnimationEvent.ANIMATION_COMPLETE, 'CarouselClose');
      _this.loadCarouselImages();
      _this.loadProjectInfo(); 
    };  
    
    this.initFramework = function() {
      var scrollBarWidth = 17;

      //Set window resize function
      $(window).resize(function() {
        Content.setWindowHeight();
       // Content.setBasicContentHeight();
       Content.setContentHeights();
        $('#filters').width($(window).width() - scrollBarWidth);
	
	//Position background top, no need to position bottom
	$('#backgroundTop').css('backgroundPosition', '50% ' + ($('#backgroundTop').height() - 800) + 'px');
      });
	
      //Set event for iPad / iPod orientation change
      window.onorientationchange = function(){
        Content.setWindowHeight();
        Content.setBasicContentHeight();
      };
      
      //Emulate resize event to resize properly
      $(window).trigger('resize');
      	      
      //Bind the click function to the email sign up
      $('#signUpButton').bind('click', function() {
        SignUp.submitForm();
      });
                  
      //Bind the blur function to the email sign up
      SignUp.init($('#signUpEmail'));	      
      $('#signUpEmail').bind("blur", function() {
        SignUp.init($(this));					 
      });

      //Bind the click event to the close button on the basic content window
      $('#close').bind('click', function() {
        $('#close').fadeOut();					 
        Content.contentMode = false;
        $('#projects-wrapper').animate({top: '0'}, Content.animation.outSpeed, Content.animation.easingOutMethod);

        //Get Current Project URL
	var selectedProjectUrl = $('#projectGallery div.selectedProject').siblings('.deeplink').val();
	if(typeof selectedProjectUrl == 'undefined') selectedProjectUrl = ' '; //Rather than '/', there is a strange ie7 bug where it changes the page width by ~5px when deeplink is set to '/'

        //Set deeplink back to current project url
        SWFAddress.setValue(selectedProjectUrl); 
        this.blur(); 
        return false;	  
      }); 
    };
    
    /**Handle the event raised when the deeplink is changed**/ 
    onDeeplinkChange = function(event) {
      //Get first level item
      var section = SWFAddress.getPathNames()[0];
      var pageid = SWFAddress.getPathNames()[1];
      var subsection = SWFAddress.getPathNames()[2];
      var subpageid = SWFAddress.getPathNames()[3];   
      
      if(typeof section == 'undefined') SWFAddress.setValue('/')
      
      //Update content to reflect deeplink change
      loadSection(section, pageid, subsection, subpageid);


      //Set page title
      SWFAddress.setTitle(applicationTitle + ' ' + event.path);
    };  
  
    /**Make any updates neccessary after the deeplink is updated**/ 
    loadSection = function(section, pageid, subsection, subpageid) {
      //There will be 3 types of content to load:
      //  1. Home page (load the default project gallery)
      //  2. Basic content page (load the basic content window)
      //  3. The project gallery with a selected client (load the project gallery with a specified client)
      section = (typeof section == 'undefined') ? 'projects' : section;  
      switch (section.toLowerCase()) {
        case 'projects':
	default:
	  //To make sure there are not multiple events firing, we first try to remove events
	  disableKeyboardEvents();

	  //Then add events to listen for keyboard events
          enableKeyboardEvents();
	              Events.addEventListener(AnimationEvent.ANIMATION_COMPLETE, _this.initProject, _this, 'CarouselClose')	

          //Check if carousel exists, if it does try to close it.
          if(projectContainerIsOpen) {
            _this.projectsOpen = false;	    
            hideProjectContainer(_this.carousel);   
            //Make sure close button is hidden nb: only applicable on  deeplink change, not on initial page load
            $("html").unbind("mousemove");  	
            hideCloseButton();	  
	  } else { 
	    _this.initProject();
   	  }
	
          break; 
        case 'about-us':
        case 'privacy-policy':	
        case 'contact-us':
	  //Remove keyboard events
          disableKeyboardEvents();
	  
          //If the current page is a sub-section, set the section & pageid to equal this
          if (typeof(subsection) != 'undefined' && typeof(subpageid) != 'undefined') {
            section = subsection;
            pageid = subpageid;
          }

          //If no images are loaded (initial load rather than deeplink change) then load project images 
	  if($('#carouselTop > div.carouselImage').size() == 1) {
            _this.initProject();	  
	  }
	  
    	  //Activate the content click
          Content.contentClick(section, pageid);
          break;
      }         
    }     
  };
      
  //The content object - for basic content (not project gallery)
  Content = {
    //non-conflicat reference to itself
    _this: this,
	  
    //The window or viewport height
    winHeight: 0,
      
    //The footer height
    ftrHeight: 0,
      
    //The height of the wrapper around the project gallery content
    projectWrapperHeight: 0,
      
    //The position the layer needs to animate to
    positionToMoveTo: 0,
      
    //Set the mode to true when the content layer is active. Default is to hide the content layer.
    contentMode: false,
    
    //The configuration data. This is primarily used to load the navigation
    _configData: null,
    
    //Initialise function
    init: function() {
      _configData = Config._data;
    },
     
    //Animation values for speed & easing. See http://jqueryui.com/demos/effect/#easing for other easing values.
    animation: {
      inSpeed: 800,
      outSpeed: 800,
      easingInMethod: 'easeInOutExpo',
      easingOutMethod: 'easeInOutExpo'
    },
      
    //Sets the height of the project gallery content window & the content layer
    setWindowHeight: function() {
      //Get window height
      Content.winHeight = getWindowHeight();
	    
      //Get footer height
      Content.ftrHeight = $('#footer').height();
	
      //Get wrapper height
      $('#projects-wrapper').height(Content.winHeight);
      Content.projectWrapperHeight = $('#projects-wrapper').height();
	
      //Set the position to move to as the window height
      Content.positionToMoveTo = Content.winHeight - Content.ftrHeight;
      
      //Move the Projects panel to the correct location if content mode is active
      if (Content.contentMode) $('#projects-wrapper').css({top: Content.positionToMoveTo});
    },
      
    //Sets the height of the content layer
    setBasicContentHeight: function() {
      //Set content layer to the same height as the window
      $('#basicContent-wrapper').height(Content.winHeight - Content.ftrHeight);
	
      //Set height of internal layers
      $('#basicContent-Left').height(Content.winHeight - Content.ftrHeight);
      $('#basicContent-Right').height(Content.winHeight - Content.ftrHeight);
      $('#basicContent-Content').height(Content.winHeight - Content.ftrHeight);
      $('#Content-Left').height(Content.winHeight - Content.ftrHeight);
      $('#Content-RightNav').height(Content.winHeight - Content.ftrHeight);
    },
      
    //Handles clicking a link to a content page. Passes through the object that produced the click.
    contentClick: function(cItem, cId) {
      //If the content window isn't yet active, animate it in.
      if (!Content.contentMode) {
        Content.contentMode = true;
		
	/* Content.positionToMoveTo IS 0, NEED TO SET AFTER CONTENT LOADED */
        var contentHeight = $('#Content-Left-contentwrap').height() + 250;
        contentHeight = (contentHeight < Content.winHeight) ? Content.winHeight : contentHeight;	
	Content.positionToMoveTo = (Content.positionToMoveTo == 0) ? Content.positionToMoveTo : contentHeight - Content.ftrHeight;
        $('#projects-wrapper').animate({top: Content.positionToMoveTo}, Content.animation.inSpeed, Content.animation.easingInMethod);
      }
      
      //Load the content
      Content.loadContent(cId);
    },
      
    //Load content of the page into the content area
    loadContent: function(cId) {
      //Load the page content
      $.ajax({
        url: "/xml/content/page" + cId + ".xml",
        success: function(data) {
          var element = data.getElementsByTagName('Page').item(0);
          $('#Content-Left-contentwrap').html(element.firstChild.data);
	  Content.setContentHeights();
	  $('#close').fadeIn();
          $('#projects-wrapper').animate({top: Content.positionToMoveTo}, Content.animation.inSpeed, Content.animation.easingInMethod);
        }
      });

      //Load Right hand Nav
      $.ajax({
        url: "/xml/config.xml",
        success: function(data) {
          var  i = 0;
          var level1 = null;
          var level2 = null;
          var navList = '';
	    
          //Get a list of first level navigation items
          level1 =  $(data).find("nav > item[show=1]");
	    
          if (level1.length > 0) {
            navList = '<ul>';
            level1.each(function() {
	      
            //Create item
            navList = navList + '<li><a id="nav_item' + $(this).attr('id') + '" onclick="javascript:SWFAddress.setValue(\'' + $(this).attr("deeplink_value") + '\'); this.blur(); return false;">' +  $(this).attr("name") + '</a>';
	        
            //Get a list of second level navigation items
            level2 =  $(data).find("nav > item[id=" + $(this).attr('id') + "][show=1]").children();
		
            if (level2.length > 0) {
              navList = navList + '<ul>';
	          
              //Add items
              level2.each(function() {
                navList = navList + '<li><a id="nav_item' + $(this).attr('id') + '" onclick="javascript:SWFAddress.setValue(\'' + $(this).attr("deeplink_value") + '\'); this.blur(); return false;"';
                if (cId == $(this).attr("id")) navList = navList + ' class="selected"'
                  navList = navList + '>' +  $(this).attr("name") + '</a></li>';
                });
		  
                navList = navList + '</ul></li>';
              //. if (level2.length > 0)
              } else {
                navList = navList + '</li>';
              }
            });
	      
            //Close top level naviation
            if (level1.length > 0) navList = navList + '</ul>';

            //Write navigation to page
            $('#Content-RightNav').html(navList);
          } //. if (level1.length > 0) 
        }
      });      
    },
    
    setContentHeights: function() {
      $('#basicContent-wrapper').height(Content.winHeight - Content.ftrHeight);

      var contentHeight = $('#Content-Left-contentwrap').height() + 250;
      contentHeight = (contentHeight < Content.winHeight) ? Content.winHeight : contentHeight;

      $('#basicContent-Left').height(contentHeight - Content.ftrHeight);
      $('#basicContent-Right').height(contentHeight - Content.ftrHeight);
      $('#basicContent-Content').height(contentHeight - Content.ftrHeight);
      $('#Content-Left').height(contentHeight - Content.ftrHeight);
      $('#Content-RightNav').height(contentHeight - Content.ftrHeight);	      
    }    
  };

  //Email sign up object
  SignUp = {
    init: function(signup) {
        if(signup.val() == '') signup.removeClass('removeBackground'); else signup.addClass('removeBackground');
	$('#signUpEmail').siblings('.error').hide();
	
    },
    
    submitForm: function() {
      //Hide error
      $('#signUpEmail').siblings('.error').hide();	    

      //Test email 
      if (!SignUp.isEmailValid($('#signUpEmail').val())) { 
        //Shake form and show error
        $('#fmSignUp').effect('shake', {times:4}, 50, function(){ 
          $('#signUpEmail').focus();						       
        });					     	    
	$('#signUpEmail').siblings('.error').text('Invalid email address!');
	$('#signUpEmail').siblings('.error').show();
	//$('#signUpEmail').focus();
      } else {
      
        //Collect data and submit the form.
        $.ajax({
          url: '/scripts/CM_Proxy.aspx',
          type: 'post',
          data: 'cm-ijdyhr-ijdyhr=' + escape($('#signUpEmail').val()),
          async: true,
          success: function() {
  
          },
          error: function(xhr, ajaxOptions, thrownError) {
            //alert('error with form submission: ' + thrownError);
          }
	});
        //Fade out the sign up form.
        SignUp.animation.fadeOutEmailSignup();	
      }
    },
    
    isEmailValid: function(a){
      return !!(a.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i));
    },

    //Animate functions for the email signup      
    animation:  {      
      fadeOutEmailSignup: function() {
        $('#signUpButton').fadeOut("slow");
        $('#signUpEmail').fadeOut("slow", function() {
	  //Clear input box
	  $(this).val('');
	  
	  //Animate thank you text
          SignUp.animation.fadeInThankyou();
        })      
      },
      
      fadeInEmailSignup: function() {
        $('#signUpEmail').fadeIn("slow");
        $('#signUpButton').fadeIn("slow")
	SignUp.init($('#signUpEmail'));
      },
      
      fadeInThankyou: function() {
        $('#thankyou').fadeIn('slow', function() {
          SignUp.animation.fadeOutThankyou();  
        });
      },

      fadeOutThankyou: function() {
        $('#thankyou').delay(2000).fadeOut('slow', function() {
          SignUp.animation.fadeInEmailSignup();
        });
      }
    }
  };

  //Other functions
  function getWindowHeight() {
    var windowHeight = 0;

    if (typeof(window.innerWidth) == 'number') {
      //Non-IE
      windowHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
      //IE 6+ in 'standards compliant mode'
      windowHeight = document.documentElement.clientHeight;
    }

    return windowHeight;
  }
  
  
function loadImage(file, container) 
{ 
  //Declare new image, set height to the inner dimensions (includes padding but not border) of the container
  var img = new Image();
  $(img).width($(container).innerWidth());
  $(img).height($(container).innerHeight());
  file = (typeof(file) == 'undefined') ? '/images/CafePalazzo1.jpg' : file;
  //Add a loading class 
  //Can be used to add any styles (such as a loading gif as a bg image with no-repeat 50% 50%)
  //Can also be used to remove any styles that should only apply after image is loaded.
  if (navigator.appName != 'Microsoft Internet Explorer') $(container).addClass('imageLoading');  
  
  $(img).load(function () {
    //Set the image hidden by default    
    $(this).hide();
    //Insert image
    $(container).prepend(this);
    //Fade image in to create a nice effect
    $(this).fadeIn(function(){
      //Remove the previously added loading class
      $(container).removeClass('imageLoading');
    });
  })

    
  // *finally*, set the src attribute of the new image to our image
  .attr('src', file).attr('alt', file).attr('title', file);
  return img;
}  

