Code examples

class.js

A JavaScript class type framework.

http://www.glgibson.com.au/examples/index.php/welcome/view/test_class_birthdays
/*
 * JavaScript class framework example
 * 
 * (c) copyright 2014 G L Gibson
 */

var Person = function(name)
{
	this.name = name;
	this.age = 20;
	this.hasBeenDisplayed = false;

	// Keep a list of all instances of the class
	Person.prototype.listOfInstances.push(this);
};

// Keep a list of all instances of the class
Person.prototype.listOfInstances = [];

// Static text shared among instances
Person.prototype.birthdayText = "<br>Happy birthday ";

// Function shared among instances
Person.prototype.display = function(highlight)
{
	var prefix = "", suffix = "";
	if (highlight !== undefined && highlight !== false)
	{
		prefix = "<em>";
						
Read more ...

suffix = "</em>&nbsp;"; } var out = "<li>" + prefix + this.name; if (this.lastName !== undefined) out += " " + this.lastName; out += suffix + " is " + this.age + " years old</li>"; this.hasBeenDisplayed = true; $("#output").append(out); }; // Function shared among instances Person.prototype.displayIfNotAlreadyDisplayed = function() { if (this.hasBeenDisplayed !== true) { this.display(true); // Call to another shared function in Person from this shared function $("#birthdayMessages").append(this.birthdayText + "<em>" + this.name + ((this.lastName !== undefined) ? " " + this.lastName : "") + "</em>"); } }; /* INCLUDE THIS IN OTHER FILES WHERE NEEDED // Loop through all instances of this class for (var i=Person.prototype.listOfInstances.length; i--;) Person.prototype.listOfInstances[i].display(); */

... Read less

test_class_birthdays.php

A demo of the JavaScript class type framework.

http://www.glgibson.com.au/examples/index.php/welcome/view/test_class_birthdays
<h2>Test - Class - birthdays</h2>  

<script src="<?php echo base_url(); ?>/JavaScript/class.js?<?php echo GLG_VERSION; ?>"></script><!-- CLASS TEST JAVASCRIPT -->

<div><ul id="output"></ul></div>
<div id="birthdayMessages"></div>

<script>
	var peter = new Person("Peter");
	var anne = new Person("Anne");
	var sam = new Person("Sam");
	var john = new Person("John");
	
	anne.age = 25;
	sam.age = 35;
	
	anne.lastName = "Sutherland";
	sam.lastName = "McDonnell";
	
	// Display people who do not have a birthday today 
	peter.display();
	sam.display();
	
	// Display anyone missed - with a birthday message
	for (var i=Person.prototype.listOfInstances.length; i--;)
		Person.prototype.listOfInstances[i].displayIfNotAlreadyDisplayed();
</script>

snippet_namespace.js

A pattern for creating a namespace with private and public functions and variables.

(function(myNameSpace)
	{
		myNameSpace.name = "Dean."; // PUBLIC
		var privateGreetingsSaid = false; // PRIVATE
		
		//PUBLIC
		myNameSpace.displayName = function()
		{
			if (privateGreetingsSaid === false)
			{
				privateFunction("I am "+ myNameSpace.name);
				privateGreetingsSaid = true;
			}
			else
			{
				privateFunction("Haven't we already met?");
			}
		};

		// PRIVATE
		function privateFunction(message)
		{
			console.log(message);
		}

	}(window.myNameSpace = window.myNameSpace || {})
);

// Add another function to the namespace
						
Read more ...

(function(myNameSpace) { var privateGreetingMessage = "Hello"; // PRIVATE // PUBLIC myNameSpace.introduce = function() { console.log(privateGreetingMessage); myNameSpace.displayName(); }; }(window.myNameSpace = window.myNameSpace || {}) ); console.log(myNameSpace); myNameSpace.introduce(); myNameSpace.displayName();

... Read less

geolocation.js

A Google map interface showing your current location and public transport routes.

http://www.glgibson.com.au/examples/index.php/welcome/view/map
function getLocation()
{
	if (navigator.geolocation)
	{
		navigator.geolocation.getCurrentPosition(showPosition, showError);
	}
	else
	{
		GLGpopup("defalut info", "Geolocation is not supported by your browser", 0, 0, "ok");
	}
}

function showPosition(position)
{
	lat = position.coords.latitude;
	lon = position.coords.longitude;
	latlon = new google.maps.LatLng(lat, lon);
	mapholder = document.getElementById('mapholder');
	mapholder.style.height = '400px';
	mapholder.style.width = '90%';

	var myOptions =
	{
		center : latlon,
		zoom : 15,
		mapTypeIds : [google.maps.MapTypeId.ROADMAP, 'roadatlas'],
		mapTypeControl : true,
		panControl : true,
		zoomControl : true,
						
Read more ...

scaleControl : true, navigationControlOptions : { style : google.maps.NavigationControlStyle.SMALL } }; var map = new google.maps.Map(document.getElementById("mapholder"), myOptions); var roadAtlasStyles = [ { featureType : 'road.highway', elementType : 'geometry', stylers : [ { hue : '#ff0022' }, { saturation : 60 }, { lightness : -20 }] }, { featureType : 'road.arterial', elementType : 'all', stylers : [ { hue : '#2200ff' }, { lightness : -40 }, { visibility : 'simplified' }, { saturation : 30 }] }, { featureType : 'road.local', elementType : 'all', stylers : [ { hue : '#f6ff00' }, { saturation : 50 }, { gamma : 0.7 }, { visibility : 'simplified' }] }, { featureType : 'water', elementType : 'geometry', stylers : [ { saturation : 40 }, { lightness : 40 }] }, { featureType : 'road.highway', elementType : 'labels', stylers : [ { visibility : 'on' }, { saturation : 98 }] }, { featureType : 'administrative.locality', elementType : 'labels', stylers : [ { hue : '#0022ff' }, { saturation : 50 }, { lightness : -10 }, { gamma : 0.90 }] }, { featureType : 'transit.line', elementType : 'geometry', stylers : [ { hue : '#ff0000' }, { visibility : 'on' }, { lightness : -70 }] }]; var styledMapOptions = { name : 'Road Atlas' }; var roadMapType = new google.maps.StyledMapType(roadAtlasStyles, styledMapOptions); map.mapTypes.set('roadatlas', roadMapType); map.setMapTypeId('roadatlas'); var marker = new google.maps.Marker( { position : latlon, map : map, title : "Your current location" }); } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: GLGpopup("defalut info", "User denied the request for Geolocation", 0, 0, "ok"); break; case error.POSITION_UNAVAILABLE: GLGpopup("defalut info", "Location information is unavailable", 0, 0, "ok"); break; case error.TIMEOUT: GLGpopup("defalut info", "The request to get the user location timed out", 0, 0, "ok"); break; case error.UNKNOWN_ERROR: GLGpopup("defalut info", "An unknown error occurred", 0, 0, "ok"); break; } }

... Read less

GLGpopup.js

An interactive pop up alert box with image viewer.

http://www.glgibson.com.au/ebay.php
(click on an ebay add thumbnail to activate the pop-up)
/*
	(c) Copyright 2014 G L Gibson - Graham Gibson
*/

/* 
 *An interative popup box that stays centered on the screen.
 * Can be used as an image viewer or a replacement for alert and confirm boxes. 
 * */

GLGpopupIsInManualProcessDestroyMode = false;

/*
 * Open a popup box.
 * Pass the image to show (or null) and the text to display at the bottom.
 * If no text is passed, then it will attempt to display the title meta-data from jpg and gif images.  
 * 
 * Pass buttons as a string containing required buttons:
 * "full screen ok cancel"
 * i.e.
 *  onclick='GLGpopup("http://www.pictures.com/cup.jpg", "A cup", 600, 480, "full screen");'
 * or..
 * onclick='GLGpopup("imageBrowser/question.png", "Please answer all questions", 200, 200, "ok");'
 * 
 * NOTE: passing "defalut question" as the image will display the GLGpopup default question image
 * and passing "defalut info" will display the GLGpopup default info image.
 * 
 * CALLBACKS
 * Create a new function first (which will be destroyed after it has been called) then call GLGpopup.
 * processKEYPRESS, processOK, processCANCEL, processCLOSED and processFULLSCREEN
						
Read more ...

* i.e. processKEYPRESS = processOK = function() { // Called when user presses a key or clicks the OK button document.getElementById("myForm").submit(); } processCANCEL = processCLOSED = function() { // Called when user clicks the CANCEL button or closes the pop-up box document.getElementById("myFormLocationField").focus(); } GLGpopup("defalut question", "Ready to submit form?", 0, 0, "ok cancel"); * * */ function GLGpopup(imageToShow, textToDisplay, popupWidth, popupHeight, buttons, processLevel) { if (!processLevel || processLevel == null || typeof processLevel == 'undefined') processLevel = ""; if ( !imageToShow || imageToShow == null) imageToShow = ""; else if (imageToShow === "defalut question") { imageToShow = "http://www.glgibson.com.au/101/question400.png"; popupWidth = 200; popupHeight = 200; if (ieVersion > -1 && ieVersion < 9) { // smaller question image for IE8 and below as it cannot resize imageToShow = "http://www.glgibson.com.au/101/question200.png"; popupWidth = 100; popupHeight = 100; } } else if (imageToShow === "defalut info") { imageToShow = "http://www.glgibson.com.au/101/dialog-information400.png"; popupWidth = 200; popupHeight = 200; if (ieVersion > -1 && ieVersion < 9) { // smaller question image for IE8 and below as it cannot resize imageToShow = "http://www.glgibson.com.au/101/dialog-information200.png"; popupWidth = 100; popupHeight = 100; } } var popupDiv = document.getElementById("imageViewerPopup"); var popupDivOuter = document.getElementById("imageViewerPopupOuter"); var popupTextDiv = document.getElementById("popupText"); if (popupDivOuter && popupDivOuter != null && popupDiv && popupDiv != null) { // Grab the window scroll position before freezing the scroll var pageScrollOffset = new getPageScrollOffset(); disableScrolling(); popupDiv.style.backgroundImage = "url('"+imageToShow+"')"; if (popupWidth == "" || Number(popupWidth) == 0) { viewportWidth = viewport().width-50; popupWidth = (viewportWidth < 400)? viewportWidth:400; } if (/^\d+$/.test(popupWidth)) popupWidth+="px"; if (/^\d+$/.test(popupHeight)) popupHeight+="px"; popupDiv.style.width = popupWidth; popupDiv.style.height = popupHeight; // Add text if (popupTextDiv && popupTextDiv != null) { popupTextDiv.style.display = "none"; popupTextDiv.innerHTML = ""; if (textToDisplay && textToDisplay != "") { textToDisplay = convertToHTML(textToDisplay); popupTextDiv.innerHTML = textToDisplay; popupTextDiv.style.display = "block"; } } // Add buttons if (buttons && buttons != "") { buttonFullScreen = contains(buttons, "full screen"); buttonOK = contains(buttons, "ok"); buttonCancel = contains(buttons, "cancel"); if (buttonOK || buttonCancel) { var okDiv = document.getElementById("OKbutton"); var cancelDiv = document.getElementById("CancelButton"); var okButtonIsSet = false; if (buttonOK && okDiv && okDiv != null) { if (!buttonCancel || !cancelDiv || cancelDiv == null) okDiv.style.marginLeft = "-16px"; else okDiv.style.marginLeft = "-80px"; okButtonIsSet = true; okDiv.style.visibility = "visible"; } if (buttonCancel && cancelDiv && cancelDiv != null) { if (!okButtonIsSet) cancelDiv.style.marginLeft = "-16px"; else cancelDiv.style.marginLeft = "48px"; cancelDiv.style.visibility = "visible"; } } if (buttonFullScreen) { var fullDiv = document.getElementById("fullScreenImageViewer"); if (fullDiv && fullDiv != null) { fullDiv.style.visibility = "visible"; } processFULLSCREEN = function(){window.open(imageToShow, '_blank');}; } } resizeAndCenterPopup(popupDivOuter, popupDiv, pageScrollOffset); showThis('fog'); showThis('imageViewerPopupOuter'); popupDivOuter.focus(); document.onkeypress=function(){hidePopUp('keypress'); return false;}; } } /* * Call automatically by GLGpopup to center and resize the popup box * */ function resizeAndCenterPopup(popupDivOuter, popupDiv, pageScrollOffset) { if (!pageScrollOffset || pageScrollOffset == null) pageScrollOffset = new getPageScrollOffset(); viewportWidth = viewport().width-70; popupDivWidth = Number((popupDiv.style.width).replace("px","")); popupDivHeight = Number((popupDiv.style.height).replace("px","")); popupDivOuter.style.maxwidth = popupDivWidth +"px"; // Capture the width to height ratio before any resizing of the width popupDivHeightRatio = 0; if (popupDivWidth > 0) popupDivHeightRatio = popupDivHeight / popupDivWidth; popupDivWidthRatio = 0; if (popupDivHeight > 0) popupDivWidthRatio = popupDivWidth / popupDivHeight; // Make sure the width does not exceed the current viewport if (popupDivWidth > viewportWidth) popupDivWidth = viewportWidth; popupDivOuter.style.width = popupDivWidth +"px"; // Calculate the gap needed for any text popupMarginBottom = 0; var popupTextDiv = document.getElementById("popupText"); if (popupTextDiv && popupTextDiv != null && popupTextDiv.offsetHeight > 0) { popupTextDiv.style.width = Number((popupDivOuter.style.width).replace("px","")) - 20+"px"; popupMarginBottom = popupTextDiv.offsetHeight + 10; } popupDivOuter.style.maxheight = popupDivHeight + popupMarginBottom +"px"; // set the height to the correct ratio popupDivOuter.style.height = (popupDivWidth * popupDivHeightRatio + popupMarginBottom) +"px"; popupDiv.style.height = (popupDivWidth * popupDivHeightRatio) +"px"; //Now re-adjust if too high for the screen viewportHeight = viewport().height-50; if (Number((popupDivOuter.style.height).replace("px","")) > viewportHeight) { popupDivOuter.style.height = viewportHeight+"px"; popupDivOuter.style.width = popupDivWidthRatio * Number((popupDivOuter.style.height).replace("px","")) +"px"; if (popupTextDiv && popupTextDiv != null && popupTextDiv.offsetHeight > 0) { popupTextDiv.style.width = Number((popupDivOuter.style.width).replace("px","")) - 20+"px"; popupMarginBottom = popupTextDiv.offsetHeight + 10; } popupDiv.style.height = Number((popupDivOuter.style.height).replace("px","")) - popupMarginBottom +"px"; popupDiv.style.width = popupDivWidthRatio * Number((popupDiv.style.height).replace("px","")) +"px"; } /* Centre the popup by adjusting its margins (the popup top,left corner is in the centre of the screen - set by CSS). Idea from Chris Coyier: http://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/ */ popupDivOuter.style.marginLeft = (Number((popupDivOuter.style.width).replace("px",""))/2*-1) + pageScrollOffset.x + "px"; popupDivOuter.style.marginTop = (Number((popupDivOuter.style.height).replace("px",""))/2*-1) + pageScrollOffset.y + "px"; // END centre the popup /* Make it fluid by converting everything to percentages */ /* scaledWidth = Number((popupDivOuter.style.width).replace("px","")); scaledHeight = Number((popupDivOuter.style.height).replace("px","")) if (viewport().width > 0 && viewport().height > 0 && scaledWidth > 0 && scaledHeight > 0) { popupDivOuter.style.width = scaledWidth / viewport().width * 100 +"%"; popupDivOuter.style.height = scaledHeight / viewport().height * 100 +"%"; popupDivOuter.style.marginLeft = Number((popupDivOuter.style.marginLeft).replace("px","")) / scaledWidth * 50 +"%"; popupDivOuter.style.marginTop = Number((popupDivOuter.style.marginTop).replace("px","")) / scaledHeight * 50 +"%"; } */ } /* * Called automatically when the user closesd the popup (from GLGpopup). * Will call the appropriate function depending on which button was clicked on. * Create a new function first (which will be destroyed after it has been called) then call GLGpopup. * */ function hidePopUp(buttonPressed) { enableScrolling(); document.onkeypress = null; hideThis('imageViewerPopupOuter'); hideThis('fullScreenImageViewer'); hideThis('OKbutton'); hideThis('CancelButton'); hideThis('fog'); /* Process our call-back function if they are defined */ if (buttonPressed && buttonPressed != "") { if (buttonPressed == "keypress" && typeof processKEYPRESS == 'function') processKEYPRESS(); else if (buttonPressed == "ok" && typeof processOK == 'function') processOK(); else if (buttonPressed == "cancel" && typeof processCANCEL == 'function') processCANCEL(); else if (buttonPressed == "closed" && typeof processCLOSED == 'function') processCLOSED(); else if (buttonPressed == "full screen" && typeof processFULLSCREEN == 'function') processFULLSCREEN(); } /* Destroy all call-back functions */ if (!GLGpopupIsInManualProcessDestroyMode) destroyAllProcesses(); } /* * Destroys all processes * */ function destroyAllProcesses() { processKEYPRESS = undefined; processOK = undefined; processCANCEL = undefined; processCLOSED = undefined; processFULLSCREEN = undefined; } function GLGpopupManualMode(on) { GLGpopupIsInManualProcessDestroyMode = (on)? true:false; } /* * Initialises with the current scroll offset of the screen. * Stores the offsets in x and y. * */ function getPageScrollOffset() { this.x = 0; this.y = 0; if (window.pageYOffset || window.pageXOffset) { this.y = window.pageYOffset; this.x = window.pageXOffset; } else if (document.documentElement.scrollTop || document.documentElement.scrollLeft) { this.y = document.documentElement.scrollTop; this.x = document.documentElement.scrollLeft; } else if (document.body.scrollTop || document.body.scrollLeft) { this.y = document.body.scrollTop; this.x = document.body.scrollLeft; } }; function toggleDisplay(id) { var folderToToggle = document.getElementById(id); if (folderToToggle && folderToToggle != null) { if(folderToToggle.style.display == 'block') folderToToggle.style.display = 'none'; else folderToToggle.style.display = 'block'; } } function showThis(id) { var folderToToggle = document.getElementById(id); if (folderToToggle && folderToToggle != null) { folderToToggle.style.visibility = 'visible'; } } function hideThis(id) { var folderToToggle = document.getElementById(id); if (folderToToggle && folderToToggle != null) { folderToToggle.style.visibility = 'hidden'; } } /* * Converts text formatting for the alert-box text: * \n = line break * ~n = line break * ~l = left aligned section * ~r = right aligned section * ~/ = end aligned section (returns to center aligned) * */ function convertToHTML(text) { if (text && text != "") { text = text .split("\n").join("<br>") .split("~n").join("<br>") .split("~l").join("<div class='left'>") .split("~r").join("<div class='right'>") .split("~/").join("</div>"); } return text; } function contains(str, search) { if (str.match(search+"+")==search) return true; return false; } /* * Viewport code downloaded from Bryan Price on an article by: * Langton, Andy . 2007. "Get viewport/window size (width and height) with javascript". Andy Langton. http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript */ function viewport() { var e = window, a = 'inner'; if ( !( 'innerWidth' in window ) ) { a = 'client'; e = document.documentElement || document.body; } return {width : e[ a+'Width' ] , height : e[ a+'Height' ]}; } /* END code from bryan Price */ /* * Stop scrolling code adapted from: * Hallodom and MusikAnimal. 2011. "How to disable scrolling temporarily?". Stackoverflow. * http://stackoverflow.com/questions/4770025/how-to-disable-scrolling-temporarily. */ function disableScrolling() { bodyTag = (document.getElementsByTagName("body")[0]); if (bodyTag && bodyTag != null) { bodyTag.style.overflow = "hidden"; if (bodyTag.addEventListener) bodyTag.addEventListener("touchmove", stopScrollingTouchscreen, false); } } function enableScrolling() { bodyTag = (document.getElementsByTagName("body")[0]); if (bodyTag && bodyTag != null) { bodyTag.style.overflow = "visible"; if (bodyTag.addEventListener) bodyTag.removeEventListener("touchmove", stopScrollingTouchscreen); } } function stopScrollingTouchscreen(e) { e.preventDefault(); } /* END code from Hallodom and MusikAnimal*/ /* Code to detect version of IE adapted from Mkyong. 2009. "How To Detect IE Version Using JavaScript". Mkyong.com. * http://www.mkyong.com/javascript/how-to-detect-ie-version-using-javascript/ * * NOTE: I have converted the code to store the value in a global variable to save calling the function everytime. * */ var ieVersion = -1; if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) ieVersion = parseFloat( RegExp.$1 ); } /* END code adapted from Mkyong */

... Read less

formValidation.js

Client side form validation.

http://www.glgibson.com.au/contact.php
	function trimMe(str) 
	{
		if (str == null)
			return str;
		str = str.replace(/^\s+/, '');
		for (var i = str.length - 1; i >= 0; i--) 
		{
			if (/\S/.test(str.charAt(i))) 
			{
				str = str.substring(0, i + 1);
				break;
			}
		}
		return str;
	}
	
	
	
	function getFormElement( $form, $id )
	{
		return document.getElementById($id);
	}

	function processEnter()
	{
		 if (!document.activeElement || document.activeElement.tagName != "TEXTAREA")
		{
			validateContactForm(); // submit form if visitor presses enter *except in the question box*
		}
						
Read more ...

} function displayMessageAtTop(messageToDisplay) { var feedbackDiv = document.getElementById("feedbackFromJavascript"); if (feedbackDiv && feedbackDiv != null) feedbackDiv.innerHTML = messageToDisplay; } /* Validate email code adapted from W3Schools. http://www.w3schools.com/js/js_form_validation.asp */ function validateEmail(emailAddy) { ret = false; if (typeof emailAddy == 'string') { var positionOfAt = emailAddy.indexOf("@"); var positionOfDot = emailAddy.lastIndexOf("."); if (positionOfAt > 0 && positionOfDot > positionOfAt+2 && emailAddy.length > positionOfDot+2) { ret = true; } } return ret; } /* END validate email */ function validateContactForm() { $error = ""; bullet = "<img src='images/bullet.gif' width=12 height=12 alt='*'>"; questionImage = "images/question400.png"; questionWidth = 200; questionHeight = 200; if (ieVersion > -1 && ieVersion < 9) { // smaller question image for IE8 and below as it cannot resize questionImage = "images/question200.png"; questionWidth = 100; questionHeight = 100; } /* Reset fields background colour */ getFormElement("contactForm", "contactName").style.backgroundColor = "#CDD6D5"; getFormElement("contactForm", "email").style.backgroundColor = "#CDD6D5"; getFormElement("contactForm", "phone").style.backgroundColor = "#CDD6D5"; getFormElement("contactForm", "question").style.backgroundColor = "#CDD6D5"; if ( trimMe(getFormElement("contactForm", "contactName").value) === "") { $error+= "\n~l"+bullet+" Please fill in your name~l"; getFormElement("contactForm", "contactName").style.backgroundColor = "#C78184"; } emailAddy = trimMe(getFormElement("contactForm", "email").value); if (emailAddy === "" && trimMe(getFormElement("contactForm", "phone").value) === "") { $error+= "\n~l"+bullet+" Please supply contact details~l"; getFormElement("contactForm", "email").style.backgroundColor = "#C78184"; getFormElement("contactForm", "phone").style.backgroundColor = "#C78184"; } if (emailAddy != "" && !validateEmail(emailAddy)) { $error+= "\n~l"+bullet+" Please supply a valid email address~l"; getFormElement("contactForm", "email").style.backgroundColor = "#C78184"; } if ( trimMe(getFormElement("contactForm", "question").value) === "") { $error+= "\n~l"+bullet+" Please fill in the question box with your query~l"; getFormElement("contactForm", "question").style.backgroundColor = "#C78184"; } if ($error != "") { GLGpopup(questionImage, "Errors found:"+$error, questionWidth, questionHeight, "ok"); } else { processOK = function() { displayMessageAtTop("Submitting"); document.contactForm.submit(); }; processCANCEL = processCLOSED = function() { displayMessageAtTop("Canceled - form has <em>not</em> been submitted."); }; GLGpopup(questionImage, "Ready to submit form?", questionWidth, questionHeight, "ok cancel hide close"); } return false; }

... Read less

themeChanger.js

Dynamically change a page theme.

http://www.pallettracker.com.au/PT%20manual/
/* 
Pallet Tracker interactive manual

DIG252 - Internet Design - Interactivity, Curtin SP2 2013
Tutor: Tegan Hooper

(c) Copyright 2013 Graham Gibson
Curtin student ID: 14023800
*/

// JQuery needs to be loaded first.

var themeName = new Array();
var themeThumbnail = new Array();
var themeHyperlink = new Array();
var themeThumbnailSize = " width='90' height='75' ";

themeName.push("Default");		themeThumbnail.push("images/themes/PTdefault.png");		themeHyperlink.push("css/myThemes/PTdefault.css");
themeName.push("Blue");				themeThumbnail.push("images/themes/Blue.png");				themeHyperlink.push("css/myThemes/Blue.css");
themeName.push("Grey");				themeThumbnail.push("images/themes/Grey.png");				themeHyperlink.push("css/myThemes/Grey.css");
themeName.push("Green");			themeThumbnail.push("images/themes/Green.png");				themeHyperlink.push("css/myThemes/Green.css");
themeName.push("Red");				themeThumbnail.push("images/themes/Red.png");					themeHyperlink.push("css/myThemes/Red.css");



/**
 * Called once the page loads.
 */
function drawThemeChanger()
						
Read more ...

{ // Add the theme changer only if the theme changer window exists. if ($('#themeChanger').length) { var themeWindow = $('#themeChanger'); themeWindow.append("<div id='themeChangerInner'></div>"); var themeInnerWindow = $('#themeChangerInner'); for ( var nextThemeItem=0; nextThemeItem<themeName.length; nextThemeItem++) { var nextThumb = "<img src='" + themeThumbnail[nextThemeItem] + "'"; nextThumb += themeThumbnailSize + "id='themeThumbImage"+nextThemeItem+"' class='themeThumbnail' alt='"+themeName[nextThemeItem]+"' "; nextThumb += "onclick='changeTheme("+nextThemeItem+")'><br>"; themeInnerWindow.append("<span class='themeThumb'>" + nextThumb + "<span class='caption'>"+themeName[nextThemeItem]+"</span></span>"); } highlightCurrentThemeThumb(); // Add a slide handle to close. themeWindow.append("<div id='themeHandleToClose' onclick='hideThemeChanger()'><\div>"); // Add a slide handle to open. $("body").append("<div id='themeChangerClosed' onclick='showThemeChanger()'><\div>"); // Now make the theme changer section visible $("#themeChangerClosed").css({"display" : "block"}); $("#themeChanger").css({"display" : "block"}); $("#themeChangerClosed").hide(); themeWindow.hide(); showThemeChangerButton(); } } /* Showing and hiding the theme changer anaimations. */ function showThemeChanger() { hideThemeChangerButton(); } function showThemeChangerCallback() { $("#themeChanger").show("slide", {direction: "right", easing: easeOutSlide, duration: 2000}); } function hideThemeChanger() { $("#themeChanger").hide("slide", {direction: "right", easing: easeOutSlide, duration: 2000}, showThemeChangerButton); } function showThemeChangerButton() { $("#themeChangerClosed").show("slide", {direction: "right", duration: 400}); $(".mainContent").animate({"margin-top" : "55px"}, 400); } function hideThemeChangerButton() { $("#themeChangerClosed").css({"background-color" : "transparent"}); setCookie("hideIndicator-themeChanger", true); $("#themeChangerClosed").hide("slide", {direction: "right", duration: 200}, showThemeChangerCallback); $(".mainContent").animate({"margin-top" : "96px"}, 400); } /* END - Showing and hiding the theme changer anaimations. */ /** * Highlights the currently selected theme. */ function highlightCurrentThemeThumb() { if ($('#themeChanger').length) { var currentTheme = getCookie("currentTheme"); if (currentTheme == null) currentTheme = 1; for ( var nextThemeItem=0; nextThemeItem<themeName.length; nextThemeItem++) { if(nextThemeItem == currentTheme) { $('#themeThumbImage'+nextThemeItem).addClass('themeSelectedImage'); } else { $('#themeThumbImage'+nextThemeItem).removeClass('themeSelectedImage'); } } } } /** * On the fly theme changer. */ function changeTheme(themeNumber) { if (themeNumber != null) { try { var themeFile=document.createElement("link"); themeFile.setAttribute("rel", "stylesheet"); themeFile.setAttribute("type", "text/css"); themeFile.setAttribute("href", themeHyperlink[themeNumber]); document.getElementsByTagName("head")[0].appendChild(themeFile); // Save as current theme only if successful. setCookie("currentTheme", ""+themeNumber); highlightCurrentThemeThumb(); } catch(err){} } /* Update the tab and interactive indicators' colours after a slight delay (to allow the CSS to fully load) */ setTimeout(setTabColours, 500); setTimeout(highlightInteractiveIndicators, 600); }

... Read less

PalletTrackerSimulator.js

Simulates a database for inventory tracking in a warehouse.

http://www.pallettracker.com.au/PT%20manual/view.html
/* 
Pallet Tracker interactive manual

DIG252 - Internet Design - Interactivity, Curtin SP2 2013
Tutor: Tegan Hooper

(c) Copyright 2013 Graham Gibson
Curtin student ID: 14023800
*/

/* Requires tools.js */

/* Used for debugging the database functions */
var showDatabaseWindow = false;

var lastLocation = getCookie("lastLocation");
if (lastLocation == null || lastLocation == "")
	lastLocation = "1A1";

var searchString = "robot";
var numberOfSearchResults = 0;
var numberOfLocationResults = 0;
var lastMessage = "";

var databaseLocation = new Array();
var databasePart = new Array();
var databaseQty = new Array();
var databaseDate = new Array();
var databaseComment = new Array();
						
Read more ...

/* Database creation / loading / saving / resetting. **************************************************************************************************/ /* If there is no database saved then create a default one. */ function initDatabase() { databaseLocation.push("1A1"); databasePart.push("Robot v1"); databaseQty.push("1"); databaseDate.push("19/7/2013"); databaseComment.push(""); databaseLocation.push("1A1"); databasePart.push("Droid"); databaseQty.push("1"); databaseDate.push("19/7/2013"); databaseComment.push(""); databaseLocation.push("1A1"); databasePart.push("Droid v3"); databaseQty.push("1"); databaseDate.push("19/7/2013"); databaseComment.push(""); databaseLocation.push("1A1"); databasePart.push("Hover platform"); databaseQty.push("2"); databaseDate.push("19/7/2013"); databaseComment.push("Suitable for all droids"); databaseLocation.push("1A2"); databasePart.push("Robot v2"); databaseQty.push("10"); databaseDate.push("19/7/2013"); databaseComment.push(""); databaseLocation.push("1A3"); databasePart.push("Robot v3"); databaseQty.push("1"); databaseDate.push("19/7/2013"); databaseComment.push("Prototype"); databaseLocation.push("1B1"); databasePart.push("Droid"); databaseQty.push("20"); databaseDate.push("19/7/2013"); databaseComment.push(""); databaseLocation.push("1B2"); databasePart.push("Droid v2"); databaseQty.push("10"); databaseDate.push("19/7/2013"); databaseComment.push(""); databaseLocation.push("1B3"); databasePart.push("Droid v3"); databaseQty.push("2"); databaseDate.push("19/7/2013"); databaseComment.push(""); databaseLocation.push("1C1"); databasePart.push("Power unit"); databaseQty.push("100"); databaseDate.push("19/7/2013"); databaseComment.push("Universal"); databaseLocation.push("1C2"); databasePart.push("AI upgrade"); databaseQty.push("50"); databaseDate.push("19/7/2013"); databaseComment.push("Only works on v2 robots"); databaseLocation.push("1C3"); databasePart.push("Hover platform"); databaseQty.push("5"); databaseDate.push("19/7/2013"); databaseComment.push("Suitable for all droids"); databaseLocation.push("ARMOURY"); databasePart.push("Laser"); databaseQty.push("1"); databaseDate.push("20/7/2013"); databaseComment.push("High powered"); databaseLocation.push("ARMOURY"); databasePart.push("Target"); databaseQty.push("1"); databaseDate.push("20/7/2013"); databaseComment.push("Shoot me!"); databaseLocation.push("OUT DROID ORDER 19/7/2013"); databasePart.push("Droid v2"); databaseQty.push("1"); databaseDate.push("20/7/2013"); databaseComment.push(""); databaseLocation.push("OUT DROID ORDER 19/7/2013"); databasePart.push("Target"); databaseQty.push("1"); databaseDate.push("20/7/2013"); databaseComment.push("Shoot me!"); databaseLocation.push("OUT DROID ORDER 19/7/2013"); databasePart.push("Laser"); databaseQty.push("1"); databaseDate.push("20/7/2013"); databaseComment.push(""); databaseLocation.push("OUT DROID ORDER 19/7/2013"); databasePart.push("Hover pad"); databaseQty.push("1"); databaseDate.push("20/7/2013"); databaseComment.push(""); databaseLocation.push("PICK ROBOT ORDER 20/7/2013"); databasePart.push("Robot v2"); databaseQty.push("1"); databaseDate.push("20/7/2013"); databaseComment.push(""); databaseLocation.push("PICK ROBOT ORDER 20/7/2013"); databasePart.push("Target"); databaseQty.push("1"); databaseDate.push("20/7/2013"); databaseComment.push("Shoot me!"); databaseLocation.push("PICK ROBOT ORDER 20/7/2013"); databasePart.push("Laser"); databaseQty.push("1"); databaseDate.push("20/7/2013"); databaseComment.push(""); } /* Reset feature - resets the database to default and clears the form. */ function resetAllDatabaseWindows() { if (confirm("Reset the database?")) { lastLocation = "1A1"; setCookie("lastLocation", lastLocation); searchString = "robot"; numberOfSearchResults = 0; numberOfLocationResults = 0; lastMessage = ""; clearAllForms(); resetDatabase(); updateAllDatabaseWindows(); } } function clearAllForms() { clearAddPartForm(); clearMoveForm(); clearOverviewForm(); clearPalletForm(); clearSearchForm(); } function resetDatabase() { // clear the database. databaseLocation.length = 0; databasePart.length = 0; databaseQty.length = 0; databaseDate.length = 0; databaseComment.length = 0; // build a new database. initDatabase(); saveDatabase(); } /* Loads the database from cookies into an array. */ function loadDatabase() { var location = getCookie("PTdatabaseLocation"); if (location) { try { databaseLocation = location.split("|"); databasePart = getCookie("PTdatabasePart").split("|"); databaseQty = getCookie("PTdatabaseQty").split("|"); databaseDate = getCookie("PTdatabaseDate").split("|"); databaseComment = getCookie("PTdatabaseComment").split("|"); } catch(err) // Corrupt database - re-initialise it. { resetDatabase(); } } else // No database found - initialise one. { resetDatabase(); } } /* Saves the database array into cookies. */ function saveDatabase() { setCookie("PTdatabaseLocation", databaseLocation.join("|")); setCookie("PTdatabasePart", databasePart.join("|")); setCookie("PTdatabaseQty", databaseQty.join("|")); setCookie("PTdatabaseDate", databaseDate.join("|")); setCookie("PTdatabaseComment", databaseComment.join("|")); } /* Updates all the Pallet Tracker Simulator windows as well as the database contents window. * Call whenever the database is created or altered. */ function updateAllDatabaseWindows() { updateDatabaseContentsWindow(); updateAddPartWindow(); updateMoveWindow(); updateOverviewWindow(); updatePreviewWindows(); updateSearchWindow(); } /* Database contents window FOR DEBUGGING. **************************************************************************************************/ /* Displays the entire database contents on all control and view pages for demonstration. */ function displayDatabase() { if (showDatabaseWindow && $('#contentSection').length) { $("#contentSection").append("<div class='textBoxBorder'><h3>Database contents</h3><div class='textSection' id='displayDatabaseDiv'></div></div>"); } } /* Delete and redraw the database window. */ function updateDatabaseContentsWindow() { if (showDatabaseWindow && $('#displayDatabaseDiv').length) { $('#displayDatabaseDivInner').remove(); $('#displayDatabaseDiv').append("<div class='textSection' id='displayDatabaseDivInner'></div>"); var databaseWindow = $('#displayDatabaseDivInner'); if (lastMessage != "") databaseWindow.append("<p class='message'>Message: "+lastMessage+"</p>"); databaseWindow.append("<div class='tableDivLeft' id='PTdisplayDatabase'>"); databaseWindow.append("<div class='tableColumn'></div><div class='tableColumn'></div>"); databaseWindow.append("<div class='tableColumn'></div><div class='tableColumn'></div><div class='tableColumn'></div>"); databaseWindow.append("<div class='tableRow'>"); databaseWindow.append("<div class='tableCellLeft'><b>Location</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Part</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Qty</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Date</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Comment</b></div>"); databaseWindow.append("</div>"); for ( var nextDatabseItem=0; nextDatabseItem<databaseLocation.length; nextDatabseItem++) { databaseWindow.append("<div class='tableRow'>"); databaseWindow.append("<div class='tableCellLeft'>"+databaseLocation[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databasePart[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseQty[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseDate[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseComment[nextDatabseItem]+"</div>"); databaseWindow.append("</div>"); } databaseWindow.append("</div>"); // tableDivLeft } } /* Add part window **************************************************************************************************/ function updateAddPartWindow() { clearAddPartForm(); } /* Clears the form after adding parts or resetting the database. */ function clearAddPartForm() { if ($("#PT-addpart-location").length) { document.getElementById("PT-addpart-location").value = lastLocation; document.getElementById("PT-addpart-part").value = ""; document.getElementById("PT-addpart-quantity").value = ""; document.getElementById("PT-addpart-date").value = ""; document.getElementById("PT-addpart-comment").value = ""; } } /* Adds a part into the database array and saves the array as cookies. */ function addPart() { var error = ""; // Get the values and replace all "|" with a "/" (the "|" is used as the split separator), then trim the result. var addPart_location = ($.trim( (document.getElementById("PT-addpart-location").value).replace("|","/") )).toUpperCase(); var addPart_part = $.trim( (document.getElementById("PT-addpart-part").value).replace("|","/") ); var addPart_qty =$.trim( (document.getElementById("PT-addpart-quantity").value).replace("|","/") ); var addPart_date = $.trim( (document.getElementById("PT-addpart-date").value).replace("|","/") ); var addPart_comment = $.trim( (document.getElementById("PT-addpart-comment").value).replace("|","/") ); if (addPart_location == "") { error +="\nCannot leave the location blank."; } if (addPart_part == "" && addPart_comment == "") { error +="\nCannot leave both the part and comment blank."; } if (addPart_date == "") { var today = new Date(); addPart_date = today.getDate() + "/"+ (today.getMonth()+1) + "/"+ today.getFullYear(); } if (error == "") // No problems, OK to add the part. { // Add the part into the database. databaseLocation.push(addPart_location); databasePart.push(addPart_part); databaseQty.push(addPart_qty); databaseDate.push(addPart_date); databaseComment.push(addPart_comment); lastLocation = addPart_location; setCookie("lastLocation", lastLocation); clearAddPartForm(); saveDatabase(); lastMessage = "Added "+addPart_part+" to location "+addPart_location; updateAllDatabaseWindows(); } else // Report validation errors. { alert("Error:\n \n"+ error); } // Reset the indicator and save the cookie so it does not highlight again. setCookie("hideIndicator-sim", true); $(".indicatorInstruction").css({"background" : ""}); } /* Move part window. **************************************************************************************************/ function updateMoveWindow() { } function clearMoveForm() { if ($("#PT-move-move").length) { document.getElementById("PT-move-move").value = ""; } } function moveTo(moveToElementId) { if ($('#'+moveToElementId).length) { var moveToLocation = ($.trim( (document.getElementById(moveToElementId).value) ).toUpperCase()); if (moveToLocation != "") { var nextCheckID=0; var quit = false; while (!quit) { nextCheckID++; var nextIDname = moveToElementId+"-checkbox-"+nextCheckID; if ($("#"+nextIDname).length) { if (document.getElementById(nextIDname).checked) databaseLocation[(document.getElementById(nextIDname).value)] = moveToLocation; } else quit = true; } lastMessage = "Moved selection to location "+moveToLocation; document.getElementById(moveToElementId).value = ""; saveDatabase(); updateAllDatabaseWindows(); } else { alert("The move to location cannot be blank"); } } // Reset the indicator and save the cookie so it does not highlight again. setCookie("hideIndicator-sim", true); $(".indicatorInstruction").css({"background" : ""}); } /* Preview windows (pallet and overview). **************************************************************************************************/ function updatePreviewWindow(previewWindowID, location, showCheckboxes) { if ($('#'+previewWindowID).length) { $('#'+previewWindowID+'_Inner').remove(); $('#'+previewWindowID).append("<div class='textSection' id='"+previewWindowID+"_Inner'></div>"); var databaseWindow = $('#'+previewWindowID+'_Inner'); databaseWindow.append("<h5>Location: "+ lastLocation+"</h5>"); databaseWindow.append("<div class='tableDivLeft' id='PTdisplayPallet'>"); if (showCheckboxes) databaseWindow.append("<div class='tableColumn'></div>"); databaseWindow.append("<div class='tableColumn'></div><div class='tableColumn'></div>"); databaseWindow.append("<div class='tableColumn'></div><div class='tableColumn'></div>"); databaseWindow.append("<div class='tableRow'>"); if (showCheckboxes) databaseWindow.append("<div class='tableCellLeft'></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Part</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Qty</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Date</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Comment</b></div>"); databaseWindow.append("</div>"); numberOfLocationResults = 0; for ( var nextDatabseItem=0; nextDatabseItem<databaseLocation.length; nextDatabseItem++) { if ( containsSearch(databaseLocation[nextDatabseItem], lastLocation) ) { numberOfLocationResults++; databaseWindow.append("<div class='tableRow'>"); if (showCheckboxes) databaseWindow.append("<div class='tableCellLeft'><input type='checkbox' id='PT-pallet-move-checkbox-"+numberOfLocationResults+"' value='"+nextDatabseItem+"'></div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databasePart[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseQty[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseDate[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseComment[nextDatabseItem]+"</div>"); databaseWindow.append("</div>"); } } if (numberOfLocationResults == 0) databaseWindow.append("</div><h5>EMPTY</h5>"); // tableDivLeft else databaseWindow.append("</div><h5>"+numberOfLocationResults+" part"+(numberOfLocationResults == 1? "":"s")+"</h5>"); //tableDivLeft } } function updatePreviewWindows(changeLastLocation) { if (changeLastLocation && changeLastLocation != "") { lastLocation = changeLastLocation; setCookie("lastLocation", lastLocation); } updatePreviewWindow("PT_pallet_window", lastLocation, true); updatePreviewWindow("PT_preview_window", lastLocation, false); } function updatePreviewWindowsAndDisableHilight(changeLastLocation) { // Reset the indicator and save the cookie so it does not highlight again. setCookie("hideIndicator-overview", true); $(".indicatorInstructionOverview").css({"background" : ""}); updatePreviewWindows(changeLastLocation); } /* Overview window. **************************************************************************************************/ function updateOverviewWindow() { if ($('#PT_overview_window').length) { $('#PT_overview_window_Inner').remove(); $('#PT_overview_window').append("<div class='textSection' id='PT_overview_window_Inner'></div>"); var databaseWindow = $('#PT_overview_window_Inner'); databaseWindow.append("<h6>Warehouse locations</h6>"); databaseWindow.append("<div class='tableDivLeft' id='PTdisplayOverview'>"); var numberOfRows = 2; var numberOfColumns = 6; var numberOfShelves = 3; var alfa=["0","A","B","C","D","E","F"]; var totalNumberOfLocations = numberOfRows * numberOfColumns * numberOfShelves; var countOccupiedLocations = 0; var warehouseLocations = new Array(); warehouseLocations.push("BIN"); // Draw up the warehouse locations in a pallet racking layout. for (var row = 1; row <=numberOfRows; row++) { databaseWindow.append("<div class='tableDivLeftPadded' id=''>"); for (var shelf = 1; shelf <=numberOfShelves; shelf++) { databaseWindow.append("<div class='tableColumn'></div>"); databaseWindow.append("<div class='tableRow'>"); for (var column = 1; column <=numberOfColumns; column++) { var nextLocation = row+""+alfa[column]+""+shelf; warehouseLocations.push(nextLocation); var nextColour = "tableCellEmptyLocation"; //if (databaseLocation.indexOf(nextLocation) >-1) -> indexOf does not work in IE8, use jQuery solution if ($.inArray(nextLocation, databaseLocation) > -1) { nextColour = "tableCellOccupiedLocation"; countOccupiedLocations++; } databaseWindow.append("<div class='"+nextColour+"' onclick='updatePreviewWindowsAndDisableHilight(\""+nextLocation+"\");'>"+nextLocation+"</div>"); } databaseWindow.append("</div>"); } databaseWindow.append("<div class='tableColumn'></div>"); } // Report the warehouse capacity. var numberOfEmptyLocations = totalNumberOfLocations - countOccupiedLocations; var tallyText = "<p><span class='occupiedLocation'>Occupied: "+countOccupiedLocations+"</span> / "; tallyText+= "<span class='emptyLocation'>Empty: "+numberOfEmptyLocations+"</span>"; if (numberOfEmptyLocations > 0 && countOccupiedLocations>0) tallyText+=" = "+Math.round((countOccupiedLocations/numberOfEmptyLocations)*100)+"% full"; tallyText+= "</p>"; databaseWindow.append(tallyText); // Now display the rest of the locations. databaseWindow.append("<h6>Other locations</h6>"); databaseWindow.append("<p class='indent'>"); for (var nextLocation = 0; nextLocation < databaseLocation.length; nextLocation++) { if ( !containsSearch(databaseLocation[nextLocation], "pick") && !containsSearch(databaseLocation[nextLocation], "out") //&& warehouseLocations.indexOf(databaseLocation[nextLocation]) == -1) -> indexOf does not work in IE8, use jQuery solution && ($.inArray(databaseLocation[nextLocation], warehouseLocations) == -1) ) { databaseWindow.append("<span class='indent' onclick='updatePreviewWindowsAndDisableHilight(\""+databaseLocation[nextLocation]+"\");'>"+databaseLocation[nextLocation]+"</span><br>"); warehouseLocations.push(databaseLocation[nextLocation]); } } databaseWindow.append("<p class='indent' onclick='updatePreviewWindowsAndDisableHilight(\"bin\");'>Recycle bin</p>"); databaseWindow.append("</p>"); // And the picking slips. databaseWindow.append("<h6>Picking slips</h6>"); databaseWindow.append("<p class='indent'>"); for (var nextLocation = 0; nextLocation < databaseLocation.length; nextLocation++) { if (containsSearch(databaseLocation[nextLocation], "pick") //&& warehouseLocations.indexOf(databaseLocation[nextLocation]) == -1) -> indexOf does not work in IE8, use jQuery solution && ($.inArray(databaseLocation[nextLocation], warehouseLocations) == -1) ) { databaseWindow.append("<span class='indent' onclick='updatePreviewWindowsAndDisableHilight(\""+databaseLocation[nextLocation]+"\");'>"+databaseLocation[nextLocation]+"</span><br>"); warehouseLocations.push(databaseLocation[nextLocation]); } } databaseWindow.append("</p>"); // And finally the out-going (in transit) orders. databaseWindow.append("<h6>In transit</h6>"); databaseWindow.append("<p class='indent'>"); for (var nextLocation = 0; nextLocation < databaseLocation.length; nextLocation++) { if (containsSearch(databaseLocation[nextLocation], "out") //&& warehouseLocations.indexOf(databaseLocation[nextLocation]) == -1) -> indexOf does not work in IE8, use jQuery solution && ($.inArray(databaseLocation[nextLocation], warehouseLocations) == -1) ) { databaseWindow.append("<span class='indent' onclick='updatePreviewWindowsAndDisableHilight(\""+databaseLocation[nextLocation]+"\");'>"+databaseLocation[nextLocation]+"</span><br>"); warehouseLocations.push(databaseLocation[nextLocation]); } } databaseWindow.append("</p>"); } } function clearOverviewForm() { } /* Pallet window. **************************************************************************************************/ function clearPalletForm() { if ($("#PT-pallet-move").length) { document.getElementById("PT-pallet-move").value = ""; } if ($("#PT-pallet-location").length) { document.getElementById("PT-pallet-location").value = ""; } } function viewPallet() { if ($("#PT-pallet-location").length) { lastLocation = $.trim( (document.getElementById("PT-pallet-location").value) ); setCookie("lastLocation", lastLocation); clearPalletForm(); updatePreviewWindows(); } // Reset the indicator and save the cookie so it does not highlight again. setCookie("hideIndicator-sim", true); $(".indicatorInstruction").css({"background" : ""}); } /* Search window. **************************************************************************************************/ function updateSearchWindow() { if ($('#PT_search_window').length) { $('#PT_search_window_Inner').remove(); $('#PT_search_window').append("<div class='textSection' id='PT_search_window_Inner'></div>"); var databaseWindow = $('#PT_search_window_Inner'); databaseWindow.append("<h5>Search results for: "+ searchString+"</h5>"); databaseWindow.append("<div class='tableDivLeft' id='PTdisplaySearch'>"); databaseWindow.append("<div class='tableColumn'></div><div class='tableColumn'></div><div class='tableColumn'></div>"); databaseWindow.append("<div class='tableColumn'></div><div class='tableColumn'></div><div class='tableColumn'></div>"); databaseWindow.append("<div class='tableRow'>"); databaseWindow.append("<div class='tableCellLeft'></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Location</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Part</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Qty</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Date</b></div>"); databaseWindow.append("<div class='tableCellLeftPadded'><b>Comment</b></div>"); databaseWindow.append("</div>"); numberOfSearchResults = 0; for ( var nextDatabseItem=0; nextDatabseItem<databaseLocation.length; nextDatabseItem++) { if ( containsSearch(databasePart[nextDatabseItem], searchString) || containsSearch(databaseComment[nextDatabseItem], searchString) ) { numberOfSearchResults++; databaseWindow.append("<div class='tableRow'>"); databaseWindow.append("<div class='tableCellLeft'><input type='checkbox' id='PT-search-move-checkbox-"+numberOfSearchResults+"' value='"+nextDatabseItem+"'></div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseLocation[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databasePart[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseQty[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseDate[nextDatabseItem]+"</div>"); databaseWindow.append("<div class='tableCellLeftPadded'>"+databaseComment[nextDatabseItem]+"</div>"); databaseWindow.append("</div>"); } } databaseWindow.append("</div><h5>"+numberOfSearchResults+" result"+(numberOfSearchResults == 1? "":"s")+"</h5>"); //tableDivLeft } } function clearSearchForm() { if ($("#PT-search-part").length) { document.getElementById("PT-search-part").value = ""; } if ($("#PT-search-move").length) { document.getElementById("PT-search-move").value = ""; } for ( var nextCheckID=1; nextCheckID<=numberOfSearchResults; nextCheckID++) { if ($("#PT-search-checkbox-"+nextCheckID).length) { document.getElementById("PT-search-checkbox-"+nextCheckID).checked = 0; } } } function searchFor() { if ($("#PT-search-part").length) { searchString = $.trim( (document.getElementById("PT-search-part").value) ); clearSearchForm(); updateSearchWindow(); } // Reset the indicator and save the cookie so it does not highlight again. setCookie("hideIndicator-sim", true); $(".indicatorInstruction").css({"background" : ""}); }

... Read less

buttons.css

A style sheet for modern flat buttons.

/*
CSS file for flat buttons - common to all devices

(c) Copyright 2014 G L Gibson - Graham Gibson
*/

/* Modern flat buttons */
.menuButton, .menuButtonSelected, 
.subMenuButton, .subMenuButtonSelected, 
.actionButton, .actionButtonArrow
{
	color: #144476;
	white-space: nowrap;
	text-decoration: none;
	font-weight: bold;
	border-radius: 5px;
	padding: 0.7em 2em;
	background-color: #bdc3c7;
	
	opacity: 0.8;
	filter: alpha(opacity=80);
	
	cursor: pointer;
}
 
.buttonGap
{
	margin: 2em;
}
						
Read more ...

.menuButton:hover, .subMenuButton:hover, .actionButton:hover, .actionButtonArrow:hover { background-color: #ADB6C2; } .menuButtonSelected, .subMenuButton, .subMenuButtonSelected { color: #924B23; background-color: #ADB6C2; } .actionButton, .actionButtonArrow { margin-top: 40px; /*color: #144476;*/ background-color: #bdc3c7; border: 3px solid #144476; } /* Text menu */ .menuButtonMobile, .menuButtonSelectedMobile, .subMenuButtonMobile, .subMenuButtonSelectedMobile { list-style-type: none; padding: 0; margin: 0; font-weight: bold; } .menuButtonSelectedMobile, .subMenuButtonSelectedMobile { list-style-type: none; padding: 0; margin: 0; color: #144476; font-weight: bold; } .subMenuButtonMobile, .subMenuButtonSelectedMobile { padding-left: 1em; } #menu, #menuSide, #submenu, #submenuSide { display: block; text-decoration: none; height: auto; overflow: hidden; } #menuSide { display: none; } #menu { position: absolute; top: 40px; left: auto; right: auto; width: 96%; overflow: visible; text-align: center; } #submenu { position: absolute; top: 100px; left: auto; right: auto; width: 96%; overflow: visible; text-align: center; } /* Add a fade effect on buttons and the logo to draw more attention to the main content area */ .menuButton, .subMenuButton, .actionButton, .actionButtonArrow, #logo, .footerSection { opacity: 0.6; filter: alpha(opacity=60); } .menuButtonSelected, .subMenuButtonSelected { opacity: 0.8; filter: alpha(opacity=80); } .menuButton:hover, .menuButtonSelected:hover, .subMenuButton:hover, .subMenuButtonSelected:hover, .actionButton:hover, #logo:hover, .footerSection:hover { opacity: 1.0; filter: alpha(opacity=100); } /* Add a transition effect */ .menuButton, .menuButtonSelected, .subMenuButton, .subMenuButtonSelected, .actionButton, .actionButtonArrow, #logo, .footerSection, .menuButton:hover, .menuButtonSelected:hover, .subMenuButton:hover, .subMenuButtonSelected:hover, .actionButton:hover, .actionButtonArrow:hover, #logo:hover, .footerSection:hover { -moz-transition: opacity 1s, background-color 1s, color 1s; -webkit-transition: opacity 1s, background-color 1s, color 1s; -o-transition: opacity 1s, background-color 1s, color 1s; transition: opacity 1s, background-color 1s, color 1s; }

... Read less

GLGpopup.css

A style sheet for a pop up alert box replacement.

/*
	(c) Copyright 2014 G L Gibson - Graham Gibson
*/

/* 
 * ...GLGpopup style sheet...
 * Opens an interative popup box that stays centered on the screen.
 * Can be used as an image viewer or a replacement for alert boxes. 
 * */

.imageSpan
{
	margin: 50px;
	border-bottom: 2px solid darkblue;
}

.imageBorder, .imageBorderClickable
{
	margin-bottom: 10px;
}

.imageBorderClickable
{
	box-shadow: 10px 10px 5px #888888;
}

.imageDiv, .clickMeForPopup, #hideImageViewer, #OKbutton, #CancelButton, #fullScreenImageViewer
{
	cursor: pointer;
						
Read more ...

} .imageDivInner { display: none; } #imageViewerPopupOuter { display: block; visibility: hidden; text-align: center; z-index: 110; width: 0; height: 0; position: absolute; top: 50%; left: 50%; margin-top: 0px; margin-left: 0px; border: 6px solid #0C2746; border-radius: 25px; border-bottom-left-radius: 0; border-top-right-radius: 0; box-shadow: 10px 10px 5px #888888; background: #BDC3C7; max-width: 100%; min-width: 200px; overflow: visible; } #imageViewerPopup { display: block; z-index: 120; position: relative; text-align: center; margin: 0 auto; width: 0; height: 0; background-image: none; background-repeat: no-repeat; background-position: center; max-width: 90%; background-size: contain; -webkit-background-size: contain; -moz-background-size: contain; -o-background-size: contain; } #popupText { display: none; z-index: 125; position: relative; color: black; overflow: hidden; text-align: center; margin: 0 auto; padding-top:10px; min-width: 180px; } #fullScreenImageViewer { position: absolute; background-image: url("Monitor.png"); z-index: 1000; width: 32px; height: 32px; top: -20px; right: 20px; visibility: hidden; } #hideImageViewer { position: absolute; background-image: url("Delete.png"); z-index: 1000; width: 32px; height: 32px; top: -20px; right: -20px; } #OKbutton { position: absolute; background-image: url("Apply.png"); z-index: 1000; width: 32px; height: 32px; bottom: -25px; left: 50%; visibility: hidden; } #CancelButton { position: absolute; background-image: url("Erase.png"); z-index: 1000; width: 32px; height: 32px; bottom: -25px; left: 50%; visibility: hidden; } #fog { display: block; visibility: hidden; width: 1000000px; /* oversized fog so it still works on browsers that do not support fixed positioning */ height: 1000000px; /* (i.e. the old Android stock browser that is on my mobile!) */ position: fixed; top: 0; left: 0; z-index: 100; background-color: #B8B8B8; opacity: 0.7; filter: alpha(opacity=70); } .imageNonClickable { } .imageClickable { cursor: pointer; } .imagePopup { box-shadow: 10px 10px 5px #888888; } .imageCaption { font-style: italic; font-weight: bold; color: darkblue; }

... Read less

calculator.html

A calculator that can be used as a stand alone or inserted into a page in an Ajax panel.

<!DOCTYPE html>

<head>
	
	<!--
	Calculator.
	(c) Copyright 2014 G L Gibson - Graham Gibson
	-->

	<title>
		G L Gibson -  Calculator plug in
	</title>
	<meta name="author" content="Graham Gibson G L Gibson 2012">
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<link rel="shortcut icon" href="favicon.ico">
	
	<link href="http://www.glgibson.com.au/101/GLGtables.css?ver=3" rel="stylesheet" type="text/css">
	
	<style>
		.numericButton
		{
			background-color: Lightgrey;
			border: 3px outset Grey;
			min-width: 3em;
			white-space: nowrap;
		}
		.functionButton
		{
			background-color: DarkSeaGreen;
						
Read more ...

border: 3px outset Olive; min-width: 3em; white-space: nowrap; } .extraFunctionButton { background-color: Crimson; border: 3px outset Red; min-width: 3em; white-space: nowrap; } .hilightcenter { color: red; text-align: center; } </style> </head> <body> <div class='custombutton'> <div class='hilightcenter'>Calculator</div> <div class="tableDivLeft" > <div class=tableColumn></div><div class=tableColumn></div><div class=tableColumn></div><div class=tableColumn></div><div class=tableColumn></div> <input type='text' size='30' maxlength='200' id='calculatorDisplay' name='calculatorDisplay' style='text-align: right;' onchange='calculatorProcess("=");'> <div class="tableRow"> <input type='button' class='tableCell numericButton' id='button_7' value='7' onclick="calculatorProcess('7');"> <input type='button' class='tableCell numericButton' id='button_8' value='8' onclick="calculatorProcess('8');"> <input type='button' class='tableCell numericButton' id='button_9' value='9' onclick="calculatorProcess('9');"> <input type='button' class='tableCell functionButton' id='button_+' value='+' onclick="calculatorProcess(' + ');"> <input type='button' class='tableCell extraFunctionButton' id='button_c' value='C' onclick="calculatorProcess('c');"> </div> <div class="tableRow"> <input type='button' class='tableCell numericButton' id='button_4' value='4' onclick="calculatorProcess('4');"> <input type='button' class='tableCell numericButton' id='button_5' value='5' onclick="calculatorProcess('5');"> <input type='button' class='tableCell numericButton' id='button_6' value='6' onclick="calculatorProcess('6');"> <input type='button' class='tableCell functionButton' id='button_-' value='-' onclick="calculatorProcess(' - ');"> <input type='button' class='tableCell functionButton' id='button_(' value='(' onclick="calculatorProcess(' (');"> </div> <div class="tableRow"> <input type='button' class='tableCell numericButton' id='button_1' value='1' onclick="calculatorProcess('1');"> <input type='button' class='tableCell numericButton' id='button_2' value='2' onclick="calculatorProcess('2');"> <input type='button' class='tableCell numericButton' id='button_3' value='3' onclick="calculatorProcess('3');"> <input type='button' class='tableCell functionButton' id='button_*' value='*' onclick="calculatorProcess(' * ');"> <input type='button' class='tableCell functionButton' id='button_)' value=')' onclick="calculatorProcess(') ');"> </div> <div class="tableRow"> <input type='button' class='tableCell numericButton' id='button_0' value='0' onclick="calculatorProcess('0');"> <input type='button' class='tableCell numericButton' id='button_00' value='00' onclick="calculatorProcess('00');"> <input type='button' class='tableCell numericButton' id='button_.' value='.' onclick="calculatorProcess('.');"> <input type='button' class='tableCell functionButton' id='button_/' value='/' onclick="calculatorProcess(' / ');"> <input type='button' class='tableCell extraFunctionButton' id='button_=' value='=' onclick="calculatorProcess('=');"> </div> </div> </div> <script> document.getElementById('calculatorDisplay').value = '0'; var lastWasAnswer = false; function calculatorProcess(processString) { var display = document.getElementById('calculatorDisplay').value; if (display == '0' || lastWasAnswer) { if (!isNaN(processString) || processString === ' (') display = ""; lastWasAnswer = false; } if (processString == "c") { display = "0"; } else if (processString == "=") { try { display = (display.replace( /[^0-9\+|\*|\/|\-|(|)|=|%]/g ,"")).trim(); if (display != "") display = eval(display); } catch (err) { display = "WHAT?"; } lastWasAnswer = true; } else { display += processString; } document.getElementById('calculatorDisplay').value = display; } </script> </body> </html>

... Read less

databaseSecurity.php

A safeguard against SQL injection attacks. Filters out unwanted code, quotes and HTML tags before inserting into a database.

/**
 *  Changes strings to injection-safe strings.
 *  Can pass String or an Array.
 *  Pass $isFileName=true for making filenames safe.
 *  
 *  (c) Copyright 2014 G L Gibson - Graham Gibson
 *  */
function safe($text, $isFileName = false)
{
	static $quoteArray = array("#", "&#039;", "&quot;", "'");
	$ret = $text;
	
	if (is_array($text))
	{
		$ret = array();
		foreach ($text as $key => $value)
		{
			$ret[] = safe($value, $isFileName);
		}
	}
	else if (is_string($text))
	{
		try
		{
			if ($isFileName)
			{
				$ret = str_replace(" ", "_", trim($ret));
				$ret = preg_replace('![^'.preg_quote($separator).'a-zA-Z0-9_\s]+!', '', $ret);
			}
						
Read more ...

else { // Get rid of quotes and # (so links can work) $text = str_replace($quoteArray, "`", $text); $text = str_replace("\"", "``", $text); // Take care of entities $text = html_entity_decode($text); $ret = htmlentities($text, ENT_QUOTES); // Add back in acceptable tags - line break and super etc. $old = array("&lt;hr /&gt;","&lt;br /&gt;", "&lt;p&gt;", "&lt;/p&gt;", "&lt;div&gt;", "&lt;/div&gt;", "&lt;sup&gt;", "&lt;/sup&gt;", "&lt;sub&gt;", "&lt;/sub&gt;", "&lt;em&gt;", "&lt;/em&gt;", "&lt;b&gt;", "&lt;/b&gt;", "&lt;h1&gt;", "&lt;/h1&gt;", "&lt;h2&gt;", "&lt;/h2&gt;", "&lt;h3&gt;", "&lt;/h3&gt;", "&lt;h4&gt;", "&lt;/h4&gt;", "&lt;h5&gt;", "&lt;/h5&gt;", "&lt;u&gt;", "&lt;/u&gt;", "&lt;", "&gt;"); $new = array("<hr />","<br />", "<p>", "</p>", "<div>", "</div>", "<sup>", "</sup>", "<sub>", "</sub>", "<em>", "</em>", "<b>", "</b>", "<h1>", "</h1>", "<h2>", "</h2>", "<h3>", "</h3>", "<h4>", "</h4>", "<h5>", "</h5>", "<u>", "</u>", "{", "}"); $ret = str_replace($old, $new, $ret); } } catch (Exception $e){} } return $ret; } /** * Decodes entities so they can be edited. * Pass a String or an Array. * */ function decode($text) { $ret = $text; if (is_array($text)) { $ret = array(); foreach ($text as $key => $value) { $ret[] = decode($value); } } else if (is_string($text)) { try { $ret = htmlentities($text); } catch (Exception $e){} } return $ret; }

... Read less

perlDatabaseTest.pl

A simple database for adding names from either the command line, a browser parameter or a PHP file. Uses a SQLite database and a text file log.

#!/usr/local/bin/perl

# Must print the header first if it already has not been printed
if (@ARGV[0] ne "noHeader")
{
	print "Content-type: text/html\n\n";
}

use strict;
use warnings;
use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
use DBI;
use GLGtools;
use GLGdatabase;

our $logfileName = "arguments.log";
our $GLGdatabase = new GLGdatabase("remember", "Barry", "Gizmo");

sub logThis($$)
{
	open(my $out, ">>", $logfileName) or exit 1;
	my $nextCount = shift; 
	my $nextValue = shift;
	
	if ($nextCount eq "")
	{
		print $out "\n";
	}
	elsif ($nextValue ne "")
						
Read more ...

{ my $tag = "Reminder ".$nextCount; my $value = GLGtools->LoremIpsum(10,8); $GLGdatabase->store($nextValue, $tag, $value); } close $out; } print <<ONE; <!DOCTYPE html><html><head><title>Perl database</title></head> <body> <h2>Adding to database</h2> <p> ONE my $counter = 0; foreach (@ARGV) { if ($_ ne "noHeader") { print "<br>$_"; logThis(++$counter, $_); } } logThis("","") if ($counter > 0); print <<TWO; </p> </body></html> TWO $GLGdatabase->dumpDatabaseToScreen() if ($GLGdatabase); exit 0;

... Read less

GLGdatabase.pm

A Perl database modual.

#!/usr/local/bin/perl 

package GLGdatabase;
use strict;
use warnings;
use DBI;
use GLGtools;
use Digest::MD5 'md5_hex';

sub new
{
	my $class = shift;
	my $self = 
	{
        _databaseName => shift,
        _userName => shift,
        _password => md5_hex(shift),
	};
	bless $self, $class;
	
	my $dbh = $self->connect();
	$dbh->do("CREATE TABLE IF NOT EXISTS memo (Id INT PRIMARY KEY, name TEXT, tag TEXT, value TEXT)");
	$dbh->disconnect();
	
	return $self;
}

sub connect()
{
						
Read more ...

my ($self) = @_; my $dbh = DBI->connect( "dbi:SQLite:dbname=".$self->{_databaseName}.".db", $self->{_userName}, $self->{_password}, { RaiseError => 1 }, ) or die $DBI::errstr; return $dbh; } sub store { my ($self, $name, $tag, $value) = @_; my $dbh = $self->connect(); $name = GLGtools->sanitise($name); $tag = GLGtools->sanitise($tag); $value = GLGtools->sanitise($value); if ($tag ne "") { my $insert = $dbh->prepare("INSERT INTO memo (name, tag, value) VALUES (?, ?, ?)"); $insert->execute($name, $tag, $value); } $dbh->disconnect(); } sub dumpDatabaseToScreen { my ($self) = @_; my $dbh = $self->connect(); my @table_names; @table_names = @{$dbh->selectcol_arrayref("SELECT name FROM sqlite_master WHERE type = 'table'")}; my (@tables, $table); foreach $table (@table_names) { print "<p>TABLE: $table<br>"; my $sql = "SELECT * FROM $table"; my $sth = $dbh->prepare($sql); $sth->execute(); while (my @row = $sth->fetchrow_array) { foreach (@row) { print $_ . "<br>"; } } print "</p>"; } $dbh->disconnect(); } 1;

... Read less

GLGtools.pm

Perl toolbag.

#!/usr/local/bin/perl 

package GLGtools;
use strict;
use warnings;
use Digest::MD5 'md5_hex';

our @alphabet = ("A".."Z", "a".."z");

#Generates random words for Lorem Ipsum.
#Pass maximum number of words and maximum number of letters per word.
sub LoremIpsum($$)
{
	my ($self, $numberOfWords, $numberOfLetters) = @_;
	$numberOfWords = int(rand($numberOfWords))+1;
	my $ret;
	
	for (my $i=0; $i < $numberOfWords; $i++)
	{
		$ret.= @alphabet[rand @alphabet] for 1..int(rand($numberOfLetters))+1; 
		$ret.= " ";
	}
	
	return $ret;	
}

# String replace all occurrences
sub replaceAll($$$)
{
						
Read more ...

my ($self, $string, $find, $replace) = @_; my $lengthOfFind = length( $find ); my $lengthOfReplace = length( $replace ); my $pos = index($string, $find); while ( $pos > -1 ) { substr( $string, $pos, $lengthOfFind, $replace ); $pos = index( $string, $find, $pos + $lengthOfReplace); } } # Sanitises strings befor adding to a database. # Prevents SQL injection and also trims the string. sub sanitise($) { my ($self, $ret) = @_; #$ret = GLGtools->replaceAll($ret, "\"", "`"); #$ret = GLGtools->replaceAll($ret, "'", "`"); $ret = GLGtools->trim($ret); return $ret; } # Code from Szabo, Gabor. 2013. "trim - removing leading and trailing white spaces with Perl". Perl Maven. http://perlmaven.com/trim. sub ltrim($) { my ($self, $ret) = @_; $ret =~ s/^\s+//; return $ret }; sub rtrim($) { my ($self, $ret) = @_; $ret =~ s/\s+$//; return $ret }; sub trim($) { my ($self, $ret) = @_; $ret =~ s/^\s+|\s+$//g; return $ret }; # End code from Szabo, Gabor

... Read less

perlHookTest.php

Executes Perl script from within PHP (add this to an Ajax panel).

<!DOCTYPE html>
<html><head><title>Test Perl Script</title></head> 
<body> 

<?php
setlocale(LC_CTYPE, "en_US.UTF-8");

$vars = escapeshellarg("Hello; there"); 
$path = "/usr/bin/perl ".__DIR__."/perlDatabseTest.pl noHeader Sherlock\ Holmes Dr\ Watson ";

$returnedFromPerl = "";
passthru($path, $returnedFromPerl);


switch ($returnedFromPerl) 
{
	case 1:
		echo "<h3 class='highlight'>ERROR - unable to add record to database.</h3>";
		break;
	case 2:
		echo "<h3 class='highlight'>ERROR - unable to read database.</h3>";
		break;
}
?>

</body></html>

testBinaryDataRead.hpp

Header file - test reading binary data using two different methods.

#ifndef TESTBINARYDATAREAD_HPP_
#define TESTBINARYDATAREAD_HPP_

#include <string>

using namespace std;

namespace testData
{

  class testData
  {
    public:
      __int32 one, two, three;
      long int four, five, six;
      long unsigned int seven, eight, nine;
      float ten, eleven, twelve;
      
      testData(int one, int two, int three, long four, long five, long six, long unsigned int seven, long unsigned int eight, long unsigned int nine, float ten, float eleven, float twelve) :
          one(one), two(two), three(three), four(four), five(five), six(six), seven(seven), eight(eight), nine(nine), ten(ten), eleven(eleven), twelve(twelve)
      {
      }
      
      testData():
        one(0), two(0), three(0), four(0), five(0), six(0), seven(0), eight(0), nine(0), ten(0), eleven(0), twelve(0)
      {
      }
      
      ~testData()
						
Read more ...

{ }; void save(string fileName); void load(string fileName); void display(); }; } #endif /* TESTBINARYDATAREAD_HPP_ */

... Read less

testBinaryDataRead.cpp

Source file - test reading binary data using two different methods. Method one reads directly into a class. Method two first reads into memory and then reads each variable separately (taking in to account different variable types, signed, unsigned, twos complement etc.).

#include "testBinaryDataRead.hpp"

#include <fstream>
#include <iostream>
#include <cstring>
#include <string>
#include <sstream>

using namespace std;
using namespace testData;

char *loadFile(string const &fileName, long &sizeOffile)
{
  char *fileMemoryBlock = 0;

  try
  {
    streampos fileSize;
    ifstream file(fileName.c_str(), ios::in | ios::binary | ios::ate);

    if (file.is_open())
    {
      fileSize = file.tellg();
      sizeOffile = fileSize;

      if (fileSize > 0)
      {
        fileMemoryBlock = new char[fileSize];
        file.seekg(0, ios::beg);
						
Read more ...

file.read(fileMemoryBlock, fileSize); file.close(); } } } catch (exception &e) { } catch (int e) { } return (fileMemoryBlock); } int main() { testData one((int) 1, (int) 2, (int) 3, (long int) 44444, (long int) -5555, (long int) -6, (unsigned long int) 123456789, (unsigned long int) 987654321, (unsigned long int) 0, (float) 3.14159265, (float) -3.14159265, (float) 1.09999); cout << endl << "Test data ONE..." << endl; one.display(); one.save("testDataGenerated.bin"); testData two; two.load("testDataGenerated.bin"); cout << endl << "Test data TWO..." << endl; two.display(); testData three; long fileSize = 0; char *dataBlock = loadFile("testDataGenerated.bin", fileSize); // Load fields in manually... three.one = *(__int32*) (dataBlock + 0); three.two = *(__int32*) (dataBlock + 4); three.three = *(__int32*) (dataBlock + 8); three.four = *(long int*) (dataBlock + 12); three.five = *(long int*) (dataBlock + 16); three.six = *(long int*) (dataBlock + 20); three.seven = *(long unsigned int*) (dataBlock + 24); three.eight = *(long unsigned int*) (dataBlock + 28); three.nine = *(long unsigned int*) (dataBlock + 32); three.ten = *(float*) (dataBlock + 36); three.eleven = *(float*) (dataBlock + 40); three.twelve = *(float*) (dataBlock + 44); cout << endl << "Test data THREE..." << endl; three.display(); return (0); } void testData::testData::save(string fileName) { ofstream ofs(fileName, ios::binary); ofs.write((char *) this, sizeof(testData::testData)); ofs.close(); } void testData::testData::load(string fileName) { ifstream ifs(fileName.c_str(), ios::binary); ifs.read((char *) this, sizeof(testData::testData)); ifs.close(); } void testData::testData::display() { cout << "one: " << dec << one << endl; cout << "two: " << dec << two << endl; cout << "three: " << dec << three << endl; cout << "four: " << dec << four << endl; cout << "five: " << dec << five << endl; cout << "six: " << dec << six << endl; cout << "seven: " << dec << seven << endl; cout << "eight: " << dec << eight << endl; cout << "nine: " << dec << nine << endl; cout << "ten: " << dec << ten << endl; cout << "eleven: " << dec << eleven << endl; cout << "twelve: " << dec << twelve << endl; }

... Read less

pptMacroDetector.java

Detects macros in ppt files (PowewrPoint prior to 2007).

package ggibson.PowerPointMacroDetector;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hslf.record.DocInfoListContainer;
import org.apache.poi.hslf.record.RecordTypes;
import org.apache.poi.hslf.record.VBAInfoAtom;
import org.apache.poi.hslf.record.VBAInfoContainer;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.util.IOUtils;

public class PowerPointMacroDetector
{
	public static void main(String[] args)
	{
		if (args.length > 0)
		{
			new PowerPointMacroDetector(args[0]);
		}
		else
		{
			new PowerPointMacroDetector(null);
		}
	}

						
Read more ...

public PowerPointMacroDetector(String fileName) { System.out.println("Loading " + fileName); InputStream file = null; try { file = new FileInputStream(fileName); } catch (Exception e) { } if (file != null) { if (containsPPTmacro(file)) { System.out.println("*** Macro detected ***"); } else { System.out.println("--- No macro detected ---"); } } else { System.out.println("!!! Unable to access file: " + fileName); } } private boolean containsPPTmacro(InputStream file) { boolean fileContainsMacro = false; BufferedInputStream contents = null; if (file != null) { contents = new BufferedInputStream(file); } if (contents != null) { NPOIFSFileSystem npoifs = null; HSLFSlideShow ppt = null; try { npoifs = new NPOIFSFileSystem(contents); ppt = new HSLFSlideShow(npoifs); DocInfoListContainer list = (DocInfoListContainer) ppt.getDocumentRecord() .findFirstOfType(RecordTypes.List.typeID); if (list != null) { VBAInfoContainer vbaInfo = (VBAInfoContainer) list.findFirstOfType(RecordTypes.VBAInfo.typeID); if (vbaInfo != null) { VBAInfoAtom vbaAtom = (VBAInfoAtom) vbaInfo.findFirstOfType(RecordTypes.VBAInfoAtom.typeID); fileContainsMacro = vbaAtom.isHasMacros(); } } } catch (IOException e1) { // Silently catch as the input stream cannot be read. } finally { IOUtils.closeQuietly(ppt); IOUtils.closeQuietly(npoifs); IOUtils.closeQuietly(contents); } } return fileContainsMacro; } }

... Read less