function validateEmail(email) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
        return true;
    }
    return false;
}
var tips = false;
function show_tips()
{
    if (!tips) {
        new Effect.BlindDown('show-hide');
        $('btn-tips').src = '/images/btn_hidetips.gif';
        tips = true;
    } else {
        new Effect.BlindUp('show-hide');
        $('btn-tips').src = '/images/btn_showtips.gif';
        tips = false;
    }

}   

var tooltip=function(){
	var id = 'tt';
	var top = 3;
	var left = 3;
	var maxw = 900;
	var speed = 10;
	var timer = 20;
	var endalpha = 95;
	var alpha = 0;
	var tt,t,c,b,h;
	var ie = document.all ? true : false;
	return{
		show:function(v,w){

			if(tt == null){
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				t = document.createElement('div');
				t.setAttribute('id',id + 'top');
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				b = document.createElement('div');
				b.setAttribute('id',id + 'bot');
				tt.appendChild(t);
				tt.appendChild(c);
				tt.appendChild(b);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				document.onmousemove = this.pos;
			}
			tt.style.display = 'block';
			c.innerHTML = v;
			tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie){
				t.style.display = 'none';
				b.style.display = 'none';
				tt.style.width = tt.offsetWidth;
				t.style.display = 'block';
				b.style.display = 'block';
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer);
		},
		pos:function(e){
			var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
			var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
			tt.style.top = (u - h) + 'px';
			tt.style.left = (l + left) + 'px';
		},
		fade:function(d){
			var a = alpha;
			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
				var i = speed;
				if(endalpha - a < speed && d == 1){
					i = endalpha - a;
				}else if(alpha < speed && d == -1){
					i = a;
				}
				alpha = a + (i * d);
				tt.style.opacity = alpha * .01;
				tt.style.filter = 'alpha(opacity=' + alpha + ')';
			}else{
				clearInterval(tt.timer);
				if(d == -1){tt.style.display = 'none'}
			}
		},
		hide:function(){
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
		}
	};
}();

function initAJAX() {
	var xmlhttp;
	if (window.XMLHttpRequest)  {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		// code for IE6, IE5
		xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
	}
	else { xmlhttp = false; }
	
	return xmlhttp;
}

// **************************
// **** Update Functions ****
// **************************
	
function updateContent(tab, page, company_id, appointment_id, timestamp, employee_id, service_id, start_time, end_time, signup_id) {
	
	if(page == undefined) page = "";
	if(company_id == undefined) company_id = "";
	if(appointment_id == undefined) appointment_id = "";
	if(timestamp == undefined) timestamp = "";
	if(employee_id == undefined) employee_id = "";
	if(service_id == undefined) service_id = "";
	if(signup_id == undefined) signup_id = "";

	var xmlhttp = initAJAX();

	// We submitted the page, so get all the element values
	if(page == "action" || page == "signup") {
		
		if(document.getElementById('client_id') == undefined) var client_id = "";  else var client_id = document.getElementById('client_id').value;
		if(signup_id != "") client_id = signup_id;

		var company_id = document.getElementById('company_id').value;
		var employee_id = document.getElementById('employee_id').value;
		var cal_date = document.getElementById('date').value;
		var start_time = document.getElementById('start_time').value;
		var end_time = document.getElementById('end_time').value;
		var service_id = document.getElementById('service_id').value;
		var message = document.getElementById('message').value;
		if(document.getElementById('send_notification') != undefined) var send_notification = document.getElementById('send_notification').checked;
		else var send_notification = "send_notification=0";
		if(tab == "client") var auto_confirm = document.getElementById('auto_confirm').checked; 
		else var auto_confirm = "0";
		if(tab == "company" && document.getElementById('cancellation_list') != undefined) var cancellation_list = document.getElementById('cancellation_list').checked;
		else var cancellation_list = "0";
		if(tab == "company" && $('#coupon_type').val() != undefined) var coupon_type = $('#coupon_type').val();
		else var coupon_type = "";
		if(tab == "company" && $('#coupon_code').val() != undefined) var coupon_code = $('#coupon_code').val();
		else var coupon_type = "";
		
		message = message.replace("%","``_25_``");
		
		values = "&employee_id=" + employee_id + "&cal_date=" + cal_date + "&start_time=" + start_time + "&end_time=" + end_time + "&service_id=" + service_id + "&message=" + message + "&send_notification=" + send_notification + "&auto_confirm=" + auto_confirm + "&cancellation_list=" + cancellation_list + "&coupon_type=" + coupon_type + "&coupon_code=" + coupon_type;

		/* Call a function here doesn't seem to work, so here is all the code */
		// Split into date and time
		var dateTime = cal_date + " " + start_time;
		var dt = dateTime.split(" ");
		var _date = dt[0];
		var _time = dt[1];
		
		// Split date into month, day and year
		var _d = _date.split("/");
		var month = _d[0] - 1; 
		var day = _d[1];
		var year = _d[2];
		// Split time into hour, minutes and dayPart
		var _t = _time.split(":");
		var hour = _t[0];
		var minute = _t[1].substring(0,2);
		var dayPart = _t[1].substring(3,2);
		var second = 0;		
		
		// Add 12 to hour if PM
		if(hour > 12 && dayPart == "P") hour = hour + 12;
		
		// 12 AM should be 00
		if(hour == 12 && dayPart == "A") hour = 0;
		
		var tzOffset = 28800; // PST
		var humDate = new Date(year, month, day, hour, minute, second);

		var _date = ((humDate.getTime() / 1000) + tzOffset);
		/* EOC */
		//var _date = parseDate(document.getElementById('date').value + " " + document.getElementById('start_time').value,"m/d/Y h:iA");
		
		xmlhttp.onreadystatechange=function() {
			
				if(xmlhttp.readyState==4) {
					
					// Update the popup
					document.getElementById('popup_content').innerHTML=xmlhttp.responseText;									
      	
					// Update parent content
					
					var sPath = parent.window.location.pathname;
					var sSearch = parent.window.location.search;
					
					// If we are on weekly
					if(sPath.search("weekly.php") > -1) {
						// We are on a company calendar
						if(sSearch.search("company_id") > -1) {
							parent.updateMonthlyCalendar('', _date, company_id, employee_id, service_id);
							parent.updateWeeklyCalendar('', _date, company_id, employee_id, service_id);
						}
						// Personal Calendar
						else {
							parent.updateMyMonthlyCalendar(_date);
							parent.updateMyWeeklyCalendar(_date);
						}
  				
					}
					// If we are on daily
					else if(sPath.search("scheday.php") > -1) {
						// We are on a company calendar
						if(sSearch.search("company_id") > -1) {
							parent.updateMonthlyCalendar('', _date, company_id, employee_id, service_id);
							parent.updateDailyCalendar('', _date, company_id, employee_id, service_id);
						}
						// Personal Calendar
						else {
							parent.updateMyMonthlyCalendar(_date);
							parent.updateMyDailyCalendar(_date);
						}
					}
					// If we are on index
					else if(sPath.search("index.php") > -1) {
						parent.updateIndexCounts();
					}
					// If we are on appointments
					else if(sPath.search("appointments.php") > -1) {
						parent.updateAppointments();
					}				
					// Update top menu bookings number
					if(parent.document.getElementById("num_bookings") != undefined) parent.updateCounts();				
					
					// If we just signed in with the quick book, change the top menu
					//if(page == "action") parent.updateHeader();
					
					// If scheduled on the facebook app
					if(parent.booka != undefined && tab == "company") {											  
						document.getElementById('fbPost').innerHTML = "Post to Facebook <a href='#' onclick='parent.booka.appointment("+company_id+"); document.getElementById(\"fbPost\").innerHTML=\"Success!\"'><img style='border:none; vertical-align:bottom' src='http://booka.me/images/fbIcon.png'></a>";
					}

				}    
			
		}
		xmlhttp.open('GET','update_content.php?tab=' + tab + '&page=' + page + '&appointment_id=' + appointment_id + values + '&client_id=' + client_id + '&company_id=' + company_id,true);
		if(document.getElementById('btn_finish') != undefined) {
			document.getElementById('btn_finish').disabled='disabled'; 
			document.getElementById('btn_finish').src='images/btn_cant_finish.png'; 
			document.getElementById('btn_finish').style.cursor = 'default';
		}
		xmlhttp.send(null);
		
		
	}
	else if(page == "login") {

		if(document.getElementById('client_id') == undefined) client_id = ""; else client_id = document.getElementById('client_id').value;
		if(signup_id != "") client_id = signup_id;
		company_id = document.getElementById('company_id').value;
		employee_id = "employee_id=" + document.getElementById('employee_id').value;
		cal_date = "cal_date=" + document.getElementById('date').value;
		start_time = "start_time=" + document.getElementById('start_time').value;
		end_time = "end_time=" + document.getElementById('end_time').value;
		service_id = "service_id=" + document.getElementById('service_id').value;
		message = "message=" + document.getElementById('message').value;
		auto_confirm = "auto_confirm=0";
		
		
		values = "&" + employee_id + "&" + cal_date + "&" + start_time + "&" + end_time + "&" + service_id + "&" + message + "&" + send_notification + "&" + auto_confirm;

	
		xmlhttp.onreadystatechange=function() {
			if(xmlhttp.readyState==4) {
				document.getElementById('popup_content').innerHTML="";
				document.getElementById('popup_content').innerHTML=xmlhttp.responseText;
				
			}
		}
		xmlhttp.open('GET','update_content.php?tab=' + tab + '&page=' + page + '&appointment_id=' + appointment_id + values + '&client_id=' + client_id + '&company_id=' + company_id,true);
		xmlhttp.send(null);		
	}
	else {
	
		xmlhttp.onreadystatechange=function() {
			if(xmlhttp.readyState==4) {
   			
				document.getElementById('popup_content').innerHTML="";
				document.getElementById('popup_content').innerHTML=xmlhttp.responseText;
				
				if(page == "manage" || page == "schedule") {

   				var script = document.createElement("script");
   				script.setAttribute("type","text/javascript");
   				var script_to_add = "function enable_finish() { " + (timestamp == -1 ? "return false;" : "") + "if(document.getElementById('start_time').value == '') return false; if(document.getElementById('client_id') != undefined) { if(document.getElementById('client_id').value = '') return false; } document.getElementById('btn_finish').disabled = false; document.getElementById('btn_finish').src='images/btn_finish.png'; document.getElementById('btn_finish').style.cursor='cursor'; }	";
   				if(tab == "reschedule" || tab == "company") script_to_add = script_to_add +  "getDaysHours(document.getElementById('date').value, document.getElementById('start_time').value, document.getElementById('company_id').value, document.getElementById('employee_id').value, document.getElementById('service_id').value, document.getElementById('tab').value, document.getElementById('appointment_id').value);";
   				if(tab == "company") script_to_add = script_to_add +  "updateServices(document.getElementById('company_id').value,document.getElementById('client_id').value,'',true); ";
   				script_to_add = script_to_add +  "getContactDetails('"+tab+"', '"+company_id+"', '"+appointment_id+"', '" + tab + "');";
   				
   				script.text = script_to_add;
   				var head = document.getElementsByTagName("head")[0];
   				head.appendChild(script);

					//top.Shadowbox.open({content:'update_content.php?tab=' + tab + '&page=' + page + '&id=' + appointment_id,player:"iframe",title:"Manage Appointment",height:337,width:718});
				}
			}
		}
		//alert('update_content.php?tab=' + tab + '&page=' + page + '&appointment_id=' + appointment_id + '&timestamp=' + timestamp + '&employee_id=' + employee_id + '&service_id=' + service_id);
		xmlhttp.open('GET','update_content.php?tab=' + tab + '&page=' + page + '&company_id=' + company_id + '&appointment_id=' + appointment_id + '&timestamp=' + timestamp + '&employee_id=' + employee_id + '&service_id=' + service_id,true);
		xmlhttp.send(null);
		
		
	}
	
}

function updateServices(company_id, client_id, service_id, booking) {

	if(booking == undefined) booking = true;
	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			
			document.getElementById("service_details_select").innerHTML=xmlhttp.responseText;
		}
	}
	//alert('update_services.php?company_id=' + company_id + '&client_id=' + client_id + '&service_id=' + service_id + '&booking=' + booking);
	xmlhttp.open('GET','update_services.php?company_id=' + company_id + '&client_id=' + client_id + '&service_id=' + service_id + '&booking=' + booking);
	xmlhttp.send(null);		
}

function checkLogin(login_id, passwrd) {
	document.getElementById("btn_login").disabled = true;
	document.getElementById("btn_login").style.cursor = "default";
	document.getElementById("btn_login").src = "images/btn_cant_login.png";
	
	var login_xmlhttp = initAJAX();
	login_xmlhttp.onreadystatechange=function() {
		if(login_xmlhttp.readyState==4) {	
			if(login_xmlhttp.responseText.search("error") > -1) {
				document.getElementById("login_info").innerHTML = "<font color=red>" + login_xmlhttp.responseText + ". Please try to log on again.</font>";
				document.getElementById("login_id").value = "";
				document.getElementById("passwrd").value = "";
				document.getElementById("login_id").focus();
				document.getElementById("btn_login").disabled = false;
				document.getElementById("btn_login").style.cursor = "cursor";
				document.getElementById("btn_login").src = "images/btn_login.png";
			}
			else updateContent('company','action',gup('company_id'),'','',gup('employee_id'),gup('service_id'),gup('start_time'),gup('end_time'),login_xmlhttp.responseText);
		}
	}
	login_xmlhttp.open('GET','login.php?login_id=' + document.getElementById('login_id').value + '&passwrd=' + document.getElementById('passwrd').value + '&book');
	login_xmlhttp.send(null);
	
	
}

function updateMonthlyCalendar(minisite_name, _date, company_id, employee_id, service_id) {
	document.getElementById("monthly_calendar").innerHTML="<div style='padding: 57px;'><img src='images/loading.gif'></div>";
	
	if(minisite_name == undefined) minisite_name = "";
	if(_date == undefined) _date = "";
	if(company_id == undefined) company_id = "";
	if(employee_id == undefined) employee_id = "";
	if(service_id == undefined) service_id = "";

	// Update monthly calendar
	var monthly_xmlhttp = initAJAX();
	monthly_xmlhttp.onreadystatechange=function() {
		if(monthly_xmlhttp.readyState==4) {				
			document.getElementById("monthly_calendar").innerHTML=monthly_xmlhttp.responseText;
		}
	}
	monthly_xmlhttp.open('GET','update_parent_content.php?monthly&date=' + _date + '&company_id=' + company_id + '&employee_id=' + employee_id + '&service_id=' + service_id + '&name=' + minisite_name);
	monthly_xmlhttp.send(null);
	
}

function updateMyMonthlyCalendar(_date) {
	document.getElementById("monthly_calendar").innerHTML="<div style='padding: 57px;'><img src='images/loading.gif'></div>";
	if(_date == undefined) _date = "";
	
	// Update monthly calendar
	var monthly_xmlhttp = initAJAX();
	monthly_xmlhttp.onreadystatechange=function() {
		if(monthly_xmlhttp.readyState==4) {				
			document.getElementById("monthly_calendar").innerHTML=monthly_xmlhttp.responseText;
		}
	}
	monthly_xmlhttp.open('GET','update_client_content.php?monthly&date=' + _date);
	monthly_xmlhttp.send(null);
	
}

function updateHeader(user_id) {
 return false;
	// Update header
	var header_xmlhttp = initAJAX();
	header_xmlhttp.onreadystatechange=function() {
		if(header_xmlhttp.readyState==4) {				
			document.getElementById("header").innerHTML=header_xmlhttp.responseText;
		}
	}
	header_xmlhttp.open('GET','update_parent_content.php?header&login_id=' + user_id);
	header_xmlhttp.send(null);
	
}

function updateWeeklyCalendar(minisite_name, _date, company_id, employee_id, service_id) {

	document.getElementById("weekly_calendar").innerHTML="<div style='text-align:center; padding-top:50px; padding-bottom:50px'><img src='images/loading.gif'></div>";
	if(minisite_name == undefined) minisite_name = "";
	if(_date == undefined) _date = "";
	if(company_id == undefined) company_id = "";
	if(employee_id == undefined) employee_id = "";
	if(service_id == undefined) service_id = "";

	if(minisite_name == undefined) minisite_name = "";

	// Update monthly calendar
	var weekly_xmlhttp = initAJAX();
	weekly_xmlhttp.onreadystatechange=function() {
		if(weekly_xmlhttp.readyState==4) {				
			document.getElementById("weekly_calendar").innerHTML=weekly_xmlhttp.responseText;
			if(document.getElementById("weekly_calendar_shadow") != undefined) 
				document.getElementById("weekly_calendar_shadow").style.height = document.getElementById("weekly_calendar").offsetHeight + "px";
			if(document.getElementById("calendar_content") != undefined) 
				document.getElementById("calendar_content").style.height = (document.getElementById("weekly_calendar").offsetHeight + 100) + "px";
		}
		
	}
	weekly_xmlhttp.open('GET','update_parent_content.php?weekly&date=' + _date + '&company_id=' + company_id + '&employee_id=' + employee_id + '&service_id=' + service_id + '&name=' + minisite_name);
	weekly_xmlhttp.send(null);
	
}

function updateMyWeeklyCalendar(_date) {
	document.getElementById("weekly_calendar").innerHTML="<div style='text-align:center; padding-top:50px; padding-bottom:50px'><img src='images/loading.gif'></div>";
	if(_date == undefined) _date = "";
	
	// Update weekly calendar
	var weekly_xmlhttp = initAJAX();
	weekly_xmlhttp.onreadystatechange=function() {
		if(weekly_xmlhttp.readyState==4) {				
			document.getElementById("weekly_calendar").innerHTML=weekly_xmlhttp.responseText;
			if(document.getElementById("weekly_calendar_shadow") != undefined) 
				document.getElementById("weekly_calendar_shadow").style.height = document.getElementById("weekly_calendar").offsetHeight + "px";
			if(document.getElementById("calendar_content") != undefined) 
				document.getElementById("calendar_content").style.height = (document.getElementById("weekly_calendar").offsetHeight + 100) + "px";
		}
		
	}
	weekly_xmlhttp.open('GET','update_client_content.php?weekly&date=' + _date);
	weekly_xmlhttp.send(null);
	
}

function updateDailyCalendar(minisite_name) {
	document.getElementById("daily_calendar").innerHTML="<div style='text-align: center; padding-top: 50px; padding-bottom: 50px;'><img src='images/loading.gif'></div>";
	if(minisite_name == undefined) minisite_name = "";
	// Update daily calendar
	var daily_xmlhttp = initAJAX();
	daily_xmlhttp.onreadystatechange=function() {
		if(daily_xmlhttp.readyState==4) {				
			document.getElementById("daily_calendar").innerHTML=daily_xmlhttp.responseText;
			if(document.getElementById("daily_calendar_shadow") != undefined) 
				document.getElementById("daily_calendar_shadow").style.height = document.getElementById("daily_calendar").offsetHeight + "px";
			if(document.getElementById("calendar_content") != undefined) 
				document.getElementById("calendar_content").style.height = (document.getElementById("daily_calendar").offsetHeight + 100) + "px";
		}
	}
	daily_xmlhttp.open('GET','update_parent_content.php?daily&date=' + gup('date') + '&company_id=' + gup('company_id') + '&employee_id=' + gup('employee_id') + '&service_id=' + gup('service_id') + '&name=' + minisite_name);
	daily_xmlhttp.send(null);
	
}

function updateMyDailyCalendar(_date) {
	document.getElementById("daily_calendar").innerHTML="<div style='text-align: center; padding-top: 50px; padding-bottom: 50px;'><img src='images/loading.gif'></div>";
	// Update daily calendar
	var daily_xmlhttp = initAJAX();
	daily_xmlhttp.onreadystatechange=function() {
		if(daily_xmlhttp.readyState==4) {				
			document.getElementById("daily_calendar").innerHTML=daily_xmlhttp.responseText;
			if(document.getElementById("daily_calendar_shadow") != undefined) 
				document.getElementById("daily_calendar_shadow").style.height = document.getElementById("daily_calendar").offsetHeight + "px";
			if(document.getElementById("calendar_content") != undefined) 
				document.getElementById("calendar_content").style.height = (document.getElementById("daily_calendar").offsetHeight + 100) + "px";
		}
	}
	daily_xmlhttp.open('GET','update_client_content.php?daily&date=' + _date);
	daily_xmlhttp.send(null);
	
}

function updateIndexCounts() {
	
	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			
			document.getElementById("index_bookings").innerHTML=xmlhttp.responseText;
		}
	}
	xmlhttp.open('GET','update_parent_content.php?index');
	xmlhttp.send(null);
	
}

function updateCounts() {
	
	
	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			
			document.getElementById("num_bookings").innerHTML=xmlhttp.responseText;
		}
	}
	xmlhttp.open('GET','update_counts.php');
	xmlhttp.send(null);
	
}

function updateNotes(note_about, note_taker, notes) {

	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			
			parent.document.getElementById("notes_header").innerHTML=xmlhttp.responseText;
		}
	}

	notes = notes.replace(/\n/g,'<br>');
	notes = notes.replace("%","``_25_``");
	xmlhttp.open('GET','update_notes.php?note_about=' + note_about + '&note_taker=' + note_taker + '&notes=' + notes);
	xmlhttp.send(null);
		
}

function updateAppointments() {
	
	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			
			document.getElementById("content").innerHTML=xmlhttp.responseText;
		}
	}
	xmlhttp.open('GET','update_parent_content.php?appointments');
	xmlhttp.send(null);
		
}

// ***********************************
// **** Get Information Functions ****
// ***********************************

function getDaysHours(day, cal_time, company_id, employee_id, service_id, tab, appointment_id, client_id) {
	
	if(appointment_id == undefined) appointment_id = "";
	var xmlhttp = initAJAX();
	
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			document.getElementById('div_time').innerHTML=xmlhttp.responseText;
			
			if(xmlhttp.responseText.search("Closed") > -1) {
				document.getElementById('btn_finish').disabled = true; 
				document.getElementById('btn_finish').src='images/btn_cant_finish.png';
				document.getElementById('btn_finish').style.cursor='default';
			}
			
			enable_finish();
		}
	}
	//alert('get_day_hours.php?date=' + day + '&start_time=' + cal_time + '&company_id=' + company_id + '&employee_id=' + employee_id + '&service_id=' + service_id + '&tab=' + tab + "&appointment_id=" + appointment_id + "&client_id=" + client_id,true);
	xmlhttp.open('GET','get_day_hours.php?date=' + day + '&start_time=' + cal_time + '&company_id=' + company_id + '&employee_id=' + employee_id + '&service_id=' + service_id + '&tab=' + tab + "&appointment_id=" + appointment_id + "&client_id=" + client_id,true);
	xmlhttp.send(null);
	
}

function getContactDetails(type, contact_id, appointment_id, tab) {
	
	if(appointment_id == undefined) appointment_id = "";
	if(tab == undefined) tab = "confirmed";
	
	if(contact_id == "") document.getElementById('contact_details').innerHTML="";
	var xmlhttp2 = initAJAX();
	
	xmlhttp2.onreadystatechange=function() {
		if(xmlhttp2.readyState==4) {
			document.getElementById('contact_details').innerHTML=xmlhttp2.responseText;
		}
	}
	//alert('get_contact_details.php?type=' + type + '&id=' + contact_id + "&appointment_id=" + appointment_id + "&tab=" + tab);
	xmlhttp2.open('GET','get_contact_details.php?type=' + type + '&id=' + contact_id + "&appointment_id=" + appointment_id + "&tab=" + tab,true);
	xmlhttp2.send(null);
	
}

function updateDayCounts(date_timestamp) {
	//alert("Updated");

	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			
			parent.document.getElementById("date_" + date_timestamp).innerHTML=xmlhttp.responseText;
		}
	}
	xmlhttp.open('GET','update_counts.php?date=' + date_timestamp);
	xmlhttp.send(null);
	
}

// **********************************
// **** Admin Approval Functions ****
// **********************************

function approveBusinessType(business_type_id) {

	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			
			if(xmlhttp.responseText == "OK") parent.document.getElementById("approved_" + business_type_id).src="images/sign_tick.png";
		}
	}
	xmlhttp.open('GET','approve_business_type.php?id=' + business_type_id);
	xmlhttp.send(null);
		
}

function approveMinisite(company_id) {

	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			
			if(xmlhttp.responseText == "OK") parent.document.getElementById("approved_" + company_id).src="images/sign_tick.png";
		}
	}
	xmlhttp.open('GET','approve_minisite.php?id=' + company_id);
	xmlhttp.send(null);
		
}


// Make sure the field is formatted correctly
function validateField(field) {
	
	// English names of fields
	fieldNames = new Array();			
	fieldNames['first_name'] = "First Name";
	fieldNames['last_name'] = "Last Name";
	fieldNames['phone'] = "Phone";
	fieldNames['email'] = "Email";
	
	
	// Default Values
	fieldDefaults = new Array();
	fieldDefaults['first_name'] = "first name";
	fieldDefaults['last_name'] = "last name";
	fieldDefaults['phone'] = "phone number";
	fieldDefaults['email'] = "email address";

	
	// Valid Formats
	fieldFormat = new Array();
	fieldFormatText = new Array();
	
	
	fieldFormat['phone'] = /\d{3}\-\d{3}\-\d{4}/;
	fieldFormatText['phone'] = "Use the fomat 'XXX-XXX-XXXX'";
	
	fieldFormat['email'] = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/;
	fieldFormatText['email'] = "Use the fomat 'user@host.ext'";
	
	// Check if field is blank
	if(document.getElementById(field).value == "") {
		alert("You must specify a '" + fieldNames[field] + "'");
		return false;
	}
	
	// Check if field has default value
	if(document.getElementById(field).value == fieldDefaults[field]) {
		alert("You must specify a '" + fieldNames[field] + "'");
		return false;
	}
	
	// Check if field is formatted correctly
	if(fieldFormat[field] != undefined) {
		if(!document.getElementById(field).value.match(fieldFormat[field])) {
			alert("Please enter a valid " + fieldNames[field] + ".  " + fieldFormatText[field]);
			return false;
		}
	}
	
	return true;

}

// Submit Quick Signup Form
function submitQSForm() {
	
	// Remove non-numeric's from phone
	var new_phone = document.getElementById("phone").value.replace(/[^\d]/g,'');
	
	// Add in dashes in appropriate locations
	
	if(new_phone.length == 10) {
		new_phone = new_phone.substr(0,3) + "-" + new_phone.substr(3,3) + "-" + new_phone.substr(6,4);
		document.getElementById("phone").value = new_phone;
	}
	
	// Validate Fields
	if(!validateField("first_name")) return false;
	if(!validateField("last_name")) return false;
	if(!validateField("phone")) return false;
	if(!validateField("email")) return false;
	
	// Book time and add user if needed
	var xmlhttp = initAJAX();
	xmlhttp.open('GET','quick_signup.php?first_name=' + document.getElementById('first_name').value + '&last_name=' + document.getElementById('last_name').value + '&phone=' + document.getElementById('phone').value + '&email=' + document.getElementById('email').value + '&captcha=' + document.getElementById('captcha').value + '&employee_id=' + document.getElementById('employee_id').value);
	xmlhttp.send(null);
	

	xmlhttp.onreadystatechange=function() {
			if(xmlhttp.readyState==4) {
					
				if(xmlhttp.responseText.search("error") > -1) {
					document.getElementById('btn_finish').disabled = false; 
					if(xmlhttp.responseText.search("email") > -1) {					
						document.getElementById('email_error').innerHTML=xmlhttp.responseText;
						document.getElementById('email_error').style.display = "block";
					}
					else if(xmlhttp.responseText.search("Captcha") > -1) {					
						document.getElementById('captcha_error').innerHTML=xmlhttp.responseText.replace("error: ","");
						document.getElementById('captcha_error').style.display = "block";
					}
				}
				else if(xmlhttp.responseText.search("login") > -1) {
					user_id = xmlhttp.responseText.replace("login ","");
					updateContent('login','login',document.getElementById('company_id').value,'','',document.getElementById('employee_id').value,document.getElementById('service_id').value,document.getElementById('start_time').value,document.getElementById('end_time').value,user_id)
				}
				else updateContent('company','action',document.getElementById('company_id').value,'','',document.getElementById('employee_id').value,document.getElementById('service_id').value,document.getElementById('start_time').value,document.getElementById('end_time').value,xmlhttp.responseText);
			}
		}
		
		
	                                                                                             
			                                                                                         
}	                                                                                             

// returns $_GET value of name
function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( top.window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

// Check if Account type has been upgraded
function checkAccountType(company_id) {
	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			if(xmlhttp.responseText.search("Premium") > -1) {			
				document.getElementById("col-right").innerHTML=xmlhttp.responseText;
			}
		}
	}
	xmlhttp.open('GET','check_account_type.php?company_id=' + company_id);
	xmlhttp.send(null);
		
}


 /*
 function unixtimetodate() {
 	var theDate = new Date(get_eid('unixtimestamp').value * 1000);
 	var utc = document.getElementById('utc2').checked;
 	//console.log("UTC2: " + utc);
 	
 	// This creates a unixtime in UTC
 	if (utc) {
 	dateString = theDate.toGMTString();
 	// This creates a unixtime in localtime (accounting for the local timezone)
 	} else {
 	dateString = theDate.toLocaleString();
 	}
 	
 	get_eid('output2').value = dateString;
 	
 	return false;
 }
 */

// Date functions
function dateToUnixTime(year, month, day, hour, minute, second) {

	var tzOffset = 28000; // PST
	var humDate = new Date(year, month, day, hour, minute, second);

	return ((humDate.getTime() / 1000.0)  - tzOffset);
}


function parseDate(dateTime, inputFormat) {
	if(inputFormat == "m/d/Y h:iA") {
		// Split into date and time
		var dt = dateTime.split(" ");
		var _date = dt[0];
		var _time = dt[1];
		
		// Split date into month, day and year
		_d = _date.split("/");
		month = _d[0] - 1;
		day = _d[1];
		year = _d[2];
		// Split time into hour, minutes and dayPart
		_t = _time.split(":");
		hour = _t[0];
		minute = _t[1].substring(0,2);
		dayPart = _t[1].substring(3,2);
		second = 0;
		
		
		// Add 12 to hour if PM
		if(hour > 12 && dayPart == "P") hour = hour + 12;
		
		// 12 AM should be 00
		if(hour == 12 && dayPart == "A") hour = 0;
		
	}
	
	return dateToUnixTime(year, month, day, hour, minute, second);
}


 
/******/
function getCompanyInfo(company_id) {
	var xmlhttp = initAJAX();
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {				
			return xmlhttp.responseText;
		}
	}
	xmlhttp.open('GET','http://booka.me/get_company_info.php?company_id=' + company_id);
	xmlhttp.send(null);
	
}

function changeClient(client_id, company_id, tab) {
	
	if(client_id == 'new') { 
		parent.doLightBox('Invite A Client','quick_signup.php?invite&schedule&date=' + document.getElementById('date').value + '&time=' + document.getElementById('start_time').value + '&service_id=' + document.getElementById('service_id').value + '&employee_id=' + document.getElementById('employee_id').value,'260','350'); 
		return false; 
	} 
	else { 
		updateServices(company_id, client_id, document.getElementById('service_id').value);
	 } 
	 enable_finish(); 
	 if(this.value < -0) { 
	 	getContactDetails('class',client_id);
	 } 
	 else { 
	 	getContactDetails('client',client_id);
	 } 
	 
	 getDaysHours(document.getElementById('date').value, document.getElementById('start_time').value, company_id, document.getElementById('employee_id').value, document.getElementById('service_id').value, tab, document.getElementById('appointment_id').value,client_id);	
	 
}

// Login on the quick signup screen
function qsLogin() {
	var params = "login_id="+$("#login_id").val()+"&passwrd="+$("#passwrd").val()+"&book=true";
	
	// Set the login-message
	$("#login-message").html("<span style='color:#0f4;'>Checking Login...</span>");
	
	// Check the login
	$.ajax({type:"POST",url:"login.php",data:params,dataType:"json",success:qsLoginReturn}); 
}

function qsLoginReturn(json) {
	if(json.success) {
		updateLogin();
		updateMenu();
		updateContent('company','action',$('#company_id').val(),'','',$('#employee_id').val(),$('#service_id').val(),$('#start_time').val(),$('#end_time').val(),json.login_id);
	}
	else $("#login-message").html("<span style='color:#f00;'>Login Failed</span>");
}

/** Booka Button functions **/
function disableBookaButton(id) { 
	$("#"+id).css({"cursor":"default"});
	$("#"+id+" .booka-btn-disabled").show();
	$("#"+id+" .booka-btn-gloss").hide();
};

function enableBookaButton(id) { 
	$("#"+id).css({"cursor":"pointer"});
	$("#"+id+" .booka-btn-disabled").hide();
	$("#"+id+" .booka-btn-gloss").show();
};

function createBookaButton(location) {
	if(typeof(location) == "undefined") location = "";
	
	$(location+" .booka-btn").prepend("<div class='booka-btn-disabled'></div><div class='booka-btn-gloss'></div>");		
	$(location+" .booka-btn").attr("unselectable","on");
	
	$(location+" .booka-btn").click(function() {
		if($("#"+$(this).attr("id")+" .booka-btn-disabled").css("display") == "none")	eval($(this).attr('clicked'));
	});
	
	$(location+" .booka-btn").mouseover(function() { 
		if($("#"+$(this).attr("id")+" .booka-btn-disabled").css("display") == "none")	$(this).css("background-image","-moz-radial-gradient(center 45deg, circle closest-corner, #f3a350 0%, #c45203 100%");
	});
	
	$(location+" .booka-btn").mouseout(function() {
		if($("#"+$(this).attr("id")+" .booka-btn-disabled").css("display") == "none")	$(this).css("background-image","");
	});

	$(location+" .booka-btn").mousedown(function() {
		
		if($("#"+$(this).attr("id")+" .booka-btn-disabled").css("display") == "none") {
			//$(this).css({"background":"-moz-linear-gradient(center top , #F3A350, #C45203)","border-color":"#78502c #B77942 #B77942 #78502c","padding":"6px 4px 4px 6px"});
			$(this).css({"border-color":"#78502c #B77942 #B77942 #78502c","padding":"6px 4px 4px 6px"});
			//$("#"+$(this).attr("id")+" .booka-btn-gloss").css("display","none");
		}
		
	});

	$(location+" .booka-btn").mouseup(function() {
		
		if($("#"+$(this).attr("id")+" .booka-btn-disabled").css("display") == "none") {
			//$(this).css({"background":"-moz-linear-gradient(center top , #C45203, #F3A350)","border-color":"#B77942 #78502c #78502c #B77942","padding":"4px 6px 6px 4px"});
			$(this).css({"border-color":"#B77942 #78502c #78502c #B77942","padding":"5px"});
			//$("#"+$(this).attr("id")+" .booka-btn-gloss").css("display","block");
		}
		
	});
		
	$.each($(location+" .booka-btn"),function() {
		if($(this).attr("disabled")) {
			$("#"+$(this).attr("id")).css({"cursor":"default"});
			$("#"+$(this).attr("id")+" .booka-btn-disabled").show();
			$("#"+$(this).attr("id")+" .booka-btn-gloss").hide();
		}
	});
	
}

/** **/

function updateLogin() {
	$.ajax({type:"GET",url:"system/inc/login/index.php",dataType:"html",success:function(data){top.$("#login").html(data)}}); 
}

function updateMenu() {
	$.ajax({type:"GET",url:"system/inc/menu/index.php",dataType:"html",success:function(data){top.$("#menu").html(data)}}); 
}


function iniGlobal() {
	createBookaButton();
}


function enable_finish() {					
						
	//var ready = !document.getElementById('btn_finish').disabled;
	var ready = true;
	
	//alert("finish: " + document.getElementById('btn_finish').disabled + " | ready: " + ready + " | client :" + document.getElementById('client_id').value + " | company: " + document.getElementById('company_id').value + " | start: " + document.getElementById('start_time').value);
	
	if(document.getElementById('client_id') != undefined) if(document.getElementById('client_id').value == "") ready = false;
	if(document.getElementById('company_id') != undefined) if(document.getElementById('company_id').value == "") ready = false;
	if(document.getElementById('start_time').value == "") ready = false;
	
	if(ready) {
		document.getElementById('btn_finish').disabled = false;
		document.getElementById('btn_finish').src="images/btn_finish.png";
		document.getElementById('btn_finish').style.cursor = 'pointer';
	}
	else {
		document.getElementById('btn_finish').disabled = true;
		document.getElementById('btn_finish').src="images/btn_cant_finish.png";							
		document.getElementById('btn_finish').style.cursor = 'default';
	}
	
}

function book() {
	params = "";
	params += "company_id="					+$("#company_id").val();
	params += "&appointment_id="		+$("#apppointment_id").val();	
	params += "&timestamp="					+$("#timestamp").val();
	params += "&employee_id="				+$("#employee_id").val();
	params += "&service_id="				+$("#service_id").val();
	params += "&cal_date="					+$("#date").val();
	params += "&start_time="				+$("#start_time").val();
	params += "&end_time="					+$("#end_time").val();
	params += "&message="						+$("#message").html().replace("%","``_25_``");
	params += "&groupon="						+$("#groupon").val();
	params += "&living_social="			+$("#living_social").val();
	params += "&send_notification="	+$("#send_notification").is(":checked") == true ? 1 : "";
	params += "&auto_confirm="			+$("#auto_confirm").is(":checked") == true ? 1 : "";
	params += "&cancellation_list="	+$("#cancellation_list").is(":checked") == true ? 1 : "";
	
	$.ajax({type:"POST",url:"ctrl/schedule/book/index.php",data:params,dataType:"json"}); 
}

function schedule(json) {
	
	params = "?";
	params += "company_id=" + json.company_id;
	params += "&tab=" + json.tab;
	params += "&page=" + json.page;
	params += "&timestamp=" + json.timestamp;
	params += "&employee_id=" + json.employee_id;
	params += "&service_id=" + json.service_id;
	
	doLightBox('Schedule Appointment','http://booka.me/update_content.php'+params,'718','340');
}


/** Lightbox functions **/
function openLightbox(m,w,h,c,s) {
	if(typeof(s) == "undefined") s = true;
	$("#lightbox-frame").css("width",w+"px").css("height",h+"px").css("left",((($(window).width()/2)-(w/2)))+"px").css("top",((($(window).height()/2)-(h/2)))+"px");		
	$("#lightbox-wrap").css("width",(w - 30)+"px").css("height",(h)+"px");	
	$("#lightbox-content").html((c ? "<a href=\"#\" onclick=\"closeLightbox();return false;\" id=\"lightbox-close\"></a>" : "")+m);
	$("#lightbox-content").css("max-height",(h - 40)+"px");
	$("#lightbox").show();
	//$('#lightbox-content').animate({width: 300, height: 300},"slow"); 
	
	if(s) createBookaButton("#lightbox");
};

function loadLightbox(w,h) {
	openLightbox("<img src='/images/loading.gif' style='margin:"+(h / 2 - 36)+"px 0 0 "+(w / 2 - 36)+"px'>",w,h,1);
}

function closeLightbox() {
	$("#lightbox").hide();
};

function lightboxPage(p,w,h,c) {
	if(typeof(w) == "undefined") w = 600;
	if(typeof(h) == "undefined") h = 480;
	if(typeof(c) == "undefined") c = true;
	$.ajax({type:"GET",url:"ctrl/lightbox/"+p+"/index.php",dataType:"html",success:function(data){openLightbox(data,w,h,c)}}); 
}

function changeCoupon(type) {
	$('#div-coupon-code').css('display',type == '' ? 'none' : 'inline'); 
}

function inviteBusiness() {
	$.ajax({type:"GET",url:"/invite_business.php",dataType:"html",success:function(data){openLightbox(data,500,400,1)}}); 
	loadLightbox(500,400);
}

function cantBookPopup(json) {
	var html = "<h1>"+json.company.name+"</h1><h2 style='color:#f00;'>"+json.employee.fname+" "+json.employee.lname+" does not have any "+json.type+" listed.</h2>";
	html += "<p>You will not be able to book an appointment with them until they complete the setup process.</p>";
	html += "<p>You can let "+json.employee.fname+" know they are still missing some information and you want to book an appointment with them.</p>";
	html += "<p style='float:left; margin-top:5px; width:180px;'>Name: <input style='width:125px;' type=text id='poker-name' value='"+json.user.name+"'></p>";
	html += "<div class='booka-btn' id='bb-poke' clicked=\"poke("+json.employee.id+",$('#poker-name').val())\">send</div>";
	
	return html;
}

function poke(eid, uname) {
	//console.log("sending to employee id "+eid+", from "+uname);
}
