// JavaScript Document
 

jQuery(document).ready(function($){
    
	
	// -- Bind the events 
	  
	bindEvents();
	
	// -- Resize the tiles 
	
	DoTileResize();
	
	
	// -- Add menu highlighting
	setActiveMenu()
	
	
	//-- Detect System Messages
	detectSystemMessage();
	
	// -- Handle the debug
	
	//handleDebug();
	
	
	
		
}); // jquery



function showSystemMessage( message, element ) {
	
	
	  // if there is no message div then show the system message where it is
	  if (jQuery('#system-message-div') && jQuery('#system-message-div').html() != null) {
		 jQuery('#system-message-div').append( message );
		  
	  } else {
		 jQuery(element).css('display', 'inline');
		  
	  }
		
}

function detectSystemMessage() {

	  // Joomla System Message
	  //if (window.console) console.log('detectSystemMessage()');
	  
	  
	  if ( jQuery('#system-message') ) {
		if ( jQuery('#system-message dd').html() != null ) { 
		 
		  showSystemMessage( jQuery('#system-message dd').html(), '#system-message' ) 
		 
		  
		} // end if message html exists
	  } // end if system message
	  
	  
	  // Chronoforms System Message
	  
	  if ( jQuery('.cf_alert') ) {
		if ( jQuery('.cf_alert').html() != null ) { 
		 
		  showSystemMessage( jQuery('.cf_alert').html(), '.cf_alert' ) 
		 
		  
		} // end if chronoforms message html exists
	  } // end if chronoforms message
	  
	  
		

}

function setActiveMenu() {
	
	
	// -- Check active menu
	
	if ( jQuery('#tileMenu li#current').length == 0 ) {
		
		
		//if (window.console) console.log('force overview menu as active');
		
		jQuery('a[rel^="overview"]').parent().attr('class','active').attr('id', 'current');
		
		//if (window.console) console.log( jQuery('a[rel^="overview"]') );
		
		
		
	}
}
  
  
  
/*
 * Function to bind events to various page elements
 */  
  
  
  function bindEvents() {
	  
	 
	
	// -- Tile Menu
	// -- Trigger quicksand or load new page
	
	if ( jQuery('#tileMenu li a') ) {
	
	  jQuery('#tileMenu li a').unbind().bind('click', function(e) {
												 
							  e.preventDefault();
							  handleTileMenuClick( jQuery(this) );

	  									 });
	}
	  
	  
	// -- Subscribe Module (Get IBS Updates)
	if (jQuery('#subscribeForm')) {
	  jQuery('#subscribeForm').unbind().bind('submit', function(e) {
							
							
							  e.preventDefault();
							  handleSubscribe( jQuery(this) );

	  									 });
	}
	
	
	// -- Image Caption Sliding 
	if (jQuery('.boxgrid.caption')) {
		jQuery('.boxgrid.caption')
			.unbind()
			.bind('mouseenter', function() { handleImageCaptionOn( jQuery(this) ); })
			.bind('mouseleave', function() { handleImageCaptionOff( jQuery(this) ); });
	  
	}
	
	
	
	
	
  }
  
  
  
  
  
  function handleImageCaptionOn(ImageObj) {
	  $(".cover", ImageObj).stop().animate({top:'190px'},{queue:false,duration:160});
  }
  
  function handleImageCaptionOff(ImageObj) {
	  $(".cover", ImageObj).stop().animate({top:'220px'},{queue:false,duration:160});
  }
  
  
  
  
  


  
  /*
   * Post name and email to mailchimp 
   */
  
  function handleSubscribe(FormObj){
		
		// ajax post the form data
		
		//----------------------------------
		// clear any previous error messages
		
		
		
		
		//----------------------------------
		// get a copy of the form html
		
		//var subscribe_form = jQuery('#subscribe-form-div').html();
		//if (window.console) console.log('subscribe_form');
		
		
		
		//----------------------------------
		// show a loading animation
		
		var ajax_load = "<img src='templates/ibs/images/loadera16.gif' alt='loading...' align='absmiddle' />";
		
		//jQuery('#subscribe-form-div').html(ajax_load);
		jQuery('#subscribe-message').html(ajax_load + " Please wait...");
		
		
		
		
		
		// ---------------------------------
		// read all data from the form
		
		var dataString = "";
		
		FormObj
           .find(':input') // Find all the input elements under those.
           .each(function(i,item) {
				//if (window.console) console.log('data item : '+ item.name);
                dataString = dataString +"&"+ item.name +"="+ item.value  ;
				
				
            });
		   
		dataString += "&tmpl=component";
		
		//-- Basic validation
		
		if ( jQuery('#subscribeForm input[name="email"]').val() == "") {
				
				jQuery('#subscribe-message').html("<strong class='invalid'>ERROR! Please enter an email address.</strong> ");
				return false;
		}
		
		if ( jQuery('#subscribeForm input[name="name"]').val() == "") {
				jQuery('#subscribe-message').html("<strong class='invalid'>ERROR! Please enter your name.</strong>");
				return false;
		}
		/**/
		
		
		// ---------------------------------
		// Call to AJAX 
		
		jQuery.ajax({
					
		  type: "POST",
		  
		  url: "index.php", 
		  
		  cache: false,
		  
		  data: dataString,
		  
		  //dataTypeString: 'xml',
		 
		
		// ----------------------------------------------------------------------
		// Network Error
		  
		  error: function(request,textStatus,errorThrown) {
			  
			jQuery('#subscribe-message')
			.html("<strong class='invalid'>ERROR! Sorry, we cannot add you to our list at the moment.</strong>");
				result = false;
			
				
		  },
		  
		  
		  
		  
		  
		// ----------------------------------------------------------------------
		// Success
		  
		  
		 success: function(data,textStatus, jqXHR) { // data,textStatus,jqXHR (updated since 1.5)
		  	
			
			var result = true;
			var checkServerSideErrors = true;
			
			//-- Check for system errors
			
			if (checkServerSideErrors) {
			
			//-- check for system message
			
			  var matchstring=/(Error)/;
			  
			  var foundin = data.match(matchstring);
			  
			
			// ----------------------------------------------------------------------
			// Server Side Error
		  		
			  if ( foundin != null && foundin != ''   ) { // && checkErrors != 0 && (request === '' || request === null)
			  	
			  	//-- get system error message from the response data
				
				jQuery('#subscribe-message').html("<div class='tempContentDiv'>"+ data +"</div>");
				
				
				//-- now read the response from the current page
				
				var sysmsg = jQuery('.tempContentDiv #subscribeError').text();
				
				 jQuery('.tempContentDiv').remove();
				
				if (window.console) console.log( sysmsg );
				
				
				
				//-- then put result and form back
				//jQuery('#subscribe-form-div').html( subscribe_form );
		
				//-- and show the error message returned
				jQuery('#subscribe-message')
				.html("<strong class='invalid'>"+ sysmsg +"</strong>");
				
				result = false;
				
			  }// end if error found 
			  
			} // end if checkServerSideErrors
			
			
			
			// ----------------------------------------------------------------------
			// do success
			
			if (result) { 
				
				
				
				jQuery('#subscribe-message').html("<strong class='invalid'>SUCCESS! You will now receive updates.</strong>");
				
				jQuery('#subscribeForm input[name="email"]').val('');
				jQuery('#subscribeForm input[name="name"]').val('');
			}
			
			
			bindEvents();
			
		} // end success function
		
		
		, complete: function() {
			
			if (window.console) console.log('done');
			
			
		} // end complete function
		
		
		  
		}); // end ajax post
		
		
		// -- END AJAX
		// ----------------------------------------------------------------------
		
		
  }

  function DoTileResize() {
	  
	  //-- Force padding on every 3rd tile
	  var licounter =0;
	  
	  if ($('#tileDiv ul li')) {
	  
	  $('#tileDiv ul li').each(function() {
		  // only proces every third
		  licounter++;
		  
		  if ( (licounter - 3) == 0 ) { 
			  $(this).attr('class', 'thirdTile');
			  
			  licounter=0;
		  }
		  
		  
		  
	  });	
	  } // end if 
  }
  
  
  
  function handleDebug() {
	// go through the whole page and  add all debug comments to the desginated debug area
	
	
	if ( $('div.debug').html() != null ) {
	  
	  if (window.console) window.console.log('debug found');
	  if (window.console) window.console.log($('div.debug').html());
	  
	  $('body').append('<div id="debug"></div>');
	  
	  $('.debug').each(function() {
		 $('#debug').append( $(this).html() );
		  
		  
		  
	  });	
	  } // end if 
	 
  }
