var mySelectMethods = {
	filter: function(element, filter, value) {
		if (navigator.userAgent.indexOf('AppleWebKit/')) {
			do {
				element.options[element.options.length - 1] = null
			} while (element.options.length > 0)
		} else {
			element.options.length = 0
		}
		if (filter == null) {
			re = /^\/.+\/$/gi
			regExpKeys = element.filters.keys().findAll(	function(o) {
				return o.startsWith("/") && o.endsWith("/")
			} )
			clean = /\//g
			for (i = 0; i < regExpKeys.length; i++) {
				re = new RegExp(regExpKeys[i].replace(clean,""), "i")
				if (re.test(value)) {
					filter = element.filters.get(regExpKeys[i])
					break
				}
			}
			if ((filter == null) || (filter == "")) {
				return false
			}
		}

		if (filter.startsWith("/")) {
			re = /\//g
			regExp = new RegExp(filter.replace(re,""), "i")
			element.allOptions.each( function (item) {
				if (regExp.test(item.value)) {
					element.options[element.options.length] = item
				}
			})

		} else if (filter.startsWith("!")) {
			foo = filter.replace("!","")
			avoid = foo.split("|")
			element.allOptions.each( function (item) {
				include = true
				for (i = 0; i < avoid.length; i++) {
					include = include && (item.value.search(avoid[i]) == -1)
				}
				if (include) {
					element.options[element.options.length] = item
				}

			})
		}


		return element
	},
	filterNow: function(element) {
		element.filter(element.filters.get($F(element.filterOn)), $F(element.filterOn))

	},
	initAllOptions: function(element) {
		element.allOptions = new Array()
		for (i = 0; i < element.options.length; i++) {
			element.allOptions.push(element.options[i])
		}

		return element
	},
	filterBasedOn: function(element, obj, f) {
		element.filters = f
		element.filterOn = obj
		new Form.Element.Observer(obj, 0.3, function(form,key) {
			element.filter(element.filters.get(key),key)
		})
	},
	establishEliminateTwinFilter: function(element,obj,exclude) {
		if (exclude == null) {
			exclude = new Array();
		}
		element.initAllOptions()
		new Form.Element.Observer(obj, 0.3, function(form,key) {
			if (navigator.userAgent.indexOf('AppleWebKit/')) {
				do {
					element.options[element.options.length - 1] = null
				} while (element.options.length > 0)
			} else {
				element.options.length = 0
			}
			element.allOptions.each( function (item) {
//				if ((item.value != key)) {
				if ((item.value != key) || (exclude.indexOf(key) != -1)) {
					element.options[element.options.length] = item
				}
			})
		})
//		element.filterBasedOn(obj,f)
//		element.filterNow()
	},
	establishFilter: function(element,obj,f) {
		element.initAllOptions()
		element.filterBasedOn(obj,f)
		element.filterNow()
	},
	establishTypeToFilter: function(element, obj) {
		element.initAllOptions()
		new Form.Element.Observer(
			obj,
			0.6,
			function(el, filterValue) {
				fieldList = element

				if (navigator.userAgent.indexOf('AppleWebKit/')) {
					do {
						fieldList.options[fieldList.options.length - 1] = null
					} while (fieldList.options.length > 0)
				} else {
					fieldList.options.length = 0
				}

				if (filterValue == "") {
					element.allOptions.each( function (item) {
						fieldList.options[fieldList.options.length] = item
					})

				} else {
					regExp = new RegExp(filterValue, 'i')
					fieldList.allOptions.each( function (item) {
						if (regExp.test(item.value)) {
							fieldList.options[fieldList.options.length] = item
						}
					})

				}
			}
		)

	}


}
Element.addMethods('SELECT', mySelectMethods)


function toggle_block_tools() {
	$('edit_button').editing = !($('edit_button').editing)
	if ($('edit_button').editing) {
		$('edit_button').down('span').update('Finish Changes')
		$('edit_button').addClassName('active_button')

	} else {
		$('edit_button').down('span').update('Make Changes')
		$('edit_button').removeClassName('active_button')
	}
	$$('.record_block_tools').each(	function(e) {
		e.setStyle({height:e.up().getDimensions().height+'px'})
		e.toggle()
	})
}

	function addleague(id) {

		if ($('league_name').value == '') {
			alert('Please Your League Name.');
			$('league_name').focus();
			return false;

		}	else {

		 $('form_submit').innerHTML = '<img src="images/loading_icon/loading_form.gif">';
		  	new Ajax.Updater('window_content', 'management/window/leagues/create_league.php', {
				parameters: $(document.add_league).serialize(),
				onComplete: function() {
					new Effect.Morph('add_alert', {style:'background:#FDFEA5; color:#000000;  border: 1px solid #F7E600;',duration:0.8});
					$('add_alert').innerHTML = '<strong>League Added!</strong>';
					$('league_name').value = '';
					reload_league_section(id, 'default');
				}
			});
		}
		return false;
	}

	function addLeagueTeam(id, sec) {

		if ($('team_name').value == '') {
			alert('Please enter a team name.');
			$('team_name').focus();
			return false;

		} else {
		 $('form_submit').innerHTML = '<img src="images/loading_icon/loading_form.gif">';
		  	new Ajax.Updater('window_content', 'management/window/leagues/create_team.php', {
				parameters: $(document.add_league).serialize(),
				onComplete: function() {
					new Effect.Morph('add_alert', {style:'background:#FDFEA5; color:#000000;  border: 1px solid #F7E600;',duration:0.8});
					$('add_alert').innerHTML = '<strong>Team Added!</strong>';
					$('team_name').value = '';
					reload_league_section(id, sec)
				}
			});
		}
		return false;

	}

	function addLeagueGame(id, sec) {

		if (($F('select_team1') == '') || ($F('select_team2') == '')) {
			alert('Please choose teams for the game!');
			return false;

		} else {
		if ($F('select_team1') == "*") {
			$('select_team1').value = null;
		}
		if ($F('select_team2') == "*") {
			$('select_team2').value = null;
		}
		 $('form_submit').innerHTML = '<img src="images/loading_icon/loading_form.gif">';
		  	new Ajax.Updater('window_content', 'management/window/leagues/create_game.php', {
				parameters: $('add_form').serialize(),
				onComplete: function() {
					new Effect.Morph('add_alert', {style:'background:#FDFEA5; color:#000000;  border: 1px solid #F7E600;',duration:0.8});
					$('add_alert').innerHTML = '<strong>Game Added!</strong>';
					$('game_name').value = '';
					reload_league_section(id, sec);
				}
			});
		}
		return false;

	}

	function reload_league(id) {
		new Ajax.Updater('section_block', 'management/updater/leagues.php', {
			parameters: {id:id, sec:'default', lid:$F('lid'), bid:$F('id')},
			evalScripts:true
		});

		return false;
	}

	function reload_league_teams(id) {
		new Ajax.Updater('section_block', 'management/updater/leagues.php', {
			parameters: {lid:id, sec:'teams'},
			evalScripts:true
		});

		return false;
	}

	function reload_league_section(id, sec, editing) {
		if (sec == 'start') {
			$('lid').value = id
		} else if (sec == 'teams') {
			$('lid').value = id
		} else if (sec == 'games') {
			$('lid').value = id
		} else if (sec == 'standings') {
			$('lid').value = id
		} else if (sec == 'team_details') {
			$('tid').value = id

		}
		bus_id = $F('bid');
		l_id = $F('lid');
		t_id = $F('tid');
		g_id = $F('gid');
		$('section_block').innerHTML = "<div style=\"background-color:white;font-size:32px;height:40px;line-height:32px;clear:both;\"><img src=\"images/loading_icon/loading_form.gif\" width=\"208\" height=\"13\"/> One moment...</div>";

		new Ajax.Updater('section_block', '/management/updater/leagues.php', {
			parameters: {sec:sec, editing:editing, bid:bus_id, lid:l_id, tid:t_id, gid:g_id},
			evalScripts:true
		});

		return false;
	}


function ajax_delete(prefix, id, dataModelClass, callOnSuccess, url) {
	if (url == null) {
		url = "/ajax_master.php"
	}
	new Ajax.Request(url, {
		method: 'post',
		parameters: {action:'delete', rid:id, dataModelClass:dataModelClass},
		onSuccess: function(transport) {
			new Effect.Shrink(prefix+id);
			callOnSuccess()
		},
		onFailure: function(transport) {
			alert("An error occurred.")
		}
	});
}

function changeGameOutcome(id, selectID) {
	if ($F(selectID) != "") {
		new Ajax.Request('/ajax_master.php', {
			method: 'post',
			parameters: {action:'changeGameOutcome', outcomeType:$F(selectID), rid:id, dataModelClass:'Game'},
			onSuccess: function(transport) {
				reload_league_section($F('lid'), 'games')
			},
			onFailure: function(transport) {
				alert("An error occurred.")
			}
		})
	}
}

function toggleGameOutcomeTools(id) {
	obj = $(id+'_outcome')
	obj.toggle()
	if (obj.visible()) {
		var timer = setTimeout("$('"+obj.id+"').fade();", 10000)
		obj.timer = timer
	} else {
		clearTimeout(obj.timer)
	}
}

//----------------------------------------------------------------------------------------

function addCoupon(id, sec) {
	tinyMCE.triggerSave(false, true);
	$('form_submit').innerHTML = '<img src="images/loading_icon/loading_form.gif">';
	if (($F('coupon_title') == '') || (($F('coupon_body') == '') && ($F('_file') == ''))) {
		alert('Every coupon needs a title and content!');
		return false;

	} else {
		$('mid').value = id
		return true;
	}
	return false;
}

function editCoupon(id, sec) {
	tinyMCE.triggerSave(false, true);
	$('form_submit').innerHTML = '<img src="images/loading_icon/loading_form.gif">';
	if (($F('coupon_title') == '') || (($F('coupon_body') == '') && ($F('_file') == ''))) {
		alert('Every coupon needs a title and content!');
		return false;

	} else {
		return true;
		 /*
$('form_submit').innerHTML = '<img src="images/loading_icon/loading_form.gif">';
		  	new Ajax.Updater('window_content', 'management/sections/coupons/ajax_edit_coupon.php', {
				parameters: $('add_form').serialize(),
				onComplete: function() {
					new Effect.Morph('add_alert', {style:'background:#FDFEA5; color:#000000;  border: 1px solid #F7E600;',duration:0.8});
					$('add_alert').innerHTML = '<strong>Changes Saved!</strong>';
					$('coupon_title').value = '';
					$('coupon_body').value = '';
					$('window').fade()
					$('overlay').fade();
					reload_coupon_section(id, sec);

				}
			});
*/
	}
	return false;
}

function reload_coupon_section(id, sec, editing) {
	if (sec == 'default') {
		$('bid').value = id
	}
/*	} else if (sec == 'teams') {
		$('lid').value = id
	} else if (sec == 'games') {
		$('lid').value = id
	} else if (sec == 'standings') {
		$('lid').value = id
	} else if (sec == 'team_details') {
		$('tid').value = id
	}*/
	bus_id = $F('bid');
	$('section_block').innerHTML = "<div style=\"background-color:white;font-size:32px;height:32px;\"><img src=\"images/loading_icon/loading_form.gif\"/> One moment...</div>";

	new Ajax.Updater('section_block', '/management/sections/coupons/ajax_updater.php', {
		parameters: {sec:sec, editing:editing, bid:bus_id, id:bus_id},
		evalScripts:true
	});

	return false;
}

function openCouponWindow(cid, w, h, ext) {

	if (ext == 'pdf') {
		var cwin = window.open('/ajax_master.php?action=couponWindow&cid='+cid,'coupon', 'status=no,toolbar=no,location=no,resizable=yes,titlebar=no');

	} else {
		var cwin = window.open('/ajax_master.php?action=couponWindow&cid='+cid,'coupon', 'status=no,toolbar=no,location=no,resizable=yes,titlebar=no,width='+(w+50)+',height='+(h+50))

	}

}

function handleCouponTemplateChange() {
	if ($F('template') == "IMG") {
		$('coupon_body_div').hide();
		$('image_uploader').show()
		$('logo_offset_span').hide();
		$('coupon_body_div').hide();
		$('restrictions_row').hide();
		$('show_expiration').hide()
		$('no_show_expiration').show()

	} else {
		$('coupon_body_div').show();
		$('image_uploader').hide()
		$('logo_offset_span').show();
		$('coupon_body_div').show();
		$('restrictions_row').show();
		$('show_expiration').show()
		$('no_show_expiration').hide()

	}
}

function setEditCouponWindowLoadState(existingImg) {
	if (existingImg) {
		$('existing_image').show();
		$('upload_image').hide();
		$('image_uploader').show();
		$('coupon_body_div').hide();
		$('logo_offset_span').hide();
		$('restrictions_row').hide();
		$('show_expiration').hide()
		$('no_show_expiration').show()

	} else {
		$('existing_image').hide();
		$('upload_image').show();
		$('image_uploader').hide();
		$('coupon_body_div').show();
		$('logo_offset_span').show();
		$('restrictions_row').show();
		$('show_expiration').show()
		$('no_show_expiration').hide()

	}
}

function removeExistingCouponImage(cid) {
	new Ajax.Request('/ajax_master.php', {
		method: 'post',
		parameters: {action:'removeCouponImage', cid:cid},
		onSuccess: function(transport) {
			$('existing_image').hide();
			$('upload_image').show();

		},
		onFailure: function(transport) {
			alert("Unable to remove coupon image.")
		}
	});
}

//------------------------------------------------------------------------------------------
// Generic functions
//------------------------------------------------------------------------------------------

function reload_section(module, sec, editing, id) {
//	if (sec == 'default') {
//		$('bid').value = id
//	}
	if (editing == null) {
		editing = false;
	}
	if ($('detailFloater').visible()) {
		$('detailFloater').hide();
	}
	bus_id = $F('bid');
	$('section_block').innerHTML = "<div style=\"border:1px solid #aaa;display:block;clear:both;background-color:white;font-size:32px;height:32px;padding-bottom:10px;padding-top:5px;\"><img src=\"images/loading_icon/loading_form.gif\"/> One moment...</div>";

	new Ajax.Updater('section_block', '/management/'+module+'/index.php', {
		parameters: {sec:sec, editing:editing, bid:bus_id, id:id, action:'switch'},
		evalScripts:true
	});

	return false;
}

function deleteRecord(id, prefix, className, module) {
	ajax_delete(prefix, id, className, null, "/management/"+module+"/index.php");
}

function load_ajax_window(url, action, mid, from) {
	load_window(url+"?action="+action+"&bid="+$F('bid'), mid, from)
}

function handlePopupSubmit(module, sec, closeWindow, validate) {
	if (closeWindow == null)
		closeWindow = false
	if (validate != null) {
		formOK = validate()
		if (!formOK) {
			return false;
		}
	}
	$('form_submit').innerHTML = '<img src="images/loading_icon/loading_form.gif">';
  	new Ajax.Updater('window_content', '/management/'+module+'/index.php', {
		parameters: $('the_form').serialize(),
		onSuccess: function() {
			if (!closeWindow) {
				new Effect.Morph('add_alert', {style:'background:#FDFEA5; color:#000000;  border: 1px solid #F7E600;',duration:0.8});
				$('add_alert').innerHTML = '<strong>Success!</strong>';

				//Need custom anonymous function for clearing values
/*
				$('firstName').value = '';
				$('lastName').value = '';
				$('notes').value = '';
*/
			} else {
				close_window();
			}
			reload_section(module, sec, false);
		},
		onFailure: function(transport) {
			alert("An error occurred. " + transport.responseText)
		}
	});
	return false;
}



function editCustomer(id, sec, closeWindow) {
	if (closeWindow == null)
		closeWindow = false
	if (0) {
//	if (($F('type_name') == '') || ($F('type_window') == '')) {
//		alert('Don\'t forget to set a name and window for the reminder!');
		return false;

	} else {
		$('form_submit').innerHTML = '<img src="images/loading_icon/loading_form.gif">';
	  	new Ajax.Updater('window_content', '/management/reminders/index.php', {
			parameters: $('the_form').serialize(),
			onSuccess: function() {
				if (!closeWindow) {
					new Effect.Morph('add_alert', {style:'background:#FDFEA5; color:#000000;  border: 1px solid #F7E600;',duration:0.8});
					$('add_alert').innerHTML = '<strong>Success!</strong>';
					$('firstName').value = '';
					$('lastName').value = '';
					$('notes').value = '';
				} else {
					close_window();
				}
				reload_section('reminders', sec, false);
			},
			onFailure: function(transport) {
				alert("An error occurred. " + transport.responseText)
			}
		});
		return false;
	}
	return false;
}


function toggleRecordBlock(buttonID, buttonTxt, blockID) {
	if ($(blockID).visible()) {
//		$(blockID).fade({duration:.6})
		Effect.BlindUp(blockID,{duration:.3})
		$(buttonID).update("Show "+buttonTxt)
		$(buttonID).className = 'section_button_off'
	} else {
//		$(blockID).appear({duration:.6})
		Effect.BlindDown(blockID,{duration:.3})
		$(buttonID).update("Hide "+buttonTxt)
		$(buttonID).className = 'section_button'
	}
}

function makeCustomer(id) {
	new Ajax.Request('/management/reminders/index.php', {
		method: 'post',
		parameters: {action:'makeCustomer', rid:id, bid:$F('bid')},
		onSuccess: function(transport) {
			$('make_'+id).fade()
//			new Effect.Shrink(prefix+id);
		},
		onFailure: function(transport) {
			alert("An error occurred.")
		}
	});

}




//------------------------------------------------------------------------------------

	function reload_calendar(date, module) {

		if (module == null) {
			module = "reminders"
		}
		endDayFocus()

		$('calendarTitle').innerHTML = "<h2>One moment... <img src='/images/loading_icon/loading_div_transp.gif'/></h2>";
		$('calendarBody').setOpacity(.2)
		$('calendarHeader').setOpacity(.2)
		$('prevMonthControl').setOpacity(.2)
		$('nextMonthControl').setOpacity(.2)
		if ($('calendarPostit').visible()) {
			$('calendarPostit').setOpacity(.2)
		}

		new Ajax.Updater('sectionBody', '/management/'+module+'/index.php', {
			parameters: {action: 'changeCalendarView', date: date, bid:$F('bid')},
			onSuccess: function (transport) {
				if ($('calendarPostit').visible()) {
					$('calendarPostit').setOpacity(1)
				}
			},
			onFailure: function (transport) {
				alert('An unknown error occurred.')
			}
		});
	}


	//can also be called with one argument that is an object keyed by field
	function showDetailFloater(clonepos, title, msg, ol, ot, w, h, sw, sh) {
		if (typeof(clonepos) == 'object') {
			args = clonepos
			clonepos = args.clonepos
			title = args.title
			msg = args.msg
			ol = args.ol
			ot = args.ot
			w = args.w
			h = args.h
			sw = args.sw
			sh = args.sh
			animation = args.animation
			duration = args.duration
			borderStyle = args.borderStyle
			contentStyle = args.contentStyle
			hideClose = args.hideClose
			contentWidthReduction = args.contentWidthReduction
			contentHeightReduction = args.contentHeightReduction
			afterFinish = args.afterFinish
			var onclose = args.onclose
		}
		if (afterFinish == null) {
			afterFinish = function() {};
		}
		if (contentWidthReduction == null) {
			contentWidthReduction = 18
		}
		if (contentHeightReduction == null) {
			contentHeightReduction = 18
		}
		if (w == null) {
			w = 155;
		}
		if (h == null) {
			h = 145
		}
		if (ol == null) {
			ol = -15
		}
		if (ot == null) {
			ot = -15
		}
		if (sw == null) {
			sw = true
		}
		if (sh == null) {
			sh = true
		}
		if (duration == null) {
			duration = .3
		}

		if (onclose != null) {
			$('detailFloater').onclose = onclose;
		}

//		if (!Prototype.Browser.IE) {
			if (borderStyle != null) {
				$('detailFloater').setStyle(borderStyle)
			}
			if (contentStyle != null) {
				$('detailFloaterContent').setStyle(contentStyle)
			}
//		}

		if (!$('detailFloater').visible()) {
			$('detailFloater').clonePosition(clonepos, {offsetLeft:ol, offsetTop:ot, setWidth:sw, setHeight:sh})
			if (!sw) {
				$('detailFloater').setStyle({
					width:w+'px'
				})
			}
			if (!sh) {
				$('detailFloater').setStyle({
					height:h+'px'
				})
			}
			dim = $('detailFloater').getDimensions()
			$('detailFloaterContent').setStyle({
				width:(dim.width - contentWidthReduction)+'px',
				height:(dim.height - contentHeightReduction)+'px'

			})

			theContent = ""
			if (hideClose == null) {
				theContent += "<div class=\"windowCloseWidget\" onclick=\"hideFloater();\" style=\"margin-top:-4px;margin-right:-4px;\">&nbsp;</div>";

			}
			if ((title != null) && (title != "")) {
				theContent += "<div id=\"detailFloaterHeader\">"+title+"</div>";
			}
			theContent += msg;


			$('detailFloaterContent').update(theContent);

			if (animation == 'appear') {
				Effect.Appear('detailFloater', {duration:duration, afterFinish:afterFinish})

			} else {
				Effect.Grow('detailFloater', {duration:duration, afterFinish:afterFinish})
			}
		}

	}

	function showPostitNoteExplanation(title, msg,w,h) {
		if (w == null) {
			w = 155
		}
		if (h == null) {
			h = 145
		}
		if (!$('calendarDetails').visible()) {
			$('calendarDetails').clonePosition('calendarPostit', {offsetLeft:-45, offsetTop:-45, setWidth:false, setHeight:false})
			$('calendarDetails').setStyle({
				width:w+'px',
				height:h+'px'
			})
			$('calendarDetailsContent').setStyle({
				height:(h-15)+'px'
			})

			$('calendarDetailsContent').update("<a href=\"javascript:void(0);\" onclick=\"endDayFocus()\"><img src=\"/images/window_close_widget.png\" class=\"close_widget\"/></a><div style=\"font-weight:bold;font-size:10pt;\">"+title+"</div>"+msg)
			Effect.Grow('calendarDetails', {duration:.3})

		}
	}

	function calendarJump(module) {
		d = mktime(0, 0, 0, $F('jumpMonth'), 1, $F('jumpYear')) - 0;
		reload_calendar(d, module);
	}

	function mktime () {
	    // http://kevin.vanzonneveld.net
	    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +   improved by: baris ozdil
	    // +      input by: gabriel paderni
	    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +   improved by: FGFEmperor
	    // +      input by: Yannoo
	    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +      input by: jakes
	    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +   bugfixed by: Marc Palau
	    // +   improved by: Brett Zamir (http://brett-zamir.me)
	    // +      input by: 3D-GRAF
	    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
	    // *     example 1: mktime(14, 10, 2, 2, 1, 2008);
	    // *     returns 1: 1201871402
	    // *     example 2: mktime(0, 0, 0, 0, 1, 2008);
	    // *     returns 2: 1196463600
	    // *     example 3: make = mktime();
	    // *     example 3: td = new Date();
	    // *     example 3: real = Math.floor(td.getTime()/1000);
	    // *     example 3: diff = (real - make);
	    // *     results 3: diff < 5
	    // *     example 4: mktime(0, 0, 0, 13, 1, 1997)
	    // *     returns 4: 883609200
	    // *     example 5: mktime(0, 0, 0, 1, 1, 1998)
	    // *     returns 5: 883609200
	    // *     example 6: mktime(0, 0, 0, 1, 1, 98)
	    // *     returns 6: 883609200

	    var no=0, i = 0, ma=0, mb=0, d = new Date(), dn = new Date(), argv = arguments, argc = argv.length;

	    var dateManip = {
	        0: function (tt){ return d.setHours(tt); },
	        1: function (tt){ return d.setMinutes(tt); },
	        2: function (tt){ var set = d.setSeconds(tt); mb = d.getDate() - dn.getDate(); d.setDate(1); return set;},
	        3: function (tt){ var set = d.setMonth(parseInt(tt, 10)-1); ma = d.getFullYear() - dn.getFullYear(); return set;},
	        4: function (tt){ return d.setDate(tt+mb);},
	        5: function (tt){
	            if (tt >= 0 && tt <= 69) {
	                tt += 2000;
	            }
	            else if (tt >= 70 && tt <= 100) {
	                tt += 1900;
	            }
	            return d.setFullYear(tt+ma);
	        }
	        // 7th argument (for DST) is deprecated
	    };

	    for (i = 0; i < argc; i++){
	        no = parseInt(argv[i]*1, 10);
	        if (isNaN(no)) {
	            return false;
	        } else {
	            // arg is number, let's manipulate date object
	            if (!dateManip[i](no)){
	                // failed
	                return false;
	            }
	        }
	    }
	    for (i = argc; i < 6; i++) {
	        switch (i) {
	            case 0:
	                no = dn.getHours();
	                break;
	            case 1:
	                no = dn.getMinutes();
	                break;
	            case 2:
	                no = dn.getSeconds();
	                break;
	            case 3:
	                no = dn.getMonth()+1;
	                break;
	            case 4:
	                no = dn.getDate();
	                break;
	            case 5:
	                no = dn.getFullYear();
	                break;
	        }
	        dateManip[i](no);
	    }

	    return Math.floor(d.getTime()/1000);
	}


	function hideFloater(id, how, duration) {
		if (duration == null) {
			duration = .2
		}
		if (how == null) {
			how = "shrink"
		}
		if ($('detailFloater').visible()) {
			if (how == "shrink") {
				Effect.Shrink('detailFloater', {duration:duration})
			} else if (how == "puff") {
				Effect.Puff('detailFloater', {duration:duration})
			} else if (how == "hide") {
				$('detailFloater').hide();
			} else {
				Effect.Fade('detailFloater', {duration:duration})
			}
			var onclose = $('detailFloater').onclose;
			if (onclose != null) {
				onclose();
			}
		}
	}


	function endDayFocus(id, how) {
		if (how == null) {
			how = "shrink"
		}
		if ($('calendarDetails').visible()) {
			if (how == "shrink") {
				Effect.Shrink('calendarDetails', {duration:.2})
			} else if (how == "puff") {
				Effect.Puff('calendarDetails', {duration:.2})
			} else {
				Effect.Fade('calendarDetails', {duration:.2})
			}
		}
	}

	function toggleDayFocusFirePanel() {
		if ($('firingPanel').visible()) {
			Effect.BlindUp('firingPanel', {duration:.2})
		} else {
			Effect.BlindDown('firingPanel', {duration:.2})

		}
	}


var crossfade = {
	from: null,
	to: null,
	fromOpacity: {from: 1.0, to: 0.0},
	toOpacity: {from: 0.0, to: 1.0},
	fromDuration: 0.5,
	toDuration: 0.5,
	change: function(from, to)
	{
		/* optional method arguments */
		if (typeof(from) != "undefined") { this.from = from; }
		if (typeof(to) != "undefined") { this.to = to; }

		/* throw error if function has been called without from and to */
		if (this.from == null || this.to == null)
		{
			throw "Must have both to and from";
		}

		/* make sure we're dealing with DOM Elements */
		try
		{
			if (typeof(this.from) != "object" || typeof(this.to) != "object")
			{
				this.from = $(String(this.from));
				this.to = $(String(this.to));
			}
		}
		catch (e)
		{
			throw "Prototype is not loaded";
		}

		/* make sure to is hidden and has the same location as from */
		this.to.hide();
		this.from.absolutize();
		this.to.absolutize();
		this.to.clonePosition(this.from);

		/* attempt to cross fade Elements */
		try
		{
			/* fade out from */
			this.from.fade({duration: this.fromDuration, from: this.fromOpacity.from, to: this.fromOpacity.to});

			/* fade in to */
			this.to.appear({duration: this.toDuration, from: this.toOpacity.from, to: this.toOpacity.to});

			/* */
			var fromId = this.from.id;
			var toId = this.to.id;

			this.from.id = fromId + "temp";
			this.to.id = fromId;
			this.from.id = toId;

			/* remove from node */
/* 			this.to.parentNode.removeChild(this.from); */
			/* change to node's id to that of from node */
/* 			this.to.id = fromId; */
			/* add new to node */
/* 			var newTo = new Element('div'); */
			/* make sure it's hidden */
/* 			newTo.hide(); */
/* 			this.to.parentNode.appendChild(newTo); */
		}
		catch (e)
		{
			throw "Scriptaculous is not loaded";
		}
	}
};


function close_window2(how){
	if (how == null) {
		how = "shrink"
	}
	if ($('window').visible()) {
		if (how == "shrink") {
			Effect.Shrink('window', {duration:.4})

		} else if (how == "puff") {
			Effect.Puff('window', {duration:.4})

		} else if (how == "hide") {
			$('window').hide();

		} else if (how == "switchoff") {
			Effect.SwitchOff('window', {duration:.4})

		} else if (how == "fold") {
			Effect.Fold('window', {duration:.4})

		} else if (how == "dropout") {
			Effect.DropOut('window', {duration:.4})

		} else if (how == "squish") {
			Effect.Squish('window', {duration:.4})

		} else {
			Effect.Fade('window', {duration:.4})
		}
//		Effect.Fade('overlay', {queue:'end'});
		Effect.Fade('overlay', {duration:.6});

	}

}

function addHit(what, category, doAfter) {
	if (($$('input[name=id]').length) > 0) {
		id = $$('input[name=id]')[0].value;
	} else {
		id = "";
	}
	new Ajax.Request('/tracker.php', {
		method: 'post',
		parameters: {
			hit:what,
			category:category,
			id:id
		},
		onSuccess: function(transport) {
			if (doAfter != null) {
				doAfter();
			}
		},
		onFailure: function(transport) {
//			alert("An error occurred.")
		}
	})
}

function showVirginProfileContactPage() {

//	$('yacVirginIntro3').oldContent = $('yacVirginIntro3').innerHTML;

  	new Ajax.Updater('window', '/management/sections/contact.php', {
		parameters: {
			bid:$$('input[name=id]')[0].value
		},
		evalScripts:true,
		onLoaded: function() {
//			$('yacVirginIntro3').fadehide;
		},
		onInteractive: function() {
		},
		onComplete: function() {
			$('window').className = 'virginContact';
			$('window').appear({duration:.2});
			$('yacVirginIntro3').hide();
			$('overlay').show();

		},
		onFailure:function(transport) {
			alert('An error occurred: '+transport.responseText);
		}
	});
}

function hideVirginProfileContactPage() {
//	$('yacVirginIntro3').className = 'yacVirginIntro3Start yacVirginIntro';
//	$('yacVirginIntro3').innerHTML = $('yacVirginIntro3').oldContent;
	$('window').hide();
	$('yacVirginIntro3').show();
	$('overlay').hide();
}

function sendVirginContactForm() {
	var re = /\D/g;
	$('customerPhone').value = $F('customerPhone').replace(re,'');
	if ($F('customerName') && $F('customerEmail') && $F('customerPhone') && $F('customerMessage')) {

		if ($F('customerPhone').match(/^\d{10}$/)) {


			new Ajax.Request('/management/sections/contact.php', {
				method: 'post',
				parameters: {
					action			:'sendForm',
					mid				:$F('mid'),
					bid				:$F('bid'),
					customerName		:$F('customerName'),
					customerEmail		:$F('customerEmail'),
					customerPhone		:$F('customerPhone'),
					customerMessage	:$F('customerMessage')
				},
				onLoaded: function() {
				},
				onSuccess: function(transport) {
					alert('Your message was sent!');
					$('window').fade({duration:.2});
					$('overlay').hide();
				},
				onFailure: function(transport) {
					alert("An error occurred.")
				}
			});
		} else {
			alert('Please be sure to enter a 10-digit phone number.');
		}
	} else {
		alert("To send this contact form, please complete all the fields.");
	}

}


Event.observe(window, 'load', function() {
	$(document.body).insert('<div id="detailFloater" style="display:none;"><div id="detailFloaterContent"></div></div>')
});

function BeginSmartForm() {

	$$('[defaultValue]').each(	function(e) {
		$(e).setAttribute('defaultText', e.getAttribute('defaultValue'));
	})


	$$('[optional]').each(	function(e) {
		dv = e.getAttribute('defaultText')
		e.setAttribute('defaultText', dv+" (optional)");
	})

	$$('[defaultText]').each(	function (e) {
		$(e).addClassName("smartField")
		$(e).setAttribute('origDefaultText', $(e).getAttribute('defaultText'));

		if ($(e).getAttribute('doOnReturn') != "") {
			Event.observe(e, 'keypress', function(event) {
				if (event.keyCode == Event.KEY_RETURN) {
					eval($(e).getAttribute('doOnReturn'));
				}
			});
		}


		if ($F(e) == "") {
			$(e).value = $(e).getAttribute('defaultText');
			$(e).addClassName('defaultText');
		} else {
			if ($(e).getAttribute('smartType') == "password") {
				$(e).changeInputType('password', false);
			}

		}

		new Event.observe(e, 'focus', function(event) {
			if ($(e).hasClassName("defaultText")) {
				$(e).value = ""
				$(e).removeClassName("defaultText")
			}
			if ($(e).getAttribute('smartType') == "password") {
				$(e).setAttribute('defaultText', '');
				$(e).changeInputType('password', true);

			}

			if ($(e).getAttribute('onFirstClick') != "") {
				eval($(e).getAttribute('onFirstClick'));
				$(e).setAttribute('onFirstClick', '');
			}
			if ($(e).getAttribute('doOnClick') != "") {
				eval($(e).getAttribute('doOnClick'));
			}


		})
		new Event.observe(e, 'blur', function(event) {
			if ($(e).value == "") {
				$(e).setAttribute('defaultText', $(e).getAttribute('origDefaultText'));
				$(e).value = $(e).getAttribute('defaultText')
				if ($(e).getAttribute('smartType') == "password") {
					$(e).changeInputType('text', false);

				}
				if ($(e).getAttribute('doOnEmptyBlur') != "") {
					eval($(e).getAttribute('doOnEmptyBlur'));
				}
				$(e).addClassName("defaultText")
				$(e).removeClassName("textEntered")

//			} else {
//				$(e).addClassName("textEntered")

			}

		})
	})

}

function CheckSmartFormSubmit(returnObj, divID) {
	canSubmit = true;
	badFields = new Object();
	if (divID != null) {
		str = '#' + divID + ' [required]';
	} else {
		str = '[required]';
	}
	$$(str).each(	function(e) {
		if (($(e).value == "") || ($F(e) == $(e).getAttribute('defaultText'))) {
			badFields[e.id] = "bad";
			canSubmit = false;
			$(e).addClassName('badField');

		} else {
			$(e).removeClassName('badField');
		}
	})
	if (returnObj != null) {
		return {canSubmit:canSubmit, badFields:badFields};
	} else {
		return canSubmit;

	}

}

var mySmartFormMethods = {
	setToDefault: function(e, filter, value) {
		if (e.getAttribute('origDefaultText')) {
			$(e).setAttribute('defaultText', $(e).getAttribute('origDefaultText'));

			$(e).value = $(e).getAttribute('defaultText')
			$(e).addClassName("defaultText");
			$(e).removeClassName("textEntered");


			if ($(e).getAttribute('smartType') == "password") {
				newE = $(e).changeInputType('text', false);
				newE.value = $(e).getAttribute('defaultText')
				newE.addClassName("defaultText");
				newE.removeClassName("textEntered");
			}


			if ($(e).getAttribute('doOnEmptyBlur') != "") {
				eval($(e).getAttribute('doOnEmptyBlur'));
			}

		}
	},
	changeInputType: function(e, type, focus) {
		if (Prototype.Browser.IE) {
			Event.stopObserving(e);
			if (type == "text") {

				newE = new Element('input', {
					'name'			:e.getAttribute('name'),
					'id'				:e.getAttribute('id'),
					'type'			:'text',
					'defaultText'		:e.getAttribute('defaultText'),
					'required'		:e.getAttribute('required'),
					'optional'		:e.getAttribute('optional'),
					'smartType'		:e.getAttribute('smartType'),
					'origDefaultText'	:e.getAttribute('origDefaultText'),
					'onFirstClick'		:e.getAttribute('onFirstClick'),
					'doOnClick'		:e.getAttribute('doOnClick'),
					'doOnEmptyBlur'	:e.getAttribute('doOnEmptyBlur'),
					'onblur'			:e.getAttribute('onblur'),
					'onfocus'			:e.getAttribute('onfocus')
				});
				newE.value = e.value;

			} else if (type == "password") {
				newE = new Element('input', {
					'name'			:e.getAttribute('name'),
					'id'				:e.getAttribute('id'),
					'type'			:'password',
					'defaultText'		:e.getAttribute('defaultText'),
					'required'		:e.getAttribute('required'),
					'optional'		:e.getAttribute('optional'),
					'smartType'		:e.getAttribute('smartType'),
					'origDefaultText'	:e.getAttribute('origDefaultText'),
					'onFirstClick'		:e.getAttribute('onFirstClick'),
					'doOnClick'		:e.getAttribute('doOnClick'),
					'doOnEmptyBlur'	:e.getAttribute('doOnEmptyBlur'),
					'onblur'			:e.getAttribute('onblur'),
					'onfocus'			:e.getAttribute('onfocus')
				});
				newE.value = e.value;

			}
			e.replace(newE);
			if (focus) {
				newE.activate();
			}




			new Event.observe(newE, 'blur', function(event) {

				new Event.observe(newE, 'focus', function(event) {
					if (newE.hasClassName("defaultText")) {
						newE.value = ""
						newE.removeClassName("defaultText")
					}
					if (newE.getAttribute('smartType') == "password") {
						newE.setAttribute('defaultText', '');
						newE.changeInputType('password', true);

					}


					if (newE.getAttribute('onFirstClick') != "") {
						eval(newE.getAttribute('onFirstClick'));
						newE.setAttribute('onFirstClick', '');
					}
					if (newE.getAttribute('doOnClick') != "") {
						eval(newE.getAttribute('doOnClick'));
					}
				})

				if (newE.value == "") {
					newE.setAttribute('defaultText', e.getAttribute('origDefaultText'));
					newE.value = newE.getAttribute('defaultText')
					if (newE.getAttribute('smartType') == "password") {
						newE.changeInputType('text', false);

					}
					if (newE.getAttribute('doOnEmptyBlur') != "") {
						eval(newE.getAttribute('doOnEmptyBlur'));
					}
					newE.addClassName("defaultText")
					newE.removeClassName("textEntered")

	//			} else {
	//				$(e).addClassName("textEntered")

				}

			})
			return newE;


		} else {
			e.setAttribute('type', type);
			return e;

		}

	}
}
Element.addMethods('INPUT', mySmartFormMethods);

function handleChangeCRMEmployeeSelector(selector) {

	var parameters = $H({selectorID:selector.id, selectorValue:selector.value});
	$$('.CRMEmployeeSelector').each(function(e) {
		parameters.set(e.id, e.value);
	})
	parameters.set('goLink', $('CRMEmployeeSelectorLink').innerHTML);

	new Ajax.Updater('employeeSelector', '/employeeSelector.php', {
		parameters: parameters,
		onSuccess: function(transport) {
		},
		onFailure: function(transport) {
		}
	});
}

function CRMEmployeeSelector_selectedValue() {
	lastSelector = $$('.CRMEmployeeSelector').last();

	return lastSelector.value;
}

function CRMEmployeeSelector_allValues() {
	var vals = new Array();
	$$('.CRMEmployeeSelector').each(function(e) {
		vals.push(e.value);
	})

	return vals.join(":");
}

function CRMEmployeeSelector_addToHash(theHash) {
	$$('.CRMEmployeeSelector').each(function(e) {
		theHash.set(e.id, e.value);
	})
	return theHash;

}


function markPaymentAsBad(id) {
	new Ajax.Request('/sales/updater/markPaymentAsBad.php', {
		method: 'post',
		parameters: {
			id:id
		},
		onSuccess: function(transport) {
			var response = transport.responseText.evalJSON();
			if (response.status == "success") {
				$('bad_'+id).hide();
				$('date_'+id).update($('date_'+id).innerHTML + "<div style=\"color:red;\">" + response.date + " BAD</div>");
				$('row_'+id).setStyle({backgroundColor:'#F5E6E8'});
				$('amount_'+id).setStyle({textDecoration:'line-through'});
			} else {
				alert("An error occurred: "+response.reason);
			}
		},
		onFailure: function(transport) {
			alert('An error occurred');
		}
	});
}

function linkExistingEventToFacebook(eventid) {
	$('linkExistingEventToFacebook_link').hide();
	$('linkExistingEventToFacebook_progress').show();
	new Ajax.Request('/management/events/ajax/linkExistingEventToFacebook.php', {
		method: 'post',
		parameters: {
			eid:eventid
		},
		onSuccess: function(transport) {
			var response = transport.responseText.evalJSON();

			if (response.status == "success") {
				$('linkExistingEventToFacebook').hide();
				alert("This event has been sent to Facebook.");
			} else {
				$('linkExistingEventToFacebook_link').show();
				$('linkExistingEventToFacebook_progress').hide();
				alert("An error occurred: " + response.reason);
			}
		},
		onFailure: function(transport) {
			$('linkExistingEventToFacebook_link').show();
			$('linkExistingEventToFacebook_progress').hide();
			alert('An unknown error occurred.');
		}
	});
}


function linkExistingEventToFacebookWithDiv(eventid) {

	theDiv = $('event_'+eventid);

	$$('#event_'+eventid+' .linkExistingEventToFacebook_link')[0].hide();
	$$('#event_'+eventid+' .fbprogress')[0].show();
	new Ajax.Request('/management/events/ajax/linkExistingEventToFacebook.php', {
		method: 'post',
		parameters: {
			eid:eventid
		},
		onSuccess: function(transport) {
			var response = transport.responseText.evalJSON();

			if (response.status == "success") {
				$('event_'+eventid).hide();
				alert("The event has been sent to Facebook.");
			} else {
				$$('#event_'+eventid+' .linkExistingEventToFacebook_link')[0].show();
				$$('#event_'+eventid+' .fbprogress')[0].hide();
				alert("An error occurred: " + response.reason);
			}
		},
		onFailure: function(transport) {
			$$('#event_'+eventid+' .linkExistingEventToFacebook_link')[0].show();
			$$('#event_'+eventid+' .fbprogress')[0].hide();
			alert('An unknown error occurred.');
		}
	});
}

function _setDashboardType(v) {
	new Ajax.Request('/dashboard/ajax/changeType.php', {
		method: 'post',
		parameters: {
			version:v
		},
		onSuccess: function(transport) {
			var response = transport.responseText.evalJSON();

			if (response.status == "success") {
				alert("Your dashboard version has been changed. The next Dashboard page you load will be in version "+v);
			} else {
				alert("An error occurred: " + response.reason);
			}
		},
		onFailure: function(transport) {
			alert('An unknown error occurred.');
		}
	});
}

function setDashboardType(v, qs) {
	self.location.href = "/dashboard/ajax/changeType.php?version="+v+"&"+qs;
}

function switchDashboard15Biz(url,view,val) {
	if (val == "_add") {
		if (bizid = prompt("Enter the business ID you would like to add access for:")) {
			new Ajax.Request('/dashboard/ajax/quickAddVenueAdmin.php', {
				method: 'post',
				parameters: {
					business_id:bizid
				},
				onSuccess: function(transport) {
					var response = transport.responseText.evalJSON();

					if (response.status == "success") {
						window.location = url+'?view='+view+'&id='+bizid

					} else {
						alert("An error occurred: " + response.reason);
					}
				},
				onFailure: function(transport) {
					alert('An unknown error occurred.');
				}
			});

		}
	} else if (val == "_quick") {
		if (bizid = prompt("Enter the business ID you would like to access:")) {
			window.location = url+'?view='+view+'&id='+bizid
		}
	} else {
		window.location = url+'?view='+view+'&id='+val
	}
}

function uniqid (prefix, more_entropy) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kankrelune (http://www.webfaktory.info/)
    // %        note 1: Uses an internal counter (in php_js global) to avoid collision
    // *     example 1: uniqid();
    // *     returns 1: 'a30285b160c14'
    // *     example 2: uniqid('foo');
    // *     returns 2: 'fooa30285b1cd361'
    // *     example 3: uniqid('bar', true);
    // *     returns 3: 'bara20285b23dfd1.31879087'

    if (typeof prefix == 'undefined') {
        prefix = "";
    }

    var retId;
    var formatSeed = function (seed, reqWidth) {
        seed = parseInt(seed,10).toString(16); // to hex str
        if (reqWidth < seed.length) { // so long we split
            return seed.slice(seed.length - reqWidth);
        }
        if (reqWidth > seed.length) { // so short we pad
            return Array(1 + (reqWidth - seed.length)).join('0')+seed;
        }
        return seed;
    };

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    // END REDUNDANT
    if (!this.php_js.uniqidSeed) { // init seed with big random int
        this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
    }
    this.php_js.uniqidSeed++;

    retId  = prefix; // start with prefix, add current milliseconds hex string
    retId += formatSeed(parseInt(new Date().getTime()/1000,10),8);
    retId += formatSeed(this.php_js.uniqidSeed,5); // add seed hex string

    if (more_entropy) {
        // for more entropy we add a float lower to 10
        retId += (Math.random()*10).toFixed(8).toString();
    }

    return retId;
}

function toggleButtonLinkLoad(id, str, force) {
	if (str == null) {
		str = "Saving...";
	}
	if (($(id).oldHTML == null) || (force != null)) {
		if (force == null) {
			$(id).oldHTML = $(id).innerHTML;
		}
		$(id).update("<img src='/images/loading_icon/loading_circle_small.gif' class='buttonIcon'/>"+str);
	} else {
		$(id).update($(id).oldHTML);
		$(id).oldHTML = null;
	}

}