// JavaScript Document
// list of default fields in text boxes
var txtArr = Array('Please enter', 'Your name', 'Your email (will never be published)', 'Your comments');
var originalTxt = '';
var popupTimerHandle = null;
var email_pass = null;
var order = 'DESC'; // this is the global var that changes and is passed over in the ajax filter on lists (DESC is highest on top)
var populateComplete = false; // this checks wether it is safe to run another ajax call (multithreading workaround kinda)
var text_border_color = '#6a6a6a';
var focused_border_colour = '#7a370c';
var border_size = '1px';


function focusTxt(obj){
	
	originalTxt = obj.value;
	
	for(i=0;i<txtArr.length;i++){
		if(obj.value == txtArr[i]){
			obj.value = '';
		}
	}
	obj.style.fontStyle = 'normal';
	obj.style.color = '#333';
	obj.style.border = '1px solid #a1c8d9';
	
}
function blurTxt(obj){
	
	obj.style.color = '#666';
	obj.style.border = '1px solid #CCC';
	
	if(originalTxt != ''){
		for(i=0;i<txtArr.length;i++){
			if(originalTxt == txtArr[i]){
				obj.value = txtArr[i];
				obj.style.fontStyle = 'italic';
			}
		}
	}
	
}
// public txt
function focusPublicTxt(obj,color){
	
	originalTxt = trimAll(obj.value);
	
	for(i=0;i<txtArr.length;i++){
		if(obj.value == txtArr[i]){
			obj.value = '';
		}
	}
	obj.style.fontStyle = 'normal';
	obj.style.border = border_size + ' solid ' + focused_border_colour;
	
}
function blurPublicTxt(obj,color){
	
	obj.style.color = color;
	obj.style.border = border_size + ' solid ' + text_border_color;
	
	if(originalTxt != ''){
		for(i=0;i<txtArr.length;i++){
			if(originalTxt == txtArr[i] && obj.value == ''){
				obj.value = txtArr[i];
			}
		}
	}
	
}
function trimAll(sString){
	while (sString.substring(0,1) == ' '){
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function focusBtn(obj){
	obj.style.background = '#4992b2';
}
function blurBtn(obj){
	obj.style.background = '#75aac1';
}

// 404 message in the case of a lost ajax page, should never fire.
function get_booboo(){
	return '<div class="loaderHolder">'
			
				+ '<div class="booboo">'
				+ '<p><span>Whoops, something\'s gone horribly wrong...</span></p>'
				+ '<p>It appears I can\'t find the page you\'re looking for.</p>'
				+ '</div>'
			
			+ '</div><!-- end of loaderHolder -->';	
}

// loader text for waiting on ajax call, requires refresh markup with contained function
function get_loader(function_var){
	return '<div class="loaderHolder">'
			
				+ '<div class="loading">Loading</div>'
				
				+ '<div class="spinnerHolder">'
				
					+ '<div class="spinner"><!-- no image in html to allow for eay styling in one place through css --></div>'
					
				+ '</div><!-- end of spinnerHolder -->'
				
				+ '<div style="padding:20px 0;text-align:center;cursor:pointer;">' + function_var + '</div>'
			
			+ '</div><!-- end of loaderHolder -->';	
			
}

function reset_alert_div_size(){
	
	document.getElementById('alertDiv').style.width = '300px';
	document.getElementById('alertDiv').style.height = '';
	document.getElementById('alertDiv').style.minHeight = '100px';
	
}

// client side validation, only checking required fields
function isFormValid(formID, required_arr){
	
	var message = '';
	var form = document.getElementById(formID);
	
	for(i=0; i<required_arr.length; i++){
		if(form.elements[required_arr[i]].value == '' || form.elements[required_arr[i]].value == 'empty'){
			message = message + '<p><strong>' + ucwords(str_replace(required_arr[i], '_', ' ')) + '</strong> is a required field.</p>';
			document.getElementById(required_arr[i]).style.border = '1px solid red';	
		}
		else{
			document.getElementById(required_arr[i]).style.border = '1px solid ' + text_border_color;	
		}
	}
	
	if(message != ''){
		
		if(email_pass == false){
			message = message + '<p>Please provide a valid email.</p>';
		}

		document.getElementById('alertHeader').innerHTML = '<h1>Form Error!</h1>';
		document.getElementById('alertTxt').innerHTML = '<p>' + message + '</p>';
		reset_alert_div_size();
		open_error('#alertDiv');
		return false;
		
	}
	
	// check if we have a password, if so, make sure the two match
	if(document.getElementById('password')){
		
		if(check_password('password', 'confirm_password') == false){
			
			document.getElementById('password').style.border = '1px solid red';
			document.getElementById('confirm_password').style.border = '1px solid red';
			document.getElementById('alertHeader').innerHTML = '<p>Form Error</p>';
			document.getElementById('alertTxt').innerHTML = '<p>Passwords do not match</p>';
			open_error('#alertDiv');
			return false;
			
		}
		
	}
	
	// check if we have username
	if(document.getElementById('username')){
		
		if(username_pass == false){
			
			document.getElementById('username').style.border = '1px solid red';
			document.getElementById('alertHeader').innerHTML = '<p>Form Error</p>';
			document.getElementById('alertTxt').innerHTML = '<p>Username already taken</p>';
			open_error('#alertDiv');
			return false;
			
		}
		
	}
	
	// check if we have a submit id
	if(document.getElementById('submitID')){
		
		document.getElementById('submitID').value = 421;
		
	}
	
	if(email_pass == false){
		return false;	
	}

}

// clearing forms
function clearForm(formID,clear_arr){
	
	for(i=0; i<clear_arr.length; i++){
		document.getElementById(clear_arr[i]).value = '';	
	}
	
}

function check_password(password1, password2){
	
	var p_1 = document.getElementById(password1).value;
	var p_2 = document.getElementById(password2).value;
	
	return (p_1 != p_2) ? false : true ;
	
}

function confirmEmail(str){
	
	if (str.length==0){
	  
	  document.getElementById("emailPrompt").innerHTML="";
	  return;
	  
	}
	  
	if (window.XMLHttpRequest){var xmlhttp=new XMLHttpRequest();} else {var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
	xmlhttp.onreadystatechange=function(){
	  
	  if (xmlhttp.readyState==4 && xmlhttp.status==200){
		
		if(xmlhttp.responseText.indexOf('Invalid Email Address') != -1){
		
			document.getElementById("emailPrompt").innerHTML = '<img src="imgs/small_cross.png" width="16" height="16" border="0" alt="Invalid Email" id="invalidEmail" title="Invalid email address!" />';
			email_pass = false;
			applyTips('#invalidEmail');
			
		}else {
			
			document.getElementById("emailPrompt").innerHTML = '<img src="imgs/small_tick.png" width="16" height="16" border="0" alt="Valid Email" id="validEmail" title="Valid email address" />';
			email_pass = true;
			applyTips('#validEmail');
			
		}
	  
	  }
	  
	}
	
	xmlhttp.open("GET","includes/ajax/email.validitity.check.php?q="+escape(str),true);
	xmlhttp.send();
	
}
function confirmEmail2(str){
	
	if (str.length==0){
	  
	  document.getElementById("emailPrompt").innerHTML="";
	  return;
	  
	}
	  
	if (window.XMLHttpRequest){var xmlhttp=new XMLHttpRequest();} else {var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
	xmlhttp.onreadystatechange=function(){
	  
	  if (xmlhttp.readyState==4 && xmlhttp.status==200){
		
		if(xmlhttp.responseText.indexOf('Invalid Email Address') != -1){
		
			document.getElementById("contact_emailPrompt").innerHTML = '<img src="imgs/small_cross.png" width="16" height="16" border="0" alt="Invalid Email" id="invalidEmail" title="Invalid email address!" />';
			email_pass = false;
			applyTips('#invalidEmail');
			
		}else {
			
			document.getElementById("contact_emailPrompt").innerHTML = '<img src="imgs/small_tick.png" width="16" height="16" border="0" alt="Valid Email" id="validEmail" title="Valid email address" />';
			email_pass = true;
			applyTips('#validEmail');
			
		}
	  
	  }
	  
	}
	
	xmlhttp.open("GET","includes/ajax/email.validitity.check.php?q="+escape(str),true);
	xmlhttp.send();
	
}

// used to decode php urlencoded strings (ajax stuff) and other stuff too
function str_replace(string,seperator,replacement) {
	
	var temp = string.split(seperator);
	return temp.join(replacement);
	
}

// simple ajax call to populate form fields based on record id
function populateForm(form_id,the_class,record_id,iFrame_id){
	
	var params = 'the_class='+the_class+'&record_id='+record_id;
	// set the popluated var to false so the fetch images function won't fire
	populateComplete = false;
	
	if(window.XMLHttpRequest){var xmlhttp=new XMLHttpRequest();} else {var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	xmlhttp.onreadystatechange=function(){
		if(xmlhttp.readyState==4 && xmlhttp.status==200){
			
			var the_form = document.getElementById(form_id);
			var data = xmlhttp.responseText;
			var dataObj = eval('(' + data + ')');
			
			for( var i in dataObj ){
				
				for( var key in dataObj[i] ){
					
					if (dataObj[i].hasOwnProperty(key)) {
						
					    if(document.getElementById(key)){
							
							document.getElementById(key).value = str_replace(unescape(dataObj[i][key]), '+', ' ');
							
							// check for a textarea
							if(document.getElementById(''+key+'WidgIframe')){
								
								var value_1 = str_replace(unescape(dataObj[i][key]), '|', '"');
								var clean_value = str_replace(value_1, '+', ' ');
								
								document.getElementsByTagName("iframe")[0].contentWindow.document.body.innerHTML = clean_value;
								//document.getElementById('cke_contents_'+iFrame_id).contentWindow.document.body.innerHTML = clean_value;
								
							}
							
							// check for any images
							if(document.getElementById(''+key+'_src')){
								document.getElementById(''+key+'_src').src = '../imgs/'+img_root+'/'+unescape(dataObj[i][key])+'';
							}
							
							// check for select boxes
							if(document.getElementById('category') && key == document.getElementById('category').id){
								document.getElementById('category').value = str_replace(unescape(dataObj[i][key]), '+', ' ');
							}
							
							// check for date / time - we need to combine into one field if we have this on the page and format correctly (example: 09/23/2011 00:00)
							if(document.getElementById('event_date') && key == 'event_date' && str_replace(unescape(dataObj[i][key]), '+', ' ') != '0000-00-00 00:00:00'){
								// Split timestamp into [ Y, M, D, h, m, s ]
								var t = str_replace(unescape(dataObj[i][key] + ' 00:00:00'), '+', ' ').split(/[- :]/);
								
								// Apply each element to the Date function
								var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
								
								var month = d.getMonth() + 1;
								month = (month < 10) ? '0'+month : month;
								var day   = d.getDate();
								var year  = d.getFullYear();
								var formatted_date = month+'/'+day+'/'+year;
								
								var db_dt = str_replace('0000-00-00 ' + unescape(dataObj[i]['event_time']), '+', ' ').split(/[- :]/);
								var dt = new Date (db_dt[0], db_dt[1]-1, db_dt[2], db_dt[3], db_dt[4], db_dt[5]);
								var hour        = dt.getHours();
								hour = (hour < 10) ? '0'+hour : hour;
								var minute      = dt.getMinutes();
								minute = (minute < 10) ? '0'+minute : minute;
								
								// and now add the time
								document.getElementById('event_date').value = formatted_date + ' ' + hour + ':' + minute;
								
								
							}
							
						}
						
					}
					
					// check for images
					if(document.getElementById('the_img') && key == 'img'){
						// load the image
						document.getElementById('the_img').src = '../imgs/events/'+unescape(dataObj[i][key]);
						document.getElementById('old_img_name').value = unescape(dataObj[i][key]);
					}
					
				}
				
			}
			// form is no populated with data, continue if needed... (fetch_gallery_images)
			populateComplete = true;
		}
	}
	xmlhttp.open("GET","../includes/ajax/record.get.php?" + params,true);
	xmlhttp.send();
	
}

function colorElelment(html_obj){
	
	// create an array of elements with class name listRepeater (this is to loop over later and set background styles)
	// as IE is shit we have to do a work around becuse it can't manage a simple function!
	var arr = new Array;
	if (document.getElementsByClassName) {
		arr = document.getElementsByClassName('listRepeater');
	}else{
		var d = document.getElementsByTagName("div");
		for(v=0;v<d.length;v++) {
			if (d[v].className == "listRepeater") {
			  arr.push(document.getElementById(d[v].id));
			}
		}
	}
	// loop and set styles
	for(i=0;i<arr.length;i++){
		if(arr[i].id != html_obj.id){
			document.getElementById(arr[i].id).style.background = '#FFF';	
		}
	}
	html_obj.style.background = '#c8edee';
	
}

function fetch_gallery_images(gallery_id, div_id, the_class, img_root){
	
	// as php is not multi thread capable, we should just check to see if the form has populated from the populateForm call 
	// (as this will always be called after a form population function)
	if(populateComplete == true){
		
		var params = "gallery_id=" + gallery_id + "&the_class=" + the_class + "&img_root=" + img_root;
		
		if(window.XMLHttpRequest){var xmlhttp=new XMLHttpRequest();} else {var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
		xmlhttp.onreadystatechange=function(){
			if(xmlhttp.readyState==4 && xmlhttp.status==200){
				if(xmlhttp.responseText.indexOf('FAIL') == -1){ // meaning not found
					// set div content to returned data
					document.getElementById(div_id).innerHTML = xmlhttp.responseText;
					// apply sortble ui
					apply_ui();
					
				}else{
					// someting went wrong, show error
					document.getElementById(div_id).innerHTML = get_booboo();
					
				}
			}else{
				
				document.getElementById(div_id).innerHTML = get_loader('<span style="cursor:pointer" onclick="fetch_gallery_images(\''+gallery_id+'\', \''+div_id+'\',\''+the_class+'\')">[refresh]</span>');	
				
			}
		}
		xmlhttp.open("GET","../includes/ajax/images.get.php?" + params,true);
		xmlhttp.send();
		
	}else{
		
		var t = setTimeout('fetch_gallery_images('+gallery_id+',\''+div_id+'\',\''+the_class+'\', \''+img_root+'\')', 1000);
		
	}
	
}

function activateChangeBtn(the_class, record_id, img_field, old_img_name, upload_dir){
	
	// the passed in params will be added to the onclick handler for the changeBtn
	var btn = document.getElementById('changeImgBtn');
	btn.style.visibility = 'visible';
	btn.setAttribute('onclick','changeImg(\''+the_class+'\', '+record_id+', \'img\', \''+old_img_name+'\', \''+upload_dir+'\');return false');
	
}

function showChangeImgBtn(){
	
	document.getElementById('changeImgBtn').style.display = 'block';
	
}

function loadImg(src){
	
	document.getElementById('selectedImg').src = '../imgs/'+src;
	
}

function loadTheImg(src){
	
	document.getElementById('selectedImg').src = '../imgs/'+src;
	
}

function changeImg(the_class, record_id, img_field, old_img_name, upload_dir){
	
	// as this is a universal funcion, img_field will only be from the design section
	// we're going to popup the modal with the option to upload a new image, 
	// set a couple of hidden fields then post to an ajax page that will upload and write to the db
	var header = '<p>Select an image:</p>';
	
	// create the form
	var form = document.createElement('form');
	form.setAttribute('method','post');
	form.setAttribute('enctype','multipart/form-data');
	form.setAttribute('action','actions/image.change.php');
	form.setAttribute('id','changeImgForm');
	
	var img_input = create_img_input('New Image:', 'new_img', 'new_img');
	
	var hidden_class = create_hidden_input('the_class', the_class);
	var hidden_id = create_hidden_input('record_id', record_id);
	var hidden_url = create_hidden_input('request_url', document.getElementById('requestURL').value);
	var hidden_img_field = create_hidden_input('img_field', img_field);
	var hidden_old_img = create_hidden_input('old_img', old_img_name);
	var hidden_upload_location = create_hidden_input('upload_dir', upload_dir);
	
	var btn_holder = document.createElement('div');
	btn_holder.setAttribute('id','uploadBtnHolder');
	btn_holder.setAttribute('style','padding:10px 0 0 0;text-align:center');
	
	var btn = document.createElement('input');
	btn.setAttribute('type','image');
	btn.setAttribute('value','Upload');
	btn.setAttribute('src','../imgs/update_btn.png');
	
	var message = '<div id="changeImgHolder" style="text-align:left"></div>';
	
	open_message(header, message);
	
	document.getElementById('changeImgHolder').appendChild(form);
	document.getElementById('changeImgForm').appendChild(img_input);
	document.getElementById('changeImgForm').appendChild(btn_holder);
	document.getElementById('uploadBtnHolder').appendChild(btn);
	document.getElementById('changeImgForm').appendChild(hidden_class);
	document.getElementById('changeImgForm').appendChild(hidden_id);
	document.getElementById('changeImgForm').appendChild(hidden_url);
	document.getElementById('changeImgForm').appendChild(hidden_img_field);
	document.getElementById('changeImgForm').appendChild(hidden_old_img);
	document.getElementById('changeImgForm').appendChild(hidden_upload_location);
	
}

function changeSingleImg(the_class, img_field, upload_dir){
	
	// as this is a universal funcion, img_field will only be from the design section
	// we're going to popup the modal with the option to upload a new image, 
	// set a couple of hidden fields then post to an ajax page that will upload and write to the db
	var header = '<p>Select an image:</p>';
	
	// create the form
	var form = document.createElement('form');
	form.setAttribute('method','post');
	form.setAttribute('enctype','multipart/form-data');
	form.setAttribute('action','actions/image.change.php');
	form.setAttribute('id','changeImgForm');
	
	var img_input = create_img_input('New Image:', 'new_img', 'new_img');
	
	var hidden_class = create_hidden_input('the_class', the_class);
	var hidden_id = create_hidden_input('record_id', document.getElementById('id').value);
	var hidden_url = create_hidden_input('request_url', document.getElementById('requestURL').value);
	var hidden_img_field = create_hidden_input('img_field', img_field);
	var hidden_old_img = create_hidden_input('old_img', document.getElementById('old_img_name').value);
	var hidden_upload_location = create_hidden_input('upload_dir', upload_dir);
	
	var btn_holder = document.createElement('div');
	btn_holder.setAttribute('id','uploadBtnHolder');
	btn_holder.setAttribute('style','padding:10px 0 0 0;text-align:center');
	
	var btn = document.createElement('input');
	btn.setAttribute('type','image');
	btn.setAttribute('value','Upload');
	btn.setAttribute('src','../imgs/update_btn.png');
	
	var message = '<div id="changeImgHolder" style="text-align:left"></div>';
	
	open_message(header, message);
	
	document.getElementById('changeImgHolder').appendChild(form);
	document.getElementById('changeImgForm').appendChild(img_input);
	document.getElementById('changeImgForm').appendChild(btn_holder);
	document.getElementById('uploadBtnHolder').appendChild(btn);
	document.getElementById('changeImgForm').appendChild(hidden_class);
	document.getElementById('changeImgForm').appendChild(hidden_id);
	document.getElementById('changeImgForm').appendChild(hidden_url);
	document.getElementById('changeImgForm').appendChild(hidden_img_field);
	document.getElementById('changeImgForm').appendChild(hidden_old_img);
	document.getElementById('changeImgForm').appendChild(hidden_upload_location);
	
}

function create_hidden_input(name, value){
	
	var hidden_input = document.createElement('input');
	hidden_input.setAttribute('type', 'hidden');
	hidden_input.setAttribute('name',name);
	hidden_input.setAttribute('value', value);
	return hidden_input;
	
}

function resetTextBox(textElement){
	
	document.getElementById(textElement).style.fontStyle = 'normal';
	document.getElementById(textElement).style.color = '#333';
	
}

// popup for deleting records
function getRecordForDelete(the_class, record_id){
	
	document.getElementById('alertHeader').innerHTML = 'Confirm delete';
	document.getElementById('alertTxt').innerHTML = 'Are you sure you want to remove this record?' 
	+ '<div class="alertBtns">'
		+ '<div class="left">'
			+ '<input type="buton" value="Cancel" class="whiteBtn" style="width:50px;" onclick="disablePopup(\'#alertDiv\')" />'
		+ '</div>'
		+ '<div class="right">'
			+ '<input type="button" onclick="doDelete(\''+the_class+'\','+record_id+')" id="confirmBtn" name="confirmBtn" value="Proceed" class="btnIni" onmouseover="focusBtn(this)" onmouseout="blurBtn(this)" />'
    	+ '</div>'
		+ '<div class="clear"> </div>'
	+ '</div>';
	open_error('#alertDiv');
	
}

function doDelete(the_class, record_id){
	
	var params = 'the_class='+the_class+'&record_id='+record_id;
	
	if(window.XMLHttpRequest){var xmlhttp=new XMLHttpRequest();} else {var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	xmlhttp.onreadystatechange=function(){
		if(xmlhttp.readyState==4 && xmlhttp.status==200){
			if(xmlhttp.responseText.indexOf('FAIL') == -1){
				location.href=document.getElementById('requestURL').value + '&result=success';
			}else{
				location.href=document.getElementById('requestURL').value + '&result=fail';
			}
		}
	}
	xmlhttp.open("GET","../includes/ajax/record.delete.php?" + params,true);
	xmlhttp.send();
	
}

function filterList(filterField, divID, arrowID, listName){
	// hide all arrow images
	document.getElementById('titleArrow').style.visibility = 'hidden';
	document.getElementById('dateArrow').style.visibility = 'hidden';
	// requires table name and field to be filtered	
	var params = 'f='+filterField+'&o='+order;
	// set div content to loader
	document.getElementById(divID).innerHTML = get_loader('<span style="cursor:pointer" onclick="manageList(\''+filterField+'\', \''+divID+'\')">[refresh]</span>');
	// call ajax
	if(window.XMLHttpRequest){var xmlhttp=new XMLHttpRequest();} else {var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	xmlhttp.onreadystatechange=function(){
		if(xmlhttp.readyState==4 && xmlhttp.status==200){
			if(xmlhttp.responseText.indexOf('FAIL') == -1){ // meaning not found
				// set div content to returned data
				document.getElementById(divID).innerHTML = xmlhttp.responseText;
				showArrow(''+arrowID+'');
			}else{
				// someting went wrong, show error
				document.getElementById(divID).innerHTML = get_booboo();
			}
		}
	}
	xmlhttp.open("GET","../includes/ajax/"+listName+".filter.php?" + params,true);
	xmlhttp.send();
	
}

function showArrow(arrowID){
	
	if(order == 'ASC'){
		document.getElementById(arrowID).src = '../imgs/filterDownArrow.png';
		document.getElementById(arrowID).style.visibility = 'visible';
		order = 'DESC';
	}else{
		document.getElementById(arrowID).src = '../imgs/filterUpArrow.png';	
		document.getElementById(arrowID).style.visibility = 'visible';
		order = 'ASC';
	}
	
}

function addInput(formName,elementName, div_id){
	
	var arr = new Array;
	if (document.getElementsByName) {
		arr = document.getElementsByName(elementName + '[]');
	}else{
		var d = document.getElementsByTagName("input");
		for(v=0;v<d.length;v++) {
			if (d[v].name == elementName + '[]') {
			  arr.push(document.getElementById(d[v].id));
			}
		}
	}
	var div = document.getElementById(div_id);
	// add input type (image)
	var the_input = create_img_input('Image '+(arr.length + 1)+': ', elementName+'[]', elementName+'_'+(arr.length + 1));// label, name, id
	
	// create fieldset
	var new_field_set = document.createElement('fieldset');
	new_field_set.setAttribute('className','inputSet');
	new_field_set.setAttribute('class','inputSet');
	// append to container
	div.appendChild(new_field_set);
	new_field_set.appendChild(the_input);
	
}

function create_img_input(label, name, id){
	
	var new_input = document.createElement('input');
	// name as designimage_before
	new_input.setAttribute('name',name);
	new_input.setAttribute('type','file');
	new_input.setAttribute('className', 'txtIni');
	// id is plus next available index (array count + 1)
	new_input.setAttribute('id',id);
	new_input.setAttribute('class', 'txtIni');
	// now add the label
	var new_label = document.createElement('label');
	new_label.setAttribute('for', new_input.id);
	new_label.innerHTML = label;
	// create fieldset
	var new_field_set = document.createElement('fieldset');
	new_field_set.setAttribute('className','inputSet');
	new_field_set.setAttribute('class','inputSet');
	
	new_field_set.appendChild(new_label);
	new_field_set.appendChild(new_input);
	
	return new_field_set;
	
}

function loadImg(src){
	
	document.getElementById('selectedImg').src = '../imgs/'+src;
	
}

function showRemoveBtn(button_id,record_id){
	// this is a bit of a hack, but works ok.
	// we're going to assign the record id to the buttons value, this is so we can pass it to the delete function
	document.getElementById(button_id).style.visibility = 'visible';
	document.getElementById(button_id).value = record_id;
	
}

function locateTo(url){
	
	location.href = url;
		
}

function showTitle(str){
	document.getElementById('galTitle').innerHTML = str;
}
function hideTitle(){
	document.getElementById('galTitle').innerHTML = '';	
}

function open_message(header,message){
	
	document.getElementById('alertHeader').innerHTML = header;
	document.getElementById('alertTxt').innerHTML = message;
	open_error('#alertDiv');
	
}

function open_error(divID){
	//LOADING POPUP
	centerPopup(divID);
	//load popup
	loadPopup(divID),
					
	//CLOSING POPUP
	//Click the x event!
	$(divID+'Close').click(function(){
		disablePopup(divID);
	});
	
}

function open_modal(divID){
	//LOADING POPUP
	centerPopup(divID);
	//load popup
	loadPopup(divID),
					
	//CLOSING POPUP
	//Click the x event!
	$(divID+'Close').click(function(){
		disablePopup(divID);
	});
	
}

function showHiddenDiv(divID){
	document.getElementById(divID).style.display = 'block';
}

function apply_custom_form(){
		
	var options = {styleClass: "selectDark", jScrollPane: 1}
	$(".funckySelect").styleSelect(options);
		
}

function isErrorFormValid(default_txt){
	
	if(document.getElementById('errorMessage').value == default_txt){
		
		document.getElementById('errorPrompt').innerHTML = '<span style="color:#C00;font-weight:bold;font-size:20px">Please fill in the blanks.</span>';
		return false;
		
	}else{
		
		document.getElementById('submitID').value = 421;
		document.getElementById('errorForm').submit();
		return true;
			
	}
		
}

function return_to_top(){
	scroll(0,0);
  }

function loadNextRecords(){
	
	// show the loading image
	document.getElementById('progressiveLoader').style.display = 'block';
		
	// call the ajax page
	if (window.XMLHttpRequest){var xmlhttp = new XMLHttpRequest();} else {var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
		xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			if(xmlhttp.responseText.indexOf('No records') == -1){
				
				// we're good to append our returned data to the div
				var container = document.getElementById('blogsHolder');
					
				// 1. create a new div to hold the data (infinateDayHolder)
				var holder_div = create_element('div', 'blogRepeaterOuter');
				// 1. (a) set a random id (time)
				var currentTime = new Date();
				var temp_id = currentTime.getTime();
				holder_div.setAttribute('id',temp_id);
				// 1. (b) set the style to none 
				holder_div.setAttribute('style', 'display:none');
					
				// 2. set the holder html to the returned data
				holder_div.innerHTML = xmlhttp.responseText;
					
				// 3. now append this to the main container div
				container.appendChild(holder_div);
				
				// 4. and finally fade in (have to set a timeout as good ol' IE is crap!)
				//var t = setTimeout('fadeIn('+holder_div.id+', 800)', 900);
				fadeIn(holder_div.id, 800)
				
				// 5. we're now good to get rid of the loader image
				fadeOut('progressiveLoader', 800);
				
				// 6. and increase background image height
				increase_background_height();
					
			}
			
		}
		
	}

	xmlhttp.open("GET","includes/ajax/progressive.get.php",true);
	xmlhttp.send();
	
}

function create_element(elementType, the_class_name){
		
	var new_element = document.createElement(elementType);
	new_element.setAttribute('className', the_class_name);
	new_element.setAttribute('class',the_class_name);
	return new_element;
	
}

function increase_background_height(){
	var the_height = xDocSize();
	document.getElementById('background_img').style.height = the_height + 'px';
}

function ucwords(str) {
	return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
	return $1.toUpperCase();    });
}

/////////////////////////////////////////////////  Fade Up Functions  ////////////////////////////////////////////////////////////////////
function fadeOut(thisId, speed) {
    var thisE = document.getElementById(thisId);
    thisE.style.zoom = 1; //needed for IE
    speed = speed/20;
    var i = 100;
    var intervalId = setInterval(function() {
        if(i>=0) {
            thisE.style.opacity = i/100;
            thisE.style.filter = 'alpha(opacity='+i+')';
            i -= 5;
        } else {
            setTimeout(function() {thisE.style.display = "none";}, speed);
            clearInterval(intervalId);
            return false;
        }
    }, speed);
}

function fadeIn(thisId, speed) {
    var thisE = document.getElementById(thisId);
    thisE.style.display = "block";
    thisE.style.zoom = 1; //needed for IE
    thisE.style.opacity = 0;
    thisE.style.filter = "alpha(opacity = 0)";
    speed = speed/20;
    var i = 0;
    var intervalId = setInterval(function() {
        if(i <= 100) {
            thisE.style.opacity = i/100;
            thisE.style.filter = 'alpha(opacity='+i+')';
            i += 5;
        } else {
            clearInterval(intervalId);
            return false;
        }
    }, speed);
}

function set_100Percent_height(divID){
	var _docHeight = xDocSize();
//alert(_docHeight);
	var blanket_height=_docHeight;//$(document).height();
	document.getElementById(divID).style.height=blanket_height+'px';
	
}

function xDocSize()
{
  var b=document.body, e=document.documentElement;
  var esw=0, eow=0, bsw=0, bow=0, esh=0, eoh=0, bsh=0, boh=0;
  if (e) {
    esw = e.scrollWidth;
    eow = e.offsetWidth;
    esh = e.scrollHeight;
    eoh = e.offsetHeight;
  }
  if (b) {
    bsw = b.scrollWidth;
    bow = b.offsetWidth;
    bsh = b.scrollHeight;
    boh = b.offsetHeight;
  }
//  alert('compatMode: ' + document.compatMode + '\n\ndocumentElement.scrollHeight: ' + esh + '\ndocumentElement.offsetHeight: ' + eoh + '\nbody.scrollHeight: ' + bsh + '\nbody.offsetHeight: ' + boh + '\n\ndocumentElement.scrollWidth: ' + esw + '\ndocumentElement.offsetWidth: ' + eow + '\nbody.scrollWidth: ' + bsw + '\nbody.offsetWidth: ' + bow);
  //return {w:Math.max(esw,eow,bsw,bow),h:Math.max(esh,eoh,bsh,boh)};
  return Math.max(esh,eoh,bsh,boh);
}

function set_blanket_size(){
	var _docHeight = xDocSize();
//alert(_docHeight);
	blanket_height=_docHeight;//$(document).height();
	var blanket=document.getElementById('backgroundPopup');
	blanket.style.height=blanket_height+'px';
	
}
