function enableLiveSearch() {

	 var livesearch = true;

	if(document.cookie.indexOf('livesearch=s%3A1%3A%220%22%3B') >= 0) {
		livesearch = false;
	}

	if(livesearch && $('liveSearch') && $('liveSearchAnswers')) {
		new Ajax.Autocompleter("liveSearch", "liveSearchAnswers", "ajax/livesearch/", {paramName: "text", minChars: 2});
	}


}


function selectAll(selectBoxName) {

	if(!$(selectBoxName)) return false;

	var theOptions = $A($(selectBoxName).options);

	theOptions.each(function(option) {

		if(option != null) {

			$(selectBoxName).options[ option.index ].selected = true;

		}

	 });
	
	return false;

}




function addCrew(id) {
	
	crewlistLoading('Adding to crew list');

	new Ajax.Request( 'ajax/crewlist/add/?id='+id, { onComplete: function(transport) { _addCrew(transport); }} );
	
	return false;

}

function _addCrew(transport) {

	transportText = ajaxTransportText(transport);

	if(transportText['error']) {

		$('crewlist_message').innerHTML = '<img src="img/admin/notice.png"> '+transportText['text'];

	} else {
		
		$('crewlist_update').innerHTML = transportText['text'];
	
		zebra('table', 'crewlistTable', 'tr', 'odd, even');

	}
	
	_crewlistLoading();

}



function deleteCrew(id) {
	
	crewlistLoading('Deleting from crew list');

	new Ajax.Request( 'ajax/crewlist/delete/?id='+id, { onComplete: function(transport) { _deleteCrew(transport); }} );
	
	return false;

}

function _deleteCrew(transport) {

	transportText = ajaxTransportText(transport);
	
	if(transportText['error']) {

		$('crewlist_message').innerHTML = '<img src="img/admin/notice.png"> '+transportText['text'];
		
	} else {

		$('crewlist_update').innerHTML = transportText['text'];
	
		zebra('table', 'crewlistTable', 'tr', 'odd, even');

	}
	
	_crewlistLoading();


}


function clearCrew() {
	
	crewlistLoading('Clearing crew list');
	
	answer = confirm('Are you sure you want to clear the crew list?');

	if(answer === false) {
		_crewlistLoading();
		return false;
	}

	new Ajax.Request( 'ajax/crewlist/clear/', { onComplete: function(transport) { _clearCrew(transport); }} );
	
	return false;

}

function _clearCrew(transport) {

	transportText = ajaxTransportText(transport);
	
	if(transportText['error']) {

		$('crewlist_message').innerHTML = '<img src="img/admin/notice.png"> '+transportText['text'];
		
	} else {

		$('crewlist_update').innerHTML = transportText['text'];
	
		zebra('table', 'crewlistTable', 'tr', 'odd, even');

	}
	
	_crewlistLoading();


}


function rememberCrew() {
	
	crewlistLoading('Storing crew list');
	
	new Ajax.Request( 'ajax/crewlist/remember/', { onComplete: function(transport) { _rememberCrew(transport); }} );
	
	return false;

}

function _rememberCrew(transport) {

	transportText = ajaxTransportText(transport);
	
	if(transportText['error']) {

		$('crewlist_message').innerHTML = '<img src="img/admin/notice.png"> '+transportText['text'];
		
	}

	_crewlistLoading();

}




function crewlistLoading(message) {

	$('crewlist_message').innerHTML = '<img src="img/layout/working.gif" width="16" height="16" /> ' + message;

	Effect.Appear('crewlist_message',{duration: 0.5, queue: {position:'front', scope:'crewlistLoading', limit: 50}});

}

function _crewlistLoading() {

	setTimeout(function() {
		Effect.Fade('crewlist_message',{duration: 0.5, queue: {position:'end', scope:'crewlistLoading', limit: 50}});
	}, 500);

}





function stillClick() {

	var url_post = '';
	if(R(3) != '') {
		url_post += R(3) + '/';
	}
	
	return windowopen('listing/still/'+url_post, "left=50,top=100,width=500,height=350,resizable");

}


function showreelClick() {

	var url_post = '';
	if(R(3) != '') {
		url_post += R(3) + '/';
	}
	
	return windowopen('listing/showreel/'+url_post, "left=50,top=100,width=500,height=350,resizable");

}

function crewlistEmail() {

	Effect.toggle('emailCrew', 'appear', {duration: .3});
	
	location.hash = 'emailForm';

	return false;

}





function resizeWindow() {
	
	var width = 500;
	var height = 400;

	if(document.body.clientHeight) {
		width = document.body.clientWidth + 100;
		height = document.body.clientHeight + 100;
	}

	if(width > 500) width = 600;
	if(height > 400) height = 400;

	window.resizeTo(width, height);

}

function windowopen(url, vars) {
	
	if(vars == null) vars = 'width=10,height=10,resizable, scrollbars';
	
	var base = document.getElementsByTagName('base')[0].href;
	
	var currentTime = new Date();

	window.open(base + url, currentTime.getTime(), vars);
	
	return false;

}

function gets(varName) {

	var toReturn = '';

	var urlHalves = String(document.location).split('?');

	if(urlHalves[1]) {
		var urlVars = urlHalves[1].split('&');
		for(i=0; i<=(urlVars.length); i++) {
			if(urlVars[i]){
				var urlVarPair = urlVars[i].split('=');
				if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
					toReturn = urlVarPair[1];
				}
			}
		}
	}

	return toReturn;

}

function R(number) {
	
	var toReturn = '';
	
	var location = String(document.location);
	location = location.replace(document.getElementsByTagName('base')[0].href, '');
	
	var Rs = location.split('/');

	//get rid of the last GET variable if its there
	var last = Rs.last();
	if(last.startsWith('?')) {
		Rs.splice(-1);
	}

	number--;
	
	if(Rs[number]) {
		return Rs[number];
	} else {
		return '';	
	}

}



function cancel() {

	var sure = confirm('Are you sure you want to cancel?');
	
	if(sure) {
		goBack();
	}

	return false;

}

function forward(page) {

	document.location.href = document.getElementsByTagName('base')[0].href + page;

}

var floatActivityDivTop = 0;
function floatActivityDiv() {

	if (document.documentElement && document.documentElement.scrollTop) {
		scrollTop = document.documentElement.scrollTop;
	} else {
		scrollTop = document.body.scrollTop;
	}
	
	floatActivityDivTop += (scrollTop + 20 - floatActivityDivTop) / 6;

	$('showActivity').style.top = floatActivityDivTop + 'px';
	$('showActivity').style.right = 20 + 'px';

}



function ajaxTransportText(transport) {

	var toReturn = new Array();

	if(transport.statusText != "OK") {
		toReturn['error'] = true;
		toReturn['text'] = (transport.statusText != "Internal Server Error") ? 'Error with server' : transport.responseText;
	} else {
		toReturn['error'] = false;
		toReturn['text'] = transport.responseText;
	}
	
	return toReturn;

}



//if request takes longer than 1.5 seconds, it shows 'activity'
Ajax.Responders.register({
	onCreate: function() {
		if($('showActivity') && Ajax.activeRequestCount> 0) {
			setTimeout("if(Ajax.activeRequestCount> 0) { showActivity() }", 1500);
		}
	},
	onComplete: function() {
		if($('showActivity') && Ajax.activeRequestCount == 0) {
			hideActivity();
		}
	}
});

function showActivity() {
	if($('showActivity')) {
		Effect.Appear('showActivity',{duration: 0.5, queue: {position:'front', scope:'showActivity', limit: 50}});
	}
}
function hideActivity() {
	if($('showActivity')) {
		Effect.Fade('showActivity',{duration: 0.5, queue: {position:'end', scope:'showActivity', limit: 50}});
	}
}

function goBack() {

	history.go(-1);

	return false;

}

var docSubmitted = false;

function formSubmit() {
	
	if(ignoreLock) return true;

	if(docSubmitted == true) {

		alert('A form is currently submitting. Please be patient!');
		return false;

	} else {

		docSubmitted = true;

		setTimeout("showActivity()", 2000);

		return true;

	}

}



// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini
// http://dean.edwards.name/weblog/2005/10/add-event/

// had also tried http://ecmascript.stchur.com/2006/10/12/fixing-ies-attachevent-failures/
// altho could not do return false on it

function addEvent(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = addEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = _handleEvent;
	}
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function _handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || _fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$_handleEvent = handlers[i];
		if (this.$$_handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function _fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = _fixEvent.preventDefault;
	event.stopPropagation = _fixEvent.stopPropagation;
	return event;
};
_fixEvent.preventDefault = function() {
	this.returnValue = false;
};
_fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};








// http://24ways.org/2005/splintered-striper

/*
 * Summary:      Core experiment function that applies any number of classes to all child elements
 *               contained in all occurences of a parent element (either with or without a specific class)
 * Parameters:   parentElementTag - parent tag name
 *               parentElementClass - class assigned to the parent; if null, all parentElementTag elements will be affected
 *               childElementTag -  tag name of the child elements to apply the styles to
 *               styleClasses - comma separated list of any number of style classes (using 2 classes gives the classic "zebra" effect)
 * Return:       none
 */
 
function zebra(parentElementTag, parentElementClass, childElementTag, styleClasses)
{

	var i=0,currentParent,currentChild;
	// capability and sanity check
	if ((document.getElementsByTagName)&&(parentElementTag)&&(childElementTag)&&(styleClasses)) {
		// turn the comma separate list of classes into an array
		var styles = styleClasses.split(',');
		// get an array of all parent tags
		var parentItems = document.getElementsByTagName(parentElementTag);
		// loop through all parent elements
		while (currentParent = parentItems[i++]) {
			// if parentElementClass was null, or if the current parent's class matches the specified class
			if ((parentElementClass == null)||(currentParent.className.indexOf(parentElementClass) > -1)) {
				var j=0,k=0;
				// get all child elements in the current parent element
				var childItems = currentParent.getElementsByTagName(childElementTag);
				// loop through all child elements
				while (currentChild = childItems[j++]) {
					// based on the current element and the number of styles in the array, work out which class to apply
					k = (j+(styles.length-1)) % styles.length;
					// add the class to the child element - if any other classes were already present, they're kept intact
					currentChild.className = currentChild.className+" "+styles[k];
				}
			}
		}
	}
}

var inits = new Array();

function initAdd(func) {
	inits[inits.length] = func;	
}

var ignoreLock = false;

function init() {

	$$('button').each(function(el) {

		var origName = el.name;

		addEvent(el, 'click', function() {

			if(el.className.indexOf('ignoreLock') > -1) {
				ignoreLock = true;
			} else {
				ignoreLock = false;	
			}

			this.name = origName;
		});

		el.name = 'submitButton';

	})
	
	$$('form').each(function(el) {

		addEvent(el, 'submit', function(e) {

			if(el.method != 'post') {
								  
				$$('button').each(function(el) {
	
					if(el.value.length > 20) {
						el.value = 'Working...';	
					}
	
				})
				
			}

			var answer = formSubmit();
			if(answer === false) {
				e.preventDefault();
			}

		});

	})
	
	$$('.extLink').each(function(el) {

		el.target = "_blank";

	});



	$$('h1').each(function(el) {
		if(el.className != 'noLink') {
			el.onclick = function() {
				window.open("http://film.vic.gov.au/", "_blank");
			}
			el.onmouseover = function() {
				window.status = 'http://film.vic.gov.au/';
			}
			el.onmouseout = function() {
				window.status = '';	
			}
		}
	})

	$$('h2').each(function(el) {
		if(el.className != 'noLink') {
			el.onclick = function() {
				location.href = document.getElementsByTagName('base')[0].href;
			}
			el.onmouseover = function() {
				window.status = document.getElementsByTagName('base')[0].href;
			}
			el.onmouseout = function() {
				window.status = '';	
			}
		}
	})
	
	$$('#footer img').each(function(el) {

		el.onclick = function() {
			window.open("http://vic.gov.au/", "_blank");
		}
		el.onmouseover = function() {
			window.status = 'http://vic.gov.au/';
		}
		el.onmouseout = function() {
			window.status = '';	
		}
	})
	
	zebra('table', 'zebra', 'tr', 'odd, even');

	if($('showActivity')) {
		setInterval("floatActivityDiv()", 30);
	}

	initAdd('enableLiveSearch');
	initAdd('enableTooltips');

	for(var i = 0;i < inits.length;i++) {
		eval(inits[i]+'()');
	}

}

